file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
buildresult.rs | use ofborg::message::{Pr, Repo};
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum BuildStatus {
Skipped,
Success,
Failure,
TimedOut,
UnexpectedError { err: String },
}
pub struct LegacyBuildResult {
pub repo: Repo,
pub pr: Pr,
pub system: String,
pub output: Vec<String>,
pub attempt_id: String,
pub request_id: String,
pub status: BuildStatus,
pub skipped_attrs: Option<Vec<String>>,
pub attempted_attrs: Option<Vec<String>>,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum V1Tag {
V1,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum BuildResult {
V1 {
tag: V1Tag, // use serde once all enum variants have a tag
repo: Repo,
pr: Pr,
system: String,
output: Vec<String>,
attempt_id: String,
request_id: String,
// removed success
status: BuildStatus,
skipped_attrs: Option<Vec<String>>,
attempted_attrs: Option<Vec<String>>,
},
Legacy {
repo: Repo,
pr: Pr,
system: String,
output: Vec<String>,
attempt_id: String,
request_id: String,
success: Option<bool>, // replaced by status
status: Option<BuildStatus>,
skipped_attrs: Option<Vec<String>>,
attempted_attrs: Option<Vec<String>>,
},
}
impl BuildResult {
pub fn legacy(&self) -> LegacyBuildResult {
// TODO: replace this with simpler structs for specific usecases, since
// it's decouples the structs from serialization. These can be changed
// as long as we can translate all enum variants.
match *self {
BuildResult::Legacy {
ref repo,
ref pr,
ref system,
ref output,
ref attempt_id,
ref request_id,
ref attempted_attrs,
ref skipped_attrs,
..
} => LegacyBuildResult {
repo: repo.to_owned(),
pr: pr.to_owned(),
system: system.to_owned(),
output: output.to_owned(),
attempt_id: attempt_id.to_owned(),
request_id: request_id.to_owned(),
status: self.status(),
attempted_attrs: attempted_attrs.to_owned(),
skipped_attrs: skipped_attrs.to_owned(),
},
BuildResult::V1 {
ref repo,
ref pr,
ref system,
ref output,
ref attempt_id,
ref request_id,
ref attempted_attrs,
ref skipped_attrs,
..
} => LegacyBuildResult {
repo: repo.to_owned(),
pr: pr.to_owned(),
system: system.to_owned(),
output: output.to_owned(),
attempt_id: attempt_id.to_owned(),
request_id: request_id.to_owned(),
status: self.status(),
attempted_attrs: attempted_attrs.to_owned(),
skipped_attrs: skipped_attrs.to_owned(),
},
}
}
pub fn status(&self) -> BuildStatus {
match *self {
BuildResult::Legacy {
ref status,
ref success,
..
} => status.to_owned().unwrap_or_else(|| {
// Fallback for old format.
match *success {
None => BuildStatus::Skipped,
Some(true) => BuildStatus::Success,
Some(false) => BuildStatus::Failure,
} | BuildResult::V1 { ref status, .. } => status.to_owned(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
#[test]
fn v1_serialization() {
let input = r#"{"tag":"V1","repo":{"owner":"NixOS","name":"nixpkgs","full_name":"NixOS/nixpkgs","clone_url":"https://github.com/nixos/nixpkgs.git"},"pr":{"target_branch":"master","number":42,"head_sha":"0000000000000000000000000000000000000000"},"system":"x86_64-linux","output":["unpacking sources"],"attempt_id":"attempt-id-foo","request_id":"bogus-request-id","status":"Success","skipped_attrs":["AAAAAASomeThingsFailToEvaluate"],"attempted_attrs":["hello"]}"#;
let result: BuildResult = serde_json::from_str(input).expect("result required");
assert_eq!(result.status(), BuildStatus::Success);
let output = serde_json::to_string(&result).expect("json required");
assert_eq!(output, r#"{"tag":"V1","repo":{"owner":"NixOS","name":"nixpkgs","full_name":"NixOS/nixpkgs","clone_url":"https://github.com/nixos/nixpkgs.git"},"pr":{"target_branch":"master","number":42,"head_sha":"0000000000000000000000000000000000000000"},"system":"x86_64-linux","output":["unpacking sources"],"attempt_id":"attempt-id-foo","request_id":"bogus-request-id","status":"Success","skipped_attrs":["AAAAAASomeThingsFailToEvaluate"],"attempted_attrs":["hello"]}"#, "json of: {:?}", result);
}
#[test]
fn legacy_serialization() {
let input = r#"{"repo":{"owner":"NixOS","name":"nixpkgs","full_name":"NixOS/nixpkgs","clone_url":"https://github.com/nixos/nixpkgs.git"},"pr":{"target_branch":"master","number":42,"head_sha":"0000000000000000000000000000000000000000"},"system":"x86_64-linux","output":["unpacking sources"],"attempt_id":"attempt-id-foo","request_id":"bogus-request-id","success":true,"status":"Success","skipped_attrs":["AAAAAASomeThingsFailToEvaluate"],"attempted_attrs":["hello"]}"#;
let result: BuildResult = serde_json::from_str(input).expect("result required");
assert_eq!(result.status(), BuildStatus::Success);
let output = serde_json::to_string(&result).expect("json required");
assert_eq!(output, r#"{"repo":{"owner":"NixOS","name":"nixpkgs","full_name":"NixOS/nixpkgs","clone_url":"https://github.com/nixos/nixpkgs.git"},"pr":{"target_branch":"master","number":42,"head_sha":"0000000000000000000000000000000000000000"},"system":"x86_64-linux","output":["unpacking sources"],"attempt_id":"attempt-id-foo","request_id":"bogus-request-id","success":true,"status":"Success","skipped_attrs":["AAAAAASomeThingsFailToEvaluate"],"attempted_attrs":["hello"]}"#, "json of: {:?}", result);
}
#[test]
fn legacy_none_serialization() {
let input = r#"{"repo":{"owner":"NixOS","name":"nixpkgs","full_name":"NixOS/nixpkgs","clone_url":"https://github.com/nixos/nixpkgs.git"},"pr":{"target_branch":"master","number":42,"head_sha":"0000000000000000000000000000000000000000"},"system":"x86_64-linux","output":[],"attempt_id":"attempt-id-foo","request_id":"bogus-request-id"}"#;
let result: BuildResult = serde_json::from_str(input).expect("result required");
assert_eq!(result.status(), BuildStatus::Skipped);
let output = serde_json::to_string(&result).expect("json required");
assert_eq!(output, r#"{"repo":{"owner":"NixOS","name":"nixpkgs","full_name":"NixOS/nixpkgs","clone_url":"https://github.com/nixos/nixpkgs.git"},"pr":{"target_branch":"master","number":42,"head_sha":"0000000000000000000000000000000000000000"},"system":"x86_64-linux","output":[],"attempt_id":"attempt-id-foo","request_id":"bogus-request-id","success":null,"status":null,"skipped_attrs":null,"attempted_attrs":null}"#, "json of: {:?}", result);
}
#[test]
fn legacy_no_status_serialization() {
let input = r#"{"repo":{"owner":"NixOS","name":"nixpkgs","full_name":"NixOS/nixpkgs","clone_url":"https://github.com/nixos/nixpkgs.git"},"pr":{"target_branch":"master","number":42,"head_sha":"0000000000000000000000000000000000000000"},"system":"x86_64-linux","output":["unpacking sources"],"attempt_id":"attempt-id-foo","request_id":"bogus-request-id","success":true,"status":null,"skipped_attrs":["AAAAAASomeThingsFailToEvaluate"],"attempted_attrs":["hello"]}"#;
let result: BuildResult = serde_json::from_str(input).expect("result required");
assert_eq!(result.status(), BuildStatus::Success);
let output = serde_json::to_string(&result).expect("json required");
assert_eq!(output, r#"{"repo":{"owner":"NixOS","name":"nixpkgs","full_name":"NixOS/nixpkgs","clone_url":"https://github.com/nixos/nixpkgs.git"},"pr":{"target_branch":"master","number":42,"head_sha":"0000000000000000000000000000000000000000"},"system":"x86_64-linux","output":["unpacking sources"],"attempt_id":"attempt-id-foo","request_id":"bogus-request-id","success":true,"status":null,"skipped_attrs":["AAAAAASomeThingsFailToEvaluate"],"attempted_attrs":["hello"]}"#, "json of: {:?}", result);
}
} | }), |
index.js | import database from '../../database/database';
import Endpoint from '../endpoint';
/**
* api list_address
*/
class | extends Endpoint {
constructor() {
super('72dlrjquBORj0rhx');
}
/**
* returns records from table address. it returns the newest records by
* default
* @param app
* @param req (p0: address_base, p1: address_version, p2:
* address_key_identifier, p3: address, p4: status, p5:
* order_by="create_date desc", p6: record_limit: 1000)
* @param res
*/
handler(app, req, res) {
const orderBy = req.query.p5 || 'create_date desc';
const limit = parseInt(req.query.p6) || 1000;
const addressRepository = database.getRepository('address');
addressRepository.listAddress({
'address.address_base': req.query.p0,
address_version : req.query.p1,
address_key_identifier: req.query.p2,
address : req.query.p3,
'address.status' : req.query.p4
}, orderBy, limit)
.then(addresses => res.send(addresses))
.catch(e => res.send({
api_status : 'fail',
api_message: `unexpected generic api error: (${e})`
}));
}
}
export default new _72dlrjquBORj0rhx();
| _72dlrjquBORj0rhx |
main.go | // seed = {{ index . "_config "seed" }}
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"reflect"
"regexp"
"strings"
"text/template"
"github.com/flaviostutz/ruller"
"github.com/sirupsen/logrus"
)
var (
mapidc = 0
conditionDebug = false
)
func main() |
func executeTemplate(dir string, templ string, input map[string]interface{}) (string, error) {
tmpl := template.New("root").Funcs(template.FuncMap{
"hasPrefix": func(str string, prefix string) bool {
return strings.HasPrefix(str, prefix)
},
"attributeCode": staticAttributeCode,
})
tmpl1, err := tmpl.ParseGlob(dir + "/*.tmpl")
buf := new(bytes.Buffer)
err = tmpl1.ExecuteTemplate(buf, templ, input)
if err != nil {
return "", err
}
return buf.String(), nil
}
func staticAttributeCode(attributeName string, attributeValue interface{}, depth int) string {
result := ""
mapvar := "output"
if depth > 0 {
mapvar = fmt.Sprintf("output%d", depth)
}
if reflect.ValueOf(attributeValue).Kind() == reflect.Map {
if attributeName == "_items" || !strings.HasPrefix(attributeName, "_") {
map1 := attributeValue.(map[string]interface{})
nextmapvar := fmt.Sprintf("output%d", depth+1)
result = result + fmt.Sprintf("%s := make(map[string]interface{})\n ", nextmapvar)
result = result + fmt.Sprintf("%s[\"%s\"] = %s\n ", mapvar, attributeName, nextmapvar)
for k, v := range map1 {
s := staticAttributeCode(k, v, depth+1)
result = result + s
}
}
} else {
if !strings.HasPrefix(attributeName, "_") {
if reflect.ValueOf(attributeValue).Kind() == reflect.Bool {
result = fmt.Sprintf("%s[\"%s\"] = %t\n ", mapvar, attributeName, attributeValue)
} else if reflect.ValueOf(attributeValue).Kind() == reflect.Float64 {
result = fmt.Sprintf("%s[\"%s\"] = %f\n ", mapvar, attributeName, attributeValue)
} else {
result = fmt.Sprintf("%s[\"%s\"] = \"%s\"\n ", mapvar, attributeName, attributeValue)
}
} else if attributeName == "_condition" && conditionDebug {
result = fmt.Sprintf("%s[\"%s_debug\"] = \"%s\"\n ", mapvar, attributeName, attributeValue)
}
}
return result
}
func traverseConditionCode(map1 map[string]interface{}, defaultConditionStr string, inputTypes map[string]ruller.InputType, ruleGroupName string, seed string) error {
createDefaultCondition := true
for k, v := range map1 {
// logrus.Debugf("KKKKKK %s %s", k, v)
if reflect.ValueOf(v).Kind() == reflect.Slice {
items := v.([]interface{})
for _, i := range items {
if reflect.ValueOf(i).Kind() == reflect.Map {
rm := i.(map[string]interface{})
traverseConditionCode(rm, defaultConditionStr, inputTypes, ruleGroupName, seed)
}
}
} else if reflect.ValueOf(v).Kind() == reflect.Map {
if k == "_items" {
logrus.Debugf("Traversing condition for %s with child items", k)
traverseConditionCode(v.(map[string]interface{}), defaultConditionStr, inputTypes, ruleGroupName, seed)
}
} else {
if k == "_condition" {
createDefaultCondition = false
conditionStr := map1[k]
map1["_conditionCode"] = conditionCode(conditionStr, inputTypes, ruleGroupName, seed)
}
}
}
if createDefaultCondition {
map1["_conditionCode"] = conditionCode(defaultConditionStr, inputTypes, ruleGroupName, seed)
}
return nil
}
func orderedRules(map1 map[string]interface{}, parentid int, ruleGroupName string, rules *[]map[string]interface{}) error {
logrus.Debugf("orderedRules parentid=%d", parentid)
mapidc = mapidc + 1
mapid := mapidc
map1["_id"] = mapid
map1["_parentid"] = fmt.Sprintf("%d", parentid)
map1["_ruleGroupName"] = ruleGroupName
*rules = append(*rules, map1)
logrus.Debugf("Adding rule %s", map1)
for k, v := range map1 {
if k == "_items" {
logrus.Debugf("attribute %s has children rules", k)
if reflect.ValueOf(v).Kind() == reflect.Slice {
logrus.Debugf("attribute %s is an array", k)
items := v.([]interface{})
for _, i := range items {
if reflect.ValueOf(i).Kind() == reflect.Map {
rm := i.(map[string]interface{})
logrus.Debugf("attribute %s is an array of maps. calling recursive for item %s", k, i)
orderedRules(rm, mapid, ruleGroupName, rules)
}
}
} else if reflect.ValueOf(v).Kind() == reflect.Map {
logrus.Debugf("attribute %s is map. calling recursive", k)
orderedRules(v.(map[string]interface{}), mapid, ruleGroupName, rules)
}
// } else if !strings.HasPrefix(k, "_") {
// logrus.Debugf("attribute %s is a static rule member", k)
}
}
return nil
}
func typeName(inputType ruller.InputType) string {
if inputType == ruller.String {
return "String"
} else if inputType == ruller.Float64 {
return "Float64"
} else if inputType == ruller.Bool {
return "Bool"
} else {
return "-"
}
}
func conditionCode(value interface{}, inputTypes map[string]ruller.InputType, ruleGroupName string, seed string) string {
if reflect.ValueOf(value).Kind() == reflect.String {
condition := value.(string)
// logrus.Debugf("CONDITION %s", condition)
//REGEX FUNC
regexExpreRegex := regexp.MustCompile("(input:[a-z0-9-_]+)\\s*~=\\s*'(.+)'")
condition = regexExpreRegex.ReplaceAllString(condition, "match($1,\"$2\")")
concatRegex := regexp.MustCompile("concat\\(\\s*([a-z0-9_:()',]+)\\s*\\)")
condition = concatRegex.ReplaceAllString(condition, "concatString($1)")
//GROUP REFERENCES TO STRING
//_condition="group:members" ---> ""members""
groupRegex := regexp.MustCompile("contains\\(\\s*group:([a-z0-9_-]+)\\s*,\\s*([0-9a-zA-Z:_,()'.\\\"\\[\\]]+)\\s*\\)")
condition = groupRegex.ReplaceAllString(condition, "groupContains(\""+ruleGroupName+"\",\"$1\",$2)")
//RANDOM PERC REFERENCES
percRegex := regexp.MustCompile("randomPerc\\(\\s*([0-9]+)\\s*,\\s*([0-9a-z:]+)\\s*\\)")
condition = percRegex.ReplaceAllString(condition, "randomPerc($1,$2,"+seed+")")
perc2Regex := regexp.MustCompile("randomPercRange\\(\\s*([0-9]+),\\s*([0-9]+)\\s*,\\s*([0-9a-z:]+)\\s*\\)")
condition = perc2Regex.ReplaceAllString(condition, "randomPercRange($1,$2,$3,"+seed+")")
//ADD CASTS
//_condition="input:age > 30 and input:name='stutz'" ---> "input:age.(float64) > 30 and input:name.(string)=='stutz'"
//find all numeric comparisons
numberInputRegex := regexp.MustCompile("input:([a-z0-9-_]+)\\s*([><]|==|!=)\\s*[0-9]+")
numberMatches := numberInputRegex.FindAllStringSubmatch(condition, -1)
for _, numberMatch := range numberMatches {
logrus.Debugf("Condition number match %s - %s", numberMatch[0], numberMatch[1])
//fields uses comparison, so it needs to be float64
attributeName := numberMatch[1]
logrus.Debugf("Updating attribute '%s' to '%s'", attributeName, fmt.Sprintf("%s.(float64)", attributeName))
condition = strings.Replace(condition, attributeName, fmt.Sprintf("%s.(float64)", attributeName), -1)
//check and collect input types
it, exists := inputTypes[attributeName]
if exists {
if it != ruller.Float64 {
panic(fmt.Errorf("Attribute '%s' was defined as '%v' and now is being redefined as 'Float64'. Aborting", attributeName, typeName(it)))
}
} else {
inputTypes[attributeName] = ruller.Float64
logrus.Debugf("Input %s is Float64", attributeName)
}
}
//cast all other attributes to string
inputNameRegex2 := regexp.MustCompile("input:([a-z0-9-_\\.]+)")
matches := inputNameRegex2.FindAllStringSubmatch(condition, -1)
for _, match := range matches {
if len(match) > 1 {
sm := match[1]
//update all matches that hasn't been changed on previous step
if !strings.Contains(sm, ".") {
logrus.Debugf("Updating attribute '%s' to '%s'", sm, fmt.Sprintf("%s.(string)", sm))
condition = strings.Replace(condition, "input:"+sm, fmt.Sprintf("input:%s.(string)", sm), -1)
condition = strings.Replace(condition, ".(string).(string)", ".(string)", -1)
//check and collect input types
it, exists := inputTypes[sm]
if exists {
if it != ruller.String {
panic(fmt.Errorf("Attribute '%s' was defined as '%v' and now is being redefined as 'String'. Aborting", sm, typeName(it)))
}
} else {
inputTypes[sm] = ruller.String
logrus.Debugf("Input %s is String", sm)
}
} else {
logrus.Debugf("Ignoring already casted attribute %s", sm)
}
}
}
//GET INPUT FROM CONTEXT
//_condition="input:age > 30 and input:name='stutz'" ---> "ctx.Input["age"].(float64) > 30 and ctx.Input["name"].(string)=="stutz""
inputNameRegex := regexp.MustCompile("input:([a-z0-9-_]+)")
logrus.Debugf("CONDITION %s", condition)
condition = inputNameRegex.ReplaceAllString(condition, "ctx.Input[\"$1\"]")
//REPLACE OTHER CHARS
delimRegex := regexp.MustCompile("'([^']*)'")
condition = delimRegex.ReplaceAllString(condition, "\"$1\"")
condition = strings.Replace(condition, " and ", " && ", -1)
condition = strings.Replace(condition, " or ", " || ", -1)
logrus.Debugf("CONDITION CODE = %s", condition)
return condition
} else {
panic(fmt.Errorf("Invalid non string '_condition' field. '%v'", value))
}
}
| {
logrus.Infof("Starting Ruller DSL Feature Flag code generator")
logLevel := flag.String("log-level", "info", "debug, info, warning or error")
source := flag.String("source", "/opt/rules.json", "Comma separated list of files to be used as input json")
target := flag.String("target", "/opt/rules.go", "Output file name that will be created with the generated Go code")
templDir := flag.String("templdir", "/app/templates", "Directory where the templates can be found")
condDebug := flag.Bool("condition-debug", false, "Whetever show output nodes with condition info for debugging")
flag.Parse()
switch *logLevel {
case "debug":
logrus.SetLevel(logrus.DebugLevel)
break
case "warning":
logrus.SetLevel(logrus.WarnLevel)
break
case "error":
logrus.SetLevel(logrus.ErrorLevel)
break
default:
logrus.SetLevel(logrus.InfoLevel)
}
conditionDebug = *condDebug
sf := strings.Split(*source, ",")
jsonRulesMap := make(map[string]interface{})
for _, sourceFile := range sf {
logrus.Infof("Loading json rules %s", sourceFile)
jsonFile, err := os.Open(sourceFile)
if err != nil {
logrus.Errorf("Error loading json file. err=%s", err)
os.Exit(1)
}
defer jsonFile.Close()
byteValue, _ := ioutil.ReadAll(jsonFile)
var jsonRules map[string]interface{}
json.Unmarshal([]byte(byteValue), &jsonRules)
nameregex := regexp.MustCompile("\\/([a-z0-9_-]*)\\..*")
namer := nameregex.FindStringSubmatch(sourceFile)
if len(namer) > 1 {
name := namer[1]
jsonRulesMap[name] = jsonRules
} else {
logrus.Warnf("Couldn't find a valid group rule name in file name. filename=%s", sourceFile)
}
}
logrus.Debugf("json rules menu %s", jsonRulesMap["menu"])
logrus.Debugf("json rules domains %s", jsonRulesMap["domains"])
//PREPARE MAP FOR EACH DSL
templateRulesMap := make(map[string]interface{})
for ruleGroupName, v := range jsonRulesMap {
logrus.Debugf("PROCESSING RULE GROUP %s", ruleGroupName)
jsonRules := v.(map[string]interface{})
templateRule := make(map[string]interface{})
templateRulesMap[ruleGroupName] = templateRule
//PREPARE CONFIGURATIONS
logrus.Debugf("CONFIGURATIONS")
hashSeed := 1234
flatten := false
keepFirst := true
inputTypes := make(map[string]ruller.InputType)
defaultConditionStr := "true"
config, exists := jsonRules["_config"].(map[string]interface{})
if exists {
dc, exists := config["default_condition"]
if exists {
if reflect.ValueOf(dc).Kind() == reflect.String {
defaultConditionStr = dc.(string)
} else if reflect.ValueOf(dc).Kind() == reflect.Bool {
defaultConditionStr = fmt.Sprintf("%t", dc.(bool))
} else {
panic(fmt.Errorf("_config default_condition exists but is neither Bool or String type"))
}
}
hs, exists := config["seed"]
if exists {
if reflect.ValueOf(hs).Kind() == reflect.Float64 {
hashSeed = int(hs.(float64))
} else {
panic(fmt.Errorf("_config seed exists but is not Float64"))
}
}
ft, exists := config["flatten"]
if exists {
if reflect.ValueOf(ft).Kind() == reflect.Bool {
flatten = ft.(bool)
} else {
panic(fmt.Errorf("flatten exists but is not boolean"))
}
}
kf, exists := config["keep_first"]
if exists {
if reflect.ValueOf(kf).Kind() == reflect.Bool {
keepFirst = kf.(bool)
} else {
panic(fmt.Errorf("keep_first exists but is not boolean"))
}
}
} else {
config = make(map[string]interface{})
}
config["flatten"] = flatten
config["keep_first"] = keepFirst
templateRule["_config"] = config
//PREPARE "_condition" ATTRIBUTES (generate Go code)
logrus.Debugf("_CONDITION ATTRIBUTES")
err := traverseConditionCode(jsonRules, defaultConditionStr, inputTypes, ruleGroupName, fmt.Sprintf("%d", hashSeed))
if err != nil {
panic(err)
}
// jsonRules["_inputTypes"] = inputTypes
templateRule["_ruleGroupName"] = ruleGroupName
//PREPARE GROUP DEFINITIONS
logrus.Debugf("GROUPS")
groupCodes := make(map[string]string)
groups, exists := jsonRules["_groups"].(map[string]interface{})
if exists {
//FIXME NEEDED?
// delete(groups, "_condition")
for gn, gv := range groups {
if strings.HasPrefix(gn, "_") {
continue
}
logrus.Debugf(">>>>GROUP %s %s", gn, gv)
t := reflect.TypeOf(gv)
if t.Kind() == reflect.Slice {
garray := ""
for _, v := range gv.([]interface{}) {
garray = garray + fmt.Sprintf("\"%s\",", v)
}
garray = strings.Trim(garray, ",")
groupCodes[gn] = fmt.Sprintf("loadGroupArray(groups, \"%s\", \"%s\", []string{%s})", ruleGroupName, gn, garray)
} else if reflect.ValueOf(gv).Kind() == reflect.String {
// loadGroupFromFile(groups, "hugeids", "/opt/group1.txt")
groupCodes[gn] = fmt.Sprintf("loadGroupFromFile(groups, \"%s\", \"%s\", \"%s\")", ruleGroupName, gn, gv.(string))
} else {
panic(fmt.Errorf("_groups %s exists but is neither an array of strings nor a string with a file path. rule group %s", gn, ruleGroupName))
}
}
} else {
logrus.Debugf("No groups found")
}
templateRule["_groupCodes"] = groupCodes
logrus.Debugf("REQUIRED INPUTS")
requiredInputCodes := make(map[string]string)
for in, it := range inputTypes {
icode := fmt.Sprintf("ruller.AddRequiredInput(\"%s\", \"%s\", ruller.%s)", ruleGroupName, in, typeName(it))
requiredInputCodes[in] = icode
}
templateRule["_requiredInputCodes"] = requiredInputCodes
//ORDERED RULES
logrus.Debugf("ORDERED RULES")
rules := make([]map[string]interface{}, 0)
orderedRules(jsonRules, -1, ruleGroupName, &rules)
templateRule["_orderedRules"] = rules
logrus.Debugf("templateRule %s", templateRule)
}
logrus.Debugf("Generating Go code")
sourceCode, err := executeTemplate(*templDir, "main.tmpl", templateRulesMap)
if err != nil {
panic(err)
}
logrus.Debugf("Write Go code to disk")
err = ioutil.WriteFile(*target, []byte(sourceCode), 0644)
if err != nil {
panic(err)
}
logrus.Debugf("Code generation finished")
} |
test_hs2.py | #!/usr/bin/env python
# Copyright (c) 2012 Cloudera, Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Client tests for Impala's HiveServer2 interface
import pytest
from tests.hs2.hs2_test_suite import HS2TestSuite, needs_session, operation_id_to_query_id
from TCLIService import TCLIService
from ImpalaService import ImpalaHiveServer2Service
from ExecStats.ttypes import TExecState
class TestHS2(HS2TestSuite):
def test_open_session(self):
"""Check that a session can be opened"""
open_session_req = TCLIService.TOpenSessionReq()
TestHS2.check_response(self.hs2_client.OpenSession(open_session_req))
def test_open_session_unsupported_protocol(self):
"""Test that we get the right protocol version back if we ask for one larger than the
server supports. This test will fail as we support newer version of HS2, and should be
updated."""
open_session_req = TCLIService.TOpenSessionReq()
open_session_req.protocol_version = \
TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V7
open_session_resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(open_session_resp)
assert open_session_resp.serverProtocolVersion == \
TCLIService.TProtocolVersion.HIVE_CLI_SERVICE_PROTOCOL_V6
def test_close_session(self):
"""Test that an open session can be closed"""
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
close_session_req = TCLIService.TCloseSessionReq()
close_session_req.sessionHandle = resp.sessionHandle
TestHS2.check_response(self.hs2_client.CloseSession(close_session_req))
def test_double_close_session(self):
"""Test that an already closed session cannot be closed a second time"""
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
close_session_req = TCLIService.TCloseSessionReq()
close_session_req.sessionHandle = resp.sessionHandle
TestHS2.check_response(self.hs2_client.CloseSession(close_session_req))
# Double close should be an error
TestHS2.check_response(self.hs2_client.CloseSession(close_session_req),
TCLIService.TStatusCode.ERROR_STATUS)
@needs_session()
def | (self):
"""Tests that GetOperationStatus returns a valid result for a running query"""
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = "SELECT COUNT(*) FROM functional.alltypes"
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
get_operation_status_req = TCLIService.TGetOperationStatusReq()
get_operation_status_req.operationHandle = execute_statement_resp.operationHandle
get_operation_status_resp = \
self.hs2_client.GetOperationStatus(get_operation_status_req)
TestHS2.check_response(get_operation_status_resp)
assert get_operation_status_resp.operationState in \
[TCLIService.TOperationState.INITIALIZED_STATE,
TCLIService.TOperationState.RUNNING_STATE,
TCLIService.TOperationState.FINISHED_STATE]
@needs_session()
def test_malformed_get_operation_status(self):
"""Tests that a short guid / secret returns an error (regression would be to crash
impalad)"""
operation_handle = TCLIService.TOperationHandle()
operation_handle.operationId = TCLIService.THandleIdentifier()
operation_handle.operationId.guid = "short"
operation_handle.operationId.secret = "short_secret"
assert len(operation_handle.operationId.guid) != 16
assert len(operation_handle.operationId.secret) != 16
operation_handle.operationType = TCLIService.TOperationType.EXECUTE_STATEMENT
operation_handle.hasResultSet = False
get_operation_status_req = TCLIService.TGetOperationStatusReq()
get_operation_status_req.operationHandle = operation_handle
get_operation_status_resp = \
self.hs2_client.GetOperationStatus(get_operation_status_req)
TestHS2.check_response(get_operation_status_resp,
TCLIService.TStatusCode.ERROR_STATUS)
err_msg = "(guid size: %d, expected 16, secret size: %d, expected 16)" \
% (len(operation_handle.operationId.guid),
len(operation_handle.operationId.secret))
assert err_msg in get_operation_status_resp.status.errorMessage
@pytest.mark.execute_serially
def test_socket_close_forces_session_close(self):
"""Test that closing the underlying socket forces the associated session to close.
See IMPALA-564"""
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
num_sessions = self.impalad_test_service.get_metric_value(
"impala-server.num-open-hiveserver2-sessions")
assert num_sessions > 0
self.socket.close()
self.socket = None
self.impalad_test_service.wait_for_metric_value(
"impala-server.num-open-hiveserver2-sessions", num_sessions - 1)
@pytest.mark.execute_serially
def test_multiple_sessions(self):
"""Test that multiple sessions on the same socket connection are allowed"""
num_sessions = self.impalad_test_service.get_metric_value(
"impala-server.num-open-hiveserver2-sessions")
session_ids = []
for _ in xrange(5):
open_session_req = TCLIService.TOpenSessionReq()
resp = self.hs2_client.OpenSession(open_session_req)
TestHS2.check_response(resp)
# Check that all sessions get different IDs
assert resp.sessionHandle not in session_ids
session_ids.append(resp.sessionHandle)
self.impalad_test_service.wait_for_metric_value(
"impala-server.num-open-hiveserver2-sessions", num_sessions + 5)
self.socket.close()
self.socket = None
self.impalad_test_service.wait_for_metric_value(
"impala-server.num-open-hiveserver2-sessions", num_sessions)
@needs_session()
def test_get_schemas(self):
get_schemas_req = TCLIService.TGetSchemasReq()
get_schemas_req.sessionHandle = self.session_handle
get_schemas_resp = self.hs2_client.GetSchemas(get_schemas_req)
TestHS2.check_response(get_schemas_resp)
fetch_results_req = TCLIService.TFetchResultsReq()
fetch_results_req.operationHandle = get_schemas_resp.operationHandle
fetch_results_req.maxRows = 100
fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
TestHS2.check_response(fetch_results_resp)
query_id = operation_id_to_query_id(get_schemas_resp.operationHandle.operationId)
profile_page = self.impalad_test_service.read_query_profile_page(query_id)
# Test fix for IMPALA-619
assert "Sql Statement: GET_SCHEMAS" in profile_page
assert "Query Type: DDL" in profile_page
def get_log(self, query_stmt):
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = query_stmt
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
# Fetch results to make sure errors are generated
fetch_results_req = TCLIService.TFetchResultsReq()
fetch_results_req.operationHandle = execute_statement_resp.operationHandle
fetch_results_req.maxRows = 100
fetch_results_resp = self.hs2_client.FetchResults(fetch_results_req)
TestHS2.check_response(fetch_results_resp)
get_log_req = TCLIService.TGetLogReq()
get_log_req.operationHandle = execute_statement_resp.operationHandle
get_log_resp = self.hs2_client.GetLog(get_log_req)
TestHS2.check_response(get_log_resp)
return get_log_resp.log
@needs_session()
def test_get_log(self):
# Test query that generates BE warnings
log = self.get_log("select * from functional.alltypeserror")
assert "Error converting column" in log
# Test overflow warning
log = self.get_log("select cast(1000 as decimal(2, 1))")
assert "Expression overflowed, returning NULL" in log
@needs_session()
def test_get_exec_summary(self):
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = "SELECT COUNT(1) FROM functional.alltypes"
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
exec_summary_req = ImpalaHiveServer2Service.TGetExecSummaryReq()
exec_summary_req.operationHandle = execute_statement_resp.operationHandle
exec_summary_req.sessionHandle = self.session_handle
exec_summary_resp = self.hs2_client.GetExecSummary(exec_summary_req)
# Test getting the summary while query is running. We can't verify anything
# about the summary (depends how much progress query has made) but the call
# should work.
TestHS2.check_response(exec_summary_resp)
close_operation_req = TCLIService.TCloseOperationReq()
close_operation_req.operationHandle = execute_statement_resp.operationHandle
TestHS2.check_response(self.hs2_client.CloseOperation(close_operation_req))
exec_summary_resp = self.hs2_client.GetExecSummary(exec_summary_req)
TestHS2.check_response(exec_summary_resp)
assert len(exec_summary_resp.summary.nodes) > 0
@needs_session()
def test_get_profile(self):
execute_statement_req = TCLIService.TExecuteStatementReq()
execute_statement_req.sessionHandle = self.session_handle
execute_statement_req.statement = "SELECT COUNT(2) FROM functional.alltypes"
execute_statement_resp = self.hs2_client.ExecuteStatement(execute_statement_req)
TestHS2.check_response(execute_statement_resp)
get_profile_req = ImpalaHiveServer2Service.TGetRuntimeProfileReq()
get_profile_req.operationHandle = execute_statement_resp.operationHandle
get_profile_req.sessionHandle = self.session_handle
get_profile_resp = self.hs2_client.GetRuntimeProfile(get_profile_req)
TestHS2.check_response(get_profile_resp)
assert execute_statement_req.statement in get_profile_resp.profile
close_operation_req = TCLIService.TCloseOperationReq()
close_operation_req.operationHandle = execute_statement_resp.operationHandle
TestHS2.check_response(self.hs2_client.CloseOperation(close_operation_req))
get_profile_resp = self.hs2_client.GetRuntimeProfile(get_profile_req)
TestHS2.check_response(get_profile_resp)
assert execute_statement_req.statement in get_profile_resp.profile
| test_get_operation_status |
role.go | // *** WARNING: this file was generated by pulumigen. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package v1
import (
"context"
"reflect"
metav1 "github.com/pulumi/pulumi-kubernetes/sdk/v3/go/kubernetes/meta/v1"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
// Role is a namespaced, logical grouping of PolicyRules that can be referenced as a unit by a RoleBinding.
type Role struct {
pulumi.CustomResourceState
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
ApiVersion pulumi.StringPtrOutput `pulumi:"apiVersion"`
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
Kind pulumi.StringPtrOutput `pulumi:"kind"`
// Standard object's metadata.
Metadata metav1.ObjectMetaPtrOutput `pulumi:"metadata"`
// Rules holds all the PolicyRules for this Role
Rules PolicyRuleArrayOutput `pulumi:"rules"`
}
// NewRole registers a new resource with the given unique name, arguments, and options.
func NewRole(ctx *pulumi.Context,
name string, args *RoleArgs, opts ...pulumi.ResourceOption) (*Role, error) {
if args == nil {
args = &RoleArgs{}
}
args.ApiVersion = pulumi.StringPtr("rbac.authorization.k8s.io/v1")
args.Kind = pulumi.StringPtr("Role")
aliases := pulumi.Aliases([]pulumi.Alias{
{
Type: pulumi.String("kubernetes:rbac.authorization.k8s.io/v1alpha1:Role"),
},
{
Type: pulumi.String("kubernetes:rbac.authorization.k8s.io/v1beta1:Role"),
},
})
opts = append(opts, aliases)
var resource Role
err := ctx.RegisterResource("kubernetes:rbac.authorization.k8s.io/v1:Role", name, args, &resource, opts...)
if err != nil {
return nil, err
}
return &resource, nil
}
// GetRole gets an existing Role resource's state with the given name, ID, and optional
// state properties that are used to uniquely qualify the lookup (nil if not required).
func | (ctx *pulumi.Context,
name string, id pulumi.IDInput, state *RoleState, opts ...pulumi.ResourceOption) (*Role, error) {
var resource Role
err := ctx.ReadResource("kubernetes:rbac.authorization.k8s.io/v1:Role", name, id, state, &resource, opts...)
if err != nil {
return nil, err
}
return &resource, nil
}
// Input properties used for looking up and filtering Role resources.
type roleState struct {
}
type RoleState struct {
}
func (RoleState) ElementType() reflect.Type {
return reflect.TypeOf((*roleState)(nil)).Elem()
}
type roleArgs struct {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
ApiVersion *string `pulumi:"apiVersion"`
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
Kind *string `pulumi:"kind"`
// Standard object's metadata.
Metadata *metav1.ObjectMeta `pulumi:"metadata"`
// Rules holds all the PolicyRules for this Role
Rules []PolicyRule `pulumi:"rules"`
}
// The set of arguments for constructing a Role resource.
type RoleArgs struct {
// APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas to the latest internal value, and may reject unrecognized values. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources
ApiVersion pulumi.StringPtrInput
// Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint the client submits requests to. Cannot be updated. In CamelCase. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
Kind pulumi.StringPtrInput
// Standard object's metadata.
Metadata metav1.ObjectMetaPtrInput
// Rules holds all the PolicyRules for this Role
Rules PolicyRuleArrayInput
}
func (RoleArgs) ElementType() reflect.Type {
return reflect.TypeOf((*roleArgs)(nil)).Elem()
}
type RoleInput interface {
pulumi.Input
ToRoleOutput() RoleOutput
ToRoleOutputWithContext(ctx context.Context) RoleOutput
}
func (*Role) ElementType() reflect.Type {
return reflect.TypeOf((*Role)(nil))
}
func (i *Role) ToRoleOutput() RoleOutput {
return i.ToRoleOutputWithContext(context.Background())
}
func (i *Role) ToRoleOutputWithContext(ctx context.Context) RoleOutput {
return pulumi.ToOutputWithContext(ctx, i).(RoleOutput)
}
func (i *Role) ToRolePtrOutput() RolePtrOutput {
return i.ToRolePtrOutputWithContext(context.Background())
}
func (i *Role) ToRolePtrOutputWithContext(ctx context.Context) RolePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(RolePtrOutput)
}
type RolePtrInput interface {
pulumi.Input
ToRolePtrOutput() RolePtrOutput
ToRolePtrOutputWithContext(ctx context.Context) RolePtrOutput
}
type rolePtrType RoleArgs
func (*rolePtrType) ElementType() reflect.Type {
return reflect.TypeOf((**Role)(nil))
}
func (i *rolePtrType) ToRolePtrOutput() RolePtrOutput {
return i.ToRolePtrOutputWithContext(context.Background())
}
func (i *rolePtrType) ToRolePtrOutputWithContext(ctx context.Context) RolePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(RolePtrOutput)
}
// RoleArrayInput is an input type that accepts RoleArray and RoleArrayOutput values.
// You can construct a concrete instance of `RoleArrayInput` via:
//
// RoleArray{ RoleArgs{...} }
type RoleArrayInput interface {
pulumi.Input
ToRoleArrayOutput() RoleArrayOutput
ToRoleArrayOutputWithContext(context.Context) RoleArrayOutput
}
type RoleArray []RoleInput
func (RoleArray) ElementType() reflect.Type {
return reflect.TypeOf((*[]*Role)(nil)).Elem()
}
func (i RoleArray) ToRoleArrayOutput() RoleArrayOutput {
return i.ToRoleArrayOutputWithContext(context.Background())
}
func (i RoleArray) ToRoleArrayOutputWithContext(ctx context.Context) RoleArrayOutput {
return pulumi.ToOutputWithContext(ctx, i).(RoleArrayOutput)
}
// RoleMapInput is an input type that accepts RoleMap and RoleMapOutput values.
// You can construct a concrete instance of `RoleMapInput` via:
//
// RoleMap{ "key": RoleArgs{...} }
type RoleMapInput interface {
pulumi.Input
ToRoleMapOutput() RoleMapOutput
ToRoleMapOutputWithContext(context.Context) RoleMapOutput
}
type RoleMap map[string]RoleInput
func (RoleMap) ElementType() reflect.Type {
return reflect.TypeOf((*map[string]*Role)(nil)).Elem()
}
func (i RoleMap) ToRoleMapOutput() RoleMapOutput {
return i.ToRoleMapOutputWithContext(context.Background())
}
func (i RoleMap) ToRoleMapOutputWithContext(ctx context.Context) RoleMapOutput {
return pulumi.ToOutputWithContext(ctx, i).(RoleMapOutput)
}
type RoleOutput struct{ *pulumi.OutputState }
func (RoleOutput) ElementType() reflect.Type {
return reflect.TypeOf((*Role)(nil))
}
func (o RoleOutput) ToRoleOutput() RoleOutput {
return o
}
func (o RoleOutput) ToRoleOutputWithContext(ctx context.Context) RoleOutput {
return o
}
func (o RoleOutput) ToRolePtrOutput() RolePtrOutput {
return o.ToRolePtrOutputWithContext(context.Background())
}
func (o RoleOutput) ToRolePtrOutputWithContext(ctx context.Context) RolePtrOutput {
return o.ApplyTWithContext(ctx, func(_ context.Context, v Role) *Role {
return &v
}).(RolePtrOutput)
}
type RolePtrOutput struct{ *pulumi.OutputState }
func (RolePtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**Role)(nil))
}
func (o RolePtrOutput) ToRolePtrOutput() RolePtrOutput {
return o
}
func (o RolePtrOutput) ToRolePtrOutputWithContext(ctx context.Context) RolePtrOutput {
return o
}
func (o RolePtrOutput) Elem() RoleOutput {
return o.ApplyT(func(v *Role) Role {
if v != nil {
return *v
}
var ret Role
return ret
}).(RoleOutput)
}
type RoleArrayOutput struct{ *pulumi.OutputState }
func (RoleArrayOutput) ElementType() reflect.Type {
return reflect.TypeOf((*[]Role)(nil))
}
func (o RoleArrayOutput) ToRoleArrayOutput() RoleArrayOutput {
return o
}
func (o RoleArrayOutput) ToRoleArrayOutputWithContext(ctx context.Context) RoleArrayOutput {
return o
}
func (o RoleArrayOutput) Index(i pulumi.IntInput) RoleOutput {
return pulumi.All(o, i).ApplyT(func(vs []interface{}) Role {
return vs[0].([]Role)[vs[1].(int)]
}).(RoleOutput)
}
type RoleMapOutput struct{ *pulumi.OutputState }
func (RoleMapOutput) ElementType() reflect.Type {
return reflect.TypeOf((*map[string]Role)(nil))
}
func (o RoleMapOutput) ToRoleMapOutput() RoleMapOutput {
return o
}
func (o RoleMapOutput) ToRoleMapOutputWithContext(ctx context.Context) RoleMapOutput {
return o
}
func (o RoleMapOutput) MapIndex(k pulumi.StringInput) RoleOutput {
return pulumi.All(o, k).ApplyT(func(vs []interface{}) Role {
return vs[0].(map[string]Role)[vs[1].(string)]
}).(RoleOutput)
}
func init() {
pulumi.RegisterInputType(reflect.TypeOf((*RoleInput)(nil)).Elem(), &Role{})
pulumi.RegisterInputType(reflect.TypeOf((*RolePtrInput)(nil)).Elem(), &Role{})
pulumi.RegisterInputType(reflect.TypeOf((*RoleArrayInput)(nil)).Elem(), RoleArray{})
pulumi.RegisterInputType(reflect.TypeOf((*RoleMapInput)(nil)).Elem(), RoleMap{})
pulumi.RegisterOutputType(RoleOutput{})
pulumi.RegisterOutputType(RolePtrOutput{})
pulumi.RegisterOutputType(RoleArrayOutput{})
pulumi.RegisterOutputType(RoleMapOutput{})
}
| GetRole |
servers.py | import ibmsecurity.utilities.tools
import logging
logger = logging.getLogger(__name__)
module_uri = "/isam/felb/configuration/services/"
requires_modulers = None
requires_version = None
def add(isamAppliance, service_name, address, active, port, weight, secure, ssllabel, check_mode=False, force=False):
"""
Creating a server
"""
change_required = _check_exist(isamAppliance, service_name, address, port=port)
if force is True or change_required is True:
if check_mode is True:
return isamAppliance.create_return_object(changed=True)
else:
return isamAppliance.invoke_post("Creating a server",
"{0}{1}/servers".format(module_uri, service_name, address),
{
"active": active,
"address": address,
"port": port,
"weight": weight,
"secure": secure,
"ssllabel": ssllabel
},
requires_version=requires_version, requires_modules=requires_modulers)
else:
return isamAppliance.create_return_object()
def delete(isamAppliance, service_name, address, check_mode=False, force=False):
"""
deletes a server from specified service name
"""
if force is True or _check_exist(isamAppliance, service_name, address) is True:
if check_mode is True:
return isamAppliance.create_return_object(changed=True)
else:
return isamAppliance.invoke_delete("Deleting a server",
"{0}{1}/servers/{2}".format(module_uri, service_name, address),
requires_version=requires_version, requires_modules=requires_modulers)
else:
return isamAppliance.create_return_object()
def get(isamAppliance, service_name, address, check_mode=False, force=False):
"""
Retrieves server from specified service name
"""
return (
isamAppliance.invoke_get("Retrieving a server", "{0}{1}/servers/{2}".format(module_uri, service_name, address),
requires_version=requires_version, requires_modules=requires_modulers))
def get_all(isamAppliance, service_name, check_mode=False, force=False):
"""
Retrieves a list of servers under a specified service
"""
return isamAppliance.invoke_get("Retrieving servers for a service",
"{0}{1}/servers".format(module_uri, service_name),
requires_version=requires_version, requires_modules=requires_modulers)
def | (isamAppliance, service_name, address, active, new_address, new_port, weight, secure=False, ssllabel=None,
check_mode=False,
force=False):
"""
Updating server
"""
change_required = _check_update(isamAppliance, service_name, address, active, new_address, new_port, weight, secure,
ssllabel)
if force is True or change_required is True:
if check_mode is True:
return isamAppliance.create_return_object(changed=True)
else:
return isamAppliance.invoke_put("Updating a server",
"{0}{1}/servers/{2}".format(module_uri, service_name, address),
{
"address": new_address,
"active": active,
"port": new_port,
"weight": weight,
"secure": secure,
"ssllabel": ssllabel
},
requires_modules=requires_modulers,
requires_version=requires_version)
else:
return isamAppliance.create_return_object()
def _check_update(isamAppliance, service_name, address, active, new_address, new_port, weight, secure=False,
ssllabel=None):
"""
idempontency test
"""
org_obj = get(isamAppliance, service_name, address)
if org_obj['data']['address'] != new_address:
return True
elif org_obj['data']['active'] != active:
return True
elif org_obj['data']['port'] != new_port:
return True
elif org_obj['data']['weight'] != weight:
return True
elif org_obj['data']['secure'] != secure:
return True
elif org_obj['data']['ssllabel'] != ssllabel:
return True
else:
return False
def _check_exist(isamAppliance, service_name, address):
"""
idempotency test for delete function
"""
check_obj = {}
# Check weather the address with corresponding server exists
try:
check_obj = get(isamAppliance, service_name, address)
except:
return False
return True
def compare(isamAppliance1, isamAppliance2):
"""
Compare cluster configuration between two appliances
"""
ret_obj1 = get(isamAppliance1)
ret_obj2 = get(isamAppliance2)
return ibmsecurity.utilities.tools.json_compare(ret_obj1, ret_obj2, deleted_keys=[])
| update |
mysql.go | package db
import (
"database/sql"
"fmt"
"log"
setting "dynamic-router/service/utils"
_ "github.com/go-sql-driver/mysql"
)
//SQLDB SQLDB
var SQLDB *sql.DB
//Setup Setup
func Setup() {
var err error | SQLDB, err = sql.Open(setting.DatabaseSetting.Type, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
setting.DatabaseSetting.User,
setting.DatabaseSetting.Password,
setting.DatabaseSetting.Host,
setting.DatabaseSetting.Name))
if err != nil {
log.Fatal(err.Error())
}
err = SQLDB.Ping()
if err != nil {
log.Fatal(err.Error())
}
} | |
babel.config.js | module.exports = {
presets: [
['@babel/preset-env', {
targets: {
node: 'current',
firefox: '60', | }],
],
}; | chrome: '67',
safari: '11.1',
}, |
locations.js | /**
* The idea behind "locations" (for lack of a better term)
* is that we can manage multiple goto points / zones or in the future nogo areas etc.
*
* They include the drawing logic (draw function) which is called by the vacuum-map,
* and can define hooks for user-interaction such as tapping or panning.
*/
/**
* Represents a point the robot can be sent to.
*/
export class GotoPoint {
constructor(x ,y) {
this.x = x;
this.y = y;
}
draw(ctx, transformFromMapSpace) {
const p1 = new DOMPoint(this.x, this.y).matrixTransform(transformFromMapSpace);
ctx.beginPath();
ctx.lineWidth = 2;
ctx.arc(p1.x, p1.y, 5, 0, 2 * Math.PI, false);
ctx.fillStyle = "red";
ctx.fill();
ctx.strokeStyle = "#550000";
ctx.stroke();
}
toZone(x2, y2) {
return new Zone(this.x, this.y, x2, y2);
}
}
/**
* Represents a zone for zoned_cleanup.
*/
export class Zone {
constructor(x1 ,y1, x2, y2) {
this.buttonSize = 30;
this.active = true;
this.isResizing = false;
this.x1 = Math.min(x1, x2);
this.x2 = Math.max(x1, x2);
this.y1 = Math.min(y1, y2);
this.y2 = Math.max(y1, y2);
}
draw(ctx, transformMapToScreenSpace) {
const p1 = new DOMPoint(this.x1, this.y1).matrixTransform(transformMapToScreenSpace);
const p2 = new DOMPoint(this.x2, this.y2).matrixTransform(transformMapToScreenSpace);
ctx.save();
if (!this.active) {
ctx.strokeStyle = "rgb(255, 255, 255)";
ctx.fillStyle = "rgba(255, 255, 255, 0.4)";
} else {
ctx.setLineDash([15, 5]);
ctx.strokeStyle = "rgb(255, 255, 255)";
ctx.fillStyle = "rgba(255, 255, 255, 0)";
}
ctx.lineWidth = 2;
ctx.fillRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
ctx.strokeRect(p1.x, p1.y, p2.x - p1.x, p2.y - p1.y);
ctx.restore();
if (this.active) {
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(p2.x, p1.y, this.buttonSize / 2, 0, 2 * Math.PI, false);
ctx.fillStyle = "red";
ctx.fill();
ctx.strokeStyle = "#550000";
ctx.stroke();
ctx.beginPath();
ctx.arc(p2.x, p2.y, this.buttonSize / 2, 0, 2 * Math.PI, false);
ctx.fillStyle = "green";
ctx.fill();
ctx.strokeStyle = "#005500";
ctx.stroke();
}
}
/**
* Handler for intercepting tap events on the canvas
* Used for activating / deleting the zone
*
* @param {{x: number, y: number}} tappedPoint - The tapped point in screen coordinates
* @param {DOMMatrix} transformMapToScreenSpace - The transformation for transforming map-space coordinates into screen-space.
* This is the transform applied by the vacuum-map canvas.
*/
tap(tappedPoint, transformMapToScreenSpace) {
const p1 = new DOMPoint(this.x1, this.y1).matrixTransform(transformMapToScreenSpace);
const p2 = new DOMPoint(this.x2, this.y2).matrixTransform(transformMapToScreenSpace);
const distanceFromDelete = Math.sqrt(
Math.pow(tappedPoint.x - p2.x, 2) + Math.pow(tappedPoint.y - p1.y, 2)
);
if (this.active && distanceFromDelete <= this.buttonSize / 2) {
return {
updatedLocation: null,
stopPropagation: true
};
} else if (
tappedPoint.x >= p1.x
&& tappedPoint.x <= p2.x
&& tappedPoint.y >= p1.y
&& tappedPoint.y <= p2.y
) {
this.active = true;
return {
updatedLocation: this,
stopPropagation: false
};
} else {
this.active = false;
}
return {
updatedLocation: this,
stopPropagation: false
};
}
/**
* Handler for intercepting pan events on the canvas
* Used for resizing / moving the zone
*
* @param {{x: number, y: number}} start - The coordinates where the panning started
* @param {{x: number, y: number}} last - The coordinates from the last call
* @param {{x: number, y: number}} current - The current coordinates of the pointer
* @param {DOMMatrix} transformMapToScreenSpace - The transformation for transforming map-space coordinates into screen-space.
* This is the transform applied by the vacuum-map canvas.
*/
translate(start, last, current, transformMapToScreenSpace) {
if (this.active) {
const transformCanvasToMapSpace = transformMapToScreenSpace.inverse();
const p1 = new DOMPoint(this.x1, this.y1).matrixTransform(transformMapToScreenSpace);
const p2 = new DOMPoint(this.x2, this.y2).matrixTransform(transformMapToScreenSpace);
const distanceFromResize = Math.sqrt(
Math.pow(last.x - p2.x, 2) + Math.pow(last.y - p2.y, 2)
);
if (!this.isResizing && distanceFromResize <= this.buttonSize / 2) {
this.isResizing = true;
}
const lastInMapSpace = new DOMPoint(last.x, last.y).matrixTransform(transformCanvasToMapSpace);
const currentInMapSpace = new DOMPoint(current.x, current.y).matrixTransform(transformCanvasToMapSpace);
const dx = currentInMapSpace.x - lastInMapSpace.x;
const dy = currentInMapSpace.y - lastInMapSpace.y;
if (this.isResizing) {
if (currentInMapSpace.x > this.x1 + 5 && this.x2 + dx > this.x1 + 5) {
this.x2 += dx;
}
if (currentInMapSpace.y > this.y1 + 5 && this.y2 + dy > this.y1 + 5) {
this.y2 += dy;
}
return {
updatedLocation: this,
stopPropagation: true
};
} else if (
last.x >= p1.x
&& last.x <= p2.x
&& last.y >= p1.y
&& last.y <= p2.y
) {
this.x1 += dx;
this.y1 += dy;
this.x2 += dx;
this.y2 += dy;
return {
updatedLocation: this,
stopPropagation: true
};
} else {
this.active = false;
}
}
return {
updatedLocation: this,
stopPropagation: false
};
}
}
/**
* Current goto target point
*/
export class GotoTarget {
constructor(x ,y) {
this.x = x;
this.y = y;
}
draw(ctx, transformFromMapSpace) {
const p1 = new DOMPoint(this.x, this.y).matrixTransform(transformFromMapSpace);
ctx.beginPath();
ctx.lineWidth = 2;
ctx.arc(p1.x, p1.y, 5, 0, 2 * Math.PI, false);
ctx.fillStyle = "rgb(107, 244, 66)";
ctx.fill();
ctx.strokeStyle = "rgb(53, 145, 26)";
ctx.stroke();
}
}
/**
* Represents the currently cleaned zone
*/
export class | {
/**
* @param {DOMPoint} p1
* @param {DOMPoint} p2
*/
constructor(p1, p2) {
this.p1 = p1;
this.p2 = p2;
}
draw(ctx, transformFromMapSpace) {
const p1Screen = this.p1.matrixTransform(transformFromMapSpace);
const p2Screen = this.p2.matrixTransform(transformFromMapSpace);
ctx.strokeStyle = "rgb(53, 145, 26)";
ctx.fillStyle = "rgba(107, 244, 66, 0.3)";
ctx.lineWidth = 2;
ctx.fillRect(p1Screen.x, p1Screen.y, p2Screen.x - p1Screen.x, p2Screen.y - p1Screen.y);
ctx.strokeRect(p1Screen.x, p1Screen.y, p2Screen.x - p1Screen.x, p2Screen.y - p1Screen.y);
}
}
/**
* Represents a virtual wall the robot does not pass
*/
export class VirtualWall {
constructor(x1 ,y1, x2, y2, editable) {
this.editable = editable || false;
if (editable) {
this.active = true;
this.buttonSize = 30;
} else {
this.active = false;
}
this.x1 = Math.min(x1, x2);
this.x2 = Math.max(x1, x2);
this.y1 = Math.min(y1, y2);
this.y2 = Math.max(y1, y2);
}
draw(ctx, transformFromMapSpace) {
const p1 = new DOMPoint(this.x1, this.y1).matrixTransform(transformFromMapSpace);
const p2 = new DOMPoint(this.x2, this.y2).matrixTransform(transformFromMapSpace);
ctx.save();
ctx.beginPath();
ctx.lineWidth = 5;
ctx.lineCap = "round";
ctx.strokeStyle = "red";
if (this.editable && this.active) {
ctx.setLineDash([8, 6]);
}
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.strokeStyle = "red";
ctx.stroke();
ctx.restore();
if (this.active) {
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(p1.x, p1.y, this.buttonSize / 2, 0, 2 * Math.PI, false);
ctx.fillStyle = "darkred";
ctx.fill();
ctx.strokeStyle = "#550000";
ctx.stroke();
ctx.beginPath();
ctx.arc(p2.x, p2.y, this.buttonSize / 2, 0, 2 * Math.PI, false);
ctx.fillStyle = "green";
ctx.fill();
ctx.strokeStyle = "#005500";
ctx.stroke();
}
if (this.editable) {
this.matrix = new DOMMatrix().rotateFromVectorSelf(p2.y - p1.y,p2.x - p1.x);
this.sp1 = p1.matrixTransform(new DOMMatrix().translate(-10).rotateFromVectorSelf(p2.y - p1.y,p2.x - p1.x));
this.sp2 = p2.matrixTransform(new DOMMatrix().translate(+10).rotateFromVectorSelf(p2.y - p1.y,p2.x - p1.x));
}
}
/**
* Handler for intercepting tap events on the canvas
* Used for activating / deleting the wall
*
* @param {{x: number, y: number}} tappedPoint - The tapped point in screen coordinates
* @param {DOMMatrix} transformMapToScreenSpace - The transformation for transforming map-space coordinates into screen-space.
* This is the transform applied by the vacuum-map canvas.
*/
tap(tappedPoint, transformMapToScreenSpace) {
if (!this.editable) {
return {
updatedLocation: this,
stopPropagation: false
};
}
const p1 = new DOMPoint(this.x1, this.y1).matrixTransform(transformMapToScreenSpace);
// eslint-disable-next-line no-unused-vars
const p2 = new DOMPoint(this.x2, this.y2).matrixTransform(transformMapToScreenSpace);
const distanceFromDelete = Math.sqrt(
Math.pow(tappedPoint.x - p1.x, 2) + Math.pow(tappedPoint.y - p1.y, 2)
);
const sTappedPoint = new DOMPoint(tappedPoint.x,tappedPoint.y).matrixTransform(this.matrix);
if (this.active && distanceFromDelete <= this.buttonSize / 2) {
return {
updatedLocation: null,
stopPropagation: true
};
} else if (
sTappedPoint.x >= this.sp1.x
&& sTappedPoint.x <= this.sp2.x
&& sTappedPoint.y >= this.sp1.y
&& sTappedPoint.y <= this.sp2.y
) {
this.active = true;
return {
updatedLocation: this,
stopPropagation: false
};
} else {
this.active = false;
}
return {
updatedLocation: this,
stopPropagation: false
};
}
/**
* Handler for intercepting pan events on the canvas
* Used for resizing / moving the zone
*
* @param {{x: number, y: number}} start - The coordinates where the panning started
* @param {{x: number, y: number}} last - The coordinates from the last call
* @param {{x: number, y: number}} current - The current coordinates of the pointer
* @param {DOMMatrix} transformMapToScreenSpace - The transformation for transforming map-space coordinates into screen-space.
* This is the transform applied by the vacuum-map canvas.
*/
translate(start, last, current, transformMapToScreenSpace) {
if (this.active) {
const transformCanvasToMapSpace = transformMapToScreenSpace.inverse();
// eslint-disable-next-line no-unused-vars
const p1 = new DOMPoint(this.x1, this.y1).matrixTransform(transformMapToScreenSpace);
const p2 = new DOMPoint(this.x2, this.y2).matrixTransform(transformMapToScreenSpace);
const distanceFromResize = Math.sqrt(
Math.pow(last.x - p2.x, 2) + Math.pow(last.y - p2.y, 2)
);
const lastInMapSpace = new DOMPoint(last.x, last.y).matrixTransform(transformCanvasToMapSpace);
const currentInMapSpace = new DOMPoint(current.x, current.y).matrixTransform(transformCanvasToMapSpace);
const dx = currentInMapSpace.x - lastInMapSpace.x;
const dy = currentInMapSpace.y - lastInMapSpace.y;
const sLast = new DOMPoint(last.x,last.y).matrixTransform(this.matrix);
if (distanceFromResize <= this.buttonSize / 2) {
this.x2 += dx;
this.y2 += dy;
return {
updatedLocation: this,
stopPropagation: true
};
} else if (
sLast.x >= this.sp1.x
&& sLast.x <= this.sp2.x
&& sLast.y >= this.sp1.y
&& sLast.y <= this.sp2.y
) {
this.x1 += dx;
this.y1 += dy;
this.x2 += dx;
this.y2 += dy;
return {
updatedLocation: this,
stopPropagation: true
};
}
}
return {
updatedLocation: this,
stopPropagation: false
};
}
}
/**
* Represents a nogo zone the robot does not enter
*/
export class ForbiddenZone {
constructor(x1, y1, x2, y2, x3, y3, x4, y4, editable) {
this.editable = editable || false;
if (editable) {
this.active = true;
this.isResizing = false;
this.buttonSize = 30;
} else {
this.active = false;
}
this.x1 = x1;
this.x2 = x2;
this.x3 = x3;
this.x4 = x4;
this.y1 = y1;
this.y2 = y2;
this.y3 = y3;
this.y4 = y4;
}
draw(ctx, transformMapToScreenSpace) {
const p1 = new DOMPoint(this.x1, this.y1).matrixTransform(transformMapToScreenSpace);
const p2 = new DOMPoint(this.x2, this.y2).matrixTransform(transformMapToScreenSpace);
const p3 = new DOMPoint(this.x3, this.y3).matrixTransform(transformMapToScreenSpace);
const p4 = new DOMPoint(this.x4, this.y4).matrixTransform(transformMapToScreenSpace);
ctx.save();
if (!this.active) {
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.fillStyle = "rgba(255, 0, 0, 0.4)";
} else {
ctx.setLineDash([8, 6]);
ctx.strokeStyle = "rgb(255, 0, 0)";
ctx.fillStyle = "rgba(255, 0, 0, 0)";
}
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(p1.x, p1.y);
ctx.lineTo(p2.x, p2.y);
ctx.lineTo(p3.x, p3.y);
ctx.lineTo(p4.x, p4.y);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.restore();
if (this.active) {
ctx.lineWidth = 2;
ctx.beginPath();
ctx.arc(p2.x, p2.y, this.buttonSize / 2, 0, 2 * Math.PI, false);
ctx.fillStyle = "darkred";
ctx.fill();
ctx.strokeStyle = "#550000";
ctx.stroke();
ctx.beginPath();
ctx.arc(p3.x, p3.y, this.buttonSize / 2, 0, 2 * Math.PI, false);
ctx.fillStyle = "green";
ctx.fill();
ctx.strokeStyle = "#005500";
ctx.stroke();
}
}
/**
* Handler for intercepting tap events on the canvas
* Used for activating / deleting the zone
*
* @param {{x: number, y: number}} tappedPoint - The tapped point in screen coordinates
* @param {DOMMatrix} transformMapToScreenSpace - The transformation for transforming map-space coordinates into screen-space.
* This is the transform applied by the vacuum-map canvas.
*/
tap(tappedPoint, transformMapToScreenSpace) {
if (!this.editable) {
return {
updatedLocation: this,
stopPropagation: false
};
}
const p1 = new DOMPoint(this.x1, this.y1).matrixTransform(transformMapToScreenSpace);
const p2 = new DOMPoint(this.x2, this.y2).matrixTransform(transformMapToScreenSpace);
const p3 = new DOMPoint(this.x3, this.y3).matrixTransform(transformMapToScreenSpace);
// eslint-disable-next-line no-unused-vars
const p4 = new DOMPoint(this.x4, this.y4).matrixTransform(transformMapToScreenSpace);
const distanceFromDelete = Math.sqrt(
Math.pow(tappedPoint.x - p2.x, 2) + Math.pow(tappedPoint.y - p2.y, 2)
);
if (this.active && distanceFromDelete <= this.buttonSize / 2) {
return {
updatedLocation: null,
stopPropagation: true
};
} else if (
tappedPoint.x >= p1.x
&& tappedPoint.x <= p3.x
&& tappedPoint.y >= p1.y
&& tappedPoint.y <= p3.y
) {
this.active = true;
return {
updatedLocation: this,
stopPropagation: false
};
} else {
this.active = false;
}
return {
updatedLocation: this,
stopPropagation: false
};
}
/**
* Handler for intercepting pan events on the canvas
* Used for resizing / moving the zone
*
* @param {{x: number, y: number}} start - The coordinates where the panning started
* @param {{x: number, y: number}} last - The coordinates from the last call
* @param {{x: number, y: number}} current - The current coordinates of the pointer
* @param {DOMMatrix} transformMapToScreenSpace - The transformation for transforming map-space coordinates into screen-space.
* This is the transform applied by the vacuum-map canvas.
*/
translate(start, last, current, transformMapToScreenSpace) {
if (this.active) {
const transformCanvasToMapSpace = transformMapToScreenSpace.inverse();
const p1 = new DOMPoint(this.x1, this.y1).matrixTransform(transformMapToScreenSpace);
// eslint-disable-next-line no-unused-vars
const p2 = new DOMPoint(this.x2, this.y2).matrixTransform(transformMapToScreenSpace);
const p3 = new DOMPoint(this.x3, this.y3).matrixTransform(transformMapToScreenSpace);
// eslint-disable-next-line no-unused-vars
const p4 = new DOMPoint(this.x4, this.y4).matrixTransform(transformMapToScreenSpace);
const distanceFromResize = Math.sqrt(
Math.pow(last.x - p3.x, 2) + Math.pow(last.y - p3.y, 2)
);
if (!this.isResizing && distanceFromResize <= this.buttonSize / 2) {
this.isResizing = true;
}
const lastInMapSpace = new DOMPoint(last.x, last.y).matrixTransform(transformCanvasToMapSpace);
const currentInMapSpace = new DOMPoint(current.x, current.y).matrixTransform(transformCanvasToMapSpace);
const dx = currentInMapSpace.x - lastInMapSpace.x;
const dy = currentInMapSpace.y - lastInMapSpace.y;
if (this.isResizing) {
if (currentInMapSpace.x > this.x1 + 5 && this.x2 + dx > this.x1 + 5) {
this.x2 += dx;
this.x3 += dx;
}
if (currentInMapSpace.y > this.y1 + 5 && this.y3 + dy > this.y1 + 5) {
this.y3 += dy;
this.y4 += dy;
}
return {
updatedLocation: this,
stopPropagation: true
};
} else if (
last.x >= p1.x
&& last.x <= p3.x
&& last.y >= p1.y
&& last.y <= p3.y
) {
this.x1 += dx;
this.y1 += dy;
this.x2 += dx;
this.y2 += dy;
this.x3 += dx;
this.y3 += dy;
this.x4 += dx;
this.y4 += dy;
return {
updatedLocation: this,
stopPropagation: true
};
}
}
return {
updatedLocation: this,
stopPropagation: false
};
}
}
| CurrentCleaningZone |
replication.go | // Copyright 2018 Project Harbor Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package api
import (
"fmt"
"net/http"
"github.com/goharbor/harbor/src/common/dao"
"github.com/goharbor/harbor/src/common/models"
"github.com/goharbor/harbor/src/common/utils/log"
api_models "github.com/goharbor/harbor/src/core/api/models"
"github.com/goharbor/harbor/src/core/notifier"
"github.com/goharbor/harbor/src/replication/core"
"github.com/goharbor/harbor/src/replication/event/notification"
"github.com/goharbor/harbor/src/replication/event/topic"
)
// ReplicationAPI handles API calls for replication
type ReplicationAPI struct {
BaseController
}
// Prepare does authentication and authorization works
func (r *ReplicationAPI) Prepare() {
r.BaseController.Prepare()
if !r.SecurityCtx.IsAuthenticated() {
r.HandleUnauthorized()
return
}
if !r.SecurityCtx.IsSysAdmin() && !r.SecurityCtx.IsSolutionUser() {
r.HandleForbidden(r.SecurityCtx.GetUsername())
return
}
}
// Post trigger a replication according to the specified policy
func (r *ReplicationAPI) Post() {
replication := &api_models.Replication{}
r.DecodeJSONReqAndValidate(replication)
policy, err := core.GlobalController.GetPolicy(replication.PolicyID)
if err != nil {
r.HandleInternalServerError(fmt.Sprintf("failed to get replication policy %d: %v", replication.PolicyID, err))
return
}
if policy.ID == 0 {
r.HandleNotFound(fmt.Sprintf("replication policy %d not found", replication.PolicyID))
return
}
count, err := dao.GetTotalCountOfRepJobs(&models.RepJobQuery{
PolicyID: replication.PolicyID,
Statuses: []string{models.JobPending, models.JobRunning},
Operations: []string{models.RepOpTransfer, models.RepOpDelete},
})
if err != nil {
r.HandleInternalServerError(fmt.Sprintf("failed to filter jobs of policy %d: %v",
replication.PolicyID, err))
return
}
if count > 0 {
r.RenderError(http.StatusPreconditionFailed, "policy has running/pending jobs, new replication can not be triggered")
return
}
if err = startReplication(replication.PolicyID); err != nil {
r.HandleInternalServerError(fmt.Sprintf("failed to publish replication topic for policy %d: %v", replication.PolicyID, err))
return
}
log.Infof("replication signal for policy %d sent", replication.PolicyID)
}
func | (policyID int64) error {
return notifier.Publish(topic.StartReplicationTopic,
notification.StartReplicationNotification{
PolicyID: policyID,
})
}
| startReplication |
dialogs.js | /**
* Created by Holger Stitz on 18.08.2016.
*/
import { I18nextManager } from 'phovea_core';
export class DialogUtils {
/**
* utility dialog when a session was not found
* @param {CLUEGraphManager} manager
* @param {string} id session id
*/
static showProveanceGraphNotFoundDialog(manager, id, additionalCSSClasses = '') {
import('phovea_ui/dist/components/dialogs').then(({ Dialog }) => {
const dialog = Dialog.generateDialog(I18nextManager.getInstance().i18n.t('tdp:core.sessionNotFound'), I18nextManager.getInstance().i18n.t('tdp:core.newSession'), additionalCSSClasses);
// append bg-danger to the dialog parent element
dialog.body.parentElement.parentElement.parentElement.classList.add('bg-danger');
dialog.body.innerHTML = `
<p>
${I18nextManager.getInstance().i18n.t('tdp:core.notAccessibleMessage', { id })}
</p>
<p>
${I18nextManager.getInstance().i18n.t('tdp:core.possibleReasons')}
<ul>
<li>${I18nextManager.getInstance().i18n.t('tdp:core.possibleReason1')}</li>
<li>${I18nextManager.getInstance().i18n.t('tdp:core.possibleReason2')}</li> | ${I18nextManager.getInstance().i18n.t('tdp:core.contactOwnerMessage')}
</p>`;
dialog.onSubmit(() => {
dialog.hide();
return false;
});
dialog.onHide(() => {
dialog.destroy();
manager.newGraph();
});
dialog.show();
});
}
}
//# sourceMappingURL=dialogs.js.map | <li>${I18nextManager.getInstance().i18n.t('tdp:core.possibleReason3')}</li>
</ul>
</p>
<p> |
static_test.go | // Copyright 2018 CNI authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"fmt"
"net"
"strings"
"github.com/containernetworking/cni/pkg/skel"
"github.com/containernetworking/cni/pkg/types"
"github.com/containernetworking/cni/pkg/types/100"
"github.com/containernetworking/plugins/pkg/testutils"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
)
var _ = Describe("static Operations", func() {
for _, ver := range testutils.AllSpecVersions {
// Redefine ver inside for scope so real value is picked up by each dynamically defined It()
// See Gingkgo's "Patterns for dynamically generating tests" documentation.
ver := ver
It(fmt.Sprintf("[%s] allocates and releases addresses with ADD/DEL", ver), func() {
const ifname string = "eth0"
const nspath string = "/some/where"
conf := fmt.Sprintf(`{
"cniVersion": "%s",
"name": "mynet",
"type": "ipvlan",
"master": "foo0",
"ipam": {
"type": "static",
"addresses": [ {
"address": "10.10.0.1/24",
"gateway": "10.10.0.254"
},
{
"address": "3ffe:ffff:0:01ff::1/64",
"gateway": "3ffe:ffff:0::1"
}],
"routes": [
{ "dst": "0.0.0.0/0" },
{ "dst": "192.168.0.0/16", "gw": "10.10.5.1" },
{ "dst": "3ffe:ffff:0:01ff::1/64" }],
"dns": {
"nameservers" : ["8.8.8.8"],
"domain": "example.com",
"search": [ "example.com" ]
}
}
}`, ver)
args := &skel.CmdArgs{
ContainerID: "dummy",
Netns: nspath,
IfName: ifname,
StdinData: []byte(conf),
}
// Allocate the IP
r, raw, err := testutils.CmdAddWithArgs(args, func() error {
return cmdAdd(args)
})
Expect(err).NotTo(HaveOccurred())
if testutils.SpecVersionHasIPVersion(ver) {
Expect(strings.Index(string(raw), "\"version\":")).Should(BeNumerically(">", 0))
}
result, err := types100.GetResult(r)
Expect(err).NotTo(HaveOccurred())
// Gomega is cranky about slices with different caps
Expect(*result.IPs[0]).To(Equal(
types100.IPConfig{
Address: mustCIDR("10.10.0.1/24"),
Gateway: net.ParseIP("10.10.0.254"),
}))
Expect(*result.IPs[1]).To(Equal(
types100.IPConfig{
Address: mustCIDR("3ffe:ffff:0:01ff::1/64"),
Gateway: net.ParseIP("3ffe:ffff:0::1"),
},
))
Expect(len(result.IPs)).To(Equal(2))
Expect(result.Routes).To(Equal([]*types.Route{
{Dst: mustCIDR("0.0.0.0/0")},
{Dst: mustCIDR("192.168.0.0/16"), GW: net.ParseIP("10.10.5.1")},
{Dst: mustCIDR("3ffe:ffff:0:01ff::1/64")},
}))
// Release the IP
err = testutils.CmdDelWithArgs(args, func() error {
return cmdDel(args)
})
Expect(err).NotTo(HaveOccurred())
})
It(fmt.Sprintf("[%s] doesn't error when passed an unknown ID on DEL", ver), func() {
const ifname string = "eth0"
const nspath string = "/some/where"
conf := fmt.Sprintf(`{
"cniVersion": "%s",
"name": "mynet",
"type": "ipvlan",
"master": "foo0",
"ipam": {
"type": "static",
"addresses": [ {
"address": "10.10.0.1/24",
"gateway": "10.10.0.254"
},
{
"address": "3ffe:ffff:0:01ff::1/64",
"gateway": "3ffe:ffff:0::1"
}],
"routes": [
{ "dst": "0.0.0.0/0" },
{ "dst": "192.168.0.0/16", "gw": "10.10.5.1" },
{ "dst": "3ffe:ffff:0:01ff::1/64" }],
"dns": {
"nameservers" : ["8.8.8.8"],
"domain": "example.com",
"search": [ "example.com" ]
}
}
}`, ver)
args := &skel.CmdArgs{
ContainerID: "dummy",
Netns: nspath,
IfName: ifname,
StdinData: []byte(conf),
}
// Release the IP
err := testutils.CmdDelWithArgs(args, func() error {
return cmdDel(args)
})
Expect(err).NotTo(HaveOccurred())
})
It(fmt.Sprintf("[%s] allocates and releases addresses with ADD/DEL, with ENV variables", ver), func() {
const ifname string = "eth0"
const nspath string = "/some/where"
conf := fmt.Sprintf(`{
"cniVersion": "%s",
"name": "mynet",
"type": "ipvlan",
"master": "foo0",
"ipam": {
"type": "static",
"routes": [
{ "dst": "0.0.0.0/0" },
{ "dst": "192.168.0.0/16", "gw": "10.10.5.1" }],
"dns": {
"nameservers" : ["8.8.8.8"],
"domain": "example.com",
"search": [ "example.com" ]
}
}
}`, ver)
args := &skel.CmdArgs{
ContainerID: "dummy",
Netns: nspath,
IfName: ifname,
StdinData: []byte(conf),
Args: "IP=10.10.0.1/24;GATEWAY=10.10.0.254",
}
// Allocate the IP
r, raw, err := testutils.CmdAddWithArgs(args, func() error {
return cmdAdd(args)
})
Expect(err).NotTo(HaveOccurred())
if testutils.SpecVersionHasIPVersion(ver) {
Expect(strings.Index(string(raw), "\"version\":")).Should(BeNumerically(">", 0))
}
result, err := types100.GetResult(r)
Expect(err).NotTo(HaveOccurred())
// Gomega is cranky about slices with different caps
Expect(*result.IPs[0]).To(Equal(
types100.IPConfig{
Address: mustCIDR("10.10.0.1/24"),
Gateway: net.ParseIP("10.10.0.254"),
}))
Expect(len(result.IPs)).To(Equal(1))
Expect(result.Routes).To(Equal([]*types.Route{
{Dst: mustCIDR("0.0.0.0/0")},
{Dst: mustCIDR("192.168.0.0/16"), GW: net.ParseIP("10.10.5.1")},
}))
// Release the IP
err = testutils.CmdDelWithArgs(args, func() error {
return cmdDel(args)
})
Expect(err).NotTo(HaveOccurred())
})
It(fmt.Sprintf("[%s] allocates and releases multiple addresses with ADD/DEL, with ENV variables", ver), func() {
const ifname string = "eth0"
const nspath string = "/some/where"
conf := fmt.Sprintf(`{
"cniVersion": "%s",
"name": "mynet",
"type": "ipvlan",
"master": "foo0",
"ipam": {
"type": "static"
}
}`, ver)
args := &skel.CmdArgs{
ContainerID: "dummy",
Netns: nspath,
IfName: ifname,
StdinData: []byte(conf),
Args: "IP=10.10.0.1/24,11.11.0.1/24;GATEWAY=10.10.0.254",
}
// Allocate the IP
r, raw, err := testutils.CmdAddWithArgs(args, func() error {
return cmdAdd(args)
})
if !testutils.SpecVersionHasMultipleIPs(ver) {
errStr := fmt.Sprintf("CNI version %s does not support more than 1 address per family", ver)
Expect(err).To(MatchError(errStr))
return
}
Expect(err).NotTo(HaveOccurred())
if testutils.SpecVersionHasIPVersion(ver) {
Expect(strings.Index(string(raw), "\"version\":")).Should(BeNumerically(">", 0))
}
result, err := types100.GetResult(r)
Expect(err).NotTo(HaveOccurred())
// Gomega is cranky about slices with different caps
Expect(*result.IPs[0]).To(Equal(
types100.IPConfig{
Address: mustCIDR("10.10.0.1/24"),
Gateway: net.ParseIP("10.10.0.254"),
}))
Expect(*result.IPs[1]).To(Equal(
types100.IPConfig{
Address: mustCIDR("11.11.0.1/24"),
Gateway: nil,
}))
Expect(len(result.IPs)).To(Equal(2))
// Release the IP
err = testutils.CmdDelWithArgs(args, func() error {
return cmdDel(args)
})
Expect(err).NotTo(HaveOccurred())
})
It(fmt.Sprintf("[%s] allocates and releases multiple addresses with ADD/DEL, from RuntimeConfig", ver), func() {
const ifname string = "eth0"
const nspath string = "/some/where"
conf := fmt.Sprintf(`{
"cniVersion": "%s",
"name": "mynet",
"type": "ipvlan",
"master": "foo0",
"capabilities": {"ips": true},
"ipam": {
"type": "static",
"routes": [
{ "dst": "0.0.0.0/0", "gw": "10.10.0.254" },
{ "dst": "3ffe:ffff:0:01ff::1/64",
"gw": "3ffe:ffff:0::1" } ],
"dns": {
"nameservers" : ["8.8.8.8"],
"domain": "example.com",
"search": [ "example.com" ]
}
},
"RuntimeConfig": {
"ips" : ["10.10.0.1/24", "3ffe:ffff:0:01ff::1/64"]
}
}`, ver)
args := &skel.CmdArgs{
ContainerID: "dummy",
Netns: nspath,
IfName: ifname,
StdinData: []byte(conf),
}
// Allocate the IP
r, raw, err := testutils.CmdAddWithArgs(args, func() error {
return cmdAdd(args)
})
Expect(err).NotTo(HaveOccurred())
if testutils.SpecVersionHasIPVersion(ver) {
Expect(strings.Index(string(raw), "\"version\":")).Should(BeNumerically(">", 0))
}
result, err := types100.GetResult(r)
Expect(err).NotTo(HaveOccurred())
// Gomega is cranky about slices with different caps
Expect(*result.IPs[0]).To(Equal(
types100.IPConfig{
Address: mustCIDR("10.10.0.1/24"),
}))
Expect(*result.IPs[1]).To(Equal(
types100.IPConfig{
Address: mustCIDR("3ffe:ffff:0:01ff::1/64"),
},
))
Expect(len(result.IPs)).To(Equal(2))
Expect(result.Routes).To(Equal([]*types.Route{
{Dst: mustCIDR("0.0.0.0/0"), GW: net.ParseIP("10.10.0.254")},
{Dst: mustCIDR("3ffe:ffff:0:01ff::1/64"), GW: net.ParseIP("3ffe:ffff:0::1")},
}))
// Release the IP
err = testutils.CmdDelWithArgs(args, func() error {
return cmdDel(args)
})
Expect(err).NotTo(HaveOccurred())
})
It(fmt.Sprintf("[%s] allocates and releases multiple addresses with ADD/DEL, from args", ver), func() {
const ifname string = "eth0"
const nspath string = "/some/where"
conf := fmt.Sprintf(`{
"cniVersion": "%s", | "type": "static",
"routes": [
{ "dst": "0.0.0.0/0", "gw": "10.10.0.254" },
{ "dst": "3ffe:ffff:0:01ff::1/64",
"gw": "3ffe:ffff:0::1" } ],
"dns": {
"nameservers" : ["8.8.8.8"],
"domain": "example.com",
"search": [ "example.com" ]
}
},
"args": {
"cni": {
"ips" : ["10.10.0.1/24", "3ffe:ffff:0:01ff::1/64"]
}
}
}`, ver)
args := &skel.CmdArgs{
ContainerID: "dummy",
Netns: nspath,
IfName: ifname,
StdinData: []byte(conf),
}
// Allocate the IP
r, raw, err := testutils.CmdAddWithArgs(args, func() error {
return cmdAdd(args)
})
Expect(err).NotTo(HaveOccurred())
if testutils.SpecVersionHasIPVersion(ver) {
Expect(strings.Index(string(raw), "\"version\":")).Should(BeNumerically(">", 0))
}
result, err := types100.GetResult(r)
Expect(err).NotTo(HaveOccurred())
// Gomega is cranky about slices with different caps
Expect(*result.IPs[0]).To(Equal(
types100.IPConfig{
Address: mustCIDR("10.10.0.1/24"),
}))
Expect(*result.IPs[1]).To(Equal(
types100.IPConfig{
Address: mustCIDR("3ffe:ffff:0:01ff::1/64"),
},
))
Expect(len(result.IPs)).To(Equal(2))
Expect(result.Routes).To(Equal([]*types.Route{
{Dst: mustCIDR("0.0.0.0/0"), GW: net.ParseIP("10.10.0.254")},
{Dst: mustCIDR("3ffe:ffff:0:01ff::1/64"), GW: net.ParseIP("3ffe:ffff:0::1")},
}))
// Release the IP
err = testutils.CmdDelWithArgs(args, func() error {
return cmdDel(args)
})
Expect(err).NotTo(HaveOccurred())
})
It(fmt.Sprintf("[%s] allocates and releases multiple addresses with ADD/DEL, from RuntimeConfig/ARGS/CNI_ARGS", ver), func() {
const ifname string = "eth0"
const nspath string = "/some/where"
conf := fmt.Sprintf(`{
"cniVersion": "%s",
"name": "mynet",
"type": "ipvlan",
"master": "foo0",
"capabilities": {"ips": true},
"ipam": {
"type": "static",
"routes": [
{ "dst": "0.0.0.0/0", "gw": "10.10.0.254" },
{ "dst": "3ffe:ffff:0:01ff::1/64",
"gw": "3ffe:ffff:0::1" } ],
"dns": {
"nameservers" : ["8.8.8.8"],
"domain": "example.com",
"search": [ "example.com" ]
}
},
"RuntimeConfig": {
"ips" : ["10.10.0.1/24", "3ffe:ffff:0:01ff::1/64"]
},
"args": {
"cni": {
"ips" : ["10.10.0.2/24", "3ffe:ffff:0:01ff::2/64"]
}
}
}`, ver)
args := &skel.CmdArgs{
ContainerID: "dummy",
Netns: nspath,
IfName: ifname,
StdinData: []byte(conf),
Args: "IP=10.10.0.3/24,11.11.0.3/24;GATEWAY=10.10.0.254",
}
// Allocate the IP
r, raw, err := testutils.CmdAddWithArgs(args, func() error {
return cmdAdd(args)
})
Expect(err).NotTo(HaveOccurred())
if testutils.SpecVersionHasIPVersion(ver) {
Expect(strings.Index(string(raw), "\"version\":")).Should(BeNumerically(">", 0))
}
result, err := types100.GetResult(r)
Expect(err).NotTo(HaveOccurred())
// only addresses in runtimeConfig configured because of its priorities
Expect(*result.IPs[0]).To(Equal(
types100.IPConfig{
Address: mustCIDR("10.10.0.1/24"),
}))
Expect(*result.IPs[1]).To(Equal(
types100.IPConfig{
Address: mustCIDR("3ffe:ffff:0:01ff::1/64"),
},
))
Expect(len(result.IPs)).To(Equal(2))
Expect(result.Routes).To(Equal([]*types.Route{
{Dst: mustCIDR("0.0.0.0/0"), GW: net.ParseIP("10.10.0.254")},
{Dst: mustCIDR("3ffe:ffff:0:01ff::1/64"), GW: net.ParseIP("3ffe:ffff:0::1")},
}))
// Release the IP
err = testutils.CmdDelWithArgs(args, func() error {
return cmdDel(args)
})
Expect(err).NotTo(HaveOccurred())
})
}
})
func mustCIDR(s string) net.IPNet {
ip, n, err := net.ParseCIDR(s)
n.IP = ip
if err != nil {
Fail(err.Error())
}
return *n
} | "name": "mynet",
"type": "ipvlan",
"master": "foo0",
"ipam": { |
fabric-multiselect.ts | class FabricMultiSelect extends HTMLElement {
private _refs: { [index: string]: any };
private _disabled: boolean = false;
private _required: boolean = false;
private _value: any[];
private _options: any[];
private _label: string = '';
constructor() {
super();
this._refs = {};
this._value = [];
this._options = [];
}
get disabled() { return this._disabled; }
set disabled(value) { if (this._disabled === value) return; this._disabled = !!value; this.__setProperties('disabled'); }
get required() { return this._required; }
set required(value) { if (this._required === value) return; this._required = !!value; this.__setProperties('required'); }
get value() { return this._value || [] }
//@ts-ignore
set value(value) { value = [].concat(value); if (value.sort().join(',') === this._value.sort().join(',')) return; this._value = value; this.__setProperties('value') }
get options() { return this._options || [] }
set options(value) { this._options = value; this.__setProperties('options'); }
get label() { return this._label }
set label(value) { if (value === this._label) return; this._label = value; this.__setProperties('label'); }
connectedCallback() {
this.__setupUI();
this.__setProperties();
this.__addListeners();
}
private __setupUI() {
let markup = `<div class="ms-MultiSelect" tabindex="0">
<label class="ms-Label"></label>
<div class="ms-MultiSelect--container flex-container">
<fabric-table modifier="selectable" columns='[{\"id\":\"value\",\"label\":\"Selected\"}]' rowid="value" itemheight="20" class="ms-MultiSelect--selected stretch"></fabric-table>
<ul class="ms-MultiSelect--controls flex-container vertical">
<li><button data-action="select-all"><<</button></li>
<li><button data-action="select"><</button></li>
<li><button data-action="unselect">></button></li>
<li><button data-action="unselect-all">>></button></li>
</ul>
<fabric-table modifier="selectable" columns='[{\"id\":\"value\",\"label\":\"Selectable\"}]' rowid="value" itemheight="20" class="ms-MultiSelect--selectable stretch"></fabric-table>
</div>
</div>`; | if (this.children && this.children.length > 0) {
let options = [];
let value = [];
while (this.children.length > 0) {
// Check conditions - remove non-matching children
if (this.children[0].tagName.toLowerCase() === 'option') {
// Move child to options
//@ts-ignore
options.push({ id: this.children[0].value || this.children[0].label || this.children[0].textContent, value: this.children[0].textContent })
//@ts-ignore
if (this.children[0].hasAttribute('selected')) value.push(this.children[0].value || this.children[0].label || this.children[0].textContent);
}
this.removeChild(this.children[0]);
}
if (options.length > 0) this._options = options;
if (value.length > 0) this._value = value;
}
// Create new markup
this.innerHTML = markup;
// Update references
this._refs = {
container: this.querySelector('.ms-MultiSelect--container'),
label: this.querySelector('label'),
selected: this.querySelector('.ms-MultiSelect--selected'),
selectable: this.querySelector('.ms-MultiSelect--selectable'),
controls: this.querySelector('.ms-MultiSelect--controls')
}
}
private __setProperties(property?: string) {
if (!this._refs || !this._refs.container) return;
if (property == null || property === 'disabled') {
this._refs.container.classList[(this._disabled) ? 'add' : 'remove']('is-disabled');
}
if (property == null || property === 'label') {
this._refs.label.textContent = this._label || ''
}
if (property == null || property === 'options' || property === 'value') {
this._refs.selectable.items = (this._options || []).filter(option => this._value.indexOf(option.id) === -1)
this._refs.selected.items = (this._options || []).filter(option => this._value.indexOf(option.id) !== -1)
}
}
private __addListeners() {
if (this._refs.controls)
this._refs.controls.addEventListener('click', (e: MouseEvent) => {
//@ts-ignore
if (e.target && e.target.tagName === 'BUTTON') {
// console.log('onControlClick', e, e.target.dataset.action)
//@ts-ignore
switch (e.target.dataset.action) {
case 'select-all':
this.value = this.options.map(o => o.value)
break;
case 'select':
let toSelect = this._refs.selectable.selected;
if (toSelect && toSelect.length > 0) this.value = this.value.concat(toSelect)
break;
case 'unselect':
let toDeselect = this._refs.selected.selected;
if (toDeselect && toDeselect.length > 0) {
//@ts-ignore
let value = [].concat(this.value);
//@ts-ignore
toDeselect.forEach(element => {
//@ts-ignore
let position = value.indexOf(element);
if (position !== -1) value.splice(position, 1)
});
this.value = value;
}
break;
case 'unselect-all':
this.value = [];
break;
}
}
})
}
checkValidity() {
return (this.required === true) ? this.value.length > 0 : true;
}
static get observedAttributes() {
return ['label', 'value', 'disabled', 'required'];
}
attributeChangedCallback(attr: string, oldValue: string, newValue: string) {
// console.log('attributeChangedCallback', attr, oldValue, newValue);
let n: string | string[] = (attr === 'value') ? newValue.split(',') : newValue;
//@ts-ignore
if (typeof this[attr] === 'boolean') { n = this.hasAttribute(attr) }
//@ts-ignore
if (oldValue === n || n === this[attr]) return;
//@ts-ignore
this[attr] = n;
}
}
window.customElements.define('fabric-multiselect', FabricMultiSelect);
// Set styles
(function (w, d) {
let style = d.createElement('STYLE');
style.textContent = `fabric-multiselect {
display: inline-block;
font-family:Segoe UI WestEuropean,Segoe UI,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;
height: 250px;
}
fabric-multiselect .flex-container {
display: -ms-flexbox;
display: -webkit-flex;
display: flex;
-webkit-flex-direction: row;
-ms-flex-direction: row;
flex-direction: row;
-webkit-flex-wrap: nowrap;
-ms-flex-wrap: nowrap;
flex-wrap: nowrap;
-webkit-justify-content: center;
-ms-flex-pack: center;
justify-content: center;
-webkit-align-content: stretch;
-ms-flex-line-pack: stretch;
align-content: stretch;
-webkit-align-items: stretch;
-ms-flex-align: stretch;
align-items: stretch;
}
fabric-multiselect .flex-container.vertical{
-webkit-flex-direction: column;
-ms-flex-direction: column;
flex-direction: column;
}
fabric-multiselect .flex-container > * {
order: 0;
flex: 0 1 auto;
align-self: auto;
}
fabric-multiselect .flex-container > *.stretch {
flex: 1 1 auto;
}
fabric-multiselect .ms-MultiSelect--controls{
margin: 5px;
padding: 0px;
width: 50px;
list-style-type: none
}
fabric-multiselect .ms-MultiSelect{
height: 100%
}
fabric-multiselect .ms-MultiSelect--container{
height: calc(100% - 25px)
}
.ms-MultiSelect .ms-Label {
display: inline-block;
margin-bottom: 8px;
font-size: 12px;
}
.ms-MultiSelect fabric-table {
box-sizing: border-box;
border: 1px solid #eaeaea
}
.ms-MultiSelect--controls li {
text-align:center
}
.ms-MultiSelect--controls button {
background: none;
border: 0;
color: #666666;
font-family:Segoe UI WestEuropean,Segoe UI,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif;-webkit-font-smoothing:antialiased;
}
`;
d.head.appendChild(style);
})(window, document); |
// Move predefined options to new markup |
containerization.go | // Package containerization loads the kubernetes specifics parts, like
// BOSHContainerization, from the BOSH manifest.
package containerization
import (
"github.com/ghodss/yaml"
corev1 "k8s.io/api/core/v1"
"code.cloudfoundry.org/cf-operator/pkg/bosh/bpm"
)
// Manifest is a BOSH deployment manifest
type Manifest struct {
InstanceGroups []*InstanceGroup `json:"instance_groups,omitempty"`
}
// InstanceGroup has been added to navigate to the containerization fields
type InstanceGroup struct {
Jobs []Job `json:"jobs"`
// for env.bosh.agent.settings.affinity
Env Env `json:"env,omitempty"`
}
// Job has been added to navigate to the containerization fields
type Job struct {
Properties JobProperties `json:"properties,omitempty"`
}
// JobProperties has been added to navigate to the containerization fields
type JobProperties struct {
BOSHContainerization BOSHContainerization `json:"bosh_containerization"`
}
// Env has been added to navigate to the containerization fields
type Env struct {
BOSH BOSH `json:"bosh,omitempty"`
}
// BOSH has been added to navigate to the containerization fields
type BOSH struct {
Agent Agent `json:"agent,omitempty"`
}
// Agent has been added to navigate to the containerization fields
type Agent struct {
Settings Settings `json:"settings,omitempty"`
}
// Settings has been added to make the k8s native Affinity field accessible
type Settings struct {
Affinity *corev1.Affinity `json:"affinity,omitempty" yaml:"affinity,omitempty"`
}
// BOSHContainerization represents the special 'bosh_containerization'
// property key. It contains all kubernetes structures we need to add to the BOSH manifest.
type BOSHContainerization struct {
Consumes map[string]JobLink `json:"consumes"`
Instances []JobInstance `json:"instances"`
Release string `json:"release"`
BPM *bpm.Config `json:"bpm,omitempty" yaml:"bpm,omitempty"`
Ports []Port `json:"ports"`
Run RunConfig `json:"run"`
PreRenderScripts []string `json:"pre_render_scripts" yaml:"pre_render_scripts"`
Debug bool `json:"debug" yaml:"debug"`
}
// Port represents the port to be opened up for this job
type Port struct {
Name string `json:"name"`
Protocol string `json:"protocol"`
Internal int `json:"internal"`
}
// JobInstance for data gathering
type JobInstance struct {
Address string `json:"address"`
AZ string `json:"az"`
ID string `json:"id"`
Index int `json:"index"`
Instance int `json:"instance"`
Name string `json:"name"`
Network map[string]interface{} `json:"networks"`
IP string `json:"ip"`
}
// JobLink describes links inside a job properties
// bosh_containerization.
type JobLink struct {
Instances []JobInstance `json:"instances"`
Properties map[string]interface{} `json:"properties"`
}
// HealthCheck defines liveness and readiness probes for a container
type HealthCheck struct {
ReadinessProbe *corev1.Probe `json:"readiness"`
LivenessProbe *corev1.Probe `json:"liveness"`
}
// RunConfig describes the runtime configuration for this job
type RunConfig struct {
HealthChecks map[string]HealthCheck `json:"healthcheck"`
}
// LoadKubeYAML is a special loader, since the YAML is already compatible to
// k8s structures without further transformation.
func LoadKubeYAML(data []byte) (*Manifest, error) | {
m := &Manifest{}
err := yaml.Unmarshal(data, m)
if err != nil {
return nil, err
}
return m, nil
} |
|
__init__.py | # Copyright 2021 AI Singapore
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# | # https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Utility functions for heuristic nodes
""" | |
ReagentDatasets.js | import React from 'react';
import {Grid, Row, Col, Accordion, Panel, ListGroup, ListGroupItem, Button,Table} from 'react-bootstrap';
import axios from 'axios';
class | extends React.Component {
constructor(props){
super(props)
this.state = {
datasets:[],
totaldocuments:""
}
this.handleSerice = props.handleChange;
}
componentDidMount(){
this.getDatasets();
}
getDatasets(){
axios.request({
method:'get',
url:'http://lincsportal.ccs.miami.edu/dcic/api/fetchdata?fields=datasetname,datasetgroup,assayname,centerletter,centerurl,assaydesignmethod,biologicalbucket&limit=200&searchTerm='+this.props.id+'"&skip=0'
}).then((response) => {
this.setState({datasets: response.data.results.documents,totaldocuments: response.data.results.totalDocuments}, () => {
});
}).catch((error) => {
console.log(error);
});
}
render() {
let datasetItems;
datasetItems = this.state.datasets.map(dataset => {
let id = dataset.datasetgroup;
let title = dataset.datasetname;
let assay = dataset.assayname;
let center = "/media/icons/" + dataset.centerletter + ".png";
let area = dataset.biologicalbucket;
let sourcelink = dataset.centerdatasetid;
return (
<tr key={id}>
<td style={{fontSize: "0.8rem",padding: ".3rem"}}>
<a style={{ color: "#337ab7"}} className="data-button"
href={`/signatures/datasets/${dataset.datasetgroup}`}>{id}</a>
</td>
<td style={{fontSize: "0.8rem",padding: ".3rem"}}>
{title}
</td>
<td style={{fontSize: "0.8rem",padding: ".3rem"}} >
<img className="listcenterimage" src={center} role="presentation"/>
</td>
<td style={{fontSize: "0.8rem",padding: ".3rem"}}>{assay}</td>
<td style={{fontSize: "0.8rem",padding: ".3rem"}}>{area}</td>
</tr>
)
});
return (
<div >
<h5 style={{color:"#CC3300"}}>Datasets : {this.state.totaldocuments}</h5>
<hr style={{borderTop: "1px solid #CC3300"}} />
<Table bordered >
<thead>
<tr>
<th style={{width:"10%",fontSize: "0.8rem",padding: ".3rem"}}>ID</th>
<th style={{width:"40%",fontSize: "0.8rem",padding: ".3rem"}}>Dataset</th>
<th style={{width:"10%",fontSize: "0.8rem",padding: ".3rem"}}>Center</th>
<th style={{width:"20%",fontSize: "0.8rem",padding: ".3rem"}}>Assay</th>
<th style={{width:"10%",fontSize: "0.8rem",padding: ".3rem"}}>Subject Area</th>
</tr>
</thead>
<tbody>
{datasetItems}
</tbody>
</Table>
</div>
);
}
}
export default ReagentDatasets;
| ReagentDatasets |
setup.py | #!/usr/bin/env python
import sys
from os.path import exists
from setuptools import setup
import versioneer
# NOTE: These are tested in `continuous_integration/test_imports.sh` If
# you modify these, make sure to change the corresponding line there.
extras_require = {
"array": ["numpy >= 1.18"],
"bag": [], # keeping for backwards compatibility
"dataframe": ["numpy >= 1.18", "pandas >= 1.0"],
"distributed": ["distributed == 2022.01.0"],
"diagnostics": [
"bokeh >= 2.1.1",
"jinja2",
],
"delayed": [], # keeping for backwards compatibility
}
extras_require["complete"] = sorted({v for req in extras_require.values() for v in req})
# after complete is set, add in test
extras_require["test"] = [
"pytest",
"pytest-rerunfailures",
"pytest-xdist",
"pre-commit",
]
install_requires = [
"cloudpickle >= 1.1.1",
"fsspec >= 0.6.0",
"packaging >= 20.0",
"partd >= 0.3.10",
"pyyaml >= 5.3.1",
"toolz >= 0.8.2",
]
packages = [
"dask",
"dask.array",
"dask.bag",
"dask.bytes",
"dask.dataframe",
"dask.dataframe.io",
"dask.dataframe.tseries",
"dask.diagnostics",
]
tests = [p + ".tests" for p in packages]
# Only include pytest-runner in setup_requires if we're invoking tests
if {"pytest", "test", "ptr"}.intersection(sys.argv):
setup_requires = ["pytest-runner"]
else:
setup_requires = []
setup( | url="https://github.com/dask/dask/",
maintainer="Matthew Rocklin",
maintainer_email="[email protected]",
license="BSD",
keywords="task-scheduling parallel numpy pandas pydata",
classifiers=[
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"License :: OSI Approved :: BSD License",
],
packages=packages + tests,
long_description=open("README.rst").read() if exists("README.rst") else "",
python_requires=">=3.7",
install_requires=install_requires,
setup_requires=setup_requires,
tests_require=["pytest"],
extras_require=extras_require,
include_package_data=True,
zip_safe=False,
) | name="dask",
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description="Parallel PyData with Task Scheduling", |
App.js | //최종
import React, { Component } from "react";
import firebase, { auth, provider } from "./firebase";
import { connect } from "react-redux";
import "./App.css";
import { sendMessage } from "./chat";
import Modal from 'react-responsive-modal';
class App extends Component {
constructor(props) {
super(props); // 리액트 클래스의 생성자를 미리 실행후 state설정을 해준다.
this.login = this.login.bind(this);
this.logout = this.logout.bind(this);
this.onOpenModal = this.onOpenModal.bind(this);
this.onCloseModal = this.onCloseModal.bind(this);
this.state = {
input: "",
user: null,
open: false
};
}
_handleText = e => {
this.setState({ input: e.target.value });
};
//login 버튼 실행시 google login popup 뜨고 login 성공 시 user set
login = () => {
auth.signInWithRedirect(provider);
};
//logout 버튼 실행시 user값 null
logout = () => {
auth.signOut().then(() => {
this.setState({
user: null
});
});
window.location.reload(); //페이지 새로고침
};
//login 상태 확인
checkAuthState = () => {
auth.onAuthStateChanged(user => {
if (user) {
this.setState({ user });
}
});
};
//자동으로 스크롤 내리기
autoscroll() {
var d = document.getElementById("message");
d.scrollTop = d.scrollHeight;
console.log(d);
}
componentDidMount() {
this.checkAuthState();
this.autoscroll();
}
componentDidUpdate() {
this.autoscroll();
}
//입력 눌렀을 때 실행
inputText = input => {
const { sendMessage } = this.props;
if (input === "") {
return 0;
}
else {
sendMessage(input);
this.keyReset();
this.setState({ input: "" });
this.autoscroll();
}
this.autoscroll();
};
//메모 함수 구현
note = input => {
if (this.state.user === null) {
alert("Google login 해주세요.");
}
else {
var memoRef = firebase.database().ref("memos/" + this.state.user.uid);
var txt = input;
if (txt === "") {
return;
}
memoRef.push({
txt: txt,
creatData: new Date().getTime()
});
//alert("저장되었습니다.");
this.setState({
input: ""
});
this.keyReset();
}
};
//search + list
search = input => {
const {sendMessage} = this.props;
if (this.state.user === null) {
alert("로그인 먼저 해주세요");
return 0;
}
else {
var txt;
if (input === "") { txt = "저장된 메모 리스트입니다."; }
else { txt = input + "로 검색한 결과입니다."; }
sendMessage(txt, "MEMO_LIST", "bot");
var ref = firebase.database().ref("memos/" + this.state.user.uid);
ref.on("child_added", function (e) {
var message = e.val().txt;
var key = e.key;
if (input === "") {
sendMessage(message, "MEMO_LIST", "bot_list", key);
}
else {
if (message.match(input)) {
sendMessage(message, "MEMO_LIST", "bot_list", key);
}
}
});
this.keyReset();
}
}
//삭제 함수
delete(e){
//x버튼을 누루면
const { sendMessage } = this.props;
var ref = firebase.database().ref("memos/" + this.state.user.uid);
var tmp_key = firebase.database().ref("memos/" + this.state.user.uid + '/' + e);
var txt = "새로 갱신한 리스트입니다."
console.log(e);
if (window.confirm("삭제 하시겠습니까??")) {
tmp_key.remove();
sendMessage(txt, "MEMO_LIST", "bot");
ref.on("child_added", function (e) {
var message = e.val().txt;
sendMessage(message, "MEMO_LIST", "bot_list");
});
}
else {
return;
}
};
getOpenSourceList(){
var ref = firebase.database().ref("opensrc/data");
ref.on("value", function (e) {
var list = e.val();
console.log(list);
document.getElementById("opensrc").innerText=list;
});
}
onOpenModal = () => {
this.setState({ open: true });
};
onCloseModal = () => {
this.setState({ open: false });
};
//입력창 초기화
keyReset() {
document.getElementById("message_box").value = "";
document.getElementById("search_box").value = "";
this.setState({ input: "" });
}
//화면에 랜더링(표시)
render() {
const { feed } = this.props;
return (
<div className="Whole_container"> | </div>
<div id="user-container">
{this.state.user ? (
<button className="sign_button" onClick={this.logout}>sign Out</button>
): (
<button className="sign_button" onClick={this.login}>Sign in with Google</button>
)}
<button className="os_button" onClick={() => {this.onOpenModal()}}>☆</button>
</div>
</div>
</header>
<main>
<div className="in_main">
<div className="in_in_main">
<div className="message_card">
<div id="search_from">
<textarea type="text" id="search_box" placeholder="?" />
<button id="button_2" onClick={() => { this.search(document.getElementById("search_box").value); }}>검색</button>
</div>
<div id="message">{feed.map(entry => (
<div sender={entry.sender}>
{entry.text}
<button sender={entry.sender} onClick={() => {this.delete(entry.key);}}>X</button>
</div>
))}
</div>
<div id="message-form">
<textarea type="text" id="message_box" value={this.state.input} onChange={this._handleText} placeholder="궁금한점?"/>
<button id="button_2" onClick={() => {this.inputText(this.state.input);}}>입력</button>
<button id="button_2" onClick={() => {this.note(this.state.input);}}>메모</button>
</div>
</div>
</div>
</div>
</main>
<Modal open={this.state.open} width="60%" height="80%" effect="fadeInUp" onClose={this.onCloseModal}>
<div>
<h2>
<button id="open" onClick={() => this.getOpenSourceList()}>오픈소스 사용정보</button>
</h2>
<div id="opensrc"></div>
<button id="close" onClick={() => this.onCloseModal()}>닫기</button>
</div>
</Modal>
</div>
);
}
}
const mapStateToProps = state => ({
feed: state
});
export default connect(
mapStateToProps,
{
sendMessage
}
)(App); | <header className="Header">
<div className="In_header">
<div className="In_in_header">
<h1>Kookmini</h1> |
MatrixFactorization.py | from lib.utils import top_k
from TraditionalRecommenderSystems.MatrixFactorization.Models import BaseMF
import numpy as np
import pandas as pd
import torch
from torch import nn
import torch.utils.data as data
from tqdm import tqdm
class MatrixFactorization(object):
def __init__(self, user_item_pairs, user_list, item_list, nb_factor=40, drop_rate=0.5, batch_size=32, lr=1e-1,
optimizer=torch.optim.Adam, loss_func=nn.MSELoss(reduction='mean'), sparse=False,
weight_decay=0., device='cuda', pro_process=None):
"""
Matrix Factorization based on Pytorch.
:param user_item_pairs: list. [(user, item, rating)].
:param user_list: list. The list of all the users (with no repeat).
:param item_list: list. The list of all the items (with no repeat).
:param nb_factor: int. The number of factors.
:param drop_rate: float 0~1. Drop rate of the dropout layer.
:param batch_size: int. Batch size of training
:param lr: float. Learning rate.
:param optimizer: torch.optim. Optimizer utilized to train the model.
:param loss_func: torch.nn.*Loss. Loss function of training.
:param sparse: boolean. The gradient requires to be sparse or not.
:param weight_decay: float. L2 regularization.
:param device: 'cpu' or 'cuda'.
:param pro_process: nn.Module.
"""
self.user_item_pairs = pd.DataFrame(user_item_pairs)
# build index-user, index-item
self.index_2_user = np.array(user_list)
self.index_2_item = np.array(item_list)
assert len(self.index_2_user) == len(set(self.index_2_user))
assert len(self.index_2_item) == len(set(self.index_2_item))
self.user_2_index = {self.index_2_user[i]: i for i in range(len(self.index_2_user))}
self.item_2_index = {self.index_2_item[i]: i for i in range(len(self.index_2_item))}
self.nb_user, self.nb_item = len(user_list), len(item_list)
# prepare training loader
train_user_indices = torch.from_numpy(self.users_to_indices(self.user_item_pairs[0].values)).long()
train_item_indices = torch.from_numpy(self.items_to_indices(self.user_item_pairs[1].values)).long()
train_ratings = torch.from_numpy(self.user_item_pairs[2].values.reshape(-1, 1)).float()
self.train_data_loader = data.DataLoader(data.TensorDataset(train_user_indices, train_item_indices,
train_ratings), batch_size=batch_size, shuffle=True)
# build model
self.nb_factor = nb_factor
self.lr = lr
self.batch_size = batch_size
self.loss_func = loss_func
self.weight_decay = weight_decay
self.device = device
self.sparse = sparse
self.process = pro_process
self.model = BaseMF(self.nb_user, self.nb_item, nb_factor, drop_rate, sparse, pro_process=self.process).to(device)
self.optimizer = optimizer(self.model.parameters(), lr=lr, weight_decay=weight_decay)
# build history rating matrix
self.pred_rating_matrix = None
self.history_rating_matrix = None
self.update_history_rating_matrix()
def train(self, epochs, test_data=None, test_epoch_step=1):
"""
Train the model.
:param epochs: int. The epochs of training.
:param test_data: [(user, item, rating)]. None if no validation is applied.
:param test_epoch_step: int. The step of validation.
:return: (list of training loss, list of test loss) if validation is applied, else only the list of training loss.
"""
hist_train_loss, hist_test_loss = [], []
if test_data is not None:
test_data = pd.DataFrame(test_data)
for epoch in range(epochs):
print('Epoch-{}/{}:'.format(epoch+1, epochs))
self.model.train()
train_loss = self.train_epoch()
hist_train_loss.append(train_loss)
if (test_data is not None) and (epoch % test_epoch_step == 0):
self.model.eval()
test_loss = self.eval(test_data.iloc[:, [0, 1]].values, ground_truth=test_data[2].values)
hist_test_loss.append(test_loss)
print('training loss = {}, test loss = {}'.format(train_loss, test_loss))
else:
print('training loss = {}'.format(train_loss))
self.update_pred_rating_matrix()
return hist_train_loss, hist_test_loss
def train_epoch(self):
"""
:return: training loss.
"""
self.model.train()
epoch_loss = 0.
for id_user, id_item, id_rating in tqdm(self.train_data_loader):
batch_loss = self.train_on_batch(id_user, id_item, id_rating)
epoch_loss += batch_loss
epoch_loss /= len(self.train_data_loader)
return epoch_loss
def train_on_batch(self, user_indices, item_indices, ratings):
users, items, ratings = user_indices.to(self.device), item_indices.to(self.device), ratings.to(self.device)
self.optimizer.zero_grad()
outputs = self.model(users, items)
loss = self.loss_func(outputs, ratings)
loss.backward()
self.optimizer.step()
return loss.item()
def eval(self, user_item_pairs, ground_truth, batch_size=100):
"""
Predict the ratings of the pairs of (user, item).
:param user_item_pairs: list of (user, item).
:param ground_truth: the ground truth rating.
:param batch_size: batch_size of predicting.
:return: ratings. size=[nb_pairs]
"""
self.model.eval()
outputs = self.predict(user_item_pairs, batch_size=batch_size).ravel()
loss = np.mean((outputs-ground_truth.ravel())**2)
return loss
def predict(self, user_item_pairs, batch_size=100):
"""
Predict the ratings of the pairs of (user, item).
:param user_item_pairs: list of (user, item)
:param batch_size: batch_size of predicting.
:return: ratings. size=[nb_pairs]
"""
pairs = pd.DataFrame(user_item_pairs)
user_indices = self.users_to_indices(pairs[0].values)
item_indices = self.items_to_indices(pairs[1].values)
self.model.eval()
outputs = []
with torch.no_grad():
start_id = 0
end_id = min(batch_size, len(pairs))
while start_id < len(pairs):
outputs.append(self.predict_on_batch(user_indices[start_id:end_id], item_indices[start_id:end_id]))
start_id += batch_size
end_id = min(start_id+batch_size, len(pairs))
return np.concatenate(outputs, axis=0)
def predict_on_batch(self, user_indices, item_indices):
users = torch.from_numpy(user_indices).long().to(self.device)
items = torch.from_numpy(item_indices).long().to(self.device)
outputs = self.model(users, items)
return outputs.data.cpu().numpy()
def update_history_rating_matrix(self):
"""
Update history rating matrix.
:return: self.
"""
self.history_rating_matrix = pd.DataFrame(index=self.index_2_user, columns=self.index_2_item)
for i, j, k in self.user_item_pairs.values:
if i and j and k:
self.history_rating_matrix[j][i] = k
return self
def update_pred_rating_matrix(self):
"""
Update prediction rating matrix.
:return: self.
"""
pred_matrix = self.model.get_rating_matrix().data.cpu().numpy()
self.pred_rating_matrix = np.where(self.history_rating_matrix.isna(), pred_matrix, np.nan)
return self
# def get_single_rating(self, i, j):
# return self.pred_rating_matrix[i][j] if not np.isnan(self.pred_rating_matrix[i][j])\
# else self.history_rating_matrix.values[i][j]
#
# def predict_ratings_with_matrix(self, user_item_pairs):
# """
# Predict the ratings of the pairs of (user, item).
# :param user_item_pairs: list of (user, item)
# :return: ratings. size=[nb_pairs]
# """
# pairs = pd.DataFrame(user_item_pairs)
# users = self.users_to_indices(pairs[0])
# items = self.items_to_indices(pairs[1])
# return np.array([self.get_single_rating(users[i], items[i]) for i in range(len(user_item_pairs))])
def predict_ratings(self, user_item_pairs):
"""
Predict the ratings of the pairs of (user, item).
:param user_item_pairs: list of (user, item)
:return: ratings. size=[nb_pairs]
"""
return self.predict(user_item_pairs).ravel()
def recommend(self, users, nb_recommendation):
"""
return the recommendations and their corresponding ratings.
:param users: array of users
:param nb_recommendation: The number of items to be recommended.
:return: Indices of recommended items and their corresponding scores.
"""
user_indices = self.users_to_indices(users)
id_recommend, rating_recommend = top_k(np.where(np.isnan(self.pred_rating_matrix[user_indices, :]),
-np.inf, self.pred_rating_matrix[user_indices, :]),
k=nb_recommendation, axis=-1, reverse=True, sort=True)
return id_recommend, rating_recommend
def users_to_indices(self, users):
return np.array([self.user_2_index[user] for user in users]).ravel()
def | (self, indices):
return self.index_2_user[np.array(indices).ravel()]
def items_to_indices(self, items):
return np.array([self.item_2_index[item] for item in items]).ravel()
def indices_to_items(self, indices):
return self.index_2_item[np.array(indices).ravel()]
| indices_to_users |
test_utils.rs | use crate::tests::fakes::{
create_fake_dns_client, create_fake_on_winch, get_interfaces, get_open_sockets, KeyboardEvents,
NetworkFrames, TerminalEvent, TestBackend,
};
use std::iter;
use crate::network::dns::Client;
use crate::{Opt, OsInputOutput, RenderOpts};
use ::crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers};
use packet_builder::*;
use pnet::datalink::DataLinkReceiver;
use std::collections::HashMap;
use std::io::Write;
use std::sync::{Arc, Mutex};
use packet_builder::payload::PayloadData;
use pnet::packet::Packet;
use pnet_base::MacAddr;
pub fn sleep_and_quit_events(sleep_num: usize) -> Box<KeyboardEvents> {
let mut events: Vec<Option<Event>> = iter::repeat(None).take(sleep_num).collect();
events.push(Some(Event::Key(KeyEvent {
modifiers: KeyModifiers::CONTROL,
code: KeyCode::Char('c'),
})));
Box::new(KeyboardEvents::new(events))
}
pub fn build_tcp_packet(
source_ip: &str,
destination_ip: &str,
source_port: u16,
destination_port: u16,
payload: &'static [u8],
) -> Vec<u8> |
pub fn sample_frames() -> Vec<Box<dyn DataLinkReceiver>> {
vec![NetworkFrames::new(vec![
Some(build_tcp_packet(
"10.0.0.2",
"1.1.1.1",
443,
12345,
b"I am a fake tcp upload packet",
)),
Some(build_tcp_packet(
"1.1.1.1",
"10.0.0.2",
12345,
443,
b"I am a fake tcp download packet",
)),
Some(build_tcp_packet(
"10.0.0.2",
"1.1.1.1",
54321,
53,
b"I am a fake DNS query packet",
)),
]) as Box<dyn DataLinkReceiver>]
}
pub fn os_input_output(
network_frames: Vec<Box<dyn DataLinkReceiver>>,
sleep_num: usize,
) -> OsInputOutput {
os_input_output_factory(
network_frames,
None,
create_fake_dns_client(HashMap::new()),
sleep_and_quit_events(sleep_num),
)
}
pub fn os_input_output_stdout(
network_frames: Vec<Box<dyn DataLinkReceiver>>,
sleep_num: usize,
stdout: Option<Arc<Mutex<Vec<u8>>>>,
) -> OsInputOutput {
os_input_output_factory(
network_frames,
stdout,
create_fake_dns_client(HashMap::new()),
sleep_and_quit_events(sleep_num),
)
}
pub fn os_input_output_dns(
network_frames: Vec<Box<dyn DataLinkReceiver>>,
sleep_num: usize,
stdout: Option<Arc<Mutex<Vec<u8>>>>,
dns_client: Option<Client>,
) -> OsInputOutput {
os_input_output_factory(
network_frames,
stdout,
dns_client,
sleep_and_quit_events(sleep_num),
)
}
pub fn os_input_output_factory(
network_frames: Vec<Box<dyn DataLinkReceiver>>,
stdout: Option<Arc<Mutex<Vec<u8>>>>,
dns_client: Option<Client>,
keyboard_events: Box<dyn Iterator<Item = Event> + Send>,
) -> OsInputOutput {
let on_winch = create_fake_on_winch(false);
let cleanup = Box::new(|| {});
let write_to_stdout: Box<dyn FnMut(String) + Send> = match stdout {
Some(stdout) => Box::new({
move |output: String| {
let mut stdout = stdout.lock().unwrap();
writeln!(&mut stdout, "{}", output).unwrap();
}
}),
None => Box::new(move |_output: String| {}),
};
OsInputOutput {
network_interfaces: get_interfaces(),
network_frames,
get_open_sockets,
keyboard_events,
dns_client,
on_winch,
cleanup,
write_to_stdout,
}
}
pub fn opts_raw() -> Opt {
opts_factory(true)
}
pub fn opts_ui() -> Opt {
opts_factory(false)
}
fn opts_factory(raw: bool) -> Opt {
Opt {
interface: Some(String::from("interface_name")),
raw,
no_resolve: false,
show_dns: false,
render_opts: RenderOpts {
addresses: false,
connections: false,
processes: false,
total_utilization: false,
},
}
}
type BackendWithStreams = (
Arc<Mutex<Vec<TerminalEvent>>>,
Arc<Mutex<Vec<String>>>,
TestBackend,
);
pub fn test_backend_factory(w: u16, h: u16) -> BackendWithStreams {
let terminal_events: Arc<Mutex<Vec<TerminalEvent>>> = Arc::new(Mutex::new(Vec::new()));
let terminal_draw_events: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
let backend = TestBackend::new(
terminal_events.clone(),
terminal_draw_events.clone(),
Arc::new(Mutex::new(w)),
Arc::new(Mutex::new(h)),
);
(terminal_events, terminal_draw_events, backend)
}
| {
let mut pkt_buf = [0u8; 1500];
let pkt = packet_builder!(
pkt_buf,
ether({set_destination => MacAddr(0,0,0,0,0,0), set_source => MacAddr(0,0,0,0,0,0)}) /
ipv4({set_source => ipv4addr!(source_ip), set_destination => ipv4addr!(destination_ip) }) /
tcp({set_source => source_port, set_destination => destination_port }) /
payload(payload)
);
pkt.packet().to_vec()
} |
apply_cluster.go | /*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cloudup
import (
"bytes"
"context"
"fmt"
"net"
"net/url"
"os"
"path"
"strconv"
"strings"
"github.com/blang/semver/v4"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog/v2"
kopsbase "k8s.io/kops"
"k8s.io/kops/pkg/acls"
"k8s.io/kops/pkg/apis/kops"
"k8s.io/kops/pkg/apis/kops/registry"
"k8s.io/kops/pkg/apis/kops/util"
"k8s.io/kops/pkg/apis/kops/validation"
"k8s.io/kops/pkg/apis/nodeup"
"k8s.io/kops/pkg/assets"
"k8s.io/kops/pkg/client/simple"
"k8s.io/kops/pkg/client/simple/vfsclientset"
"k8s.io/kops/pkg/dns"
"k8s.io/kops/pkg/featureflag"
"k8s.io/kops/pkg/model"
"k8s.io/kops/pkg/model/alimodel"
"k8s.io/kops/pkg/model/awsmodel"
"k8s.io/kops/pkg/model/azuremodel"
"k8s.io/kops/pkg/model/components"
"k8s.io/kops/pkg/model/components/etcdmanager"
"k8s.io/kops/pkg/model/components/kubeapiserver"
"k8s.io/kops/pkg/model/domodel"
"k8s.io/kops/pkg/model/gcemodel"
"k8s.io/kops/pkg/model/iam"
"k8s.io/kops/pkg/model/openstackmodel"
"k8s.io/kops/pkg/resources/digitalocean"
"k8s.io/kops/pkg/templates"
"k8s.io/kops/pkg/wellknownports"
"k8s.io/kops/upup/models"
"k8s.io/kops/upup/pkg/fi"
"k8s.io/kops/upup/pkg/fi/cloudup/aliup"
"k8s.io/kops/upup/pkg/fi/cloudup/awsup"
"k8s.io/kops/upup/pkg/fi/cloudup/azure"
"k8s.io/kops/upup/pkg/fi/cloudup/bootstrapchannelbuilder"
"k8s.io/kops/upup/pkg/fi/cloudup/cloudformation"
"k8s.io/kops/upup/pkg/fi/cloudup/do"
"k8s.io/kops/upup/pkg/fi/cloudup/gce"
"k8s.io/kops/upup/pkg/fi/cloudup/openstack"
"k8s.io/kops/upup/pkg/fi/cloudup/terraform"
"k8s.io/kops/upup/pkg/fi/cloudup/terraformWriter"
"k8s.io/kops/util/pkg/architectures"
"k8s.io/kops/util/pkg/hashing"
"k8s.io/kops/util/pkg/mirrors"
"k8s.io/kops/util/pkg/vfs"
)
const (
starline = "*********************************************************************************"
)
var (
// AlphaAllowGCE is a feature flag that gates GCE support while it is alpha
AlphaAllowGCE = featureflag.New("AlphaAllowGCE", featureflag.Bool(false))
// AlphaAllowALI is a feature flag that gates aliyun support while it is alpha
AlphaAllowALI = featureflag.New("AlphaAllowALI", featureflag.Bool(false))
// OldestSupportedKubernetesVersion is the oldest kubernetes version that is supported in Kops
OldestSupportedKubernetesVersion = "1.17.0"
// OldestRecommendedKubernetesVersion is the oldest kubernetes version that is not deprecated in Kops
OldestRecommendedKubernetesVersion = "1.18.0"
)
type ApplyClusterCmd struct {
Cloud fi.Cloud
Cluster *kops.Cluster
InstanceGroups []*kops.InstanceGroup
// NodeUpAssets are the assets for downloading nodeup
NodeUpAssets map[architectures.Architecture]*mirrors.MirroredAsset
// TargetName specifies how we are operating e.g. direct to GCE, or AWS, or dry-run, or terraform
TargetName string
// Target is the fi.Target we will operate against
Target fi.Target
// OutDir is a local directory in which we place output, can cache files etc
OutDir string
// Assets is a list of sources for files (primarily when not using everything containerized)
// Formats:
// raw url: http://... or https://...
// url with hash: <hex>@http://... or <hex>@https://...
Assets map[architectures.Architecture][]*mirrors.MirroredAsset
Clientset simple.Clientset
// DryRun is true if this is only a dry run
DryRun bool
// AllowKopsDowngrade permits applying with a kops version older than what was last used to apply to the cluster.
AllowKopsDowngrade bool
// RunTasksOptions defines parameters for task execution, e.g. retry interval
RunTasksOptions *fi.RunTasksOptions
// The channel we are using
channel *kops.Channel
// Phase can be set to a Phase to run the specific subset of tasks, if we don't want to run everything
Phase Phase
// LifecycleOverrides is passed in to override the lifecycle for one of more tasks.
// The key value is the task name such as InternetGateway and the value is the fi.Lifecycle
// that is re-mapped.
LifecycleOverrides map[string]fi.Lifecycle
// TaskMap is the map of tasks that we built (output)
TaskMap map[string]fi.Task
}
func (c *ApplyClusterCmd) Run(ctx context.Context) error {
if c.InstanceGroups == nil {
list, err := c.Clientset.InstanceGroupsFor(c.Cluster).List(ctx, metav1.ListOptions{})
if err != nil {
return err
}
var instanceGroups []*kops.InstanceGroup
for i := range list.Items {
instanceGroups = append(instanceGroups, &list.Items[i])
}
c.InstanceGroups = instanceGroups
}
for _, ig := range c.InstanceGroups {
// Try to guess the path for additional third party volume plugins in Flatcar
image := strings.ToLower(ig.Spec.Image)
if strings.Contains(image, "flatcar") {
if c.Cluster.Spec.Kubelet == nil {
c.Cluster.Spec.Kubelet = &kops.KubeletConfigSpec{}
}
if c.Cluster.Spec.Kubelet.VolumePluginDirectory == "" {
c.Cluster.Spec.Kubelet.VolumePluginDirectory = "/var/lib/kubelet/volumeplugins/"
}
}
}
channel, err := ChannelForCluster(c.Cluster)
if err != nil {
klog.Warningf("%v", err)
}
c.channel = channel
stageAssetsLifecycle := fi.LifecycleSync
securityLifecycle := fi.LifecycleSync
networkLifecycle := fi.LifecycleSync
clusterLifecycle := fi.LifecycleSync
switch c.Phase {
case Phase(""):
// Everything ... the default
// until we implement finding assets we need to Ignore them
stageAssetsLifecycle = fi.LifecycleIgnore
case PhaseStageAssets:
networkLifecycle = fi.LifecycleIgnore
securityLifecycle = fi.LifecycleIgnore
clusterLifecycle = fi.LifecycleIgnore
case PhaseNetwork:
stageAssetsLifecycle = fi.LifecycleIgnore
securityLifecycle = fi.LifecycleIgnore
clusterLifecycle = fi.LifecycleIgnore
case PhaseSecurity:
stageAssetsLifecycle = fi.LifecycleIgnore
networkLifecycle = fi.LifecycleExistsAndWarnIfChanges
clusterLifecycle = fi.LifecycleIgnore
case PhaseCluster:
if c.TargetName == TargetDryRun {
stageAssetsLifecycle = fi.LifecycleIgnore
securityLifecycle = fi.LifecycleExistsAndWarnIfChanges
networkLifecycle = fi.LifecycleExistsAndWarnIfChanges
} else {
stageAssetsLifecycle = fi.LifecycleIgnore
networkLifecycle = fi.LifecycleExistsAndValidates
securityLifecycle = fi.LifecycleExistsAndValidates
}
default:
return fmt.Errorf("unknown phase %q", c.Phase)
}
// This is kinda a hack. Need to move phases out of fi. If we use Phase here we introduce a circular
// go dependency.
phase := string(c.Phase)
assetBuilder := assets.NewAssetBuilder(c.Cluster, phase)
err = c.upgradeSpecs(assetBuilder)
if err != nil {
return err
}
err = c.validateKopsVersion()
if err != nil {
return err
}
err = c.validateKubernetesVersion()
if err != nil {
return err
}
cluster := c.Cluster
configBase, err := vfs.Context.BuildVfsPath(cluster.Spec.ConfigBase)
if err != nil {
return fmt.Errorf("error parsing config base %q: %v", cluster.Spec.ConfigBase, err)
}
if !c.AllowKopsDowngrade {
kopsVersionUpdatedBytes, err := configBase.Join(registry.PathKopsVersionUpdated).ReadFile()
if err == nil {
kopsVersionUpdated := strings.TrimSpace(string(kopsVersionUpdatedBytes))
version, err := semver.Parse(kopsVersionUpdated)
if err != nil {
return fmt.Errorf("error parsing last kops version updated: %v", err)
}
if version.GT(semver.MustParse(kopsbase.Version)) {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
fmt.Printf("The cluster was last updated by kops version %s\n", kopsVersionUpdated)
fmt.Printf("To permit updating by the older version %s, run with the --allow-kops-downgrade flag\n", kopsbase.Version)
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
return fmt.Errorf("kops version older than last used to update the cluster")
}
} else if err != os.ErrNotExist {
return fmt.Errorf("error reading last kops version used to update: %v", err)
}
}
cloud := c.Cloud
err = validation.DeepValidate(c.Cluster, c.InstanceGroups, true, cloud)
if err != nil {
return err
}
if cluster.Spec.KubernetesVersion == "" {
return fmt.Errorf("KubernetesVersion not set")
}
if cluster.Spec.DNSZone == "" && !dns.IsGossipHostname(cluster.ObjectMeta.Name) {
return fmt.Errorf("DNSZone not set")
}
l := &Loader{}
l.Init()
keyStore, err := c.Clientset.KeyStore(cluster)
if err != nil {
return err
}
sshCredentialStore, err := c.Clientset.SSHCredentialStore(cluster)
if err != nil {
return err
}
secretStore, err := c.Clientset.SecretStore(cluster)
if err != nil {
return err
}
addonsClient := c.Clientset.AddonsFor(cluster)
addons, err := addonsClient.List()
if err != nil {
return fmt.Errorf("error fetching addons: %v", err)
}
// Normalize k8s version
versionWithoutV := strings.TrimSpace(cluster.Spec.KubernetesVersion)
versionWithoutV = strings.TrimPrefix(versionWithoutV, "v")
if cluster.Spec.KubernetesVersion != versionWithoutV {
klog.Warningf("Normalizing kubernetes version: %q -> %q", cluster.Spec.KubernetesVersion, versionWithoutV)
cluster.Spec.KubernetesVersion = versionWithoutV
}
// check if we should recommend turning off anonymousAuth
{
// we do a check here because setting modifying the kubelet object messes with the output
warn := false
if cluster.Spec.Kubelet == nil {
warn = true
} else if cluster.Spec.Kubelet.AnonymousAuth == nil {
warn = true
}
if warn {
fmt.Println("")
fmt.Printf("%s\n", starline)
fmt.Println("")
fmt.Println("Kubelet anonymousAuth is currently turned on. This allows RBAC escalation and remote code execution possibilities.")
fmt.Println("It is highly recommended you turn it off by setting 'spec.kubelet.anonymousAuth' to 'false' via 'kops edit cluster'")
fmt.Println("")
fmt.Println("See https://kops.sigs.k8s.io/security/#kubelet-api")
fmt.Println("")
fmt.Printf("%s\n", starline)
fmt.Println("")
}
}
if fi.BoolValue(c.Cluster.Spec.EncryptionConfig) {
secret, err := secretStore.FindSecret("encryptionconfig")
if err != nil {
return fmt.Errorf("could not load encryptionconfig secret: %v", err)
}
if secret == nil {
fmt.Println("")
fmt.Println("You have encryptionConfig enabled, but no encryptionconfig secret has been set.")
fmt.Println("See `kops create secret encryptionconfig -h` and https://kubernetes.io/docs/tasks/administer-cluster/encrypt-data/")
return fmt.Errorf("could not find encryptionconfig secret")
}
}
ciliumSpec := c.Cluster.Spec.Networking.Cilium
if ciliumSpec != nil && ciliumSpec.EnableEncryption {
secret, err := secretStore.FindSecret("ciliumpassword")
if err != nil {
return fmt.Errorf("could not load the ciliumpassword secret: %w", err)
}
if secret == nil {
fmt.Println("")
fmt.Println("You have cilium encryption enabled, but no ciliumpassword secret has been set.")
fmt.Println("See `kops create secret ciliumpassword -h`")
return fmt.Errorf("could not find ciliumpassword secret")
}
}
if err := c.addFileAssets(assetBuilder); err != nil {
return err
}
// Only setup transfer of kops assets if using a FileRepository
if c.Cluster.Spec.Assets != nil && c.Cluster.Spec.Assets.FileRepository != nil {
if err := SetKopsAssetsLocations(assetBuilder); err != nil {
return err
}
}
checkExisting := true
project := ""
var sshPublicKeys [][]byte
{
keys, err := sshCredentialStore.FindSSHPublicKeys(fi.SecretNameSSHPrimary)
if err != nil {
return fmt.Errorf("error retrieving SSH public key %q: %v", fi.SecretNameSSHPrimary, err)
}
for _, k := range keys {
sshPublicKeys = append(sshPublicKeys, []byte(k.Spec.PublicKey))
}
}
modelContext := &model.KopsModelContext{
IAMModelContext: iam.IAMModelContext{Cluster: cluster},
InstanceGroups: c.InstanceGroups,
}
switch kops.CloudProviderID(cluster.Spec.CloudProvider) {
case kops.CloudProviderGCE:
{
gceCloud := cloud.(gce.GCECloud)
project = gceCloud.Project()
if !AlphaAllowGCE.Enabled() {
return fmt.Errorf("GCE support is currently alpha, and is feature-gated. export KOPS_FEATURE_FLAGS=AlphaAllowGCE")
}
}
case kops.CloudProviderDO:
{
if len(sshPublicKeys) == 0 && (c.Cluster.Spec.SSHKeyName == nil || *c.Cluster.Spec.SSHKeyName == "") {
return fmt.Errorf("SSH public key must be specified when running with DigitalOcean (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
}
case kops.CloudProviderAWS:
{
awsCloud := cloud.(awsup.AWSCloud)
accountID, partition, err := awsCloud.AccountInfo()
if err != nil {
return err
}
modelContext.AWSAccountID = accountID
modelContext.AWSPartition = partition
if len(sshPublicKeys) == 0 && c.Cluster.Spec.SSHKeyName == nil {
return fmt.Errorf("SSH public key must be specified when running with AWS (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
if len(sshPublicKeys) > 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with AWS; please delete a key using `kops delete secret`")
}
}
case kops.CloudProviderALI:
{
fmt.Println("")
fmt.Println("aliyun support has been deprecated due to lack of maintainers. It may be removed in a future version of kOps.")
fmt.Println("")
if !AlphaAllowALI.Enabled() {
return fmt.Errorf("aliyun support is currently alpha, and is feature-gated. export KOPS_FEATURE_FLAGS=AlphaAllowALI")
}
if len(sshPublicKeys) == 0 {
return fmt.Errorf("SSH public key must be specified when running with ALICloud (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
if len(sshPublicKeys) != 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with ALICloud; please delete a key using `kops delete secret`")
}
}
case kops.CloudProviderAzure:
{
if !featureflag.Azure.Enabled() {
return fmt.Errorf("azure support is currently alpha, and is feature-gated. Please export KOPS_FEATURE_FLAGS=Azure")
}
if len(sshPublicKeys) == 0 {
return fmt.Errorf("SSH public key must be specified when running with AzureCloud (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
if len(sshPublicKeys) != 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with AzureCloud; please delete a key using `kops delete secret`")
}
}
case kops.CloudProviderOpenstack:
{
if len(sshPublicKeys) == 0 {
return fmt.Errorf("SSH public key must be specified when running with Openstack (create with `kops create secret --name %s sshpublickey admin -i ~/.ssh/id_rsa.pub`)", cluster.ObjectMeta.Name)
}
if len(sshPublicKeys) != 1 {
return fmt.Errorf("exactly one 'admin' SSH public key can be specified when running with Openstack; please delete a key using `kops delete secret`")
}
}
default:
return fmt.Errorf("unknown CloudProvider %q", cluster.Spec.CloudProvider)
}
modelContext.SSHPublicKeys = sshPublicKeys
modelContext.Region = cloud.Region()
if dns.IsGossipHostname(cluster.ObjectMeta.Name) {
klog.Infof("Gossip DNS: skipping DNS validation")
} else {
err = validateDNS(cluster, cloud)
if err != nil {
return err
}
}
tf := &TemplateFunctions{
KopsModelContext: *modelContext,
cloud: cloud,
}
configBuilder, err := newNodeUpConfigBuilder(cluster, assetBuilder, c.Assets)
if err != nil {
return err
}
bootstrapScriptBuilder := &model.BootstrapScriptBuilder{
NodeUpConfigBuilder: configBuilder,
NodeUpAssets: c.NodeUpAssets,
}
{
templates, err := templates.LoadTemplates(cluster, models.NewAssetPath("cloudup/resources"))
if err != nil {
return fmt.Errorf("error loading templates: %v", err)
}
err = tf.AddTo(templates.TemplateFunctions, secretStore)
if err != nil {
return err
}
bcb := bootstrapchannelbuilder.NewBootstrapChannelBuilder(
modelContext,
&clusterLifecycle,
assetBuilder,
templates,
addons,
)
l.Builders = append(l.Builders,
bcb,
&model.PKIModelBuilder{
KopsModelContext: modelContext,
Lifecycle: &clusterLifecycle,
},
&model.IssuerDiscoveryModelBuilder{
KopsModelContext: modelContext,
Lifecycle: &clusterLifecycle,
Cluster: cluster,
},
&kubeapiserver.KubeApiserverBuilder{
AssetBuilder: assetBuilder,
KopsModelContext: modelContext,
Lifecycle: &clusterLifecycle,
},
&etcdmanager.EtcdManagerBuilder{
AssetBuilder: assetBuilder,
KopsModelContext: modelContext,
Lifecycle: &clusterLifecycle,
},
&model.MasterVolumeBuilder{KopsModelContext: modelContext, Lifecycle: &clusterLifecycle},
)
switch kops.CloudProviderID(cluster.Spec.CloudProvider) {
case kops.CloudProviderAWS:
awsModelContext := &awsmodel.AWSModelContext{
KopsModelContext: modelContext,
}
l.Builders = append(l.Builders,
&awsmodel.APILoadBalancerBuilder{AWSModelContext: awsModelContext, Lifecycle: &clusterLifecycle, SecurityLifecycle: &securityLifecycle},
&awsmodel.BastionModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &clusterLifecycle, SecurityLifecycle: &securityLifecycle},
&awsmodel.DNSModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &clusterLifecycle},
&awsmodel.ExternalAccessModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &securityLifecycle},
&awsmodel.FirewallModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &securityLifecycle},
&awsmodel.SSHKeyModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &securityLifecycle},
&awsmodel.NetworkModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &networkLifecycle},
&awsmodel.IAMModelBuilder{AWSModelContext: awsModelContext, Lifecycle: &securityLifecycle, Cluster: cluster},
&awsmodel.OIDCProviderBuilder{AWSModelContext: awsModelContext, Lifecycle: &securityLifecycle, KeyStore: keyStore},
)
awsModelBuilder := &awsmodel.AutoscalingGroupModelBuilder{
AWSModelContext: awsModelContext,
BootstrapScriptBuilder: bootstrapScriptBuilder,
Lifecycle: &clusterLifecycle,
SecurityLifecycle: &securityLifecycle,
Cluster: cluster,
}
if featureflag.Spotinst.Enabled() {
l.Builders = append(l.Builders, &awsmodel.SpotInstanceGroupModelBuilder{
AWSModelContext: awsModelContext,
BootstrapScriptBuilder: bootstrapScriptBuilder,
Lifecycle: &clusterLifecycle,
SecurityLifecycle: &securityLifecycle,
})
if featureflag.SpotinstHybrid.Enabled() {
l.Builders = append(l.Builders, awsModelBuilder)
}
} else {
l.Builders = append(l.Builders, awsModelBuilder)
}
nth := c.Cluster.Spec.NodeTerminationHandler
if nth != nil && fi.BoolValue(nth.Enabled) && fi.BoolValue(nth.EnableSQSTerminationDraining) {
l.Builders = append(l.Builders, &awsmodel.NodeTerminationHandlerBuilder{
AWSModelContext: awsModelContext,
Lifecycle: &clusterLifecycle,
})
}
case kops.CloudProviderDO:
doModelContext := &domodel.DOModelContext{
KopsModelContext: modelContext,
}
l.Builders = append(l.Builders,
&domodel.APILoadBalancerModelBuilder{DOModelContext: doModelContext, Lifecycle: &securityLifecycle},
&domodel.DropletBuilder{DOModelContext: doModelContext, BootstrapScriptBuilder: bootstrapScriptBuilder, Lifecycle: &clusterLifecycle},
)
case kops.CloudProviderGCE:
gceModelContext := &gcemodel.GCEModelContext{
KopsModelContext: modelContext,
}
storageACLLifecycle := securityLifecycle
if storageACLLifecycle != fi.LifecycleIgnore {
// This is a best-effort permissions fix
storageACLLifecycle = fi.LifecycleWarnIfInsufficientAccess
}
l.Builders = append(l.Builders,
&gcemodel.APILoadBalancerBuilder{GCEModelContext: gceModelContext, Lifecycle: &securityLifecycle},
&gcemodel.ExternalAccessModelBuilder{GCEModelContext: gceModelContext, Lifecycle: &securityLifecycle},
&gcemodel.FirewallModelBuilder{GCEModelContext: gceModelContext, Lifecycle: &securityLifecycle},
&gcemodel.NetworkModelBuilder{GCEModelContext: gceModelContext, Lifecycle: &networkLifecycle},
&gcemodel.StorageAclBuilder{GCEModelContext: gceModelContext, Cloud: cloud.(gce.GCECloud), Lifecycle: &storageACLLifecycle},
&gcemodel.AutoscalingGroupModelBuilder{GCEModelContext: gceModelContext, BootstrapScriptBuilder: bootstrapScriptBuilder, Lifecycle: &clusterLifecycle},
)
case kops.CloudProviderALI:
aliModelContext := &alimodel.ALIModelContext{
KopsModelContext: modelContext,
}
l.Builders = append(l.Builders,
&alimodel.APILoadBalancerModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.NetworkModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.RAMModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.SSHKeyModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.FirewallModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.ExternalAccessModelBuilder{ALIModelContext: aliModelContext, Lifecycle: &clusterLifecycle},
&alimodel.ScalingGroupModelBuilder{ALIModelContext: aliModelContext, BootstrapScriptBuilder: bootstrapScriptBuilder, Lifecycle: &clusterLifecycle},
)
case kops.CloudProviderAzure:
azureModelContext := &azuremodel.AzureModelContext{
KopsModelContext: modelContext,
}
l.Builders = append(l.Builders,
&azuremodel.APILoadBalancerModelBuilder{AzureModelContext: azureModelContext, Lifecycle: &clusterLifecycle},
&azuremodel.NetworkModelBuilder{AzureModelContext: azureModelContext, Lifecycle: &clusterLifecycle},
&azuremodel.ResourceGroupModelBuilder{AzureModelContext: azureModelContext, Lifecycle: &clusterLifecycle},
&azuremodel.VMScaleSetModelBuilder{AzureModelContext: azureModelContext, BootstrapScriptBuilder: bootstrapScriptBuilder, Lifecycle: &clusterLifecycle},
)
case kops.CloudProviderOpenstack:
openstackModelContext := &openstackmodel.OpenstackModelContext{
KopsModelContext: modelContext,
}
l.Builders = append(l.Builders,
&openstackmodel.NetworkModelBuilder{OpenstackModelContext: openstackModelContext, Lifecycle: &networkLifecycle},
&openstackmodel.SSHKeyModelBuilder{OpenstackModelContext: openstackModelContext, Lifecycle: &securityLifecycle},
&openstackmodel.FirewallModelBuilder{OpenstackModelContext: openstackModelContext, Lifecycle: &securityLifecycle},
&openstackmodel.ServerGroupModelBuilder{OpenstackModelContext: openstackModelContext, BootstrapScriptBuilder: bootstrapScriptBuilder, Lifecycle: &clusterLifecycle},
)
default:
return fmt.Errorf("unknown cloudprovider %q", cluster.Spec.CloudProvider)
}
}
taskMap, err := l.BuildTasks(assetBuilder, &stageAssetsLifecycle, c.LifecycleOverrides)
if err != nil {
return fmt.Errorf("error building tasks: %v", err)
}
c.TaskMap = taskMap
var target fi.Target
dryRun := false
shouldPrecreateDNS := true
switch c.TargetName {
case TargetDirect:
switch kops.CloudProviderID(cluster.Spec.CloudProvider) {
case kops.CloudProviderGCE:
target = gce.NewGCEAPITarget(cloud.(gce.GCECloud))
case kops.CloudProviderAWS:
target = awsup.NewAWSAPITarget(cloud.(awsup.AWSCloud))
case kops.CloudProviderDO:
target = do.NewDOAPITarget(cloud.(*digitalocean.Cloud))
case kops.CloudProviderOpenstack:
target = openstack.NewOpenstackAPITarget(cloud.(openstack.OpenstackCloud))
case kops.CloudProviderALI:
target = aliup.NewALIAPITarget(cloud.(aliup.ALICloud))
case kops.CloudProviderAzure:
target = azure.NewAzureAPITarget(cloud.(azure.AzureCloud))
default:
return fmt.Errorf("direct configuration not supported with CloudProvider:%q", cluster.Spec.CloudProvider)
}
case TargetTerraform:
checkExisting = false
outDir := c.OutDir
tf := terraform.NewTerraformTarget(cloud, project, outDir, cluster.Spec.Target)
// We include a few "util" variables in the TF output
if err := tf.AddOutputVariable("region", terraformWriter.LiteralFromStringValue(cloud.Region())); err != nil {
return err
}
if project != "" {
if err := tf.AddOutputVariable("project", terraformWriter.LiteralFromStringValue(project)); err != nil {
return err
}
}
if err := tf.AddOutputVariable("cluster_name", terraformWriter.LiteralFromStringValue(cluster.ObjectMeta.Name)); err != nil {
return err
}
target = tf
// Can cause conflicts with terraform management
shouldPrecreateDNS = false
case TargetCloudformation:
checkExisting = false
outDir := c.OutDir
target = cloudformation.NewCloudformationTarget(cloud, project, outDir)
// Can cause conflicts with cloudformation management
shouldPrecreateDNS = false
case TargetDryRun:
target = fi.NewDryRunTarget(assetBuilder, os.Stdout)
dryRun = true
// Avoid making changes on a dry-run
shouldPrecreateDNS = false
default:
return fmt.Errorf("unsupported target type %q", c.TargetName)
}
c.Target = target
if !dryRun {
acl, err := acls.GetACL(configBase, cluster)
if err != nil {
return err
}
err = configBase.Join(registry.PathKopsVersionUpdated).WriteFile(bytes.NewReader([]byte(kopsbase.Version)), acl)
if err != nil {
return fmt.Errorf("error writing kops version: %v", err)
}
err = registry.WriteConfigDeprecated(cluster, configBase.Join(registry.PathClusterCompleted), c.Cluster)
if err != nil {
return fmt.Errorf("error writing completed cluster spec: %v", err)
}
vfsMirror := vfsclientset.NewInstanceGroupMirror(cluster, configBase)
for _, g := range c.InstanceGroups {
// TODO: We need to update the mirror (below), but do we need to update the primary?
_, err := c.Clientset.InstanceGroupsFor(c.Cluster).Update(ctx, g, metav1.UpdateOptions{})
if err != nil {
return fmt.Errorf("error writing InstanceGroup %q to registry: %v", g.ObjectMeta.Name, err)
}
// TODO: Don't write if vfsMirror == c.ClientSet
if err := vfsMirror.WriteMirror(g); err != nil {
return fmt.Errorf("error writing instance group spec to mirror: %v", err)
}
}
}
context, err := fi.NewContext(target, cluster, cloud, keyStore, secretStore, configBase, checkExisting, taskMap)
if err != nil {
return fmt.Errorf("error building context: %v", err)
}
defer context.Close()
var options fi.RunTasksOptions
if c.RunTasksOptions != nil {
options = *c.RunTasksOptions
} else {
options.InitDefaults()
}
err = context.RunTasks(options)
if err != nil {
return fmt.Errorf("error running tasks: %v", err)
}
if dns.IsGossipHostname(cluster.Name) {
shouldPrecreateDNS = false
}
if shouldPrecreateDNS {
if err := precreateDNS(ctx, cluster, cloud); err != nil {
klog.Warningf("unable to pre-create DNS records - cluster startup may be slower: %v", err)
}
}
err = target.Finish(taskMap) //This will finish the apply, and print the changes
if err != nil {
return fmt.Errorf("error closing target: %v", err)
}
return nil
}
// upgradeSpecs ensures that fields are fully populated / defaulted
func (c *ApplyClusterCmd) upgradeSpecs(assetBuilder *assets.AssetBuilder) error {
fullCluster, err := PopulateClusterSpec(c.Clientset, c.Cluster, c.Cloud, assetBuilder)
if err != nil {
return err
}
c.Cluster = fullCluster
for i, g := range c.InstanceGroups {
fullGroup, err := PopulateInstanceGroupSpec(fullCluster, g, c.Cloud, c.channel)
if err != nil {
return err
}
c.InstanceGroups[i] = fullGroup
}
return nil
}
// validateKopsVersion ensures that kops meet the version requirements / recommendations in the channel
func (c *ApplyClusterCmd) validateKopsVersion() error {
kopsVersion, err := semver.ParseTolerant(kopsbase.Version)
if err != nil {
klog.Warningf("unable to parse kops version %q", kopsbase.Version)
// Not a hard-error
return nil
}
if c.channel == nil {
klog.Warning("channel unavailable, skipping version validation")
return nil
}
versionInfo := kops.FindKopsVersionSpec(c.channel.Spec.KopsVersions, kopsVersion)
if versionInfo == nil {
klog.Warningf("unable to find version information for kops version %q in channel", kopsVersion)
// Not a hard-error
return nil
}
recommended, err := versionInfo.FindRecommendedUpgrade(kopsVersion)
if err != nil {
klog.Warningf("unable to parse version recommendation for kops version %q in channel", kopsVersion)
}
required, err := versionInfo.IsUpgradeRequired(kopsVersion)
if err != nil {
klog.Warningf("unable to parse version requirement for kops version %q in channel", kopsVersion)
}
if recommended != nil && !required {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
fmt.Printf("A new kops version is available: %s", recommended)
fmt.Printf("\n")
fmt.Printf("Upgrading is recommended\n")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_kops", recommended.String()))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
} else if required {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
if recommended != nil {
fmt.Printf("a new kops version is available: %s\n", recommended)
}
fmt.Println("")
fmt.Printf("This version of kops (%s) is no longer supported; upgrading is required\n", kopsbase.Version)
fmt.Printf("(you can bypass this check by exporting KOPS_RUN_OBSOLETE_VERSION)\n")
fmt.Println("")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_kops", recommended.String()))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
}
if required {
if os.Getenv("KOPS_RUN_OBSOLETE_VERSION") == "" {
return fmt.Errorf("kops upgrade is required")
}
}
return nil
}
// validateKubernetesVersion ensures that kubernetes meet the version requirements / recommendations in the channel
func (c *ApplyClusterCmd) validateKubernetesVersion() error {
parsed, err := util.ParseKubernetesVersion(c.Cluster.Spec.KubernetesVersion)
if err != nil {
klog.Warningf("unable to parse kubernetes version %q", c.Cluster.Spec.KubernetesVersion)
// Not a hard-error
return nil
}
kopsVersion, err := semver.Parse(kopsbase.KOPS_RELEASE_VERSION)
if err != nil {
klog.Warningf("unable to parse kops version %q", kopsVersion)
} else {
tooNewVersion := kopsVersion
tooNewVersion.Minor++
tooNewVersion.Pre = nil
tooNewVersion.Build = nil
if util.IsKubernetesGTE(tooNewVersion.String(), *parsed) {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
fmt.Printf("This version of kubernetes is not yet supported; upgrading kops is required\n")
fmt.Printf("(you can bypass this check by exporting KOPS_RUN_TOO_NEW_VERSION)\n")
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
if os.Getenv("KOPS_RUN_TOO_NEW_VERSION") == "" {
return fmt.Errorf("kops upgrade is required")
}
}
}
if !util.IsKubernetesGTE(OldestSupportedKubernetesVersion, *parsed) {
fmt.Printf("This version of Kubernetes is no longer supported; upgrading Kubernetes is required\n")
fmt.Printf("\n")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_k8s", OldestRecommendedKubernetesVersion))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
return fmt.Errorf("kubernetes upgrade is required")
}
if !util.IsKubernetesGTE(OldestRecommendedKubernetesVersion, *parsed) {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
fmt.Printf("Kops support for this Kubernetes version is deprecated and will be removed in a future release.\n")
fmt.Printf("\n")
fmt.Printf("Upgrading Kubernetes is recommended\n")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_k8s", OldestRecommendedKubernetesVersion))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
}
// TODO: make util.ParseKubernetesVersion not return a pointer
kubernetesVersion := *parsed
if c.channel == nil {
klog.Warning("unable to load channel, skipping kubernetes version recommendation/requirements checks")
return nil
}
versionInfo := kops.FindKubernetesVersionSpec(c.channel.Spec.KubernetesVersions, kubernetesVersion)
if versionInfo == nil {
klog.Warningf("unable to find version information for kubernetes version %q in channel", kubernetesVersion)
// Not a hard-error
return nil
}
recommended, err := versionInfo.FindRecommendedUpgrade(kubernetesVersion)
if err != nil {
klog.Warningf("unable to parse version recommendation for kubernetes version %q in channel", kubernetesVersion)
}
required, err := versionInfo.IsUpgradeRequired(kubernetesVersion)
if err != nil {
klog.Warningf("unable to parse version requirement for kubernetes version %q in channel", kubernetesVersion)
}
if recommended != nil && !required {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
fmt.Printf("A new kubernetes version is available: %s\n", recommended)
fmt.Printf("Upgrading is recommended (try kops upgrade cluster)\n")
fmt.Printf("\n")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_k8s", recommended.String()))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
} else if required {
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
if recommended != nil {
fmt.Printf("A new kubernetes version is available: %s\n", recommended)
}
fmt.Printf("\n")
fmt.Printf("This version of kubernetes is no longer supported; upgrading is required\n")
fmt.Printf("(you can bypass this check by exporting KOPS_RUN_OBSOLETE_VERSION)\n")
fmt.Printf("\n")
fmt.Printf("More information: %s\n", buildPermalink("upgrade_k8s", recommended.String()))
fmt.Printf("\n")
fmt.Printf("%s\n", starline)
fmt.Printf("\n")
}
if required {
if os.Getenv("KOPS_RUN_OBSOLETE_VERSION") == "" {
return fmt.Errorf("kubernetes upgrade is required")
}
}
return nil
}
// addFileAssets adds the file assets within the assetBuilder
func (c *ApplyClusterCmd) addFileAssets(assetBuilder *assets.AssetBuilder) error {
var baseURL string
if components.IsBaseURL(c.Cluster.Spec.KubernetesVersion) {
baseURL = c.Cluster.Spec.KubernetesVersion
} else {
baseURL = "https://storage.googleapis.com/kubernetes-release/release/v" + c.Cluster.Spec.KubernetesVersion
}
c.Assets = make(map[architectures.Architecture][]*mirrors.MirroredAsset)
c.NodeUpAssets = make(map[architectures.Architecture]*mirrors.MirroredAsset)
for _, arch := range architectures.GetSupported() {
c.Assets[arch] = []*mirrors.MirroredAsset{}
k8sAssetsNames := []string{
fmt.Sprintf("/bin/linux/%s/kubelet", arch),
fmt.Sprintf("/bin/linux/%s/kubectl", arch),
}
if needsMounterAsset(c.Cluster, c.InstanceGroups) {
k8sAssetsNames = append(k8sAssetsNames, fmt.Sprintf("/bin/linux/%s/mounter", arch))
}
for _, an := range k8sAssetsNames {
k, err := url.Parse(baseURL)
if err != nil {
return err
}
k.Path = path.Join(k.Path, an)
u, hash, err := assetBuilder.RemapFileAndSHA(k)
if err != nil {
return err
}
c.Assets[arch] = append(c.Assets[arch], mirrors.BuildMirroredAsset(u, hash))
}
cniAsset, cniAssetHash, err := findCNIAssets(c.Cluster, assetBuilder, arch)
if err != nil {
return err
}
c.Assets[arch] = append(c.Assets[arch], mirrors.BuildMirroredAsset(cniAsset, cniAssetHash))
if c.Cluster.Spec.Networking.LyftVPC != nil {
lyftAsset, lyftAssetHash, err := findLyftVPCAssets(c.Cluster, assetBuilder, arch)
if err != nil {
return err
}
c.Assets[arch] = append(c.Assets[arch], mirrors.BuildMirroredAsset(lyftAsset, lyftAssetHash))
}
var containerRuntimeAssetUrl *url.URL
var containerRuntimeAssetHash *hashing.Hash
switch c.Cluster.Spec.ContainerRuntime {
case "docker":
containerRuntimeAssetUrl, containerRuntimeAssetHash, err = findDockerAsset(c.Cluster, assetBuilder, arch)
case "containerd":
containerRuntimeAssetUrl, containerRuntimeAssetHash, err = findContainerdAsset(c.Cluster, assetBuilder, arch)
default:
err = fmt.Errorf("unknown container runtime: %q", c.Cluster.Spec.ContainerRuntime)
}
if err != nil {
return err
}
c.Assets[arch] = append(c.Assets[arch], mirrors.BuildMirroredAsset(containerRuntimeAssetUrl, containerRuntimeAssetHash))
asset, err := NodeUpAsset(assetBuilder, arch)
if err != nil {
return err
}
c.NodeUpAssets[arch] = asset
}
return nil
}
// buildPermalink returns a link to our "permalink docs", to further explain an error message
func buildPermalink(key, anchor string) string {
url := "https://github.com/kubernetes/kops/blob/master/permalinks/" + key + ".md"
if anchor != "" {
url += "#" + anchor
}
return url
}
func | (c *kops.Cluster) (*kops.Channel, error) {
channelLocation := c.Spec.Channel
if channelLocation == "" {
channelLocation = kops.DefaultChannel
}
return kops.LoadChannel(channelLocation)
}
// needsMounterAsset checks if we need the mounter program
// This is only needed currently on ContainerOS i.e. GCE, but we don't have a nice way to detect it yet
func needsMounterAsset(c *kops.Cluster, instanceGroups []*kops.InstanceGroup) bool {
// TODO: Do real detection of ContainerOS (but this has to work with image names, and maybe even forked images)
switch kops.CloudProviderID(c.Spec.CloudProvider) {
case kops.CloudProviderGCE:
return true
default:
return false
}
}
type nodeUpConfigBuilder struct {
// Assets is a list of sources for files (primarily when not using everything containerized)
// Formats:
// raw url: http://... or https://...
// url with hash: <hex>@http://... or <hex>@https://...
assets map[architectures.Architecture][]*mirrors.MirroredAsset
assetBuilder *assets.AssetBuilder
channels []string
configBase vfs.Path
cluster *kops.Cluster
etcdManifests map[kops.InstanceGroupRole][]string
images map[kops.InstanceGroupRole]map[architectures.Architecture][]*nodeup.Image
protokubeAsset map[architectures.Architecture][]*mirrors.MirroredAsset
channelsAsset map[architectures.Architecture][]*mirrors.MirroredAsset
}
func newNodeUpConfigBuilder(cluster *kops.Cluster, assetBuilder *assets.AssetBuilder, assets map[architectures.Architecture][]*mirrors.MirroredAsset) (model.NodeUpConfigBuilder, error) {
configBase, err := vfs.Context.BuildVfsPath(cluster.Spec.ConfigBase)
if err != nil {
return nil, fmt.Errorf("error parsing config base %q: %v", cluster.Spec.ConfigBase, err)
}
channels := []string{
configBase.Join("addons", "bootstrap-channel.yaml").Path(),
}
for i := range cluster.Spec.Addons {
channels = append(channels, cluster.Spec.Addons[i].Manifest)
}
etcdManifests := map[kops.InstanceGroupRole][]string{}
images := map[kops.InstanceGroupRole]map[architectures.Architecture][]*nodeup.Image{}
protokubeAsset := map[architectures.Architecture][]*mirrors.MirroredAsset{}
channelsAsset := map[architectures.Architecture][]*mirrors.MirroredAsset{}
for _, arch := range architectures.GetSupported() {
asset, err := ProtokubeAsset(assetBuilder, arch)
if err != nil {
return nil, err
}
protokubeAsset[arch] = append(protokubeAsset[arch], asset)
}
for _, arch := range architectures.GetSupported() {
asset, err := ChannelsAsset(assetBuilder, arch)
if err != nil {
return nil, err
}
channelsAsset[arch] = append(channelsAsset[arch], asset)
}
for _, role := range kops.AllInstanceGroupRoles {
isMaster := role == kops.InstanceGroupRoleMaster
isAPIServer := role == kops.InstanceGroupRoleAPIServer
images[role] = make(map[architectures.Architecture][]*nodeup.Image)
if components.IsBaseURL(cluster.Spec.KubernetesVersion) {
// When using a custom version, we want to preload the images over http
components := []string{"kube-proxy"}
if isMaster {
components = append(components, "kube-apiserver", "kube-controller-manager", "kube-scheduler")
}
if isAPIServer {
components = append(components, "kube-apiserver")
}
for _, arch := range architectures.GetSupported() {
for _, component := range components {
baseURL, err := url.Parse(cluster.Spec.KubernetesVersion)
if err != nil {
return nil, err
}
baseURL.Path = path.Join(baseURL.Path, "/bin/linux", string(arch), component+".tar")
u, hash, err := assetBuilder.RemapFileAndSHA(baseURL)
if err != nil {
return nil, err
}
image := &nodeup.Image{
Sources: []string{u.String()},
Hash: hash.Hex(),
}
images[role][arch] = append(images[role][arch], image)
}
}
}
// `docker load` our images when using a KOPS_BASE_URL, so we
// don't need to push/pull from a registry
if os.Getenv("KOPS_BASE_URL") != "" && isMaster {
for _, arch := range architectures.GetSupported() {
for _, name := range []string{"kops-controller", "dns-controller", "kube-apiserver-healthcheck"} {
baseURL, err := url.Parse(os.Getenv("KOPS_BASE_URL"))
if err != nil {
return nil, err
}
baseURL.Path = path.Join(baseURL.Path, "/images/"+name+"-"+string(arch)+".tar.gz")
u, hash, err := assetBuilder.RemapFileAndSHA(baseURL)
if err != nil {
return nil, err
}
image := &nodeup.Image{
Sources: []string{u.String()},
Hash: hash.Hex(),
}
images[role][arch] = append(images[role][arch], image)
}
}
}
if os.Getenv("KOPS_BASE_URL") != "" && isAPIServer {
for _, arch := range architectures.GetSupported() {
for _, name := range []string{"kube-apiserver-healthcheck"} {
baseURL, err := url.Parse(os.Getenv("KOPS_BASE_URL"))
if err != nil {
return nil, err
}
baseURL.Path = path.Join(baseURL.Path, "/images/"+name+"-"+string(arch)+".tar.gz")
u, hash, err := assetBuilder.RemapFileAndSHA(baseURL)
if err != nil {
return nil, err
}
image := &nodeup.Image{
Sources: []string{u.String()},
Hash: hash.Hex(),
}
images[role][arch] = append(images[role][arch], image)
}
}
}
if isMaster {
for _, etcdCluster := range cluster.Spec.EtcdClusters {
if etcdCluster.Provider == kops.EtcdProviderTypeManager {
p := configBase.Join("manifests/etcd/" + etcdCluster.Name + ".yaml").Path()
etcdManifests[role] = append(etcdManifests[role], p)
}
}
}
}
configBuilder := nodeUpConfigBuilder{
assetBuilder: assetBuilder,
assets: assets,
channels: channels,
configBase: configBase,
cluster: cluster,
etcdManifests: etcdManifests,
images: images,
protokubeAsset: protokubeAsset,
channelsAsset: channelsAsset,
}
return &configBuilder, nil
}
// BuildNodeUpConfig returns the NodeUp config, in YAML format
func (n *nodeUpConfigBuilder) BuildConfig(ig *kops.InstanceGroup, apiserverAdditionalIPs []string, caResource fi.Resource) (*nodeup.Config, error) {
cluster := n.cluster
if ig == nil {
return nil, fmt.Errorf("instanceGroup cannot be nil")
}
role := ig.Spec.Role
if role == "" {
return nil, fmt.Errorf("cannot determine role for instance group: %v", ig.ObjectMeta.Name)
}
useGossip := dns.IsGossipHostname(cluster.Spec.MasterInternalName)
isMaster := role == kops.InstanceGroupRoleMaster
config := nodeup.NewConfig(cluster, ig)
config.Assets = make(map[architectures.Architecture][]string)
for _, arch := range architectures.GetSupported() {
config.Assets[arch] = []string{}
for _, a := range n.assets[arch] {
config.Assets[arch] = append(config.Assets[arch], a.CompactString())
}
}
config.ClusterName = cluster.ObjectMeta.Name
config.InstanceGroupName = ig.ObjectMeta.Name
if isMaster || useGossip {
for _, arch := range architectures.GetSupported() {
for _, a := range n.protokubeAsset[arch] {
config.Assets[arch] = append(config.Assets[arch], a.CompactString())
}
}
for _, arch := range architectures.GetSupported() {
for _, a := range n.channelsAsset[arch] {
config.Assets[arch] = append(config.Assets[arch], a.CompactString())
}
}
}
useConfigServer := featureflag.KopsControllerStateStore.Enabled() && (role != kops.InstanceGroupRoleMaster)
if useConfigServer {
baseURL := url.URL{
Scheme: "https",
Host: net.JoinHostPort("kops-controller.internal."+cluster.ObjectMeta.Name, strconv.Itoa(wellknownports.KopsControllerPort)),
Path: "/",
}
ca, err := fi.ResourceAsString(caResource)
if err != nil {
// CA task may not have run yet; we'll retry
return nil, fmt.Errorf("failed to read CA certificate: %w", err)
}
configServer := &nodeup.ConfigServerOptions{
Server: baseURL.String(),
CloudProvider: cluster.Spec.CloudProvider,
CA: ca,
}
config.ConfigServer = configServer
} else {
config.ConfigBase = fi.String(n.configBase.Path())
}
if isMaster {
config.ApiserverAdditionalIPs = apiserverAdditionalIPs
}
for _, manifest := range n.assetBuilder.StaticManifests {
match := false
for _, r := range manifest.Roles {
if r == role {
match = true
}
}
if !match {
continue
}
config.StaticManifests = append(config.StaticManifests, &nodeup.StaticManifest{
Key: manifest.Key,
Path: manifest.Path,
})
}
config.Images = n.images[role]
config.Channels = n.channels
config.EtcdManifests = n.etcdManifests[role]
return config, nil
}
| ChannelForCluster |
robust-point-in-polygon_20211115104748.ts | module.exports = robustPointInPolygon
var orient = require('robust-orientation')
function robustPointInPolygon(vs: number[][], point: number[]) {
const [x, y]: any = point;
var n = vs.length
let inside: number = 1
var lim: number = n
for(var i = 0, j = n-1; i<lim; j=i++) {
const a:number[] = vs[i]
const b:number[] = vs[j]
const yi: number = a[1]
const yj: number = b[1]
if(yj < yi) {
if(yj < y && y < yi) {
const s: any = orient(a, b, point)
if(s === 0) {
return 0
} else {
(inside as number) ^= (0 < s) | 0
}
} else if(y === yi) {
var c = vs[(i+1)%n]
var yk = c[1]
if(yi < yk) {
const s:any = orient(a, b, point)
if(s === 0) {
return 0
} else {
(inside as number) ^= (0 < s)|0
}
}
}
} else if(yi < yj) {
if(yi < y && y < yj) {
const s:any= orient(a, b, point)
if(s === 0) {
return 0
} else {
(inside as number) ^= (s < 0)|0
}
} else if(y === yi) {
var c = vs[(i+1)%n]
var yk = c[1]
if(yk < yi) {
const s:any = orient(a, b, point)
if(s === 0) {
return 0
} else {
(inside as number) ^= ((s as number) < 0) | 0
}
}
}
} else if(y === yi) {
var x0 = Math.min(a[0], b[0])
var x1 = Math.max(a[0], b[0])
if(i === 0) {
while(j>0) {
var k = (j+n-1)%n
var p = vs[k]
if(p[1] !== y) {
break
}
var px = p[0]
x0 = Math.min(x0, px)
x1 = Math.max(x1, px)
j = k
}
if(j === 0) {
if(x0 <= x && x <= x1) {
return 0
}
return 1
}
lim = j+1
}
const y0: number = vs[(j+n-1)%n][1]
while(i+1<lim) {
const p: any = vs[i+1]
if(p[1] !== y) {
break
}
const px = p[0]
x0 = Math.min(x0, px)
x1 = Math.max(x1, px)
i += 1
}
if(x0 <= x && x <= x1) {
return 0
}
const y1: any = (vs[(i+1)%n] as any)[1]
if(x < x0 && (y0 < y !== y1 < y)) {
(inside as number) ^= 1 | }
return 2 * inside - 1
} | }
} |
config-example.ts | import type { Config } from './schema.ts'
export const example: Config = {
/** 抽奖发起者的uid */
uid: 573732342,
/** 至少一个或多个抽奖动态的tid(目前为18位),注意要字符串形式(因为超过了JS最大安全整数) */
tid: ['##################'],
/** 选择抽奖条件,至少选择一个条件,至多全选 */
needs: {
/** 点赞 */
like: false,
/** 回复 */
reply: false,
/** 转发 */
repost: true,
},
/** 以上三个条件之间的关系,“并且”填false,“或者”填true */
or: false,
/** 参与抽奖者是否需要关注抽奖发起者 */
follow: true,
/** 被抽中的抽奖者人数 */ | /** 禁止参与抽奖的用户的uid列表,可以为空 */
blockuid: [],
/** 参与抽奖者在评论或者转发时不能出现的关键字字符串列表,可以为空 */
blockword: [],
/** 禁止自己参与抽奖 */
blockself: true,
} | count: 1,
/** 抽奖截止时间,去掉字符串(注意不是把字符串清空)则为当前时间 */
endtime: Number(new Date('2020-12-20 20:00:00')), |
voxelize.rs | use super::*;
use pbr::ProgressBar;
use std::path::{Path, PathBuf};
fn recursively_subdivide(triangle : Triangle, area_cutoff : f32, buf : &mut Vec<Triangle>) {
if triangle.area() < area_cutoff {
buf.push(triangle);
} else {
//
// a
// / \
// d---f
// / \ / \
// b---e---c
//
let a = triangle.points[0];
let b = triangle.points[1];
let c = triangle.points[2];
let d = 0.5 * (a + b);
let e = 0.5 * (b + c);
let f = 0.5 * (c + a);
let ta = triangle.uv[0];
let tb = triangle.uv[1];
let tc = triangle.uv[2];
let td = 0.5 * (ta + tb);
let te = 0.5 * (tb + tc);
let tf = 0.5 * (tc + ta);
let t_adf = Triangle { points : [a, d, f], uv : [ta, td, tf], ..triangle };
let t_bed = Triangle { points : [b, e, d], uv : [tb, te, td], ..triangle };
let t_def = Triangle { points : [d, e, f], uv : [td, te, tf], ..triangle };
let t_cfe = Triangle { points : [c, f, e], uv : [tc, tf, te], ..triangle };
recursively_subdivide(t_adf, area_cutoff, buf);
recursively_subdivide(t_bed, area_cutoff, buf);
recursively_subdivide(t_def, area_cutoff, buf);
recursively_subdivide(t_cfe, area_cutoff, buf);
}
}
use obj::Obj;
pub fn convert_obj_file_textured(obj_file : PathBuf, svdag_file : PathBuf, mat_file : PathBuf, depth : usize){
use std::path::Path;
use std::fs;
let mut obj_data : Obj = Obj::load(&obj_file).expect("Failed to load obj file");
let mut triangles = vec![];
let mut materials = HashMap::new();
use std::path::PathBuf;
let mut obj_root = obj_file.clone();
obj_root.set_file_name("");
let mut material_mat_list = vec![];
let mut material_idx_list = vec![];
let mut material_tex_list = vec![];
let mut material_col_list = vec![];
let mut next_material = 0;
for mtl in obj_data.data.material_libs.iter_mut() {
use std::io::Read;
use std::fs::File;
println!("Reloading: {:?}", mtl.filename);
mtl.reload(File::open(&obj_root.join(&mtl.filename)).unwrap()).unwrap();
for mat in &mtl.materials {
let nid = materials.len();
materials.entry(mat.name.clone()).or_insert(nid);
material_idx_list.push(next_material);
let mat_offset = next_material;
let mut unique_colors = HashSet::new();
if let Some(kd_tex_file) = &mat.map_kd {
println!("Loading texture: {:?}", kd_tex_file);
let img = read_image_maybe_tga(obj_root.join(kd_tex_file));
let img = img.into_rgb();
println!(" Finding Unique Colors...");
for (_,_,&image::Rgb(p)) in img.enumerate_pixels() {
unique_colors.insert(p);
}
println!(" Unique Colors: {}", unique_colors.len());
next_material += unique_colors.len();
material_tex_list.push(Some(img));
material_col_list.push(Some(unique_colors.iter().cloned().collect::<Vec<_>>()));
} else {
next_material += 1;
material_tex_list.push(None);
material_col_list.push(None);
}
println!(" Material Offset: {}", mat_offset);
let kdd = mat.kd.unwrap_or([0.0; 3]);
material_mat_list.push(Material {
albedo : kdd,
metalness : mat.km.unwrap_or(0.0),
emission : mat.ke.unwrap_or([0.0; 3]),
roughness : 0.3,
});
}
}
println!("Material Count: {}", materials.len());
println!("Processing Triangles...");
let mut min = Vec3::new(f32::MAX, f32::MAX, f32::MAX);
let mut max = Vec3::new(f32::MIN, f32::MIN, f32::MIN);
for &[x,y,z] in &obj_data.data.position {
if x < min.x {min.x = x;}
if y < min.y {min.y = y;}
if z < min.z {min.z = z;}
if x > max.x {max.x = x;}
if y > max.y {max.y = y;}
if z > max.z |
}
let size = max - min;
let mut max_size = size.x;
if size.y > max_size {max_size = size.y;}
if size.z > max_size {max_size = size.z;}
println!("Max Size: {}", max_size);
let area_cutoff = 4.0 * (max_size * max_size) / (4.0f32.powf(depth as f32));
println!("Area Cutoff: {}", area_cutoff);
for o in 0..(obj_data.data.objects.len()) {
let object = &obj_data.data.objects[o];
for g in 0..(object.groups.len()) {
let group = &object.groups[g];
let next = materials.len();
let id = if let Some(obj::ObjMaterial::Ref(s)) = &group.material {
*materials.entry(s.clone()).or_insert(next)
} else {
0
};
for p in 0..(group.polys.len()) {
let poly = &group.polys[p];
for v in 2..(poly.0.len()) {
let v0 = obj_data.data.position[poly.0[0].0];
let v1 = obj_data.data.position[poly.0[v-1].0];
let v2 = obj_data.data.position[poly.0[v].0];
let t0 = poly.0[0].1 .map(|i| obj_data.data.texture[i]).unwrap_or([0.0,0.0]);
let t1 = poly.0[v-1].1.map(|i| obj_data.data.texture[i]).unwrap_or([0.0,0.0]);
let t2 = poly.0[v].1 .map(|i| obj_data.data.texture[i]).unwrap_or([0.0,0.0]);
let v0 = Vec3::new(v0[0], v0[1], v0[2]);
let v1 = Vec3::new(v1[0], v1[1], v1[2]);
let v2 = Vec3::new(v2[0], v2[1], v2[2]);
let t0 = Vec2::new(t0[0], t0[1]);
let t1 = Vec2::new(t1[0], t1[1]);
let t2 = Vec2::new(t2[0], t2[1]);
let t = Triangle{
points : [v0, v1, v2],
normal : (v0 - v1).cross(v1 - v2),
uv : [t0, t1, t2],
mat : material_idx_list[id] as u16,
..Default::default()
};
let t_start = triangles.len();
recursively_subdivide(t, area_cutoff, &mut triangles);
let ref tex = material_tex_list[id];
let ref col = material_col_list[id];
if let (Some(t), Some(col)) = (tex, col) {
for tri in triangles[t_start..].iter_mut() {
let cuv = tri.uv_center();
let c = texture_lookup(&t, cuv.x, cuv.y);
let i = col.iter().enumerate().find_map(|(i, p)| if *p == c {Some(i)} else {None}).unwrap();
tri.mat += i as u16;
}
}
}
}
}
}
println!("Triangles: {}", triangles.len());
let material_list = (0..(material_mat_list.len()))
.flat_map(|i| {
let m = &material_mat_list[i];
if let Some(ref c) = material_col_list[i] {
c.iter()
.map(|c| Material {
albedo : [
c[0] as f32 / 255.0,
c[1] as f32 / 255.0,
c[2] as f32 / 255.0
],
..*m
})
.collect::<Vec<_>>()
} else {
vec![*m]
}
})
.collect::<Vec<_>>();
println!("Material Count: {}", material_list.len());
println!("Constructing SVDAG...");
use std::time::*;
let mut pb = ProgressBar::new(8*8*8*8);
let start = Instant::now();
let vchunk = VoxelChunk::from_mesh(depth, &triangles, min, max_size, &mut |t| { pb.total = t; pb.inc(); });
let elapsed = start.elapsed();
pb.finish();
println!("Time to voxelize: {:?}", elapsed);
println!("DAG nodes: {}", vchunk.len());
let serialized = bincode::serialize(&vchunk).unwrap();
let serialized_mats = bincode::serialize(&material_list).unwrap();
fs::write(svdag_file, serialized).unwrap();
fs::write(mat_file, serialized_mats).unwrap();
}
pub fn convert_obj_file_with_materials(obj_file : PathBuf, svdag_file : PathBuf, mat_file : PathBuf, depth : usize){
use obj::Obj;
use std::path::Path;
use std::fs;
let mut obj_data = Obj::load(&obj_file).expect("Failed to load obj file");
let mut triangles = vec![];
let mut materials = HashMap::new();
use std::path::PathBuf;
let mut obj_root = obj_file.clone();
obj_root.set_file_name("");
let mut material_list = vec![Material::default(); materials.len()];
for mtl in obj_data.data.material_libs.iter_mut() {
use std::io::Read;
use std::fs::File;
println!("Reloading: {:?}", mtl.filename);
mtl.reload(File::open(&obj_root.join(&mtl.filename)).unwrap()).unwrap();
for mat in &mtl.materials {
let kd = if let Some(kd_tex_file) = &mat.map_kd {
println!("Loading texture: {:?}", kd_tex_file);
let img = read_image_maybe_tga(obj_root.join(kd_tex_file));
println!(" img: {:?}", img.color());
let img = img.into_rgb();
let (w, h) = img.dimensions();
println!(" Averaging...");
let mut color = [0.0; 3];
for (_,_,&image::Rgb(p)) in img.enumerate_pixels() {
color[0] += p[0] as f32;
color[1] += p[1] as f32;
color[2] += p[2] as f32;
}
color[0] /= (w * h * 255) as f32;
color[1] /= (w * h * 255) as f32;
color[2] /= (w * h * 255) as f32;
println!(" Color: {:?}", color);
color
} else {
[1.0; 3]
};
let next = materials.len();
let _id = *materials.entry(mat.name.clone()).or_insert(next);
let mut kdd = mat.kd.unwrap_or([0.0; 3]);
kdd[0] *= kd[0];
kdd[1] *= kd[1];
kdd[2] *= kd[2];
material_list.push(Material {
albedo : kdd,
metalness : mat.km.unwrap_or(0.0),
emission : mat.ke.unwrap_or([0.0; 3]),
roughness : 0.3,
});
}
}
println!("Material Count: {}", materials.len());
println!("Processing Triangles...");
for o in 0..(obj_data.data.objects.len()) {
let object = &obj_data.data.objects[o];
for g in 0..(object.groups.len()) {
let group = &object.groups[g];
let next = materials.len();
let id = if let Some(obj::ObjMaterial::Ref(s)) = &group.material {
*materials.entry(s.clone()).or_insert(next) as u16
} else {
0
};
for p in 0..(group.polys.len()) {
let poly = &group.polys[p];
for v in 2..(poly.0.len()) {
let v0 = obj_data.data.position[poly.0[0].0];
let v1 = obj_data.data.position[poly.0[v-1].0];
let v2 = obj_data.data.position[poly.0[v].0];
let v0 = Vec3::new(v0[0], v0[1], v0[2]);
let v1 = Vec3::new(v1[0], v1[1], v1[2]);
let v2 = Vec3::new(v2[0], v2[1], v2[2]);
triangles.push(Triangle{
points : [v0, v1, v2],
normal : (v0 - v1).cross(v1 - v2),
// mat : 0,
mat : id,
..Default::default()
});
}
}
}
}
println!("Triangles: {}", triangles.len());
let mut min = Vec3::new(f32::MAX, f32::MAX, f32::MAX);
let mut max = Vec3::new(f32::MIN, f32::MIN, f32::MIN);
for [x,y,z] in obj_data.data.position {
if x < min.x {min.x = x;}
if y < min.y {min.y = y;}
if z < min.z {min.z = z;}
if x > max.x {max.x = x;}
if y > max.y {max.y = y;}
if z > max.z {max.z = z;}
}
let size = max - min;
let mut max_size = size.x;
if size.y > max_size {max_size = size.y;}
if size.z > max_size {max_size = size.z;}
println!("Constructing SVDAG...");
use std::time::*;
let mut pb = ProgressBar::new(8*8*8*8);
let start = Instant::now();
let vchunk = VoxelChunk::from_mesh(depth, &triangles, min, max_size, &mut |t| { pb.total = t; pb.inc(); });
let elapsed = start.elapsed();
pb.finish();
println!("Time to voxelize: {:?}", elapsed);
println!("DAG nodes: {}", vchunk.len());
let serialized = bincode::serialize(&vchunk).unwrap();
let serialized_mats = bincode::serialize(&material_list).unwrap();
fs::write(svdag_file, serialized).unwrap();
fs::write(mat_file, serialized_mats).unwrap();
}
pub fn convert_obj_file(obj_file : PathBuf, svdag_file : PathBuf, depth : usize){
use obj::Obj;
use std::path::Path;
use std::fs;
let obj_data = Obj::load(&obj_file).expect("Failed to load obj file");
let mut triangles = vec![];
use std::path::PathBuf;
println!("Processing Triangles...");
for o in 0..(obj_data.data.objects.len()) {
let object = &obj_data.data.objects[o];
for g in 0..(object.groups.len()) {
let group = &object.groups[g];
for p in 0..(group.polys.len()) {
let poly = &group.polys[p];
for v in 2..(poly.0.len()) {
let v0 = obj_data.data.position[poly.0[0].0];
let v1 = obj_data.data.position[poly.0[v-1].0];
let v2 = obj_data.data.position[poly.0[v].0];
let v0 = Vec3::new(v0[0], v0[1], v0[2]);
let v1 = Vec3::new(v1[0], v1[1], v1[2]);
let v2 = Vec3::new(v2[0], v2[1], v2[2]);
triangles.push(Triangle{
points : [v0, v1, v2],
normal : (v0 - v1).cross(v1 - v2),
mat : 0,
..Default::default()
});
}
}
}
}
println!("Triangles: {}", triangles.len());
let mut min = Vec3::new(f32::MAX, f32::MAX, f32::MAX);
let mut max = Vec3::new(f32::MIN, f32::MIN, f32::MIN);
for [x,y,z] in obj_data.data.position {
if x < min.x {min.x = x;}
if y < min.y {min.y = y;}
if z < min.z {min.z = z;}
if x > max.x {max.x = x;}
if y > max.y {max.y = y;}
if z > max.z {max.z = z;}
}
let size = max - min;
let mut max_size = size.x;
if size.y > max_size {max_size = size.y;}
if size.z > max_size {max_size = size.z;}
println!("Constructing SVDAG...");
use std::time::*;
let mut pb = ProgressBar::new(8*8*8*8);
let start = Instant::now();
let vchunk = VoxelChunk::from_mesh(depth, &triangles, min, max_size, &mut |t| { pb.total = t; pb.inc(); });
let elapsed = start.elapsed();
pb.finish();
println!("Time to voxelize: {:?}", elapsed);
println!("DAG nodes: {}", vchunk.len());
let serialized = bincode::serialize(&vchunk).unwrap();
fs::write(svdag_file, serialized).unwrap();
}
use image;
fn read_image_maybe_tga<P : AsRef<Path>>(path : P) -> image::DynamicImage {
let path : &Path = path.as_ref();
let bytes = std::fs::read(path).unwrap();
let byte_stream = std::io::Cursor::new(&bytes);
let mut reader = image::io::Reader::new(byte_stream);
// somewhat sketchy logic to deal with some tga files I had
if path.extension().map(|ext| ext.to_string_lossy().to_string()) == Some("tga".to_string()) {
reader.set_format(image::ImageFormat::Tga);
} else {
reader = reader.with_guessed_format().unwrap();
}
let image = reader.decode().unwrap();
image
}
| {max.z = z;} |
code.rs | use serde::Deserialize;
#[derive(Deserialize)]
pub struct | {
pub language: Option<String>,
pub content: String,
}
| CodeReq |
mailgun.py | from __future__ import unicode_literals
import datetime
from chatterbot.input import InputAdapter
from chatterbot.conversation import Statement
class Mailgun(InputAdapter):
"""
Get input from Mailgun.
"""
def __init__(self, **kwargs):
super(Mailgun, self).__init__(**kwargs)
# Use the bot's name for the name of the sender
self.name = kwargs.get('name')
self.from_address = kwargs.get('mailgun_from_address')
self.api_key = kwargs.get('mailgun_api_key')
self.endpoint = kwargs.get('mailgun_api_endpoint')
def get_email_stored_events(self):
import requests
yesterday = datetime.datetime.now() - datetime.timedelta(1)
return requests.get(
'{}/events'.format(self.endpoint),
auth=('api', self.api_key),
params={
'begin': yesterday.isoformat(),
'ascending': 'yes',
'limit': 1
}
)
def get_stored_email_urls(self):
|
def get_message(self, url):
import requests
return requests.get(
url,
auth=('api', self.api_key)
)
def process_input(self, statement):
urls = self.get_stored_email_urls()
url = list(urls)[0]
response = self.get_message(url)
message = response.json()
text = message.get('stripped-text')
return Statement(text)
| response = self.get_email_stored_events()
data = response.json()
for item in data.get('items', []):
if 'storage' in item:
if 'url' in item['storage']:
yield item['storage']['url'] |
parser.rs | use proc_macro2::TokenStream;
use quote::quote;
use std::iter::Peekable;
#[derive(Debug)]
pub enum ParseArg {
Pipe,
Semicolon,
RedirectFd(i32, i32), // fd1, fd2
RedirectFile(i32, TokenStream, bool), // fd1, file, append?
ArgStr(TokenStream),
ArgVec(TokenStream),
}
pub struct | <I: Iterator<Item = ParseArg>> {
iter: Peekable<I>,
}
impl<I: Iterator<Item = ParseArg>> Parser<I> {
pub fn from(iter: Peekable<I>) -> Self {
Self { iter }
}
pub fn parse(mut self, for_spawn: bool) -> TokenStream {
let mut ret = quote!(::cmd_lib::GroupCmds::default());
while self.iter.peek().is_some() {
let cmd = self.parse_cmd();
if !cmd.is_empty() {
ret.extend(quote!(.append(#cmd)));
if for_spawn && self.iter.peek().is_some() {
panic!("wrong spawning format: group command not allowed");
}
}
}
ret
}
fn parse_cmd(&mut self) -> TokenStream {
let mut cmds = quote!(::cmd_lib::Cmds::default());
while self.iter.peek().is_some() {
let cmd = self.parse_pipe();
cmds.extend(quote!(.pipe(#cmd)));
if !matches!(self.iter.peek(), Some(ParseArg::Pipe)) {
self.iter.next();
break;
}
self.iter.next();
}
cmds
}
fn parse_pipe(&mut self) -> TokenStream {
let mut ret = quote!(::cmd_lib::Cmd::default());
while let Some(arg) = self.iter.peek() {
match arg {
ParseArg::RedirectFd(fd1, fd2) => {
if fd1 != fd2 {
let mut redirect = quote!(::cmd_lib::Redirect);
match (fd1, fd2) {
(1, 2) => redirect.extend(quote!(::StdoutToStderr)),
(2, 1) => redirect.extend(quote!(::StderrToStdout)),
_ => panic!("unsupported fd numbers: {} {}", fd1, fd2),
}
ret.extend(quote!(.add_redirect(#redirect)));
}
}
ParseArg::RedirectFile(fd1, file, append) => {
let mut redirect = quote!(::cmd_lib::Redirect);
match fd1 {
0 => redirect.extend(quote!(::FileToStdin(#file.into_path_buf()))),
1 => {
redirect.extend(quote!(::StdoutToFile(#file.into_path_buf(), #append)))
}
2 => {
redirect.extend(quote!(::StderrToFile(#file.into_path_buf(), #append)))
}
_ => panic!("unsupported fd ({}) redirect to file {}", fd1, file),
}
ret.extend(quote!(.add_redirect(#redirect)));
}
ParseArg::ArgStr(opt) => {
ret.extend(quote!(.add_arg(#opt.into_os_string())));
}
ParseArg::ArgVec(opts) => {
ret.extend(quote! (.add_args(#opts.iter().map(|s| ::std::ffi::OsString::from(s)).collect())));
}
ParseArg::Pipe | ParseArg::Semicolon => break,
}
self.iter.next();
}
ret
}
}
| Parser |
admin.py | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from django.utils.translation import gettext as _
from core import models
class | (BaseUserAdmin):
ordering = ['id']
list_display = ['email', 'name']
fieldsets = (
(None, {'fields': ('email', 'password')}),
(_('Personal Info'), {'fields': ('name',)}),
(
_('Permissions'),
{
'fields': (
'is_active',
'is_staff',
'is_superuser',
)
}
),
(_('Important dates'), {'fields': ('last_login',)}),
)
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'password1', 'password2')
}),
)
admin.site.register(models.User, UserAdmin)
admin.site.register(models.Tag)
admin.site.register(models.Ingredient)
admin.site.register(models.Recipe)
| UserAdmin |
Bitmap.ts | /*
The MIT License (MIT)
Copyright (c) 2016 Tom Zoehner
Copyright (c) 2018 Thomas Bluemel
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import { Blob } from "./Blob";
import { EMFJSError, Helper } from "./Helper";
export class BitmapBase {
public getWidth() {
throw new EMFJSError("getWidth not implemented");
}
public getHeight() {
throw new EMFJSError("getHeight not implemented"); | public width: number;
public height: number;
public planes: number;
public bitcount: number;
constructor(reader: Blob, skipsize: boolean) {
if (skipsize) {
reader.skip(4);
}
this.width = reader.readUint16();
this.height = reader.readUint16();
this.planes = reader.readUint16();
this.bitcount = reader.readUint16();
}
public colors() {
return this.bitcount <= 8 ? 1 << this.bitcount : 0;
}
}
export class BitmapInfoHeader {
public width: number;
public height: number;
public planes: number;
public bitcount: number;
public compression: number;
public sizeimage: number;
public xpelspermeter: number;
public ypelspermeter: number;
public clrused: number;
public clrimportant: number;
constructor(reader: Blob, skipsize: boolean) {
if (skipsize) {
reader.skip(4);
}
this.width = reader.readInt32();
this.height = reader.readInt32();
this.planes = reader.readUint16();
this.bitcount = reader.readUint16();
this.compression = reader.readUint32();
this.sizeimage = reader.readUint32();
this.xpelspermeter = reader.readInt32();
this.ypelspermeter = reader.readInt32();
this.clrused = reader.readUint32();
this.clrimportant = reader.readUint32();
}
public colors() {
if (this.clrused !== 0) {
return this.clrused < 256 ? this.clrused : 256;
} else {
return this.bitcount > 8 ? 0 : 1 << this.bitcount;
}
}
}
export class BitmapInfo extends BitmapBase {
private _usergb: boolean;
private _infosize: number;
private _header: BitmapCoreHeader | BitmapInfoHeader;
constructor(reader: Blob, usergb: boolean) {
super();
this._usergb = usergb;
const hdrsize = reader.readUint32();
this._infosize = hdrsize;
if (hdrsize === Helper.GDI.BITMAPCOREHEADER_SIZE) {
this._header = new BitmapCoreHeader(reader, false);
this._infosize += this._header.colors() * (usergb ? 3 : 2);
} else {
this._header = new BitmapInfoHeader(reader, false);
const masks = (this._header as BitmapInfoHeader).compression
=== Helper.GDI.BitmapCompression.BI_BITFIELDS ? 3 : 0;
if (hdrsize <= Helper.GDI.BITMAPINFOHEADER_SIZE + (masks * 4)) {
this._infosize = Helper.GDI.BITMAPINFOHEADER_SIZE + (masks * 4);
}
this._infosize += this._header.colors() * (usergb ? 4 : 2);
}
}
public getWidth() {
return this._header.width;
}
public getHeight() {
return Math.abs(this._header.height);
}
public infosize() {
return this._infosize;
}
public header() {
return this._header;
}
}
export class DIBitmap extends BitmapBase {
private _reader: Blob;
private _offset: number;
private _location: any;
private _info: BitmapInfo;
constructor(reader: Blob, bitmapInfo?: any) {
super();
this._reader = reader;
this._offset = reader.pos;
this._location = bitmapInfo;
this._info = new BitmapInfo(reader, true);
}
public getWidth() {
return this._info.getWidth();
}
public getHeight() {
return this._info.getHeight();
}
public totalSize() {
return this._location.header.size + this._location.data.size;
}
public makeBitmapFileHeader() {
const buf = new ArrayBuffer(14);
const view = new Uint8Array(buf);
view[0] = 0x42;
view[1] = 0x4d;
Helper._writeUint32Val(view, 2, this.totalSize() + 14);
Helper._writeUint32Val(view, 10, this._info.infosize() + 14);
return Helper._blobToBinary(view);
}
public base64ref() {
const prevpos = this._reader.pos;
this._reader.seek(this._offset);
let mime = "image/bmp";
const header = this._info.header();
let data;
if (header instanceof BitmapInfoHeader && header.compression != null) {
switch (header.compression) {
case Helper.GDI.BitmapCompression.BI_JPEG:
mime = "data:image/jpeg";
break;
case Helper.GDI.BitmapCompression.BI_PNG:
mime = "data:image/png";
break;
default:
data = this.makeBitmapFileHeader();
break;
}
} else {
data = this.makeBitmapFileHeader();
}
this._reader.seek(this._location.header.offset);
if (data != null) {
data += this._reader.readBinary(this._location.header.size);
} else {
data = this._reader.readBinary(this._location.header.size);
}
this._reader.seek(this._location.data.offset);
data += this._reader.readBinary(this._location.data.size);
const ref = "data:" + mime + ";base64," + btoa(data);
this._reader.seek(prevpos);
return ref;
}
} | }
}
export class BitmapCoreHeader { |
coelacanth_vault.py | #!/usr/bin/python
import random
from Crypto.Util import number
from functools import reduce
TOTAL = 15
THRESHOLD = 10
MAX_COELACANTH = 9
NUM_LOCKS = 5
NUM_TRIES = 250
# substitute for math.prod
prod = lambda n: reduce(lambda x, y: x*y, n)
def create_key(t, n, size=8):
while True:
seq = sorted([number.getPrime(size) for _ in range(TOTAL)])
if len(set(seq)) != len(seq):
continue
alpha = prod(seq[:t])
beta = prod(seq[-t + 1:])
if alpha > beta:
secret = random.randint(beta, alpha)
shares = [(secret % num, num) for num in seq]
return secret, shares
def construct_key(shares):
glue = lambda A, n, s=1, t=0, N=0: (n < 2 and t % N or glue(n, A % n, t, s - A//n * t, N or n), -1)[n < 1]
mod = prod([m for s, m in shares])
secret = sum([s * glue(mod//m, m) * mod//m for s, m in shares]) % mod
return secret
if __name__ == "__main__":
print("Hi, and welcome to the virtual Animal Crossing: New Horizon coelacanth vault!")
print("There are {} different cryptolocks that must be unlocked in order to open the vault.".format(NUM_LOCKS))
print("You get one portion of each code for each coelacanth you have caught, and will need to use them to reconstruct the key for each lock.")
print("Unfortunately, it appears you have not caught enough coelacanths, and thus will need to find another way into the vault.")
print("Be warned, these locks have protection against brute force; too many wrong attempts and you will have to start over!")
print("")
num_shares = abs(int(input("How many coelacanth have you caught? ")))
if num_shares > MAX_COELACANTH:
print("Don't be silly! You definitely haven't caught more than {} coelacanth!".format(MAX_COELACANTH))
print("Come back when you decide to stop lying.")
quit() | print("Generating key for lock {}, please wait...".format(lock_num))
secret, shares = create_key(THRESHOLD, TOTAL)
r_secret = construct_key(random.sample(shares, THRESHOLD))
assert(secret == r_secret)
print("Generated!")
print("Here are your key portions:")
print(random.sample(shares, num_shares))
for num_attempts in range(NUM_TRIES):
n_secret = abs(int(input("Please input the key: ")))
if secret == n_secret:
print("Lock {} unlocked with {} failed attempts!".format(lock_num, num_attempts))
break
else:
print("Key incorrect. You have {} tries remaining for this lock.".format(NUM_TRIES - num_attempts))
else:
print("BRUTE FORCE DETECTED. LOCKS SHUT DOWN.")
print("Get out. You don't deserve what's in this vault.")
quit()
print("Opening vault...")
with open("flag.txt", "r") as f:
print(f.read()) |
for lock_num in range(NUM_LOCKS): |
__main__.py | import click
from flask.cli import FlaskGroup
from . import create_app
@click.group(cls=FlaskGroup, create_app=create_app)
def | ():
"""Management script for the python_project_template application."""
if __name__ == "__main__": # pragma: no cover
main()
| main |
app.tsx | import * as React from 'react';
import {Component} from 'react';
import Select from '@atlaskit/single-select';
import Button from '@atlaskit/button';
import FieldText from '@atlaskit/field-text';
import Checkbox from '@atlaskit/checkbox';
import Cristal, { InitialPosition, CristalProps, CristalState } from '../src';
import {ComponentWrapper, CristalCreatorWrapper, CritalOptions, CristalToggleOptions} from './styled';
export interface AppProps {
}
export interface AppState {
initialPosition: {value: InitialPosition};
title: string;
isResizable: boolean;
isDraggable: boolean;
isVisible: boolean;
cristals: CristalProps[];
cristalStates: {[key: string]: CristalState};
children: string;
}
export type StatePropName = keyof AppState;
const positionItems = [
{
items: [
{ value: 'top-left', content: 'Top left' },
{ value: 'top-center', content: 'Top center' },
{ value: 'top-right', content: 'Top right' },
{ value: 'center', content: 'Center' },
{ value: 'bottom-left', content: 'Bottom left' },
{ value: 'bottom-center', content: 'Bottom center' },
{ value: 'bottom-right', content: 'Bottom right' }
]
}
];
const selectedItem: any = positionItems[0].items[1];
const defaultTitle = 'Fancy cristal window';
const defaultChildren = '😎';
export default class App | tends Component<AppProps, AppState> {
state: AppState = {
title: defaultTitle,
initialPosition: selectedItem,
isResizable: true,
isDraggable: true,
isVisible: true,
children: defaultChildren,
cristals: [{
children: defaultChildren,
title: defaultTitle
}, {
children: '🤔',
title: 'Fancy cristal window 2',
initialPosition: 'bottom-left'
}],
cristalStates: {}
}
onPositionChange = (e: any) => {
this.setState({
initialPosition: e.item
});
}
onMax = (ref:React.RefObject<Cristal>) => () => {
var cristal = ref.current;
if (cristal!=null) {
cristal.setState({width:window.innerWidth,x:0,y:0,height:window.innerHeight});
}
}
onMin = (ref:React.RefObject<Cristal>) => () => {
var cristal = ref.current;
if (cristal!=null) {
cristal.setState({width:1, x:-1, y:-1, height:1});
}
}
removeCristal = (index: number) => () => {
const {cristals} = this.state;
cristals.splice(index, 1);
this.setState({
cristals
});
}
onMove = (state: CristalState) => {
const {cristalStates} = this.state;
cristalStates['1'] = state;
// TODO: fancy render
}
renderCristals = () => {
const {cristals} = this.state;
if (!cristals.length) return;
const content = cristals.map((cristal, index) => {
const {children} = cristal;
const cref = React.createRef<Cristal>();
return (
<Cristal
key={index}
onClose={this.removeCristal(index)}
onMin={this.onMin(cref)}
onMax={this.onMax(cref)}
onMove={this.onMove}
ref={cref}
{...cristal}
>
<ComponentWrapper>
{children}
</ComponentWrapper>
</Cristal>
)
});
return content;
}
createNewCristal = () => {
const {cristals, title, children, initialPosition, isResizable, isDraggable} = this.state;
cristals.push({
children,
title,
isResizable,
isDraggable,
initialPosition: initialPosition.value
});
this.setState({cristals});
}
onTitleChange = (e: any) => {
const title = e.target.value;
this.setState({title});
}
onChildrenChange = (e: any) => {
const children = e.target.value;
this.setState({children});
}
onCheckboxChange = (propName: StatePropName) => () => {
const currentValue = this.state[propName];
this.setState({ [propName]: !currentValue } as any);
}
render() {
const {title, children} = this.state;
return (
<div>
{this.renderCristals()}
<Cristal
title="Create a new cristal window"
isResizable={false}
isDraggable={false}
initialPosition="top-center"
>
<CristalCreatorWrapper>
<CritalOptions>
<Select
label="Position"
items={positionItems}
defaultSelected={selectedItem}
onSelected={this.onPositionChange}
droplistShouldFitContainer={true}
/>
<FieldText label="Title" value={title} onChange={this.onTitleChange} />
<FieldText label="Content" value={children} onChange={this.onChildrenChange} />
</CritalOptions>
<CristalToggleOptions>
<Checkbox
initiallyChecked={true}
label="Resizable"
onChange={this.onCheckboxChange('isResizable')}
/>
<Checkbox
initiallyChecked={true}
label="Draggable"
onChange={this.onCheckboxChange('isDraggable')}
/>
</CristalToggleOptions>
<Button shouldFitContainer appearance="primary" onClick={this.createNewCristal}>
Create
</Button>
</CristalCreatorWrapper>
</Cristal>
</div>
);
}
}
| ex |
error.rs | // Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
/// Error type for the `ClaimDevicesByClaimCode` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ClaimDevicesByClaimCodeError {
/// Kind of error that occurred.
pub kind: ClaimDevicesByClaimCodeErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `ClaimDevicesByClaimCode` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ClaimDevicesByClaimCodeErrorKind {
#[allow(missing_docs)] // documentation missing in model
ForbiddenException(crate::error::ForbiddenException),
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ClaimDevicesByClaimCodeError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ClaimDevicesByClaimCodeErrorKind::ForbiddenException(_inner) => _inner.fmt(f),
ClaimDevicesByClaimCodeErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
ClaimDevicesByClaimCodeErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ClaimDevicesByClaimCodeErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ClaimDevicesByClaimCodeError {
fn code(&self) -> Option<&str> {
ClaimDevicesByClaimCodeError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ClaimDevicesByClaimCodeError {
/// Creates a new `ClaimDevicesByClaimCodeError`.
pub fn new(kind: ClaimDevicesByClaimCodeErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ClaimDevicesByClaimCodeError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ClaimDevicesByClaimCodeErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ClaimDevicesByClaimCodeError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ClaimDevicesByClaimCodeErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `ClaimDevicesByClaimCodeErrorKind::ForbiddenException`.
pub fn is_forbidden_exception(&self) -> bool {
matches!(
&self.kind,
ClaimDevicesByClaimCodeErrorKind::ForbiddenException(_)
)
}
/// Returns `true` if the error kind is `ClaimDevicesByClaimCodeErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
ClaimDevicesByClaimCodeErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `ClaimDevicesByClaimCodeErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ClaimDevicesByClaimCodeErrorKind::InvalidRequestException(_)
)
}
}
impl std::error::Error for ClaimDevicesByClaimCodeError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ClaimDevicesByClaimCodeErrorKind::ForbiddenException(_inner) => Some(_inner),
ClaimDevicesByClaimCodeErrorKind::InternalFailureException(_inner) => Some(_inner),
ClaimDevicesByClaimCodeErrorKind::InvalidRequestException(_inner) => Some(_inner),
ClaimDevicesByClaimCodeErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `DescribeDevice` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct DescribeDeviceError {
/// Kind of error that occurred.
pub kind: DescribeDeviceErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `DescribeDevice` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum DescribeDeviceErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
#[allow(missing_docs)] // documentation missing in model
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for DescribeDeviceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result |
}
impl aws_smithy_types::retry::ProvideErrorKind for DescribeDeviceError {
fn code(&self) -> Option<&str> {
DescribeDeviceError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl DescribeDeviceError {
/// Creates a new `DescribeDeviceError`.
pub fn new(kind: DescribeDeviceErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `DescribeDeviceError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: DescribeDeviceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `DescribeDeviceError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: DescribeDeviceErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `DescribeDeviceErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
DescribeDeviceErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `DescribeDeviceErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
DescribeDeviceErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `DescribeDeviceErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
DescribeDeviceErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for DescribeDeviceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
DescribeDeviceErrorKind::InternalFailureException(_inner) => Some(_inner),
DescribeDeviceErrorKind::InvalidRequestException(_inner) => Some(_inner),
DescribeDeviceErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
DescribeDeviceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `FinalizeDeviceClaim` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct FinalizeDeviceClaimError {
/// Kind of error that occurred.
pub kind: FinalizeDeviceClaimErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `FinalizeDeviceClaim` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum FinalizeDeviceClaimErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
#[allow(missing_docs)] // documentation missing in model
PreconditionFailedException(crate::error::PreconditionFailedException),
#[allow(missing_docs)] // documentation missing in model
ResourceConflictException(crate::error::ResourceConflictException),
#[allow(missing_docs)] // documentation missing in model
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for FinalizeDeviceClaimError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
FinalizeDeviceClaimErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
FinalizeDeviceClaimErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
FinalizeDeviceClaimErrorKind::PreconditionFailedException(_inner) => _inner.fmt(f),
FinalizeDeviceClaimErrorKind::ResourceConflictException(_inner) => _inner.fmt(f),
FinalizeDeviceClaimErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
FinalizeDeviceClaimErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for FinalizeDeviceClaimError {
fn code(&self) -> Option<&str> {
FinalizeDeviceClaimError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl FinalizeDeviceClaimError {
/// Creates a new `FinalizeDeviceClaimError`.
pub fn new(kind: FinalizeDeviceClaimErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `FinalizeDeviceClaimError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: FinalizeDeviceClaimErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `FinalizeDeviceClaimError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: FinalizeDeviceClaimErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `FinalizeDeviceClaimErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
FinalizeDeviceClaimErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `FinalizeDeviceClaimErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
FinalizeDeviceClaimErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `FinalizeDeviceClaimErrorKind::PreconditionFailedException`.
pub fn is_precondition_failed_exception(&self) -> bool {
matches!(
&self.kind,
FinalizeDeviceClaimErrorKind::PreconditionFailedException(_)
)
}
/// Returns `true` if the error kind is `FinalizeDeviceClaimErrorKind::ResourceConflictException`.
pub fn is_resource_conflict_exception(&self) -> bool {
matches!(
&self.kind,
FinalizeDeviceClaimErrorKind::ResourceConflictException(_)
)
}
/// Returns `true` if the error kind is `FinalizeDeviceClaimErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
FinalizeDeviceClaimErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for FinalizeDeviceClaimError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
FinalizeDeviceClaimErrorKind::InternalFailureException(_inner) => Some(_inner),
FinalizeDeviceClaimErrorKind::InvalidRequestException(_inner) => Some(_inner),
FinalizeDeviceClaimErrorKind::PreconditionFailedException(_inner) => Some(_inner),
FinalizeDeviceClaimErrorKind::ResourceConflictException(_inner) => Some(_inner),
FinalizeDeviceClaimErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
FinalizeDeviceClaimErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `GetDeviceMethods` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct GetDeviceMethodsError {
/// Kind of error that occurred.
pub kind: GetDeviceMethodsErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `GetDeviceMethods` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum GetDeviceMethodsErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
#[allow(missing_docs)] // documentation missing in model
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for GetDeviceMethodsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
GetDeviceMethodsErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
GetDeviceMethodsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
GetDeviceMethodsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
GetDeviceMethodsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for GetDeviceMethodsError {
fn code(&self) -> Option<&str> {
GetDeviceMethodsError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl GetDeviceMethodsError {
/// Creates a new `GetDeviceMethodsError`.
pub fn new(kind: GetDeviceMethodsErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `GetDeviceMethodsError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: GetDeviceMethodsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `GetDeviceMethodsError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: GetDeviceMethodsErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `GetDeviceMethodsErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
GetDeviceMethodsErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `GetDeviceMethodsErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
GetDeviceMethodsErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `GetDeviceMethodsErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
GetDeviceMethodsErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for GetDeviceMethodsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
GetDeviceMethodsErrorKind::InternalFailureException(_inner) => Some(_inner),
GetDeviceMethodsErrorKind::InvalidRequestException(_inner) => Some(_inner),
GetDeviceMethodsErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
GetDeviceMethodsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `InitiateDeviceClaim` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct InitiateDeviceClaimError {
/// Kind of error that occurred.
pub kind: InitiateDeviceClaimErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `InitiateDeviceClaim` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum InitiateDeviceClaimErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
#[allow(missing_docs)] // documentation missing in model
ResourceConflictException(crate::error::ResourceConflictException),
#[allow(missing_docs)] // documentation missing in model
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for InitiateDeviceClaimError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
InitiateDeviceClaimErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
InitiateDeviceClaimErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
InitiateDeviceClaimErrorKind::ResourceConflictException(_inner) => _inner.fmt(f),
InitiateDeviceClaimErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
InitiateDeviceClaimErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for InitiateDeviceClaimError {
fn code(&self) -> Option<&str> {
InitiateDeviceClaimError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl InitiateDeviceClaimError {
/// Creates a new `InitiateDeviceClaimError`.
pub fn new(kind: InitiateDeviceClaimErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `InitiateDeviceClaimError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: InitiateDeviceClaimErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `InitiateDeviceClaimError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: InitiateDeviceClaimErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `InitiateDeviceClaimErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
InitiateDeviceClaimErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `InitiateDeviceClaimErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
InitiateDeviceClaimErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `InitiateDeviceClaimErrorKind::ResourceConflictException`.
pub fn is_resource_conflict_exception(&self) -> bool {
matches!(
&self.kind,
InitiateDeviceClaimErrorKind::ResourceConflictException(_)
)
}
/// Returns `true` if the error kind is `InitiateDeviceClaimErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
InitiateDeviceClaimErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for InitiateDeviceClaimError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
InitiateDeviceClaimErrorKind::InternalFailureException(_inner) => Some(_inner),
InitiateDeviceClaimErrorKind::InvalidRequestException(_inner) => Some(_inner),
InitiateDeviceClaimErrorKind::ResourceConflictException(_inner) => Some(_inner),
InitiateDeviceClaimErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
InitiateDeviceClaimErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `InvokeDeviceMethod` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct InvokeDeviceMethodError {
/// Kind of error that occurred.
pub kind: InvokeDeviceMethodErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `InvokeDeviceMethod` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum InvokeDeviceMethodErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
#[allow(missing_docs)] // documentation missing in model
PreconditionFailedException(crate::error::PreconditionFailedException),
#[allow(missing_docs)] // documentation missing in model
RangeNotSatisfiableException(crate::error::RangeNotSatisfiableException),
#[allow(missing_docs)] // documentation missing in model
ResourceConflictException(crate::error::ResourceConflictException),
#[allow(missing_docs)] // documentation missing in model
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for InvokeDeviceMethodError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
InvokeDeviceMethodErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
InvokeDeviceMethodErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
InvokeDeviceMethodErrorKind::PreconditionFailedException(_inner) => _inner.fmt(f),
InvokeDeviceMethodErrorKind::RangeNotSatisfiableException(_inner) => _inner.fmt(f),
InvokeDeviceMethodErrorKind::ResourceConflictException(_inner) => _inner.fmt(f),
InvokeDeviceMethodErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
InvokeDeviceMethodErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for InvokeDeviceMethodError {
fn code(&self) -> Option<&str> {
InvokeDeviceMethodError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl InvokeDeviceMethodError {
/// Creates a new `InvokeDeviceMethodError`.
pub fn new(kind: InvokeDeviceMethodErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `InvokeDeviceMethodError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: InvokeDeviceMethodErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `InvokeDeviceMethodError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: InvokeDeviceMethodErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `InvokeDeviceMethodErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
InvokeDeviceMethodErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `InvokeDeviceMethodErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
InvokeDeviceMethodErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `InvokeDeviceMethodErrorKind::PreconditionFailedException`.
pub fn is_precondition_failed_exception(&self) -> bool {
matches!(
&self.kind,
InvokeDeviceMethodErrorKind::PreconditionFailedException(_)
)
}
/// Returns `true` if the error kind is `InvokeDeviceMethodErrorKind::RangeNotSatisfiableException`.
pub fn is_range_not_satisfiable_exception(&self) -> bool {
matches!(
&self.kind,
InvokeDeviceMethodErrorKind::RangeNotSatisfiableException(_)
)
}
/// Returns `true` if the error kind is `InvokeDeviceMethodErrorKind::ResourceConflictException`.
pub fn is_resource_conflict_exception(&self) -> bool {
matches!(
&self.kind,
InvokeDeviceMethodErrorKind::ResourceConflictException(_)
)
}
/// Returns `true` if the error kind is `InvokeDeviceMethodErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
InvokeDeviceMethodErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for InvokeDeviceMethodError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
InvokeDeviceMethodErrorKind::InternalFailureException(_inner) => Some(_inner),
InvokeDeviceMethodErrorKind::InvalidRequestException(_inner) => Some(_inner),
InvokeDeviceMethodErrorKind::PreconditionFailedException(_inner) => Some(_inner),
InvokeDeviceMethodErrorKind::RangeNotSatisfiableException(_inner) => Some(_inner),
InvokeDeviceMethodErrorKind::ResourceConflictException(_inner) => Some(_inner),
InvokeDeviceMethodErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
InvokeDeviceMethodErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListDeviceEvents` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListDeviceEventsError {
/// Kind of error that occurred.
pub kind: ListDeviceEventsErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `ListDeviceEvents` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListDeviceEventsErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
#[allow(missing_docs)] // documentation missing in model
RangeNotSatisfiableException(crate::error::RangeNotSatisfiableException),
#[allow(missing_docs)] // documentation missing in model
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListDeviceEventsError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListDeviceEventsErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
ListDeviceEventsErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ListDeviceEventsErrorKind::RangeNotSatisfiableException(_inner) => _inner.fmt(f),
ListDeviceEventsErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
ListDeviceEventsErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListDeviceEventsError {
fn code(&self) -> Option<&str> {
ListDeviceEventsError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListDeviceEventsError {
/// Creates a new `ListDeviceEventsError`.
pub fn new(kind: ListDeviceEventsErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListDeviceEventsError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListDeviceEventsErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListDeviceEventsError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListDeviceEventsErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `ListDeviceEventsErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
ListDeviceEventsErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `ListDeviceEventsErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
ListDeviceEventsErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `ListDeviceEventsErrorKind::RangeNotSatisfiableException`.
pub fn is_range_not_satisfiable_exception(&self) -> bool {
matches!(
&self.kind,
ListDeviceEventsErrorKind::RangeNotSatisfiableException(_)
)
}
/// Returns `true` if the error kind is `ListDeviceEventsErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListDeviceEventsErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for ListDeviceEventsError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListDeviceEventsErrorKind::InternalFailureException(_inner) => Some(_inner),
ListDeviceEventsErrorKind::InvalidRequestException(_inner) => Some(_inner),
ListDeviceEventsErrorKind::RangeNotSatisfiableException(_inner) => Some(_inner),
ListDeviceEventsErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
ListDeviceEventsErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListDevices` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListDevicesError {
/// Kind of error that occurred.
pub kind: ListDevicesErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `ListDevices` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListDevicesErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
#[allow(missing_docs)] // documentation missing in model
RangeNotSatisfiableException(crate::error::RangeNotSatisfiableException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListDevicesError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListDevicesErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
ListDevicesErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
ListDevicesErrorKind::RangeNotSatisfiableException(_inner) => _inner.fmt(f),
ListDevicesErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListDevicesError {
fn code(&self) -> Option<&str> {
ListDevicesError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListDevicesError {
/// Creates a new `ListDevicesError`.
pub fn new(kind: ListDevicesErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListDevicesError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListDevicesErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListDevicesError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListDevicesErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `ListDevicesErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
ListDevicesErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `ListDevicesErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(&self.kind, ListDevicesErrorKind::InvalidRequestException(_))
}
/// Returns `true` if the error kind is `ListDevicesErrorKind::RangeNotSatisfiableException`.
pub fn is_range_not_satisfiable_exception(&self) -> bool {
matches!(
&self.kind,
ListDevicesErrorKind::RangeNotSatisfiableException(_)
)
}
}
impl std::error::Error for ListDevicesError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListDevicesErrorKind::InternalFailureException(_inner) => Some(_inner),
ListDevicesErrorKind::InvalidRequestException(_inner) => Some(_inner),
ListDevicesErrorKind::RangeNotSatisfiableException(_inner) => Some(_inner),
ListDevicesErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `ListTagsForResource` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct ListTagsForResourceError {
/// Kind of error that occurred.
pub kind: ListTagsForResourceErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `ListTagsForResource` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum ListTagsForResourceErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for ListTagsForResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
ListTagsForResourceErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
ListTagsForResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
ListTagsForResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for ListTagsForResourceError {
fn code(&self) -> Option<&str> {
ListTagsForResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl ListTagsForResourceError {
/// Creates a new `ListTagsForResourceError`.
pub fn new(kind: ListTagsForResourceErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `ListTagsForResourceError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: ListTagsForResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `ListTagsForResourceError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: ListTagsForResourceErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `ListTagsForResourceErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
ListTagsForResourceErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `ListTagsForResourceErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
ListTagsForResourceErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for ListTagsForResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ListTagsForResourceErrorKind::InternalFailureException(_inner) => Some(_inner),
ListTagsForResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
ListTagsForResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `TagResource` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct TagResourceError {
/// Kind of error that occurred.
pub kind: TagResourceErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `TagResource` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum TagResourceErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
#[allow(missing_docs)] // documentation missing in model
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for TagResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
TagResourceErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
TagResourceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
TagResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
TagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for TagResourceError {
fn code(&self) -> Option<&str> {
TagResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl TagResourceError {
/// Creates a new `TagResourceError`.
pub fn new(kind: TagResourceErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `TagResourceError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: TagResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `TagResourceError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: TagResourceErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `TagResourceErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
TagResourceErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `TagResourceErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(&self.kind, TagResourceErrorKind::InvalidRequestException(_))
}
/// Returns `true` if the error kind is `TagResourceErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
TagResourceErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for TagResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
TagResourceErrorKind::InternalFailureException(_inner) => Some(_inner),
TagResourceErrorKind::InvalidRequestException(_inner) => Some(_inner),
TagResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
TagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `UnclaimDevice` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UnclaimDeviceError {
/// Kind of error that occurred.
pub kind: UnclaimDeviceErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `UnclaimDevice` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UnclaimDeviceErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
#[allow(missing_docs)] // documentation missing in model
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UnclaimDeviceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UnclaimDeviceErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
UnclaimDeviceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
UnclaimDeviceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
UnclaimDeviceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for UnclaimDeviceError {
fn code(&self) -> Option<&str> {
UnclaimDeviceError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl UnclaimDeviceError {
/// Creates a new `UnclaimDeviceError`.
pub fn new(kind: UnclaimDeviceErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `UnclaimDeviceError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UnclaimDeviceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `UnclaimDeviceError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UnclaimDeviceErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `UnclaimDeviceErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
UnclaimDeviceErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `UnclaimDeviceErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
UnclaimDeviceErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `UnclaimDeviceErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UnclaimDeviceErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for UnclaimDeviceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UnclaimDeviceErrorKind::InternalFailureException(_inner) => Some(_inner),
UnclaimDeviceErrorKind::InvalidRequestException(_inner) => Some(_inner),
UnclaimDeviceErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
UnclaimDeviceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `UntagResource` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UntagResourceError {
/// Kind of error that occurred.
pub kind: UntagResourceErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `UntagResource` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UntagResourceErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
#[allow(missing_docs)] // documentation missing in model
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UntagResourceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UntagResourceErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
UntagResourceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
UntagResourceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
UntagResourceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for UntagResourceError {
fn code(&self) -> Option<&str> {
UntagResourceError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl UntagResourceError {
/// Creates a new `UntagResourceError`.
pub fn new(kind: UntagResourceErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `UntagResourceError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UntagResourceErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `UntagResourceError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UntagResourceErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `UntagResourceErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
UntagResourceErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `UntagResourceErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
UntagResourceErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `UntagResourceErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UntagResourceErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for UntagResourceError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UntagResourceErrorKind::InternalFailureException(_inner) => Some(_inner),
UntagResourceErrorKind::InvalidRequestException(_inner) => Some(_inner),
UntagResourceErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
UntagResourceErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
/// Error type for the `UpdateDeviceState` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub struct UpdateDeviceStateError {
/// Kind of error that occurred.
pub kind: UpdateDeviceStateErrorKind,
/// Additional metadata about the error, including error code, message, and request ID.
pub(crate) meta: aws_smithy_types::Error,
}
/// Types of errors that can occur for the `UpdateDeviceState` operation.
#[non_exhaustive]
#[derive(std::fmt::Debug)]
pub enum UpdateDeviceStateErrorKind {
#[allow(missing_docs)] // documentation missing in model
InternalFailureException(crate::error::InternalFailureException),
#[allow(missing_docs)] // documentation missing in model
InvalidRequestException(crate::error::InvalidRequestException),
#[allow(missing_docs)] // documentation missing in model
ResourceNotFoundException(crate::error::ResourceNotFoundException),
/// An unexpected error, e.g. invalid JSON returned by the service or an unknown error code
Unhandled(Box<dyn std::error::Error + Send + Sync + 'static>),
}
impl std::fmt::Display for UpdateDeviceStateError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match &self.kind {
UpdateDeviceStateErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
UpdateDeviceStateErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
UpdateDeviceStateErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
UpdateDeviceStateErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
}
}
impl aws_smithy_types::retry::ProvideErrorKind for UpdateDeviceStateError {
fn code(&self) -> Option<&str> {
UpdateDeviceStateError::code(self)
}
fn retryable_error_kind(&self) -> Option<aws_smithy_types::retry::ErrorKind> {
None
}
}
impl UpdateDeviceStateError {
/// Creates a new `UpdateDeviceStateError`.
pub fn new(kind: UpdateDeviceStateErrorKind, meta: aws_smithy_types::Error) -> Self {
Self { kind, meta }
}
/// Creates the `UpdateDeviceStateError::Unhandled` variant from any error type.
pub fn unhandled(err: impl Into<Box<dyn std::error::Error + Send + Sync + 'static>>) -> Self {
Self {
kind: UpdateDeviceStateErrorKind::Unhandled(err.into()),
meta: Default::default(),
}
}
/// Creates the `UpdateDeviceStateError::Unhandled` variant from a `aws_smithy_types::Error`.
pub fn generic(err: aws_smithy_types::Error) -> Self {
Self {
meta: err.clone(),
kind: UpdateDeviceStateErrorKind::Unhandled(err.into()),
}
}
/// Returns the error message if one is available.
pub fn message(&self) -> Option<&str> {
self.meta.message()
}
/// Returns error metadata, which includes the error code, message,
/// request ID, and potentially additional information.
pub fn meta(&self) -> &aws_smithy_types::Error {
&self.meta
}
/// Returns the request ID if it's available.
pub fn request_id(&self) -> Option<&str> {
self.meta.request_id()
}
/// Returns the error code if it's available.
pub fn code(&self) -> Option<&str> {
self.meta.code()
}
/// Returns `true` if the error kind is `UpdateDeviceStateErrorKind::InternalFailureException`.
pub fn is_internal_failure_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDeviceStateErrorKind::InternalFailureException(_)
)
}
/// Returns `true` if the error kind is `UpdateDeviceStateErrorKind::InvalidRequestException`.
pub fn is_invalid_request_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDeviceStateErrorKind::InvalidRequestException(_)
)
}
/// Returns `true` if the error kind is `UpdateDeviceStateErrorKind::ResourceNotFoundException`.
pub fn is_resource_not_found_exception(&self) -> bool {
matches!(
&self.kind,
UpdateDeviceStateErrorKind::ResourceNotFoundException(_)
)
}
}
impl std::error::Error for UpdateDeviceStateError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
UpdateDeviceStateErrorKind::InternalFailureException(_inner) => Some(_inner),
UpdateDeviceStateErrorKind::InvalidRequestException(_inner) => Some(_inner),
UpdateDeviceStateErrorKind::ResourceNotFoundException(_inner) => Some(_inner),
UpdateDeviceStateErrorKind::Unhandled(_inner) => Some(_inner.as_ref()),
}
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ResourceNotFoundException {
/// <p>404</p>
pub code: std::option::Option<std::string::String>,
/// <p>The requested device could not be found.</p>
pub message: std::option::Option<std::string::String>,
}
impl ResourceNotFoundException {
/// <p>404</p>
pub fn code(&self) -> std::option::Option<&str> {
self.code.as_deref()
}
}
impl std::fmt::Debug for ResourceNotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ResourceNotFoundException");
formatter.field("code", &self.code);
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ResourceNotFoundException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ResourceNotFoundException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ResourceNotFoundException")?;
if let Some(inner_1) = &self.message {
write!(f, ": {}", inner_1)?;
}
Ok(())
}
}
impl std::error::Error for ResourceNotFoundException {}
/// See [`ResourceNotFoundException`](crate::error::ResourceNotFoundException)
pub mod resource_not_found_exception {
/// A builder for [`ResourceNotFoundException`](crate::error::ResourceNotFoundException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) code: std::option::Option<std::string::String>,
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>404</p>
pub fn code(mut self, input: impl Into<std::string::String>) -> Self {
self.code = Some(input.into());
self
}
/// <p>404</p>
pub fn set_code(mut self, input: std::option::Option<std::string::String>) -> Self {
self.code = input;
self
}
/// <p>The requested device could not be found.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
/// <p>The requested device could not be found.</p>
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`ResourceNotFoundException`](crate::error::ResourceNotFoundException)
pub fn build(self) -> crate::error::ResourceNotFoundException {
crate::error::ResourceNotFoundException {
code: self.code,
message: self.message,
}
}
}
}
impl ResourceNotFoundException {
/// Creates a new builder-style object to manufacture [`ResourceNotFoundException`](crate::error::ResourceNotFoundException)
pub fn builder() -> crate::error::resource_not_found_exception::Builder {
crate::error::resource_not_found_exception::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InvalidRequestException {
/// <p>400</p>
pub code: std::option::Option<std::string::String>,
/// <p>The 400 error message returned by the web server.</p>
pub message: std::option::Option<std::string::String>,
}
impl InvalidRequestException {
/// <p>400</p>
pub fn code(&self) -> std::option::Option<&str> {
self.code.as_deref()
}
}
impl std::fmt::Debug for InvalidRequestException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InvalidRequestException");
formatter.field("code", &self.code);
formatter.field("message", &self.message);
formatter.finish()
}
}
impl InvalidRequestException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for InvalidRequestException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InvalidRequestException")?;
if let Some(inner_2) = &self.message {
write!(f, ": {}", inner_2)?;
}
Ok(())
}
}
impl std::error::Error for InvalidRequestException {}
/// See [`InvalidRequestException`](crate::error::InvalidRequestException)
pub mod invalid_request_exception {
/// A builder for [`InvalidRequestException`](crate::error::InvalidRequestException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) code: std::option::Option<std::string::String>,
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>400</p>
pub fn code(mut self, input: impl Into<std::string::String>) -> Self {
self.code = Some(input.into());
self
}
/// <p>400</p>
pub fn set_code(mut self, input: std::option::Option<std::string::String>) -> Self {
self.code = input;
self
}
/// <p>The 400 error message returned by the web server.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
/// <p>The 400 error message returned by the web server.</p>
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`InvalidRequestException`](crate::error::InvalidRequestException)
pub fn build(self) -> crate::error::InvalidRequestException {
crate::error::InvalidRequestException {
code: self.code,
message: self.message,
}
}
}
}
impl InvalidRequestException {
/// Creates a new builder-style object to manufacture [`InvalidRequestException`](crate::error::InvalidRequestException)
pub fn builder() -> crate::error::invalid_request_exception::Builder {
crate::error::invalid_request_exception::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct InternalFailureException {
/// <p>500</p>
pub code: std::option::Option<std::string::String>,
/// <p>The 500 error message returned by the web server.</p>
pub message: std::option::Option<std::string::String>,
}
impl InternalFailureException {
/// <p>500</p>
pub fn code(&self) -> std::option::Option<&str> {
self.code.as_deref()
}
}
impl std::fmt::Debug for InternalFailureException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("InternalFailureException");
formatter.field("code", &self.code);
formatter.field("message", &self.message);
formatter.finish()
}
}
impl InternalFailureException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for InternalFailureException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "InternalFailureException")?;
if let Some(inner_3) = &self.message {
write!(f, ": {}", inner_3)?;
}
Ok(())
}
}
impl std::error::Error for InternalFailureException {}
/// See [`InternalFailureException`](crate::error::InternalFailureException)
pub mod internal_failure_exception {
/// A builder for [`InternalFailureException`](crate::error::InternalFailureException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) code: std::option::Option<std::string::String>,
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>500</p>
pub fn code(mut self, input: impl Into<std::string::String>) -> Self {
self.code = Some(input.into());
self
}
/// <p>500</p>
pub fn set_code(mut self, input: std::option::Option<std::string::String>) -> Self {
self.code = input;
self
}
/// <p>The 500 error message returned by the web server.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
/// <p>The 500 error message returned by the web server.</p>
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`InternalFailureException`](crate::error::InternalFailureException)
pub fn build(self) -> crate::error::InternalFailureException {
crate::error::InternalFailureException {
code: self.code,
message: self.message,
}
}
}
}
impl InternalFailureException {
/// Creates a new builder-style object to manufacture [`InternalFailureException`](crate::error::InternalFailureException)
pub fn builder() -> crate::error::internal_failure_exception::Builder {
crate::error::internal_failure_exception::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct RangeNotSatisfiableException {
/// <p>416</p>
pub code: std::option::Option<std::string::String>,
/// <p>The requested number of results specified by nextToken cannot be satisfied.</p>
pub message: std::option::Option<std::string::String>,
}
impl RangeNotSatisfiableException {
/// <p>416</p>
pub fn code(&self) -> std::option::Option<&str> {
self.code.as_deref()
}
}
impl std::fmt::Debug for RangeNotSatisfiableException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("RangeNotSatisfiableException");
formatter.field("code", &self.code);
formatter.field("message", &self.message);
formatter.finish()
}
}
impl RangeNotSatisfiableException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for RangeNotSatisfiableException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "RangeNotSatisfiableException")?;
if let Some(inner_4) = &self.message {
write!(f, ": {}", inner_4)?;
}
Ok(())
}
}
impl std::error::Error for RangeNotSatisfiableException {}
/// See [`RangeNotSatisfiableException`](crate::error::RangeNotSatisfiableException)
pub mod range_not_satisfiable_exception {
/// A builder for [`RangeNotSatisfiableException`](crate::error::RangeNotSatisfiableException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) code: std::option::Option<std::string::String>,
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>416</p>
pub fn code(mut self, input: impl Into<std::string::String>) -> Self {
self.code = Some(input.into());
self
}
/// <p>416</p>
pub fn set_code(mut self, input: std::option::Option<std::string::String>) -> Self {
self.code = input;
self
}
/// <p>The requested number of results specified by nextToken cannot be satisfied.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
/// <p>The requested number of results specified by nextToken cannot be satisfied.</p>
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`RangeNotSatisfiableException`](crate::error::RangeNotSatisfiableException)
pub fn build(self) -> crate::error::RangeNotSatisfiableException {
crate::error::RangeNotSatisfiableException {
code: self.code,
message: self.message,
}
}
}
}
impl RangeNotSatisfiableException {
/// Creates a new builder-style object to manufacture [`RangeNotSatisfiableException`](crate::error::RangeNotSatisfiableException)
pub fn builder() -> crate::error::range_not_satisfiable_exception::Builder {
crate::error::range_not_satisfiable_exception::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ResourceConflictException {
/// <p>409</p>
pub code: std::option::Option<std::string::String>,
/// <p>An error message explaining the error or its remedy.</p>
pub message: std::option::Option<std::string::String>,
}
impl ResourceConflictException {
/// <p>409</p>
pub fn code(&self) -> std::option::Option<&str> {
self.code.as_deref()
}
}
impl std::fmt::Debug for ResourceConflictException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ResourceConflictException");
formatter.field("code", &self.code);
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ResourceConflictException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ResourceConflictException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ResourceConflictException")?;
if let Some(inner_5) = &self.message {
write!(f, ": {}", inner_5)?;
}
Ok(())
}
}
impl std::error::Error for ResourceConflictException {}
/// See [`ResourceConflictException`](crate::error::ResourceConflictException)
pub mod resource_conflict_exception {
/// A builder for [`ResourceConflictException`](crate::error::ResourceConflictException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) code: std::option::Option<std::string::String>,
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>409</p>
pub fn code(mut self, input: impl Into<std::string::String>) -> Self {
self.code = Some(input.into());
self
}
/// <p>409</p>
pub fn set_code(mut self, input: std::option::Option<std::string::String>) -> Self {
self.code = input;
self
}
/// <p>An error message explaining the error or its remedy.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
/// <p>An error message explaining the error or its remedy.</p>
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`ResourceConflictException`](crate::error::ResourceConflictException)
pub fn build(self) -> crate::error::ResourceConflictException {
crate::error::ResourceConflictException {
code: self.code,
message: self.message,
}
}
}
}
impl ResourceConflictException {
/// Creates a new builder-style object to manufacture [`ResourceConflictException`](crate::error::ResourceConflictException)
pub fn builder() -> crate::error::resource_conflict_exception::Builder {
crate::error::resource_conflict_exception::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct PreconditionFailedException {
/// <p>412</p>
pub code: std::option::Option<std::string::String>,
/// <p>An error message explaining the error or its remedy.</p>
pub message: std::option::Option<std::string::String>,
}
impl PreconditionFailedException {
/// <p>412</p>
pub fn code(&self) -> std::option::Option<&str> {
self.code.as_deref()
}
}
impl std::fmt::Debug for PreconditionFailedException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("PreconditionFailedException");
formatter.field("code", &self.code);
formatter.field("message", &self.message);
formatter.finish()
}
}
impl PreconditionFailedException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for PreconditionFailedException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "PreconditionFailedException")?;
if let Some(inner_6) = &self.message {
write!(f, ": {}", inner_6)?;
}
Ok(())
}
}
impl std::error::Error for PreconditionFailedException {}
/// See [`PreconditionFailedException`](crate::error::PreconditionFailedException)
pub mod precondition_failed_exception {
/// A builder for [`PreconditionFailedException`](crate::error::PreconditionFailedException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) code: std::option::Option<std::string::String>,
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>412</p>
pub fn code(mut self, input: impl Into<std::string::String>) -> Self {
self.code = Some(input.into());
self
}
/// <p>412</p>
pub fn set_code(mut self, input: std::option::Option<std::string::String>) -> Self {
self.code = input;
self
}
/// <p>An error message explaining the error or its remedy.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
/// <p>An error message explaining the error or its remedy.</p>
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`PreconditionFailedException`](crate::error::PreconditionFailedException)
pub fn build(self) -> crate::error::PreconditionFailedException {
crate::error::PreconditionFailedException {
code: self.code,
message: self.message,
}
}
}
}
impl PreconditionFailedException {
/// Creates a new builder-style object to manufacture [`PreconditionFailedException`](crate::error::PreconditionFailedException)
pub fn builder() -> crate::error::precondition_failed_exception::Builder {
crate::error::precondition_failed_exception::Builder::default()
}
}
#[allow(missing_docs)] // documentation missing in model
#[non_exhaustive]
#[derive(std::clone::Clone, std::cmp::PartialEq)]
pub struct ForbiddenException {
/// <p>403</p>
pub code: std::option::Option<std::string::String>,
/// <p>The 403 error message returned by the web server.</p>
pub message: std::option::Option<std::string::String>,
}
impl ForbiddenException {
/// <p>403</p>
pub fn code(&self) -> std::option::Option<&str> {
self.code.as_deref()
}
}
impl std::fmt::Debug for ForbiddenException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut formatter = f.debug_struct("ForbiddenException");
formatter.field("code", &self.code);
formatter.field("message", &self.message);
formatter.finish()
}
}
impl ForbiddenException {
/// Returns the error message.
pub fn message(&self) -> Option<&str> {
self.message.as_deref()
}
}
impl std::fmt::Display for ForbiddenException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ForbiddenException")?;
if let Some(inner_7) = &self.message {
write!(f, ": {}", inner_7)?;
}
Ok(())
}
}
impl std::error::Error for ForbiddenException {}
/// See [`ForbiddenException`](crate::error::ForbiddenException)
pub mod forbidden_exception {
/// A builder for [`ForbiddenException`](crate::error::ForbiddenException)
#[non_exhaustive]
#[derive(std::default::Default, std::clone::Clone, std::cmp::PartialEq, std::fmt::Debug)]
pub struct Builder {
pub(crate) code: std::option::Option<std::string::String>,
pub(crate) message: std::option::Option<std::string::String>,
}
impl Builder {
/// <p>403</p>
pub fn code(mut self, input: impl Into<std::string::String>) -> Self {
self.code = Some(input.into());
self
}
/// <p>403</p>
pub fn set_code(mut self, input: std::option::Option<std::string::String>) -> Self {
self.code = input;
self
}
/// <p>The 403 error message returned by the web server.</p>
pub fn message(mut self, input: impl Into<std::string::String>) -> Self {
self.message = Some(input.into());
self
}
/// <p>The 403 error message returned by the web server.</p>
pub fn set_message(mut self, input: std::option::Option<std::string::String>) -> Self {
self.message = input;
self
}
/// Consumes the builder and constructs a [`ForbiddenException`](crate::error::ForbiddenException)
pub fn build(self) -> crate::error::ForbiddenException {
crate::error::ForbiddenException {
code: self.code,
message: self.message,
}
}
}
}
impl ForbiddenException {
/// Creates a new builder-style object to manufacture [`ForbiddenException`](crate::error::ForbiddenException)
pub fn builder() -> crate::error::forbidden_exception::Builder {
crate::error::forbidden_exception::Builder::default()
}
}
| {
match &self.kind {
DescribeDeviceErrorKind::InternalFailureException(_inner) => _inner.fmt(f),
DescribeDeviceErrorKind::InvalidRequestException(_inner) => _inner.fmt(f),
DescribeDeviceErrorKind::ResourceNotFoundException(_inner) => _inner.fmt(f),
DescribeDeviceErrorKind::Unhandled(_inner) => _inner.fmt(f),
}
} |
ablate_elmo_sub_filter.py | import argparse
from datetime import datetime
from tensorflow.contrib.keras.python.keras.initializers import TruncatedNormal
from docqa import trainer
from docqa.data_processing.qa_training_data import ContextLenKey
from docqa.dataset import ClusteredBatcher
from docqa.encoder import DocumentAndQuestionEncoder, SingleSpanAnswerEncoder, DocumentAndQuestionEncoderWithSubstring
from docqa.evaluator import LossEvaluator, SpanEvaluator
from docqa.elmo.elmo import ElmoLayer
from docqa.elmo.lm_qa_models import AttentionWithElmo, SquadContextConcatSkip
from docqa.model_dir import ModelDir
from docqa.nn.attention import BiAttention, StaticAttentionSelf
from docqa.nn.embedder import FixedWordEmbedder, CharWordEmbedder, LearnedCharEmbedder, LearnedSubstringEmbedder, \
FilteredFixedWordEmbedder
from docqa.nn.layers import FullyConnected, ChainBiMapper, NullBiMapper, MaxPool, Conv1d, SequenceMapperSeq, \
VariationalDropoutLayer, ResidualLayer, ConcatWithProduct, MapperSeq, DropoutLayer
from docqa.nn.recurrent_layers import CudnnGru
from docqa.nn.similarity_layers import TriLinear
from docqa.nn.span_prediction import BoundsPredictor
from docqa.squad.squad_data import SquadCorpus, DocumentQaTrainingData
def main():
|
if __name__ == "__main__":
main() | parser = argparse.ArgumentParser("Train our ELMo model on SQuAD")
parser.add_argument("output_dir")
parser.add_argument("--dim", type=int, default=90)
parser.add_argument("--l2", type=float, default=0)
parser.add_argument("--mode", choices=["input", "output", "both", "none"], default="both")
parser.add_argument("--top_layer_only", action="store_true")
#parser.add_argument("--combination", choices=["x, y", "x * y", "x, y, x * y"], default="x, y")
parser.add_argument("--use_substring", type=str, default="None")
parser.add_argument("--sub_dim", type=int, default=50)
args = parser.parse_args()
print(args)
out = args.output_dir + "-" + datetime.now().strftime("%m%d-%H%M%S")
dim = args.dim
recurrent_layer = CudnnGru(dim, w_init=TruncatedNormal(stddev=0.05))
params = trainer.TrainParams(trainer.SerializableOptimizer("Adadelta", dict(learning_rate=1.0)),
ema=0.999, max_checkpoints_to_keep=2, async_encoding=10,
num_epochs=24, log_period=30, eval_period=1200, save_period=1200,
best_weights=("dev", "b17/text-f1"),
eval_samples=dict(dev=None, train=8000))
lm_reduce = MapperSeq(
ElmoLayer(args.l2, layer_norm=False, top_layer_only=args.top_layer_only),
DropoutLayer(0.5),
)
CharEmbedderCls, EncoderCls = (LearnedCharEmbedder, DocumentAndQuestionEncoder) if args.use_substring == "None" \
else (LearnedSubstringEmbedder, DocumentAndQuestionEncoderWithSubstring)
charEmbedder = CharEmbedderCls(word_size_th=14, char_th=20, char_dim=args.sub_dim, init_scale=0.05, force_cpu=True)
if args.use_substring != None:
charEmbedder._load_substring_vocab(args.use_substring)
final_sub_dim = 100 #if args.combination == "x, y" else 300
model = AttentionWithElmo(
#combination=args.combination,
encoder=EncoderCls(SingleSpanAnswerEncoder()),
lm_model=SquadContextConcatSkip(),
append_before_atten=(args.mode == "both" or args.mode == "output"),
append_embed=(args.mode == "both" or args.mode == "input"),
max_batch_size=128,
word_embed=FilteredFixedWordEmbedder(vec_name="glove.840B.300d", word_vec_init_scale=0, learn_unk=True, cpu=True),
char_embed=CharWordEmbedder(
charEmbedder,
MaxPool(Conv1d(final_sub_dim, 5, 0.8)),
shared_parameters=True
),
embed_mapper=SequenceMapperSeq(
VariationalDropoutLayer(0.8),
recurrent_layer,
VariationalDropoutLayer(0.8),
),
lm_reduce=None,
lm_reduce_shared=lm_reduce,
per_sentence=False,
memory_builder=NullBiMapper(),
attention=BiAttention(TriLinear(bias=True), True),
match_encoder=SequenceMapperSeq(FullyConnected(dim * 2, activation="relu"),
ResidualLayer(SequenceMapperSeq(
VariationalDropoutLayer(0.8),
recurrent_layer,
VariationalDropoutLayer(0.8),
StaticAttentionSelf(TriLinear(bias=True), ConcatWithProduct()),
FullyConnected(dim * 2, activation="relu"),
)),
VariationalDropoutLayer(0.8)),
predictor = BoundsPredictor(ChainBiMapper(
first_layer=recurrent_layer,
second_layer=recurrent_layer
))
)
batcher = ClusteredBatcher(45, ContextLenKey(), False, False)
data = DocumentQaTrainingData(SquadCorpus(), None, batcher, batcher)
with open(__file__, "r") as f:
notes = f.read()
notes = str(sorted(args.__dict__.items(), key=lambda x:x[0])) + "\n" + notes
trainer.start_training(data, model, params,
[LossEvaluator(), SpanEvaluator(bound=[17], text_eval="squad")],
ModelDir(out), notes) |
typeof-vardecl-udt.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
import sys
import os
from clr import *
sys.path.append("..")
import testfuncs
def test(thefile, compilerPath, silent):
'''return number of successes'''
symbols, ok = testfuncs.buildAndGetSymbols(thefile, compilerPath, silent)
if ok:
try:
ok = symbols["Symbol '/g_s'"]['kind'] == 'Variable'
ok = ok and symbols["Symbol '/g_s'"]['type']['core']['name'] == '/S'
if not silent:
if not ok:
print (fg.RED+ "ERR: g_s type could not be validated"+ style.RESET_ALL)
else:
print (style.BRIGHT+ "OK! "+ style.RESET_ALL)
except Exception as e:
print (fg.RED+ "Err: Parsed --dumpsym may lack some expected keys"+ style.RESET_ALL, e)
return ok
result = 0 # to define for sub-tests
resultFailed = 0
def | (compiler, silent, azdxcpath):
global result
global resultFailed
# Working directory should have been set to this script's directory by the calling parent
# You can get it once doTests() is called, but not during initialization of the module,
# because at that time it will still be set to the working directory of the calling script
workDir = os.getcwd()
if test(os.path.join(workDir, "../Semantic/combined-vardecl-udt.azsl"), compiler, silent): result += 1
else: resultFailed += 1
if __name__ == "__main__":
print ("please call from testapp.py")
| doTests |
client_test.go | //+build integration
package tests
import (
"fmt"
"testing"
"time"
"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/resolver"
consul "github.com/mbobakov/grpc-consul-resolver"
)
func TestClient(t *testing.T) {
// Register a new builder with dev logger
resolver.Register(consul.NewBuilder(createLogger(), nil))
conn, err := grpc.Dial(
"consul://127.0.0.1:8500/whoami?wait=14s&tag=public",
grpc.WithInsecure(),
)
if err != nil {
t.Fatal(err)
}
time.Sleep(29 * time.Second)
if err = conn.Close(); err != nil {
t.Fatal(err)
}
}
func createLogger() logr.Logger | {
zapLog, err := zap.NewDevelopment()
if err != nil {
panic(fmt.Sprintf("who watches the watchmen (%v)?", err))
}
return zapr.NewLogger(zapLog)
} |
|
resource_vmxpath.go | package v
import (
"os"
"path"
"path/filepath"
prompt "github.com/c-bata/go-prompt"
"github.com/jeffwubj/escapeshellchar"
homedir "github.com/mitchellh/go-homedir"
)
func GetVMXPathesSuggestions() []prompt.Suggest {
vmxpathes := checkExt(".vmx")
s := make([]prompt.Suggest, len(vmxpathes))
for i := range vmxpathes {
s[i] = prompt.Suggest{
Text: vmxpathes[i],
// Description: vmxpathes[i].Status.StartTime.String(),
}
}
return s
}
func getHomeFolder() string {
home, _ := homedir.Dir()
return home
}
func | (ext string) []string {
home := path.Join(getHomeFolder(), "Virtual Machines.localized")
var files []string
filepath.Walk(home, func(path string, f os.FileInfo, _ error) error {
if !f.IsDir() {
if filepath.Ext(path) == ext {
path = escapeshellchar.EscapeShellString(path)
files = append(files, path)
}
}
return nil
})
return files
}
| checkExt |
helper.go | package reco
import (
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
"strings"
"time"
"github.com/reconfigureio/archiver"
)
// M is a convenience wrapper for map[string]interface{}.
type M map[string]interface{}
// String returns value of key as string.
func (m M) String(key string) string {
return String(m[key])
}
// Int returns value of key as int.
func (m M) Int(key string) int {
return Int(m[key])
}
// Bool returns value of key as bool.
func (m M) Bool(key string) bool {
return Bool(m[key])
}
// HasKey checks if key exists in the map.
func (m M) HasKey(key string) bool {
_, ok := m[key]
return ok
}
// Int returns int value of v if v is an int,
// or 0 otherwise.
func Int(v interface{}) int {
if v1, ok := v.(int); ok {
return v1
}
if v1, ok := v.(string); ok {
n, _ := strconv.Atoi(v1)
return n
}
return 0
}
// String returns string value of v if v is a
// string, or "" otherwise.
func String(v interface{}) string {
if v1, ok := v.(string); ok {
return v1
}
return ""
}
// Bool returns bool value of v if v is a bool,
// or false otherwise.
func Bool(v interface{}) bool {
if v1, ok := v.(bool); ok {
return v1
}
if v1, ok := v.(int); ok {
return v1 > 0
}
if v1, ok := v.(string); ok {
switch strings.ToLower(v1) {
case "1", "true", "yes":
return true
}
}
return false
}
// StringSlice returns strings slice of v
// if v is a string slice, otherwise returns
// nil.
func StringSlice(v interface{}) []string {
if s, ok := v.([]string); ok {
return s
}
return nil
}
// Args is convenience wrapper for []interface
// to fetch element at without wrong index errors.
type Args []interface{}
// At returns element at i.
func (a Args) At(i int) interface{} {
if len(a) <= i {
return nil
}
return a[i]
}
// Last returns last element.
func (a Args) Last() interface{} {
if len(a) > 0 {
return a[len(a)-1]
}
return nil
}
// First returns first element.
func (a Args) First() interface{} {
if len(a) > 0 {
return a[0]
}
return nil
}
func archiveDir(dir string) (string, error) {
tmp, err := tmpDir()
if err != nil |
tmpArchive := path.Join(tmp, "source.tar.gz")
ignoredFiles := []string{
".reco-work",
".reco",
}
files := ignoreFiles(dir, ignoredFiles)
if len(files) == 0 {
return "", fmt.Errorf("'%s' is empty", dir)
}
return tmpArchive, archiver.TarGz.Make(tmpArchive, files)
}
// tmpDir wraps ioutil.TempDir for reco.
func tmpDir() (string, error) {
tmp := "./.reco-work/.tmp"
if err := os.MkdirAll(tmp, os.FileMode(0775)); err != nil {
return "", err
}
return ioutil.TempDir(tmp, "reco")
}
// ignoreFiles returns files in src without ignored.
func ignoreFiles(src string, ignored []string) (fs []string) {
dir, err := os.Open(src)
if err != nil {
return
}
files, err := dir.Readdirnames(-1)
if err != nil {
return
}
for _, file := range files {
found := false
for _, i := range ignored {
if _, f := path.Split(file); f == i {
found = true
break
}
}
if !found {
fs = append(fs, file)
}
}
return
}
type timeRounder time.Duration
// Nearest rounds to the nearest duration and returns the string.
func (t timeRounder) Nearest(d time.Duration) string {
duration := time.Duration(t)
str := "-"
if t > 0 {
// round to duration e.g. sec, min
// easy trick with integer division
duration /= d
duration *= d
str = duration.String()
}
return str
}
| {
return "", err
} |
cuboid.rs | //! Cuboid objects.
use crate::{
coord::{Coord, Direction, Periodic, Translate},
describe::{unwrap_name, Describe},
iterator::{ResidueIter, ResidueIterOut},
system::{Component, Residue},
volume::*,
};
use rand::seq::index::sample;
use serde_derive::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
/// A cuboid shaped volume box.
pub struct Cuboid {
/// Component name.
pub name: Option<String>,
/// Component residue.
pub residue: Option<Residue>,
#[serde(skip)]
/// Origin position of component.
pub origin: Coord,
#[serde(skip)]
/// Size of component (nm).
pub size: Coord,
/// A density may be set for the component.
pub density: Option<f64>,
#[serde(skip)]
/// Residue coordinates of component, relative to its `origin`.
pub coords: Vec<Coord>,
}
impl_component![Cuboid];
impl_translate![Cuboid];
impl Cuboid {
/// Calculate the center position of the cuboid, relative to the origin.
fn center(&self) -> Coord {
Coord {
x: self.size.x / 2.0,
y: self.size.y / 2.0,
z: self.size.z / 2.0,
}
}
/// Calculate the box size.
fn calc_box_size(&self) -> Coord {
self.size
}
/// Construct a `Cylinder` from the cuboid by cutting its coordinates.
/// It will be directed along the default cylinder alignment.
pub fn to_cylinder(&self, radius: f64, height: f64, alignment: Direction) -> Cylinder {
// Check if we need to extend the cube to create the complete cylinder.
let diameter = 2.0 * radius;
let pbc_multiples = match alignment {
Direction::X => (
(height / self.size.x).ceil() as usize,
(diameter / self.size.y).ceil() as usize,
(diameter / self.size.z).ceil() as usize,
),
Direction::Y => (
(diameter / self.size.x).ceil() as usize,
(height / self.size.y).ceil() as usize,
(diameter / self.size.z).ceil() as usize,
),
Direction::Z => (
(diameter / self.size.x).ceil() as usize,
(diameter / self.size.y).ceil() as usize,
(height / self.size.z).ceil() as usize,
),
};
// Closure to calculate the coordinate in the center of the "bottom"
// cuboid face from which the cylinder will be created.
let get_bottom_center = |cuboid: &Cuboid| match alignment {
Direction::X => Coord {
x: 0.0,
..cuboid.center()
},
Direction::Y => Coord {
y: 0.0,
..cuboid.center()
},
Direction::Z => Coord {
z: 0.0,
..cuboid.center()
},
};
let coords = match pbc_multiples {
(1, 1, 1) => {
let bottom_center = get_bottom_center(&self);
cut_to_cylinder(&self.coords, bottom_center, alignment, radius, height)
}
(nx, ny, nz) => {
let extended = self.pbc_multiply(nx, ny, nz);
let bottom_center = get_bottom_center(&extended);
cut_to_cylinder(&extended.coords, bottom_center, alignment, radius, height)
}
};
Cylinder {
name: self.name.clone(),
residue: self.residue.clone(),
origin: self.origin,
radius,
height,
density: self.density,
alignment,
coords,
}
}
/// Construct a `Sphere` from the cuboid by cutting its coordinates.
pub fn to_sphere(&self, radius: f64) -> Spheroid {
// Check whether we need to extend the cuboid to create the full sphere
let diameter = 2.0 * radius;
let pbc_multiples = (
(diameter / self.size.x).ceil() as usize,
(diameter / self.size.y).ceil() as usize,
(diameter / self.size.z).ceil() as usize,
);
let coords = match pbc_multiples {
(1, 1, 1) => cut_to_sphere(&self.coords, self.center(), radius),
(nx, ny, nz) => {
let extended = self.pbc_multiply(nx, ny, nz);
cut_to_sphere(&extended.coords, extended.center(), radius)
}
};
Spheroid {
name: self.name.clone(),
residue: self.residue.clone(),
origin: self.origin,
radius,
density: self.density,
coords,
}
}
}
impl Contains for Cuboid {
fn contains(&self, coord: Coord) -> bool {
let (x, y, z) = coord.to_tuple();
let (x0, y0, z0) = self.origin.to_tuple();
let (x1, y1, z1) = (self.origin + self.size).to_tuple();
x >= x0 && x <= x1 && y >= y0 && y <= y1 && z >= z0 && z <= z1
}
}
impl Default for Cuboid {
fn default() -> Cuboid {
Cuboid {
name: None,
residue: None,
origin: Coord::ORIGO,
size: Coord::ORIGO,
density: None,
coords: vec![],
}
}
}
impl Describe for Cuboid {
fn describe(&self) -> String {
format!(
"{} (Box of size {} at {})",
unwrap_name(&self.name),
self.size,
self.origin
)
}
fn describe_short(&self) -> String {
format!("{} (Box)", unwrap_name(&self.name))
}
}
impl Periodic for Cuboid {
/// Clone cuboid coordinates into PBC multiples.
fn pbc_multiply(&self, nx: usize, ny: usize, nz: usize) -> Cuboid {
let coords = pbc_multiply_volume(&self.coords, self.size, nx, ny, nz);
Cuboid {
origin: self.origin,
size: self.size.pbc_multiply(nx, ny, nz),
coords,
// TODO: Add explicit parameters here
..self.clone()
}
}
}
impl Volume for Cuboid {
fn fill(self, fill_type: FillType) -> Cuboid {
let num_coords = fill_type.to_num_coords(&self);
// To fill the cuboid in a uniform manner, construct a lattice grid which can contain
// the desired number of atoms. Then, select the desired number of cells from this | // Use `ceil` since we want the upper limit of available cells
let nx = (self.size.x / target_cell_length).ceil() as u64;
let ny = (self.size.y / target_cell_length).ceil() as u64;
let nz = (self.size.z / target_cell_length).ceil() as u64;
let num_cells = nx * ny * nz;
let mut rng = rand::thread_rng();
let selected_indices = sample(&mut rng, num_cells as usize, num_coords as usize);
let dx = self.size.x / (nx as f64);
let dy = self.size.y / (ny as f64);
let dz = self.size.z / (nz as f64);
let coords = selected_indices
.into_iter()
.map(|i| {
let ix = i as u64 % nx;
let iy = (i as u64 / nx) % ny;
let iz = i as u64 / (nx * ny);
Coord::new(
dx * (ix as f64 + 0.5),
dy * (iy as f64 + 0.5),
dz * (iz as f64 + 0.5),
)
})
.collect::<Vec<_>>();
let density = Some((num_coords as f64) / self.volume());
Cuboid {
density,
coords,
..self
}
}
fn volume(&self) -> f64 {
self.size.x * self.size.y * self.size.z
}
}
#[cfg(test)]
mod tests {
use super::*;
fn setup_cuboid(dx: f64, dy: f64, dz: f64, spacing: f64) -> Cuboid {
let mut coords = Vec::new();
let mut x = 0.0;
while x < dx - spacing {
let mut y = 0.0;
while y < dy - spacing {
let mut z = 0.0;
while z < dz - spacing {
coords.push(Coord::new(x, y, z));
z += spacing;
}
y += spacing;
}
x += spacing;
}
Cuboid {
size: Coord::new(dx, dy, dz),
coords,
..Cuboid::default()
}
}
#[test]
fn translate_a_cuboid() {
let translate = Coord::new(1.0, 2.0, 3.0);
let cuboid = setup_cuboid(0.0, 0.0, 0.0, 0.0).translate(translate);
assert_eq!(translate, cuboid.origin);
}
#[test]
fn calculate_cuboid_center() {
let cuboid = setup_cuboid(1.0, 1.0, 1.0, 0.1);
let center = Coord::new(0.5, 0.5, 0.5);
assert_eq!(center, cuboid.center());
}
#[test]
fn translated_cuboid_center_is_correct() {
let translate = Coord::new(1.0, 1.0, 1.0);
let cuboid = setup_cuboid(1.0, 1.0, 1.0, 0.1).translate(translate);
let center = Coord::new(0.5, 0.5, 0.5);
assert_eq!(center, cuboid.center());
}
#[test]
fn calc_box_size_of_cuboid() {
let cuboid = setup_cuboid(1.0, 2.0, 3.0, 0.1);
assert_eq!(Coord::new(1.0, 2.0, 3.0), cuboid.calc_box_size());
}
#[test]
fn cuboid_into_cylinder() {
let translate = Coord::new(1.0, 2.0, 3.0);
let cuboid = setup_cuboid(10.0, 10.0, 10.0, 1.0).translate(translate);
let radius = 2.5;
let height = 8.0;
let alignment = Direction::Z;
let cylinder = cuboid.to_cylinder(radius, height, alignment);
assert!(cylinder.coords.len() > 0);
assert_eq!(cuboid.origin, cylinder.origin);
for coord in cylinder.coords {
let (dr, dh) = Coord::ORIGO.distance_cylindrical(coord, alignment);
assert!(dr <= radius);
assert!(dh >= 0.0 && dh <= height);
}
}
#[test]
fn cuboid_to_cylinder_keeps_an_expected_number_of_coordinates() {
let density = 100.0;
let radius = 2.5;
let diameter = radius * 2.0;
let cuboid = Cuboid {
// size: Coord::new(1.0 * diameter, diameter, diameter),
size: Coord::new(radius, radius, radius),
..Cuboid::default()
}
.fill(FillType::Density(density));
let cylinder = cuboid.to_cylinder(radius, diameter, Direction::X);
let expected_coords = (cylinder.volume() * density).round() as usize;
let ratio = cylinder.coords.len() as f64 / expected_coords as f64;
assert!(ratio >= 0.95 && ratio <= 1.05);
}
#[test]
fn cuboid_expands_to_create_full_cylinder_if_too_small() {
let cuboid = setup_cuboid(10.0, 10.0, 10.0, 1.0);
let too_large_radius = 10.0;
let too_large_height = 15.0;
let alignment = Direction::Z;
let large_cylinder = cuboid.to_cylinder(too_large_radius, too_large_height, alignment);
assert!(large_cylinder.coords.len() > cuboid.coords.len());
}
#[test]
fn cuboid_into_sphere() {
let translate = Coord::new(1.0, 2.0, 3.0);
let cuboid = setup_cuboid(10.0, 10.0, 10.0, 1.0).translate(translate);
let radius = 5.0;
let sphere = cuboid.to_sphere(radius);
assert!(sphere.coords.len() > 0);
assert_eq!(cuboid.origin, sphere.origin);
for coord in sphere.coords {
assert!(coord.distance(Coord::ORIGO) <= radius);
}
}
#[test]
fn cuboid_expands_to_create_full_sphere_if_too_small() {
let cuboid = setup_cuboid(10.0, 10.0, 10.0, 1.0);
let too_large_radius = 10.0;
let large_sphere = cuboid.to_sphere(too_large_radius);
assert!(large_sphere.coords.len() > cuboid.coords.len());
}
#[test]
fn create_periodic_multiple_of_cuboid() {
let cuboid = Cuboid {
size: Coord::new(2.0, 2.0, 2.0),
coords: vec![Coord::new(0.5, 1.0, 1.5)],
..Cuboid::default()
};
let cuboid_octupled = cuboid.pbc_multiply(2, 2, 2);
assert_eq!(8 * cuboid.coords.len(), cuboid_octupled.coords.len());
let expected_coords = vec![
Coord::new(0.5, 1.0, 1.5), // base coordinate (1, 1, 1)
Coord::new(0.5, 1.0, 3.5), // (1, 1, 2)
Coord::new(0.5, 3.0, 1.5), // (1, 2, 1)
Coord::new(0.5, 3.0, 3.5), // (1, 2, 2)
Coord::new(2.5, 1.0, 1.5), // (2, 1, 1)
Coord::new(2.5, 1.0, 3.5), // (2, 1, 2)
Coord::new(2.5, 3.0, 1.5), // (2, 2, 1)
Coord::new(2.5, 3.0, 3.5), // (2, 2, 2)
];
for coord in expected_coords {
assert!(cuboid_octupled.coords.contains(&coord));
}
}
#[test]
fn create_no_added_periodic_multiples_of_cuboid_just_clones() {
let cuboid = Cuboid {
size: Coord::new(2.0, 2.0, 2.0),
coords: vec![Coord::new(0.5, 1.0, 1.5)],
..Cuboid::default()
};
let cloned_cuboid = cuboid.pbc_multiply(1, 1, 1);
assert_eq!(cuboid.origin, cloned_cuboid.origin);
assert_eq!(cuboid.size, cloned_cuboid.size);
assert_eq!(cuboid.coords, cloned_cuboid.coords);
}
#[test]
fn cuboid_contains_coordinates_in_absolute_space() {
let cuboid = Cuboid {
origin: Coord::new(1.0, 1.0, 1.0),
size: Coord::new(1.0, 1.0, 1.0),
..Cuboid::default()
};
let err = 1e-9;
// Inside
assert!(cuboid.contains(Coord::new(1.0 + err, 1.0 + err, 1.0 + err)));
assert!(cuboid.contains(Coord::new(2.0 - err, 2.0 - err, 2.0 - err)));
// Outside
assert!(!cuboid.contains(Coord::new(1.0 - err, 1.0 + err, 1.0 + err)));
assert!(!cuboid.contains(Coord::new(1.0 + err, 1.0 - err, 1.0 + err)));
assert!(!cuboid.contains(Coord::new(1.0 + err, 1.0 + err, 1.0 - err)));
// Outside
assert!(!cuboid.contains(Coord::new(2.0 + err, 2.0 - err, 2.0 - err)));
assert!(!cuboid.contains(Coord::new(2.0 - err, 2.0 + err, 2.0 - err)));
assert!(!cuboid.contains(Coord::new(2.0 - err, 2.0 - err, 2.0 + err)));
}
#[test]
fn density_is_set_after_fill() {
let num_atoms = 1000;
let size = Coord::new(1.0, 2.0, 3.0);
let cuboid = Cuboid {
size,
..Cuboid::default()
}
.fill(FillType::NumCoords(num_atoms));
assert_eq!(cuboid.coords.len(), num_atoms as usize);
let volume = size.x * size.y * size.z;
let expected_density = num_atoms as f64 / volume;
let density = cuboid.density.unwrap();
let ratio = density / expected_density;
assert!(ratio >= 0.9 && ratio <= 1.1);
}
#[test]
fn cuboid_volume_is_correct() {
let cuboid = Cuboid {
size: Coord::new(1.0, 3.0, 7.0),
..Cuboid::default()
};
assert_eq!(cuboid.volume(), 1.0 * 3.0 * 7.0);
}
#[test]
fn cuboid_center_calculation_is_correct() {
let size = Coord::new(1.0, 7.0, 13.0);
let cuboid = Cuboid {
size,
..Cuboid::default()
};
assert_eq!(
cuboid.center(),
Coord::new(size.x / 2.0, size.y / 2.0, size.z / 2.0)
);
}
} | // list and add their corresponding coordinate.
let cell_volume = self.volume() / (num_coords as f64);
let target_cell_length = cell_volume.powf(1.0 / 3.0);
|
serialize.py | import json, uuid
from datetime import datetime, date
from decimal import Decimal
from werkzeug.http import http_date
from django.db.models import Model
from django.db.models.base import ModelBase
from django.db.models.query import QuerySet, ValuesQuerySet
from django.db.models.fields.related import ManyToManyField
from uppsell.models import Urn
def model_to_dict(instance):
"""Like django.forms.models.model_to_dict, but returns everything
including non-editable fields"""
opts, data = instance._meta, {}
for f in opts.concrete_fields + opts.many_to_many:
if isinstance(f, ManyToManyField):
if instance.pk is None:
data[f.name] = []
else:
data[f.name] = list(f.value_from_object(instance).values_list('pk', flat=True))
else:
data[f.name] = f.value_from_object(instance)
return data
class UppsellJSONEncoder(json.JSONEncoder):
| def default(self, obj):
if isinstance(obj, (Model, ModelBase)):
return model_to_dict(obj)
if isinstance(obj, (QuerySet, ValuesQuerySet)):
return [model_to_dict(m) for m in obj]
elif isinstance(obj, datetime):
return obj.isoformat("T")
elif isinstance(obj, date):
return obj.isoformat()
elif isinstance(obj, Decimal):
return float(obj)
elif isinstance(obj, Urn) or isinstance(obj, uuid.UUID):
return str(obj)
return json.JSONEncoder.default(self, obj) |
|
manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
|
if __name__ == '__main__':
main()
| os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'test_mobile_33934.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv) |
__init__.py | '''
.. module:: skrf.io
========================================
io (:mod:`skrf.io`)
========================================
This Package provides functions and objects for input/output.
The general functions :func:`~general.read` and :func:`~general.write`
can be used to read and write [almost] any skrf object to disk, using the
:mod:`pickle` module.
Reading and writing touchstone files is supported through the
:class:`~touchstone.Touchstone` class, which can be more easily used
through the Network constructor, :func:`~skrf.network.Network.__init__`
.. automodule:: skrf.io.general
.. automodule:: skrf.io.touchstone
.. automodule:: skrf.io.csv
'''
import general
import csv | import touchstone
from general import *
from csv import *
from touchstone import * | |
cqr.go | package backend
import (
"encoding/json"
"github.com/hscells/cqr"
"github.com/hscells/transmute/ir"
)
// CommonQueryRepresentationQuery is the transmute wrapper for CQR.
type CommonQueryRepresentationQuery struct {
repr cqr.CommonQueryRepresentation
}
// CommonQueryRepresentationBackend is the backend for compiling transmute ir into CQR.
type CommonQueryRepresentationBackend struct{}
// Representation returns the CQR.
func (q CommonQueryRepresentationQuery) Representation() (interface{}, error) {
return q.repr, nil
}
// String returns a JSON-encoded representation of the cqr.
func (q CommonQueryRepresentationQuery) String() (string, error) {
b, err := json.Marshal(q.repr)
return string(b), err
}
// StringPretty returns a pretty-printed JSON-encoded representation of the cqr.
func (q CommonQueryRepresentationQuery) StringPretty() (string, error) {
b, err := json.MarshalIndent(q.repr, "", " ")
return string(b), err
}
// Compile transforms the transmute ir into CQR. The CQR is slightly different to the transmute ir, in that the
// depth of the children is different. Take note of how the children of a transmute ir differs from the children of CQR.
func (b CommonQueryRepresentationBackend) Compile(q ir.BooleanQuery) (BooleanQuery, error) {
var children []cqr.CommonQueryRepresentation
for _, keyword := range q.Keywords {
k := cqr.NewKeyword(keyword.QueryString, keyword.Fields...)
k.Options = keyword.Options
if k.Options == nil {
k.Options = make(map[string]interface{})
} | children = append(children, k)
}
for _, child := range q.Children {
var subChildren []cqr.CommonQueryRepresentation
for _, subChild := range child.Children {
c, err := b.Compile(subChild)
if err != nil {
return nil, err
}
cqrSub := c.(CommonQueryRepresentationQuery).repr
subChildren = append(subChildren, cqrSub)
}
for _, keyword := range child.Keywords {
k := cqr.NewKeyword(keyword.QueryString, keyword.Fields...).
SetOption(cqr.ExplodedString, keyword.Exploded).
SetOption(cqr.TruncatedString, keyword.Truncated).(cqr.Keyword)
//if !keyword.Exploded {
// delete(k.Options, cqr.ExplodedString)
//}
//if !keyword.Truncated {
// delete(k.Options, cqr.TruncatedString)
//}
subChildren = append(subChildren, k)
}
if len(child.Operator) == 0 {
children = append(children, subChildren...)
} else {
bq := cqr.NewBooleanQuery(child.Operator, subChildren)
for k, v := range child.Options {
bq.SetOption(k, v)
}
children = append(children, bq)
}
}
var repr cqr.CommonQueryRepresentation
if len(q.Operator) == 0 && len(q.Children) == 1 {
var keywords []cqr.CommonQueryRepresentation
for _, kw := range q.Children[0].Keywords {
keywords = append(keywords, cqr.NewKeyword(kw.QueryString, kw.Fields...).SetOption(cqr.ExplodedString, kw.Exploded).SetOption(cqr.TruncatedString, kw.Truncated))
}
for _, child := range q.Children[0].Children {
keyword, err := b.Compile(child)
if err != nil {
return nil, err
}
keywords = append(keywords, keyword.(CommonQueryRepresentationQuery).repr)
}
repr = cqr.NewBooleanQuery(q.Children[0].Operator, keywords)
} else {
repr = cqr.NewBooleanQuery(q.Operator, children)
}
for k, v := range q.Options {
repr.SetOption(k, v)
}
return CommonQueryRepresentationQuery{repr: repr}, nil
}
// NewCQRBackend returns a new CQR backend.
func NewCQRBackend() CommonQueryRepresentationBackend {
return CommonQueryRepresentationBackend{}
}
func NewCQRQuery(query cqr.CommonQueryRepresentation) CommonQueryRepresentationQuery {
return CommonQueryRepresentationQuery{repr: query}
} | k = k.SetOption(cqr.ExplodedString, keyword.Exploded).SetOption(cqr.TruncatedString, keyword.Truncated).(cqr.Keyword) |
copy-emails.js | const path = require('path');
const fs = require('fs');
// copy files in DOCS (examples):
// from: semcore/email/.tmp/badge/examples/index.html
// top website/docs/product-emails/badge-email/examples/badge-index.html
(function() {
const buildFolderName = '.tmp';
const rootSourceTemplate = path.join(__dirname, `../semcore/email/${buildFolderName}`);
function getDirectories(source) {
return fs
.readdirSync(source, { withFileTypes: true })
.filter((dirent) => dirent.isDirectory())
.map((dirent) => dirent.name);
}
function getPathFileInDocs(componentName, fileName) {
return path.join(
__dirname,
'docs/product-emails/',
`${componentName}-email`,
'examples',
`${componentName}-${fileName}.html`,
);
}
function readAndWriteFilesInDocs(componentName) {
const pathDirecoryExample = path.join(rootSourceTemplate, componentName, 'examples');
if (!fs.existsSync(pathDirecoryExample)) return; | const fileName = file.replace(/.html/, '');
const data = fs.readFileSync(path.join(pathDirecoryExample, file), { encoding: 'utf-8' });
fs.writeFileSync(getPathFileInDocs(componentName, fileName), data);
});
}
const components = getDirectories(rootSourceTemplate);
components.forEach((componentName) => {
readAndWriteFilesInDocs(componentName);
});
})(); | fs.readdirSync(pathDirecoryExample).forEach((file) => { |
_utils.py | """Utility functions used by PyTorch algorithms."""
import torch
import torch.nn.functional as F
class _Default: # pylint: disable=too-few-public-methods
"""A wrapper class to represent default arguments.
Args:
val (object): Argument value.
"""
def __init__(self, val):
self.val = val
def make_optimizer(optimizer_type, module, **kwargs):
"""Create an optimizer for PyTorch algos.
Args:
optimizer_type (Union[type, tuple[type, dict]]): Type of optimizer.
This can be an optimizer type such as 'torch.optim.Adam' or a
tuple of type and dictionary, where dictionary contains arguments
to initialize the optimizer e.g. (torch.optim.Adam, {'lr' = 1e-3})
module (torch.nn.Module): The module whose parameters needs to be
optimized. | Returns:
torch.optim.Optimizer: Constructed optimizer.
Raises:
ValueError: Raises value error when `optimizer_type` is tuple, and
non-default argument is passed in `kwargs`.
"""
if isinstance(optimizer_type, tuple):
opt_type, opt_args = optimizer_type
for name, arg in kwargs.items():
if not isinstance(arg, _Default):
raise ValueError('Should not specify {} and explicit \
optimizer args at the same time'.format(name))
return opt_type(module.parameters(), **opt_args)
opt_args = {}
for name, arg in kwargs.items():
if isinstance(arg, _Default):
opt_args[name] = arg.val
else:
opt_args[name] = arg
return optimizer_type(module.parameters(), **opt_args)
def compute_advantages(discount, gae_lambda, max_path_length, baselines,
rewards):
"""Calculate advantages.
Advantages are a discounted cumulative sum.
Calculate advantages using a baseline (value function) according to
Generalized Advantage Estimation (GAE)
The discounted cumulative sum can be computed using conv2d with filter.
filter:
[1, (discount * gae_lambda), (discount * gae_lambda) ^ 2, ...]
where the length is same with max_path_length.
baselines and rewards are also has same shape.
baselines:
[ [b_11, b_12, b_13, ... b_1n],
[b_21, b_22, b_23, ... b_2n],
...
[b_m1, b_m2, b_m3, ... b_mn] ]
rewards:
[ [r_11, r_12, r_13, ... r_1n],
[r_21, r_22, r_23, ... r_2n],
...
[r_m1, r_m2, r_m3, ... r_mn] ]
Args:
discount (float): RL discount factor (i.e. gamma).
gae_lambda (float): Lambda, as used for Generalized Advantage
Estimation (GAE).
max_path_length (int): Maximum length of a single rollout.
baselines (torch.Tensor): A 2D vector of value function estimates with
shape (N, T), where N is the batch dimension (number of episodes)
and T is the maximum path length experienced by the agent. If an
episode terminates in fewer than T time steps, the remaining
elements in that episode should be set to 0.
rewards (torch.Tensor): A 2D vector of per-step rewards with shape
(N, T), where N is the batch dimension (number of episodes) and T
is the maximum path length experienced by the agent. If an episode
terminates in fewer than T time steps, the remaining elements in
that episode should be set to 0.
Returns:
torch.Tensor: A 2D vector of calculated advantage values with shape
(N, T), where N is the batch dimension (number of episodes) and T
is the maximum path length experienced by the agent. If an episode
terminates in fewer than T time steps, the remaining values in that
episode should be set to 0.
"""
adv_filter = torch.full((1, 1, 1, max_path_length - 1),
discount * gae_lambda)
adv_filter = torch.cumprod(F.pad(adv_filter, (1, 0), value=1), dim=-1)
deltas = (rewards + discount * F.pad(baselines, (0, 1))[:, 1:] - baselines)
deltas = F.pad(deltas, (0, max_path_length - 1)).unsqueeze(0).unsqueeze(0)
advantages = F.conv2d(deltas, adv_filter, stride=1).squeeze()
return advantages
def pad_to_last(nums, total_length, axis=-1, val=0):
"""Pad val to last in nums in given axis.
length of the result in given axis should be total_length.
Raises:
IndexError: If the input axis value is out of range of the nums array
Args:
nums (numpy.ndarray): The array to pad.
total_length (int): The final width of the Array.
axis (int): Axis along which a sum is performed.
val (int): The value to set the padded value.
Returns:
torch.Tensor: Padded array
"""
tensor = torch.Tensor(nums)
axis = (axis + len(tensor.shape)) if axis < 0 else axis
if len(tensor.shape) <= axis:
raise IndexError('axis {} is out of range {}'.format(
axis, tensor.shape))
padding_config = [0, 0] * len(tensor.shape)
padding_idx = abs(axis - len(tensor.shape)) * 2 - 1
padding_config[padding_idx] = max(total_length - tensor.shape[axis], val)
return F.pad(tensor, padding_config)
def filter_valids(tensor, valids):
"""Filter out tensor using valids (last index of valid tensors).
valids contains last indices of each rows.
Args:
tensor (torch.Tensor): The tensor to filter
valids (list[int]): Array of length of the valid values
Returns:
torch.Tensor: Filtered Tensor
"""
return [tensor[i][:valids[i]] for i in range(len(valids))] | kwargs (dict): Other keyword arguments to initialize optimizer. This
is not used when `optimizer_type` is tuple.
|
task_group.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 .task_definition import TaskDefinition
class TaskGroup(TaskDefinition):
"""TaskGroup.
:param agent_execution:
:type agent_execution: :class:`TaskExecution <task-agent.v4_0.models.TaskExecution>`
:param author:
:type author: str
:param category:
:type category: str
:param contents_uploaded:
:type contents_uploaded: bool
:param contribution_identifier:
:type contribution_identifier: str
:param contribution_version:
:type contribution_version: str
:param data_source_bindings:
:type data_source_bindings: list of :class:`DataSourceBinding <task-agent.v4_0.models.DataSourceBinding>`
:param definition_type:
:type definition_type: str
:param demands:
:type demands: list of :class:`object <task-agent.v4_0.models.object>`
:param deprecated:
:type deprecated: bool
:param description:
:type description: str
:param disabled:
:type disabled: bool
:param execution:
:type execution: dict
:param friendly_name:
:type friendly_name: str
:param groups:
:type groups: list of :class:`TaskGroupDefinition <task-agent.v4_0.models.TaskGroupDefinition>`
:param help_mark_down:
:type help_mark_down: str
:param host_type:
:type host_type: str
:param icon_url:
:type icon_url: str
:param id:
:type id: str
:param inputs:
:type inputs: list of :class:`TaskInputDefinition <task-agent.v4_0.models.TaskInputDefinition>`
:param instance_name_format:
:type instance_name_format: str
:param minimum_agent_version:
| :type minimum_agent_version: str
:param name:
:type name: str
:param output_variables:
:type output_variables: list of :class:`TaskOutputVariable <task-agent.v4_0.models.TaskOutputVariable>`
:param package_location:
:type package_location: str
:param package_type:
:type package_type: str
:param preview:
:type preview: bool
:param release_notes:
:type release_notes: str
:param runs_on:
:type runs_on: list of str
:param satisfies:
:type satisfies: list of str
:param server_owned:
:type server_owned: bool
:param source_definitions:
:type source_definitions: list of :class:`TaskSourceDefinition <task-agent.v4_0.models.TaskSourceDefinition>`
:param source_location:
:type source_location: str
:param version:
:type version: :class:`TaskVersion <task-agent.v4_0.models.TaskVersion>`
:param visibility:
:type visibility: list of str
:param comment: Gets or sets comment.
:type comment: str
:param created_by: Gets or sets the identity who created.
:type created_by: :class:`IdentityRef <task-agent.v4_0.models.IdentityRef>`
:param created_on: Gets or sets date on which it got created.
:type created_on: datetime
:param deleted: Gets or sets as 'true' to indicate as deleted, 'false' otherwise.
:type deleted: bool
:param modified_by: Gets or sets the identity who modified.
:type modified_by: :class:`IdentityRef <task-agent.v4_0.models.IdentityRef>`
:param modified_on: Gets or sets date on which it got modified.
:type modified_on: datetime
:param owner: Gets or sets the owner.
:type owner: str
:param parent_definition_id: Gets or sets parent task group Id. This is used while creating a draft task group.
:type parent_definition_id: str
:param revision: Gets or sets revision.
:type revision: int
:param tasks:
:type tasks: list of :class:`TaskGroupStep <task-agent.v4_0.models.TaskGroupStep>`
"""
_attribute_map = {
'agent_execution': {'key': 'agentExecution', 'type': 'TaskExecution'},
'author': {'key': 'author', 'type': 'str'},
'category': {'key': 'category', 'type': 'str'},
'contents_uploaded': {'key': 'contentsUploaded', 'type': 'bool'},
'contribution_identifier': {'key': 'contributionIdentifier', 'type': 'str'},
'contribution_version': {'key': 'contributionVersion', 'type': 'str'},
'data_source_bindings': {'key': 'dataSourceBindings', 'type': '[DataSourceBinding]'},
'definition_type': {'key': 'definitionType', 'type': 'str'},
'demands': {'key': 'demands', 'type': '[object]'},
'deprecated': {'key': 'deprecated', 'type': 'bool'},
'description': {'key': 'description', 'type': 'str'},
'disabled': {'key': 'disabled', 'type': 'bool'},
'execution': {'key': 'execution', 'type': '{object}'},
'friendly_name': {'key': 'friendlyName', 'type': 'str'},
'groups': {'key': 'groups', 'type': '[TaskGroupDefinition]'},
'help_mark_down': {'key': 'helpMarkDown', 'type': 'str'},
'host_type': {'key': 'hostType', 'type': 'str'},
'icon_url': {'key': 'iconUrl', 'type': 'str'},
'id': {'key': 'id', 'type': 'str'},
'inputs': {'key': 'inputs', 'type': '[TaskInputDefinition]'},
'instance_name_format': {'key': 'instanceNameFormat', 'type': 'str'},
'minimum_agent_version': {'key': 'minimumAgentVersion', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'output_variables': {'key': 'outputVariables', 'type': '[TaskOutputVariable]'},
'package_location': {'key': 'packageLocation', 'type': 'str'},
'package_type': {'key': 'packageType', 'type': 'str'},
'preview': {'key': 'preview', 'type': 'bool'},
'release_notes': {'key': 'releaseNotes', 'type': 'str'},
'runs_on': {'key': 'runsOn', 'type': '[str]'},
'satisfies': {'key': 'satisfies', 'type': '[str]'},
'server_owned': {'key': 'serverOwned', 'type': 'bool'},
'source_definitions': {'key': 'sourceDefinitions', 'type': '[TaskSourceDefinition]'},
'source_location': {'key': 'sourceLocation', 'type': 'str'},
'version': {'key': 'version', 'type': 'TaskVersion'},
'visibility': {'key': 'visibility', 'type': '[str]'},
'comment': {'key': 'comment', 'type': 'str'},
'created_by': {'key': 'createdBy', 'type': 'IdentityRef'},
'created_on': {'key': 'createdOn', 'type': 'iso-8601'},
'deleted': {'key': 'deleted', 'type': 'bool'},
'modified_by': {'key': 'modifiedBy', 'type': 'IdentityRef'},
'modified_on': {'key': 'modifiedOn', 'type': 'iso-8601'},
'owner': {'key': 'owner', 'type': 'str'},
'parent_definition_id': {'key': 'parentDefinitionId', 'type': 'str'},
'revision': {'key': 'revision', 'type': 'int'},
'tasks': {'key': 'tasks', 'type': '[TaskGroupStep]'}
}
def __init__(self, agent_execution=None, author=None, category=None, contents_uploaded=None, contribution_identifier=None, contribution_version=None, data_source_bindings=None, definition_type=None, demands=None, deprecated=None, description=None, disabled=None, execution=None, friendly_name=None, groups=None, help_mark_down=None, host_type=None, icon_url=None, id=None, inputs=None, instance_name_format=None, minimum_agent_version=None, name=None, output_variables=None, package_location=None, package_type=None, preview=None, release_notes=None, runs_on=None, satisfies=None, server_owned=None, source_definitions=None, source_location=None, version=None, visibility=None, comment=None, created_by=None, created_on=None, deleted=None, modified_by=None, modified_on=None, owner=None, parent_definition_id=None, revision=None, tasks=None):
super(TaskGroup, self).__init__(agent_execution=agent_execution, author=author, category=category, contents_uploaded=contents_uploaded, contribution_identifier=contribution_identifier, contribution_version=contribution_version, data_source_bindings=data_source_bindings, definition_type=definition_type, demands=demands, deprecated=deprecated, description=description, disabled=disabled, execution=execution, friendly_name=friendly_name, groups=groups, help_mark_down=help_mark_down, host_type=host_type, icon_url=icon_url, id=id, inputs=inputs, instance_name_format=instance_name_format, minimum_agent_version=minimum_agent_version, name=name, output_variables=output_variables, package_location=package_location, package_type=package_type, preview=preview, release_notes=release_notes, runs_on=runs_on, satisfies=satisfies, server_owned=server_owned, source_definitions=source_definitions, source_location=source_location, version=version, visibility=visibility)
self.comment = comment
self.created_by = created_by
self.created_on = created_on
self.deleted = deleted
self.modified_by = modified_by
self.modified_on = modified_on
self.owner = owner
self.parent_definition_id = parent_definition_id
self.revision = revision
self.tasks = tasks | |
open.go | // Copyright 2018 The go-hep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package open contains the structures describing request and response for open request.
// See xrootd protocol specification (http://xrootd.org/doc/dev45/XRdv310.pdf, p. 63) for details.
package open // import "go-hep.org/x/hep/xrootd/xrdproto/open"
import (
"go-hep.org/x/hep/xrootd/internal/xrdenc"
"go-hep.org/x/hep/xrootd/xrdfs"
"go-hep.org/x/hep/xrootd/xrdproto"
)
// RequestID is the id of the request, it is sent as part of message.
// See xrootd protocol specification for details: http://xrootd.org/doc/dev45/XRdv310.pdf, 2.3 Client Request Format.
const RequestID uint16 = 3010
// Response is a response for the open request,
// which contains the file handle, the compression page size,
// the compression type and the stat information.
type Response struct {
FileHandle xrdfs.FileHandle
Compression *xrdfs.FileCompression
Stat *xrdfs.EntryStat
}
// MarshalXrd implements xrdproto.Marshaler.
func (o Response) MarshalXrd(wBuffer *xrdenc.WBuffer) error {
wBuffer.WriteBytes(o.FileHandle[:])
if o.Compression == nil {
return nil
}
if err := o.Compression.MarshalXrd(wBuffer); err != nil {
return err
}
if o.Stat == nil {
return nil
}
if err := o.Stat.MarshalXrd(wBuffer); err != nil {
return err
}
return nil
}
// UnmarshalXrd implements xrdproto.Unmarshaler.
func (o *Response) UnmarshalXrd(rBuffer *xrdenc.RBuffer) error {
rBuffer.ReadBytes(o.FileHandle[:])
if rBuffer.Len() == 0 {
return nil
}
o.Compression = &xrdfs.FileCompression{}
if err := o.Compression.UnmarshalXrd(rBuffer); err != nil {
return err
}
if rBuffer.Len() == 0 {
return nil
}
o.Stat = &xrdfs.EntryStat{}
if err := o.Stat.UnmarshalXrd(rBuffer); err != nil {
return err
}
return nil
}
// RespID implements xrdproto.Response.RespID.
func (resp *Response) RespID() uint16 { return RequestID }
// Request holds open request parameters.
type Request struct {
Mode xrdfs.OpenMode
Options xrdfs.OpenOptions
_ [12]byte
Path string
}
// Opaque implements xrdproto.FilepathRequest.Opaque.
func (req *Request) Opaque() string {
return xrdproto.Opaque(req.Path)
}
// SetOpaque implements xrdproto.FilepathRequest.SetOpaque.
func (req *Request) SetOpaque(opaque string) {
xrdproto.SetOpaque(&req.Path, opaque)
}
// NewRequest forms a Request according to provided path, mode, and options.
func NewRequest(path string, mode xrdfs.OpenMode, options xrdfs.OpenOptions) *Request |
// MarshalXrd implements xrdproto.Marshaler.
func (o Request) MarshalXrd(wBuffer *xrdenc.WBuffer) error {
wBuffer.WriteU16(uint16(o.Mode))
wBuffer.WriteU16(uint16(o.Options))
wBuffer.Next(12)
wBuffer.WriteStr(o.Path)
return nil
}
// UnmarshalXrd implements xrdproto.Unmarshaler.
func (o *Request) UnmarshalXrd(rBuffer *xrdenc.RBuffer) error {
o.Mode = xrdfs.OpenMode(rBuffer.ReadU16())
o.Options = xrdfs.OpenOptions(rBuffer.ReadU16())
rBuffer.Skip(12)
o.Path = rBuffer.ReadStr()
return nil
}
// ReqID implements xrdproto.Request.ReqID.
func (req *Request) ReqID() uint16 { return RequestID }
// ShouldSign implements xrdproto.Request.ShouldSign.
func (req *Request) ShouldSign() bool {
// According to specification, the open request needs to be signed
// if any of the following options has been specified.
return req.Options&xrdfs.OpenOptionsDelete != 0 ||
req.Options&xrdfs.OpenOptionsNew != 0 ||
req.Options&xrdfs.OpenOptionsOpenUpdate != 0 ||
req.Options&xrdfs.OpenOptionsMkPath != 0 ||
req.Options&xrdfs.OpenOptionsOpenAppend != 0
}
var (
_ xrdproto.FilepathRequest = (*Request)(nil)
)
| {
return &Request{Mode: mode, Options: options, Path: path}
} |
utils.py | import re
import time
from django.conf import settings
from django.utils.timezone import make_aware, make_naive, utc
re_pattern = re.compile('[^\u0000-\uD7FF\uE000-\uFFFF]+', re.UNICODE)
def | (u):
# We may not be able to store all special characters thanks
# to MySQL's boneheadedness, so accept the minor loss of fidelity
# in the cached data fields.
return re_pattern.sub(' ', u)
def could_be_utc(dt):
if settings.USE_TZ:
return make_aware(dt, utc)
else:
if dt.tzinfo:
return make_naive(dt, utc)
else:
return dt
class RetryError(Exception):
def __init__(self, fn, tries, exceptions):
name = getattr(fn, '__name__', None) or str(fn)
super().__init__('%s failed after %d tries' % (name, tries))
self.exceptions = exceptions
def retry_with_backoff(fn, tries=10, wait=0.5, exception_classes=(Exception,)):
exceptions = []
for t in range(tries):
try:
return fn()
except exception_classes as e:
exceptions.append(e)
time.sleep(wait * (1.5**t))
raise RetryError(fn, tries, exceptions)
| sanitize_unicode |
main.go | package main
import (
"log"
"github.com/yangluoshen/broker/app"
"github.com/yangluoshen/broker/di"
)
func | () {
c := di.GetContainerByEnv()
err := c.Invoke(func(a *app.HttpApp) error {
return a.Run()
})
if err != nil {
log.Fatalf("fail to serve, err: %v", err)
}
}
| main |
lib.rs | //! Futures compatibility for [`tracing`].
//!
//! # Overview
//!
//! [`tracing`] is a framework for instrumenting Rust programs to collect
//! structured, event-based diagnostic information. This crate provides utilities
//! for using `tracing` to instrument asynchronous code written using futures and
//! async/await.
//!
//! The crate provides the following traits:
//!
//! * [`Instrument`] allows a `tracing` [span] to be attached to a future, sink,
//! stream, or executor.
//!
//! * [`WithSubscriber`] allows a `tracing` [`Subscriber`] to be attached to a
//! future, sink, stream, or executor.
//!
//! *Compiler support: [requires `rustc` 1.42+][msrv]*
//!
//! [msrv]: #supported-rust-versions
//!
//! # Feature flags
//!
//! This crate provides a number of feature flags that enable compatibility
//! features with other crates in the asynchronous ecosystem:
//!
//! - `tokio`: Enables compatibility with the `tokio` crate, including
//! [`Instrument`] and [`WithSubscriber`] implementations for
//! `tokio::executor::Executor`, `tokio::runtime::Runtime`, and
//! `tokio::runtime::current_thread`. Enabled by default.
//! - `tokio-executor`: Enables compatibility with the `tokio-executor`
//! crate, including [`Instrument`] and [`WithSubscriber`]
//! implementations for types implementing `tokio_executor::Executor`.
//! This is intended primarily for use in crates which depend on
//! `tokio-executor` rather than `tokio`; in general the `tokio` feature
//! should be used instead.
//! - `std-future`: Enables compatibility with `std::future::Future`.
//! - `futures-01`: Enables compatibility with version 0.1.x of the [`futures`]
//! crate.
//! - `futures-03`: Enables compatibility with version 0.3.x of the `futures`
//! crate's `Spawn` and `LocalSpawn` traits.
//! - `tokio-alpha`: Enables compatibility with `tokio` 0.2's alpha releases,
//! including the `tokio` 0.2 `Executor` and `TypedExecutor` traits.
//! - `std`: Depend on the Rust standard library.
//!
//! `no_std` users may disable this feature with `default-features = false`:
//!
//! ```toml
//! [dependencies]
//! tracing-futures = { version = "0.2.3", default-features = false }
//! ```
//!
//! The `tokio`, `std-future` and `std` features are enabled by default.
//!
//! [`tracing`]: https://crates.io/crates/tracing
//! [span]: https://docs.rs/tracing/latest/tracing/span/index.html
//! [`Subscriber`]: https://docs.rs/tracing/latest/tracing/subscriber/index.html
//! [`Instrument`]: trait.Instrument.html
//! [`WithSubscriber`]: trait.WithSubscriber.html
//! [`futures`]: https://crates.io/crates/futures
//!
//! ## Supported Rust Versions
//!
//! Tracing is built against the latest stable release. The minimum supported
//! version is 1.42. The current Tracing version is not guaranteed to build on
//! Rust versions earlier than the minimum supported version.
//!
//! Tracing follows the same compiler support policies as the rest of the Tokio
//! project. The current stable Rust compiler and the three most recent minor
//! versions before it will always be supported. For example, if the current
//! stable compiler version is 1.45, the minimum supported version will not be
//! increased past 1.42, three minor versions prior. Increasing the minimum
//! supported compiler version is not considered a semver breaking change as
//! long as doing so complies with this policy.
//!
#![doc(html_root_url = "https://docs.rs/tracing-futures/0.2.4")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/tokio-rs/tracing/master/assets/logo-type.png",
issue_tracker_base_url = "https://github.com/tokio-rs/tracing/issues/"
)]
#![warn(
missing_debug_implementations,
missing_docs,
rust_2018_idioms,
unreachable_pub,
bad_style,
const_err,
dead_code,
improper_ctypes,
non_shorthand_field_patterns,
no_mangle_generic_items,
overflowing_literals,
path_statements,
patterns_in_fns_without_body,
private_in_public,
unconditional_recursion,
unused,
unused_allocation,
unused_comparisons,
unused_parens,
while_true
)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg), deny(broken_intra_doc_links))]
#[cfg(feature = "std-future")]
use pin_project::pin_project;
#[cfg(feature = "std-future")]
use core::{pin::Pin, task::Context};
#[cfg(feature = "std")]
use tracing::{dispatcher, Dispatch};
use tracing::Span;
/// Implementations for `Instrument`ed future executors.
pub mod executor;
/// Extension trait allowing futures, streams, sinks, and executors to be
/// instrumented with a `tracing` [span].
///
/// [span]: https://docs.rs/tracing/latest/tracing/span/index.html
pub trait Instrument: Sized {
/// Instruments this type with the provided `Span`, returning an
/// `Instrumented` wrapper.
///
/// If the instrumented type is a future, stream, or sink, the attached `Span`
/// will be [entered] every time it is polled. If the instrumented type
/// is a future executor, every future spawned on that executor will be
/// instrumented by the attached `Span`.
///
/// # Examples
///
/// Instrumenting a future:
///
// TODO: ignored until async-await is stable...
/// ```rust,ignore
/// use tracing_futures::Instrument;
///
/// # async fn doc() {
/// let my_future = async {
/// // ...
/// };
///
/// my_future
/// .instrument(tracing::info_span!("my_future"))
/// .await
/// # }
/// ```
///
/// [entered]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.enter
fn instrument(self, span: Span) -> Instrumented<Self> {
Instrumented { inner: self, span }
}
/// Instruments this type with the [current] `Span`, returning an
/// `Instrumented` wrapper.
///
/// If the instrumented type is a future, stream, or sink, the attached `Span`
/// will be [entered] every time it is polled. If the instrumented type
/// is a future executor, every future spawned on that executor will be
/// instrumented by the attached `Span`.
///
/// This can be used to propagate the current span when spawning a new future.
///
/// # Examples
///
// TODO: ignored until async-await is stable...
/// ```rust,ignore
/// use tracing_futures::Instrument;
///
/// # async fn doc() {
/// let span = tracing::info_span!("my_span");
/// let _enter = span.enter();
///
/// // ...
///
/// let future = async {
/// tracing::debug!("this event will occur inside `my_span`");
/// // ...
/// };
/// tokio::spawn(future.in_current_span());
/// # }
/// ```
///
/// [current]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.current
/// [entered]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.enter
#[inline]
fn in_current_span(self) -> Instrumented<Self> {
self.instrument(Span::current())
}
}
/// Extension trait allowing futures, streams, and sinks to be instrumented with
/// a `tracing` [`Subscriber`].
///
/// [`Subscriber`]: https://docs.rs/tracing/latest/tracing/subscriber/trait.Subscriber.html
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
pub trait WithSubscriber: Sized {
/// Attaches the provided [`Subscriber`] to this type, returning a
/// `WithDispatch` wrapper.
///
/// When the wrapped type is a future, stream, or sink, the attached
/// subscriber will be set as the [default] while it is being polled.
/// When the wrapped type is an executor, the subscriber will be set as the
/// default for any futures spawned on that executor.
///
/// [`Subscriber`]: https://docs.rs/tracing/latest/tracing/subscriber/trait.Subscriber.html
/// [default]: https://docs.rs/tracing/latest/tracing/dispatcher/index.html#setting-the-default-subscriber
fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where
S: Into<Dispatch>,
{
WithDispatch {
inner: self,
dispatch: subscriber.into(),
}
}
/// Attaches the current [default] [`Subscriber`] to this type, returning a
/// `WithDispatch` wrapper.
///
/// When the wrapped type is a future, stream, or sink, the attached
/// subscriber will be set as the [default] while it is being polled.
/// When the wrapped type is an executor, the subscriber will be set as the
/// default for any futures spawned on that executor.
///
/// This can be used to propagate the current dispatcher context when
/// spawning a new future.
///
/// [`Subscriber`]: https://docs.rs/tracing/latest/tracing/subscriber/trait.Subscriber.html
/// [default]: https://docs.rs/tracing/latest/tracing/dispatcher/index.html#setting-the-default-subscriber
#[inline]
fn with_current_subscriber(self) -> WithDispatch<Self> {
WithDispatch {
inner: self,
dispatch: dispatcher::get_default(|default| default.clone()),
}
}
}
/// A future, stream, sink, or executor that has been instrumented with a `tracing` span.
#[cfg_attr(feature = "std-future", pin_project)]
#[derive(Debug, Clone)]
pub struct Instrumented<T> {
#[cfg(feature = "std-future")]
#[pin]
inner: T,
#[cfg(not(feature = "std-future"))]
inner: T,
span: Span,
}
/// A future, stream, sink, or executor that has been instrumented with a
/// `tracing` subscriber.
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
#[cfg_attr(feature = "std-future", pin_project)]
#[derive(Clone, Debug)]
pub struct WithDispatch<T> {
// cfg_attr doesn't work inside structs, apparently...
#[cfg(feature = "std-future")]
#[pin]
inner: T,
#[cfg(not(feature = "std-future"))]
inner: T,
dispatch: Dispatch,
}
impl<T: Sized> Instrument for T {}
#[cfg(feature = "std-future")]
#[cfg_attr(docsrs, doc(cfg(feature = "std-future")))]
impl<T: core::future::Future> core::future::Future for Instrumented<T> {
type Output = T::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> core::task::Poll<Self::Output> {
let this = self.project();
let _enter = this.span.enter();
this.inner.poll(cx)
}
}
#[cfg(feature = "futures-01")]
#[cfg_attr(docsrs, doc(cfg(feature = "futures-01")))]
impl<T: futures_01::Future> futures_01::Future for Instrumented<T> {
type Item = T::Item;
type Error = T::Error;
fn poll(&mut self) -> futures_01::Poll<Self::Item, Self::Error> {
let _enter = self.span.enter();
self.inner.poll()
}
}
#[cfg(feature = "futures-01")]
#[cfg_attr(docsrs, doc(cfg(feature = "futures-01")))]
impl<T: futures_01::Stream> futures_01::Stream for Instrumented<T> {
type Item = T::Item;
type Error = T::Error;
fn poll(&mut self) -> futures_01::Poll<Option<Self::Item>, Self::Error> {
let _enter = self.span.enter();
self.inner.poll()
}
}
#[cfg(feature = "futures-01")]
#[cfg_attr(docsrs, doc(cfg(feature = "futures-01")))]
impl<T: futures_01::Sink> futures_01::Sink for Instrumented<T> {
type SinkItem = T::SinkItem;
type SinkError = T::SinkError;
fn start_send(
&mut self,
item: Self::SinkItem,
) -> futures_01::StartSend<Self::SinkItem, Self::SinkError> {
let _enter = self.span.enter();
self.inner.start_send(item)
}
fn poll_complete(&mut self) -> futures_01::Poll<(), Self::SinkError> {
let _enter = self.span.enter();
self.inner.poll_complete()
}
}
#[cfg(all(feature = "futures-03", feature = "std-future"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "futures-03", feature = "std-future"))))]
impl<T: futures::Stream> futures::Stream for Instrumented<T> {
type Item = T::Item;
fn poll_next(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> futures::task::Poll<Option<Self::Item>> {
let this = self.project();
let _enter = this.span.enter();
T::poll_next(this.inner, cx)
}
}
#[cfg(all(feature = "futures-03", feature = "std-future"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "futures-03", feature = "std-future"))))]
impl<I, T: futures::Sink<I>> futures::Sink<I> for Instrumented<T>
where
T: futures::Sink<I>,
{
type Error = T::Error;
fn poll_ready(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> futures::task::Poll<Result<(), Self::Error>> {
let this = self.project();
let _enter = this.span.enter();
T::poll_ready(this.inner, cx)
}
fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> {
let this = self.project();
let _enter = this.span.enter();
T::start_send(this.inner, item)
}
fn poll_flush(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> futures::task::Poll<Result<(), Self::Error>> {
let this = self.project();
let _enter = this.span.enter();
T::poll_flush(this.inner, cx)
}
fn poll_close(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> futures::task::Poll<Result<(), Self::Error>> {
let this = self.project();
let _enter = this.span.enter();
T::poll_close(this.inner, cx)
}
}
impl<T> Instrumented<T> {
/// Borrows the `Span` that this type is instrumented by.
pub fn span(&self) -> &Span {
&self.span
}
/// Mutably borrows the `Span` that this type is instrumented by.
pub fn span_mut(&mut self) -> &mut Span {
&mut self.span
}
/// Borrows the wrapped type.
pub fn inner(&self) -> &T {
&self.inner
}
/// Mutably borrows the wrapped type.
pub fn inner_mut(&mut self) -> &mut T {
&mut self.inner
}
/// Get a pinned reference to the wrapped type.
#[cfg(feature = "std-future")]
#[cfg_attr(docsrs, doc(cfg(feature = "std-future")))]
pub fn inner_pin_ref(self: Pin<&Self>) -> Pin<&T> {
self.project_ref().inner
}
/// Get a pinned mutable reference to the wrapped type.
#[cfg(feature = "std-future")]
#[cfg_attr(docsrs, doc(cfg(feature = "std-future")))]
pub fn inner_pin_mut(self: Pin<&mut Self>) -> Pin<&mut T> {
self.project().inner
}
/// Consumes the `Instrumented`, returning the wrapped type.
///
/// Note that this drops the span.
pub fn into_inner(self) -> T {
self.inner
}
}
#[cfg(feature = "std")]
impl<T: Sized> WithSubscriber for T {}
#[cfg(all(feature = "futures-01", feature = "std"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "futures-01", feature = "std"))))]
impl<T: futures_01::Future> futures_01::Future for WithDispatch<T> {
type Item = T::Item;
type Error = T::Error;
fn poll(&mut self) -> futures_01::Poll<Self::Item, Self::Error> {
let inner = &mut self.inner;
dispatcher::with_default(&self.dispatch, || inner.poll())
}
}
#[cfg(all(feature = "std-future", feature = "std"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "std-future", feature = "std"))))]
impl<T: core::future::Future> core::future::Future for WithDispatch<T> {
type Output = T::Output;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> core::task::Poll<Self::Output> {
let this = self.project();
let dispatch = this.dispatch;
let future = this.inner;
dispatcher::with_default(dispatch, || future.poll(cx))
}
}
#[cfg(feature = "std")]
impl<T> WithDispatch<T> {
/// Wrap a future, stream, sink or executor with the same subscriber as this WithDispatch.
pub fn with_dispatch<U>(&self, inner: U) -> WithDispatch<U> {
WithDispatch {
dispatch: self.dispatch.clone(),
inner,
}
}
/// Borrows the `Dispatch` that this type is instrumented by.
pub fn dispatch(&self) -> &Dispatch {
&self.dispatch
}
/// Get a pinned reference to the wrapped type.
#[cfg(feature = "std-future")]
#[cfg_attr(docsrs, doc(cfg(feature = "std-future")))]
pub fn inner_pin_ref(self: Pin<&Self>) -> Pin<&T> {
self.project_ref().inner
}
/// Get a pinned mutable reference to the wrapped type.
#[cfg(feature = "std-future")]
#[cfg_attr(docsrs, doc(cfg(feature = "std-future")))]
pub fn inner_pin_mut(self: Pin<&mut Self>) -> Pin<&mut T> {
self.project().inner
}
/// Borrows the wrapped type.
pub fn inner(&self) -> &T {
&self.inner
}
/// Mutably borrows the wrapped type.
pub fn inner_mut(&mut self) -> &mut T {
&mut self.inner
}
/// Consumes the `WithDispatch`, returning the wrapped type.
pub fn into_inner(self) -> T {
self.inner
}
}
#[cfg(test)]
pub(crate) use self::support as test_support;
// This has to have the same name as the module in `tracing`.
#[path = "../../tracing/tests/support/mod.rs"]
#[cfg(test)]
#[allow(unreachable_pub)]
pub(crate) mod support;
#[cfg(test)]
mod tests {
use super::{test_support::*, *};
#[cfg(feature = "futures-01")]
mod futures_01_tests {
use futures_01::{future, stream, task, Async, Future, Stream};
use tracing::subscriber::with_default;
use super::*;
struct PollN<T, E> {
and_return: Option<Result<T, E>>,
finish_at: usize,
polls: usize,
}
impl PollN<(), ()> {
fn new_ok(finish_at: usize) -> Self {
Self {
and_return: Some(Ok(())),
finish_at,
polls: 0,
}
}
fn new_err(finish_at: usize) -> Self {
Self {
and_return: Some(Err(())),
finish_at,
polls: 0,
}
}
}
impl<T, E> futures_01::Future for PollN<T, E> {
type Item = T;
type Error = E;
fn poll(&mut self) -> futures_01::Poll<Self::Item, Self::Error> {
self.polls += 1;
if self.polls == self.finish_at {
self.and_return
.take()
.expect("polled after ready")
.map(Async::Ready)
} else {
task::current().notify();
Ok(Async::NotReady)
}
}
}
#[test]
fn future_enter_exit_is_reasonable() {
let (subscriber, handle) = subscriber::mock()
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.drop_span(span::mock().named("foo"))
.done()
.run_with_handle();
with_default(subscriber, || {
PollN::new_ok(2)
.instrument(tracing::trace_span!("foo"))
.wait()
.unwrap();
});
handle.assert_finished();
}
#[test]
fn future_error_ends_span() {
let (subscriber, handle) = subscriber::mock()
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.drop_span(span::mock().named("foo"))
.done()
.run_with_handle();
with_default(subscriber, || {
PollN::new_err(2)
.instrument(tracing::trace_span!("foo"))
.wait()
.unwrap_err();
});
handle.assert_finished();
}
#[test]
fn stream_enter_exit_is_reasonable() {
let (subscriber, handle) = subscriber::mock()
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.enter(span::mock().named("foo")) | .drop_span(span::mock().named("foo"))
.run_with_handle();
with_default(subscriber, || {
stream::iter_ok::<_, ()>(&[1, 2, 3])
.instrument(tracing::trace_span!("foo"))
.for_each(|_| future::ok(()))
.wait()
.unwrap();
});
handle.assert_finished();
}
#[test]
fn span_follows_future_onto_threadpool() {
let (subscriber, handle) = subscriber::mock()
.enter(span::mock().named("a"))
.enter(span::mock().named("b"))
.exit(span::mock().named("b"))
.enter(span::mock().named("b"))
.exit(span::mock().named("b"))
.drop_span(span::mock().named("b"))
.exit(span::mock().named("a"))
.drop_span(span::mock().named("a"))
.done()
.run_with_handle();
let mut runtime = tokio::runtime::Runtime::new().unwrap();
with_default(subscriber, || {
tracing::trace_span!("a").in_scope(|| {
let future = PollN::new_ok(2)
.instrument(tracing::trace_span!("b"))
.map(|_| {
tracing::trace_span!("c").in_scope(|| {
// "c" happens _outside_ of the instrumented future's
// span, so we don't expect it.
})
});
runtime.block_on(Box::new(future)).unwrap();
})
});
handle.assert_finished();
}
}
#[cfg(all(feature = "futures-03", feature = "std-future"))]
mod futures_03_tests {
use futures::{future, sink, stream, FutureExt, SinkExt, StreamExt};
use tracing::subscriber::with_default;
use super::*;
#[test]
fn stream_enter_exit_is_reasonable() {
let (subscriber, handle) = subscriber::mock()
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.drop_span(span::mock().named("foo"))
.run_with_handle();
with_default(subscriber, || {
Instrument::instrument(stream::iter(&[1, 2, 3]), tracing::trace_span!("foo"))
.for_each(|_| future::ready(()))
.now_or_never()
.unwrap();
});
handle.assert_finished();
}
#[test]
fn sink_enter_exit_is_reasonable() {
let (subscriber, handle) = subscriber::mock()
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo"))
.drop_span(span::mock().named("foo"))
.run_with_handle();
with_default(subscriber, || {
Instrument::instrument(sink::drain(), tracing::trace_span!("foo"))
.send(1u8)
.now_or_never()
.unwrap()
.unwrap()
});
handle.assert_finished();
}
}
} | .exit(span::mock().named("foo"))
.enter(span::mock().named("foo"))
.exit(span::mock().named("foo")) |
nested_generators.rs | // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![feature(generators)]
#![feature(generator_trait)]
use std::ops::Generator;
use std::ops::GeneratorState;
fn | () {
let _generator = || {
let mut sub_generator = || {
yield 2;
};
match sub_generator.resume() {
GeneratorState::Yielded(x) => {
yield x;
}
_ => panic!(),
};
};
}
| main |
BlobFileReader-test.js | "use strict";
jest.dontMock('../BlobFileReader.js').dontMock('../MediaFileReader.js').dontMock('../ChunkedFileData.js');
var BlobFileReader = require('../BlobFileReader');
function throwOnError(onSuccess) {
return {
onSuccess: onSuccess,
onError: function onError() {
throw new Error();
} | var fileReader;
beforeEach(function () {
fileReader = new BlobFileReader(new Blob(["This is a simple file"]));
});
it("should be able to read the right type of files", function () {
expect(BlobFileReader.canReadFile("fakefile")).toBe(false);
expect(BlobFileReader.canReadFile("http://localhost")).toBe(false);
expect(BlobFileReader.canReadFile(new Blob())).toBe(true);
});
it("should have the right size information", function () {
return new Promise(function (resolve, reject) {
fileReader.init(throwOnError(resolve));
jest.runAllTimers();
}).then(function () {
expect(fileReader.getSize()).toBe(21);
});
});
it("should read a byte", function () {
return new Promise(function (resolve, reject) {
fileReader.loadRange([0, 4], throwOnError(resolve));
jest.runAllTimers();
}).then(function (tags) {
expect(fileReader.getByteAt(0)).toBe("T".charCodeAt(0));
});
});
it("should read a byte after loading the same range twice", function () {
return new Promise(function (resolve, reject) {
fileReader.loadRange([0, 4], throwOnError(function () {
fileReader.loadRange([0, 4], throwOnError(resolve));
}));
}).then(function (tags) {
expect(fileReader.getByteAt(0)).toBe("T".charCodeAt(0));
});
});
it("should not read a byte that hasn't been loaded yet", function () {
return new Promise(function (resolve, reject) {
fileReader.init(throwOnError(resolve));
jest.runAllTimers();
}).then(function (tags) {
expect(function () {
var byte0 = fileReader.getByteAt(0);
}).toThrow();
});
});
}); | };
}
describe("BlobFileReader", function () { |
datomic.py | # -*- coding: utf-8 -*-
from urllib.parse import urljoin
from edn import loads
import requests
class Database(object):
def __init__(self, name, conn):
self.name = name
self.conn = conn
def __getattr__(self, name):
def f(*args, **kwargs):
return getattr(self.conn, name)(self.name, *args, **kwargs)
return f
class Datomic(object):
def __init__(self, location, storage):
self.location = location
self.storage = storage
def db_url(self, dbname):
return urljoin(self.location, 'data/') + self.storage + '/' + dbname
def create_database(self, dbname):
|
def transact(self, dbname, data):
r = requests.post(self.db_url(dbname)+'/', data={'tx-data':data},
headers={'Accept':'application/edn'})
assert r.status_code in (200, 201), (r.status_code, r.text)
return loads(r.content)
def query(self, dbname, query, extra_args=[], history=False):
args = '[{:db/alias ' + self.storage + '/' + dbname
if history:
args += ' :history true'
args += '} ' + ' '.join(str(a) for a in extra_args) + ']'
r = requests.get(urljoin(self.location, 'api/query'),
params={'args' : args, 'q':query},
headers={'Accept':'application/edn'})
assert r.status_code == 200, r.text
return loads(r.content)
def entity(self, dbname, eid):
r = requests.get(self.db_url(dbname) + '/-/entity', params={'e':eid},
headers={'Accept':'application/edn'})
assert r.status_code == 200
return loads(r.content)
if __name__ == '__main__':
q = """[{
:db/id #db/id[:db.part/db]
:db/ident :person/name
:db/valueType :db.type/string
:db/cardinality :db.cardinality/one
:db/doc "A person's name"
:db.install/_attribute :db.part/db}]"""
conn = Datomic('http://localhost:3000/', 'tdb')
db = conn.create_database('cms')
db.transact(q)
db.transact('[{:db/id #db/id[:db.part/user] :person/name "Peter"}]')
r = db.query('[:find ?e ?n :where [?e :person/name ?n]]')
print(r)
eid = r[0][0]
print(db.query('[:find ?n :in $ ?e :where [?e :person/name ?n]]', [eid], history=True))
print(db.entity(eid))
| r = requests.post(self.db_url(''), data={'db-name':dbname})
assert r.status_code in (200, 201), r.text
return Database(dbname, self) |
oauth.provider.interface.ts | import { OAuthProfile } from './models/oauth-profile.model';
| export interface IOathProvider {
login(): Promise<string>;
getProfile(accessToken: string): Promise<OAuthProfile>;
} |
|
friendship_query.go | // Copyright 2019-present Facebook
//
// 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 entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/contrib/entgql/internal/todouuid/ent/friendship"
"entgo.io/contrib/entgql/internal/todouuid/ent/predicate"
"entgo.io/contrib/entgql/internal/todouuid/ent/user"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/google/uuid"
)
// FriendshipQuery is the builder for querying Friendship entities.
type FriendshipQuery struct {
config
limit *int
offset *int
unique *bool
order []OrderFunc
fields []string
predicates []predicate.Friendship
// eager-loading edges.
withUser *UserQuery
withFriend *UserQuery
modifiers []func(*sql.Selector)
loadTotal []func(context.Context, []*Friendship) error
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the FriendshipQuery builder.
func (fq *FriendshipQuery) Where(ps ...predicate.Friendship) *FriendshipQuery {
fq.predicates = append(fq.predicates, ps...)
return fq
}
// Limit adds a limit step to the query.
func (fq *FriendshipQuery) Limit(limit int) *FriendshipQuery {
fq.limit = &limit
return fq
}
// Offset adds an offset step to the query.
func (fq *FriendshipQuery) Offset(offset int) *FriendshipQuery {
fq.offset = &offset
return fq
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (fq *FriendshipQuery) Unique(unique bool) *FriendshipQuery {
fq.unique = &unique
return fq
}
// Order adds an order step to the query.
func (fq *FriendshipQuery) Order(o ...OrderFunc) *FriendshipQuery {
fq.order = append(fq.order, o...)
return fq
}
// QueryUser chains the current query on the "user" edge.
func (fq *FriendshipQuery) QueryUser() *UserQuery {
query := &UserQuery{config: fq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := fq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := fq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(friendship.Table, friendship.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, friendship.UserTable, friendship.UserColumn),
)
fromU = sqlgraph.SetNeighbors(fq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// QueryFriend chains the current query on the "friend" edge.
func (fq *FriendshipQuery) QueryFriend() *UserQuery {
query := &UserQuery{config: fq.config}
query.path = func(ctx context.Context) (fromU *sql.Selector, err error) {
if err := fq.prepareQuery(ctx); err != nil {
return nil, err
}
selector := fq.sqlQuery(ctx)
if err := selector.Err(); err != nil {
return nil, err
}
step := sqlgraph.NewStep(
sqlgraph.From(friendship.Table, friendship.FieldID, selector),
sqlgraph.To(user.Table, user.FieldID),
sqlgraph.Edge(sqlgraph.M2O, false, friendship.FriendTable, friendship.FriendColumn),
)
fromU = sqlgraph.SetNeighbors(fq.driver.Dialect(), step)
return fromU, nil
}
return query
}
// First returns the first Friendship entity from the query.
// Returns a *NotFoundError when no Friendship was found.
func (fq *FriendshipQuery) First(ctx context.Context) (*Friendship, error) {
nodes, err := fq.Limit(1).All(ctx)
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{friendship.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (fq *FriendshipQuery) FirstX(ctx context.Context) *Friendship {
node, err := fq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Friendship ID from the query.
// Returns a *NotFoundError when no Friendship ID was found.
func (fq *FriendshipQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = fq.Limit(1).IDs(ctx); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{friendship.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (fq *FriendshipQuery) FirstIDX(ctx context.Context) int {
id, err := fq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Friendship entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Friendship entity is found.
// Returns a *NotFoundError when no Friendship entities are found.
func (fq *FriendshipQuery) Only(ctx context.Context) (*Friendship, error) {
nodes, err := fq.Limit(2).All(ctx)
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{friendship.Label}
default:
return nil, &NotSingularError{friendship.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (fq *FriendshipQuery) OnlyX(ctx context.Context) *Friendship {
node, err := fq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Friendship ID in the query.
// Returns a *NotSingularError when more than one Friendship ID is found.
// Returns a *NotFoundError when no entities are found.
func (fq *FriendshipQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = fq.Limit(2).IDs(ctx); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{friendship.Label}
default:
err = &NotSingularError{friendship.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (fq *FriendshipQuery) OnlyIDX(ctx context.Context) int {
id, err := fq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Friendships.
func (fq *FriendshipQuery) All(ctx context.Context) ([]*Friendship, error) {
if err := fq.prepareQuery(ctx); err != nil {
return nil, err
}
return fq.sqlAll(ctx)
}
// AllX is like All, but panics if an error occurs.
func (fq *FriendshipQuery) AllX(ctx context.Context) []*Friendship {
nodes, err := fq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Friendship IDs.
func (fq *FriendshipQuery) IDs(ctx context.Context) ([]int, error) {
var ids []int
if err := fq.Select(friendship.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (fq *FriendshipQuery) IDsX(ctx context.Context) []int {
ids, err := fq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (fq *FriendshipQuery) Count(ctx context.Context) (int, error) {
if err := fq.prepareQuery(ctx); err != nil {
return 0, err
}
return fq.sqlCount(ctx)
}
// CountX is like Count, but panics if an error occurs.
func (fq *FriendshipQuery) CountX(ctx context.Context) int {
count, err := fq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (fq *FriendshipQuery) Exist(ctx context.Context) (bool, error) {
if err := fq.prepareQuery(ctx); err != nil {
return false, err
}
return fq.sqlExist(ctx)
}
// ExistX is like Exist, but panics if an error occurs.
func (fq *FriendshipQuery) ExistX(ctx context.Context) bool {
exist, err := fq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the FriendshipQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (fq *FriendshipQuery) Clone() *FriendshipQuery {
if fq == nil {
return nil
}
return &FriendshipQuery{
config: fq.config,
limit: fq.limit,
offset: fq.offset,
order: append([]OrderFunc{}, fq.order...),
predicates: append([]predicate.Friendship{}, fq.predicates...),
withUser: fq.withUser.Clone(),
withFriend: fq.withFriend.Clone(),
// clone intermediate query.
sql: fq.sql.Clone(),
path: fq.path,
unique: fq.unique,
}
}
// WithUser tells the query-builder to eager-load the nodes that are connected to
// the "user" edge. The optional arguments are used to configure the query builder of the edge.
func (fq *FriendshipQuery) WithUser(opts ...func(*UserQuery)) *FriendshipQuery {
query := &UserQuery{config: fq.config}
for _, opt := range opts {
opt(query)
}
fq.withUser = query
return fq
}
// WithFriend tells the query-builder to eager-load the nodes that are connected to
// the "friend" edge. The optional arguments are used to configure the query builder of the edge.
func (fq *FriendshipQuery) WithFriend(opts ...func(*UserQuery)) *FriendshipQuery {
query := &UserQuery{config: fq.config}
for _, opt := range opts {
opt(query)
}
fq.withFriend = query
return fq
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// CreatedAt time.Time `json:"created_at,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Friendship.Query().
// GroupBy(friendship.FieldCreatedAt).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
//
func (fq *FriendshipQuery) GroupBy(field string, fields ...string) *FriendshipGroupBy {
grbuild := &FriendshipGroupBy{config: fq.config}
grbuild.fields = append([]string{field}, fields...)
grbuild.path = func(ctx context.Context) (prev *sql.Selector, err error) {
if err := fq.prepareQuery(ctx); err != nil {
return nil, err
}
return fq.sqlQuery(ctx), nil
}
grbuild.label = friendship.Label
grbuild.flds, grbuild.scan = &grbuild.fields, grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// CreatedAt time.Time `json:"created_at,omitempty"`
// }
//
// client.Friendship.Query().
// Select(friendship.FieldCreatedAt).
// Scan(ctx, &v)
//
func (fq *FriendshipQuery) Select(fields ...string) *FriendshipSelect {
fq.fields = append(fq.fields, fields...)
selbuild := &FriendshipSelect{FriendshipQuery: fq}
selbuild.label = friendship.Label
selbuild.flds, selbuild.scan = &fq.fields, selbuild.Scan
return selbuild
}
func (fq *FriendshipQuery) prepareQuery(ctx context.Context) error {
for _, f := range fq.fields {
if !friendship.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if fq.path != nil {
prev, err := fq.path(ctx)
if err != nil {
return err
}
fq.sql = prev
}
return nil
}
func (fq *FriendshipQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Friendship, error) {
var (
nodes = []*Friendship{}
_spec = fq.querySpec()
loadedTypes = [2]bool{
fq.withUser != nil,
fq.withFriend != nil,
}
)
_spec.ScanValues = func(columns []string) ([]interface{}, error) {
return (*Friendship).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []interface{}) error {
node := &Friendship{config: fq.config}
nodes = append(nodes, node)
node.Edges.loadedTypes = loadedTypes
return node.assignValues(columns, values)
}
if len(fq.modifiers) > 0 {
_spec.Modifiers = fq.modifiers
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, fq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
if query := fq.withUser; query != nil {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Friendship)
for i := range nodes {
fk := nodes[i].UserID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return nil, err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return nil, fmt.Errorf(`unexpected foreign-key "user_id" returned %v`, n.ID)
}
for i := range nodes {
nodes[i].Edges.User = n
}
}
}
if query := fq.withFriend; query != nil {
ids := make([]uuid.UUID, 0, len(nodes))
nodeids := make(map[uuid.UUID][]*Friendship)
for i := range nodes {
fk := nodes[i].FriendID
if _, ok := nodeids[fk]; !ok {
ids = append(ids, fk)
}
nodeids[fk] = append(nodeids[fk], nodes[i])
}
query.Where(user.IDIn(ids...))
neighbors, err := query.All(ctx)
if err != nil {
return nil, err
}
for _, n := range neighbors {
nodes, ok := nodeids[n.ID]
if !ok {
return nil, fmt.Errorf(`unexpected foreign-key "friend_id" returned %v`, n.ID)
}
for i := range nodes {
nodes[i].Edges.Friend = n
}
}
}
for i := range fq.loadTotal {
if err := fq.loadTotal[i](ctx, nodes); err != nil {
return nil, err
}
}
return nodes, nil
}
func (fq *FriendshipQuery) sqlCount(ctx context.Context) (int, error) {
_spec := fq.querySpec()
if len(fq.modifiers) > 0 {
_spec.Modifiers = fq.modifiers
}
_spec.Node.Columns = fq.fields
if len(fq.fields) > 0 {
_spec.Unique = fq.unique != nil && *fq.unique
}
return sqlgraph.CountNodes(ctx, fq.driver, _spec)
}
func (fq *FriendshipQuery) sqlExist(ctx context.Context) (bool, error) {
n, err := fq.sqlCount(ctx)
if err != nil {
return false, fmt.Errorf("ent: check existence: %w", err)
}
return n > 0, nil
}
func (fq *FriendshipQuery) querySpec() *sqlgraph.QuerySpec {
_spec := &sqlgraph.QuerySpec{
Node: &sqlgraph.NodeSpec{
Table: friendship.Table,
Columns: friendship.Columns,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: friendship.FieldID,
},
},
From: fq.sql,
Unique: true,
}
if unique := fq.unique; unique != nil {
_spec.Unique = *unique
}
if fields := fq.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, friendship.FieldID)
for i := range fields {
if fields[i] != friendship.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := fq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := fq.limit; limit != nil {
_spec.Limit = *limit
}
if offset := fq.offset; offset != nil {
_spec.Offset = *offset
}
if ps := fq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (fq *FriendshipQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(fq.driver.Dialect())
t1 := builder.Table(friendship.Table) | if len(columns) == 0 {
columns = friendship.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if fq.sql != nil {
selector = fq.sql
selector.Select(selector.Columns(columns...)...)
}
if fq.unique != nil && *fq.unique {
selector.Distinct()
}
for _, p := range fq.predicates {
p(selector)
}
for _, p := range fq.order {
p(selector)
}
if offset := fq.offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := fq.limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// FriendshipGroupBy is the group-by builder for Friendship entities.
type FriendshipGroupBy struct {
config
selector
fields []string
fns []AggregateFunc
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Aggregate adds the given aggregation functions to the group-by query.
func (fgb *FriendshipGroupBy) Aggregate(fns ...AggregateFunc) *FriendshipGroupBy {
fgb.fns = append(fgb.fns, fns...)
return fgb
}
// Scan applies the group-by query and scans the result into the given value.
func (fgb *FriendshipGroupBy) Scan(ctx context.Context, v interface{}) error {
query, err := fgb.path(ctx)
if err != nil {
return err
}
fgb.sql = query
return fgb.sqlScan(ctx, v)
}
func (fgb *FriendshipGroupBy) sqlScan(ctx context.Context, v interface{}) error {
for _, f := range fgb.fields {
if !friendship.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("invalid field %q for group-by", f)}
}
}
selector := fgb.sqlQuery()
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := fgb.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
func (fgb *FriendshipGroupBy) sqlQuery() *sql.Selector {
selector := fgb.sql.Select()
aggregation := make([]string, 0, len(fgb.fns))
for _, fn := range fgb.fns {
aggregation = append(aggregation, fn(selector))
}
// If no columns were selected in a custom aggregation function, the default
// selection is the fields used for "group-by", and the aggregation functions.
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(fgb.fields)+len(fgb.fns))
for _, f := range fgb.fields {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
return selector.GroupBy(selector.Columns(fgb.fields...)...)
}
// FriendshipSelect is the builder for selecting fields of Friendship entities.
type FriendshipSelect struct {
*FriendshipQuery
selector
// intermediate query (i.e. traversal path).
sql *sql.Selector
}
// Scan applies the selector query and scans the result into the given value.
func (fs *FriendshipSelect) Scan(ctx context.Context, v interface{}) error {
if err := fs.prepareQuery(ctx); err != nil {
return err
}
fs.sql = fs.FriendshipQuery.sqlQuery(ctx)
return fs.sqlScan(ctx, v)
}
func (fs *FriendshipSelect) sqlScan(ctx context.Context, v interface{}) error {
rows := &sql.Rows{}
query, args := fs.sql.Query()
if err := fs.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
} | columns := fq.fields |
task.py | from urllib.parse import urlparse
from datetime import date
class TableNode:
def __init__(self, task, _id):
self.task = task
self.requires = []
self.id = _id
class GraphDependency:
def __init__(self, tasks):
nodes = {}
for task in tasks:
nodes[task.id] = TableNode(task=task, _id=task.output.id)
for _input in task.inputs:
nodes[_input.id] = TableNode(task=task, _id=_input.id)
for task in tasks:
nodes[task.id].requires = [nodes[table.id] for table in task.inputs]
self.requirements = list(nodes.values())
self.build_graph()
def __dep_resolve(self, node, resolved):
for edge in node.requires:
if edge not in resolved:
self.__dep_resolve(edge, resolved)
resolved.append(node)
def resolve(self, node):
resolved = []
self.__dep_resolve(node, resolved)
return resolved
def build_edges(self, dn):
if dn in self.requirements:
self.nodes.add(dn)
for edge in dn.requires:
if edge in self.requirements:
self.edges.append({'source': dn, 'target': edge})
self.build_edges(edge)
def build_graph(self):
self.nodes = set()
self.edges = []
for dn in self.requirements:
self.build_edges(dn)
self.nodes = list(self.nodes)
self.starts = []
self.ends = []
targets = set([e['target'] for e in self.edges])
sources = set([e['source'] for e in self.edges])
for dn in self.nodes:
if dn not in targets:
self.starts.append(dn)
if dn not in sources:
self.ends.append(dn)
def sorted(self):
s = []
for node in self.starts:
for r_node in self.resolve(node):
if r_node not in s:
s.append(r_node)
return s
class Task:
def __init__(self, name, inputs, output, module=None, arguments=None, constraints=None):
self.name = name
self.inputs = inputs
self.output = output
self.module = module
self.arguments = arguments
self.constraints = constraints
self.s3 = None
@property
def id(self):
return self.output.id
def status(self):
is_valid = self.constraints.execute(s3=self.s3)
if not is_valid and not self.module:
status = 'NO_SOLUTION'
elif not is_valid and self.module:
status = 'NOT_AVAILABLE'
elif is_valid:
status = 'AVAILABLE'
return status
class | :
def __init__(self, name, tasks):
self.tasks = tasks
self.name = name
def create_tasks(self, build_operator):
self.graph = GraphDependency(self.tasks)
build_tasks = {}
for node in self.graph.nodes:
task_id = f"build_{node.id}" if node.task.module and node.requires else f"use_{node.id}"
build_tasks[node.id] = build_operator(
task_id=task_id,
node=node)
# task_id=task_id,
# execution_timeout=self.timeout_build,
# retries=0,
# trigger_rule="all_success",
# python_callable=self.call_build,
# op_kwargs={'node': node},
# provide_context=True, dag=dag)
nodes_input = set()
nodes_output = set()
for edge in self.graph.edges:
target = edge['target'].id
source = edge['source'].id
if target in build_tasks and source in build_tasks:
nodes_input.add(source)
nodes_output.add(target)
print(build_tasks[target], build_tasks[source])
build_tasks[target] >> build_tasks[source]
nodes_ends = set(build_tasks.keys()) - nodes_input
nodes_starts = set(build_tasks.keys()) - nodes_output
starts = [build_tasks[node_id] for node_id in nodes_ends]
ends = [build_tasks[node_id] for node_id in nodes_starts]
return {'starts': starts, 'ends': ends}
class Constraint:
def __init__(self, table):
self.table = table
class CExists(Constraint):
def __init__(self, *args, format_path='{self.table.absolute_path}', **kwargs):
super().__init__(*args, **kwargs)
self.format_path = format_path
def execute(self, s3):
path = self.format_path.format(self=self)
parsed = urlparse(path, allow_fragments=False)
bucket = parsed.netloc
key = parsed.path.lstrip('/')
try:
s3.get_object(Bucket=bucket, Key=key)
except Exception:
return False
else:
return True
class CDelta(Constraint):
def __init__(self, *args, delta, format_path='{self.table.absolute_path}', **kwargs):
super().__init__(*args, **kwargs)
self.delta = delta
self.format_path = format_path
def execute(self, s3):
path = self.format_path.format(self=self)
parsed = urlparse(path, allow_fragments=False)
bucket = parsed.netloc
key = parsed.path.lstrip('/')
try:
s3_object = s3.get_object(Bucket=bucket, Key=key)
except Exception:
return False
else:
last_modified = s3_object['LastModified']
today = date.today()
return last_modified.date() >= (today + self.delta)
| Job |
BrightnessHighRounded.tsx | import React from 'react';
import createSvgIcon from './helpers/createSvgIcon';
export default createSvgIcon(
<path d="M20 8.69V6c0-1.1-.9-2-2-2h-2.69l-1.9-1.9c-.78-.78-2.05-.78-2.83 0L8.69 4H6c-1.1 0-2 .9-2 2v2.69l-1.9 1.9c-.78.78-.78 2.05 0 2.83l1.9 1.9V18c0 1.1.9 2 2 2h2.69l1.9 1.9c.78.78 2.05.78 2.83 0l1.9-1.9H18c1.1 0 2-.9 2-2v-2.69l1.9-1.9c.78-.78.78-2.05 0-2.83L20 8.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6zm0-10c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z" />,
'BrightnessHighRounded', | ); | |
program.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use crate::ir::{ExecutableDefinition, FragmentDefinition, OperationDefinition};
use fnv::FnvHashMap;
use interner::StringKey;
use rayon::{iter::ParallelIterator, prelude::*};
use schema::SDLSchema;
use std::{collections::HashMap, sync::Arc};
/// A collection of all documents that are being compiled.
#[derive(Debug, Clone)]
pub struct Program {
pub schema: Arc<SDLSchema>,
fragments: FnvHashMap<StringKey, Arc<FragmentDefinition>>,
operations: Vec<Arc<OperationDefinition>>,
}
impl Program {
pub fn new(schema: Arc<SDLSchema>) -> Self {
Self {
schema,
fragments: Default::default(),
operations: Default::default(),
}
}
pub fn from_definitions(
schema: Arc<SDLSchema>,
definitions: Vec<ExecutableDefinition>,
) -> Self {
let mut operations = Vec::new();
let mut fragments = HashMap::default();
for definition in definitions {
match definition {
ExecutableDefinition::Operation(operation) => {
operations.push(Arc::new(operation));
}
ExecutableDefinition::Fragment(fragment) => {
fragments.insert(fragment.name.item, Arc::new(fragment));
}
}
}
Self {
schema,
fragments,
operations,
}
}
pub fn insert_fragment(&mut self, fragment: Arc<FragmentDefinition>) {
let name = fragment.name.item;
if let Some(previous) = self.fragments.insert(name, fragment) {
panic!(
"Can only insert '{}' once. Had {:?} and trying to insert {:?}.",
name, previous, self.fragments[&name]
);
};
}
pub fn fragment(&self, name: StringKey) -> Option<&Arc<FragmentDefinition>> {
self.fragments.get(&name)
}
/// Searches for an operation by name.
///
/// NOTE: This is a linear search, we currently don't frequently search
/// for operations by name, so this might be overall faster than
/// using a map internally.
pub fn | (&self, name: StringKey) -> Option<&Arc<OperationDefinition>> {
self.operations()
.find(|operation| operation.name.item == name)
}
pub fn insert_operation(&mut self, operation: Arc<OperationDefinition>) {
self.operations.push(operation);
}
pub fn operations(&self) -> impl Iterator<Item = &Arc<OperationDefinition>> {
self.operations.iter()
}
pub fn par_operations(&self) -> impl ParallelIterator<Item = &Arc<OperationDefinition>> {
self.operations.par_iter()
}
pub fn par_operations_mut(
&mut self,
) -> impl ParallelIterator<Item = &mut Arc<OperationDefinition>> {
self.operations.par_iter_mut()
}
pub fn fragments(&self) -> impl Iterator<Item = &Arc<FragmentDefinition>> {
self.fragments.values()
}
pub fn par_fragments(&self) -> impl ParallelIterator<Item = &Arc<FragmentDefinition>> {
self.fragments.par_iter().map(|(_, v)| v)
}
pub fn par_fragments_mut(
&mut self,
) -> impl ParallelIterator<Item = &mut Arc<FragmentDefinition>> {
self.fragments.par_iter_mut().map(|(_, v)| v)
}
pub fn document_count(&self) -> usize {
self.fragments.len() + self.operations.len()
}
pub fn merge_program(
&mut self,
other_program: &Self,
removed_definition_names: Option<&[StringKey]>,
) {
let mut operations: FnvHashMap<StringKey, Arc<OperationDefinition>> = self
.operations
.drain(..)
.map(|op| (op.name.item, op))
.collect();
for fragment in other_program.fragments() {
self.fragments
.insert(fragment.name.item, Arc::clone(fragment));
}
for operation in other_program.operations() {
operations.insert(operation.name.item, Arc::clone(operation));
}
if let Some(removed_definition_names) = removed_definition_names {
for removed in removed_definition_names {
self.fragments.remove(removed);
operations.remove(removed);
}
}
self.operations
.extend(operations.into_iter().map(|(_, op)| op));
}
}
| operation |
main.go | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Code generated by cloud.google.com/go/internal/gapicgen/gensnippets. DO NOT EDIT.
// [START securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_sync]
package main
import (
"context"
securitycenter "cloud.google.com/go/securitycenter/apiv1"
"google.golang.org/api/iterator"
securitycenterpb "google.golang.org/genproto/googleapis/cloud/securitycenter/v1"
)
func main() {
ctx := context.Background()
c, err := securitycenter.NewClient(ctx)
if err != nil |
defer c.Close()
req := &securitycenterpb.ListNotificationConfigsRequest{
// TODO: Fill request struct fields.
// See https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/securitycenter/v1#ListNotificationConfigsRequest.
}
it := c.ListNotificationConfigs(ctx, req)
for {
resp, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
// TODO: Handle error.
}
// TODO: Use resp.
_ = resp
}
}
// [END securitycenter_v1_generated_SecurityCenter_ListNotificationConfigs_sync]
| {
// TODO: Handle error.
} |
views.py | from django.shortcuts import render
from catalog.models import Book, Author, BookInstance, Genre
from django.contrib.auth.mixins import LoginRequiredMixin
def index(request):
"""View function for home page of site."""
# Generate counts of some of the main objects
num_books = Book.objects.all().count()
num_instances = BookInstance.objects.all().count()
# Available books (status = 'a')
num_instances_available = BookInstance.objects.filter(status__exact='a').count()
# The 'all()' is implied by default.
num_authors = Author.objects.count()
# Number of visits to this view, as counted in the session variable.
num_visits = request.session.get('num_visits', 1)
request.session['num_visits'] = num_visits + 1
context = {
'num_books': num_books,
'num_instances': num_instances,
'num_instances_available': num_instances_available,
'num_authors': num_authors,
'num_visits': num_visits,
}
# Render the HTML template index.html with the data in the context variable
return render(request, 'index.html', context=context)
from django.views import generic
class BookListView(generic.ListView):
model = Book
paginate_by = 2
class BookDetailView(generic.DetailView):
model = Book
def book_detail_view(request, primary_key):
try:
book = Book.objects.get(pk=primary_key)
except Book.DoesNotExist:
raise Http404('Book does not exist')
return render(request, 'catalog/book_detail.html', context={'book': book})
class AuthorListView(generic.ListView):
model = Author
paginate_by = 2
class AuthorDetailView(generic.DetailView):
model = Author
class LoanedBooksByUserListView(LoginRequiredMixin,generic.ListView):
"""Generic class-based view listing books on loan to current user."""
model = BookInstance
template_name ='catalog/bookinstance_list_borrowed_user.html'
paginate_by = 2
def get_queryset(self):
return BookInstance.objects.filter(borrower=self.request.user).filter(status__exact='o').order_by('due_back')
# Added as part of challenge!
from django.contrib.auth.mixins import PermissionRequiredMixin
class LoanedBooksAllListView(PermissionRequiredMixin, generic.ListView):
"""Generic class-based view listing all books on loan. Only visible to users with can_mark_returned permission."""
model = BookInstance
permission_required = 'catalog.can_mark_returned'
template_name = 'catalog/bookinstance_list_borrowed_all.html'
paginate_by = 10
def get_queryset(self):
return BookInstance.objects.filter(status__exact='o').order_by('due_back')
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
import datetime
from django.contrib.auth.decorators import login_required, permission_required
# from .forms import RenewBookForm
from catalog.forms import RenewBookForm
@login_required
@permission_required('catalog.can_mark_returned', raise_exception=True)
def renew_book_librarian(request, pk):
"""View function for renewing a specific BookInstance by librarian."""
book_instance = get_object_or_404(BookInstance, pk=pk)
# If this is a POST request then process the Form data
if request.method == 'POST': | # Create a form instance and populate it with data from the request (binding):
form = RenewBookForm(request.POST)
# Check if the form is valid:
if form.is_valid():
# process the data in form.cleaned_data as required (here we just write it to the model due_back field)
book_instance.due_back = form.cleaned_data['renewal_date']
book_instance.save()
# redirect to a new URL:
return HttpResponseRedirect(reverse('all-borrowed'))
# If this is a GET (or any other method) create the default form
else:
proposed_renewal_date = datetime.date.today() + datetime.timedelta(weeks=3)
form = RenewBookForm(initial={'renewal_date': proposed_renewal_date})
context = {
'form': form,
'book_instance': book_instance,
}
return render(request, 'catalog/book_renew_librarian.html', context)
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from catalog.models import Author
class AuthorCreate(CreateView):
model = Author
fields = ['first_name', 'last_name', 'date_of_birth', 'date_of_death']
initial = {'date_of_death': '11/06/2020'}
class AuthorUpdate(UpdateView):
model = Author
fields = '__all__' # Not recommended (potential security issue if more fields added)
class AuthorDelete(DeleteView):
model = Author
success_url = reverse_lazy('authors')
class BookCreate(CreateView):
model = Book
fields = ['title', 'author', 'summary', 'isbn', 'genre', 'language']
# initial = {'date_of_death': '11/06/2020'} | |
field_test.go | package template
import (
"testing"
"github.com/elastic/beats/libbeat/common"
"github.com/stretchr/testify/assert"
)
func TestField(t *testing.T) {
esVersion2, err := NewVersion("2.0.0")
assert.NoError(t, err)
falseVar := false
tests := []struct {
field Field
method func(f Field) common.MapStr
output common.MapStr
}{
{
field: Field{Type: "long"},
method: func(f Field) common.MapStr { return f.other() },
output: common.MapStr{
"type": "long",
},
},
{
field: Field{Type: "scaled_float"},
method: func(f Field) common.MapStr { return f.scaledFloat() },
output: common.MapStr{
"type": "scaled_float",
"scaling_factor": 1000,
},
},
{
field: Field{Type: "scaled_float", ScalingFactor: 100},
method: func(f Field) common.MapStr { return f.scaledFloat() },
output: common.MapStr{
"type": "scaled_float",
"scaling_factor": 100,
},
},
{
field: Field{Type: "scaled_float", esVersion: *esVersion2},
method: func(f Field) common.MapStr { return f.scaledFloat() },
output: common.MapStr{
"type": "float",
}, | {
field: Field{Type: "object", Enabled: &falseVar},
method: func(f Field) common.MapStr { return f.other() },
output: common.MapStr{
"type": "object",
"enabled": false,
},
},
{
field: Field{Type: "object", Enabled: &falseVar},
method: func(f Field) common.MapStr { return f.object() },
output: common.MapStr{
"type": "object",
"enabled": false,
},
},
{
field: Field{Type: "text", Analyzer: "autocomplete"},
method: func(f Field) common.MapStr { return f.text() },
output: common.MapStr{
"type": "text",
"analyzer": "autocomplete",
"norms": false,
},
},
{
field: Field{Type: "text", Analyzer: "autocomplete", Norms: true},
method: func(f Field) common.MapStr { return f.text() },
output: common.MapStr{
"type": "text",
"analyzer": "autocomplete",
},
},
{
field: Field{Type: "text", SearchAnalyzer: "standard", Norms: true},
method: func(f Field) common.MapStr { return f.text() },
output: common.MapStr{
"type": "text",
"search_analyzer": "standard",
},
},
{
field: Field{Type: "text", Analyzer: "autocomplete", SearchAnalyzer: "standard", Norms: true},
method: func(f Field) common.MapStr { return f.text() },
output: common.MapStr{
"type": "text",
"analyzer": "autocomplete",
"search_analyzer": "standard",
},
},
{
field: Field{Type: "text", MultiFields: Fields{Field{Name: "raw", Type: "keyword"}}, Norms: true},
method: func(f Field) common.MapStr { return f.text() },
output: common.MapStr{
"type": "text",
"fields": common.MapStr{
"raw": common.MapStr{
"type": "keyword",
"ignore_above": 1024,
},
},
},
},
{
field: Field{Type: "text", MultiFields: Fields{
Field{Name: "raw", Type: "keyword"},
Field{Name: "indexed", Type: "text"},
}, Norms: true},
method: func(f Field) common.MapStr { return f.text() },
output: common.MapStr{
"type": "text",
"fields": common.MapStr{
"raw": common.MapStr{
"type": "keyword",
"ignore_above": 1024,
},
"indexed": common.MapStr{
"type": "text",
"norms": false,
},
},
},
},
}
for _, test := range tests {
output := test.method(test.field)
assert.Equal(t, test.output, output)
}
}
func TestDynamicTemplate(t *testing.T) {
tests := []struct {
field Field
method func(f Field) common.MapStr
output common.MapStr
}{
{
field: Field{
Type: "object", ObjectType: "keyword",
Name: "context",
},
method: func(f Field) common.MapStr { return f.object() },
output: common.MapStr{
"context": common.MapStr{
"mapping": common.MapStr{"type": "keyword"},
"match_mapping_type": "string",
"path_match": "context.*",
},
},
},
{
field: Field{
Type: "object", ObjectType: "long",
path: "language", Name: "english",
},
method: func(f Field) common.MapStr { return f.object() },
output: common.MapStr{
"language.english": common.MapStr{
"mapping": common.MapStr{"type": "long"},
"match_mapping_type": "long",
"path_match": "language.english.*",
},
},
},
{
field: Field{
Type: "object", ObjectType: "text",
path: "language", Name: "english",
},
method: func(f Field) common.MapStr { return f.object() },
output: common.MapStr{
"language.english": common.MapStr{
"mapping": common.MapStr{"type": "text"},
"match_mapping_type": "string",
"path_match": "language.english.*",
},
},
},
}
for _, test := range tests {
dynamicTemplates = nil
test.method(test.field)
assert.Equal(t, test.output, dynamicTemplates[0])
}
} | }, |
evaluate_imagenet_gradcam_energy_inside_bbox.py | import argparse
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data.distributed
import torchvision.transforms as transforms
import resnet_multigpu_cgc as resnet
import cv2
import datasets as pointing_datasets
"""
Here, we evaluate the content heatmap (Grad-CAM heatmap within object bounding box) on the imagenet dataset.
"""
model_names = ['resnet18', 'resnet50']
parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument('data', metavar='DIR', help='path to dataset')
parser.add_argument('-a', '--arch', metavar='ARCH', default='resnet18',
choices=model_names,
help='model architecture: ' +
' | '.join(model_names) +
' (default: resnet18)')
parser.add_argument('-j', '--workers', default=16, type=int, metavar='N',
help='number of data loading workers (default: 16)')
parser.add_argument('-b', '--batch-size', default=256, type=int,
metavar='N', help='mini-batch size (default: 96)')
parser.add_argument('--pretrained', dest='pretrained', action='store_true',
help='use pre-trained model')
parser.add_argument('-g', '--num-gpus', default=1, type=int,
metavar='N', help='number of GPUs to match (default: 4)')
parser.add_argument('--resume', default='', type=str, metavar='PATH',
help='path to latest checkpoint (default: none)')
parser.add_argument('--input_resize', default=224, type=int,
metavar='N', help='Resize for smallest side of input (default: 224)')
def main():
global args
args = parser.parse_args()
if args.pretrained:
print("=> using pre-trained model '{}'".format(args.arch))
if args.arch.startswith('resnet'):
model = resnet.__dict__[args.arch](pretrained=True)
else:
assert False, 'Unsupported architecture: {}'.format(args.arch)
else:
print("=> creating model '{}'".format(args.arch))
if args.arch.startswith('resnet'):
model = resnet.__dict__[args.arch]()
model = torch.nn.DataParallel(model).cuda()
if args.resume:
print("=> loading checkpoint '{}'".format(args.resume))
checkpoint = torch.load(args.resume)
model.load_state_dict(checkpoint['state_dict'])
if (not args.resume) and (not args.pretrained):
assert False, "Please specify either the pre-trained model or checkpoint for evaluation"
cudnn.benchmark = True
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
# Here, we don't resize the images. We feed the full image and use AdaptivePooling before FC.
# We will resize Gradcam heatmap to image size and compare the actual bbox co-ordinates
val_dataset = pointing_datasets.ImageNetDetection(args.data,
transform=transforms.Compose([
transforms.Resize(args.input_resize),
transforms.ToTensor(),
normalize,
]))
# we set batch size=1 since we are loading full resolution images.
val_loader = torch.utils.data.DataLoader(
val_dataset, batch_size=1, shuffle=False,
num_workers=args.workers, pin_memory=True)
validate_multi(val_loader, val_dataset, model)
def | (val_loader, val_dataset, model):
batch_time = AverageMeter()
heatmap_inside_bbox = AverageMeter()
# switch to evaluate mode
model.eval()
end = time.time()
for i, (images, annotation, targets) in enumerate(val_loader):
images = images.cuda(non_blocking=True)
targets = targets.cuda(non_blocking=True)
# we assume batch size == 1 and unwrap the first elem of every list in annotation object
annotation = unwrap_dict(annotation)
image_size = val_dataset.as_image_size(annotation)
output, feats = model(images, vanilla_with_feats=True)
output_gradcam = compute_gradcam(output, feats, targets)
output_gradcam_np = output_gradcam.data.cpu().numpy()[0] # since we have batch size==1
resized_output_gradcam = cv2.resize(output_gradcam_np, image_size)
spatial_sum = resized_output_gradcam.sum()
if spatial_sum <= 0:
# We ignore images with zero Grad-CAM
continue
# resized_output_gradcam is now normalized and can be considered as probabilities
resized_output_gradcam = resized_output_gradcam / spatial_sum
mask = pointing_datasets.imagenet_as_mask(annotation, targets[0].item())
mask = mask.type(torch.ByteTensor)
mask = mask.cpu().data.numpy()
gcam_inside_gt_mask = mask * resized_output_gradcam
# Now we sum the heatmap inside the object bounding box
total_gcam_inside_gt_mask = gcam_inside_gt_mask.sum()
heatmap_inside_bbox.update(total_gcam_inside_gt_mask)
if i % 1000 == 0:
print('\nResults after {} examples: '.format(i+1))
print('Curr % of heatmap inside bbox: {:.4f} ({:.4f})'.format(heatmap_inside_bbox.val * 100,
heatmap_inside_bbox.avg * 100))
# measure elapsed time
batch_time.update(time.time() - end)
end = time.time()
print('\nFinal Results - ')
print('\n\n% of heatmap inside bbox: {:.4f}'.format(heatmap_inside_bbox.avg * 100))
return
def compute_gradcam(output, feats, target):
"""
Compute the gradcam for the top predicted category
:param output:
:param feats:
:param target:
:return:
"""
eps = 1e-8
relu = nn.ReLU(inplace=True)
target = target.cpu().numpy()
one_hot = np.zeros((output.shape[0], output.shape[-1]), dtype=np.float32)
indices_range = np.arange(output.shape[0])
one_hot[indices_range, target[indices_range]] = 1
one_hot = torch.from_numpy(one_hot)
one_hot.requires_grad = True
# Compute the Grad-CAM for the original image
one_hot_cuda = torch.sum(one_hot.cuda() * output)
dy_dz1, = torch.autograd.grad(one_hot_cuda, feats, grad_outputs=torch.ones(one_hot_cuda.size()).cuda(),
retain_graph=True, create_graph=True)
# Changing to dot product of grad and features to preserve grad spatial locations
gcam512_1 = dy_dz1 * feats
gradcam = gcam512_1.sum(dim=1)
gradcam = relu(gradcam)
spatial_sum1 = gradcam.sum(dim=[1, 2]).unsqueeze(-1).unsqueeze(-1)
gradcam = (gradcam / (spatial_sum1 + eps)) + eps
return gradcam
def unwrap_dict(dict_object):
new_dict = {}
for k, v in dict_object.items():
if k == 'object':
new_v_list = []
for elem in v:
new_v_list.append(unwrap_dict(elem))
new_dict[k] = new_v_list
continue
if isinstance(v, dict):
new_v = unwrap_dict(v)
elif isinstance(v, list) and len(v) == 1:
new_v = v[0]
else:
new_v = v
new_dict[k] = new_v
return new_dict
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.val = val
self.sum += val * n
self.count += n
self.avg = self.sum / self.count
if __name__ == '__main__':
main()
| validate_multi |
source_visit.ts | import { DataTypes, Model } from 'sequelize'
import { sequelize } from '../../core/db'
import Project from './project'
import Visitor from './visitor'
import { ISourceVisitCreate /* , ISourceVisitRetrieve */ } from '../types'
import { NotFound } from '../../core/http-exception'
class SourceVisit extends Model {
// 查找
static async getSourceVisit(/* sourceVisitInfo: ISourceVisitRetrieve */) {
// const { visitor, website, size, cost } = sourceVisitInfo
// todo 根据条件筛选
const list = await SourceVisit.findAll({
attributes: [
'id',
[sequelize.fn('inet_ntoa', sequelize.col('Visitor.ip')), 'visitor'],
[sequelize.col('Project.website'), 'website'],
'source_name',
'size',
'cost'
],
include: [
{
model: Project,
attributes: []
},
{
model: Visitor,
attributes: []
}
],
raw: true,
where: {}
})
return list
}
// 新增
static async addSourceVisit(sourceVisitInfo: ISourceVisitCreate) {
const { visitor, website, size, cost, sourceName } = sourceVisitInfo
// todo 新增前查看该资源是否被访问过,如果访问过只需记录加1 uv
// 1 将visitor转为id存储
// 2 将website转为id存储
const visitorId = await SourceVisit.getVisitorIdByVisitor(visitor)
const websiteId = await SourceVisit.getWebsiteIdByWebsite(website)
await SourceVisit.create({
visitor: visitorId,
website_id: websiteId,
source_name: sourceName,
size,
cost
})
}
// 删除
static async deleteSourceVisit(id: number) {
const record = SourceVisit.findOne({
where: {
id
}
})
if (!record) {
throw new NotFound('该删除项不存在')
}
await SourceVisit.destroy({
where: {
id
}
})
}
// 根据ip获取visitor_id
static async getVisitorIdByVisitor(ip: string) {
const record = await Visitor.findOne({
attributes: ['id'],
where: sequelize.where(
sequelize.fn('inet_ntoa', sequelize.col('Visitor.ip')),
ip
)
})
if (record) {
return record.getDataValue('id')
}
return null
}
// 根据website获取website_id
static async getWebsiteIdByWebsite(website: string) {
const record = await Project.findOne({
attributes: ['id'],
where: {
website
}
})
if (record) {
return record.getDataValue('id')
}
return null
}
}
SourceVisit.init(
{
id: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
autoIncrement: true,
primaryKey: true,
comment: '主键id'
},
visitor: {
type: DataTypes.INTEGER.UNSIGNED,
comment: '访问者id'
},
website_id: {
type: DataTypes.INTEGER.UNSIGNED,
comment: '网站地址id'
},
source_name: {
type: DataTypes.STRING(64),
comment: '资源名称'
},
size: {
type: DataTypes.INTEGER.UNSIGNED,
comment: '资源大小'
},
cost: {
type: DataTypes.INTEGER.UNSIGNED,
comment: '加载时长'
},
website: {
type: DataTypes.INTEGER.UNSIGNED,
field: 'website_id',
references: {
model: Project,
key: 'id'
}
},
visitor_id: {
type: DataTypes.INTEGER.UNSIGNED,
field: 'visitor',
references: {
model: Visitor, | }
},
{
sequelize,
tableName: 'source_visit',
timestamps: true,
createdAt: 'create_time',
updatedAt: false,
indexes: [
{
unique: true,
fields: ['id']
},
{
fields: ['website_id']
},
{
fields: ['visitor']
}
]
}
)
SourceVisit.belongsTo(Project, {
foreignKey: 'website_id'
})
SourceVisit.belongsTo(Visitor, {
foreignKey: 'visitor'
})
export default SourceVisit | key: 'id'
} |
bool_model_operations.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 msrest.pipeline import ClientRawResponse
from .. import models
class BoolModelOperations(object):
| """BoolModelOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
def __init__(self, client, config, serializer, deserializer):
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self.config = config
def get_true(
self, custom_headers=None, raw=False, **operation_config):
"""Get true Boolean value.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: bool
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
:raises:
:class:`ErrorException<fixtures.acceptancetestsbodyboolean.models.ErrorException>`
"""
# Construct URL
url = '/bool/true'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('bool', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
def put_true(
self, bool_body, custom_headers=None, raw=False, **operation_config):
"""Set Boolean value true.
:param bool_body:
:type bool_body: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
:raises:
:class:`ErrorException<fixtures.acceptancetestsbodyboolean.models.ErrorException>`
"""
# Construct URL
url = '/bool/true'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(bool_body, 'bool')
# Construct and send request
request = self._client.put(url, query_parameters)
response = self._client.send(
request, header_parameters, body_content, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_false(
self, custom_headers=None, raw=False, **operation_config):
"""Get false Boolean value.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: bool
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
:raises:
:class:`ErrorException<fixtures.acceptancetestsbodyboolean.models.ErrorException>`
"""
# Construct URL
url = '/bool/false'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('bool', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
def put_false(
self, bool_body, custom_headers=None, raw=False, **operation_config):
"""Set Boolean value false.
:param bool_body:
:type bool_body: bool
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: None
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
:raises:
:class:`ErrorException<fixtures.acceptancetestsbodyboolean.models.ErrorException>`
"""
# Construct URL
url = '/bool/false'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct body
body_content = self._serialize.body(bool_body, 'bool')
# Construct and send request
request = self._client.put(url, query_parameters)
response = self._client.send(
request, header_parameters, body_content, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
if raw:
client_raw_response = ClientRawResponse(None, response)
return client_raw_response
def get_null(
self, custom_headers=None, raw=False, **operation_config):
"""Get null Boolean value.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: bool
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
:raises:
:class:`ErrorException<fixtures.acceptancetestsbodyboolean.models.ErrorException>`
"""
# Construct URL
url = '/bool/null'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('bool', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized
def get_invalid(
self, custom_headers=None, raw=False, **operation_config):
"""Get invalid Boolean value.
:param dict custom_headers: headers that will be added to the request
:param bool raw: returns the direct response alongside the
deserialized response
:param operation_config: :ref:`Operation configuration
overrides<msrest:optionsforoperations>`.
:rtype: bool
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
:raises:
:class:`ErrorException<fixtures.acceptancetestsbodyboolean.models.ErrorException>`
"""
# Construct URL
url = '/bool/invalid'
# Construct parameters
query_parameters = {}
# Construct headers
header_parameters = {}
header_parameters['Content-Type'] = 'application/json; charset=utf-8'
if custom_headers:
header_parameters.update(custom_headers)
# Construct and send request
request = self._client.get(url, query_parameters)
response = self._client.send(request, header_parameters, **operation_config)
if response.status_code not in [200]:
raise models.ErrorException(self._deserialize, response)
deserialized = None
if response.status_code == 200:
deserialized = self._deserialize('bool', response)
if raw:
client_raw_response = ClientRawResponse(deserialized, response)
return client_raw_response
return deserialized |
|
region_request.go | // Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package tikv
import (
"bytes"
"context"
"fmt"
"strconv"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"github.com/opentracing/opentracing-go"
"github.com/pingcap/errors"
"github.com/pingcap/failpoint"
"github.com/pingcap/kvproto/pkg/coprocessor"
"github.com/pingcap/kvproto/pkg/errorpb"
"github.com/pingcap/kvproto/pkg/kvrpcpb"
"github.com/pingcap/tidb/kv"
tidbmetrics "github.com/pingcap/tidb/metrics"
"github.com/pingcap/tidb/store/tikv/logutil"
"github.com/pingcap/tidb/store/tikv/metrics"
"github.com/pingcap/tidb/store/tikv/storeutil"
"github.com/pingcap/tidb/store/tikv/tikvrpc"
"github.com/pingcap/tidb/store/tikv/util"
"github.com/pingcap/tidb/util/execdetails"
)
// ShuttingDown is a flag to indicate tidb-server is exiting (Ctrl+C signal
// receved for example). If this flag is set, tikv client should not retry on
// network error because tidb-server expect tikv client to exit as soon as possible.
var ShuttingDown uint32
// RegionRequestSender sends KV/Cop requests to tikv server. It handles network
// errors and some region errors internally.
//
// Typically, a KV/Cop request is bind to a region, all keys that are involved
// in the request should be located in the region.
// The sending process begins with looking for the address of leader store's
// address of the target region from cache, and the request is then sent to the
// destination tikv server over TCP connection.
// If region is updated, can be caused by leader transfer, region split, region
// merge, or region balance, tikv server may not able to process request and
// send back a RegionError.
// RegionRequestSender takes care of errors that does not relevant to region
// range, such as 'I/O timeout', 'NotLeader', and 'ServerIsBusy'. For other
// errors, since region range have changed, the request may need to split, so we
// simply return the error to caller.
type RegionRequestSender struct {
regionCache *RegionCache
client Client
storeAddr string
rpcError error
failStoreIDs map[uint64]struct{}
RegionRequestRuntimeStats
}
// RegionRequestRuntimeStats records the runtime stats of send region requests.
type RegionRequestRuntimeStats struct {
Stats map[tikvrpc.CmdType]*RPCRuntimeStats
}
// NewRegionRequestRuntimeStats returns a new RegionRequestRuntimeStats.
func NewRegionRequestRuntimeStats() RegionRequestRuntimeStats {
return RegionRequestRuntimeStats{
Stats: make(map[tikvrpc.CmdType]*RPCRuntimeStats),
}
}
// RPCRuntimeStats indicates the RPC request count and consume time.
type RPCRuntimeStats struct {
Count int64
// Send region request consume time.
Consume int64
}
// String implements fmt.Stringer interface.
func (r *RegionRequestRuntimeStats) String() string {
var buf bytes.Buffer
for k, v := range r.Stats {
if buf.Len() > 0 {
buf.WriteByte(',')
}
buf.WriteString(fmt.Sprintf("%s:{num_rpc:%d, total_time:%s}", k.String(), v.Count, execdetails.FormatDuration(time.Duration(v.Consume))))
}
return buf.String()
}
// Clone returns a copy of itself.
func (r *RegionRequestRuntimeStats) Clone() RegionRequestRuntimeStats {
newRs := NewRegionRequestRuntimeStats()
for cmd, v := range r.Stats {
newRs.Stats[cmd] = &RPCRuntimeStats{
Count: v.Count,
Consume: v.Consume,
}
}
return newRs
}
// Merge merges other RegionRequestRuntimeStats.
func (r *RegionRequestRuntimeStats) Merge(rs RegionRequestRuntimeStats) {
for cmd, v := range rs.Stats {
stat, ok := r.Stats[cmd]
if !ok {
r.Stats[cmd] = &RPCRuntimeStats{
Count: v.Count,
Consume: v.Consume,
}
continue
}
stat.Count += v.Count
stat.Consume += v.Consume
}
}
// RegionBatchRequestSender sends BatchCop requests to TiFlash server by stream way.
type RegionBatchRequestSender struct {
RegionRequestSender
}
// NewRegionBatchRequestSender creates a RegionBatchRequestSender object.
func NewRegionBatchRequestSender(cache *RegionCache, client Client) *RegionBatchRequestSender {
return &RegionBatchRequestSender{RegionRequestSender: RegionRequestSender{regionCache: cache, client: client}}
}
func (ss *RegionBatchRequestSender) sendStreamReqToAddr(bo *Backoffer, ctxs []copTaskAndRPCContext, req *tikvrpc.Request, timout time.Duration) (resp *tikvrpc.Response, retry bool, cancel func(), err error) {
// use the first ctx to send request, because every ctx has same address.
cancel = func() {}
rpcCtx := ctxs[0].ctx
if e := tikvrpc.SetContext(req, rpcCtx.Meta, rpcCtx.Peer); e != nil {
return nil, false, cancel, errors.Trace(e)
}
ctx := bo.ctx
if rawHook := ctx.Value(RPCCancellerCtxKey{}); rawHook != nil {
ctx, cancel = rawHook.(*RPCCanceller).WithCancel(ctx)
}
start := time.Now()
resp, err = ss.client.SendRequest(ctx, rpcCtx.Addr, req, timout)
if ss.Stats != nil {
recordRegionRequestRuntimeStats(ss.Stats, req.Type, time.Since(start))
}
if err != nil {
cancel()
ss.rpcError = err
e := ss.onSendFail(bo, ctxs, err)
if e != nil {
return nil, false, func() {}, errors.Trace(e)
}
return nil, true, func() {}, nil
}
// We don't need to process region error or lock error. Because TiFlash will retry by itself.
return
}
func recordRegionRequestRuntimeStats(stats map[tikvrpc.CmdType]*RPCRuntimeStats, cmd tikvrpc.CmdType, d time.Duration) {
stat, ok := stats[cmd]
if !ok {
stats[cmd] = &RPCRuntimeStats{
Count: 1,
Consume: int64(d),
}
return
}
stat.Count++
stat.Consume += int64(d)
}
func (ss *RegionBatchRequestSender) onSendFail(bo *Backoffer, ctxs []copTaskAndRPCContext, err error) error {
// If it failed because the context is cancelled by ourself, don't retry.
if errors.Cause(err) == context.Canceled || status.Code(errors.Cause(err)) == codes.Canceled {
return errors.Trace(err)
} else if atomic.LoadUint32(&ShuttingDown) > 0 {
return errTiDBShuttingDown
}
for _, failedCtx := range ctxs {
ctx := failedCtx.ctx
if ctx.Meta != nil {
ss.regionCache.OnSendFail(bo, ctx, ss.needReloadRegion(ctx), err)
}
}
// Retry on send request failure when it's not canceled.
// When a store is not available, the leader of related region should be elected quickly.
// TODO: the number of retry time should be limited:since region may be unavailable
// when some unrecoverable disaster happened.
err = bo.Backoff(boTiKVRPC, errors.Errorf("send tikv request error: %v, ctxs: %v, try next peer later", err, ctxs))
return errors.Trace(err)
}
// NewRegionRequestSender creates a new sender.
func NewRegionRequestSender(regionCache *RegionCache, client Client) *RegionRequestSender {
return &RegionRequestSender{
regionCache: regionCache,
client: client,
}
}
// SendReq sends a request to tikv server.
func (s *RegionRequestSender) SendReq(bo *Backoffer, req *tikvrpc.Request, regionID RegionVerID, timeout time.Duration) (*tikvrpc.Response, error) {
resp, _, err := s.SendReqCtx(bo, req, regionID, timeout, kv.TiKV)
return resp, err
}
func (s *RegionRequestSender) getRPCContext(
bo *Backoffer,
req *tikvrpc.Request,
regionID RegionVerID,
sType kv.StoreType,
) (*RPCContext, error) {
switch sType {
case kv.TiKV:
var seed uint32
if req.ReplicaReadSeed != nil {
seed = *req.ReplicaReadSeed
}
return s.regionCache.GetTiKVRPCContext(bo, regionID, req.ReplicaReadType, seed)
case kv.TiFlash:
return s.regionCache.GetTiFlashRPCContext(bo, regionID)
case kv.TiDB:
return &RPCContext{Addr: s.storeAddr}, nil
default:
return nil, errors.Errorf("unsupported storage type: %v", sType)
}
}
// SendReqCtx sends a request to tikv server and return response and RPCCtx of this RPC.
func (s *RegionRequestSender) SendReqCtx(
bo *Backoffer,
req *tikvrpc.Request,
regionID RegionVerID,
timeout time.Duration,
sType kv.StoreType,
) (
resp *tikvrpc.Response,
rpcCtx *RPCContext,
err error,
) {
if span := opentracing.SpanFromContext(bo.ctx); span != nil && span.Tracer() != nil {
span1 := span.Tracer().StartSpan("regionRequest.SendReqCtx", opentracing.ChildOf(span.Context()))
defer span1.Finish()
bo = bo.Clone()
bo.ctx = opentracing.ContextWithSpan(bo.ctx, span1)
}
failpoint.Inject("tikvStoreSendReqResult", func(val failpoint.Value) {
switch val.(string) {
case "timeout":
failpoint.Return(nil, nil, errors.New("timeout"))
case "GCNotLeader":
if req.Type == tikvrpc.CmdGC {
failpoint.Return(&tikvrpc.Response{
Resp: &kvrpcpb.GCResponse{RegionError: &errorpb.Error{NotLeader: &errorpb.NotLeader{}}},
}, nil, nil)
}
case "GCServerIsBusy":
if req.Type == tikvrpc.CmdGC {
failpoint.Return(&tikvrpc.Response{
Resp: &kvrpcpb.GCResponse{RegionError: &errorpb.Error{ServerIsBusy: &errorpb.ServerIsBusy{}}},
}, nil, nil)
}
case "callBackofferHook":
if bo.vars != nil && bo.vars.Hook != nil {
bo.vars.Hook("callBackofferHook", bo.vars)
}
case "requestTiDBStoreError":
if sType == kv.TiDB {
failpoint.Return(nil, nil, ErrTiKVServerTimeout)
}
}
})
tryTimes := 0
for {
if (tryTimes > 0) && (tryTimes%100000 == 0) {
logutil.Logger(bo.ctx).Warn("retry get ", zap.Uint64("region = ", regionID.GetID()), zap.Int("times = ", tryTimes))
}
rpcCtx, err = s.getRPCContext(bo, req, regionID, sType)
if err != nil {
return nil, nil, err
}
failpoint.Inject("invalidCacheAndRetry", func() {
// cooperate with github.com/pingcap/tidb/store/gcworker/setGcResolveMaxBackoff
if c := bo.ctx.Value("injectedBackoff"); c != nil {
resp, err = tikvrpc.GenRegionErrorResp(req, &errorpb.Error{EpochNotMatch: &errorpb.EpochNotMatch{}})
failpoint.Return(resp, nil, err)
}
})
if rpcCtx == nil {
// If the region is not found in cache, it must be out
// of date and already be cleaned up. We can skip the
// RPC by returning RegionError directly.
// TODO: Change the returned error to something like "region missing in cache",
// and handle this error like EpochNotMatch, which means to re-split the request and retry.
resp, err = tikvrpc.GenRegionErrorResp(req, &errorpb.Error{EpochNotMatch: &errorpb.EpochNotMatch{}})
return resp, nil, err
}
logutil.Eventf(bo.ctx, "send %s request to region %d at %s", req.Type, regionID.id, rpcCtx.Addr)
s.storeAddr = rpcCtx.Addr
var retry bool
resp, retry, err = s.sendReqToRegion(bo, rpcCtx, req, timeout)
if err != nil {
return nil, nil, errors.Trace(err)
}
// recheck whether the session/query is killed during the Next()
if bo.vars != nil && bo.vars.Killed != nil && atomic.LoadUint32(bo.vars.Killed) == 1 {
return nil, nil, ErrQueryInterrupted
}
failpoint.Inject("mockRetrySendReqToRegion", func(val failpoint.Value) {
if val.(bool) {
retry = true
}
})
if retry {
tryTimes++
continue
}
var regionErr *errorpb.Error
regionErr, err = resp.GetRegionError()
if err != nil {
return nil, nil, errors.Trace(err)
}
if regionErr != nil {
retry, err = s.onRegionError(bo, rpcCtx, req.ReplicaReadSeed, regionErr)
if err != nil {
return nil, nil, errors.Trace(err)
}
if retry {
tryTimes++
continue
}
}
return resp, rpcCtx, nil
}
}
// RPCCancellerCtxKey is context key attach rpc send cancelFunc collector to ctx.
type RPCCancellerCtxKey struct{}
// RPCCanceller is rpc send cancelFunc collector.
type RPCCanceller struct {
sync.Mutex
allocID int
cancels map[int]func()
cancelled bool
}
// NewRPCanceller creates RPCCanceller with init state.
func NewRPCanceller() *RPCCanceller {
return &RPCCanceller{cancels: make(map[int]func())}
}
// WithCancel generates new context with cancel func.
func (h *RPCCanceller) WithCancel(ctx context.Context) (context.Context, func()) {
nctx, cancel := context.WithCancel(ctx)
h.Lock()
if h.cancelled {
h.Unlock()
cancel()
return nctx, func() {}
}
id := h.allocID
h.allocID++
h.cancels[id] = cancel
h.Unlock()
return nctx, func() {
cancel()
h.Lock()
delete(h.cancels, id)
h.Unlock()
}
}
// CancelAll cancels all inflight rpc context.
func (h *RPCCanceller) CancelAll() {
h.Lock()
for _, c := range h.cancels {
c()
}
h.cancelled = true
h.Unlock()
}
func (s *RegionRequestSender) sendReqToRegion(bo *Backoffer, rpcCtx *RPCContext, req *tikvrpc.Request, timeout time.Duration) (resp *tikvrpc.Response, retry bool, err error) {
if e := tikvrpc.SetContext(req, rpcCtx.Meta, rpcCtx.Peer); e != nil {
return nil, false, errors.Trace(e)
}
// judge the store limit switch.
if limit := storeutil.StoreLimit.Load(); limit > 0 {
if err := s.getStoreToken(rpcCtx.Store, limit); err != nil {
return nil, false, err
}
defer s.releaseStoreToken(rpcCtx.Store)
}
ctx := bo.ctx
if rawHook := ctx.Value(RPCCancellerCtxKey{}); rawHook != nil {
var cancel context.CancelFunc
ctx, cancel = rawHook.(*RPCCanceller).WithCancel(ctx)
defer cancel()
}
var sessionID uint64
if v := bo.ctx.Value(util.SessionID); v != nil {
sessionID = v.(uint64)
}
injectFailOnSend := false
failpoint.Inject("rpcFailOnSend", func(val failpoint.Value) {
inject := true
// Optional filters
if s, ok := val.(string); ok {
if s == "greengc" && !req.IsGreenGCRequest() {
inject = false
} else if s == "write" && !req.IsTxnWriteRequest() {
inject = false
}
} else if sessionID == 0 {
inject = false
}
if inject {
logutil.Logger(ctx).Info("[failpoint] injected RPC error on send", zap.Stringer("type", req.Type),
zap.Stringer("req", req.Req.(fmt.Stringer)), zap.Stringer("ctx", &req.Context))
injectFailOnSend = true
err = errors.New("injected RPC error on send")
}
})
if !injectFailOnSend {
start := time.Now()
resp, err = s.client.SendRequest(ctx, rpcCtx.Addr, req, timeout)
if s.Stats != nil {
recordRegionRequestRuntimeStats(s.Stats, req.Type, time.Since(start))
failpoint.Inject("tikvStoreRespResult", func(val failpoint.Value) {
if val.(bool) {
if req.Type == tikvrpc.CmdCop && bo.totalSleep == 0 {
failpoint.Return(&tikvrpc.Response{
Resp: &coprocessor.Response{RegionError: &errorpb.Error{EpochNotMatch: &errorpb.EpochNotMatch{}}},
}, false, nil)
}
}
})
}
failpoint.Inject("rpcFailOnRecv", func(val failpoint.Value) {
inject := true
// Optional filters
if s, ok := val.(string); ok {
if s == "greengc" && !req.IsGreenGCRequest() {
inject = false
} else if s == "write" && !req.IsTxnWriteRequest() {
inject = false
}
} else if sessionID == 0 {
inject = false
}
if inject {
logutil.Logger(ctx).Info("[failpoint] injected RPC error on recv", zap.Stringer("type", req.Type),
zap.Stringer("req", req.Req.(fmt.Stringer)), zap.Stringer("ctx", &req.Context))
err = errors.New("injected RPC error on recv")
resp = nil
}
})
failpoint.Inject("rpcContextCancelErr", func(val failpoint.Value) {
if val.(bool) {
ctx1, cancel := context.WithCancel(context.Background())
cancel()
select {
case <-ctx1.Done():
}
ctx = ctx1
err = ctx.Err()
resp = nil
}
})
}
if err != nil {
s.rpcError = err
// Because in rpc logic, context.Cancel() will be transferred to rpcContext.Cancel error. For rpcContext cancel,
// we need to retry the request. But for context cancel active, for example, limitExec gets the required rows,
// we shouldn't retry the request, it will go to backoff and hang in retry logic.
if ctx.Err() != nil && errors.Cause(ctx.Err()) == context.Canceled {
return nil, false, errors.Trace(ctx.Err())
}
failpoint.Inject("noRetryOnRpcError", func(val failpoint.Value) {
if val.(bool) {
failpoint.Return(nil, false, err)
}
})
if e := s.onSendFail(bo, rpcCtx, err); e != nil {
return nil, false, errors.Trace(e)
}
return nil, true, nil
} | // Checking limit is not thread safe, preferring this for avoiding load in loop.
count := st.tokenCount.Load()
if count < limit {
// Adding tokenCount is no thread safe, preferring this for avoiding check in loop.
st.tokenCount.Add(1)
return nil
}
tidbmetrics.GetStoreLimitErrorCounter.WithLabelValues(st.addr, strconv.FormatUint(st.storeID, 10)).Inc()
return ErrTokenLimit.GenWithStackByArgs(st.storeID)
}
func (s *RegionRequestSender) releaseStoreToken(st *Store) {
count := st.tokenCount.Load()
// Decreasing tokenCount is no thread safe, preferring this for avoiding check in loop.
if count > 0 {
st.tokenCount.Sub(1)
return
}
logutil.BgLogger().Warn("release store token failed, count equals to 0")
}
func (s *RegionRequestSender) onSendFail(bo *Backoffer, ctx *RPCContext, err error) error {
if span := opentracing.SpanFromContext(bo.ctx); span != nil && span.Tracer() != nil {
span1 := span.Tracer().StartSpan("regionRequest.onSendFail", opentracing.ChildOf(span.Context()))
defer span1.Finish()
bo = bo.Clone()
bo.ctx = opentracing.ContextWithSpan(bo.ctx, span1)
}
// If it failed because the context is cancelled by ourself, don't retry.
if errors.Cause(err) == context.Canceled {
return errors.Trace(err)
} else if atomic.LoadUint32(&ShuttingDown) > 0 {
return errTiDBShuttingDown
}
if status.Code(errors.Cause(err)) == codes.Canceled {
select {
case <-bo.ctx.Done():
return errors.Trace(err)
default:
// If we don't cancel, but the error code is Canceled, it must be from grpc remote.
// This may happen when tikv is killed and exiting.
// Backoff and retry in this case.
logutil.BgLogger().Warn("receive a grpc cancel signal from remote", zap.Error(err))
}
}
if ctx.Meta != nil {
s.regionCache.OnSendFail(bo, ctx, s.needReloadRegion(ctx), err)
}
// Retry on send request failure when it's not canceled.
// When a store is not available, the leader of related region should be elected quickly.
// TODO: the number of retry time should be limited:since region may be unavailable
// when some unrecoverable disaster happened.
if ctx.Store != nil && ctx.Store.storeType == kv.TiFlash {
err = bo.Backoff(boTiFlashRPC, errors.Errorf("send tiflash request error: %v, ctx: %v, try next peer later", err, ctx))
} else {
err = bo.Backoff(boTiKVRPC, errors.Errorf("send tikv request error: %v, ctx: %v, try next peer later", err, ctx))
}
return errors.Trace(err)
}
// needReloadRegion checks is all peers has sent failed, if so need reload.
func (s *RegionRequestSender) needReloadRegion(ctx *RPCContext) (need bool) {
if s.failStoreIDs == nil {
s.failStoreIDs = make(map[uint64]struct{})
}
s.failStoreIDs[ctx.Store.storeID] = struct{}{}
need = len(s.failStoreIDs) == len(ctx.Meta.Peers)
if need {
s.failStoreIDs = nil
}
return
}
func regionErrorToLabel(e *errorpb.Error) string {
if e.GetNotLeader() != nil {
return "not_leader"
} else if e.GetRegionNotFound() != nil {
return "region_not_found"
} else if e.GetKeyNotInRegion() != nil {
return "key_not_in_region"
} else if e.GetEpochNotMatch() != nil {
return "epoch_not_match"
} else if e.GetServerIsBusy() != nil {
return "server_is_busy"
} else if e.GetStaleCommand() != nil {
return "stale_command"
} else if e.GetStoreNotMatch() != nil {
return "store_not_match"
}
return "unknown"
}
func (s *RegionRequestSender) onRegionError(bo *Backoffer, ctx *RPCContext, seed *uint32, regionErr *errorpb.Error) (retry bool, err error) {
if span := opentracing.SpanFromContext(bo.ctx); span != nil && span.Tracer() != nil {
span1 := span.Tracer().StartSpan("tikv.onRegionError", opentracing.ChildOf(span.Context()))
defer span1.Finish()
bo = bo.Clone()
bo.ctx = opentracing.ContextWithSpan(bo.ctx, span1)
}
metrics.TiKVRegionErrorCounter.WithLabelValues(regionErrorToLabel(regionErr)).Inc()
if notLeader := regionErr.GetNotLeader(); notLeader != nil {
// Retry if error is `NotLeader`.
logutil.BgLogger().Debug("tikv reports `NotLeader` retry later",
zap.String("notLeader", notLeader.String()),
zap.String("ctx", ctx.String()))
if notLeader.GetLeader() == nil {
// The peer doesn't know who is the current leader. Generally it's because
// the Raft group is in an election, but it's possible that the peer is
// isolated and removed from the Raft group. So it's necessary to reload
// the region from PD.
s.regionCache.InvalidateCachedRegion(ctx.Region)
if err = bo.Backoff(BoRegionMiss, errors.Errorf("not leader: %v, ctx: %v", notLeader, ctx)); err != nil {
return false, errors.Trace(err)
}
} else {
// don't backoff if a new leader is returned.
s.regionCache.UpdateLeader(ctx.Region, notLeader.GetLeader().GetStoreId(), ctx.AccessIdx)
}
return true, nil
}
if storeNotMatch := regionErr.GetStoreNotMatch(); storeNotMatch != nil {
// store not match
logutil.BgLogger().Warn("tikv reports `StoreNotMatch` retry later",
zap.Stringer("storeNotMatch", storeNotMatch),
zap.Stringer("ctx", ctx))
ctx.Store.markNeedCheck(s.regionCache.notifyCheckCh)
return true, nil
}
if epochNotMatch := regionErr.GetEpochNotMatch(); epochNotMatch != nil {
logutil.BgLogger().Debug("tikv reports `EpochNotMatch` retry later",
zap.Stringer("EpochNotMatch", epochNotMatch),
zap.Stringer("ctx", ctx))
if seed != nil {
*seed = *seed + 1
}
err = s.regionCache.OnRegionEpochNotMatch(bo, ctx, epochNotMatch.CurrentRegions)
return false, errors.Trace(err)
}
if regionErr.GetServerIsBusy() != nil {
logutil.BgLogger().Warn("tikv reports `ServerIsBusy` retry later",
zap.String("reason", regionErr.GetServerIsBusy().GetReason()),
zap.Stringer("ctx", ctx))
if ctx != nil && ctx.Store != nil && ctx.Store.storeType == kv.TiFlash {
err = bo.Backoff(boTiFlashServerBusy, errors.Errorf("server is busy, ctx: %v", ctx))
} else {
err = bo.Backoff(boTiKVServerBusy, errors.Errorf("server is busy, ctx: %v", ctx))
}
if err != nil {
return false, errors.Trace(err)
}
return true, nil
}
if regionErr.GetStaleCommand() != nil {
logutil.BgLogger().Debug("tikv reports `StaleCommand`", zap.Stringer("ctx", ctx))
err = bo.Backoff(boStaleCmd, errors.Errorf("stale command, ctx: %v", ctx))
if err != nil {
return false, errors.Trace(err)
}
return true, nil
}
if regionErr.GetRaftEntryTooLarge() != nil {
logutil.BgLogger().Warn("tikv reports `RaftEntryTooLarge`", zap.Stringer("ctx", ctx))
return false, errors.New(regionErr.String())
}
if regionErr.GetRegionNotFound() != nil && seed != nil {
logutil.BgLogger().Debug("tikv reports `RegionNotFound` in follow-reader",
zap.Stringer("ctx", ctx), zap.Uint32("seed", *seed))
*seed = *seed + 1
}
if regionErr.GetMaxTimestampNotSynced() != nil {
logutil.BgLogger().Warn("tikv reports `MaxTimestampNotSynced`", zap.Stringer("ctx", ctx))
err = bo.Backoff(boMaxTsNotSynced, errors.Errorf("max timestamp not synced, ctx: %v", ctx))
if err != nil {
return false, errors.Trace(err)
}
return true, nil
}
// For other errors, we only drop cache here.
// Because caller may need to re-split the request.
logutil.BgLogger().Debug("tikv reports region failed",
zap.Stringer("regionErr", regionErr),
zap.Stringer("ctx", ctx))
// When the request is sent to TiDB, there is no region in the request, so the region id will be 0.
// So when region id is 0, there is no business with region cache.
if ctx.Region.id != 0 {
s.regionCache.InvalidateCachedRegion(ctx.Region)
}
return false, nil
}
func pbIsolationLevel(level kv.IsoLevel) kvrpcpb.IsolationLevel {
switch level {
case kv.RC:
return kvrpcpb.IsolationLevel_RC
case kv.SI:
return kvrpcpb.IsolationLevel_SI
default:
return kvrpcpb.IsolationLevel_SI
}
} | return
}
func (s *RegionRequestSender) getStoreToken(st *Store, limit int64) error { |
user.model.test.js | /* eslint-disable */
const expect = require('chai').expect;
const mongoose = require('mongoose');
const User = mongoose.model('User');
const mock = {
john: {
firstName: 'John',
lastName: 'Doe',
username: 'jdoe',
password: 'JD0eP@ss',
email: '[email protected]'
},
jane: {
firstName: 'Jane',
lastName: 'Doe',
username: 'janey',
password: '12JaneyP@ss',
email: '[email protected]'
}
};
let user1, user2, user3;
// Mocha Tests
describe('User Model Unit Tests:', () => {
before(done => {
User.remove().exec(() => {
user1 = new User(mock.john);
user2 = new User(mock.jane);
user3 = new User(mock.john);
done();
});
});
it('should start with an empty collection', done => {
User.find().exec((err, users) => {
expect(users).to.have.length(0);
done();
});
});
describe('Method Save', () => {
it('should allow john to save without issues', done => {
user1.save(err => {
expect(err).to.not.exist;
done();
});
});
it('should now contain a single user', done => {
User.find().exec((err, users) => {
expect(users).to.have.length(1);
done();
});
});
it('should allow a different user to save without issues', done => {
user2.save(err => {
expect(err).to.not.exist;
done();
});
});
it('should now contain two users', done => {
User.find().exec((err, users) => {
expect(users).to.have.length(2);
done();
});
});
it('should prevent saving a user with the same username', done => {
user3.save(err => {
expect(err).to.exist;
done();
});
});
it('should prevent saving without a firstName', done => {
user1.firstName = '';
user1.save(err => {
expect(err).to.exist;
done();
});
});
| user1.firstName = 'John';
user1.lastName = '';
user1.save(err => {
expect(err).to.exist;
done();
});
});
it('should prevent saving without a valid password', done => {
user1.lastName = 'Doe';
user1.password = 'jdoepass';
user1.save(err => {
expect(err).to.exist;
done();
});
});
it('should prevent saving without a valid email', done => {
user1.password = 'JD0eP@ss';
user1.email = 'jdoe@gmail';
user1.save(err => {
expect(err).to.exist;
done();
});
});
});
after(() => {
User.remove().exec();
});
}); | it('should prevent saving without a lastName', done => { |
events_ttrpc.rs | // This file is generated by ttrpc-compiler 0.4.0. Do not edit
// @generated
// https://github.com/Manishearth/rust-clippy/issues/702
#![allow(unknown_lints)]
#![allow(clipto_camel_casepy)]
#![cfg_attr(rustfmt, rustfmt_skip)]
#![allow(box_pointers)]
#![allow(dead_code)]
#![allow(missing_docs)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(non_upper_case_globals)]
#![allow(trivial_casts)]
#![allow(unsafe_code)]
#![allow(unused_imports)]
#![allow(unused_results)]
use protobuf::{CodedInputStream, CodedOutputStream, Message};
use std::collections::HashMap;
use std::sync::Arc;
#[derive(Clone)]
pub struct EventsClient {
client: ::ttrpc::Client,
}
impl EventsClient {
pub fn new(client: ::ttrpc::Client) -> Self {
EventsClient {
client: client,
}
}
pub fn forward(&self, ctx: ttrpc::context::Context, req: &super::events::ForwardRequest) -> ::ttrpc::Result<super::empty::Empty> {
let mut cres = super::empty::Empty::new();
::ttrpc::client_request!(self, ctx, req, "containerd.services.events.ttrpc.v1.Events", "Forward", cres);
Ok(cres)
}
}
struct ForwardMethod {
service: Arc<std::boxed::Box<dyn Events + Send + Sync>>,
}
impl ::ttrpc::MethodHandler for ForwardMethod {
fn handler(&self, ctx: ::ttrpc::TtrpcContext, req: ::ttrpc::Request) -> ::ttrpc::Result<()> {
::ttrpc::request_handler!(self, ctx, req, events, ForwardRequest, forward);
Ok(())
}
}
pub trait Events {
fn forward(&self, _ctx: &::ttrpc::TtrpcContext, _req: super::events::ForwardRequest) -> ::ttrpc::Result<super::empty::Empty> {
Err(::ttrpc::Error::RpcStatus(::ttrpc::get_status(::ttrpc::Code::NOT_FOUND, "/containerd.services.events.ttrpc.v1.Events/Forward is not supported".to_string())))
}
}
pub fn | (service: Arc<std::boxed::Box<dyn Events + Send + Sync>>) -> HashMap <String, Box<dyn ::ttrpc::MethodHandler + Send + Sync>> {
let mut methods = HashMap::new();
methods.insert("/containerd.services.events.ttrpc.v1.Events/Forward".to_string(),
std::boxed::Box::new(ForwardMethod{service: service.clone()}) as std::boxed::Box<dyn ::ttrpc::MethodHandler + Send + Sync>);
methods
}
| create_events |
local_test_cluster_util.go | // Copyright 2015 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package kv
import (
"context"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/gossip"
"github.com/cockroachdb/cockroach/pkg/internal/client"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/rpc/nodedialer"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/stop"
"github.com/opentracing/opentracing-go"
)
// localTestClusterTransport augments senderTransport with an optional
// delay for each RPC, to simulate latency for benchmarking.
// TODO(bdarnell): there's probably a better place to put this.
type localTestClusterTransport struct {
Transport
latency time.Duration
}
func (l *localTestClusterTransport) SendNext(
ctx context.Context, ba roachpb.BatchRequest,
) (*roachpb.BatchResponse, error) {
if l.latency > 0 |
return l.Transport.SendNext(ctx, ba)
}
// InitFactoryForLocalTestCluster initializes a TxnCoordSenderFactory
// that can be used with LocalTestCluster.
func InitFactoryForLocalTestCluster(
st *cluster.Settings,
nodeDesc *roachpb.NodeDescriptor,
tracer opentracing.Tracer,
clock *hlc.Clock,
latency time.Duration,
stores client.Sender,
stopper *stop.Stopper,
gossip *gossip.Gossip,
) client.TxnSenderFactory {
return NewTxnCoordSenderFactory(
TxnCoordSenderFactoryConfig{
AmbientCtx: log.AmbientContext{Tracer: st.Tracer},
Settings: st,
Clock: clock,
Stopper: stopper,
},
NewDistSenderForLocalTestCluster(st, nodeDesc, tracer, clock, latency, stores, stopper, gossip),
)
}
// NewDistSenderForLocalTestCluster creates a DistSender for a LocalTestCluster.
func NewDistSenderForLocalTestCluster(
st *cluster.Settings,
nodeDesc *roachpb.NodeDescriptor,
tracer opentracing.Tracer,
clock *hlc.Clock,
latency time.Duration,
stores client.Sender,
stopper *stop.Stopper,
g *gossip.Gossip,
) *DistSender {
retryOpts := base.DefaultRetryOptions()
retryOpts.Closer = stopper.ShouldQuiesce()
rpcContext := rpc.NewInsecureTestingContext(clock, stopper)
senderTransportFactory := SenderTransportFactory(tracer, stores)
return NewDistSender(DistSenderConfig{
AmbientCtx: log.AmbientContext{Tracer: st.Tracer},
Settings: st,
Clock: clock,
RPCContext: rpcContext,
RPCRetryOptions: &retryOpts,
nodeDescriptor: nodeDesc,
NodeDialer: nodedialer.New(rpcContext, gossip.AddressResolver(g)),
TestingKnobs: ClientTestingKnobs{
TransportFactory: func(
opts SendOptions,
nodeDialer *nodedialer.Dialer,
replicas ReplicaSlice,
) (Transport, error) {
transport, err := senderTransportFactory(opts, nodeDialer, replicas)
if err != nil {
return nil, err
}
return &localTestClusterTransport{transport, latency}, nil
},
},
}, g)
}
| {
time.Sleep(l.latency)
} |
RestoreIPAddresses.py | __source__ = 'https://leetcode.com/problems/restore-ip-addresses/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/restore-ip-addresses.py
# Time: O(n^m) = O(3^4)
# Space: O(n * m) = O(3 * 4)
# DFS
#
# Description: Leetcode # 93. Restore IP Addresses
#
# Given a string containing only digits, restore it by returning all possible valid IP address combinations.
#
# For example:
# Given "25525511135",
#
# return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
#
# Related Topics
# Backtracking String
#
import unittest
class Solution(unittest.TestCase):
# @param s, a string
# @return a list of strings
def restoreIpAddresses(self, s):
result = []
self.restoreIpAddressesRecur(result, s, 0, "", 0)
return result
def | (self, result, s, start, current, dots):
# pruning to improve performance
if (4 - dots) * 3 < len(s) - start or (4 - dots) > len(s) - start: # break if 1) the # of rest numbers > 3 * dots
return # 2) more dots than # rest numbers ( =>1 dots have no number is not valid )
if start == len(s) and dots == 4:
result.append(current[: -1]) # clone current[:lastword - 1] b.c last char will always be '.'
else:
for i in xrange(start, start + 3):
if len(s) > i and self.isValid(s[start: i + 1]):
current += s[start : i + 1] + '.'
self.restoreIpAddressesRecur(result, s , i + 1, current, dots + 1)
current = current[:-(i - start + 2)]
def isValid(self, s):
if len(s) == 0 or (s[0] == "0" and s != "0"):
return False
return int(s) < 256
def test(self):
self.assertEqual(['0.0.0.0'], self.restoreIpAddresses("0000"))
class Solution2(object):
def restoreIpAddresses(self, s):
"""
:type s: str
:rtype: List[str]
"""
if len(s) < 4:
return []
res = []
self.dfs(s, res, 0, [], 0)
return res
def dfs(self, s, res, idx, cur, dot):
if(4 - dot) * 3 < len(s) - idx or (4 - dot) > len(s) - idx:
return
if idx == len(s) and dot == 4:
res.append(''.join(cur)[:-1])
return
for i in xrange(idx, idx + 3):
if len(s) > i and self.isValid(s[idx:i + 1]):
cur.append(s[idx:i + 1] + '.')
self.dfs(s, res, i + 1, cur, dot + 1)
cur.pop()
def isValid(self, s):
if len(s) == 0 or (s[0] == "0" and s != "0"):
return False
return int(s) < 256
class SolutionOther:
# @param s, a string
# @return a list of strings
def restoreIpAddresses(self, s):
def dfs(s, sub, ips,ip):
if sub == 4:
if s == '':
#print "s =", s, "ip = ", ip[1:]
ips.append(ip[1:])
return
for i in range(1,4):
if i <= len(s):
if int(s[:i]) <= 255:
#print ip
dfs(s[i:], sub+1, ips, ip+'.'+s[:i])
if s[0] == '0':
break
self.ips = []
self.ip = ''
ips = []
dfs(s, 0, ips, '')
self.dfs_notworking(s, 0, self.ips, self.ip)
print self.ips
return ips
def dfs_notworking(self, s, sub, ips, ip):
if sub == 4:
print s, ip
if s == '':
print self.ip
self.ips.append(self.ip[1:])
return
for i in range(1, 4):
if i <= len(s):
if int(s[:i]) <= 255:
self.dfs_notworking(s[i:], sub+1, self.ips, self.ip+'.'+s[:i])
if s[0] == '0':
break
#test
class TestMethods(unittest.TestCase):
def test_Local(self):
self.assertEqual(1, 1)
test = SolutionOther()
#print test.restoreIpAddresses("25525511135")
#print Solution().restoreIpAddresses("0000")
print Solution().restoreIpAddresses("25525511135")
if __name__ == '__main__':
unittest.main()
Java = '''
# Thought:
3-loop divides the string s into 4 substring: s1, s2, s3, s4. Check if each substring is valid.
In isValid, strings whose length greater than 3 or equals to 0 is not valid;
or if the string's length is longer than 1 and the first letter is '0' then it's invalid;
or the string whose integer representation greater than 255 is invalid.
# 4ms 33.49%
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> solutions = new ArrayList<String>();
restoreIp(s, solutions, 0, "", 0);
return solutions;
}
private void restoreIp(String ip, List<String> solutions, int idx, String restored, int count) {
if (count > 4) return;
if (count == 4 && idx == ip.length()) solutions.add(restored);
for (int i=1; i<4; i++) {
if (idx+i > ip.length()) break;
String s = ip.substring(idx,idx+i);
if ((s.startsWith("0") && s.length()>1) || (i==3 && Integer.parseInt(s) >= 256)) continue;
restoreIp(ip, solutions, idx+i, restored+s+(count==3?"" : "."), count+1);
}
}
}
# 1ms 99.64%
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> result = new ArrayList<>();
if (s.length() < 4 || s.length() > 12) {
return result;
}
restoreIp(s.toCharArray(), 1, result, new ArrayList<>(), s.charAt(0) - '0');
return result;
}
private void restoreIp(char[] s, int index, List<String> result, List<Integer> cur, int num) {
if (index == s.length) {
if (cur.size() == 3) {
cur.add(num);
result.add(convertIp(cur));
cur.remove(cur.size() - 1);
}
return;
}
int curNum = s[index] - '0';
int next = num * 10 + curNum;
if (num != 0 && next < 256) {
restoreIp(s, index + 1, result, cur, next);
}
if (s.length - index <= (4 - cur.size() - 1) * 3) {
cur.add(num);
restoreIp(s, index + 1, result, cur, curNum);
cur.remove(cur.size() - 1);
}
}
private String convertIp(List<Integer> nums) {
StringBuilder sb = new StringBuilder();
sb.append(nums.get(0));
for (int i = 1; i < 4; i++) {
sb.append('.').append(nums.get(i));
}
return sb.toString();
}
}
# 1ms 99.64%
class Solution {
public List<String> restoreIpAddresses(String s) {
List<String> result = new ArrayList<String>();
List<String> temp = new ArrayList<String>();
dfs(s,temp,result,0);
return result;
}
public void dfs(String s, List<String> tmp, List<String> res, int start){
if (tmp.size() == 4 && start == s.length()) {
res.add(tmp.get(0) + '.' + tmp.get(1) + '.' + tmp.get(2) + '.' + tmp.get(3));
return;
}
int num = 0;
if (s.length() - start > (4 - tmp.size()) * 3 ) return;
if (s.length() - start < (4 - tmp.size())) return;
for (int i = start; i < 3 + start && i < s.length(); i++) {
num = num * 10 + (s.charAt(i) - '0');
if (num > 255 || num < 0) break;
tmp.add(s.substring(start, i + 1));
dfs(s, tmp, res, i + 1);
tmp.remove(tmp.size() - 1);
if (num == 0) break;
}
}
}
'''
| restoreIpAddressesRecur |
index.ts | export { Block } from './Block'; | export type { Props as BlockProps } from './Block'; |
|
toggle-method.rs | #![crate_name = "foo"]
// Struct methods with documentation should be wrapped in a <details> toggle with an appropriate
// summary. Struct methods with no documentation should not be wrapped.
//
// @has foo/struct.Foo.html
// @has - '//details[@class="rustdoc-toggle method-toggle"]//summary//code' 'is_documented()'
// @has - '//details[@class="rustdoc-toggle method-toggle"]//*[@class="docblock"]' 'is_documented is documented'
// @!has - '//details[@class="rustdoc-toggle method-toggle"]//summary//code' 'not_documented()'
pub struct | {
}
impl Foo {
pub fn not_documented() {}
/// is_documented is documented
pub fn is_documented() {}
}
| Foo |
test_case.go | package helpers
import (
"encoding/json"
"net/http/httptest"
"strings"
"github.com/khihadysucahyo/go-echo-boilerplate/server"
"github.com/labstack/echo/v4"
mocket "github.com/selvatico/go-mocket"
)
const UserId = 1
type TestCase struct {
TestName string
Request Request
RequestBody interface{}
HandlerFunc func(s *server.Server, c echo.Context) error
QueryMock *QueryMock
Expected ExpectedResponse
}
type PathParam struct {
Name string
Value string
}
type Request struct {
Method string
Url string
PathParam *PathParam
}
type MockReply []map[string]interface{}
type QueryMock struct {
Query string
Reply MockReply
}
type ExpectedResponse struct {
StatusCode int
BodyPart string
}
func PrepareContextFromTestCase(s *server.Server, test TestCase) (c echo.Context, recorder *httptest.ResponseRecorder) {
requestJson, _ := json.Marshal(test.RequestBody)
request := httptest.NewRequest(test.Request.Method, test.Request.Url, strings.NewReader(string(requestJson)))
request.Header.Set(echo.HeaderContentType, echo.MIMEApplicationJSON)
recorder = httptest.NewRecorder()
c = s.Echo.NewContext(request, recorder)
if test.Request.PathParam != nil {
c.SetParamNames(test.Request.PathParam.Name)
c.SetParamValues(test.Request.PathParam.Value)
}
if test.QueryMock != nil {
mocket.Catcher.Reset().NewMock().WithQuery(test.QueryMock.Query).WithReply(test.QueryMock.Reply)
} |
return
} | |
test_v1_flex_volume_source.py | # coding: utf-8
| """
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.11.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
import unittest
import kubernetes.client
from kubernetes.client.rest import ApiException
from kubernetes.client.models.v1_flex_volume_source import V1FlexVolumeSource
class TestV1FlexVolumeSource(unittest.TestCase):
""" V1FlexVolumeSource unit test stubs """
def setUp(self):
pass
def tearDown(self):
pass
def testV1FlexVolumeSource(self):
"""
Test V1FlexVolumeSource
"""
# FIXME: construct object with mandatory attributes with example values
#model = kubernetes.client.models.v1_flex_volume_source.V1FlexVolumeSource()
pass
if __name__ == '__main__':
unittest.main() | |
proposal.go | package types
import (
"errors"
"fmt"
"time"
tmbytes "github.com/tendermint/tendermint/libs/bytes"
"github.com/tendermint/tendermint/libs/protoio"
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
tmtime "github.com/tendermint/tendermint/types/time"
)
var (
ErrInvalidBlockPartSignature = errors.New("error invalid block part signature")
ErrInvalidBlockPartHash = errors.New("error invalid block part hash")
)
// Proposal defines a block proposal for the consensus.
// It refers to the block by BlockID field.
// It must be signed by the correct proposer for the given Height/Round
// to be considered valid. It may depend on votes from a previous round,
// a so-called Proof-of-Lock (POL) round, as noted in the POLRound.
// If POLRound >= 0, then BlockID corresponds to the block that is locked in POLRound.
type Proposal struct {
Type tmproto.SignedMsgType
Height int64 `json:"height"`
Round int32 `json:"round"` // there can not be greater than 2_147_483_647 rounds
POLRound int32 `json:"pol_round"` // -1 if null.
BlockID BlockID `json:"block_id"`
Timestamp time.Time `json:"timestamp"`
Signature []byte `json:"signature"`
}
// NewProposal returns a new Proposal.
// If there is no POLRound, polRound should be -1.
func NewProposal(height int64, round int32, polRound int32, blockID BlockID) *Proposal {
return &Proposal{
Type: tmproto.ProposalType,
Height: height,
Round: round,
BlockID: blockID,
POLRound: polRound,
Timestamp: tmtime.Now(),
}
}
// ValidateBasic performs basic validation.
func (p *Proposal) ValidateBasic() error {
if p.Type != tmproto.ProposalType {
return errors.New("invalid Type")
}
if p.Height < 0 {
return errors.New("negative Height")
}
if p.Round < 0 {
return errors.New("negative Round")
}
if p.POLRound < -1 |
if err := p.BlockID.ValidateBasic(); err != nil {
return fmt.Errorf("wrong BlockID: %v", err)
}
// ValidateBasic above would pass even if the BlockID was empty:
if !p.BlockID.IsComplete() {
return fmt.Errorf("expected a complete, non-empty BlockID, got: %v", p.BlockID)
}
// NOTE: Timestamp validation is subtle and handled elsewhere.
if len(p.Signature) == 0 {
return errors.New("signature is missing")
}
if len(p.Signature) > MaxSignatureSize {
return fmt.Errorf("signature is too big (max: %d)", MaxSignatureSize)
}
return nil
}
// String returns a string representation of the Proposal.
//
// 1. height
// 2. round
// 3. block ID
// 4. POL round
// 5. first 6 bytes of signature
// 6. timestamp
//
// See BlockID#String.
func (p *Proposal) String() string {
return fmt.Sprintf("Proposal{%v/%v (%v, %v) %X @ %s}",
p.Height,
p.Round,
p.BlockID,
p.POLRound,
tmbytes.Fingerprint(p.Signature),
CanonicalTime(p.Timestamp))
}
// ProposalSignBytes returns the proto-encoding of the canonicalized Proposal,
// for signing.
//
// Panics if the marshaling fails.
//
// See CanonicalizeProposal
func ProposalSignBytes(chainID string, p *tmproto.Proposal) []byte {
pb := CanonicalizeProposal(chainID, p)
bz, err := protoio.MarshalDelimited(&pb)
if err != nil {
panic(err)
}
return bz
}
// ToProto converts Proposal to protobuf
func (p *Proposal) ToProto() *tmproto.Proposal {
if p == nil {
return &tmproto.Proposal{}
}
pb := new(tmproto.Proposal)
pb.BlockID = p.BlockID.ToProto()
pb.Type = p.Type
pb.Height = p.Height
pb.Round = p.Round
pb.PolRound = p.POLRound
pb.Timestamp = p.Timestamp
pb.Signature = p.Signature
return pb
}
// FromProto sets a protobuf Proposal to the given pointer.
// It returns an error if the proposal is invalid.
func ProposalFromProto(pp *tmproto.Proposal) (*Proposal, error) {
if pp == nil {
return nil, errors.New("nil proposal")
}
p := new(Proposal)
blockID, err := BlockIDFromProto(&pp.BlockID)
if err != nil {
return nil, err
}
p.BlockID = *blockID
p.Type = pp.Type
p.Height = pp.Height
p.Round = pp.Round
p.POLRound = pp.PolRound
p.Timestamp = pp.Timestamp
p.Signature = pp.Signature
return p, p.ValidateBasic()
}
| {
return errors.New("negative POLRound (exception: -1)")
} |
Models_predict_manager.py | import os
import pandas as pd
import numpy as np
import pickle
import logging, shutil, glob
import pymongo, joblib
from Fuzzy_clustering.ver_tf2.Clusterer import clusterer
from Fuzzy_clustering.ver_tf2.Cluster_predict_regressors import cluster_predict
from Fuzzy_clustering.ver_tf2.Global_predict_regressor import global_predict
from Fuzzy_clustering.ver_tf2.Combine_predict_model import Combine_overall_predict
from Fuzzy_clustering.ver_tf2.util_database import write_database
class ModelPredictManager_ver2(object):
def __init__(self, path_model):
self.istrained = False
self.path_model = path_model
try:
self.load()
except:
pass
def init(self, static_data, data_variables, use_db=False):
self.data_variables = data_variables
self.static_data = static_data
self.thres_split = static_data['clustering']['thres_split']
self.thres_act = static_data['clustering']['thres_act']
self.n_clusters = static_data['clustering']['n_clusters']
self.rated = static_data['rated']
self.var_imp = static_data['clustering']['var_imp']
self.var_lin = static_data['clustering']['var_lin']
self.var_nonreg = static_data['clustering']['var_nonreg']
self.create_logger()
self.use_db = use_db
if use_db:
self.db = self.open_db()
def open_db(self):
try:
myclient = pymongo.MongoClient(
"mongodb://" + self.static_data['url'] + ":" + self.static_data['port'] + "/")
project_db = myclient[self.static_data['_id']]
except:
self.logger.info('Cannot open Database')
self.use_db = False
project_db = None
raise ConnectionError('Cannot open Database')
self.logger.info('Open Database successfully')
return project_db
def load_data(self):
data_path = self.static_data['path_data']
X = pd.read_csv(os.path.join(data_path, 'dataset_X_test.csv'), index_col=0, header=0, parse_dates=True, dayfirst=True)
if os.path.exists(os.path.join(data_path, 'dataset_y_test.csv')):
y = pd.read_csv(os.path.join(data_path, 'dataset_y_test.csv'), index_col=0, header=0, parse_dates=True, dayfirst=True)
else:
y=None
if os.path.exists(os.path.join(data_path, 'dataset_cnn_test.pickle')):
X_cnn = joblib.load(os.path.join(data_path, 'dataset_cnn_test.pickle'))
X_cnn = X_cnn.transpose([0, 2, 3, 1])
else:
X_cnn = np.array([])
if os.path.exists(os.path.join(data_path, 'dataset_lstm_test.pickle')):
X_lstm = joblib.load(os.path.join(data_path, 'dataset_lstm_test.pickle'))
else:
X_lstm = np.array([])
self.logger.info('Data loaded successfully')
return X, X_cnn, X_lstm, y
def create_logger(self):
self.logger = logging.getLogger(__name__)
self.logger.setLevel(logging.INFO)
handler = logging.FileHandler(os.path.join(self.static_data['path_project'], 'log_model_evaluation.log'), 'a')
handler.setLevel(logging.INFO)
# create a logging format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
# add the handlers to the logger
self.logger.addHandler(handler)
def | (self, X_test, X_cnn_test, X_lstm_test, y_test=None):
data_path = self.static_data['path_data']
pred_cluster = dict()
X_test = pd.DataFrame(self.sc.transform(X_test.values), columns=X_test.columns, index=X_test.index)
if not hasattr(self, 'clusterer'):
self.clusterer = clusterer(self.static_data['path_fuzzy_models'],
self.static_data['clustering']['cluster_file'], self.static_data['type'])
act_test = self.clusterer.compute_activations(X_test)
act_test = self.check_if_all_nans(act_test)
for clust in self.regressors.keys():
if clust == 'Global':
if len(self.regressors['Global']['models']) > 0:
predict_module = global_predict(self.static_data)
pred_cluster['Global'] = predict_module.predict(X_test.values, X_cnn=X_cnn_test, X_lstm=X_lstm_test)
if y_test is not None:
pred_cluster['Global']['metrics'] = predict_module.evaluate(pred_cluster['Global'], self.scale_y.transform(y_test.values))
pred_cluster['Global']['dates'] = X_test.index
pred_cluster['Global']['index'] = np.arange(0, X_test.shape[0])
else:
dates = X_test.index[act_test[clust] >= self.thres_act]
nind = np.where(act_test[clust] >= self.thres_act)[0]
nind.sort()
x = X_test.loc[dates]
if y_test is not None:
targ = y_test.loc[dates].values
else:
targ = None
if len(X_cnn_test.shape) > 1:
x_cnn = X_cnn_test[nind]
else:
x_cnn = np.array([])
if len(X_lstm_test.shape) > 1:
x_lstm = X_lstm_test[nind]
else:
x_lstm = np.array([])
predict_module = cluster_predict(self.static_data, clust)
pred_cluster[clust] = predict_module.predict(x.values, X_cnn=x_cnn, X_lstm=x_lstm)
if targ is not None and targ.shape[0]>0:
pred_cluster[clust]['metrics'] = predict_module.evaluate(pred_cluster[clust], self.scale_y.transform(targ))
pred_cluster[clust]['dates'] = dates
pred_cluster[clust]['index'] = nind
predictions = dict()
result_clust = pd.DataFrame()
for clust in pred_cluster.keys():
for method in pred_cluster[clust].keys():
if not method in {'dates', 'index', 'metrics'}:
if not method in predictions.keys():
predictions[method] = pd.DataFrame(index=X_test.index, columns=[cl for cl in pred_cluster.keys()])
predictions[method].loc[pred_cluster[clust]['dates'], clust] = pred_cluster[clust][method].ravel()
elif method in {'metrics'}:
result_clust = pd.concat([result_clust, pred_cluster[clust][method]['mae'].rename(clust)], axis=1)
combine_overall = Combine_overall_predict(self.static_data)
predictions_final = combine_overall.predict(pred_cluster, predictions)
for method, pred in predictions_final.items():
pred = self.scale_y.inverse_transform(pred.reshape(-1, 1))
pred[np.where(pred<0)] = 0
predictions_final[method] = pred
if y_test is not None:
result_clust.to_csv(os.path.join(data_path, 'result_of_clusters.csv'))
return predictions_final
def compute_metrics(self, pred, y):
if self.rated is None:
rated = y.ravel()
else:
rated = self.rated
err = np.abs(pred.ravel() - y.ravel()) / rated
sse = np.sum(np.square(pred.ravel() - y.ravel()))
rms = np.sqrt(np.mean(np.square(err)))
mae = np.mean(err)
mse = sse / y.shape[0]
return [sse, rms, mae, mse]
def evaluate(self, pred_all, y):
result = pd.DataFrame(index=[method for method in pred_all.keys()], columns=['sse', 'rms', 'mae', 'mse'])
for method, pred in pred_all.items():
if isinstance(pred, pd.DataFrame):
result.loc[method] = self.compute_metrics(pred.values, y)
else:
result.loc[method] = self.compute_metrics(pred, y)
return result
def predict(self):
if self.istrained:
X, X_cnn, X_lstm, y = self.load_data()
indices = X.index
if self.static_data['type'] == 'pv' and self.static_data['NWP_model'] == 'skiron':
index = np.where(X['flux'] > 1e-8)[0]
X = X.iloc[index]
X_cnn = X_cnn[index]
else:
index = indices
predictions_final_temp = self.predict_regressors(X, X_cnn, X_lstm)
predictions_final = dict()
for method, pred in predictions_final_temp.items():
pred_temp = pd.DataFrame(0, index=indices, columns=[method])
pred_temp.loc[index, method] = pred
predictions_final[method] = pred_temp
return predictions_final
else:
raise ModuleNotFoundError('Model %s is not trained', self.static_data['_id'])
def predict_online(self, X, X_cnn= np.array([]), X_lstm= np.array([])):
if len(X_cnn.shape)>1:
X_cnn = X_cnn.transpose([0, 2, 3, 1])
if self.istrained:
indices = X.index
if self.static_data['type'] == 'pv' and self.static_data['NWP_model'] == 'skiron':
index = X.index[np.where(X['flux'] > 1e-8)[0]]
X = X.loc[index]
X_cnn = X_cnn[np.where(X['flux'] > 1e-8)[0]]
else:
index = indices
predictions_final_temp = self.predict_regressors(X, X_cnn, X_lstm)
predictions_final = dict()
for method, pred in predictions_final_temp.items():
pred_temp = pd.DataFrame(0, index=indices, columns=[method])
pred_temp.loc[index, method] = pred
predictions_final[method] = pred_temp
return predictions_final
else:
raise ModuleNotFoundError('Model %s is not trained', self.static_data['_id'])
def evaluate_all(self):
data_path = self.static_data['path_data']
if self.istrained:
X, X_cnn, X_lstm, y = self.load_data()
y_test = y.copy()
indices = X.index
if self.static_data['type'] == 'pv' and self.static_data['NWP_model'] == 'skiron':
index = np.where(X['flux'] > 1e-8)[0]
X = X.iloc[index]
y = y.iloc[index]
X_cnn = X_cnn[index]
index = indices[index]
else:
index = indices
predictions_final_temp = self.predict_regressors(X, X_cnn, X_lstm, y)
predictions_final = dict()
for method, pred in predictions_final_temp.items():
pred_temp = pd.DataFrame(0, index=indices, columns=[method])
pred_temp.loc[index, method] = pred
predictions_final[method] = pred_temp
if y_test is not None:
result_all = self.evaluate(predictions_final, y_test.values)
result_all.to_csv(os.path.join(data_path, 'result_final.csv'))
joblib.dump(predictions_final, os.path.join(data_path, 'predictions_final.pickle'))
y_test.to_csv(os.path.join(data_path, 'target_test.csv'))
else:
raise ModuleNotFoundError('Model %s is not trained', self.static_data['_id'])
def check_if_all_nans(self, activations):
if activations.isna().all(axis=1).any() == True:
indices = activations.index[activations.isna().all(axis=1).to_numpy().ravel()]
if indices.shape[0]>50:
raise RuntimeError('Too many nans. Please check your model')
for ind in indices:
act = activations.loc[ind]
clust = act.idxmax()
activations.loc[ind, clust] = 0.1
return activations
def load(self):
if os.path.exists(os.path.join(self.path_model, 'manager' + '.pickle')):
try:
f = open(os.path.join(self.path_model, 'manager' + '.pickle'), 'rb')
tmp_dict = pickle.load(f)
f.close()
if 'path_model' in tmp_dict.keys():
del tmp_dict['path_model']
self.__dict__.update(tmp_dict)
except:
raise ValueError('Cannot find model for %s', self.path_model)
else:
raise ValueError('Cannot find model for %s', self.path_model)
if __name__ == '__main__':
from util_database import write_database
from Fuzzy_clustering.ver_tf2.Projects_train_manager import ProjectsTrainManager
static_data = write_database()
project_manager = ProjectsTrainManager(static_data)
project_manager.initialize()
project_manager.create_datasets(project_manager.data_eval, test=True)
project = [pr for pr in project_manager.group_static_data if pr['_id'] == 'Lach'][0]
static_data = project['static_data']
model = ModelPredictManager(static_data['path_model'])
model.init(project['static_data'], project_manager.data_variables)
model.evaluate_all() | predict_regressors |
main.rs | // ref 引用:&
fn cal_length(s: &String) -> usize {
s.len()
}
// borrow 借用:&mut
fn modify_s(s: &mut String) {
s.push | {
let mut s = String::from("hello");
println!("s: {}", s);
let len = cal_length(&s);
println!("s len: {}", len);
modify_s(&mut s);
println!("new s: {}", s);
println!("Hello, world!");
}
| _str(", world");
}
fn main() |
rpc.go | package rpc
import (
"context"
"errors"
"fmt"
"net/http"
"github.com/linuskendall/jsonrpc/v2"
)
var epoch_schedule EpochSchedule = EpochSchedule{FirstNormalEpoch: 0, FirstNormalSlot: 0, LeaderScheduleSlotOffset: 432000, SlotsPerEpoch: 432000, warmup: false}
const MINIMUM_SLOTS_PER_EPOCH uint64 = 32
type Slot uint64
type Epoch uint64
type Block uint64
type Identity struct {
Identity string `json:identity`
}
type Version struct {
FeatureSet uint64 `json:"feature-set"`
CoreVersion string `json:"solana-core"`
}
type EpochInfo struct {
AbsoluteSlot Slot `json:absoluteSlot`
BlockHeight uint64 `json:blockHeight`
Epoch Epoch `json:epoch`
SlotIndex uint64 `json:slotIndex`
SlotsInEpoch uint64 `json:slotsInEpoch`
TransactionCount uint64 `json:transactionCount`
}
type Client struct {
url string
client jsonrpc.RPCClient
headers http.Header
}
type RpcError struct {
Url string
Method string
Err error
}
type CommitmentType string
const (
CommitmentMax = CommitmentType("max")
CommitmentRecent = CommitmentType("recent")
CommitmentConfirmed = CommitmentType("confirmed")
CommitmentFinalized = CommitmentType("finalized")
CommitmentRoot = CommitmentType("root")
CommitmentSingle = CommitmentType("single")
CommitmentSingleGossip = CommitmentType("singleGossip")
CommitmentProcessed = CommitmentType("processed")
)
func (r *RpcError) Error() string {
var eType string
switch r.Err.(type) {
case nil:
eType = "nil error"
case *jsonrpc.HTTPError:
eType = "http error"
default:
eType = "rpc error"
}
return fmt.Sprintf("[%s].[%s] %s, %v", r.Url, r.Method, eType, r.Err)
}
func NewError(url string, method string, e error) *RpcError {
return &RpcError{
Url: url,
Err: e,
Method: method,
}
}
func NewClient(url string) *Client {
rpcClient := jsonrpc.NewClient(url)
return &Client{
url: url,
client: rpcClient,
}
}
func (c *Client) SetHeader(k, v string) {
if c.headers == nil {
c.headers = http.Header{}
}
c.headers.Set(k, v)
}
func (c *Client) MinimumLedgerSlot(ctx context.Context) (out Slot, err error) {
err = c.client.CallFor(ctx, &out, "minimumLedgerSlot")
if err != nil {
err = NewError(c.url, "minimumLedgerSlot", err)
}
return
}
func (c *Client) GetSlot(ctx context.Context, commitment CommitmentType) (out Slot, err error) {
var params []interface{}
if commitment != "" |
err = c.client.CallFor(ctx, &out, "getSlot")
if err != nil {
err = NewError(c.url, "getSlot", err)
}
return
}
func (c *Client) GetEpochInfo(ctx context.Context, commitment CommitmentType) (out EpochInfo, err error) {
var params []interface{}
if commitment != "" {
params = append(params, string(commitment))
}
err = c.client.CallFor(ctx, &out, "getEpochInfo")
if err != nil {
err = NewError(c.url, "getEpochInfo", err)
}
return
}
func (c *Client) GetEpochSchedule(ctx context.Context) (out EpochSchedule, err error) {
if epoch_schedule.SlotsPerEpoch > 0 {
out = epoch_schedule
} else {
err = c.client.CallFor(ctx, &out, "getEpochSchedule")
if err != nil {
err = NewError(c.url, "getEpochSchedule", err)
}
}
return
}
func (c *Client) GetConfirmedBlocks(ctx context.Context, start_slot Slot, end_slot Slot) (blocks []uint64, err error) {
blocks = []uint64{}
if start_slot > end_slot {
err = NewError(c.url, "getConfirmedBlocks", errors.New("start_slot is greater than end slot"))
return
}
response, _ := c.client.Call(ctx, "getConfirmedBlocks", uint64(start_slot), uint64(end_slot))
if response == nil || response.Result == nil {
err = NewError(c.url, "getConfirmedBlocks", errors.New("nil result received"))
return
}
err = response.GetObject(&blocks)
if err != nil {
err = NewError(c.url, "getConfirmedBlocks", err)
}
return
}
func (c *Client) GetMaxRetransmitSlot(ctx context.Context) (out Slot, err error) {
err = c.client.CallFor(ctx, &out, "getMaxRetransmitSlot")
if err != nil {
err = NewError(c.url, "getMaxRetransmitSlot", err)
}
return
}
func (c *Client) GetVersion(ctx context.Context) (out Version, err error) {
err = c.client.CallFor(ctx, &out, "getVersion")
if err != nil {
err = NewError(c.url, "getVersion", err)
}
return
}
func (c *Client) GetIdentity(ctx context.Context) (out Identity, err error) {
err = c.client.CallFor(ctx, &out, "getIdentity")
if err != nil {
err = NewError(c.url, "getIdentity", err)
}
return
}
func (c *Client) GetGenesisHash(ctx context.Context) (out string, err error) {
err = c.client.CallFor(ctx, &out, "getGenesisHash")
if err != nil {
err = NewError(c.url, "getGenesisHash", err)
}
return
}
| {
params = append(params, string(commitment))
} |
preco_estados.js | function getTablePrecoEstados() {
return "tb_preco_estado";
}
function dbLoad() {
var db = Ti.Database.open(Ti.App.Properties.getString(DATABASE_FILE));
return db;
}
function createPrecoEstados() {
db = dbLoad();
db.execute("CREATE TABLE IF NOT EXISTS " + getTablePrecoEstados() + "(\n id INTEGER PRIMARY KEY, pe_id INTEGER, fk_estado INTEGER, pe_preco_1 FLOAT,\n pe_preco_2 FLOAT, pe_preco_3 FLOAT, pe_icms FLOAT, pe_base INTEGER, fk_marca INTEGER, ep_id INTEGER\n );");
db.close();
}
function dropPrecoEstados() {
db = dbLoad();
db.execute("DROP TABLE IF EXISTS " + getTablePrecoEstados());
db.close();
}
function insertPrecoEstados(pe_id, fk_estado, pe_preco_1, pe_preco_2, pe_preco_3, pe_icms, pe_base, fk_marca, ep_id) {
db = dbLoad();
db.execute("INSERT INTO " + getTablePrecoEstados() + " (\n pe_id, fk_estado, pe_preco_1, pe_preco_2, pe_preco_3, pe_icms, pe_base, fk_marca, ep_id) \n VALUES (?,?,?,?,?,?,?,?,?)", pe_id, fk_estado, pe_preco_1, pe_preco_2, pe_preco_3, pe_icms, pe_base, fk_marca, ep_id);
db.close();
}
function | () {
db = dbLoad();
var precoestados = db.execute("SELECT * FROM " + getTablePrecoEstados());
db.close();
return precoestados;
}
function processPrecoEstados(jsonTxt) {
dropPrecoEstados();
createPrecoEstados();
var jsonObject = JSON.parse(jsonTxt);
for (var j = 0; j < jsonObject.length; j++) {
var pe_id = jsonObject[j].pe_id;
var fk_estado = jsonObject[j].fk_estado;
var pe_preco_1 = jsonObject[j].pe_preco_1;
var pe_preco_2 = jsonObject[j].pe_preco_2;
var pe_preco_3 = jsonObject[j].pe_preco_3;
var pe_icms = jsonObject[j].pe_icms;
var pe_base = jsonObject[j].pe_base;
var fk_marca = jsonObject[j].fk_marca;
var ep_id = jsonObject[j].ep_id;
insertPrecoEstados(pe_id, fk_estado, pe_preco_1, pe_preco_2, pe_preco_3, pe_icms, pe_base, fk_marca, ep_id);
}
} | selectallPrecoEstados |
simi_song.js | // 相似歌曲
module.exports = (query, request) => {
const data = {
songid: query.id,
limit: query.limit || 50,
offset: query.offset || 0
}
return request(
'POST', `https://music.163.com/weapi/v1/discovery/simiSong`, data,
{crypto: 'weapi', cookie: query.cookie, proxy: query.proxy}
) | } |
|
test_game.py | import unittest
from reconchess import LocalGame, WinReason
from chess import *
import time
import random
SENSE_BY_SQUARE = {
A8: [A8, B8, A7, B7],
B8: [A8, B8, C8, A7, B7, C7],
C8: [B8, C8, D8, B7, C7, D7],
D8: [C8, D8, E8, C7, D7, E7],
E8: [D8, E8, F8, D7, E7, F7],
F8: [E8, F8, G8, E7, F7, G7],
G8: [F8, G8, H8, F7, G7, H7],
H8: [G8, H8, G7, H7],
A7: [A8, B8, A7, B7, A6, B6],
B7: [A8, B8, C8, A7, B7, C7, A6, B6, C6],
C7: [B8, C8, D8, B7, C7, D7, B6, C6, D6],
D7: [C8, D8, E8, C7, D7, E7, C6, D6, E6],
E7: [D8, E8, F8, D7, E7, F7, D6, E6, F6],
F7: [E8, F8, G8, E7, F7, G7, E6, F6, G6],
G7: [F8, G8, H8, F7, G7, H7, F6, G6, H6],
H7: [G8, H8, G7, H7, G6, H6],
A6: [A7, B7, A6, B6, A5, B5],
B6: [A7, B7, C7, A6, B6, C6, A5, B5, C5],
C6: [B7, C7, D7, B6, C6, D6, B5, C5, D5],
D6: [C7, D7, E7, C6, D6, E6, C5, D5, E5],
E6: [D7, E7, F7, D6, E6, F6, D5, E5, F5],
F6: [E7, F7, G7, E6, F6, G6, E5, F5, G5],
G6: [F7, G7, H7, F6, G6, H6, F5, G5, H5],
H6: [G7, H7, G6, H6, G5, H5],
A5: [A6, B6, A5, B5, A4, B4],
B5: [A6, B6, C6, A5, B5, C5, A4, B4, C4],
C5: [B6, C6, D6, B5, C5, D5, B4, C4, D4],
D5: [C6, D6, E6, C5, D5, E5, C4, D4, E4],
E5: [D6, E6, F6, D5, E5, F5, D4, E4, F4],
F5: [E6, F6, G6, E5, F5, G5, E4, F4, G4],
G5: [F6, G6, H6, F5, G5, H5, F4, G4, H4],
H5: [G6, H6, G5, H5, G4, H4],
A4: [A5, B5, A4, B4, A3, B3],
B4: [A5, B5, C5, A4, B4, C4, A3, B3, C3],
C4: [B5, C5, D5, B4, C4, D4, B3, C3, D3],
D4: [C5, D5, E5, C4, D4, E4, C3, D3, E3],
E4: [D5, E5, F5, D4, E4, F4, D3, E3, F3],
F4: [E5, F5, G5, E4, F4, G4, E3, F3, G3],
G4: [F5, G5, H5, F4, G4, H4, F3, G3, H3],
H4: [G5, H5, G4, H4, G3, H3],
A3: [A4, B4, A3, B3, A2, B2],
B3: [A4, B4, C4, A3, B3, C3, A2, B2, C2],
C3: [B4, C4, D4, B3, C3, D3, B2, C2, D2],
D3: [C4, D4, E4, C3, D3, E3, C2, D2, E2],
E3: [D4, E4, F4, D3, E3, F3, D2, E2, F2],
F3: [E4, F4, G4, E3, F3, G3, E2, F2, G2],
G3: [F4, G4, H4, F3, G3, H3, F2, G2, H2],
H3: [G4, H4, G3, H3, G2, H2],
A2: [A3, B3, A2, B2, A1, B1],
B2: [A3, B3, C3, A2, B2, C2, A1, B1, C1],
C2: [B3, C3, D3, B2, C2, D2, B1, C1, D1],
D2: [C3, D3, E3, C2, D2, E2, C1, D1, E1],
E2: [D3, E3, F3, D2, E2, F2, D1, E1, F1],
F2: [E3, F3, G3, E2, F2, G2, E1, F1, G1],
G2: [F3, G3, H3, F2, G2, H2, F1, G1, H1],
H2: [G3, H3, G2, H2, G1, H1],
A1: [A2, B2, A1, B1],
B1: [A2, B2, C2, A1, B1, C1],
C1: [B2, C2, D2, B1, C1, D1],
D1: [C2, D2, E2, C1, D1, E1],
E1: [D2, E2, F2, D1, E1, F1],
F1: [E2, F2, G2, E1, F1, G1],
G1: [F2, G2, H2, F1, G1, H1],
H1: [G2, H2, G1, H1],
}
class LocalGameSenseTest(unittest.TestCase):
def setUp(self):
self.game = LocalGame()
def test_senses_actions_content(self):
sense_actions = self.game.sense_actions()
for square in SQUARES:
self.assertIn(square, sense_actions)
def test_sense_invalid(self):
for square in [-1, 65, 66, 1023730, -2]:
with self.assertRaises(ValueError):
self.game.sense(square)
def test_sense_squares(self):
for square in SQUARES:
sense_result = self.game.sense(square)
squares = [s for s, p in sense_result]
self.assertEqual(squares, SENSE_BY_SQUARE[square])
def test_sense_pieces(self):
for sense_square in SQUARES:
sense_result = self.game.sense(sense_square)
for square, piece in sense_result:
self.assertEqual(piece, self.game.board.piece_at(square))
class LocalGameTimeTest(unittest.TestCase):
def test_time(self, seconds=1, turns=20, phases=3):
delta = seconds / (turns * phases)
game = LocalGame(seconds_per_player=seconds)
turn = True
time_by_color = game.seconds_left_by_color.copy()
game.start()
for i in range(turns):
for _ in range(phases):
start = game.get_seconds_left()
time.sleep(delta)
end = game.get_seconds_left()
self.assertAlmostEqual(start - end, delta, places=2)
time_by_color[turn] = game.get_seconds_left()
turn = not turn
game.end_turn()
self.assertAlmostEqual(game.get_seconds_left(), time_by_color[turn], places=2)
game.end()
self.assertAlmostEqual(game.get_seconds_left(), time_by_color[turn], places=2)
time.sleep(delta)
self.assertAlmostEqual(game.get_seconds_left(), time_by_color[turn], places=2)
class LocalGameMoveActionsTest(unittest.TestCase):
STARTING_WHITE_PAWN_CAPTURES = [
Move(A2, B3),
Move(B2, A3), Move(B2, C3),
Move(C2, B3), Move(C2, D3),
Move(D2, C3), Move(D2, E3),
Move(E2, D3), Move(E2, F3),
Move(F2, E3), Move(F2, G3),
Move(G2, F3), Move(G2, H3),
Move(H2, G3),
]
BLACK_STARTING_PAWN_CAPTURES = [
Move(A7, B6),
Move(B7, A6), Move(B7, C6),
Move(C7, B6), Move(C7, D6),
Move(D7, C6), Move(D7, E6),
Move(E7, D6), Move(E7, F6),
Move(F7, E6), Move(F7, G6),
Move(G7, F6), Move(G7, H6),
Move(H7, G6),
]
def setUp(self):
self.game = LocalGame()
def test_starting_pawn_capture_moves(self):
move_actions = self.game.move_actions()
for move in self.STARTING_WHITE_PAWN_CAPTURES:
self.assertIn(move, move_actions)
self.game.board.turn = BLACK
move_actions = self.game.move_actions()
for move in self.BLACK_STARTING_PAWN_CAPTURES:
self.assertIn(move, move_actions)
def test_pass(self):
self.assertNotIn(None, self.game.move_actions())
self.assertNotIn(Move.null(), self.game.move_actions())
def test_superset_fuzz(self, max_turns=500):
turn = 1
while not self.game.board.is_game_over() and turn < max_turns:
truth_moves = set(self.game.board.generate_pseudo_legal_moves())
recon_moves = set(self.game.move_actions())
self.assertTrue(recon_moves.issuperset(truth_moves))
self.game.board.push(random.sample(truth_moves, 1)[0])
turn += 1
class LocalGameMoveTest(unittest.TestCase):
def setUp(self):
self.game = LocalGame()
def test_legal_kingside_castle(self):
"""
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
R . . . K . . R
"""
self.game.board.set_board_fen('8/8/8/8/8/8/8/R3K2R')
self.game.board.set_castling_fen('KQkq')
req, taken, opt_capture = self.game.move(Move(E1, G1))
self.assertEqual(req, taken)
self.assertIsNone(opt_capture)
self.assertEqual(self.game.board.board_fen(), '8/8/8/8/8/8/8/R4RK1')
def | (self):
"""
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
R . . . K . . R
"""
self.game.board.set_board_fen('8/8/8/8/8/8/8/R3K2R')
self.game.board.set_castling_fen('KQkq')
req, taken, opt_capture = self.game.move(Move(E1, C1))
self.assertEqual(req, taken)
self.assertIsNone(opt_capture)
self.assertEqual(self.game.board.board_fen(), '8/8/8/8/8/8/8/2KR3R')
def test_queenside_castle_piece_between(self):
"""
r . P . k b n r r . . P k b n r r P . . k b n r
p p . p p p p p p p . p p p p p p p . p p p p p
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
P P . P P P P P P P . P P P P P P P . P P P P P
R . p . K B N R R . . p K B N R R p . . K B N R
"""
for fen in ['r1P1kbnr/pp1ppppp/8/8/8/8/PP1PPPPP/R1p1KBNR',
'r2Pkbnr/pp1ppppp/8/8/8/8/PP1PPPPP/R2pKBNR',
'rP2kbnr/pp1ppppp/8/8/8/8/PP1PPPPP/Rp2KBNR']:
self.game.board.set_board_fen(fen)
self.game.board.turn = WHITE
self.game.turn = WHITE
req, tak, opt_capture = self.game.move(Move(E1, C1))
self.assertEqual(tak, None)
self.game.board.turn = BLACK
self.game.turn = BLACK
req, tak, opt_capture = self.game.move(Move(E8, C8))
self.assertEqual(tak, None)
def test_kingside_castle_piece_between(self):
"""
r n b q k P . r r n b q k . P r
p p p p p . p p p p p p p . p p
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
P P P P P . P P P P P P P . P P
R N B Q K p . R R N B Q K . p R
:return:
"""
for fen in ['rnbqkP1r/ppppp1pp/8/8/8/8/PPPPP1PP/RNBQKp1R',
'rnbqk1Pr/ppppp1pp/8/8/8/8/PPPPP1PP/RNBQK1pR']:
self.game.board.set_board_fen(fen)
self.game.board.turn = WHITE
self.game.turn = WHITE
req, tak, opt_capture = self.game.move(Move(E1, G1))
self.assertEqual(tak, None)
self.game.board.turn = BLACK
self.game.turn = BLACK
req, tak, opt_capture = self.game.move(Move(E8, G8))
self.assertEqual(tak, None)
def test_queenside_castle_no_rights(self):
"""
r . . . k . . r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
P P P P P P P P
R . . . K . . R
"""
self.game.board.set_board_fen('r3k2r/pppppppp/8/8/8/8/PPPPPPPP/R3K2R')
self.game.board.turn = WHITE
self.game.turn = WHITE
for castling_fen in ['-', 'k', 'q', 'kq', 'Kk', 'Kq', 'Kkq']:
self.game.board.set_castling_fen(castling_fen)
with self.assertRaises(ValueError):
self.game.move(Move(E1, C1))
self.game.board.turn = BLACK
self.game.turn = BLACK
for castling_fen in ['-', 'K', 'Q', 'KQ', 'Kk', 'Qk', 'KQk']:
self.game.board.set_castling_fen(castling_fen)
with self.assertRaises(ValueError):
self.game.move(Move(E8, C8))
def test_kingside_castle_no_rights(self):
"""
r . . . k . . r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
P P P P P P P P
R . . . K . . R
"""
self.game.board.set_board_fen('r3k2r/pppppppp/8/8/8/8/PPPPPPPP/R3K2R')
self.game.board.turn = WHITE
self.game.turn = WHITE
for castling_fen in ['-', 'k', 'q', 'kq', 'Qk', 'Qq', 'Qkq']:
self.game.board.set_castling_fen(castling_fen)
with self.assertRaises(ValueError):
self.game.move(Move(E1, G1))
self.game.board.turn = BLACK
self.game.turn = BLACK
for castling_fen in ['-', 'K', 'Q', 'KQ', 'Kq', 'Qq', 'KQq']:
self.game.board.set_castling_fen(castling_fen)
with self.assertRaises(ValueError):
self.game.move(Move(E8, G8))
def test_castling_into_check(self):
"""
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . q .
. . . . . . . .
. . . . . . . .
. . . . K . . R
"""
self.game.board.set_board_fen('8/8/8/8/6q1/8/8/4K2R')
self.assertFalse(self.game.board.is_check())
move = Move(E1, G1)
req, taken, opt_capture = self.game.move(move)
self.assertEqual(req, taken)
self.assertIsNone(opt_capture)
self.game.board.turn = WHITE
self.assertTrue(self.game.board.is_check())
def test_castling_out_of_check(self):
"""
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
q . . . K . . R
"""
self.game.board.set_board_fen('8/8/8/8/8/8/8/q3K2R')
self.assertTrue(self.game.board.is_check())
move = Move(E1, G1)
req, taken, opt_capture = self.game.move(move)
self.assertEqual(req, taken)
self.assertIsNone(opt_capture)
self.game.board.turn = WHITE
self.assertFalse(self.game.board.is_check())
def test_castling_stay_in_check(self):
"""
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . q .
. . . . . . . .
. . . . K . . R
"""
self.game.board.set_board_fen('8/8/8/8/8/6q1/8/4K2R')
self.assertTrue(self.game.board.is_check())
move = Move(E1, G1)
req, taken, opt_capture = self.game.move(move)
self.assertEqual(req, taken)
self.assertIsNone(opt_capture)
self.game.board.turn = WHITE
self.assertTrue(self.game.board.is_check())
def test_en_passant_white(self):
"""
r n b q k b n r
p . p p p p p p
. . . . . . . .
. . . . . . . .
P p . . . . . .
. . . . . . . .
. P P P P P P P
R N B Q K B N R
"""
# test that en passant captures result in the correct capture square
self.game.board.set_board_fen('rnbqkbnr/p1pppppp/8/8/1p6/8/PPPPPPPP/RNBQKBNR')
req, taken, opt_capture = self.game.move(Move(A2, A4))
self.assertEqual(req, taken)
self.assertIsNone(opt_capture)
req, taken, opt_capture = self.game.move(Move(B4, A3))
self.assertEqual(req, taken)
self.assertIsNotNone(opt_capture)
self.assertEqual(opt_capture, A4)
def test_en_passant_black(self):
"""
r n b q k b n r
p p p p p . p p
. . . . . . . .
. . . . . p P .
. . . . . . . .
. . . . . . . .
P P P P P P . P
R N B Q K B N R
"""
# test that en passant captures result in the correct capture square
self.game.board.set_board_fen('rnbqkbnr/pppppppp/8/6P1/8/8/PPPPPP1P/RNBQKBNR')
self.game.turn = BLACK
self.game.board.turn = BLACK
req, taken, opt_capture = self.game.move(Move(F7, F5))
self.assertEqual(req, taken)
self.assertIsNone(opt_capture)
req, taken, opt_capture = self.game.move(Move(G5, F6))
self.assertEqual(req, taken)
self.assertIsNotNone(opt_capture)
self.assertEqual(opt_capture, F5)
def test_move_opponent_piece(self):
# test moving opponent pieces
b = Board()
b.turn = BLACK
for move in b.generate_pseudo_legal_moves():
with self.assertRaises(ValueError):
self.game.move(move)
def test_move_no_piece(self):
# test a move from a square with no piece
for from_square in SquareSet(BB_RANK_3 | BB_RANK_4 | BB_RANK_5 | BB_RANK_6):
for to_square in SQUARES:
with self.assertRaises(ValueError):
m = Move(from_square, to_square)
self.game.move(m)
def test_move_illegal(self):
for from_square in SquareSet(BB_RANK_1 | BB_RANK_2):
for to_square in SQUARES:
move = Move(from_square, to_square)
if move not in self.game.move_actions():
with self.assertRaises(ValueError):
self.game.move(move)
def test_sliding_straight_capture(self):
"""
. . . . . . . .
. . . p . . . .
. . . . . . . .
. p . R . p . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
"""
result_by_move = {
Move(D5, C5): (Move(D5, C5), None),
Move(D5, B5): (Move(D5, B5), B5),
Move(D5, A5): (Move(D5, B5), B5),
Move(D5, D6): (Move(D5, D6), None),
Move(D5, D7): (Move(D5, D7), D7),
Move(D5, D8): (Move(D5, D7), D7),
Move(D5, E5): (Move(D5, E5), None),
Move(D5, F5): (Move(D5, F5), F5),
Move(D5, G5): (Move(D5, F5), F5),
Move(D5, H5): (Move(D5, F5), F5),
Move(D5, D4): (Move(D5, D4), None),
Move(D5, D3): (Move(D5, D3), None),
Move(D5, D2): (Move(D5, D2), None),
Move(D5, D1): (Move(D5, D1), None),
}
for expected_req, (expected_taken, expected_capture) in result_by_move.items():
self.game.board.set_board_fen('8/3p4/8/1p1R1p2/8/8/8/8')
self.game.board.turn = WHITE
self.game.turn = WHITE
req, taken, opt_capture = self.game.move(expected_req)
self.assertEqual(req, expected_req)
self.assertEqual(taken, expected_taken)
self.assertEqual(opt_capture, expected_capture)
def test_sliding_straight_into_ally(self):
"""
. . . . . . . .
. . . p . . . .
. . . . . . . .
. p . R . p . .
. . . . . . . .
. . . . . . . .
. . . P . . . .
. . . . . . . .
"""
for move in [Move(D5, D2), Move(D5, D1)]:
self.game.board.set_board_fen('8/3p4/8/1p1R1p2/8/8/3P4/8')
self.game.board.turn = WHITE
self.game.turn = WHITE
with self.assertRaises(ValueError):
req, taken, opt_capture = self.game.move(move)
def test_sliding_diagonal_capture(self):
"""
p . . . . . p .
. . . . . . . .
. . . . . . . .
. . . X . . . .
. . . . . . . .
. . . . . . . .
p . . . . . p .
. . . . . . . .
"""
result_by_move = {
Move(D5, C6): (Move(D5, C6), None),
Move(D5, B7): (Move(D5, B7), None),
Move(D5, A8): (Move(D5, A8), A8),
Move(D5, E6): (Move(D5, E6), None),
Move(D5, F7): (Move(D5, F7), None),
Move(D5, G8): (Move(D5, G8), G8),
Move(D5, E4): (Move(D5, E4), None),
Move(D5, F3): (Move(D5, F3), None),
Move(D5, G2): (Move(D5, G2), G2),
Move(D5, H1): (Move(D5, G2), G2),
Move(D5, C4): (Move(D5, C4), None),
Move(D5, B3): (Move(D5, B3), None),
Move(D5, A2): (Move(D5, A2), A2),
}
for expected_req, (expected_taken, expected_capture) in result_by_move.items():
self.game.board.set_board_fen('p5p1/8/8/3B4/8/8/p5p1/8')
self.game.board.turn = WHITE
self.game.turn = WHITE
req, taken, opt_capture = self.game.move(expected_req)
self.assertEqual(req, expected_req)
self.assertEqual(taken, expected_taken)
self.assertEqual(opt_capture, expected_capture)
def test_sliding_diagonal_into_ally(self):
"""
p . . . . . p .
. . . . . . . .
. . . . . . . .
. . . X . . . .
. . . . . . . .
. . . . . . . .
p . . . . . P .
. . . . . . . .
"""
for move in [Move(D5, G2), Move(D5, H1)]:
self.game.board.set_board_fen('p5p1/8/8/3B4/8/8/p5P1/8')
self.game.board.turn = WHITE
self.game.turn = WHITE
with self.assertRaises(ValueError):
req, taken, opt_capture = self.game.move(move)
def test_pawn_auto_promotion(self):
"""
. . . . . . . .
. . . P . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
"""
self.game.board.set_board_fen('8/3P4/8/8/8/8/8/8')
req, taken, opt_capture = self.game.move(Move(D7, D8))
self.assertEqual(Move(D7, D8), req)
self.assertNotEqual(req, taken)
self.assertEqual(req.to_square, taken.to_square)
self.assertEqual(req.from_square, taken.from_square)
self.assertIsNone(req.promotion)
self.assertEqual(taken.promotion, QUEEN)
def test_pass(self):
req, taken, opt_capture = self.game.move(None)
self.assertEqual(req, None)
self.assertEqual(taken, None)
self.assertIsNone(opt_capture)
self.game.board.turn = BLACK
req, taken, opt_capture = self.game.move(None)
self.assertEqual(req, None)
self.assertEqual(taken, None)
self.assertIsNone(opt_capture)
self.game.board.turn = WHITE
self.game.board.remove_piece_at(0)
req, taken, opt_capture = self.game.move(None)
self.assertEqual(req, None)
self.assertEqual(taken, None)
self.assertIsNone(opt_capture)
def test_legal_fuzz(self, max_turns=500):
board = Board()
turn = 1
while not board.is_game_over() and turn < max_turns:
move = random.choice(list(board.generate_pseudo_legal_moves()) + [None])
req, taken, opt_square = self.game.move(move)
self.assertEqual(req, taken)
if move is not None and board.is_capture(move):
self.assertIsNotNone(opt_square)
board.push(move if move is not None else Move.null())
self.assertEqual(self.game.board, board)
turn += 1
class OpponentMoveResultsTestCase(unittest.TestCase):
def test_no_capture(self):
game = LocalGame()
game.start()
_, _, result1 = game.move(Move(A2, A4))
self.assertIsNone(result1)
self.assertEqual(result1, game.opponent_move_results())
game.end_turn()
self.assertEqual(result1, game.opponent_move_results())
game.sense(E5)
self.assertEqual(result1, game.opponent_move_results())
_, _, result2 = game.move(Move(F7, F5))
self.assertIsNone(result2)
self.assertEqual(result2, game.opponent_move_results())
def test_capture(self):
"""
r n b q k b n r
p p p . . p p p
. . . . . . . .
. . . p p . . .
. . . P P . . .
. . . . . . . .
P P P . . P P P
R N B Q K B N R
"""
game = LocalGame()
game.board.set_board_fen('rnbqkbnr/ppp2ppp/8/3pp3/3PP3/8/PPP2PPP/RNBQKBNR')
game.start()
_, _, result1 = game.move(Move(D4, E5))
self.assertEqual(result1, E5)
self.assertEqual(result1, game.opponent_move_results())
game.end_turn()
self.assertEqual(result1, game.opponent_move_results())
game.sense(E5)
self.assertEqual(result1, game.opponent_move_results())
_, _, result2 = game.move(Move(D5, E4))
self.assertEqual(result2, E4)
self.assertEqual(result2, game.opponent_move_results())
class IsOverTest(unittest.TestCase):
def test_not_over(self):
game = LocalGame()
game.start()
self.assertFalse(game.is_over())
def test_forced_over(self):
game = LocalGame()
game.start()
self.assertFalse(game.is_over())
game.end()
self.assertTrue(game.is_over())
def test_no_time_both(self):
game = LocalGame(seconds_per_player=0)
game.start()
self.assertTrue(game.is_over())
def test_no_time_white(self):
game = LocalGame()
game.seconds_left_by_color[WHITE] = 0
game.start()
self.assertTrue(game.is_over())
def test_no_time_black(self):
game = LocalGame()
game.seconds_left_by_color[BLACK] = 0
game.start()
self.assertTrue(game.is_over())
def test_white_king_captured(self):
"""
r n b q k b n r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
P P P P P P P P
R N B Q . B N R
"""
game = LocalGame()
game.board.set_board_fen('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQ1BNR')
game.start()
self.assertTrue(game.is_over())
def test_black_king_captured(self):
"""
r n b q . b n r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
P P P P P P P P
R N B Q K B N R
"""
game = LocalGame()
game.board.set_board_fen('rnbq1bnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR')
game.start()
self.assertTrue(game.is_over())
class WinnerInfoTestCase(unittest.TestCase):
def test_not_over(self):
game = LocalGame()
game.start()
self.assertIsNone(game.get_winner_color())
self.assertIsNone(game.get_win_reason())
def test_forced_over(self):
game = LocalGame()
game.start()
game.end()
self.assertIsNone(game.get_winner_color())
self.assertIsNone(game.get_win_reason())
def test_no_time_white(self):
game = LocalGame()
game.seconds_left_by_color[WHITE] = 0
game.start()
self.assertEqual(BLACK, game.get_winner_color())
self.assertEqual(WinReason.TIMEOUT, game.get_win_reason())
def test_no_time_black(self):
game = LocalGame()
game.seconds_left_by_color[BLACK] = 0
game.start()
self.assertEqual(WHITE, game.get_winner_color())
self.assertEqual(WinReason.TIMEOUT, game.get_win_reason())
def test_white_king_captured(self):
"""
r n b q k b n r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
P P P P P P P P
R N B Q . B N R
"""
game = LocalGame()
game.board.set_board_fen('rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQ1BNR')
game.start()
self.assertEqual(BLACK, game.get_winner_color())
self.assertEqual(WinReason.KING_CAPTURE, game.get_win_reason())
def test_black_king_captured(self):
"""
r n b q . b n r
p p p p p p p p
. . . . . . . .
. . . . . . . .
. . . . . . . .
. . . . . . . .
P P P P P P P P
R N B Q K B N R
"""
game = LocalGame()
game.board.set_board_fen('rnbq1bnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR')
game.start()
self.assertEqual(WHITE, game.get_winner_color())
self.assertEqual(WinReason.KING_CAPTURE, game.get_win_reason())
class GetGameHistoryTestCase(unittest.TestCase):
def test_no_history_until_game_over(self):
g = LocalGame()
g.sense(E2)
self.assertEqual(g.get_game_history(), None)
g.move(Move(E2, E4))
self.assertEqual(g.get_game_history(), None)
g.sense(A8)
g.move(Move(E7, E5))
self.assertEqual(g.get_game_history(), None)
g.sense(E2)
g.move(Move(F1, B5))
g.sense(A8)
g.move(Move(D7, D5))
g.sense(E8)
g.move(Move(B5, E8))
self.assertTrue(g.is_over())
self.assertNotEqual(g.get_game_history(), None)
| test_legal_queenside_castle |
tests.rs | extern crate openssl;
extern crate rand;
use openssl::symm::{Cipher, Crypter, Mode};
use std::io::prelude::*;
use read;
use write;
pub const TEST: &[u8] = b"It was the best of times, it was the worst of times.";
#[test]
fn basic_read_encrypt() {
let source: &[u8] = TEST;
let key: [u8; 128 / 8] = rand::random();
let iv: [u8; 128 / 8] = rand::random();
let cipher = Cipher::aes_128_cbc();
let mut encrypted = [0u8; 1024];
let mut encryptor = read::Encryptor::new(source, cipher, &key, &iv).unwrap();
let mut total_bytes_read = 0;
loop {
let bytes_read = encryptor
.read(&mut encrypted)
.expect("Encryptor read failure!");
if bytes_read == 0 {
break;
}
eprintln!("Read {} bytes out of encrypted stream", bytes_read);
eprintln!(
"Bytes: {:?}",
&encrypted[total_bytes_read..total_bytes_read + bytes_read]
);
total_bytes_read += bytes_read;
}
let mut crypter = Crypter::new(cipher, Mode::Decrypt, &key, Some(&iv)).unwrap();
let mut decrypted = [0u8; 1024];
let mut bytes_decrypted = crypter
.update(&encrypted[0..total_bytes_read], &mut decrypted)
.unwrap();
bytes_decrypted += crypter.finalize(&mut decrypted[bytes_decrypted..]).unwrap();
eprintln!("Decrypted {} bytes", bytes_decrypted);
let decrypted_msg = String::from_utf8(decrypted[0..bytes_decrypted].to_vec()).unwrap();
eprintln!("Decrypted message: {}", decrypted_msg);
assert_eq!(String::from_utf8(source.to_vec()).unwrap(), decrypted_msg);
}
#[test]
fn basic_write_encrypt() {
let source: &[u8] = TEST;
let key: [u8; 128 / 8] = rand::random(); | let mut bytes_written = 0;
{
let mut encryptor = write::Encryptor::new(&mut encrypted, cipher, &key, &iv).unwrap();
while bytes_written < source.len() {
let write_bytes = encryptor.write(&source[bytes_written..]).unwrap();
eprintln!("Wrote {} bytes to cryptostream", write_bytes);
bytes_written += write_bytes;
}
}
eprintln!("Encrypted bytes: {:?}", &encrypted[0..bytes_written]);
let mut crypter = Crypter::new(cipher, Mode::Decrypt, &key, Some(&iv)).unwrap();
let mut decrypted = [0u8; 1024];
let mut bytes_decrypted = crypter.update(&encrypted, &mut decrypted).unwrap();
bytes_decrypted += crypter.finalize(&mut decrypted[bytes_decrypted..]).unwrap();
eprintln!("Decrypted {} bytes", bytes_decrypted);
let decrypted_msg = String::from_utf8(decrypted[0..bytes_decrypted].to_vec()).unwrap();
eprintln!("Decrypted message: {}", decrypted_msg);
assert_eq!(String::from_utf8(source.to_vec()).unwrap(), decrypted_msg);
}
#[test]
fn basic_read_decrypt() {
let source = TEST;
let key: [u8; 128 / 8] = rand::random();
let iv: [u8; 128 / 8] = rand::random();
let cipher = Cipher::aes_128_cbc();
let mut crypter = Crypter::new(cipher, Mode::Encrypt, &key, Some(&iv)).unwrap();
let mut encrypted = [0u8; 1024];
let mut bytes_written = crypter.update(TEST, &mut encrypted).unwrap();
bytes_written += crypter.finalize(&mut encrypted[bytes_written..]).unwrap();
let encrypted = &encrypted[0..bytes_written]; // reframe
let mut decrypted = [0u8; 1024];
let mut bytes_decrypted = 0;
{
let mut decryptor = read::Decryptor::new(encrypted, cipher, &key, &iv).unwrap();
while bytes_decrypted < source.len() {
let decrypt_bytes = decryptor.read(&mut decrypted[bytes_decrypted..]).unwrap();
bytes_decrypted += decrypt_bytes;
}
eprintln!("Decrypted a total of {} bytes", bytes_decrypted);
}
let decrypted = &decrypted[0..bytes_decrypted]; // reframe
assert_eq!(&decrypted, &TEST);
}
#[test]
fn basic_write_decrypt() {
let source = TEST;
let key: [u8; 128 / 8] = rand::random();
let iv: [u8; 128 / 8] = rand::random();
let cipher = Cipher::aes_128_cbc();
let mut cryptor = Crypter::new(cipher, Mode::Encrypt, &key, Some(&iv)).unwrap();
let mut encrypted = [0u8; 1024];
let mut bytes_written = cryptor.update(TEST, &mut encrypted).unwrap();
bytes_written += cryptor.finalize(&mut encrypted[bytes_written..]).unwrap();
let encrypted = &encrypted[0..bytes_written]; // reframe
let mut decrypted = Vec::new();
let mut bytes_decrypted = 0;
{
let mut decryptor = write::Decryptor::new(&mut decrypted, cipher, &key, &iv).unwrap();
while bytes_decrypted < source.len() {
let decrypt_bytes = decryptor.write(&encrypted[bytes_decrypted..]).unwrap();
bytes_decrypted += decrypt_bytes;
}
eprintln!("Decrypted a total of {} bytes", bytes_decrypted);
}
assert_eq!(&decrypted, &TEST);
}
#[test]
fn empty_read_decrypt() {
let key: [u8; 128 / 8] = rand::random();
let iv: [u8; 128 / 8] = rand::random();
let cipher = Cipher::aes_128_cbc();
let encrypted: &[u8] = b"";
let mut decrypted = [0u8; 1024];
let mut decryptor = read::Decryptor::new(encrypted, cipher, &key, &iv).unwrap();
let decrypted_bytes = decryptor.read(&mut decrypted[0..]).unwrap();
assert_eq!(decrypted_bytes, 0);
} | let iv: [u8; 128 / 8] = rand::random();
let cipher = Cipher::aes_128_cbc();
let mut encrypted = Vec::new(); |
prometheus_reporter.go | package prometheus_reporter
import (
"github.com/boostlearn/go-cluster-limiter/cluster_limiter"
"github.com/prometheus/client_golang/prometheus"
)
type PromReporter struct {
metricVec *prometheus.GaugeVec
}
func NewLimiterReporter(reporterName string) cluster_limiter.ReporterI |
func (reporter *PromReporter) Update(name string, metrics map[string]float64) {
for metricName, metricValue := range metrics {
metric := reporter.metricVec.WithLabelValues(name, metricName)
if metric != nil {
metric.Set(metricValue)
}
}
}
| {
if len(reporterName) == 0 {
reporterName = "boostlearn"
}
reporter := &PromReporter{}
reporter.metricVec = prometheus.NewGaugeVec(prometheus.GaugeOpts{
Namespace: reporterName,
Subsystem: "",
Name: "cluster_limiter",
}, []string{"name", "metric"})
prometheus.MustRegister(reporter.metricVec)
return reporter
} |
circularity.ts | import debugModule from "debug";
const debug = debugModule("codec:format:utils:circularity");
import type * as Format from "@truffle/codec/format/common";
export function tie(untied: Format.Values.Result): Format.Values.Result {
return tieWithTable(untied, []);
}
function tieWithTable(
untied: Format.Values.Result,
seenSoFar: (Format.Values.ArrayValue | Format.Values.StructValue)[]
): Format.Values.Result {
if (untied.kind === "error") {
return untied;
}
let reference: number;
switch (untied.type.typeClass) {
case "array":
let untiedAsArray = <Format.Values.ArrayValue>untied; //dammit TS
reference = untiedAsArray.reference;
if (reference === undefined) {
//we need to do some pointer stuff here, so let's first create our new
//object we'll be pointing to | let tied = { ...untiedAsArray, value: [...untiedAsArray.value] };
//now, we can't use a map here, or we'll screw things up!
//we want to *mutate* value, not replace it with a new object
for (let index in tied.value) {
tied.value[index] = tieWithTable(tied.value[index], [
tied,
...seenSoFar
]);
}
return tied;
} else {
return { ...seenSoFar[reference - 1], reference };
}
case "struct":
let untiedAsStruct = <Format.Values.StructValue>untied; //dammit TS
reference = untiedAsStruct.reference;
if (reference === undefined) {
//we need to do some pointer stuff here, so let's first create our new
//object we'll be pointing to
//[we don't want to alter the original accidentally so let's clone a bit]
let tied = {
...untiedAsStruct,
value: untiedAsStruct.value.map(component => ({ ...component }))
};
//now, we can't use a map here, or we'll screw things up!
//we want to *mutate* value, not replace it with a new object
for (let index in tied.value) {
tied.value[index] = {
...tied.value[index],
value: tieWithTable(tied.value[index].value, [tied, ...seenSoFar])
};
}
return tied;
} else {
return { ...seenSoFar[reference - 1], reference };
}
case "tuple": //currently there are no memory tuples, but may as well
//can't be circular, just recurse
//note we can just recurse with a straight tie here; don't need tieWithTable
let untiedAsTuple = <Format.Values.TupleValue>untied; //dammit TS
//we need to do some pointer stuff here, so let's first create our new
//object we'll be pointing to
let tied = { ...untiedAsTuple };
tied.value = tied.value.map(component => ({
...component,
value: tie(component.value)
}));
return tied;
default:
//other types either:
//1. aren't containers and so need no recursion
//2. are containers but can't go in or contain memory things
//and so still need no recursion
//(or, in the case of mappings, can't contain *nontrivial* memory
//things)
return untied;
}
} | //[we don't want to alter the original accidentally so let's clone a bit] |
event.rs | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
use std::path::PathBuf;
use std::time::SystemTime;
use reverie::syscalls::Sysno;
use reverie::Errno;
use reverie::ExitStatus;
use reverie::Pid;
use reverie::Tid;
use serde::{Deserialize, Serialize};
use serde_json::json;
/// A message sent to the global state whenever a thread shuts down.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ThreadExit {
/// Process ID.
pub pid: Pid,
/// Thread ID.
pub tid: Tid,
/// The start time of the thread.
pub start: SystemTime,
/// The end time of the thread.
pub end: SystemTime,
/// The series of events from this thread.
pub events: Vec<Event>,
/// The final exit status of this thread.
pub exit_status: ExitStatus,
}
// TODO: Handle signal, rdtsc, and cpuid events.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Event {
/// A syscall event. Happens whenever a syscall happens.
Syscall {
/// The time at which the syscall started.
start: SystemTime,
/// The time at which the syscall completed.
end: SystemTime,
/// The syscall number.
sysno: Sysno,
/// The formatted syscall with all of its arguments.
pretty: String,
/// The result of the syscall.
result: Result<i64, Errno>,
},
/// A successful execve event.
Exec {
/// The time at which the execve syscall was executed.
timestamp: SystemTime,
/// The program being executed.
program: Program,
},
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct | {
/// The path to the program.
pub name: PathBuf,
/// The program arguments.
pub args: Vec<String>,
}
impl Program {
pub fn new(name: PathBuf, args: Vec<String>) -> Self {
Self { name, args }
}
}
impl ThreadExit {
pub fn trace_event(&self, epoch: SystemTime, events: &mut Vec<serde_json::Value>) {
let thread_name = format!("TID {}", self.tid);
// Record the thread/process start.
{
let ts = self.start.duration_since(epoch).unwrap().as_micros() as u64;
events.push(json!({
"name": thread_name,
"cat": "process",
"ph": "B",
"ts": ts,
"pid": self.pid,
"tid": self.tid,
}));
}
for event in &self.events {
match event {
Event::Syscall {
start,
end,
sysno,
pretty,
result,
} => {
let ts = start.duration_since(epoch).unwrap().as_micros() as u64;
let duration = end.duration_since(*start).unwrap().as_micros() as u64;
events.push(json!({
"name": sysno.to_string(),
"cat": "syscall",
"ph": "X",
"ts": ts,
"dur": duration,
"pid": self.pid,
"tid": self.tid,
"args": {
"pretty": pretty,
"result": format!("{:?}", result),
},
}));
}
Event::Exec { timestamp, program } => {
let ts = timestamp.duration_since(epoch).unwrap().as_micros() as u64;
// FIXME: This shouldn't be an "instant" event. We should be
// able to determine the duration of the execve call.
events.push(json!({
"name": "execve",
"cat": "syscall",
"ph": "i",
"ts": ts,
"pid": self.pid,
"tid": self.tid,
"args": {
"program": program,
}
}));
}
}
}
// Record the thread/process exit.
{
let ts = self.end.duration_since(epoch).unwrap().as_micros() as u64;
events.push(json!({
"name": thread_name,
"cat": "process",
"ph": "E",
"ts": ts,
"pid": self.pid,
"tid": self.tid,
"args": {
"exit_status": self.exit_status,
}
}));
}
}
}
| Program |
xlsx.go | // Copyright 2020, Tamás Gulácsi.
//
// SPDX-License-Identifier: Apache-2.0
package xlsx
import (
"fmt"
"io"
"strings"
"sync"
"time"
"github.com/xuri/excelize/v2"
"github.com/UNO-SOFT/spreadsheet"
)
var _ = (spreadsheet.Writer)((*XLSXWriter)(nil))
type XLSXWriter struct {
w io.Writer
xl *excelize.File
styles map[string]int
sheets []string
mu sync.Mutex
}
type XLSXSheet struct {
xl *excelize.File
Name string
row int64
mu sync.Mutex
}
// NewWriter returns a new spreadsheet.Writer.
//
// This writer allows concurrent writes to separate sheets.
//
// This writer collects everything in memory, so big sheets may impose problems.
func Ne | io.Writer) *XLSXWriter {
return &XLSXWriter{w: w, xl: excelize.NewFile()}
}
func (xlw *XLSXWriter) Close() error {
if xlw == nil {
return nil
}
xlw.mu.Lock()
defer xlw.mu.Unlock()
xl, w := xlw.xl, xlw.w
xlw.xl, xlw.w = nil, nil
if xl == nil || w == nil {
return nil
}
_, err := xl.WriteTo(w)
return err
}
func (xlw *XLSXWriter) NewSheet(name string, columns []spreadsheet.Column) (spreadsheet.Sheet, error) {
xlw.mu.Lock()
defer xlw.mu.Unlock()
xlw.sheets = append(xlw.sheets, name)
if len(xlw.sheets) == 1 { // first
xlw.xl.SetSheetName("Sheet1", name)
} else {
xlw.xl.NewSheet(name)
}
var hasHeader bool
for i, c := range columns {
col, err := excelize.ColumnNumberToName(i + 1)
if err != nil {
return nil, err
}
if s := xlw.getStyle(c.Column); s != 0 {
if err = xlw.xl.SetColStyle(name, col, s); err != nil {
return nil, err
}
}
if s := xlw.getStyle(c.Header); s != 0 {
if err = xlw.xl.SetCellStyle(name, col+"1", col+"1", s); err != nil {
return nil, err
}
}
if c.Name != "" {
hasHeader = true
if err = xlw.xl.SetCellStr(name, col+"1", c.Name); err != nil {
return nil, err
}
}
}
xls := &XLSXSheet{xl: xlw.xl, Name: name}
if hasHeader {
xls.row++
}
return xls, nil
}
func (xlw *XLSXWriter) getStyle(style spreadsheet.Style) int {
if !style.FontBold && style.Format == "" {
return 0
}
k := fmt.Sprintf("%t\t%s", style.FontBold, style.Format)
s, ok := xlw.styles[k]
if ok {
return s
}
var buf strings.Builder
buf.WriteByte('{')
if style.FontBold {
buf.WriteString(`"font":{"bold":true}`)
}
if style.Format != "" {
if buf.Len() > 1 {
buf.WriteByte(',')
}
fmt.Fprintf(&buf, `"custom_number_format":%q`, style.Format)
}
buf.WriteByte('}')
s, err := xlw.xl.NewStyle(buf.String())
if err != nil {
panic(err)
}
if xlw.styles == nil {
xlw.styles = make(map[string]int)
}
xlw.styles[k] = s
return s
}
const MaxRowCount = 1_048_576
func (xls *XLSXSheet) Close() error { return nil }
func (xls *XLSXSheet) AppendRow(values ...interface{}) error {
xls.mu.Lock()
defer xls.mu.Unlock()
if xls.row >= MaxRowCount {
return spreadsheet.ErrTooManyRows
}
xls.row++
for i, v := range values {
axis, err := excelize.CoordinatesToCellName(i+1, int(xls.row))
if err != nil {
return fmt.Errorf("%d/%d: %w", i, int(xls.row), err)
}
isNil := v == nil
if !isNil {
if t, ok := v.(time.Time); ok {
if isNil = t.IsZero(); !isNil {
if err = xls.xl.SetCellStr(xls.Name, axis, t.Format("2006-01-02")); err != nil {
return fmt.Errorf("%s[%s]: %w", xls.Name, axis, err)
}
continue
}
}
}
if isNil {
continue
}
if err = xls.xl.SetCellValue(xls.Name, axis, v); err != nil {
return fmt.Errorf("%s[%s]: %w", xls.Name, axis, err)
}
}
return nil
}
| wWriter(w |
manage.py | #!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def | ():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'where_to_go.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
| main |
index.test.ts | import * as assert from 'assert'
import * as os from 'os'
import { Position, window, workspace, WorkspaceEdit } from 'vscode'
import { getFixturePath, getOptionsForFixture, wait } from './testUtils'
import * as utils from 'vscode-test-utils'
suite('EditorConfig extension', () => {
suiteTeardown(utils.closeAllFiles)
test('indent_style = tab; tab_width = n', async () => {
for (const n of [2, 3, 4]) {
const options = await getOptionsForFixture([`tab-width-${n}`])
assert.strictEqual(
options.insertSpaces,
false,
`editor has insertSpaces: true`,
)
assert.strictEqual(
options.tabSize,
n,
`editor has a tabSize of ${options.tabSize} instead of ${n}`,
)
}
})
test('indent_style = space; indent_size = n', async () => {
for (const n of [2, 3, 4]) {
const options = await getOptionsForFixture([`indent-size-${n}`])
assert.strictEqual(
options.insertSpaces,
true,
`editor has insertSpaces: false`,
)
assert.strictEqual(
options.tabSize,
n,
`editor has a tabSize of ${options.tabSize} instead of ${n}`,
)
}
})
test('subfolder settings', async () => {
for (const n of [2, 3, 4, 'x']) {
const options = await getOptionsForFixture(['folder', `tab-width-${n}`])
const expectedTabSize = n === 'x' ? 8 : n
assert.strictEqual(
options.insertSpaces,
false,
`editor has insertSpaces: true`,
)
assert.strictEqual(
options.tabSize,
expectedTabSize,
`editor has a tabSize of ${options.tabSize} instead of ${expectedTabSize}`,
)
}
})
test('insert_final_newline = true', async () => {
const savedText = await withSetting(
'insert_final_newline',
'true',
).saveText('foo')
assert.strictEqual(
savedText,
`foo${os.EOL}`,
'editor fails to insert final newline on save',
)
})
test('insert_final_newline = false', async () => {
const text = `foo${os.EOL}`
const savedText = await withSetting(
'insert_final_newline',
'false',
).saveText(text)
assert.strictEqual(
savedText,
text,
'editor fails to preserve final newline on save',
)
})
test('insert_final_newline = unset', async () => {
const text = `foo${os.EOL}`
const savedText1 = await withSetting(
'insert_final_newline',
'unset',
).saveText(text)
assert.strictEqual(
savedText1,
text,
'editor fails to preserve final newline on save',
)
const savedText2 = await withSetting(
'insert_final_newline',
'unset-2',
).saveText('foo')
assert.strictEqual(
savedText2,
'foo',
'editor fails to preserve no final newline on save',
)
})
test('trim_trailing_whitespace = true', async () => {
const savedText = await withSetting(
'trim_trailing_whitespace',
'true',
).saveText('foo ')
assert.strictEqual(
savedText,
'foo',
'editor fails to trim trailing whitespace on save',
)
})
test('trim_trailing_whitespace = false', async () => {
const savedText = await withSetting(
'trim_trailing_whitespace',
'false',
).saveText('foo ')
assert.strictEqual(
savedText,
'foo ',
'editor fails to preserve trailing whitespace on save',
)
})
test('trim_trailing_whitespace = unset', async () => {
const savedText = await withSetting(
'trim_trailing_whitespace',
'unset',
).saveText('foo ')
assert.strictEqual(
savedText,
'foo ',
'editor fails to preserve trailing whitespace on save',
)
})
test('end_of_line = lf', async () => {
const savedText = await withSetting('end_of_line', 'lf').saveText('foo\r\n')
assert.strictEqual(
savedText,
'foo\n',
'editor fails to convert CRLF line endings into LF on save',
)
})
test('end_of_line = crlf', async () => {
const savedText = await withSetting('end_of_line', 'crlf').saveText('foo\n')
assert.strictEqual(
savedText,
'foo\r\n',
'editor fails to convert LF line endings into CRLF on save',
)
})
test('end_of_line = unset', async () => {
const savedText = await withSetting('end_of_line', 'unset', {
contents: '\r\n',
}).saveText('foo')
assert.strictEqual(
savedText,
'foo\r\n',
'editor fails to preserve CRLF line endings on save',
)
})
test('detect indentation (space, empty root)', async () => {
const options = await getOptionsForFixture([
'detect-indentation',
'root',
'indent-style-space',
])
const expectedTabSize = 2
assert.strictEqual(
options.tabSize,
expectedTabSize,
`editor has a tabSize of ${options.tabSize} instead of ${expectedTabSize}`,
)
assert.strictEqual(
options.insertSpaces,
true,
`editor has insertSpaces: ${options.insertSpaces}`,
)
})
test('detect indentation (tab, empty root)', async () => {
const options = await getOptionsForFixture([
'detect-indentation',
'root',
'indent-style-tab',
])
const expectedTabSize = 4
assert.strictEqual(
options.tabSize,
expectedTabSize,
`editor has a tabSize of ${options.tabSize} instead of ${expectedTabSize}`,
)
assert.strictEqual(
options.insertSpaces,
false,
`editor has insertSpaces: ${options.insertSpaces}`,
)
})
test('detect indentation (space, unset tab_width=8)', async () => {
const options = await getOptionsForFixture([
'detect-indentation',
'tab_width',
'indent-style-space',
])
const expectedTabSize = 2
assert.strictEqual(
options.tabSize,
expectedTabSize,
`editor has a tabSize of ${options.tabSize} instead of ${expectedTabSize}`,
)
assert.strictEqual(
options.insertSpaces,
true,
`editor has insertSpaces: ${options.insertSpaces}`,
)
})
test('detect indentation (tab, unset tab_width=4)', async () => {
const options = await getOptionsForFixture([
'detect-indentation',
'tab_width',
'indent-style-tab',
])
const expectedTabSize = 4
assert.strictEqual(
options.tabSize,
expectedTabSize,
`editor has a tabSize of ${options.tabSize} instead of ${expectedTabSize}`,
)
assert.strictEqual(
options.insertSpaces,
false,
`editor has insertSpaces: ${options.insertSpaces}`,
)
})
test('detect indentation (space, unset)', async () => {
const options = await getOptionsForFixture([
'detect-indentation',
'unset',
'indent-style-space',
])
const expectedTabSize = 2
assert.strictEqual(
options.tabSize,
expectedTabSize,
`editor has a tabSize of ${options.tabSize} instead of ${expectedTabSize}`,
)
assert.strictEqual(
options.insertSpaces,
true,
`editor has insertSpaces: ${options.insertSpaces}`,
)
})
test('detect indentation (tab, unset)', async () => {
const options = await getOptionsForFixture([
'detect-indentation',
'unset',
'indent-style-tab',
])
const expectedTabSize = 4
assert.strictEqual(
options.tabSize,
expectedTabSize,
`editor has a tabSize of ${options.tabSize} instead of ${expectedTabSize}`,
)
assert.strictEqual(
options.insertSpaces,
false,
`editor has insertSpaces: ${options.insertSpaces}`,
)
})
})
function withSetting(
rule: string,
value: string,
options: {
contents?: string
} = {},
) {
return {
async getText() {
return (await createDoc(options.contents)).getText()
},
saveText(text: string) {
return new Promise<string>(async resolve => {
const doc = await createDoc(options.contents)
workspace.onDidChangeTextDocument(doc.save)
workspace.onDidSaveTextDocument(savedDoc => {
assert.strictEqual(savedDoc.isDirty, false, 'dirty saved doc')
resolve(savedDoc.getText())
})
const edit = new WorkspaceEdit()
edit.insert(doc.uri, new Position(0, 0), text)
assert.strictEqual(
await workspace.applyEdit(edit),
true,
'editor fails to apply edit',
)
})
},
}
async function | (contents = '') {
const uri = await utils.createFile(
contents,
getFixturePath([rule, value, 'test']),
)
const doc = await workspace.openTextDocument(uri)
await window.showTextDocument(doc)
await wait(50) // wait for EditorConfig to apply new settings
return doc
}
}
| createDoc |
tests.rs | use ds_api_types::EntropicPackument;
use maplit::hashmap;
use parse_package_arg::PackageArg;
use semver::{Version, VersionReq};
use ssri::Integrity;
use pick_version::Picker;
#[test]
fn basic_carat_range() {
let packument = EntropicPackument {
versions: hashmap! {
Version::parse("1.0.0").unwrap() => "sha256-100".parse().unwrap(),
Version::parse("1.0.1").unwrap() => "sha256-101".parse().unwrap(),
Version::parse("1.0.2").unwrap() => "sha256-102".parse().unwrap(),
Version::parse("2.0.0").unwrap() => "sha256-200".parse().unwrap(),
},
..EntropicPackument::default()
};
let sri = Picker::new()
.pick(
&packument,
&PackageArg::Range {
host: None,
name: "foo".into(),
range: VersionReq::parse("^1.0.0").unwrap(),
},
)
.unwrap();
assert_eq!(sri, "sha256-102".parse::<Integrity>().unwrap());
}
#[test]
fn basic_tilde_range() {
let packument = EntropicPackument {
versions: hashmap! {
Version::parse("1.0.0").unwrap() => "sha256-100".parse().unwrap(),
Version::parse("1.0.1").unwrap() => "sha256-101".parse().unwrap(),
Version::parse("1.0.2").unwrap() => "sha256-102".parse().unwrap(),
Version::parse("2.0.0").unwrap() => "sha256-200".parse().unwrap(),
},
..EntropicPackument::default()
};
let sri = Picker::new()
.pick(
&packument,
&PackageArg::Range {
host: None,
name: "foo".into(),
range: VersionReq::parse("~1.0.0").unwrap(),
},
)
.unwrap();
assert_eq!(sri, "sha256-102".parse::<Integrity>().unwrap());
}
#[test]
fn basic_math_range() {
let packument = EntropicPackument {
versions: hashmap! {
Version::parse("1.0.0").unwrap() => "sha256-100".parse().unwrap(),
Version::parse("1.0.1").unwrap() => "sha256-101".parse().unwrap(),
Version::parse("1.0.2").unwrap() => "sha256-102".parse().unwrap(),
Version::parse("2.0.0").unwrap() => "sha256-200".parse().unwrap(),
},
..EntropicPackument::default()
};
let sri = Picker::new()
.pick(
&packument,
&PackageArg::Range {
host: None,
name: "foo".into(),
range: VersionReq::parse("<2.0.0").unwrap(),
},
)
.unwrap();
assert_eq!(sri, "sha256-102".parse::<Integrity>().unwrap());
}
#[test]
fn basic_version_match() {
let packument = EntropicPackument {
versions: hashmap! {
Version::parse("1.0.0").unwrap() => "sha256-100".parse().unwrap(),
Version::parse("1.0.1").unwrap() => "sha256-101".parse().unwrap(),
Version::parse("1.0.2").unwrap() => "sha256-102".parse().unwrap(),
Version::parse("2.0.0").unwrap() => "sha256-200".parse().unwrap(),
},
..EntropicPackument::default()
};
let sri = Picker::new()
.pick(
&packument,
&PackageArg::Version {
host: None,
name: "foo".into(),
version: Version::parse("1.0.1").unwrap(),
},
)
.unwrap();
assert_eq!(sri, "sha256-101".parse::<Integrity>().unwrap());
}
#[test]
fn basic_tag_match() |
#[test]
fn tag_match_with_custom_default_tag() {
let packument = EntropicPackument {
tags: hashmap! {
"something".into() => Version::parse("1.0.1").unwrap(),
"latest".into() => Version::parse("1.0.2").unwrap()
},
versions: hashmap! {
Version::parse("1.0.0").unwrap() => "sha256-100".parse().unwrap(),
Version::parse("1.0.1").unwrap() => "sha256-101".parse().unwrap(),
Version::parse("1.0.2").unwrap() => "sha256-102".parse().unwrap(),
Version::parse("2.0.0").unwrap() => "sha256-200".parse().unwrap(),
},
..EntropicPackument::default()
};
let sri = Picker::new()
.default_tag("something".into())
.pick(
&packument,
&PackageArg::Tag {
host: None,
name: "foo".into(),
tag: "something".into(),
},
)
.unwrap();
assert_eq!(sri, "sha256-101".parse::<Integrity>().unwrap());
}
#[test]
fn star_range_uses_default_tag() {
let packument = EntropicPackument {
tags: hashmap! {
"latest".into() => Version::parse("1.0.0-pre.0").unwrap(),
"beta".into() => Version::parse("2.0.0-beta.0").unwrap(),
},
versions: hashmap! {
Version::parse("1.0.0-pre.0").unwrap() => "sha256-100b0".parse().unwrap(),
Version::parse("1.0.0-pre.1").unwrap() => "sha256-100b1".parse().unwrap(),
Version::parse("2.0.0-beta.0").unwrap() => "sha256-200b0".parse().unwrap(),
Version::parse("2.0.0-beta.1").unwrap() => "sha256-200b1".parse().unwrap(),
},
..EntropicPackument::default()
};
let sri = Picker::new()
.default_tag("beta".into())
.pick(
&packument,
&PackageArg::Range {
host: None,
name: "foo".into(),
range: VersionReq::any(),
},
)
.unwrap();
assert_eq!(sri, "sha256-200b0".parse::<Integrity>().unwrap());
let sri = Picker::new()
.pick(
&packument,
&PackageArg::Range {
host: None,
name: "foo".into(),
range: VersionReq::parse("*").unwrap(),
},
)
.unwrap();
assert_eq!(sri, "sha256-100b0".parse::<Integrity>().unwrap());
}
#[test]
fn error_if_no_match() {
let packument = EntropicPackument {
versions: hashmap! {
Version::parse("1.0.0").unwrap() => "sha256-100".parse().unwrap(),
Version::parse("1.0.1").unwrap() => "sha256-101".parse().unwrap(),
Version::parse("1.0.2").unwrap() => "sha256-102".parse().unwrap(),
Version::parse("2.0.0").unwrap() => "sha256-200".parse().unwrap(),
},
..EntropicPackument::default()
};
let sri = Picker::new().pick(
&packument,
&PackageArg::Range {
host: None,
name: "foo".into(),
range: VersionReq::parse("^2.0.1").unwrap(),
},
);
assert!(sri.is_err());
}
#[test]
fn error_if_no_versions() {
let packument = EntropicPackument::default();
let sri = Picker::new().pick(
&packument,
&PackageArg::Range {
host: None,
name: "foo".into(),
range: VersionReq::parse("^1.0.0").unwrap(),
},
);
assert!(sri.is_err());
}
| {
let packument = EntropicPackument {
tags: hashmap! {
"latest".into() => Version::parse("1.0.1").unwrap()
},
versions: hashmap! {
Version::parse("1.0.0").unwrap() => "sha256-100".parse().unwrap(),
Version::parse("1.0.1").unwrap() => "sha256-101".parse().unwrap(),
Version::parse("1.0.2").unwrap() => "sha256-102".parse().unwrap(),
Version::parse("2.0.0").unwrap() => "sha256-200".parse().unwrap(),
},
..EntropicPackument::default()
};
let sri = Picker::new()
.pick(
&packument,
&PackageArg::Tag {
host: None,
name: "foo".into(),
tag: "latest".into(),
},
)
.unwrap();
assert_eq!(sri, "sha256-101".parse::<Integrity>().unwrap());
} |
okcoinusd.py | # -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from ccxt.base.errors import ArgumentsRequired
from ccxt.base.errors import BadRequest
from ccxt.base.errors import InsufficientFunds
from ccxt.base.errors import InvalidOrder
from ccxt.base.errors import OrderNotFound
from ccxt.base.errors import DDoSProtection
class okcoinusd (Exchange):
def | (self):
return self.deep_extend(super(okcoinusd, self).describe(), {
'id': 'okcoinusd',
'name': 'OKCoin USD',
'countries': ['CN', 'US'],
'version': 'v1',
'rateLimit': 1000, # up to 3000 requests per 5 minutes ≈ 600 requests per minute ≈ 10 requests per second ≈ 100 ms
'has': {
'CORS': False,
'fetchOHLCV': True,
'fetchOrder': True,
'fetchOrders': False,
'fetchOpenOrders': True,
'fetchClosedOrders': True,
'fetchTickers': True,
'withdraw': True,
'futures': False,
},
'extension': '.do', # appended to endpoint URL
'timeframes': {
'1m': '1min',
'3m': '3min',
'5m': '5min',
'15m': '15min',
'30m': '30min',
'1h': '1hour',
'2h': '2hour',
'4h': '4hour',
'6h': '6hour',
'12h': '12hour',
'1d': '1day',
'3d': '3day',
'1w': '1week',
},
'api': {
'web': {
'get': [
'futures/pc/market/marketOverview',
'spot/markets/index-tickers',
'spot/markets/currencies',
'spot/markets/products',
'spot/markets/tickers',
'spot/user-level',
],
'post': [
'futures/pc/market/futuresCoin',
],
},
'public': {
'get': [
'depth',
'exchange_rate',
'future_depth',
'future_estimated_price',
'future_hold_amount',
'future_index',
'future_kline',
'future_price_limit',
'future_ticker',
'future_trades',
'kline',
'otcs',
'ticker',
'tickers',
'trades',
],
},
'private': {
'post': [
'account_records',
'batch_trade',
'borrow_money',
'borrow_order_info',
'borrows_info',
'cancel_borrow',
'cancel_order',
'cancel_otc_order',
'cancel_withdraw',
'funds_transfer',
'future_batch_trade',
'future_cancel',
'future_devolve',
'future_explosive',
'future_order_info',
'future_orders_info',
'future_position',
'future_position_4fix',
'future_trade',
'future_trades_history',
'future_userinfo',
'future_userinfo_4fix',
'lend_depth',
'order_fee',
'order_history',
'order_info',
'orders_info',
'otc_order_history',
'otc_order_info',
'repayment',
'submit_otc_order',
'trade',
'trade_history',
'trade_otc_order',
'wallet_info',
'withdraw',
'withdraw_info',
'unrepayments_info',
'userinfo',
],
},
},
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/27766791-89ffb502-5ee5-11e7-8a5b-c5950b68ac65.jpg',
'api': {
'web': 'https://www.okcoin.com/v2',
'public': 'https://www.okcoin.com/api',
'private': 'https://www.okcoin.com',
},
'www': 'https://www.okcoin.com',
'doc': [
'https://www.okcoin.com/docs/en/',
'https://www.npmjs.com/package/okcoin.com',
],
'referral': 'https://www.okcoin.com/account/register?flag=activity&channelId=600001513',
},
# these are okcoin.com fees, okex fees are in okex.js
'fees': {
'trading': {
'taker': 0.001,
'maker': 0.0005,
},
},
'exceptions': {
# see https://github.com/okcoin-okex/API-docs-OKEx.com/blob/master/API-For-Spot-EN/Error%20Code%20For%20Spot.md
'10000': ExchangeError, # "Required field, can not be null"
'10001': DDoSProtection, # "Request frequency too high to exceed the limit allowed"
'10005': AuthenticationError, # "'SecretKey' does not exist"
'10006': AuthenticationError, # "'Api_key' does not exist"
'10007': AuthenticationError, # "Signature does not match"
'1002': InsufficientFunds, # "The transaction amount exceed the balance"
'1003': InvalidOrder, # "The transaction amount is less than the minimum requirement"
'1004': InvalidOrder, # "The transaction amount is less than 0"
'1013': InvalidOrder, # no contract type(PR-1101)
'1027': InvalidOrder, # createLimitBuyOrder(symbol, 0, 0): Incorrect parameter may exceeded limits
'1050': InvalidOrder, # returned when trying to cancel an order that was filled or canceled previously
'1217': InvalidOrder, # "Order was sent at ±5% of the current market price. Please resend"
'10014': InvalidOrder, # "Order price must be between 0 and 1,000,000"
'1009': OrderNotFound, # for spot markets, cancelling closed order
'1019': OrderNotFound, # order closed?("Undo order failed")
'1051': OrderNotFound, # for spot markets, cancelling "just closed" order
'10009': OrderNotFound, # for spot markets, "Order does not exist"
'20015': OrderNotFound, # for future markets
'10008': BadRequest, # Illegal URL parameter
# todo: sort out below
# 10000 Required parameter is empty
# 10001 Request frequency too high to exceed the limit allowed
# 10002 Authentication failure
# 10002 System error
# 10003 This connection has requested other user data
# 10004 Request failed
# 10005 api_key or sign is invalid, 'SecretKey' does not exist
# 10006 'Api_key' does not exist
# 10007 Signature does not match
# 10008 Illegal parameter, Parameter erorr
# 10009 Order does not exist
# 10010 Insufficient funds
# 10011 Amount too low
# 10012 Only btc_usd ltc_usd supported
# 10013 Only support https request
# 10014 Order price must be between 0 and 1,000,000
# 10015 Order price differs from current market price too much / Channel subscription temporally not available
# 10016 Insufficient coins balance
# 10017 API authorization error / WebSocket authorization error
# 10018 borrow amount less than lower limit [usd:100,btc:0.1,ltc:1]
# 10019 loan agreement not checked
# 1002 The transaction amount exceed the balance
# 10020 rate cannot exceed 1%
# 10021 rate cannot less than 0.01%
# 10023 fail to get latest ticker
# 10024 balance not sufficient
# 10025 quota is full, cannot borrow temporarily
# 10026 Loan(including reserved loan) and margin cannot be withdrawn
# 10027 Cannot withdraw within 24 hrs of authentication information modification
# 10028 Withdrawal amount exceeds daily limit
# 10029 Account has unpaid loan, please cancel/pay off the loan before withdraw
# 1003 The transaction amount is less than the minimum requirement
# 10031 Deposits can only be withdrawn after 6 confirmations
# 10032 Please enabled phone/google authenticator
# 10033 Fee higher than maximum network transaction fee
# 10034 Fee lower than minimum network transaction fee
# 10035 Insufficient BTC/LTC
# 10036 Withdrawal amount too low
# 10037 Trade password not set
# 1004 The transaction amount is less than 0
# 10040 Withdrawal cancellation fails
# 10041 Withdrawal address not exsit or approved
# 10042 Admin password error
# 10043 Account equity error, withdrawal failure
# 10044 fail to cancel borrowing order
# 10047 self function is disabled for sub-account
# 10048 withdrawal information does not exist
# 10049 User can not have more than 50 unfilled small orders(amount<0.15BTC)
# 10050 can't cancel more than once
# 10051 order completed transaction
# 10052 not allowed to withdraw
# 10064 after a USD deposit, that portion of assets will not be withdrawable for the next 48 hours
# 1007 No trading market information
# 1008 No latest market information
# 1009 No order
# 1010 Different user of the cancelled order and the original order
# 10100 User account frozen
# 10101 order type is wrong
# 10102 incorrect ID
# 10103 the private otc order's key incorrect
# 10106 API key domain not matched
# 1011 No documented user
# 1013 No order type
# 1014 No login
# 1015 No market depth information
# 1017 Date error
# 1018 Order failed
# 1019 Undo order failed
# 10216 Non-available API / non-public API
# 1024 Currency does not exist
# 1025 No chart type
# 1026 No base currency quantity
# 1027 Incorrect parameter may exceeded limits
# 1028 Reserved decimal failed
# 1029 Preparing
# 1030 Account has margin and futures, transactions can not be processed
# 1031 Insufficient Transferring Balance
# 1032 Transferring Not Allowed
# 1035 Password incorrect
# 1036 Google Verification code Invalid
# 1037 Google Verification code incorrect
# 1038 Google Verification replicated
# 1039 Message Verification Input exceed the limit
# 1040 Message Verification invalid
# 1041 Message Verification incorrect
# 1042 Wrong Google Verification Input exceed the limit
# 1043 Login password cannot be same as the trading password
# 1044 Old password incorrect
# 1045 2nd Verification Needed
# 1046 Please input old password
# 1048 Account Blocked
# 1050 Orders have been withdrawn or withdrawn
# 1051 Order completed
# 1201 Account Deleted at 00: 00
# 1202 Account Not Exist
# 1203 Insufficient Balance
# 1204 Invalid currency
# 1205 Invalid Account
# 1206 Cash Withdrawal Blocked
# 1207 Transfer Not Support
# 1208 No designated account
# 1209 Invalid api
# 1216 Market order temporarily suspended. Please send limit order
# 1217 Order was sent at ±5% of the current market price. Please resend
# 1218 Place order failed. Please try again later
# 20001 User does not exist
# 20002 Account frozen
# 20003 Account frozen due to forced liquidation
# 20004 Contract account frozen
# 20005 User contract account does not exist
# 20006 Required field missing
# 20007 Illegal parameter
# 20008 Contract account balance is too low
# 20009 Contract status error
# 20010 Risk rate ratio does not exist
# 20011 Risk rate lower than 90%/80% before opening BTC position with 10x/20x leverage. or risk rate lower than 80%/60% before opening LTC position with 10x/20x leverage
# 20012 Risk rate lower than 90%/80% after opening BTC position with 10x/20x leverage. or risk rate lower than 80%/60% after opening LTC position with 10x/20x leverage
# 20013 Temporally no counter party price
# 20014 System error
# 20015 Order does not exist
# 20016 Close amount bigger than your open positions, liquidation quantity bigger than holding
# 20017 Not authorized/illegal operation/illegal order ID
# 20018 Order price cannot be more than 103-105% or less than 95-97% of the previous minute price
# 20019 IP restricted from accessing the resource
# 20020 Secret key does not exist
# 20021 Index information does not exist
# 20022 Wrong API interface(Cross margin mode shall call cross margin API, fixed margin mode shall call fixed margin API)
# 20023 Account in fixed-margin mode
# 20024 Signature does not match
# 20025 Leverage rate error
# 20026 API Permission Error
# 20027 no transaction record
# 20028 no such contract
# 20029 Amount is large than available funds
# 20030 Account still has debts
# 20038 Due to regulation, self function is not availavle in the country/region your currently reside in.
# 20049 Request frequency too high
# 20100 request time out
# 20101 the format of data is error
# 20102 invalid login
# 20103 event type error
# 20104 subscription type error
# 20107 JSON format error
# 20115 The quote is not match
# 20116 Param not match
# 21020 Contracts are being delivered, orders cannot be placed
# 21021 Contracts are being settled, contracts cannot be placed
},
'options': {
'marketBuyPrice': False,
'fetchOHLCVWarning': True,
'contractTypes': {
'1': 'this_week',
'2': 'next_week',
'4': 'quarter',
},
'fetchTickersMethod': 'fetch_tickers_from_api',
},
})
def fetch_markets(self, params={}):
# TODO: they have a new fee schedule as of Feb 7
# the new fees are progressive and depend on 30-day traded volume
# the following is the worst case
result = []
spotResponse = self.webGetSpotMarketsProducts()
#
# {
# "code": 0,
# "data": [
# {
# "baseCurrency":0,
# "brokerId":0,
# "callAuctionOrCallNoCancelAuction":false,
# "callNoCancelSwitchTime":{},
# "collect":"0",
# "continuousSwitchTime":{},
# "groupId":1,
# "isMarginOpen":true,
# "listDisplay":0,
# "marginRiskPreRatio":1.2,
# "marginRiskRatio":1.1,
# "marketFrom":118,
# "maxMarginLeverage":5,
# "maxPriceDigit":1,
# "maxSizeDigit":8,
# "mergeTypes":"0.1,1,10",
# "minTradeSize":0.00100000,
# "online":1,
# "productId":20,
# "quoteCurrency":7,
# "quoteIncrement":"0.1",
# "quotePrecision":2,
# "sort":30038,
# "symbol":"btc_usdt",
# "tradingMode":3
# },
# ]
# }
#
spotMarkets = self.safe_value(spotResponse, 'data', [])
markets = spotMarkets
if self.has['futures']:
futuresResponse = self.webPostFuturesPcMarketFuturesCoin()
#
# {
# "msg":"success",
# "code":0,
# "detailMsg":"",
# "data": [
# {
# "symbolId":0,
# "symbol":"f_usd_btc",
# "iceSingleAvgMinAmount":2,
# "minTradeSize":1,
# "iceSingleAvgMaxAmount":500,
# "contractDepthLevel":["0.01","0.2"],
# "dealAllMaxAmount":999,
# "maxSizeDigit":4,
# "contracts":[
# {"marketFrom":34, "id":201905240000034, "type":1, "desc":"BTC0524"},
# {"marketFrom":13, "id":201905310000013, "type":2, "desc":"BTC0531"},
# {"marketFrom":12, "id":201906280000012, "type":4, "desc":"BTC0628"},
# ],
# "maxPriceDigit":2,
# "nativeRate":1,
# "quote":"usd",
# "nativeCurrency":"usd",
# "nativeCurrencyMark":"$",
# "contractSymbol":0,
# "unitAmount":100.00,
# "symbolMark":"฿",
# "symbolDesc":"BTC"
# },
# ]
# }
#
futuresMarkets = self.safe_value(futuresResponse, 'data', [])
markets = self.array_concat(spotMarkets, futuresMarkets)
for i in range(0, len(markets)):
market = markets[i]
id = self.safe_string(market, 'symbol')
symbol = None
base = None
quote = None
baseId = None
quoteId = None
baseNumericId = None
quoteNumericId = None
lowercaseId = None
uppercaseBaseId = None
precision = {
'amount': self.safe_integer(market, 'maxSizeDigit'),
'price': self.safe_integer(market, 'maxPriceDigit'),
}
minAmount = self.safe_float(market, 'minTradeSize')
minPrice = math.pow(10, -precision['price'])
contracts = self.safe_value(market, 'contracts')
if contracts is None:
# spot markets
lowercaseId = id
parts = id.split('_')
baseId = parts[0]
quoteId = parts[1]
baseNumericId = self.safe_integer(market, 'baseCurrency')
quoteNumericId = self.safe_integer(market, 'quoteCurrency')
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
contracts = [{}]
else:
# futures markets
quoteId = self.safe_string(market, 'quote')
uppercaseBaseId = self.safe_string(market, 'symbolDesc')
baseId = uppercaseBaseId.lower()
lowercaseId = baseId + '_' + quoteId
base = self.safe_currency_code(uppercaseBaseId)
quote = self.safe_currency_code(quoteId)
for k in range(0, len(contracts)):
contract = contracts[k]
type = self.safe_string(contract, 'type', 'spot')
contractType = None
spot = True
future = False
active = True
if type == 'spot':
symbol = base + '/' + quote
active = market['online'] != 0
else:
contractId = self.safe_string(contract, 'id')
symbol = base + '-' + quote + '-' + contractId[2:8]
contractType = self.safe_string(self.options['contractTypes'], type)
type = 'future'
spot = False
future = True
fees = self.safe_value_2(self.fees, type, 'trading', {})
result.append(self.extend(fees, {
'id': id,
'lowercaseId': lowercaseId,
'contractType': contractType,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'baseNumericId': baseNumericId,
'quoteNumericId': quoteNumericId,
'info': market,
'type': type,
'spot': spot,
'future': future,
'active': active,
'precision': precision,
'limits': {
'amount': {
'min': minAmount,
'max': None,
},
'price': {
'min': minPrice,
'max': None,
},
'cost': {
'min': minAmount * minPrice,
'max': None,
},
},
}))
return result
def calculate_fee(self, symbol, type, side, amount, price, takerOrMaker='taker', params={}):
market = self.markets[symbol]
key = 'quote'
rate = market[takerOrMaker]
cost = float(self.cost_to_precision(symbol, amount * rate))
if side == 'sell':
cost *= price
else:
key = 'base'
return {
'type': takerOrMaker,
'currency': market[key],
'rate': rate,
'cost': float(self.fee_to_precision(symbol, cost)),
}
def fetch_tickers_from_api(self, symbols=None, params={}):
self.load_markets()
request = {}
response = self.publicGetTickers(self.extend(request, params))
tickers = response['tickers']
timestamp = self.safe_timestamp(response, 'date')
result = {}
for i in range(0, len(tickers)):
ticker = tickers[i]
ticker = self.parse_ticker(self.extend(tickers[i], {'timestamp': timestamp}))
symbol = ticker['symbol']
result[symbol] = ticker
return result
def fetch_tickers_from_web(self, symbols=None, params={}):
self.load_markets()
request = {}
response = self.webGetSpotMarketsTickers(self.extend(request, params))
tickers = self.safe_value(response, 'data')
result = {}
for i in range(0, len(tickers)):
ticker = self.parse_ticker(tickers[i])
symbol = ticker['symbol']
result[symbol] = ticker
return result
def fetch_tickers(self, symbols=None, params={}):
method = self.options['fetchTickersMethod']
return getattr(self, method)(symbols, params)
def fetch_order_book(self, symbol=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
method = 'publicGetFutureDepth' if market['future'] else 'publicGetDepth'
request = self.create_request(market, params)
if limit is not None:
request['size'] = limit
response = getattr(self, method)(request)
return self.parse_order_book(response)
def parse_ticker(self, ticker, market=None):
#
# { buy: "48.777300",
# change: "-1.244500",
# changePercentage: "-2.47%",
# close: "49.064000",
# createdDate: 1531704852254,
# currencyId: 527,
# dayHigh: "51.012500",
# dayLow: "48.124200",
# high: "51.012500",
# inflows: "0",
# last: "49.064000",
# low: "48.124200",
# marketFrom: 627,
# name: {},
# open: "50.308500",
# outflows: "0",
# productId: 527,
# sell: "49.064000",
# symbol: "zec_okb",
# volume: "1049.092535" }
#
timestamp = self.safe_integer_2(ticker, 'timestamp', 'createdDate')
symbol = None
if market is None:
if 'symbol' in ticker:
marketId = ticker['symbol']
if marketId in self.markets_by_id:
market = self.markets_by_id[marketId]
else:
baseId, quoteId = ticker['symbol'].split('_')
base = self.safe_currency_code(baseId)
quote = self.safe_currency_code(quoteId)
symbol = base + '/' + quote
if market is not None:
symbol = market['symbol']
last = self.safe_float(ticker, 'last')
open = self.safe_float(ticker, 'open')
change = self.safe_float(ticker, 'change')
percentage = self.safe_float(ticker, 'changePercentage')
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'high': self.safe_float(ticker, 'high'),
'low': self.safe_float(ticker, 'low'),
'bid': self.safe_float(ticker, 'buy'),
'bidVolume': None,
'ask': self.safe_float(ticker, 'sell'),
'askVolume': None,
'vwap': None,
'open': open,
'close': last,
'last': last,
'previousClose': None,
'change': change,
'percentage': percentage,
'average': None,
'baseVolume': self.safe_float_2(ticker, 'vol', 'volume'),
'quoteVolume': None,
'info': ticker,
}
def fetch_ticker(self, symbol=None, params={}):
self.load_markets()
market = self.market(symbol)
method = 'publicGetFutureTicker' if market['future'] else 'publicGetTicker'
request = self.create_request(market, params)
response = getattr(self, method)(request)
ticker = self.safe_value(response, 'ticker')
if ticker is None:
raise ExchangeError(self.id + ' fetchTicker returned an empty response: ' + self.json(response))
timestamp = self.safe_timestamp(response, 'date')
if timestamp is not None:
ticker = self.extend(ticker, {'timestamp': timestamp})
return self.parse_ticker(ticker, market)
def parse_trade(self, trade, market=None):
symbol = None
if market:
symbol = market['symbol']
timestamp = self.safe_integer(trade, 'date_ms')
id = self.safe_string(trade, 'tid')
type = None
side = self.safe_string(trade, 'type')
price = self.safe_float(trade, 'price')
amount = self.safe_float(trade, 'amount')
cost = None
if price is not None:
if amount is not None:
cost = price * amount
return {
'id': id,
'info': trade,
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'symbol': symbol,
'order': None,
'type': type,
'side': side,
'takerOrMaker': None,
'price': price,
'amount': amount,
'cost': cost,
'fee': None,
}
def fetch_trades(self, symbol, since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
method = 'publicGetFutureTrades' if market['future'] else 'publicGetTrades'
request = self.create_request(market, params)
response = getattr(self, method)(request)
return self.parse_trades(response, market, since, limit)
def parse_ohlcv(self, ohlcv, market=None, timeframe='1m', since=None, limit=None):
numElements = len(ohlcv)
volumeIndex = 6 if (numElements > 6) else 5
return [
ohlcv[0], # timestamp
float(ohlcv[1]), # Open
float(ohlcv[2]), # High
float(ohlcv[3]), # Low
float(ohlcv[4]), # Close
# float(ohlcv[5]), # quote volume
# float(ohlcv[6]), # base volume
float(ohlcv[volumeIndex]), # okex will return base volume in the 7th element for future markets
]
def fetch_ohlcv(self, symbol, timeframe='1m', since=None, limit=None, params={}):
self.load_markets()
market = self.market(symbol)
method = 'publicGetFutureKline' if market['future'] else 'publicGetKline'
request = self.create_request(market, {
'type': self.timeframes[timeframe],
})
if since is not None:
request['since'] = int((self.milliseconds() - 86400000) / 1000) # default last 24h
if limit is not None:
if self.options['fetchOHLCVWarning']:
raise ExchangeError(self.id + ' fetchOHLCV counts "limit" candles backwards in chronological ascending order, therefore the "limit" argument for ' + self.id + ' is disabled. Set ' + self.id + '.options["fetchOHLCVWarning"] = False to suppress self warning message.')
request['size'] = int(limit) # max is 1440 candles
response = getattr(self, method)(self.extend(request, params))
return self.parse_ohlcvs(response, market, timeframe, since, limit)
def fetch_balance(self, params={}):
self.load_markets()
response = self.privatePostUserinfo(params)
info = self.safe_value(response, 'info', {})
balances = self.safe_value(info, 'funds', {})
result = {'info': response}
ids = list(balances['free'].keys())
usedField = 'freezed'
# wtf, okex?
# https://github.com/okcoin-okex/API-docs-OKEx.com/commit/01cf9dd57b1f984a8737ef76a037d4d3795d2ac7
if not(usedField in list(balances.keys())):
usedField = 'holds'
usedKeys = list(balances[usedField].keys())
ids = self.array_concat(ids, usedKeys)
for i in range(0, len(ids)):
id = ids[i]
code = self.safe_currency_code(id)
account = self.account()
account['free'] = self.safe_float(balances['free'], id)
account['used'] = self.safe_float(balances[usedField], id)
result[code] = account
return self.parse_balance(result)
def create_order(self, symbol, type, side, amount, price=None, params={}):
self.load_markets()
market = self.market(symbol)
method = 'privatePostFutureTrade' if market['future'] else 'privatePostTrade'
orderSide = (side + '_market') if (type == 'market') else side
isMarketBuy = ((market['spot']) and (type == 'market') and (side == 'buy') and (not self.options['marketBuyPrice']))
orderPrice = self.safe_float(params, 'cost') if isMarketBuy else price
request = self.create_request(market, {
'type': orderSide,
})
if market['future']:
request['match_price'] = 1 if (type == 'market') else 0 # match best counter party price? 0 or 1, ignores price if 1
request['lever_rate'] = 10 # leverage rate value: 10 or 20(10 by default)
request['type'] = '1' if (side == 'buy') else '2'
elif type == 'market':
if side == 'buy':
if not orderPrice:
if self.options['marketBuyPrice']:
# eslint-disable-next-line quotes
raise ExchangeError(self.id + " market buy orders require a price argument(the amount you want to spend or the cost of the order) when self.options['marketBuyPrice'] is True.")
else:
# eslint-disable-next-line quotes
raise ExchangeError(self.id + " market buy orders require an additional cost parameter, cost = price * amount. If you want to pass the cost of the market order(the amount you want to spend) in the price argument(the default " + self.id + " behaviour), set self.options['marketBuyPrice'] = True. It will effectively suppress self warning exception as well.")
else:
request['price'] = orderPrice
else:
request['amount'] = amount
if type != 'market':
request['price'] = orderPrice
request['amount'] = amount
params = self.omit(params, 'cost')
response = getattr(self, method)(self.extend(request, params))
timestamp = self.milliseconds()
return {
'info': response,
'id': self.safe_string(response, 'order_id'),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'lastTradeTimestamp': None,
'status': None,
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'amount': amount,
'filled': None,
'remaining': None,
'cost': None,
'trades': None,
'fee': None,
}
def cancel_order(self, id, symbol=None, params={}):
if symbol is None:
raise ArgumentsRequired(self.id + ' cancelOrder() requires a symbol argument')
self.load_markets()
market = self.market(symbol)
method = 'privatePostFutureCancel' if market['future'] else 'privatePostCancelOrder'
request = self.create_request(market, {
'order_id': id,
})
response = getattr(self, method)(self.extend(request, params))
return response
def parse_order_status(self, status):
statuses = {
'-1': 'canceled',
'0': 'open',
'1': 'open',
'2': 'closed',
'3': 'open',
'4': 'canceled',
}
return self.safe_value(statuses, status, status)
def parse_order_side(self, side):
if side == 1:
return 'buy' # open long position
elif side == 2:
return 'sell' # open short position
elif side == 3:
return 'sell' # liquidate long position
elif side == 4:
return 'buy' # liquidate short position
return side
def parse_order(self, order, market=None):
side = None
type = None
if 'type' in order:
if (order['type'] == 'buy') or (order['type'] == 'sell'):
side = order['type']
type = 'limit'
elif order['type'] == 'buy_market':
side = 'buy'
type = 'market'
elif order['type'] == 'sell_market':
side = 'sell'
type = 'market'
else:
side = self.parse_order_side(order['type'])
if ('contract_name' in list(order.keys())) or ('lever_rate' in list(order.keys())):
type = 'margin'
status = self.parse_order_status(self.safe_string(order, 'status'))
symbol = None
if market is None:
marketId = self.safe_string(order, 'symbol')
if marketId in self.markets_by_id:
market = self.markets_by_id[marketId]
if market:
symbol = market['symbol']
createDateField = self.get_create_date_field()
timestamp = self.safe_integer(order, createDateField)
amount = self.safe_float(order, 'amount')
filled = self.safe_float(order, 'deal_amount')
amount = max(amount, filled)
remaining = max(0, amount - filled)
if type == 'market':
remaining = 0
average = self.safe_float(order, 'avg_price')
# https://github.com/ccxt/ccxt/issues/2452
average = self.safe_float(order, 'price_avg', average)
cost = average * filled
return {
'info': order,
'id': self.safe_string(order, 'order_id'),
'timestamp': timestamp,
'datetime': self.iso8601(timestamp),
'lastTradeTimestamp': None,
'symbol': symbol,
'type': type,
'side': side,
'price': self.safe_float(order, 'price'),
'average': average,
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': None,
}
def get_create_date_field(self):
# needed for derived exchanges
# allcoin typo create_data instead of create_date
return 'create_date'
def get_orders_field(self):
# needed for derived exchanges
# allcoin typo order instead of orders(expected based on their API docs)
return 'orders'
def fetch_order(self, id, symbol=None, params={}):
if symbol is None:
raise ExchangeError(self.id + ' fetchOrder requires a symbol argument')
self.load_markets()
market = self.market(symbol)
method = 'privatePostFutureOrderInfo' if market['future'] else 'privatePostOrderInfo'
request = self.create_request(market, {
'order_id': id,
# 'status': 0, # 0 for unfilled orders, 1 for filled orders
# 'current_page': 1, # current page number
# 'page_length': 200, # number of orders returned per page, maximum 200
})
response = getattr(self, method)(self.extend(request, params))
ordersField = self.get_orders_field()
numOrders = len(response[ordersField])
if numOrders > 0:
return self.parse_order(response[ordersField][0])
raise OrderNotFound(self.id + ' order ' + id + ' not found')
def fetch_orders(self, symbol=None, since=None, limit=None, params={}):
if symbol is None:
raise ExchangeError(self.id + ' fetchOrders requires a symbol argument')
self.load_markets()
market = self.market(symbol)
method = 'privatePostFutureOrdersInfo' if market['future'] else 'privatePost'
request = self.create_request(market)
order_id_in_params = ('order_id' in list(params.keys()))
if market['future']:
if not order_id_in_params:
raise ExchangeError(self.id + ' fetchOrders() requires order_id param for futures market ' + symbol + '(a string of one or more order ids, comma-separated)')
else:
status = params['type'] if ('type' in list(params.keys())) else params['status']
if status is None:
name = 'type' if order_id_in_params else 'status'
raise ExchangeError(self.id + ' fetchOrders() requires ' + name + ' param for spot market ' + symbol + '(0 - for unfilled orders, 1 - for filled/canceled orders)')
if order_id_in_params:
method += 'OrdersInfo'
request = self.extend(request, {
'type': status,
'order_id': params['order_id'],
})
else:
method += 'OrderHistory'
request = self.extend(request, {
'status': status,
'current_page': 1, # current page number
'page_length': 200, # number of orders returned per page, maximum 200
})
params = self.omit(params, ['type', 'status'])
response = getattr(self, method)(self.extend(request, params))
ordersField = self.get_orders_field()
return self.parse_orders(response[ordersField], market, since, limit)
def fetch_open_orders(self, symbol=None, since=None, limit=None, params={}):
request = {
'status': 0, # 0 for unfilled orders, 1 for filled orders
}
return self.fetch_orders(symbol, since, limit, self.extend(request, params))
def fetch_closed_orders(self, symbol=None, since=None, limit=None, params={}):
request = {
'status': 1, # 0 for unfilled orders, 1 for filled orders
}
return self.fetch_orders(symbol, since, limit, self.extend(request, params))
def withdraw(self, code, amount, address, tag=None, params={}):
self.check_address(address)
self.load_markets()
currency = self.currency(code)
# if amount < 0.01:
# raise ExchangeError(self.id + ' withdraw() requires amount > 0.01')
# for some reason they require to supply a pair of currencies for withdrawing one currency
currencyId = currency['id'] + '_usd'
if tag:
address = address + ':' + tag
request = {
'symbol': currencyId,
'withdraw_address': address,
'withdraw_amount': amount,
'target': 'address', # or 'okcn', 'okcom', 'okex'
}
query = params
if 'chargefee' in query:
request['chargefee'] = query['chargefee']
query = self.omit(query, 'chargefee')
else:
raise ExchangeError(self.id + ' withdraw() requires a `chargefee` parameter')
if self.password:
request['trade_pwd'] = self.password
elif 'password' in query:
request['trade_pwd'] = query['password']
query = self.omit(query, 'password')
elif 'trade_pwd' in query:
request['trade_pwd'] = query['trade_pwd']
query = self.omit(query, 'trade_pwd')
passwordInRequest = ('trade_pwd' in list(request.keys()))
if not passwordInRequest:
raise ExchangeError(self.id + ' withdraw() requires self.password set on the exchange instance or a password / trade_pwd parameter')
response = self.privatePostWithdraw(self.extend(request, query))
return {
'info': response,
'id': self.safe_string(response, 'withdraw_id'),
}
def sign(self, path, api='public', method='GET', params={}, headers=None, body=None):
url = '/'
if api != 'web':
url += self.version + '/'
url += path
if api != 'web':
url += self.extension
if api == 'private':
self.check_required_credentials()
query = self.keysort(self.extend({
'api_key': self.apiKey,
}, params))
# secret key must be at the end of query
queryString = self.rawencode(query) + '&secret_key=' + self.secret
query['sign'] = self.hash(self.encode(queryString)).upper()
body = self.urlencode(query)
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
else:
if params:
url += '?' + self.urlencode(params)
url = self.urls['api'][api] + url
return {'url': url, 'method': method, 'body': body, 'headers': headers}
def create_request(self, market, params={}):
if market['future']:
return self.deep_extend({
'symbol': market['lowercaseId'],
'contract_type': market['contractType'],
}, params)
return self.deep_extend({
'symbol': market['id'],
}, params)
def handle_errors(self, code, reason, url, method, headers, body, response, requestHeaders, requestBody):
if response is None:
return # fallback to default error handler
if 'error_code' in response:
error = self.safe_string(response, 'error_code')
message = self.id + ' ' + self.json(response)
if error in self.exceptions:
ExceptionClass = self.exceptions[error]
raise ExceptionClass(message)
else:
raise ExchangeError(message)
if 'result' in response:
if not response['result']:
raise ExchangeError(self.id + ' ' + self.json(response))
| describe |
max_bytes_filter_vows.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com [email protected]
from os.path import abspath, join, dirname
from pyvows import Vows, expect
from tornado_pyvows.context import TornadoHTTPContext
from thumbor.app import ThumborServiceApp
#from thumbor.filters.max_bytes import Filter
from thumbor.context import Context, ServerParameters
from thumbor.config import Config
from thumbor.importer import Importer
storage_path = abspath(join(dirname(__file__), 'fixtures/'))
@Vows.batch
class MaxBytesFilterVows(TornadoHTTPContext):
def get_app(self):
cfg = Config(SECURITY_KEY='ACME-SEC')
cfg.LOADER = "thumbor.loaders.file_loader"
cfg.FILE_LOADER_ROOT_PATH = storage_path
importer = Importer(cfg)
importer.import_modules()
server = ServerParameters(8889, 'localhost', 'thumbor.conf', None, 'info', None)
server.security_key = 'ACME-SEC'
ctx = Context(server, cfg, importer)
application = ThumborServiceApp(ctx)
return application
class WithRegularImage(TornadoHTTPContext):
| def topic(self):
response = self.get('/unsafe/filters:max_bytes(10000)/conselheira_tutelar.jpg')
return (response.code, response.body)
def should_be_200(self, response):
code, image = response
expect(code).to_equal(200)
expect(len(image)).to_be_lesser_or_equal_to(10000) |
|
user.module.ts | import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { UserInfo } from './userInfo/userInfo.component';
import { Bonus } from './bonus/bonus.component';
import { Homework } from './homework/homework.component';
@NgModule({
declarations: [
UserInfo,
Bonus,
Homework
],
imports: [IonicModule.forRoot(UserInfo)],
bootstrap: [IonicApp],
entryComponents: [
UserInfo,
Bonus,
Homework
],
providers: [
{provide: ErrorHandler, useClass: IonicErrorHandler}
],
exports: [IonicModule]
})
export class UserModule {} | import { ErrorHandler, NgModule } from '@angular/core'; |
|
diagram.xml.converter.ts | import {IXmlConvertService} from '../../../contracts/index';
import {IExportService} from '../../../contracts/index';
import {ExportService} from './export.service';
export class | implements IXmlConvertService {
private _xmlContent: string;
private _enqueuedPromises: Array<Promise<string>> = [];
constructor(xmlContent: string) {
this._xmlContent = xmlContent;
}
public asBpmn(): IExportService {
const formatterPromise: Promise<string> = this._bpmnExporter();
const mimeType: string = 'application/bpmn20-xml';
this._enqueuedPromises.push(formatterPromise);
return new ExportService(mimeType, this._enqueuedPromises);
}
/**
* Formats the current loaded xml.
*/
private _bpmnExporter = async(): Promise<string> => {
return Promise.resolve(this._xmlContent);
}
}
| DiagramXmlConverter |
Cruise.tsx | /**
* @file Cruise 航海
* @author Auto Generated by IconPark
*/
/* tslint:disable: max-line-length */ | /* eslint-disable max-len */
import {ISvgIconProps, IconHelper, IconWrapper} from '../runtime';
export default IconWrapper(
'cruise',
false,
(h: IconHelper, props: ISvgIconProps) => (
<svg
width={props.size}
height={props.size}
viewBox="0 0 48 48"
fill="none"
>
<path
d="M38 42L41.3908 32.6752C41.738 31.7205 41.3143 30.6572 40.4057 30.2028L24.8944 22.4472C24.3314 22.1657 23.6686 22.1657 23.1056 22.4472L7.59432 30.2028C6.68569 30.6572 6.26199 31.7205 6.60916 32.6752L10 42"
stroke={props.colors[0]}
stroke-width={props.strokeWidth}
stroke-linejoin={props.strokeLinejoin}
/>
<path
d="M35 14H13C11.8954 14 11 14.8954 11 16V28L23.1619 22.3868C23.6937 22.1414 24.3063 22.1414 24.8381 22.3868L37 28V16C37 14.8954 36.1046 14 35 14Z"
fill={props.colors[1]}
stroke={props.colors[0]}
stroke-width={props.strokeWidth}
stroke-linecap={props.strokeLinecap}
stroke-linejoin={props.strokeLinejoin}
/>
<path
d="M29 14V6C29 4.89543 28.1046 4 27 4H21C19.8954 4 19 4.89543 19 6V14"
stroke={props.colors[0]}
stroke-width={props.strokeWidth}
stroke-linecap={props.strokeLinecap}
stroke-linejoin={props.strokeLinejoin}
/>
<path
d="M24 32V40"
stroke={props.colors[0]}
stroke-width={props.strokeWidth}
stroke-linecap={props.strokeLinecap}
/>
<path
d="M4 44C8 44 8 42 11 42C14 42 14 44 17 44C20 44 20.5 42 24 42C27.5 42 28 44 31 44C34 44 34 42 37 42C40 42 40 44 44 44"
stroke={props.colors[0]}
stroke-width={props.strokeWidth}
stroke-linecap={props.strokeLinecap}
stroke-linejoin={props.strokeLinejoin}
/>
</svg>
)
); | |
pulumiTypes.go | // *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
package v20190801
import (
"context"
"reflect"
"github.com/pulumi/pulumi/sdk/v3/go/pulumi"
)
// The type of the paths for alias.
type AliasPathTypeResponse struct {
// The API versions.
ApiVersions []string `pulumi:"apiVersions"`
// The path of an alias.
Path *string `pulumi:"path"`
}
// AliasPathTypeResponseInput is an input type that accepts AliasPathTypeResponseArgs and AliasPathTypeResponseOutput values.
// You can construct a concrete instance of `AliasPathTypeResponseInput` via:
//
// AliasPathTypeResponseArgs{...}
type AliasPathTypeResponseInput interface {
pulumi.Input
ToAliasPathTypeResponseOutput() AliasPathTypeResponseOutput
ToAliasPathTypeResponseOutputWithContext(context.Context) AliasPathTypeResponseOutput
}
// The type of the paths for alias.
type AliasPathTypeResponseArgs struct {
// The API versions.
ApiVersions pulumi.StringArrayInput `pulumi:"apiVersions"`
// The path of an alias.
Path pulumi.StringPtrInput `pulumi:"path"`
}
func (AliasPathTypeResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*AliasPathTypeResponse)(nil)).Elem()
}
func (i AliasPathTypeResponseArgs) ToAliasPathTypeResponseOutput() AliasPathTypeResponseOutput {
return i.ToAliasPathTypeResponseOutputWithContext(context.Background())
}
func (i AliasPathTypeResponseArgs) ToAliasPathTypeResponseOutputWithContext(ctx context.Context) AliasPathTypeResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(AliasPathTypeResponseOutput)
}
// AliasPathTypeResponseArrayInput is an input type that accepts AliasPathTypeResponseArray and AliasPathTypeResponseArrayOutput values.
// You can construct a concrete instance of `AliasPathTypeResponseArrayInput` via:
//
// AliasPathTypeResponseArray{ AliasPathTypeResponseArgs{...} }
type AliasPathTypeResponseArrayInput interface {
pulumi.Input
ToAliasPathTypeResponseArrayOutput() AliasPathTypeResponseArrayOutput
ToAliasPathTypeResponseArrayOutputWithContext(context.Context) AliasPathTypeResponseArrayOutput
}
type AliasPathTypeResponseArray []AliasPathTypeResponseInput
func (AliasPathTypeResponseArray) ElementType() reflect.Type {
return reflect.TypeOf((*[]AliasPathTypeResponse)(nil)).Elem()
}
func (i AliasPathTypeResponseArray) ToAliasPathTypeResponseArrayOutput() AliasPathTypeResponseArrayOutput {
return i.ToAliasPathTypeResponseArrayOutputWithContext(context.Background())
}
func (i AliasPathTypeResponseArray) ToAliasPathTypeResponseArrayOutputWithContext(ctx context.Context) AliasPathTypeResponseArrayOutput {
return pulumi.ToOutputWithContext(ctx, i).(AliasPathTypeResponseArrayOutput)
}
// The type of the paths for alias.
type AliasPathTypeResponseOutput struct{ *pulumi.OutputState }
func (AliasPathTypeResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*AliasPathTypeResponse)(nil)).Elem()
}
func (o AliasPathTypeResponseOutput) ToAliasPathTypeResponseOutput() AliasPathTypeResponseOutput {
return o
}
func (o AliasPathTypeResponseOutput) ToAliasPathTypeResponseOutputWithContext(ctx context.Context) AliasPathTypeResponseOutput {
return o
}
// The API versions.
func (o AliasPathTypeResponseOutput) ApiVersions() pulumi.StringArrayOutput {
return o.ApplyT(func(v AliasPathTypeResponse) []string { return v.ApiVersions }).(pulumi.StringArrayOutput)
}
// The path of an alias.
func (o AliasPathTypeResponseOutput) Path() pulumi.StringPtrOutput {
return o.ApplyT(func(v AliasPathTypeResponse) *string { return v.Path }).(pulumi.StringPtrOutput)
}
type AliasPathTypeResponseArrayOutput struct{ *pulumi.OutputState }
func (AliasPathTypeResponseArrayOutput) ElementType() reflect.Type {
return reflect.TypeOf((*[]AliasPathTypeResponse)(nil)).Elem()
}
func (o AliasPathTypeResponseArrayOutput) ToAliasPathTypeResponseArrayOutput() AliasPathTypeResponseArrayOutput {
return o
}
func (o AliasPathTypeResponseArrayOutput) ToAliasPathTypeResponseArrayOutputWithContext(ctx context.Context) AliasPathTypeResponseArrayOutput {
return o
}
func (o AliasPathTypeResponseArrayOutput) Index(i pulumi.IntInput) AliasPathTypeResponseOutput {
return pulumi.All(o, i).ApplyT(func(vs []interface{}) AliasPathTypeResponse {
return vs[0].([]AliasPathTypeResponse)[vs[1].(int)]
}).(AliasPathTypeResponseOutput)
}
// The alias type.
type AliasTypeResponse struct {
// The alias name.
Name *string `pulumi:"name"`
// The paths for an alias.
Paths []AliasPathTypeResponse `pulumi:"paths"`
}
// AliasTypeResponseInput is an input type that accepts AliasTypeResponseArgs and AliasTypeResponseOutput values.
// You can construct a concrete instance of `AliasTypeResponseInput` via:
//
// AliasTypeResponseArgs{...}
type AliasTypeResponseInput interface {
pulumi.Input
ToAliasTypeResponseOutput() AliasTypeResponseOutput
ToAliasTypeResponseOutputWithContext(context.Context) AliasTypeResponseOutput
}
// The alias type.
type AliasTypeResponseArgs struct {
// The alias name.
Name pulumi.StringPtrInput `pulumi:"name"`
// The paths for an alias.
Paths AliasPathTypeResponseArrayInput `pulumi:"paths"`
}
func (AliasTypeResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*AliasTypeResponse)(nil)).Elem()
}
func (i AliasTypeResponseArgs) ToAliasTypeResponseOutput() AliasTypeResponseOutput {
return i.ToAliasTypeResponseOutputWithContext(context.Background())
}
func (i AliasTypeResponseArgs) ToAliasTypeResponseOutputWithContext(ctx context.Context) AliasTypeResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(AliasTypeResponseOutput)
}
// AliasTypeResponseArrayInput is an input type that accepts AliasTypeResponseArray and AliasTypeResponseArrayOutput values.
// You can construct a concrete instance of `AliasTypeResponseArrayInput` via:
//
// AliasTypeResponseArray{ AliasTypeResponseArgs{...} }
type AliasTypeResponseArrayInput interface {
pulumi.Input
ToAliasTypeResponseArrayOutput() AliasTypeResponseArrayOutput
ToAliasTypeResponseArrayOutputWithContext(context.Context) AliasTypeResponseArrayOutput
}
type AliasTypeResponseArray []AliasTypeResponseInput
func (AliasTypeResponseArray) ElementType() reflect.Type {
return reflect.TypeOf((*[]AliasTypeResponse)(nil)).Elem()
}
func (i AliasTypeResponseArray) ToAliasTypeResponseArrayOutput() AliasTypeResponseArrayOutput {
return i.ToAliasTypeResponseArrayOutputWithContext(context.Background())
}
func (i AliasTypeResponseArray) ToAliasTypeResponseArrayOutputWithContext(ctx context.Context) AliasTypeResponseArrayOutput {
return pulumi.ToOutputWithContext(ctx, i).(AliasTypeResponseArrayOutput)
}
// The alias type.
type AliasTypeResponseOutput struct{ *pulumi.OutputState }
func (AliasTypeResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*AliasTypeResponse)(nil)).Elem()
}
func (o AliasTypeResponseOutput) ToAliasTypeResponseOutput() AliasTypeResponseOutput {
return o
}
func (o AliasTypeResponseOutput) ToAliasTypeResponseOutputWithContext(ctx context.Context) AliasTypeResponseOutput {
return o
}
// The alias name.
func (o AliasTypeResponseOutput) Name() pulumi.StringPtrOutput {
return o.ApplyT(func(v AliasTypeResponse) *string { return v.Name }).(pulumi.StringPtrOutput)
}
// The paths for an alias.
func (o AliasTypeResponseOutput) Paths() AliasPathTypeResponseArrayOutput {
return o.ApplyT(func(v AliasTypeResponse) []AliasPathTypeResponse { return v.Paths }).(AliasPathTypeResponseArrayOutput)
}
type AliasTypeResponseArrayOutput struct{ *pulumi.OutputState }
func (AliasTypeResponseArrayOutput) ElementType() reflect.Type {
return reflect.TypeOf((*[]AliasTypeResponse)(nil)).Elem()
}
func (o AliasTypeResponseArrayOutput) ToAliasTypeResponseArrayOutput() AliasTypeResponseArrayOutput {
return o
}
func (o AliasTypeResponseArrayOutput) ToAliasTypeResponseArrayOutputWithContext(ctx context.Context) AliasTypeResponseArrayOutput {
return o
}
func (o AliasTypeResponseArrayOutput) Index(i pulumi.IntInput) AliasTypeResponseOutput {
return pulumi.All(o, i).ApplyT(func(vs []interface{}) AliasTypeResponse {
return vs[0].([]AliasTypeResponse)[vs[1].(int)]
}).(AliasTypeResponseOutput)
}
// Deployment dependency information.
type BasicDependencyResponse struct {
// The ID of the dependency.
Id *string `pulumi:"id"`
// The dependency resource name.
ResourceName *string `pulumi:"resourceName"`
// The dependency resource type.
ResourceType *string `pulumi:"resourceType"`
}
// BasicDependencyResponseInput is an input type that accepts BasicDependencyResponseArgs and BasicDependencyResponseOutput values.
// You can construct a concrete instance of `BasicDependencyResponseInput` via:
//
// BasicDependencyResponseArgs{...}
type BasicDependencyResponseInput interface {
pulumi.Input
ToBasicDependencyResponseOutput() BasicDependencyResponseOutput
ToBasicDependencyResponseOutputWithContext(context.Context) BasicDependencyResponseOutput
}
// Deployment dependency information.
type BasicDependencyResponseArgs struct {
// The ID of the dependency.
Id pulumi.StringPtrInput `pulumi:"id"`
// The dependency resource name.
ResourceName pulumi.StringPtrInput `pulumi:"resourceName"`
// The dependency resource type.
ResourceType pulumi.StringPtrInput `pulumi:"resourceType"`
}
func (BasicDependencyResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*BasicDependencyResponse)(nil)).Elem()
}
func (i BasicDependencyResponseArgs) ToBasicDependencyResponseOutput() BasicDependencyResponseOutput {
return i.ToBasicDependencyResponseOutputWithContext(context.Background())
}
func (i BasicDependencyResponseArgs) ToBasicDependencyResponseOutputWithContext(ctx context.Context) BasicDependencyResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(BasicDependencyResponseOutput)
}
// BasicDependencyResponseArrayInput is an input type that accepts BasicDependencyResponseArray and BasicDependencyResponseArrayOutput values.
// You can construct a concrete instance of `BasicDependencyResponseArrayInput` via:
//
// BasicDependencyResponseArray{ BasicDependencyResponseArgs{...} }
type BasicDependencyResponseArrayInput interface {
pulumi.Input
ToBasicDependencyResponseArrayOutput() BasicDependencyResponseArrayOutput
ToBasicDependencyResponseArrayOutputWithContext(context.Context) BasicDependencyResponseArrayOutput
}
type BasicDependencyResponseArray []BasicDependencyResponseInput
func (BasicDependencyResponseArray) ElementType() reflect.Type {
return reflect.TypeOf((*[]BasicDependencyResponse)(nil)).Elem()
}
func (i BasicDependencyResponseArray) ToBasicDependencyResponseArrayOutput() BasicDependencyResponseArrayOutput {
return i.ToBasicDependencyResponseArrayOutputWithContext(context.Background())
}
func (i BasicDependencyResponseArray) ToBasicDependencyResponseArrayOutputWithContext(ctx context.Context) BasicDependencyResponseArrayOutput {
return pulumi.ToOutputWithContext(ctx, i).(BasicDependencyResponseArrayOutput)
}
// Deployment dependency information.
type BasicDependencyResponseOutput struct{ *pulumi.OutputState }
func (BasicDependencyResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*BasicDependencyResponse)(nil)).Elem()
}
func (o BasicDependencyResponseOutput) ToBasicDependencyResponseOutput() BasicDependencyResponseOutput {
return o
}
func (o BasicDependencyResponseOutput) ToBasicDependencyResponseOutputWithContext(ctx context.Context) BasicDependencyResponseOutput {
return o
}
// The ID of the dependency.
func (o BasicDependencyResponseOutput) Id() pulumi.StringPtrOutput {
return o.ApplyT(func(v BasicDependencyResponse) *string { return v.Id }).(pulumi.StringPtrOutput)
}
// The dependency resource name.
func (o BasicDependencyResponseOutput) ResourceName() pulumi.StringPtrOutput {
return o.ApplyT(func(v BasicDependencyResponse) *string { return v.ResourceName }).(pulumi.StringPtrOutput)
}
// The dependency resource type.
func (o BasicDependencyResponseOutput) ResourceType() pulumi.StringPtrOutput {
return o.ApplyT(func(v BasicDependencyResponse) *string { return v.ResourceType }).(pulumi.StringPtrOutput)
}
type BasicDependencyResponseArrayOutput struct{ *pulumi.OutputState }
func (BasicDependencyResponseArrayOutput) ElementType() reflect.Type {
return reflect.TypeOf((*[]BasicDependencyResponse)(nil)).Elem()
}
func (o BasicDependencyResponseArrayOutput) ToBasicDependencyResponseArrayOutput() BasicDependencyResponseArrayOutput {
return o
}
func (o BasicDependencyResponseArrayOutput) ToBasicDependencyResponseArrayOutputWithContext(ctx context.Context) BasicDependencyResponseArrayOutput {
return o
}
func (o BasicDependencyResponseArrayOutput) Index(i pulumi.IntInput) BasicDependencyResponseOutput {
return pulumi.All(o, i).ApplyT(func(vs []interface{}) BasicDependencyResponse {
return vs[0].([]BasicDependencyResponse)[vs[1].(int)]
}).(BasicDependencyResponseOutput)
}
// The debug setting.
type DebugSetting struct {
// Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.
DetailLevel *string `pulumi:"detailLevel"`
}
// DebugSettingInput is an input type that accepts DebugSettingArgs and DebugSettingOutput values.
// You can construct a concrete instance of `DebugSettingInput` via:
//
// DebugSettingArgs{...}
type DebugSettingInput interface {
pulumi.Input
ToDebugSettingOutput() DebugSettingOutput
ToDebugSettingOutputWithContext(context.Context) DebugSettingOutput
}
// The debug setting.
type DebugSettingArgs struct {
// Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.
DetailLevel pulumi.StringPtrInput `pulumi:"detailLevel"`
}
func (DebugSettingArgs) ElementType() reflect.Type {
return reflect.TypeOf((*DebugSetting)(nil)).Elem()
}
func (i DebugSettingArgs) ToDebugSettingOutput() DebugSettingOutput {
return i.ToDebugSettingOutputWithContext(context.Background())
}
func (i DebugSettingArgs) ToDebugSettingOutputWithContext(ctx context.Context) DebugSettingOutput {
return pulumi.ToOutputWithContext(ctx, i).(DebugSettingOutput)
}
func (i DebugSettingArgs) ToDebugSettingPtrOutput() DebugSettingPtrOutput {
return i.ToDebugSettingPtrOutputWithContext(context.Background())
}
func (i DebugSettingArgs) ToDebugSettingPtrOutputWithContext(ctx context.Context) DebugSettingPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(DebugSettingOutput).ToDebugSettingPtrOutputWithContext(ctx)
}
// DebugSettingPtrInput is an input type that accepts DebugSettingArgs, DebugSettingPtr and DebugSettingPtrOutput values.
// You can construct a concrete instance of `DebugSettingPtrInput` via:
//
// DebugSettingArgs{...}
//
// or:
//
// nil
type DebugSettingPtrInput interface {
pulumi.Input
ToDebugSettingPtrOutput() DebugSettingPtrOutput
ToDebugSettingPtrOutputWithContext(context.Context) DebugSettingPtrOutput
}
type debugSettingPtrType DebugSettingArgs
func DebugSettingPtr(v *DebugSettingArgs) DebugSettingPtrInput {
return (*debugSettingPtrType)(v)
}
func (*debugSettingPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**DebugSetting)(nil)).Elem()
}
func (i *debugSettingPtrType) ToDebugSettingPtrOutput() DebugSettingPtrOutput {
return i.ToDebugSettingPtrOutputWithContext(context.Background())
}
func (i *debugSettingPtrType) ToDebugSettingPtrOutputWithContext(ctx context.Context) DebugSettingPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(DebugSettingPtrOutput)
}
// The debug setting.
type DebugSettingOutput struct{ *pulumi.OutputState }
func (DebugSettingOutput) ElementType() reflect.Type {
return reflect.TypeOf((*DebugSetting)(nil)).Elem()
}
func (o DebugSettingOutput) ToDebugSettingOutput() DebugSettingOutput {
return o
}
func (o DebugSettingOutput) ToDebugSettingOutputWithContext(ctx context.Context) DebugSettingOutput {
return o
}
func (o DebugSettingOutput) ToDebugSettingPtrOutput() DebugSettingPtrOutput {
return o.ToDebugSettingPtrOutputWithContext(context.Background())
}
func (o DebugSettingOutput) ToDebugSettingPtrOutputWithContext(ctx context.Context) DebugSettingPtrOutput {
return o.ApplyT(func(v DebugSetting) *DebugSetting {
return &v
}).(DebugSettingPtrOutput)
}
// Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.
func (o DebugSettingOutput) DetailLevel() pulumi.StringPtrOutput {
return o.ApplyT(func(v DebugSetting) *string { return v.DetailLevel }).(pulumi.StringPtrOutput)
}
type DebugSettingPtrOutput struct{ *pulumi.OutputState }
func (DebugSettingPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**DebugSetting)(nil)).Elem()
}
func (o DebugSettingPtrOutput) ToDebugSettingPtrOutput() DebugSettingPtrOutput {
return o
}
func (o DebugSettingPtrOutput) ToDebugSettingPtrOutputWithContext(ctx context.Context) DebugSettingPtrOutput {
return o
}
func (o DebugSettingPtrOutput) Elem() DebugSettingOutput {
return o.ApplyT(func(v *DebugSetting) DebugSetting { return *v }).(DebugSettingOutput)
}
// Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.
func (o DebugSettingPtrOutput) DetailLevel() pulumi.StringPtrOutput {
return o.ApplyT(func(v *DebugSetting) *string {
if v == nil {
return nil
}
return v.DetailLevel
}).(pulumi.StringPtrOutput)
}
// The debug setting.
type DebugSettingResponse struct {
// Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.
DetailLevel *string `pulumi:"detailLevel"`
}
// DebugSettingResponseInput is an input type that accepts DebugSettingResponseArgs and DebugSettingResponseOutput values.
// You can construct a concrete instance of `DebugSettingResponseInput` via:
//
// DebugSettingResponseArgs{...}
type DebugSettingResponseInput interface {
pulumi.Input
ToDebugSettingResponseOutput() DebugSettingResponseOutput
ToDebugSettingResponseOutputWithContext(context.Context) DebugSettingResponseOutput
}
// The debug setting.
type DebugSettingResponseArgs struct {
// Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.
DetailLevel pulumi.StringPtrInput `pulumi:"detailLevel"`
}
func (DebugSettingResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*DebugSettingResponse)(nil)).Elem()
}
func (i DebugSettingResponseArgs) ToDebugSettingResponseOutput() DebugSettingResponseOutput {
return i.ToDebugSettingResponseOutputWithContext(context.Background())
}
func (i DebugSettingResponseArgs) ToDebugSettingResponseOutputWithContext(ctx context.Context) DebugSettingResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(DebugSettingResponseOutput)
}
func (i DebugSettingResponseArgs) ToDebugSettingResponsePtrOutput() DebugSettingResponsePtrOutput {
return i.ToDebugSettingResponsePtrOutputWithContext(context.Background())
}
func (i DebugSettingResponseArgs) ToDebugSettingResponsePtrOutputWithContext(ctx context.Context) DebugSettingResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(DebugSettingResponseOutput).ToDebugSettingResponsePtrOutputWithContext(ctx)
}
// DebugSettingResponsePtrInput is an input type that accepts DebugSettingResponseArgs, DebugSettingResponsePtr and DebugSettingResponsePtrOutput values.
// You can construct a concrete instance of `DebugSettingResponsePtrInput` via:
//
// DebugSettingResponseArgs{...}
//
// or:
//
// nil
type DebugSettingResponsePtrInput interface {
pulumi.Input
ToDebugSettingResponsePtrOutput() DebugSettingResponsePtrOutput
ToDebugSettingResponsePtrOutputWithContext(context.Context) DebugSettingResponsePtrOutput
}
type debugSettingResponsePtrType DebugSettingResponseArgs
func DebugSettingResponsePtr(v *DebugSettingResponseArgs) DebugSettingResponsePtrInput {
return (*debugSettingResponsePtrType)(v)
}
func (*debugSettingResponsePtrType) ElementType() reflect.Type {
return reflect.TypeOf((**DebugSettingResponse)(nil)).Elem()
}
func (i *debugSettingResponsePtrType) ToDebugSettingResponsePtrOutput() DebugSettingResponsePtrOutput {
return i.ToDebugSettingResponsePtrOutputWithContext(context.Background())
}
func (i *debugSettingResponsePtrType) ToDebugSettingResponsePtrOutputWithContext(ctx context.Context) DebugSettingResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(DebugSettingResponsePtrOutput)
}
// The debug setting.
type DebugSettingResponseOutput struct{ *pulumi.OutputState }
func (DebugSettingResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*DebugSettingResponse)(nil)).Elem()
}
func (o DebugSettingResponseOutput) ToDebugSettingResponseOutput() DebugSettingResponseOutput {
return o
}
func (o DebugSettingResponseOutput) ToDebugSettingResponseOutputWithContext(ctx context.Context) DebugSettingResponseOutput {
return o
}
func (o DebugSettingResponseOutput) ToDebugSettingResponsePtrOutput() DebugSettingResponsePtrOutput {
return o.ToDebugSettingResponsePtrOutputWithContext(context.Background())
}
func (o DebugSettingResponseOutput) ToDebugSettingResponsePtrOutputWithContext(ctx context.Context) DebugSettingResponsePtrOutput {
return o.ApplyT(func(v DebugSettingResponse) *DebugSettingResponse {
return &v
}).(DebugSettingResponsePtrOutput)
}
// Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.
func (o DebugSettingResponseOutput) DetailLevel() pulumi.StringPtrOutput {
return o.ApplyT(func(v DebugSettingResponse) *string { return v.DetailLevel }).(pulumi.StringPtrOutput)
}
type DebugSettingResponsePtrOutput struct{ *pulumi.OutputState }
func (DebugSettingResponsePtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**DebugSettingResponse)(nil)).Elem()
}
func (o DebugSettingResponsePtrOutput) ToDebugSettingResponsePtrOutput() DebugSettingResponsePtrOutput {
return o
}
func (o DebugSettingResponsePtrOutput) ToDebugSettingResponsePtrOutputWithContext(ctx context.Context) DebugSettingResponsePtrOutput {
return o
}
func (o DebugSettingResponsePtrOutput) Elem() DebugSettingResponseOutput {
return o.ApplyT(func(v *DebugSettingResponse) DebugSettingResponse { return *v }).(DebugSettingResponseOutput)
}
// Specifies the type of information to log for debugging. The permitted values are none, requestContent, responseContent, or both requestContent and responseContent separated by a comma. The default is none. When setting this value, carefully consider the type of information you are passing in during deployment. By logging information about the request or response, you could potentially expose sensitive data that is retrieved through the deployment operations.
func (o DebugSettingResponsePtrOutput) DetailLevel() pulumi.StringPtrOutput {
return o.ApplyT(func(v *DebugSettingResponse) *string {
if v == nil {
return nil
}
return v.DetailLevel
}).(pulumi.StringPtrOutput)
}
// Deployment dependency information.
type DependencyResponse struct {
// The list of dependencies.
DependsOn []BasicDependencyResponse `pulumi:"dependsOn"`
// The ID of the dependency.
Id *string `pulumi:"id"`
// The dependency resource name.
ResourceName *string `pulumi:"resourceName"`
// The dependency resource type.
ResourceType *string `pulumi:"resourceType"`
}
// DependencyResponseInput is an input type that accepts DependencyResponseArgs and DependencyResponseOutput values.
// You can construct a concrete instance of `DependencyResponseInput` via:
//
// DependencyResponseArgs{...}
type DependencyResponseInput interface {
pulumi.Input
ToDependencyResponseOutput() DependencyResponseOutput
ToDependencyResponseOutputWithContext(context.Context) DependencyResponseOutput
}
// Deployment dependency information.
type DependencyResponseArgs struct {
// The list of dependencies.
DependsOn BasicDependencyResponseArrayInput `pulumi:"dependsOn"`
// The ID of the dependency.
Id pulumi.StringPtrInput `pulumi:"id"`
// The dependency resource name.
ResourceName pulumi.StringPtrInput `pulumi:"resourceName"`
// The dependency resource type.
ResourceType pulumi.StringPtrInput `pulumi:"resourceType"`
}
func (DependencyResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*DependencyResponse)(nil)).Elem()
}
func (i DependencyResponseArgs) ToDependencyResponseOutput() DependencyResponseOutput {
return i.ToDependencyResponseOutputWithContext(context.Background())
}
func (i DependencyResponseArgs) ToDependencyResponseOutputWithContext(ctx context.Context) DependencyResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(DependencyResponseOutput)
}
// DependencyResponseArrayInput is an input type that accepts DependencyResponseArray and DependencyResponseArrayOutput values.
// You can construct a concrete instance of `DependencyResponseArrayInput` via:
//
// DependencyResponseArray{ DependencyResponseArgs{...} }
type DependencyResponseArrayInput interface {
pulumi.Input
ToDependencyResponseArrayOutput() DependencyResponseArrayOutput
ToDependencyResponseArrayOutputWithContext(context.Context) DependencyResponseArrayOutput
}
type DependencyResponseArray []DependencyResponseInput
func (DependencyResponseArray) ElementType() reflect.Type {
return reflect.TypeOf((*[]DependencyResponse)(nil)).Elem()
}
func (i DependencyResponseArray) ToDependencyResponseArrayOutput() DependencyResponseArrayOutput {
return i.ToDependencyResponseArrayOutputWithContext(context.Background())
}
func (i DependencyResponseArray) ToDependencyResponseArrayOutputWithContext(ctx context.Context) DependencyResponseArrayOutput {
return pulumi.ToOutputWithContext(ctx, i).(DependencyResponseArrayOutput)
}
// Deployment dependency information.
type DependencyResponseOutput struct{ *pulumi.OutputState }
func (DependencyResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*DependencyResponse)(nil)).Elem()
}
func (o DependencyResponseOutput) ToDependencyResponseOutput() DependencyResponseOutput {
return o
}
func (o DependencyResponseOutput) ToDependencyResponseOutputWithContext(ctx context.Context) DependencyResponseOutput {
return o
}
// The list of dependencies.
func (o DependencyResponseOutput) DependsOn() BasicDependencyResponseArrayOutput {
return o.ApplyT(func(v DependencyResponse) []BasicDependencyResponse { return v.DependsOn }).(BasicDependencyResponseArrayOutput)
}
// The ID of the dependency.
func (o DependencyResponseOutput) Id() pulumi.StringPtrOutput {
return o.ApplyT(func(v DependencyResponse) *string { return v.Id }).(pulumi.StringPtrOutput)
}
// The dependency resource name.
func (o DependencyResponseOutput) ResourceName() pulumi.StringPtrOutput {
return o.ApplyT(func(v DependencyResponse) *string { return v.ResourceName }).(pulumi.StringPtrOutput)
}
// The dependency resource type.
func (o DependencyResponseOutput) ResourceType() pulumi.StringPtrOutput {
return o.ApplyT(func(v DependencyResponse) *string { return v.ResourceType }).(pulumi.StringPtrOutput)
}
type DependencyResponseArrayOutput struct{ *pulumi.OutputState }
func (DependencyResponseArrayOutput) ElementType() reflect.Type {
return reflect.TypeOf((*[]DependencyResponse)(nil)).Elem()
}
func (o DependencyResponseArrayOutput) ToDependencyResponseArrayOutput() DependencyResponseArrayOutput {
return o
}
func (o DependencyResponseArrayOutput) ToDependencyResponseArrayOutputWithContext(ctx context.Context) DependencyResponseArrayOutput {
return o
}
func (o DependencyResponseArrayOutput) Index(i pulumi.IntInput) DependencyResponseOutput {
return pulumi.All(o, i).ApplyT(func(vs []interface{}) DependencyResponse {
return vs[0].([]DependencyResponse)[vs[1].(int)]
}).(DependencyResponseOutput)
}
// Deployment properties.
type DeploymentProperties struct {
// The debug setting of the deployment.
DebugSetting *DebugSetting `pulumi:"debugSetting"`
// The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.
Mode string `pulumi:"mode"`
// The deployment on error behavior.
OnErrorDeployment *OnErrorDeployment `pulumi:"onErrorDeployment"`
// Name and value pairs that define the deployment parameters for the template. You use this element when you want to provide the parameter values directly in the request rather than link to an existing parameter file. Use either the parametersLink property or the parameters property, but not both. It can be a JObject or a well formed JSON string.
Parameters interface{} `pulumi:"parameters"`
// The URI of parameters file. You use this element to link to an existing parameters file. Use either the parametersLink property or the parameters property, but not both.
ParametersLink *ParametersLink `pulumi:"parametersLink"`
// The template content. You use this element when you want to pass the template syntax directly in the request rather than link to an existing template. It can be a JObject or well-formed JSON string. Use either the templateLink property or the template property, but not both.
Template interface{} `pulumi:"template"`
// The URI of the template. Use either the templateLink property or the template property, but not both.
TemplateLink *TemplateLink `pulumi:"templateLink"`
}
// DeploymentPropertiesInput is an input type that accepts DeploymentPropertiesArgs and DeploymentPropertiesOutput values.
// You can construct a concrete instance of `DeploymentPropertiesInput` via:
//
// DeploymentPropertiesArgs{...}
type DeploymentPropertiesInput interface {
pulumi.Input
ToDeploymentPropertiesOutput() DeploymentPropertiesOutput
ToDeploymentPropertiesOutputWithContext(context.Context) DeploymentPropertiesOutput
}
// Deployment properties.
type DeploymentPropertiesArgs struct {
// The debug setting of the deployment.
DebugSetting DebugSettingPtrInput `pulumi:"debugSetting"`
// The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.
Mode DeploymentMode `pulumi:"mode"`
// The deployment on error behavior.
OnErrorDeployment OnErrorDeploymentPtrInput `pulumi:"onErrorDeployment"`
// Name and value pairs that define the deployment parameters for the template. You use this element when you want to provide the parameter values directly in the request rather than link to an existing parameter file. Use either the parametersLink property or the parameters property, but not both. It can be a JObject or a well formed JSON string.
Parameters pulumi.Input `pulumi:"parameters"`
// The URI of parameters file. You use this element to link to an existing parameters file. Use either the parametersLink property or the parameters property, but not both.
ParametersLink ParametersLinkPtrInput `pulumi:"parametersLink"`
// The template content. You use this element when you want to pass the template syntax directly in the request rather than link to an existing template. It can be a JObject or well-formed JSON string. Use either the templateLink property or the template property, but not both.
Template pulumi.Input `pulumi:"template"`
// The URI of the template. Use either the templateLink property or the template property, but not both.
TemplateLink TemplateLinkPtrInput `pulumi:"templateLink"`
}
func (DeploymentPropertiesArgs) ElementType() reflect.Type {
return reflect.TypeOf((*DeploymentProperties)(nil)).Elem()
}
func (i DeploymentPropertiesArgs) ToDeploymentPropertiesOutput() DeploymentPropertiesOutput {
return i.ToDeploymentPropertiesOutputWithContext(context.Background())
}
func (i DeploymentPropertiesArgs) ToDeploymentPropertiesOutputWithContext(ctx context.Context) DeploymentPropertiesOutput {
return pulumi.ToOutputWithContext(ctx, i).(DeploymentPropertiesOutput)
}
func (i DeploymentPropertiesArgs) ToDeploymentPropertiesPtrOutput() DeploymentPropertiesPtrOutput {
return i.ToDeploymentPropertiesPtrOutputWithContext(context.Background())
}
func (i DeploymentPropertiesArgs) ToDeploymentPropertiesPtrOutputWithContext(ctx context.Context) DeploymentPropertiesPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(DeploymentPropertiesOutput).ToDeploymentPropertiesPtrOutputWithContext(ctx)
}
// DeploymentPropertiesPtrInput is an input type that accepts DeploymentPropertiesArgs, DeploymentPropertiesPtr and DeploymentPropertiesPtrOutput values.
// You can construct a concrete instance of `DeploymentPropertiesPtrInput` via:
//
// DeploymentPropertiesArgs{...}
//
// or:
//
// nil
type DeploymentPropertiesPtrInput interface {
pulumi.Input
ToDeploymentPropertiesPtrOutput() DeploymentPropertiesPtrOutput
ToDeploymentPropertiesPtrOutputWithContext(context.Context) DeploymentPropertiesPtrOutput
}
type deploymentPropertiesPtrType DeploymentPropertiesArgs
func DeploymentPropertiesPtr(v *DeploymentPropertiesArgs) DeploymentPropertiesPtrInput {
return (*deploymentPropertiesPtrType)(v)
}
func (*deploymentPropertiesPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**DeploymentProperties)(nil)).Elem()
}
func (i *deploymentPropertiesPtrType) ToDeploymentPropertiesPtrOutput() DeploymentPropertiesPtrOutput {
return i.ToDeploymentPropertiesPtrOutputWithContext(context.Background())
}
func (i *deploymentPropertiesPtrType) ToDeploymentPropertiesPtrOutputWithContext(ctx context.Context) DeploymentPropertiesPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(DeploymentPropertiesPtrOutput)
}
// Deployment properties.
type DeploymentPropertiesOutput struct{ *pulumi.OutputState }
func (DeploymentPropertiesOutput) ElementType() reflect.Type {
return reflect.TypeOf((*DeploymentProperties)(nil)).Elem()
}
func (o DeploymentPropertiesOutput) ToDeploymentPropertiesOutput() DeploymentPropertiesOutput {
return o
}
func (o DeploymentPropertiesOutput) ToDeploymentPropertiesOutputWithContext(ctx context.Context) DeploymentPropertiesOutput {
return o
}
func (o DeploymentPropertiesOutput) ToDeploymentPropertiesPtrOutput() DeploymentPropertiesPtrOutput {
return o.ToDeploymentPropertiesPtrOutputWithContext(context.Background())
}
func (o DeploymentPropertiesOutput) ToDeploymentPropertiesPtrOutputWithContext(ctx context.Context) DeploymentPropertiesPtrOutput {
return o.ApplyT(func(v DeploymentProperties) *DeploymentProperties {
return &v
}).(DeploymentPropertiesPtrOutput)
}
// The debug setting of the deployment.
func (o DeploymentPropertiesOutput) DebugSetting() DebugSettingPtrOutput {
return o.ApplyT(func(v DeploymentProperties) *DebugSetting { return v.DebugSetting }).(DebugSettingPtrOutput)
}
// The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.
func (o DeploymentPropertiesOutput) Mode() pulumi.StringOutput {
return o.ApplyT(func(v DeploymentProperties) string { return v.Mode }).(pulumi.StringOutput)
}
// The deployment on error behavior.
func (o DeploymentPropertiesOutput) OnErrorDeployment() OnErrorDeploymentPtrOutput {
return o.ApplyT(func(v DeploymentProperties) *OnErrorDeployment { return v.OnErrorDeployment }).(OnErrorDeploymentPtrOutput)
}
// Name and value pairs that define the deployment parameters for the template. You use this element when you want to provide the parameter values directly in the request rather than link to an existing parameter file. Use either the parametersLink property or the parameters property, but not both. It can be a JObject or a well formed JSON string.
func (o DeploymentPropertiesOutput) Parameters() pulumi.AnyOutput {
return o.ApplyT(func(v DeploymentProperties) interface{} { return v.Parameters }).(pulumi.AnyOutput)
}
// The URI of parameters file. You use this element to link to an existing parameters file. Use either the parametersLink property or the parameters property, but not both.
func (o DeploymentPropertiesOutput) ParametersLink() ParametersLinkPtrOutput {
return o.ApplyT(func(v DeploymentProperties) *ParametersLink { return v.ParametersLink }).(ParametersLinkPtrOutput)
}
// The template content. You use this element when you want to pass the template syntax directly in the request rather than link to an existing template. It can be a JObject or well-formed JSON string. Use either the templateLink property or the template property, but not both.
func (o DeploymentPropertiesOutput) Template() pulumi.AnyOutput {
return o.ApplyT(func(v DeploymentProperties) interface{} { return v.Template }).(pulumi.AnyOutput)
}
// The URI of the template. Use either the templateLink property or the template property, but not both.
func (o DeploymentPropertiesOutput) TemplateLink() TemplateLinkPtrOutput {
return o.ApplyT(func(v DeploymentProperties) *TemplateLink { return v.TemplateLink }).(TemplateLinkPtrOutput)
}
type DeploymentPropertiesPtrOutput struct{ *pulumi.OutputState }
func (DeploymentPropertiesPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**DeploymentProperties)(nil)).Elem()
}
func (o DeploymentPropertiesPtrOutput) ToDeploymentPropertiesPtrOutput() DeploymentPropertiesPtrOutput {
return o
}
func (o DeploymentPropertiesPtrOutput) ToDeploymentPropertiesPtrOutputWithContext(ctx context.Context) DeploymentPropertiesPtrOutput {
return o
}
func (o DeploymentPropertiesPtrOutput) Elem() DeploymentPropertiesOutput {
return o.ApplyT(func(v *DeploymentProperties) DeploymentProperties { return *v }).(DeploymentPropertiesOutput)
}
// The debug setting of the deployment.
func (o DeploymentPropertiesPtrOutput) DebugSetting() DebugSettingPtrOutput {
return o.ApplyT(func(v *DeploymentProperties) *DebugSetting {
if v == nil {
return nil
}
return v.DebugSetting
}).(DebugSettingPtrOutput)
}
// The mode that is used to deploy resources. This value can be either Incremental or Complete. In Incremental mode, resources are deployed without deleting existing resources that are not included in the template. In Complete mode, resources are deployed and existing resources in the resource group that are not included in the template are deleted. Be careful when using Complete mode as you may unintentionally delete resources.
func (o DeploymentPropertiesPtrOutput) Mode() pulumi.StringPtrOutput {
return o.ApplyT(func(v *DeploymentProperties) *string {
if v == nil {
return nil
}
return &v.Mode
}).(pulumi.StringPtrOutput)
}
// The deployment on error behavior.
func (o DeploymentPropertiesPtrOutput) OnErrorDeployment() OnErrorDeploymentPtrOutput {
return o.ApplyT(func(v *DeploymentProperties) *OnErrorDeployment {
if v == nil {
return nil
}
return v.OnErrorDeployment
}).(OnErrorDeploymentPtrOutput)
}
// Name and value pairs that define the deployment parameters for the template. You use this element when you want to provide the parameter values directly in the request rather than link to an existing parameter file. Use either the parametersLink property or the parameters property, but not both. It can be a JObject or a well formed JSON string.
func (o DeploymentPropertiesPtrOutput) Parameters() pulumi.AnyOutput {
return o.ApplyT(func(v *DeploymentProperties) interface{} {
if v == nil {
return nil
}
return v.Parameters
}).(pulumi.AnyOutput)
}
// The URI of parameters file. You use this element to link to an existing parameters file. Use either the parametersLink property or the parameters property, but not both.
func (o DeploymentPropertiesPtrOutput) ParametersLink() ParametersLinkPtrOutput {
return o.ApplyT(func(v *DeploymentProperties) *ParametersLink {
if v == nil {
return nil
}
return v.ParametersLink
}).(ParametersLinkPtrOutput)
}
// The template content. You use this element when you want to pass the template syntax directly in the request rather than link to an existing template. It can be a JObject or well-formed JSON string. Use either the templateLink property or the template property, but not both.
func (o DeploymentPropertiesPtrOutput) Template() pulumi.AnyOutput {
return o.ApplyT(func(v *DeploymentProperties) interface{} {
if v == nil {
return nil
}
return v.Template
}).(pulumi.AnyOutput)
}
// The URI of the template. Use either the templateLink property or the template property, but not both.
func (o DeploymentPropertiesPtrOutput) TemplateLink() TemplateLinkPtrOutput {
return o.ApplyT(func(v *DeploymentProperties) *TemplateLink {
if v == nil {
return nil
}
return v.TemplateLink
}).(TemplateLinkPtrOutput)
}
// Deployment properties with additional details.
type DeploymentPropertiesExtendedResponse struct {
// The correlation ID of the deployment.
CorrelationId string `pulumi:"correlationId"`
// The debug setting of the deployment.
DebugSetting *DebugSettingResponse `pulumi:"debugSetting"`
// The list of deployment dependencies.
Dependencies []DependencyResponse `pulumi:"dependencies"`
// The duration of the template deployment.
Duration string `pulumi:"duration"`
// The deployment mode. Possible values are Incremental and Complete.
Mode *string `pulumi:"mode"`
// The deployment on error behavior.
OnErrorDeployment *OnErrorDeploymentExtendedResponse `pulumi:"onErrorDeployment"`
// Key/value pairs that represent deployment output.
Outputs interface{} `pulumi:"outputs"`
// Deployment parameters. Use only one of Parameters or ParametersLink.
Parameters interface{} `pulumi:"parameters"`
// The URI referencing the parameters. Use only one of Parameters or ParametersLink.
ParametersLink *ParametersLinkResponse `pulumi:"parametersLink"`
// The list of resource providers needed for the deployment.
Providers []ProviderResponse `pulumi:"providers"`
// The state of the provisioning.
ProvisioningState string `pulumi:"provisioningState"`
// The template content. Use only one of Template or TemplateLink.
Template interface{} `pulumi:"template"`
// The URI referencing the template. Use only one of Template or TemplateLink.
TemplateLink *TemplateLinkResponse `pulumi:"templateLink"`
// The timestamp of the template deployment.
Timestamp string `pulumi:"timestamp"`
}
// DeploymentPropertiesExtendedResponseInput is an input type that accepts DeploymentPropertiesExtendedResponseArgs and DeploymentPropertiesExtendedResponseOutput values.
// You can construct a concrete instance of `DeploymentPropertiesExtendedResponseInput` via:
//
// DeploymentPropertiesExtendedResponseArgs{...}
type DeploymentPropertiesExtendedResponseInput interface {
pulumi.Input
ToDeploymentPropertiesExtendedResponseOutput() DeploymentPropertiesExtendedResponseOutput
ToDeploymentPropertiesExtendedResponseOutputWithContext(context.Context) DeploymentPropertiesExtendedResponseOutput
}
// Deployment properties with additional details.
type DeploymentPropertiesExtendedResponseArgs struct {
// The correlation ID of the deployment.
CorrelationId pulumi.StringInput `pulumi:"correlationId"`
// The debug setting of the deployment.
DebugSetting DebugSettingResponsePtrInput `pulumi:"debugSetting"`
// The list of deployment dependencies.
Dependencies DependencyResponseArrayInput `pulumi:"dependencies"`
// The duration of the template deployment.
Duration pulumi.StringInput `pulumi:"duration"`
// The deployment mode. Possible values are Incremental and Complete.
Mode pulumi.StringPtrInput `pulumi:"mode"`
// The deployment on error behavior.
OnErrorDeployment OnErrorDeploymentExtendedResponsePtrInput `pulumi:"onErrorDeployment"`
// Key/value pairs that represent deployment output.
Outputs pulumi.Input `pulumi:"outputs"`
// Deployment parameters. Use only one of Parameters or ParametersLink.
Parameters pulumi.Input `pulumi:"parameters"`
// The URI referencing the parameters. Use only one of Parameters or ParametersLink.
ParametersLink ParametersLinkResponsePtrInput `pulumi:"parametersLink"`
// The list of resource providers needed for the deployment.
Providers ProviderResponseArrayInput `pulumi:"providers"`
// The state of the provisioning.
ProvisioningState pulumi.StringInput `pulumi:"provisioningState"`
// The template content. Use only one of Template or TemplateLink.
Template pulumi.Input `pulumi:"template"`
// The URI referencing the template. Use only one of Template or TemplateLink.
TemplateLink TemplateLinkResponsePtrInput `pulumi:"templateLink"`
// The timestamp of the template deployment.
Timestamp pulumi.StringInput `pulumi:"timestamp"`
}
func (DeploymentPropertiesExtendedResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*DeploymentPropertiesExtendedResponse)(nil)).Elem()
}
func (i DeploymentPropertiesExtendedResponseArgs) ToDeploymentPropertiesExtendedResponseOutput() DeploymentPropertiesExtendedResponseOutput {
return i.ToDeploymentPropertiesExtendedResponseOutputWithContext(context.Background())
}
func (i DeploymentPropertiesExtendedResponseArgs) ToDeploymentPropertiesExtendedResponseOutputWithContext(ctx context.Context) DeploymentPropertiesExtendedResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(DeploymentPropertiesExtendedResponseOutput)
}
func (i DeploymentPropertiesExtendedResponseArgs) ToDeploymentPropertiesExtendedResponsePtrOutput() DeploymentPropertiesExtendedResponsePtrOutput {
return i.ToDeploymentPropertiesExtendedResponsePtrOutputWithContext(context.Background())
}
func (i DeploymentPropertiesExtendedResponseArgs) ToDeploymentPropertiesExtendedResponsePtrOutputWithContext(ctx context.Context) DeploymentPropertiesExtendedResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(DeploymentPropertiesExtendedResponseOutput).ToDeploymentPropertiesExtendedResponsePtrOutputWithContext(ctx)
}
// DeploymentPropertiesExtendedResponsePtrInput is an input type that accepts DeploymentPropertiesExtendedResponseArgs, DeploymentPropertiesExtendedResponsePtr and DeploymentPropertiesExtendedResponsePtrOutput values.
// You can construct a concrete instance of `DeploymentPropertiesExtendedResponsePtrInput` via:
//
// DeploymentPropertiesExtendedResponseArgs{...}
//
// or:
//
// nil
type DeploymentPropertiesExtendedResponsePtrInput interface {
pulumi.Input
ToDeploymentPropertiesExtendedResponsePtrOutput() DeploymentPropertiesExtendedResponsePtrOutput
ToDeploymentPropertiesExtendedResponsePtrOutputWithContext(context.Context) DeploymentPropertiesExtendedResponsePtrOutput
}
type deploymentPropertiesExtendedResponsePtrType DeploymentPropertiesExtendedResponseArgs
func DeploymentPropertiesExtendedResponsePtr(v *DeploymentPropertiesExtendedResponseArgs) DeploymentPropertiesExtendedResponsePtrInput {
return (*deploymentPropertiesExtendedResponsePtrType)(v)
}
func (*deploymentPropertiesExtendedResponsePtrType) ElementType() reflect.Type {
return reflect.TypeOf((**DeploymentPropertiesExtendedResponse)(nil)).Elem()
}
func (i *deploymentPropertiesExtendedResponsePtrType) ToDeploymentPropertiesExtendedResponsePtrOutput() DeploymentPropertiesExtendedResponsePtrOutput {
return i.ToDeploymentPropertiesExtendedResponsePtrOutputWithContext(context.Background())
}
func (i *deploymentPropertiesExtendedResponsePtrType) ToDeploymentPropertiesExtendedResponsePtrOutputWithContext(ctx context.Context) DeploymentPropertiesExtendedResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(DeploymentPropertiesExtendedResponsePtrOutput)
}
// Deployment properties with additional details.
type DeploymentPropertiesExtendedResponseOutput struct{ *pulumi.OutputState }
func (DeploymentPropertiesExtendedResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*DeploymentPropertiesExtendedResponse)(nil)).Elem()
}
func (o DeploymentPropertiesExtendedResponseOutput) ToDeploymentPropertiesExtendedResponseOutput() DeploymentPropertiesExtendedResponseOutput {
return o
}
func (o DeploymentPropertiesExtendedResponseOutput) ToDeploymentPropertiesExtendedResponseOutputWithContext(ctx context.Context) DeploymentPropertiesExtendedResponseOutput {
return o
}
func (o DeploymentPropertiesExtendedResponseOutput) ToDeploymentPropertiesExtendedResponsePtrOutput() DeploymentPropertiesExtendedResponsePtrOutput {
return o.ToDeploymentPropertiesExtendedResponsePtrOutputWithContext(context.Background())
}
func (o DeploymentPropertiesExtendedResponseOutput) ToDeploymentPropertiesExtendedResponsePtrOutputWithContext(ctx context.Context) DeploymentPropertiesExtendedResponsePtrOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) *DeploymentPropertiesExtendedResponse {
return &v
}).(DeploymentPropertiesExtendedResponsePtrOutput)
}
// The correlation ID of the deployment.
func (o DeploymentPropertiesExtendedResponseOutput) CorrelationId() pulumi.StringOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) string { return v.CorrelationId }).(pulumi.StringOutput)
}
// The debug setting of the deployment.
func (o DeploymentPropertiesExtendedResponseOutput) DebugSetting() DebugSettingResponsePtrOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) *DebugSettingResponse { return v.DebugSetting }).(DebugSettingResponsePtrOutput)
}
// The list of deployment dependencies.
func (o DeploymentPropertiesExtendedResponseOutput) Dependencies() DependencyResponseArrayOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) []DependencyResponse { return v.Dependencies }).(DependencyResponseArrayOutput)
}
// The duration of the template deployment.
func (o DeploymentPropertiesExtendedResponseOutput) Duration() pulumi.StringOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) string { return v.Duration }).(pulumi.StringOutput)
}
// The deployment mode. Possible values are Incremental and Complete.
func (o DeploymentPropertiesExtendedResponseOutput) Mode() pulumi.StringPtrOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) *string { return v.Mode }).(pulumi.StringPtrOutput)
}
// The deployment on error behavior.
func (o DeploymentPropertiesExtendedResponseOutput) OnErrorDeployment() OnErrorDeploymentExtendedResponsePtrOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) *OnErrorDeploymentExtendedResponse {
return v.OnErrorDeployment
}).(OnErrorDeploymentExtendedResponsePtrOutput)
}
// Key/value pairs that represent deployment output.
func (o DeploymentPropertiesExtendedResponseOutput) Outputs() pulumi.AnyOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) interface{} { return v.Outputs }).(pulumi.AnyOutput)
}
// Deployment parameters. Use only one of Parameters or ParametersLink.
func (o DeploymentPropertiesExtendedResponseOutput) Parameters() pulumi.AnyOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) interface{} { return v.Parameters }).(pulumi.AnyOutput)
}
// The URI referencing the parameters. Use only one of Parameters or ParametersLink.
func (o DeploymentPropertiesExtendedResponseOutput) ParametersLink() ParametersLinkResponsePtrOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) *ParametersLinkResponse { return v.ParametersLink }).(ParametersLinkResponsePtrOutput)
}
// The list of resource providers needed for the deployment.
func (o DeploymentPropertiesExtendedResponseOutput) Providers() ProviderResponseArrayOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) []ProviderResponse { return v.Providers }).(ProviderResponseArrayOutput)
}
// The state of the provisioning.
func (o DeploymentPropertiesExtendedResponseOutput) ProvisioningState() pulumi.StringOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) string { return v.ProvisioningState }).(pulumi.StringOutput)
}
// The template content. Use only one of Template or TemplateLink.
func (o DeploymentPropertiesExtendedResponseOutput) Template() pulumi.AnyOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) interface{} { return v.Template }).(pulumi.AnyOutput)
}
// The URI referencing the template. Use only one of Template or TemplateLink.
func (o DeploymentPropertiesExtendedResponseOutput) TemplateLink() TemplateLinkResponsePtrOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) *TemplateLinkResponse { return v.TemplateLink }).(TemplateLinkResponsePtrOutput)
}
// The timestamp of the template deployment.
func (o DeploymentPropertiesExtendedResponseOutput) Timestamp() pulumi.StringOutput {
return o.ApplyT(func(v DeploymentPropertiesExtendedResponse) string { return v.Timestamp }).(pulumi.StringOutput)
}
type DeploymentPropertiesExtendedResponsePtrOutput struct{ *pulumi.OutputState }
func (DeploymentPropertiesExtendedResponsePtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**DeploymentPropertiesExtendedResponse)(nil)).Elem()
}
func (o DeploymentPropertiesExtendedResponsePtrOutput) ToDeploymentPropertiesExtendedResponsePtrOutput() DeploymentPropertiesExtendedResponsePtrOutput {
return o
}
func (o DeploymentPropertiesExtendedResponsePtrOutput) ToDeploymentPropertiesExtendedResponsePtrOutputWithContext(ctx context.Context) DeploymentPropertiesExtendedResponsePtrOutput {
return o
}
func (o DeploymentPropertiesExtendedResponsePtrOutput) Elem() DeploymentPropertiesExtendedResponseOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) DeploymentPropertiesExtendedResponse { return *v }).(DeploymentPropertiesExtendedResponseOutput)
}
// The correlation ID of the deployment.
func (o DeploymentPropertiesExtendedResponsePtrOutput) CorrelationId() pulumi.StringPtrOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) *string {
if v == nil {
return nil
}
return &v.CorrelationId
}).(pulumi.StringPtrOutput)
}
// The debug setting of the deployment.
func (o DeploymentPropertiesExtendedResponsePtrOutput) DebugSetting() DebugSettingResponsePtrOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) *DebugSettingResponse {
if v == nil {
return nil
}
return v.DebugSetting
}).(DebugSettingResponsePtrOutput)
}
// The list of deployment dependencies.
func (o DeploymentPropertiesExtendedResponsePtrOutput) Dependencies() DependencyResponseArrayOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) []DependencyResponse {
if v == nil {
return nil
}
return v.Dependencies
}).(DependencyResponseArrayOutput)
}
// The duration of the template deployment.
func (o DeploymentPropertiesExtendedResponsePtrOutput) Duration() pulumi.StringPtrOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) *string {
if v == nil {
return nil
}
return &v.Duration
}).(pulumi.StringPtrOutput)
}
// The deployment mode. Possible values are Incremental and Complete.
func (o DeploymentPropertiesExtendedResponsePtrOutput) Mode() pulumi.StringPtrOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) *string {
if v == nil {
return nil
}
return v.Mode
}).(pulumi.StringPtrOutput)
}
// The deployment on error behavior.
func (o DeploymentPropertiesExtendedResponsePtrOutput) OnErrorDeployment() OnErrorDeploymentExtendedResponsePtrOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) *OnErrorDeploymentExtendedResponse {
if v == nil {
return nil
}
return v.OnErrorDeployment
}).(OnErrorDeploymentExtendedResponsePtrOutput)
}
// Key/value pairs that represent deployment output.
func (o DeploymentPropertiesExtendedResponsePtrOutput) Outputs() pulumi.AnyOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) interface{} {
if v == nil |
return v.Outputs
}).(pulumi.AnyOutput)
}
// Deployment parameters. Use only one of Parameters or ParametersLink.
func (o DeploymentPropertiesExtendedResponsePtrOutput) Parameters() pulumi.AnyOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) interface{} {
if v == nil {
return nil
}
return v.Parameters
}).(pulumi.AnyOutput)
}
// The URI referencing the parameters. Use only one of Parameters or ParametersLink.
func (o DeploymentPropertiesExtendedResponsePtrOutput) ParametersLink() ParametersLinkResponsePtrOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) *ParametersLinkResponse {
if v == nil {
return nil
}
return v.ParametersLink
}).(ParametersLinkResponsePtrOutput)
}
// The list of resource providers needed for the deployment.
func (o DeploymentPropertiesExtendedResponsePtrOutput) Providers() ProviderResponseArrayOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) []ProviderResponse {
if v == nil {
return nil
}
return v.Providers
}).(ProviderResponseArrayOutput)
}
// The state of the provisioning.
func (o DeploymentPropertiesExtendedResponsePtrOutput) ProvisioningState() pulumi.StringPtrOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) *string {
if v == nil {
return nil
}
return &v.ProvisioningState
}).(pulumi.StringPtrOutput)
}
// The template content. Use only one of Template or TemplateLink.
func (o DeploymentPropertiesExtendedResponsePtrOutput) Template() pulumi.AnyOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) interface{} {
if v == nil {
return nil
}
return v.Template
}).(pulumi.AnyOutput)
}
// The URI referencing the template. Use only one of Template or TemplateLink.
func (o DeploymentPropertiesExtendedResponsePtrOutput) TemplateLink() TemplateLinkResponsePtrOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) *TemplateLinkResponse {
if v == nil {
return nil
}
return v.TemplateLink
}).(TemplateLinkResponsePtrOutput)
}
// The timestamp of the template deployment.
func (o DeploymentPropertiesExtendedResponsePtrOutput) Timestamp() pulumi.StringPtrOutput {
return o.ApplyT(func(v *DeploymentPropertiesExtendedResponse) *string {
if v == nil {
return nil
}
return &v.Timestamp
}).(pulumi.StringPtrOutput)
}
// Identity for the resource.
type Identity struct {
// The identity type.
Type *string `pulumi:"type"`
// The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
UserAssignedIdentities map[string]interface{} `pulumi:"userAssignedIdentities"`
}
// IdentityInput is an input type that accepts IdentityArgs and IdentityOutput values.
// You can construct a concrete instance of `IdentityInput` via:
//
// IdentityArgs{...}
type IdentityInput interface {
pulumi.Input
ToIdentityOutput() IdentityOutput
ToIdentityOutputWithContext(context.Context) IdentityOutput
}
// Identity for the resource.
type IdentityArgs struct {
// The identity type.
Type *ResourceIdentityType `pulumi:"type"`
// The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
UserAssignedIdentities pulumi.MapInput `pulumi:"userAssignedIdentities"`
}
func (IdentityArgs) ElementType() reflect.Type {
return reflect.TypeOf((*Identity)(nil)).Elem()
}
func (i IdentityArgs) ToIdentityOutput() IdentityOutput {
return i.ToIdentityOutputWithContext(context.Background())
}
func (i IdentityArgs) ToIdentityOutputWithContext(ctx context.Context) IdentityOutput {
return pulumi.ToOutputWithContext(ctx, i).(IdentityOutput)
}
func (i IdentityArgs) ToIdentityPtrOutput() IdentityPtrOutput {
return i.ToIdentityPtrOutputWithContext(context.Background())
}
func (i IdentityArgs) ToIdentityPtrOutputWithContext(ctx context.Context) IdentityPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(IdentityOutput).ToIdentityPtrOutputWithContext(ctx)
}
// IdentityPtrInput is an input type that accepts IdentityArgs, IdentityPtr and IdentityPtrOutput values.
// You can construct a concrete instance of `IdentityPtrInput` via:
//
// IdentityArgs{...}
//
// or:
//
// nil
type IdentityPtrInput interface {
pulumi.Input
ToIdentityPtrOutput() IdentityPtrOutput
ToIdentityPtrOutputWithContext(context.Context) IdentityPtrOutput
}
type identityPtrType IdentityArgs
func IdentityPtr(v *IdentityArgs) IdentityPtrInput {
return (*identityPtrType)(v)
}
func (*identityPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**Identity)(nil)).Elem()
}
func (i *identityPtrType) ToIdentityPtrOutput() IdentityPtrOutput {
return i.ToIdentityPtrOutputWithContext(context.Background())
}
func (i *identityPtrType) ToIdentityPtrOutputWithContext(ctx context.Context) IdentityPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(IdentityPtrOutput)
}
// Identity for the resource.
type IdentityOutput struct{ *pulumi.OutputState }
func (IdentityOutput) ElementType() reflect.Type {
return reflect.TypeOf((*Identity)(nil)).Elem()
}
func (o IdentityOutput) ToIdentityOutput() IdentityOutput {
return o
}
func (o IdentityOutput) ToIdentityOutputWithContext(ctx context.Context) IdentityOutput {
return o
}
func (o IdentityOutput) ToIdentityPtrOutput() IdentityPtrOutput {
return o.ToIdentityPtrOutputWithContext(context.Background())
}
func (o IdentityOutput) ToIdentityPtrOutputWithContext(ctx context.Context) IdentityPtrOutput {
return o.ApplyT(func(v Identity) *Identity {
return &v
}).(IdentityPtrOutput)
}
// The identity type.
func (o IdentityOutput) Type() pulumi.StringPtrOutput {
return o.ApplyT(func(v Identity) *string { return v.Type }).(pulumi.StringPtrOutput)
}
// The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
func (o IdentityOutput) UserAssignedIdentities() pulumi.MapOutput {
return o.ApplyT(func(v Identity) map[string]interface{} { return v.UserAssignedIdentities }).(pulumi.MapOutput)
}
type IdentityPtrOutput struct{ *pulumi.OutputState }
func (IdentityPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**Identity)(nil)).Elem()
}
func (o IdentityPtrOutput) ToIdentityPtrOutput() IdentityPtrOutput {
return o
}
func (o IdentityPtrOutput) ToIdentityPtrOutputWithContext(ctx context.Context) IdentityPtrOutput {
return o
}
func (o IdentityPtrOutput) Elem() IdentityOutput {
return o.ApplyT(func(v *Identity) Identity { return *v }).(IdentityOutput)
}
// The identity type.
func (o IdentityPtrOutput) Type() pulumi.StringPtrOutput {
return o.ApplyT(func(v *Identity) *string {
if v == nil {
return nil
}
return v.Type
}).(pulumi.StringPtrOutput)
}
// The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
func (o IdentityPtrOutput) UserAssignedIdentities() pulumi.MapOutput {
return o.ApplyT(func(v *Identity) map[string]interface{} {
if v == nil {
return nil
}
return v.UserAssignedIdentities
}).(pulumi.MapOutput)
}
// Identity for the resource.
type IdentityResponse struct {
// The principal ID of resource identity.
PrincipalId string `pulumi:"principalId"`
// The tenant ID of resource.
TenantId string `pulumi:"tenantId"`
// The identity type.
Type *string `pulumi:"type"`
// The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
UserAssignedIdentities map[string]IdentityResponseUserAssignedIdentities `pulumi:"userAssignedIdentities"`
}
// IdentityResponseInput is an input type that accepts IdentityResponseArgs and IdentityResponseOutput values.
// You can construct a concrete instance of `IdentityResponseInput` via:
//
// IdentityResponseArgs{...}
type IdentityResponseInput interface {
pulumi.Input
ToIdentityResponseOutput() IdentityResponseOutput
ToIdentityResponseOutputWithContext(context.Context) IdentityResponseOutput
}
// Identity for the resource.
type IdentityResponseArgs struct {
// The principal ID of resource identity.
PrincipalId pulumi.StringInput `pulumi:"principalId"`
// The tenant ID of resource.
TenantId pulumi.StringInput `pulumi:"tenantId"`
// The identity type.
Type pulumi.StringPtrInput `pulumi:"type"`
// The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
UserAssignedIdentities IdentityResponseUserAssignedIdentitiesMapInput `pulumi:"userAssignedIdentities"`
}
func (IdentityResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*IdentityResponse)(nil)).Elem()
}
func (i IdentityResponseArgs) ToIdentityResponseOutput() IdentityResponseOutput {
return i.ToIdentityResponseOutputWithContext(context.Background())
}
func (i IdentityResponseArgs) ToIdentityResponseOutputWithContext(ctx context.Context) IdentityResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(IdentityResponseOutput)
}
func (i IdentityResponseArgs) ToIdentityResponsePtrOutput() IdentityResponsePtrOutput {
return i.ToIdentityResponsePtrOutputWithContext(context.Background())
}
func (i IdentityResponseArgs) ToIdentityResponsePtrOutputWithContext(ctx context.Context) IdentityResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(IdentityResponseOutput).ToIdentityResponsePtrOutputWithContext(ctx)
}
// IdentityResponsePtrInput is an input type that accepts IdentityResponseArgs, IdentityResponsePtr and IdentityResponsePtrOutput values.
// You can construct a concrete instance of `IdentityResponsePtrInput` via:
//
// IdentityResponseArgs{...}
//
// or:
//
// nil
type IdentityResponsePtrInput interface {
pulumi.Input
ToIdentityResponsePtrOutput() IdentityResponsePtrOutput
ToIdentityResponsePtrOutputWithContext(context.Context) IdentityResponsePtrOutput
}
type identityResponsePtrType IdentityResponseArgs
func IdentityResponsePtr(v *IdentityResponseArgs) IdentityResponsePtrInput {
return (*identityResponsePtrType)(v)
}
func (*identityResponsePtrType) ElementType() reflect.Type {
return reflect.TypeOf((**IdentityResponse)(nil)).Elem()
}
func (i *identityResponsePtrType) ToIdentityResponsePtrOutput() IdentityResponsePtrOutput {
return i.ToIdentityResponsePtrOutputWithContext(context.Background())
}
func (i *identityResponsePtrType) ToIdentityResponsePtrOutputWithContext(ctx context.Context) IdentityResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(IdentityResponsePtrOutput)
}
// Identity for the resource.
type IdentityResponseOutput struct{ *pulumi.OutputState }
func (IdentityResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*IdentityResponse)(nil)).Elem()
}
func (o IdentityResponseOutput) ToIdentityResponseOutput() IdentityResponseOutput {
return o
}
func (o IdentityResponseOutput) ToIdentityResponseOutputWithContext(ctx context.Context) IdentityResponseOutput {
return o
}
func (o IdentityResponseOutput) ToIdentityResponsePtrOutput() IdentityResponsePtrOutput {
return o.ToIdentityResponsePtrOutputWithContext(context.Background())
}
func (o IdentityResponseOutput) ToIdentityResponsePtrOutputWithContext(ctx context.Context) IdentityResponsePtrOutput {
return o.ApplyT(func(v IdentityResponse) *IdentityResponse {
return &v
}).(IdentityResponsePtrOutput)
}
// The principal ID of resource identity.
func (o IdentityResponseOutput) PrincipalId() pulumi.StringOutput {
return o.ApplyT(func(v IdentityResponse) string { return v.PrincipalId }).(pulumi.StringOutput)
}
// The tenant ID of resource.
func (o IdentityResponseOutput) TenantId() pulumi.StringOutput {
return o.ApplyT(func(v IdentityResponse) string { return v.TenantId }).(pulumi.StringOutput)
}
// The identity type.
func (o IdentityResponseOutput) Type() pulumi.StringPtrOutput {
return o.ApplyT(func(v IdentityResponse) *string { return v.Type }).(pulumi.StringPtrOutput)
}
// The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
func (o IdentityResponseOutput) UserAssignedIdentities() IdentityResponseUserAssignedIdentitiesMapOutput {
return o.ApplyT(func(v IdentityResponse) map[string]IdentityResponseUserAssignedIdentities {
return v.UserAssignedIdentities
}).(IdentityResponseUserAssignedIdentitiesMapOutput)
}
type IdentityResponsePtrOutput struct{ *pulumi.OutputState }
func (IdentityResponsePtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**IdentityResponse)(nil)).Elem()
}
func (o IdentityResponsePtrOutput) ToIdentityResponsePtrOutput() IdentityResponsePtrOutput {
return o
}
func (o IdentityResponsePtrOutput) ToIdentityResponsePtrOutputWithContext(ctx context.Context) IdentityResponsePtrOutput {
return o
}
func (o IdentityResponsePtrOutput) Elem() IdentityResponseOutput {
return o.ApplyT(func(v *IdentityResponse) IdentityResponse { return *v }).(IdentityResponseOutput)
}
// The principal ID of resource identity.
func (o IdentityResponsePtrOutput) PrincipalId() pulumi.StringPtrOutput {
return o.ApplyT(func(v *IdentityResponse) *string {
if v == nil {
return nil
}
return &v.PrincipalId
}).(pulumi.StringPtrOutput)
}
// The tenant ID of resource.
func (o IdentityResponsePtrOutput) TenantId() pulumi.StringPtrOutput {
return o.ApplyT(func(v *IdentityResponse) *string {
if v == nil {
return nil
}
return &v.TenantId
}).(pulumi.StringPtrOutput)
}
// The identity type.
func (o IdentityResponsePtrOutput) Type() pulumi.StringPtrOutput {
return o.ApplyT(func(v *IdentityResponse) *string {
if v == nil {
return nil
}
return v.Type
}).(pulumi.StringPtrOutput)
}
// The list of user identities associated with the resource. The user identity dictionary key references will be ARM resource ids in the form: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/{identityName}'.
func (o IdentityResponsePtrOutput) UserAssignedIdentities() IdentityResponseUserAssignedIdentitiesMapOutput {
return o.ApplyT(func(v *IdentityResponse) map[string]IdentityResponseUserAssignedIdentities {
if v == nil {
return nil
}
return v.UserAssignedIdentities
}).(IdentityResponseUserAssignedIdentitiesMapOutput)
}
type IdentityResponseUserAssignedIdentities struct {
// The client id of user assigned identity.
ClientId string `pulumi:"clientId"`
// The principal id of user assigned identity.
PrincipalId string `pulumi:"principalId"`
}
// IdentityResponseUserAssignedIdentitiesInput is an input type that accepts IdentityResponseUserAssignedIdentitiesArgs and IdentityResponseUserAssignedIdentitiesOutput values.
// You can construct a concrete instance of `IdentityResponseUserAssignedIdentitiesInput` via:
//
// IdentityResponseUserAssignedIdentitiesArgs{...}
type IdentityResponseUserAssignedIdentitiesInput interface {
pulumi.Input
ToIdentityResponseUserAssignedIdentitiesOutput() IdentityResponseUserAssignedIdentitiesOutput
ToIdentityResponseUserAssignedIdentitiesOutputWithContext(context.Context) IdentityResponseUserAssignedIdentitiesOutput
}
type IdentityResponseUserAssignedIdentitiesArgs struct {
// The client id of user assigned identity.
ClientId pulumi.StringInput `pulumi:"clientId"`
// The principal id of user assigned identity.
PrincipalId pulumi.StringInput `pulumi:"principalId"`
}
func (IdentityResponseUserAssignedIdentitiesArgs) ElementType() reflect.Type {
return reflect.TypeOf((*IdentityResponseUserAssignedIdentities)(nil)).Elem()
}
func (i IdentityResponseUserAssignedIdentitiesArgs) ToIdentityResponseUserAssignedIdentitiesOutput() IdentityResponseUserAssignedIdentitiesOutput {
return i.ToIdentityResponseUserAssignedIdentitiesOutputWithContext(context.Background())
}
func (i IdentityResponseUserAssignedIdentitiesArgs) ToIdentityResponseUserAssignedIdentitiesOutputWithContext(ctx context.Context) IdentityResponseUserAssignedIdentitiesOutput {
return pulumi.ToOutputWithContext(ctx, i).(IdentityResponseUserAssignedIdentitiesOutput)
}
// IdentityResponseUserAssignedIdentitiesMapInput is an input type that accepts IdentityResponseUserAssignedIdentitiesMap and IdentityResponseUserAssignedIdentitiesMapOutput values.
// You can construct a concrete instance of `IdentityResponseUserAssignedIdentitiesMapInput` via:
//
// IdentityResponseUserAssignedIdentitiesMap{ "key": IdentityResponseUserAssignedIdentitiesArgs{...} }
type IdentityResponseUserAssignedIdentitiesMapInput interface {
pulumi.Input
ToIdentityResponseUserAssignedIdentitiesMapOutput() IdentityResponseUserAssignedIdentitiesMapOutput
ToIdentityResponseUserAssignedIdentitiesMapOutputWithContext(context.Context) IdentityResponseUserAssignedIdentitiesMapOutput
}
type IdentityResponseUserAssignedIdentitiesMap map[string]IdentityResponseUserAssignedIdentitiesInput
func (IdentityResponseUserAssignedIdentitiesMap) ElementType() reflect.Type {
return reflect.TypeOf((*map[string]IdentityResponseUserAssignedIdentities)(nil)).Elem()
}
func (i IdentityResponseUserAssignedIdentitiesMap) ToIdentityResponseUserAssignedIdentitiesMapOutput() IdentityResponseUserAssignedIdentitiesMapOutput {
return i.ToIdentityResponseUserAssignedIdentitiesMapOutputWithContext(context.Background())
}
func (i IdentityResponseUserAssignedIdentitiesMap) ToIdentityResponseUserAssignedIdentitiesMapOutputWithContext(ctx context.Context) IdentityResponseUserAssignedIdentitiesMapOutput {
return pulumi.ToOutputWithContext(ctx, i).(IdentityResponseUserAssignedIdentitiesMapOutput)
}
type IdentityResponseUserAssignedIdentitiesOutput struct{ *pulumi.OutputState }
func (IdentityResponseUserAssignedIdentitiesOutput) ElementType() reflect.Type {
return reflect.TypeOf((*IdentityResponseUserAssignedIdentities)(nil)).Elem()
}
func (o IdentityResponseUserAssignedIdentitiesOutput) ToIdentityResponseUserAssignedIdentitiesOutput() IdentityResponseUserAssignedIdentitiesOutput {
return o
}
func (o IdentityResponseUserAssignedIdentitiesOutput) ToIdentityResponseUserAssignedIdentitiesOutputWithContext(ctx context.Context) IdentityResponseUserAssignedIdentitiesOutput {
return o
}
// The client id of user assigned identity.
func (o IdentityResponseUserAssignedIdentitiesOutput) ClientId() pulumi.StringOutput {
return o.ApplyT(func(v IdentityResponseUserAssignedIdentities) string { return v.ClientId }).(pulumi.StringOutput)
}
// The principal id of user assigned identity.
func (o IdentityResponseUserAssignedIdentitiesOutput) PrincipalId() pulumi.StringOutput {
return o.ApplyT(func(v IdentityResponseUserAssignedIdentities) string { return v.PrincipalId }).(pulumi.StringOutput)
}
type IdentityResponseUserAssignedIdentitiesMapOutput struct{ *pulumi.OutputState }
func (IdentityResponseUserAssignedIdentitiesMapOutput) ElementType() reflect.Type {
return reflect.TypeOf((*map[string]IdentityResponseUserAssignedIdentities)(nil)).Elem()
}
func (o IdentityResponseUserAssignedIdentitiesMapOutput) ToIdentityResponseUserAssignedIdentitiesMapOutput() IdentityResponseUserAssignedIdentitiesMapOutput {
return o
}
func (o IdentityResponseUserAssignedIdentitiesMapOutput) ToIdentityResponseUserAssignedIdentitiesMapOutputWithContext(ctx context.Context) IdentityResponseUserAssignedIdentitiesMapOutput {
return o
}
func (o IdentityResponseUserAssignedIdentitiesMapOutput) MapIndex(k pulumi.StringInput) IdentityResponseUserAssignedIdentitiesOutput {
return pulumi.All(o, k).ApplyT(func(vs []interface{}) IdentityResponseUserAssignedIdentities {
return vs[0].(map[string]IdentityResponseUserAssignedIdentities)[vs[1].(string)]
}).(IdentityResponseUserAssignedIdentitiesOutput)
}
// Deployment on error behavior.
type OnErrorDeployment struct {
// The deployment to be used on error case.
DeploymentName *string `pulumi:"deploymentName"`
// The deployment on error behavior type. Possible values are LastSuccessful and SpecificDeployment.
Type *string `pulumi:"type"`
}
// OnErrorDeploymentInput is an input type that accepts OnErrorDeploymentArgs and OnErrorDeploymentOutput values.
// You can construct a concrete instance of `OnErrorDeploymentInput` via:
//
// OnErrorDeploymentArgs{...}
type OnErrorDeploymentInput interface {
pulumi.Input
ToOnErrorDeploymentOutput() OnErrorDeploymentOutput
ToOnErrorDeploymentOutputWithContext(context.Context) OnErrorDeploymentOutput
}
// Deployment on error behavior.
type OnErrorDeploymentArgs struct {
// The deployment to be used on error case.
DeploymentName pulumi.StringPtrInput `pulumi:"deploymentName"`
// The deployment on error behavior type. Possible values are LastSuccessful and SpecificDeployment.
Type *OnErrorDeploymentType `pulumi:"type"`
}
func (OnErrorDeploymentArgs) ElementType() reflect.Type {
return reflect.TypeOf((*OnErrorDeployment)(nil)).Elem()
}
func (i OnErrorDeploymentArgs) ToOnErrorDeploymentOutput() OnErrorDeploymentOutput {
return i.ToOnErrorDeploymentOutputWithContext(context.Background())
}
func (i OnErrorDeploymentArgs) ToOnErrorDeploymentOutputWithContext(ctx context.Context) OnErrorDeploymentOutput {
return pulumi.ToOutputWithContext(ctx, i).(OnErrorDeploymentOutput)
}
func (i OnErrorDeploymentArgs) ToOnErrorDeploymentPtrOutput() OnErrorDeploymentPtrOutput {
return i.ToOnErrorDeploymentPtrOutputWithContext(context.Background())
}
func (i OnErrorDeploymentArgs) ToOnErrorDeploymentPtrOutputWithContext(ctx context.Context) OnErrorDeploymentPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(OnErrorDeploymentOutput).ToOnErrorDeploymentPtrOutputWithContext(ctx)
}
// OnErrorDeploymentPtrInput is an input type that accepts OnErrorDeploymentArgs, OnErrorDeploymentPtr and OnErrorDeploymentPtrOutput values.
// You can construct a concrete instance of `OnErrorDeploymentPtrInput` via:
//
// OnErrorDeploymentArgs{...}
//
// or:
//
// nil
type OnErrorDeploymentPtrInput interface {
pulumi.Input
ToOnErrorDeploymentPtrOutput() OnErrorDeploymentPtrOutput
ToOnErrorDeploymentPtrOutputWithContext(context.Context) OnErrorDeploymentPtrOutput
}
type onErrorDeploymentPtrType OnErrorDeploymentArgs
func OnErrorDeploymentPtr(v *OnErrorDeploymentArgs) OnErrorDeploymentPtrInput {
return (*onErrorDeploymentPtrType)(v)
}
func (*onErrorDeploymentPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**OnErrorDeployment)(nil)).Elem()
}
func (i *onErrorDeploymentPtrType) ToOnErrorDeploymentPtrOutput() OnErrorDeploymentPtrOutput {
return i.ToOnErrorDeploymentPtrOutputWithContext(context.Background())
}
func (i *onErrorDeploymentPtrType) ToOnErrorDeploymentPtrOutputWithContext(ctx context.Context) OnErrorDeploymentPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(OnErrorDeploymentPtrOutput)
}
// Deployment on error behavior.
type OnErrorDeploymentOutput struct{ *pulumi.OutputState }
func (OnErrorDeploymentOutput) ElementType() reflect.Type {
return reflect.TypeOf((*OnErrorDeployment)(nil)).Elem()
}
func (o OnErrorDeploymentOutput) ToOnErrorDeploymentOutput() OnErrorDeploymentOutput {
return o
}
func (o OnErrorDeploymentOutput) ToOnErrorDeploymentOutputWithContext(ctx context.Context) OnErrorDeploymentOutput {
return o
}
func (o OnErrorDeploymentOutput) ToOnErrorDeploymentPtrOutput() OnErrorDeploymentPtrOutput {
return o.ToOnErrorDeploymentPtrOutputWithContext(context.Background())
}
func (o OnErrorDeploymentOutput) ToOnErrorDeploymentPtrOutputWithContext(ctx context.Context) OnErrorDeploymentPtrOutput {
return o.ApplyT(func(v OnErrorDeployment) *OnErrorDeployment {
return &v
}).(OnErrorDeploymentPtrOutput)
}
// The deployment to be used on error case.
func (o OnErrorDeploymentOutput) DeploymentName() pulumi.StringPtrOutput {
return o.ApplyT(func(v OnErrorDeployment) *string { return v.DeploymentName }).(pulumi.StringPtrOutput)
}
// The deployment on error behavior type. Possible values are LastSuccessful and SpecificDeployment.
func (o OnErrorDeploymentOutput) Type() pulumi.StringPtrOutput {
return o.ApplyT(func(v OnErrorDeployment) *string { return v.Type }).(pulumi.StringPtrOutput)
}
type OnErrorDeploymentPtrOutput struct{ *pulumi.OutputState }
func (OnErrorDeploymentPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**OnErrorDeployment)(nil)).Elem()
}
func (o OnErrorDeploymentPtrOutput) ToOnErrorDeploymentPtrOutput() OnErrorDeploymentPtrOutput {
return o
}
func (o OnErrorDeploymentPtrOutput) ToOnErrorDeploymentPtrOutputWithContext(ctx context.Context) OnErrorDeploymentPtrOutput {
return o
}
func (o OnErrorDeploymentPtrOutput) Elem() OnErrorDeploymentOutput {
return o.ApplyT(func(v *OnErrorDeployment) OnErrorDeployment { return *v }).(OnErrorDeploymentOutput)
}
// The deployment to be used on error case.
func (o OnErrorDeploymentPtrOutput) DeploymentName() pulumi.StringPtrOutput {
return o.ApplyT(func(v *OnErrorDeployment) *string {
if v == nil {
return nil
}
return v.DeploymentName
}).(pulumi.StringPtrOutput)
}
// The deployment on error behavior type. Possible values are LastSuccessful and SpecificDeployment.
func (o OnErrorDeploymentPtrOutput) Type() pulumi.StringPtrOutput {
return o.ApplyT(func(v *OnErrorDeployment) *string {
if v == nil {
return nil
}
return v.Type
}).(pulumi.StringPtrOutput)
}
// Deployment on error behavior with additional details.
type OnErrorDeploymentExtendedResponse struct {
// The deployment to be used on error case.
DeploymentName *string `pulumi:"deploymentName"`
// The state of the provisioning for the on error deployment.
ProvisioningState string `pulumi:"provisioningState"`
// The deployment on error behavior type. Possible values are LastSuccessful and SpecificDeployment.
Type *string `pulumi:"type"`
}
// OnErrorDeploymentExtendedResponseInput is an input type that accepts OnErrorDeploymentExtendedResponseArgs and OnErrorDeploymentExtendedResponseOutput values.
// You can construct a concrete instance of `OnErrorDeploymentExtendedResponseInput` via:
//
// OnErrorDeploymentExtendedResponseArgs{...}
type OnErrorDeploymentExtendedResponseInput interface {
pulumi.Input
ToOnErrorDeploymentExtendedResponseOutput() OnErrorDeploymentExtendedResponseOutput
ToOnErrorDeploymentExtendedResponseOutputWithContext(context.Context) OnErrorDeploymentExtendedResponseOutput
}
// Deployment on error behavior with additional details.
type OnErrorDeploymentExtendedResponseArgs struct {
// The deployment to be used on error case.
DeploymentName pulumi.StringPtrInput `pulumi:"deploymentName"`
// The state of the provisioning for the on error deployment.
ProvisioningState pulumi.StringInput `pulumi:"provisioningState"`
// The deployment on error behavior type. Possible values are LastSuccessful and SpecificDeployment.
Type pulumi.StringPtrInput `pulumi:"type"`
}
func (OnErrorDeploymentExtendedResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*OnErrorDeploymentExtendedResponse)(nil)).Elem()
}
func (i OnErrorDeploymentExtendedResponseArgs) ToOnErrorDeploymentExtendedResponseOutput() OnErrorDeploymentExtendedResponseOutput {
return i.ToOnErrorDeploymentExtendedResponseOutputWithContext(context.Background())
}
func (i OnErrorDeploymentExtendedResponseArgs) ToOnErrorDeploymentExtendedResponseOutputWithContext(ctx context.Context) OnErrorDeploymentExtendedResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(OnErrorDeploymentExtendedResponseOutput)
}
func (i OnErrorDeploymentExtendedResponseArgs) ToOnErrorDeploymentExtendedResponsePtrOutput() OnErrorDeploymentExtendedResponsePtrOutput {
return i.ToOnErrorDeploymentExtendedResponsePtrOutputWithContext(context.Background())
}
func (i OnErrorDeploymentExtendedResponseArgs) ToOnErrorDeploymentExtendedResponsePtrOutputWithContext(ctx context.Context) OnErrorDeploymentExtendedResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(OnErrorDeploymentExtendedResponseOutput).ToOnErrorDeploymentExtendedResponsePtrOutputWithContext(ctx)
}
// OnErrorDeploymentExtendedResponsePtrInput is an input type that accepts OnErrorDeploymentExtendedResponseArgs, OnErrorDeploymentExtendedResponsePtr and OnErrorDeploymentExtendedResponsePtrOutput values.
// You can construct a concrete instance of `OnErrorDeploymentExtendedResponsePtrInput` via:
//
// OnErrorDeploymentExtendedResponseArgs{...}
//
// or:
//
// nil
type OnErrorDeploymentExtendedResponsePtrInput interface {
pulumi.Input
ToOnErrorDeploymentExtendedResponsePtrOutput() OnErrorDeploymentExtendedResponsePtrOutput
ToOnErrorDeploymentExtendedResponsePtrOutputWithContext(context.Context) OnErrorDeploymentExtendedResponsePtrOutput
}
type onErrorDeploymentExtendedResponsePtrType OnErrorDeploymentExtendedResponseArgs
func OnErrorDeploymentExtendedResponsePtr(v *OnErrorDeploymentExtendedResponseArgs) OnErrorDeploymentExtendedResponsePtrInput {
return (*onErrorDeploymentExtendedResponsePtrType)(v)
}
func (*onErrorDeploymentExtendedResponsePtrType) ElementType() reflect.Type {
return reflect.TypeOf((**OnErrorDeploymentExtendedResponse)(nil)).Elem()
}
func (i *onErrorDeploymentExtendedResponsePtrType) ToOnErrorDeploymentExtendedResponsePtrOutput() OnErrorDeploymentExtendedResponsePtrOutput {
return i.ToOnErrorDeploymentExtendedResponsePtrOutputWithContext(context.Background())
}
func (i *onErrorDeploymentExtendedResponsePtrType) ToOnErrorDeploymentExtendedResponsePtrOutputWithContext(ctx context.Context) OnErrorDeploymentExtendedResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(OnErrorDeploymentExtendedResponsePtrOutput)
}
// Deployment on error behavior with additional details.
type OnErrorDeploymentExtendedResponseOutput struct{ *pulumi.OutputState }
func (OnErrorDeploymentExtendedResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*OnErrorDeploymentExtendedResponse)(nil)).Elem()
}
func (o OnErrorDeploymentExtendedResponseOutput) ToOnErrorDeploymentExtendedResponseOutput() OnErrorDeploymentExtendedResponseOutput {
return o
}
func (o OnErrorDeploymentExtendedResponseOutput) ToOnErrorDeploymentExtendedResponseOutputWithContext(ctx context.Context) OnErrorDeploymentExtendedResponseOutput {
return o
}
func (o OnErrorDeploymentExtendedResponseOutput) ToOnErrorDeploymentExtendedResponsePtrOutput() OnErrorDeploymentExtendedResponsePtrOutput {
return o.ToOnErrorDeploymentExtendedResponsePtrOutputWithContext(context.Background())
}
func (o OnErrorDeploymentExtendedResponseOutput) ToOnErrorDeploymentExtendedResponsePtrOutputWithContext(ctx context.Context) OnErrorDeploymentExtendedResponsePtrOutput {
return o.ApplyT(func(v OnErrorDeploymentExtendedResponse) *OnErrorDeploymentExtendedResponse {
return &v
}).(OnErrorDeploymentExtendedResponsePtrOutput)
}
// The deployment to be used on error case.
func (o OnErrorDeploymentExtendedResponseOutput) DeploymentName() pulumi.StringPtrOutput {
return o.ApplyT(func(v OnErrorDeploymentExtendedResponse) *string { return v.DeploymentName }).(pulumi.StringPtrOutput)
}
// The state of the provisioning for the on error deployment.
func (o OnErrorDeploymentExtendedResponseOutput) ProvisioningState() pulumi.StringOutput {
return o.ApplyT(func(v OnErrorDeploymentExtendedResponse) string { return v.ProvisioningState }).(pulumi.StringOutput)
}
// The deployment on error behavior type. Possible values are LastSuccessful and SpecificDeployment.
func (o OnErrorDeploymentExtendedResponseOutput) Type() pulumi.StringPtrOutput {
return o.ApplyT(func(v OnErrorDeploymentExtendedResponse) *string { return v.Type }).(pulumi.StringPtrOutput)
}
type OnErrorDeploymentExtendedResponsePtrOutput struct{ *pulumi.OutputState }
func (OnErrorDeploymentExtendedResponsePtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**OnErrorDeploymentExtendedResponse)(nil)).Elem()
}
func (o OnErrorDeploymentExtendedResponsePtrOutput) ToOnErrorDeploymentExtendedResponsePtrOutput() OnErrorDeploymentExtendedResponsePtrOutput {
return o
}
func (o OnErrorDeploymentExtendedResponsePtrOutput) ToOnErrorDeploymentExtendedResponsePtrOutputWithContext(ctx context.Context) OnErrorDeploymentExtendedResponsePtrOutput {
return o
}
func (o OnErrorDeploymentExtendedResponsePtrOutput) Elem() OnErrorDeploymentExtendedResponseOutput {
return o.ApplyT(func(v *OnErrorDeploymentExtendedResponse) OnErrorDeploymentExtendedResponse { return *v }).(OnErrorDeploymentExtendedResponseOutput)
}
// The deployment to be used on error case.
func (o OnErrorDeploymentExtendedResponsePtrOutput) DeploymentName() pulumi.StringPtrOutput {
return o.ApplyT(func(v *OnErrorDeploymentExtendedResponse) *string {
if v == nil {
return nil
}
return v.DeploymentName
}).(pulumi.StringPtrOutput)
}
// The state of the provisioning for the on error deployment.
func (o OnErrorDeploymentExtendedResponsePtrOutput) ProvisioningState() pulumi.StringPtrOutput {
return o.ApplyT(func(v *OnErrorDeploymentExtendedResponse) *string {
if v == nil {
return nil
}
return &v.ProvisioningState
}).(pulumi.StringPtrOutput)
}
// The deployment on error behavior type. Possible values are LastSuccessful and SpecificDeployment.
func (o OnErrorDeploymentExtendedResponsePtrOutput) Type() pulumi.StringPtrOutput {
return o.ApplyT(func(v *OnErrorDeploymentExtendedResponse) *string {
if v == nil {
return nil
}
return v.Type
}).(pulumi.StringPtrOutput)
}
// Entity representing the reference to the deployment parameters.
type ParametersLink struct {
// If included, must match the ContentVersion in the template.
ContentVersion *string `pulumi:"contentVersion"`
// The URI of the parameters file.
Uri string `pulumi:"uri"`
}
// ParametersLinkInput is an input type that accepts ParametersLinkArgs and ParametersLinkOutput values.
// You can construct a concrete instance of `ParametersLinkInput` via:
//
// ParametersLinkArgs{...}
type ParametersLinkInput interface {
pulumi.Input
ToParametersLinkOutput() ParametersLinkOutput
ToParametersLinkOutputWithContext(context.Context) ParametersLinkOutput
}
// Entity representing the reference to the deployment parameters.
type ParametersLinkArgs struct {
// If included, must match the ContentVersion in the template.
ContentVersion pulumi.StringPtrInput `pulumi:"contentVersion"`
// The URI of the parameters file.
Uri pulumi.StringInput `pulumi:"uri"`
}
func (ParametersLinkArgs) ElementType() reflect.Type {
return reflect.TypeOf((*ParametersLink)(nil)).Elem()
}
func (i ParametersLinkArgs) ToParametersLinkOutput() ParametersLinkOutput {
return i.ToParametersLinkOutputWithContext(context.Background())
}
func (i ParametersLinkArgs) ToParametersLinkOutputWithContext(ctx context.Context) ParametersLinkOutput {
return pulumi.ToOutputWithContext(ctx, i).(ParametersLinkOutput)
}
func (i ParametersLinkArgs) ToParametersLinkPtrOutput() ParametersLinkPtrOutput {
return i.ToParametersLinkPtrOutputWithContext(context.Background())
}
func (i ParametersLinkArgs) ToParametersLinkPtrOutputWithContext(ctx context.Context) ParametersLinkPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ParametersLinkOutput).ToParametersLinkPtrOutputWithContext(ctx)
}
// ParametersLinkPtrInput is an input type that accepts ParametersLinkArgs, ParametersLinkPtr and ParametersLinkPtrOutput values.
// You can construct a concrete instance of `ParametersLinkPtrInput` via:
//
// ParametersLinkArgs{...}
//
// or:
//
// nil
type ParametersLinkPtrInput interface {
pulumi.Input
ToParametersLinkPtrOutput() ParametersLinkPtrOutput
ToParametersLinkPtrOutputWithContext(context.Context) ParametersLinkPtrOutput
}
type parametersLinkPtrType ParametersLinkArgs
func ParametersLinkPtr(v *ParametersLinkArgs) ParametersLinkPtrInput {
return (*parametersLinkPtrType)(v)
}
func (*parametersLinkPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**ParametersLink)(nil)).Elem()
}
func (i *parametersLinkPtrType) ToParametersLinkPtrOutput() ParametersLinkPtrOutput {
return i.ToParametersLinkPtrOutputWithContext(context.Background())
}
func (i *parametersLinkPtrType) ToParametersLinkPtrOutputWithContext(ctx context.Context) ParametersLinkPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ParametersLinkPtrOutput)
}
// Entity representing the reference to the deployment parameters.
type ParametersLinkOutput struct{ *pulumi.OutputState }
func (ParametersLinkOutput) ElementType() reflect.Type {
return reflect.TypeOf((*ParametersLink)(nil)).Elem()
}
func (o ParametersLinkOutput) ToParametersLinkOutput() ParametersLinkOutput {
return o
}
func (o ParametersLinkOutput) ToParametersLinkOutputWithContext(ctx context.Context) ParametersLinkOutput {
return o
}
func (o ParametersLinkOutput) ToParametersLinkPtrOutput() ParametersLinkPtrOutput {
return o.ToParametersLinkPtrOutputWithContext(context.Background())
}
func (o ParametersLinkOutput) ToParametersLinkPtrOutputWithContext(ctx context.Context) ParametersLinkPtrOutput {
return o.ApplyT(func(v ParametersLink) *ParametersLink {
return &v
}).(ParametersLinkPtrOutput)
}
// If included, must match the ContentVersion in the template.
func (o ParametersLinkOutput) ContentVersion() pulumi.StringPtrOutput {
return o.ApplyT(func(v ParametersLink) *string { return v.ContentVersion }).(pulumi.StringPtrOutput)
}
// The URI of the parameters file.
func (o ParametersLinkOutput) Uri() pulumi.StringOutput {
return o.ApplyT(func(v ParametersLink) string { return v.Uri }).(pulumi.StringOutput)
}
type ParametersLinkPtrOutput struct{ *pulumi.OutputState }
func (ParametersLinkPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**ParametersLink)(nil)).Elem()
}
func (o ParametersLinkPtrOutput) ToParametersLinkPtrOutput() ParametersLinkPtrOutput {
return o
}
func (o ParametersLinkPtrOutput) ToParametersLinkPtrOutputWithContext(ctx context.Context) ParametersLinkPtrOutput {
return o
}
func (o ParametersLinkPtrOutput) Elem() ParametersLinkOutput {
return o.ApplyT(func(v *ParametersLink) ParametersLink { return *v }).(ParametersLinkOutput)
}
// If included, must match the ContentVersion in the template.
func (o ParametersLinkPtrOutput) ContentVersion() pulumi.StringPtrOutput {
return o.ApplyT(func(v *ParametersLink) *string {
if v == nil {
return nil
}
return v.ContentVersion
}).(pulumi.StringPtrOutput)
}
// The URI of the parameters file.
func (o ParametersLinkPtrOutput) Uri() pulumi.StringPtrOutput {
return o.ApplyT(func(v *ParametersLink) *string {
if v == nil {
return nil
}
return &v.Uri
}).(pulumi.StringPtrOutput)
}
// Entity representing the reference to the deployment parameters.
type ParametersLinkResponse struct {
// If included, must match the ContentVersion in the template.
ContentVersion *string `pulumi:"contentVersion"`
// The URI of the parameters file.
Uri string `pulumi:"uri"`
}
// ParametersLinkResponseInput is an input type that accepts ParametersLinkResponseArgs and ParametersLinkResponseOutput values.
// You can construct a concrete instance of `ParametersLinkResponseInput` via:
//
// ParametersLinkResponseArgs{...}
type ParametersLinkResponseInput interface {
pulumi.Input
ToParametersLinkResponseOutput() ParametersLinkResponseOutput
ToParametersLinkResponseOutputWithContext(context.Context) ParametersLinkResponseOutput
}
// Entity representing the reference to the deployment parameters.
type ParametersLinkResponseArgs struct {
// If included, must match the ContentVersion in the template.
ContentVersion pulumi.StringPtrInput `pulumi:"contentVersion"`
// The URI of the parameters file.
Uri pulumi.StringInput `pulumi:"uri"`
}
func (ParametersLinkResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*ParametersLinkResponse)(nil)).Elem()
}
func (i ParametersLinkResponseArgs) ToParametersLinkResponseOutput() ParametersLinkResponseOutput {
return i.ToParametersLinkResponseOutputWithContext(context.Background())
}
func (i ParametersLinkResponseArgs) ToParametersLinkResponseOutputWithContext(ctx context.Context) ParametersLinkResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(ParametersLinkResponseOutput)
}
func (i ParametersLinkResponseArgs) ToParametersLinkResponsePtrOutput() ParametersLinkResponsePtrOutput {
return i.ToParametersLinkResponsePtrOutputWithContext(context.Background())
}
func (i ParametersLinkResponseArgs) ToParametersLinkResponsePtrOutputWithContext(ctx context.Context) ParametersLinkResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ParametersLinkResponseOutput).ToParametersLinkResponsePtrOutputWithContext(ctx)
}
// ParametersLinkResponsePtrInput is an input type that accepts ParametersLinkResponseArgs, ParametersLinkResponsePtr and ParametersLinkResponsePtrOutput values.
// You can construct a concrete instance of `ParametersLinkResponsePtrInput` via:
//
// ParametersLinkResponseArgs{...}
//
// or:
//
// nil
type ParametersLinkResponsePtrInput interface {
pulumi.Input
ToParametersLinkResponsePtrOutput() ParametersLinkResponsePtrOutput
ToParametersLinkResponsePtrOutputWithContext(context.Context) ParametersLinkResponsePtrOutput
}
type parametersLinkResponsePtrType ParametersLinkResponseArgs
func ParametersLinkResponsePtr(v *ParametersLinkResponseArgs) ParametersLinkResponsePtrInput {
return (*parametersLinkResponsePtrType)(v)
}
func (*parametersLinkResponsePtrType) ElementType() reflect.Type {
return reflect.TypeOf((**ParametersLinkResponse)(nil)).Elem()
}
func (i *parametersLinkResponsePtrType) ToParametersLinkResponsePtrOutput() ParametersLinkResponsePtrOutput {
return i.ToParametersLinkResponsePtrOutputWithContext(context.Background())
}
func (i *parametersLinkResponsePtrType) ToParametersLinkResponsePtrOutputWithContext(ctx context.Context) ParametersLinkResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ParametersLinkResponsePtrOutput)
}
// Entity representing the reference to the deployment parameters.
type ParametersLinkResponseOutput struct{ *pulumi.OutputState }
func (ParametersLinkResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*ParametersLinkResponse)(nil)).Elem()
}
func (o ParametersLinkResponseOutput) ToParametersLinkResponseOutput() ParametersLinkResponseOutput {
return o
}
func (o ParametersLinkResponseOutput) ToParametersLinkResponseOutputWithContext(ctx context.Context) ParametersLinkResponseOutput {
return o
}
func (o ParametersLinkResponseOutput) ToParametersLinkResponsePtrOutput() ParametersLinkResponsePtrOutput {
return o.ToParametersLinkResponsePtrOutputWithContext(context.Background())
}
func (o ParametersLinkResponseOutput) ToParametersLinkResponsePtrOutputWithContext(ctx context.Context) ParametersLinkResponsePtrOutput {
return o.ApplyT(func(v ParametersLinkResponse) *ParametersLinkResponse {
return &v
}).(ParametersLinkResponsePtrOutput)
}
// If included, must match the ContentVersion in the template.
func (o ParametersLinkResponseOutput) ContentVersion() pulumi.StringPtrOutput {
return o.ApplyT(func(v ParametersLinkResponse) *string { return v.ContentVersion }).(pulumi.StringPtrOutput)
}
// The URI of the parameters file.
func (o ParametersLinkResponseOutput) Uri() pulumi.StringOutput {
return o.ApplyT(func(v ParametersLinkResponse) string { return v.Uri }).(pulumi.StringOutput)
}
type ParametersLinkResponsePtrOutput struct{ *pulumi.OutputState }
func (ParametersLinkResponsePtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**ParametersLinkResponse)(nil)).Elem()
}
func (o ParametersLinkResponsePtrOutput) ToParametersLinkResponsePtrOutput() ParametersLinkResponsePtrOutput {
return o
}
func (o ParametersLinkResponsePtrOutput) ToParametersLinkResponsePtrOutputWithContext(ctx context.Context) ParametersLinkResponsePtrOutput {
return o
}
func (o ParametersLinkResponsePtrOutput) Elem() ParametersLinkResponseOutput {
return o.ApplyT(func(v *ParametersLinkResponse) ParametersLinkResponse { return *v }).(ParametersLinkResponseOutput)
}
// If included, must match the ContentVersion in the template.
func (o ParametersLinkResponsePtrOutput) ContentVersion() pulumi.StringPtrOutput {
return o.ApplyT(func(v *ParametersLinkResponse) *string {
if v == nil {
return nil
}
return v.ContentVersion
}).(pulumi.StringPtrOutput)
}
// The URI of the parameters file.
func (o ParametersLinkResponsePtrOutput) Uri() pulumi.StringPtrOutput {
return o.ApplyT(func(v *ParametersLinkResponse) *string {
if v == nil {
return nil
}
return &v.Uri
}).(pulumi.StringPtrOutput)
}
// Plan for the resource.
type Plan struct {
// The plan ID.
Name *string `pulumi:"name"`
// The offer ID.
Product *string `pulumi:"product"`
// The promotion code.
PromotionCode *string `pulumi:"promotionCode"`
// The publisher ID.
Publisher *string `pulumi:"publisher"`
// The plan's version.
Version *string `pulumi:"version"`
}
// PlanInput is an input type that accepts PlanArgs and PlanOutput values.
// You can construct a concrete instance of `PlanInput` via:
//
// PlanArgs{...}
type PlanInput interface {
pulumi.Input
ToPlanOutput() PlanOutput
ToPlanOutputWithContext(context.Context) PlanOutput
}
// Plan for the resource.
type PlanArgs struct {
// The plan ID.
Name pulumi.StringPtrInput `pulumi:"name"`
// The offer ID.
Product pulumi.StringPtrInput `pulumi:"product"`
// The promotion code.
PromotionCode pulumi.StringPtrInput `pulumi:"promotionCode"`
// The publisher ID.
Publisher pulumi.StringPtrInput `pulumi:"publisher"`
// The plan's version.
Version pulumi.StringPtrInput `pulumi:"version"`
}
func (PlanArgs) ElementType() reflect.Type {
return reflect.TypeOf((*Plan)(nil)).Elem()
}
func (i PlanArgs) ToPlanOutput() PlanOutput {
return i.ToPlanOutputWithContext(context.Background())
}
func (i PlanArgs) ToPlanOutputWithContext(ctx context.Context) PlanOutput {
return pulumi.ToOutputWithContext(ctx, i).(PlanOutput)
}
func (i PlanArgs) ToPlanPtrOutput() PlanPtrOutput {
return i.ToPlanPtrOutputWithContext(context.Background())
}
func (i PlanArgs) ToPlanPtrOutputWithContext(ctx context.Context) PlanPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(PlanOutput).ToPlanPtrOutputWithContext(ctx)
}
// PlanPtrInput is an input type that accepts PlanArgs, PlanPtr and PlanPtrOutput values.
// You can construct a concrete instance of `PlanPtrInput` via:
//
// PlanArgs{...}
//
// or:
//
// nil
type PlanPtrInput interface {
pulumi.Input
ToPlanPtrOutput() PlanPtrOutput
ToPlanPtrOutputWithContext(context.Context) PlanPtrOutput
}
type planPtrType PlanArgs
func PlanPtr(v *PlanArgs) PlanPtrInput {
return (*planPtrType)(v)
}
func (*planPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**Plan)(nil)).Elem()
}
func (i *planPtrType) ToPlanPtrOutput() PlanPtrOutput {
return i.ToPlanPtrOutputWithContext(context.Background())
}
func (i *planPtrType) ToPlanPtrOutputWithContext(ctx context.Context) PlanPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(PlanPtrOutput)
}
// Plan for the resource.
type PlanOutput struct{ *pulumi.OutputState }
func (PlanOutput) ElementType() reflect.Type {
return reflect.TypeOf((*Plan)(nil)).Elem()
}
func (o PlanOutput) ToPlanOutput() PlanOutput {
return o
}
func (o PlanOutput) ToPlanOutputWithContext(ctx context.Context) PlanOutput {
return o
}
func (o PlanOutput) ToPlanPtrOutput() PlanPtrOutput {
return o.ToPlanPtrOutputWithContext(context.Background())
}
func (o PlanOutput) ToPlanPtrOutputWithContext(ctx context.Context) PlanPtrOutput {
return o.ApplyT(func(v Plan) *Plan {
return &v
}).(PlanPtrOutput)
}
// The plan ID.
func (o PlanOutput) Name() pulumi.StringPtrOutput {
return o.ApplyT(func(v Plan) *string { return v.Name }).(pulumi.StringPtrOutput)
}
// The offer ID.
func (o PlanOutput) Product() pulumi.StringPtrOutput {
return o.ApplyT(func(v Plan) *string { return v.Product }).(pulumi.StringPtrOutput)
}
// The promotion code.
func (o PlanOutput) PromotionCode() pulumi.StringPtrOutput {
return o.ApplyT(func(v Plan) *string { return v.PromotionCode }).(pulumi.StringPtrOutput)
}
// The publisher ID.
func (o PlanOutput) Publisher() pulumi.StringPtrOutput {
return o.ApplyT(func(v Plan) *string { return v.Publisher }).(pulumi.StringPtrOutput)
}
// The plan's version.
func (o PlanOutput) Version() pulumi.StringPtrOutput {
return o.ApplyT(func(v Plan) *string { return v.Version }).(pulumi.StringPtrOutput)
}
type PlanPtrOutput struct{ *pulumi.OutputState }
func (PlanPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**Plan)(nil)).Elem()
}
func (o PlanPtrOutput) ToPlanPtrOutput() PlanPtrOutput {
return o
}
func (o PlanPtrOutput) ToPlanPtrOutputWithContext(ctx context.Context) PlanPtrOutput {
return o
}
func (o PlanPtrOutput) Elem() PlanOutput {
return o.ApplyT(func(v *Plan) Plan { return *v }).(PlanOutput)
}
// The plan ID.
func (o PlanPtrOutput) Name() pulumi.StringPtrOutput {
return o.ApplyT(func(v *Plan) *string {
if v == nil {
return nil
}
return v.Name
}).(pulumi.StringPtrOutput)
}
// The offer ID.
func (o PlanPtrOutput) Product() pulumi.StringPtrOutput {
return o.ApplyT(func(v *Plan) *string {
if v == nil {
return nil
}
return v.Product
}).(pulumi.StringPtrOutput)
}
// The promotion code.
func (o PlanPtrOutput) PromotionCode() pulumi.StringPtrOutput {
return o.ApplyT(func(v *Plan) *string {
if v == nil {
return nil
}
return v.PromotionCode
}).(pulumi.StringPtrOutput)
}
// The publisher ID.
func (o PlanPtrOutput) Publisher() pulumi.StringPtrOutput {
return o.ApplyT(func(v *Plan) *string {
if v == nil {
return nil
}
return v.Publisher
}).(pulumi.StringPtrOutput)
}
// The plan's version.
func (o PlanPtrOutput) Version() pulumi.StringPtrOutput {
return o.ApplyT(func(v *Plan) *string {
if v == nil {
return nil
}
return v.Version
}).(pulumi.StringPtrOutput)
}
// Plan for the resource.
type PlanResponse struct {
// The plan ID.
Name *string `pulumi:"name"`
// The offer ID.
Product *string `pulumi:"product"`
// The promotion code.
PromotionCode *string `pulumi:"promotionCode"`
// The publisher ID.
Publisher *string `pulumi:"publisher"`
// The plan's version.
Version *string `pulumi:"version"`
}
// PlanResponseInput is an input type that accepts PlanResponseArgs and PlanResponseOutput values.
// You can construct a concrete instance of `PlanResponseInput` via:
//
// PlanResponseArgs{...}
type PlanResponseInput interface {
pulumi.Input
ToPlanResponseOutput() PlanResponseOutput
ToPlanResponseOutputWithContext(context.Context) PlanResponseOutput
}
// Plan for the resource.
type PlanResponseArgs struct {
// The plan ID.
Name pulumi.StringPtrInput `pulumi:"name"`
// The offer ID.
Product pulumi.StringPtrInput `pulumi:"product"`
// The promotion code.
PromotionCode pulumi.StringPtrInput `pulumi:"promotionCode"`
// The publisher ID.
Publisher pulumi.StringPtrInput `pulumi:"publisher"`
// The plan's version.
Version pulumi.StringPtrInput `pulumi:"version"`
}
func (PlanResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*PlanResponse)(nil)).Elem()
}
func (i PlanResponseArgs) ToPlanResponseOutput() PlanResponseOutput {
return i.ToPlanResponseOutputWithContext(context.Background())
}
func (i PlanResponseArgs) ToPlanResponseOutputWithContext(ctx context.Context) PlanResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(PlanResponseOutput)
}
func (i PlanResponseArgs) ToPlanResponsePtrOutput() PlanResponsePtrOutput {
return i.ToPlanResponsePtrOutputWithContext(context.Background())
}
func (i PlanResponseArgs) ToPlanResponsePtrOutputWithContext(ctx context.Context) PlanResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(PlanResponseOutput).ToPlanResponsePtrOutputWithContext(ctx)
}
// PlanResponsePtrInput is an input type that accepts PlanResponseArgs, PlanResponsePtr and PlanResponsePtrOutput values.
// You can construct a concrete instance of `PlanResponsePtrInput` via:
//
// PlanResponseArgs{...}
//
// or:
//
// nil
type PlanResponsePtrInput interface {
pulumi.Input
ToPlanResponsePtrOutput() PlanResponsePtrOutput
ToPlanResponsePtrOutputWithContext(context.Context) PlanResponsePtrOutput
}
type planResponsePtrType PlanResponseArgs
func PlanResponsePtr(v *PlanResponseArgs) PlanResponsePtrInput {
return (*planResponsePtrType)(v)
}
func (*planResponsePtrType) ElementType() reflect.Type {
return reflect.TypeOf((**PlanResponse)(nil)).Elem()
}
func (i *planResponsePtrType) ToPlanResponsePtrOutput() PlanResponsePtrOutput {
return i.ToPlanResponsePtrOutputWithContext(context.Background())
}
func (i *planResponsePtrType) ToPlanResponsePtrOutputWithContext(ctx context.Context) PlanResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(PlanResponsePtrOutput)
}
// Plan for the resource.
type PlanResponseOutput struct{ *pulumi.OutputState }
func (PlanResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*PlanResponse)(nil)).Elem()
}
func (o PlanResponseOutput) ToPlanResponseOutput() PlanResponseOutput {
return o
}
func (o PlanResponseOutput) ToPlanResponseOutputWithContext(ctx context.Context) PlanResponseOutput {
return o
}
func (o PlanResponseOutput) ToPlanResponsePtrOutput() PlanResponsePtrOutput {
return o.ToPlanResponsePtrOutputWithContext(context.Background())
}
func (o PlanResponseOutput) ToPlanResponsePtrOutputWithContext(ctx context.Context) PlanResponsePtrOutput {
return o.ApplyT(func(v PlanResponse) *PlanResponse {
return &v
}).(PlanResponsePtrOutput)
}
// The plan ID.
func (o PlanResponseOutput) Name() pulumi.StringPtrOutput {
return o.ApplyT(func(v PlanResponse) *string { return v.Name }).(pulumi.StringPtrOutput)
}
// The offer ID.
func (o PlanResponseOutput) Product() pulumi.StringPtrOutput {
return o.ApplyT(func(v PlanResponse) *string { return v.Product }).(pulumi.StringPtrOutput)
}
// The promotion code.
func (o PlanResponseOutput) PromotionCode() pulumi.StringPtrOutput {
return o.ApplyT(func(v PlanResponse) *string { return v.PromotionCode }).(pulumi.StringPtrOutput)
}
// The publisher ID.
func (o PlanResponseOutput) Publisher() pulumi.StringPtrOutput {
return o.ApplyT(func(v PlanResponse) *string { return v.Publisher }).(pulumi.StringPtrOutput)
}
// The plan's version.
func (o PlanResponseOutput) Version() pulumi.StringPtrOutput {
return o.ApplyT(func(v PlanResponse) *string { return v.Version }).(pulumi.StringPtrOutput)
}
type PlanResponsePtrOutput struct{ *pulumi.OutputState }
func (PlanResponsePtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**PlanResponse)(nil)).Elem()
}
func (o PlanResponsePtrOutput) ToPlanResponsePtrOutput() PlanResponsePtrOutput {
return o
}
func (o PlanResponsePtrOutput) ToPlanResponsePtrOutputWithContext(ctx context.Context) PlanResponsePtrOutput {
return o
}
func (o PlanResponsePtrOutput) Elem() PlanResponseOutput {
return o.ApplyT(func(v *PlanResponse) PlanResponse { return *v }).(PlanResponseOutput)
}
// The plan ID.
func (o PlanResponsePtrOutput) Name() pulumi.StringPtrOutput {
return o.ApplyT(func(v *PlanResponse) *string {
if v == nil {
return nil
}
return v.Name
}).(pulumi.StringPtrOutput)
}
// The offer ID.
func (o PlanResponsePtrOutput) Product() pulumi.StringPtrOutput {
return o.ApplyT(func(v *PlanResponse) *string {
if v == nil {
return nil
}
return v.Product
}).(pulumi.StringPtrOutput)
}
// The promotion code.
func (o PlanResponsePtrOutput) PromotionCode() pulumi.StringPtrOutput {
return o.ApplyT(func(v *PlanResponse) *string {
if v == nil {
return nil
}
return v.PromotionCode
}).(pulumi.StringPtrOutput)
}
// The publisher ID.
func (o PlanResponsePtrOutput) Publisher() pulumi.StringPtrOutput {
return o.ApplyT(func(v *PlanResponse) *string {
if v == nil {
return nil
}
return v.Publisher
}).(pulumi.StringPtrOutput)
}
// The plan's version.
func (o PlanResponsePtrOutput) Version() pulumi.StringPtrOutput {
return o.ApplyT(func(v *PlanResponse) *string {
if v == nil {
return nil
}
return v.Version
}).(pulumi.StringPtrOutput)
}
// Resource type managed by the resource provider.
type ProviderResourceTypeResponse struct {
// The aliases that are supported by this resource type.
Aliases []AliasTypeResponse `pulumi:"aliases"`
// The API version.
ApiVersions []string `pulumi:"apiVersions"`
// The additional capabilities offered by this resource type.
Capabilities *string `pulumi:"capabilities"`
// The collection of locations where this resource type can be created.
Locations []string `pulumi:"locations"`
// The properties.
Properties map[string]string `pulumi:"properties"`
// The resource type.
ResourceType *string `pulumi:"resourceType"`
ZoneMappings []ZoneMappingResponse `pulumi:"zoneMappings"`
}
// ProviderResourceTypeResponseInput is an input type that accepts ProviderResourceTypeResponseArgs and ProviderResourceTypeResponseOutput values.
// You can construct a concrete instance of `ProviderResourceTypeResponseInput` via:
//
// ProviderResourceTypeResponseArgs{...}
type ProviderResourceTypeResponseInput interface {
pulumi.Input
ToProviderResourceTypeResponseOutput() ProviderResourceTypeResponseOutput
ToProviderResourceTypeResponseOutputWithContext(context.Context) ProviderResourceTypeResponseOutput
}
// Resource type managed by the resource provider.
type ProviderResourceTypeResponseArgs struct {
// The aliases that are supported by this resource type.
Aliases AliasTypeResponseArrayInput `pulumi:"aliases"`
// The API version.
ApiVersions pulumi.StringArrayInput `pulumi:"apiVersions"`
// The additional capabilities offered by this resource type.
Capabilities pulumi.StringPtrInput `pulumi:"capabilities"`
// The collection of locations where this resource type can be created.
Locations pulumi.StringArrayInput `pulumi:"locations"`
// The properties.
Properties pulumi.StringMapInput `pulumi:"properties"`
// The resource type.
ResourceType pulumi.StringPtrInput `pulumi:"resourceType"`
ZoneMappings ZoneMappingResponseArrayInput `pulumi:"zoneMappings"`
}
func (ProviderResourceTypeResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*ProviderResourceTypeResponse)(nil)).Elem()
}
func (i ProviderResourceTypeResponseArgs) ToProviderResourceTypeResponseOutput() ProviderResourceTypeResponseOutput {
return i.ToProviderResourceTypeResponseOutputWithContext(context.Background())
}
func (i ProviderResourceTypeResponseArgs) ToProviderResourceTypeResponseOutputWithContext(ctx context.Context) ProviderResourceTypeResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderResourceTypeResponseOutput)
}
// ProviderResourceTypeResponseArrayInput is an input type that accepts ProviderResourceTypeResponseArray and ProviderResourceTypeResponseArrayOutput values.
// You can construct a concrete instance of `ProviderResourceTypeResponseArrayInput` via:
//
// ProviderResourceTypeResponseArray{ ProviderResourceTypeResponseArgs{...} }
type ProviderResourceTypeResponseArrayInput interface {
pulumi.Input
ToProviderResourceTypeResponseArrayOutput() ProviderResourceTypeResponseArrayOutput
ToProviderResourceTypeResponseArrayOutputWithContext(context.Context) ProviderResourceTypeResponseArrayOutput
}
type ProviderResourceTypeResponseArray []ProviderResourceTypeResponseInput
func (ProviderResourceTypeResponseArray) ElementType() reflect.Type {
return reflect.TypeOf((*[]ProviderResourceTypeResponse)(nil)).Elem()
}
func (i ProviderResourceTypeResponseArray) ToProviderResourceTypeResponseArrayOutput() ProviderResourceTypeResponseArrayOutput {
return i.ToProviderResourceTypeResponseArrayOutputWithContext(context.Background())
}
func (i ProviderResourceTypeResponseArray) ToProviderResourceTypeResponseArrayOutputWithContext(ctx context.Context) ProviderResourceTypeResponseArrayOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderResourceTypeResponseArrayOutput)
}
// Resource type managed by the resource provider.
type ProviderResourceTypeResponseOutput struct{ *pulumi.OutputState }
func (ProviderResourceTypeResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*ProviderResourceTypeResponse)(nil)).Elem()
}
func (o ProviderResourceTypeResponseOutput) ToProviderResourceTypeResponseOutput() ProviderResourceTypeResponseOutput {
return o
}
func (o ProviderResourceTypeResponseOutput) ToProviderResourceTypeResponseOutputWithContext(ctx context.Context) ProviderResourceTypeResponseOutput {
return o
}
// The aliases that are supported by this resource type.
func (o ProviderResourceTypeResponseOutput) Aliases() AliasTypeResponseArrayOutput {
return o.ApplyT(func(v ProviderResourceTypeResponse) []AliasTypeResponse { return v.Aliases }).(AliasTypeResponseArrayOutput)
}
// The API version.
func (o ProviderResourceTypeResponseOutput) ApiVersions() pulumi.StringArrayOutput {
return o.ApplyT(func(v ProviderResourceTypeResponse) []string { return v.ApiVersions }).(pulumi.StringArrayOutput)
}
// The additional capabilities offered by this resource type.
func (o ProviderResourceTypeResponseOutput) Capabilities() pulumi.StringPtrOutput {
return o.ApplyT(func(v ProviderResourceTypeResponse) *string { return v.Capabilities }).(pulumi.StringPtrOutput)
}
// The collection of locations where this resource type can be created.
func (o ProviderResourceTypeResponseOutput) Locations() pulumi.StringArrayOutput {
return o.ApplyT(func(v ProviderResourceTypeResponse) []string { return v.Locations }).(pulumi.StringArrayOutput)
}
// The properties.
func (o ProviderResourceTypeResponseOutput) Properties() pulumi.StringMapOutput {
return o.ApplyT(func(v ProviderResourceTypeResponse) map[string]string { return v.Properties }).(pulumi.StringMapOutput)
}
// The resource type.
func (o ProviderResourceTypeResponseOutput) ResourceType() pulumi.StringPtrOutput {
return o.ApplyT(func(v ProviderResourceTypeResponse) *string { return v.ResourceType }).(pulumi.StringPtrOutput)
}
func (o ProviderResourceTypeResponseOutput) ZoneMappings() ZoneMappingResponseArrayOutput {
return o.ApplyT(func(v ProviderResourceTypeResponse) []ZoneMappingResponse { return v.ZoneMappings }).(ZoneMappingResponseArrayOutput)
}
type ProviderResourceTypeResponseArrayOutput struct{ *pulumi.OutputState }
func (ProviderResourceTypeResponseArrayOutput) ElementType() reflect.Type {
return reflect.TypeOf((*[]ProviderResourceTypeResponse)(nil)).Elem()
}
func (o ProviderResourceTypeResponseArrayOutput) ToProviderResourceTypeResponseArrayOutput() ProviderResourceTypeResponseArrayOutput {
return o
}
func (o ProviderResourceTypeResponseArrayOutput) ToProviderResourceTypeResponseArrayOutputWithContext(ctx context.Context) ProviderResourceTypeResponseArrayOutput {
return o
}
func (o ProviderResourceTypeResponseArrayOutput) Index(i pulumi.IntInput) ProviderResourceTypeResponseOutput {
return pulumi.All(o, i).ApplyT(func(vs []interface{}) ProviderResourceTypeResponse {
return vs[0].([]ProviderResourceTypeResponse)[vs[1].(int)]
}).(ProviderResourceTypeResponseOutput)
}
// Resource provider information.
type ProviderResponse struct {
// The provider ID.
Id string `pulumi:"id"`
// The namespace of the resource provider.
Namespace *string `pulumi:"namespace"`
// The registration policy of the resource provider.
RegistrationPolicy string `pulumi:"registrationPolicy"`
// The registration state of the resource provider.
RegistrationState string `pulumi:"registrationState"`
// The collection of provider resource types.
ResourceTypes []ProviderResourceTypeResponse `pulumi:"resourceTypes"`
}
// ProviderResponseInput is an input type that accepts ProviderResponseArgs and ProviderResponseOutput values.
// You can construct a concrete instance of `ProviderResponseInput` via:
//
// ProviderResponseArgs{...}
type ProviderResponseInput interface {
pulumi.Input
ToProviderResponseOutput() ProviderResponseOutput
ToProviderResponseOutputWithContext(context.Context) ProviderResponseOutput
}
// Resource provider information.
type ProviderResponseArgs struct {
// The provider ID.
Id pulumi.StringInput `pulumi:"id"`
// The namespace of the resource provider.
Namespace pulumi.StringPtrInput `pulumi:"namespace"`
// The registration policy of the resource provider.
RegistrationPolicy pulumi.StringInput `pulumi:"registrationPolicy"`
// The registration state of the resource provider.
RegistrationState pulumi.StringInput `pulumi:"registrationState"`
// The collection of provider resource types.
ResourceTypes ProviderResourceTypeResponseArrayInput `pulumi:"resourceTypes"`
}
func (ProviderResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*ProviderResponse)(nil)).Elem()
}
func (i ProviderResponseArgs) ToProviderResponseOutput() ProviderResponseOutput {
return i.ToProviderResponseOutputWithContext(context.Background())
}
func (i ProviderResponseArgs) ToProviderResponseOutputWithContext(ctx context.Context) ProviderResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderResponseOutput)
}
// ProviderResponseArrayInput is an input type that accepts ProviderResponseArray and ProviderResponseArrayOutput values.
// You can construct a concrete instance of `ProviderResponseArrayInput` via:
//
// ProviderResponseArray{ ProviderResponseArgs{...} }
type ProviderResponseArrayInput interface {
pulumi.Input
ToProviderResponseArrayOutput() ProviderResponseArrayOutput
ToProviderResponseArrayOutputWithContext(context.Context) ProviderResponseArrayOutput
}
type ProviderResponseArray []ProviderResponseInput
func (ProviderResponseArray) ElementType() reflect.Type {
return reflect.TypeOf((*[]ProviderResponse)(nil)).Elem()
}
func (i ProviderResponseArray) ToProviderResponseArrayOutput() ProviderResponseArrayOutput {
return i.ToProviderResponseArrayOutputWithContext(context.Background())
}
func (i ProviderResponseArray) ToProviderResponseArrayOutputWithContext(ctx context.Context) ProviderResponseArrayOutput {
return pulumi.ToOutputWithContext(ctx, i).(ProviderResponseArrayOutput)
}
// Resource provider information.
type ProviderResponseOutput struct{ *pulumi.OutputState }
func (ProviderResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*ProviderResponse)(nil)).Elem()
}
func (o ProviderResponseOutput) ToProviderResponseOutput() ProviderResponseOutput {
return o
}
func (o ProviderResponseOutput) ToProviderResponseOutputWithContext(ctx context.Context) ProviderResponseOutput {
return o
}
// The provider ID.
func (o ProviderResponseOutput) Id() pulumi.StringOutput {
return o.ApplyT(func(v ProviderResponse) string { return v.Id }).(pulumi.StringOutput)
}
// The namespace of the resource provider.
func (o ProviderResponseOutput) Namespace() pulumi.StringPtrOutput {
return o.ApplyT(func(v ProviderResponse) *string { return v.Namespace }).(pulumi.StringPtrOutput)
}
// The registration policy of the resource provider.
func (o ProviderResponseOutput) RegistrationPolicy() pulumi.StringOutput {
return o.ApplyT(func(v ProviderResponse) string { return v.RegistrationPolicy }).(pulumi.StringOutput)
}
// The registration state of the resource provider.
func (o ProviderResponseOutput) RegistrationState() pulumi.StringOutput {
return o.ApplyT(func(v ProviderResponse) string { return v.RegistrationState }).(pulumi.StringOutput)
}
// The collection of provider resource types.
func (o ProviderResponseOutput) ResourceTypes() ProviderResourceTypeResponseArrayOutput {
return o.ApplyT(func(v ProviderResponse) []ProviderResourceTypeResponse { return v.ResourceTypes }).(ProviderResourceTypeResponseArrayOutput)
}
type ProviderResponseArrayOutput struct{ *pulumi.OutputState }
func (ProviderResponseArrayOutput) ElementType() reflect.Type {
return reflect.TypeOf((*[]ProviderResponse)(nil)).Elem()
}
func (o ProviderResponseArrayOutput) ToProviderResponseArrayOutput() ProviderResponseArrayOutput {
return o
}
func (o ProviderResponseArrayOutput) ToProviderResponseArrayOutputWithContext(ctx context.Context) ProviderResponseArrayOutput {
return o
}
func (o ProviderResponseArrayOutput) Index(i pulumi.IntInput) ProviderResponseOutput {
return pulumi.All(o, i).ApplyT(func(vs []interface{}) ProviderResponse {
return vs[0].([]ProviderResponse)[vs[1].(int)]
}).(ProviderResponseOutput)
}
// The resource group properties.
type ResourceGroupPropertiesResponse struct {
// The provisioning state.
ProvisioningState string `pulumi:"provisioningState"`
}
// ResourceGroupPropertiesResponseInput is an input type that accepts ResourceGroupPropertiesResponseArgs and ResourceGroupPropertiesResponseOutput values.
// You can construct a concrete instance of `ResourceGroupPropertiesResponseInput` via:
//
// ResourceGroupPropertiesResponseArgs{...}
type ResourceGroupPropertiesResponseInput interface {
pulumi.Input
ToResourceGroupPropertiesResponseOutput() ResourceGroupPropertiesResponseOutput
ToResourceGroupPropertiesResponseOutputWithContext(context.Context) ResourceGroupPropertiesResponseOutput
}
// The resource group properties.
type ResourceGroupPropertiesResponseArgs struct {
// The provisioning state.
ProvisioningState pulumi.StringInput `pulumi:"provisioningState"`
}
func (ResourceGroupPropertiesResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*ResourceGroupPropertiesResponse)(nil)).Elem()
}
func (i ResourceGroupPropertiesResponseArgs) ToResourceGroupPropertiesResponseOutput() ResourceGroupPropertiesResponseOutput {
return i.ToResourceGroupPropertiesResponseOutputWithContext(context.Background())
}
func (i ResourceGroupPropertiesResponseArgs) ToResourceGroupPropertiesResponseOutputWithContext(ctx context.Context) ResourceGroupPropertiesResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(ResourceGroupPropertiesResponseOutput)
}
func (i ResourceGroupPropertiesResponseArgs) ToResourceGroupPropertiesResponsePtrOutput() ResourceGroupPropertiesResponsePtrOutput {
return i.ToResourceGroupPropertiesResponsePtrOutputWithContext(context.Background())
}
func (i ResourceGroupPropertiesResponseArgs) ToResourceGroupPropertiesResponsePtrOutputWithContext(ctx context.Context) ResourceGroupPropertiesResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ResourceGroupPropertiesResponseOutput).ToResourceGroupPropertiesResponsePtrOutputWithContext(ctx)
}
// ResourceGroupPropertiesResponsePtrInput is an input type that accepts ResourceGroupPropertiesResponseArgs, ResourceGroupPropertiesResponsePtr and ResourceGroupPropertiesResponsePtrOutput values.
// You can construct a concrete instance of `ResourceGroupPropertiesResponsePtrInput` via:
//
// ResourceGroupPropertiesResponseArgs{...}
//
// or:
//
// nil
type ResourceGroupPropertiesResponsePtrInput interface {
pulumi.Input
ToResourceGroupPropertiesResponsePtrOutput() ResourceGroupPropertiesResponsePtrOutput
ToResourceGroupPropertiesResponsePtrOutputWithContext(context.Context) ResourceGroupPropertiesResponsePtrOutput
}
type resourceGroupPropertiesResponsePtrType ResourceGroupPropertiesResponseArgs
func ResourceGroupPropertiesResponsePtr(v *ResourceGroupPropertiesResponseArgs) ResourceGroupPropertiesResponsePtrInput {
return (*resourceGroupPropertiesResponsePtrType)(v)
}
func (*resourceGroupPropertiesResponsePtrType) ElementType() reflect.Type {
return reflect.TypeOf((**ResourceGroupPropertiesResponse)(nil)).Elem()
}
func (i *resourceGroupPropertiesResponsePtrType) ToResourceGroupPropertiesResponsePtrOutput() ResourceGroupPropertiesResponsePtrOutput {
return i.ToResourceGroupPropertiesResponsePtrOutputWithContext(context.Background())
}
func (i *resourceGroupPropertiesResponsePtrType) ToResourceGroupPropertiesResponsePtrOutputWithContext(ctx context.Context) ResourceGroupPropertiesResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(ResourceGroupPropertiesResponsePtrOutput)
}
// The resource group properties.
type ResourceGroupPropertiesResponseOutput struct{ *pulumi.OutputState }
func (ResourceGroupPropertiesResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*ResourceGroupPropertiesResponse)(nil)).Elem()
}
func (o ResourceGroupPropertiesResponseOutput) ToResourceGroupPropertiesResponseOutput() ResourceGroupPropertiesResponseOutput {
return o
}
func (o ResourceGroupPropertiesResponseOutput) ToResourceGroupPropertiesResponseOutputWithContext(ctx context.Context) ResourceGroupPropertiesResponseOutput {
return o
}
func (o ResourceGroupPropertiesResponseOutput) ToResourceGroupPropertiesResponsePtrOutput() ResourceGroupPropertiesResponsePtrOutput {
return o.ToResourceGroupPropertiesResponsePtrOutputWithContext(context.Background())
}
func (o ResourceGroupPropertiesResponseOutput) ToResourceGroupPropertiesResponsePtrOutputWithContext(ctx context.Context) ResourceGroupPropertiesResponsePtrOutput {
return o.ApplyT(func(v ResourceGroupPropertiesResponse) *ResourceGroupPropertiesResponse {
return &v
}).(ResourceGroupPropertiesResponsePtrOutput)
}
// The provisioning state.
func (o ResourceGroupPropertiesResponseOutput) ProvisioningState() pulumi.StringOutput {
return o.ApplyT(func(v ResourceGroupPropertiesResponse) string { return v.ProvisioningState }).(pulumi.StringOutput)
}
type ResourceGroupPropertiesResponsePtrOutput struct{ *pulumi.OutputState }
func (ResourceGroupPropertiesResponsePtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**ResourceGroupPropertiesResponse)(nil)).Elem()
}
func (o ResourceGroupPropertiesResponsePtrOutput) ToResourceGroupPropertiesResponsePtrOutput() ResourceGroupPropertiesResponsePtrOutput {
return o
}
func (o ResourceGroupPropertiesResponsePtrOutput) ToResourceGroupPropertiesResponsePtrOutputWithContext(ctx context.Context) ResourceGroupPropertiesResponsePtrOutput {
return o
}
func (o ResourceGroupPropertiesResponsePtrOutput) Elem() ResourceGroupPropertiesResponseOutput {
return o.ApplyT(func(v *ResourceGroupPropertiesResponse) ResourceGroupPropertiesResponse { return *v }).(ResourceGroupPropertiesResponseOutput)
}
// The provisioning state.
func (o ResourceGroupPropertiesResponsePtrOutput) ProvisioningState() pulumi.StringPtrOutput {
return o.ApplyT(func(v *ResourceGroupPropertiesResponse) *string {
if v == nil {
return nil
}
return &v.ProvisioningState
}).(pulumi.StringPtrOutput)
}
// SKU for the resource.
type Sku struct {
// The SKU capacity.
Capacity *int `pulumi:"capacity"`
// The SKU family.
Family *string `pulumi:"family"`
// The SKU model.
Model *string `pulumi:"model"`
// The SKU name.
Name *string `pulumi:"name"`
// The SKU size.
Size *string `pulumi:"size"`
// The SKU tier.
Tier *string `pulumi:"tier"`
}
// SkuInput is an input type that accepts SkuArgs and SkuOutput values.
// You can construct a concrete instance of `SkuInput` via:
//
// SkuArgs{...}
type SkuInput interface {
pulumi.Input
ToSkuOutput() SkuOutput
ToSkuOutputWithContext(context.Context) SkuOutput
}
// SKU for the resource.
type SkuArgs struct {
// The SKU capacity.
Capacity pulumi.IntPtrInput `pulumi:"capacity"`
// The SKU family.
Family pulumi.StringPtrInput `pulumi:"family"`
// The SKU model.
Model pulumi.StringPtrInput `pulumi:"model"`
// The SKU name.
Name pulumi.StringPtrInput `pulumi:"name"`
// The SKU size.
Size pulumi.StringPtrInput `pulumi:"size"`
// The SKU tier.
Tier pulumi.StringPtrInput `pulumi:"tier"`
}
func (SkuArgs) ElementType() reflect.Type {
return reflect.TypeOf((*Sku)(nil)).Elem()
}
func (i SkuArgs) ToSkuOutput() SkuOutput {
return i.ToSkuOutputWithContext(context.Background())
}
func (i SkuArgs) ToSkuOutputWithContext(ctx context.Context) SkuOutput {
return pulumi.ToOutputWithContext(ctx, i).(SkuOutput)
}
func (i SkuArgs) ToSkuPtrOutput() SkuPtrOutput {
return i.ToSkuPtrOutputWithContext(context.Background())
}
func (i SkuArgs) ToSkuPtrOutputWithContext(ctx context.Context) SkuPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(SkuOutput).ToSkuPtrOutputWithContext(ctx)
}
// SkuPtrInput is an input type that accepts SkuArgs, SkuPtr and SkuPtrOutput values.
// You can construct a concrete instance of `SkuPtrInput` via:
//
// SkuArgs{...}
//
// or:
//
// nil
type SkuPtrInput interface {
pulumi.Input
ToSkuPtrOutput() SkuPtrOutput
ToSkuPtrOutputWithContext(context.Context) SkuPtrOutput
}
type skuPtrType SkuArgs
func SkuPtr(v *SkuArgs) SkuPtrInput {
return (*skuPtrType)(v)
}
func (*skuPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**Sku)(nil)).Elem()
}
func (i *skuPtrType) ToSkuPtrOutput() SkuPtrOutput {
return i.ToSkuPtrOutputWithContext(context.Background())
}
func (i *skuPtrType) ToSkuPtrOutputWithContext(ctx context.Context) SkuPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(SkuPtrOutput)
}
// SKU for the resource.
type SkuOutput struct{ *pulumi.OutputState }
func (SkuOutput) ElementType() reflect.Type {
return reflect.TypeOf((*Sku)(nil)).Elem()
}
func (o SkuOutput) ToSkuOutput() SkuOutput {
return o
}
func (o SkuOutput) ToSkuOutputWithContext(ctx context.Context) SkuOutput {
return o
}
func (o SkuOutput) ToSkuPtrOutput() SkuPtrOutput {
return o.ToSkuPtrOutputWithContext(context.Background())
}
func (o SkuOutput) ToSkuPtrOutputWithContext(ctx context.Context) SkuPtrOutput {
return o.ApplyT(func(v Sku) *Sku {
return &v
}).(SkuPtrOutput)
}
// The SKU capacity.
func (o SkuOutput) Capacity() pulumi.IntPtrOutput {
return o.ApplyT(func(v Sku) *int { return v.Capacity }).(pulumi.IntPtrOutput)
}
// The SKU family.
func (o SkuOutput) Family() pulumi.StringPtrOutput {
return o.ApplyT(func(v Sku) *string { return v.Family }).(pulumi.StringPtrOutput)
}
// The SKU model.
func (o SkuOutput) Model() pulumi.StringPtrOutput {
return o.ApplyT(func(v Sku) *string { return v.Model }).(pulumi.StringPtrOutput)
}
// The SKU name.
func (o SkuOutput) Name() pulumi.StringPtrOutput {
return o.ApplyT(func(v Sku) *string { return v.Name }).(pulumi.StringPtrOutput)
}
// The SKU size.
func (o SkuOutput) Size() pulumi.StringPtrOutput {
return o.ApplyT(func(v Sku) *string { return v.Size }).(pulumi.StringPtrOutput)
}
// The SKU tier.
func (o SkuOutput) Tier() pulumi.StringPtrOutput {
return o.ApplyT(func(v Sku) *string { return v.Tier }).(pulumi.StringPtrOutput)
}
type SkuPtrOutput struct{ *pulumi.OutputState }
func (SkuPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**Sku)(nil)).Elem()
}
func (o SkuPtrOutput) ToSkuPtrOutput() SkuPtrOutput {
return o
}
func (o SkuPtrOutput) ToSkuPtrOutputWithContext(ctx context.Context) SkuPtrOutput {
return o
}
func (o SkuPtrOutput) Elem() SkuOutput {
return o.ApplyT(func(v *Sku) Sku { return *v }).(SkuOutput)
}
// The SKU capacity.
func (o SkuPtrOutput) Capacity() pulumi.IntPtrOutput {
return o.ApplyT(func(v *Sku) *int {
if v == nil {
return nil
}
return v.Capacity
}).(pulumi.IntPtrOutput)
}
// The SKU family.
func (o SkuPtrOutput) Family() pulumi.StringPtrOutput {
return o.ApplyT(func(v *Sku) *string {
if v == nil {
return nil
}
return v.Family
}).(pulumi.StringPtrOutput)
}
// The SKU model.
func (o SkuPtrOutput) Model() pulumi.StringPtrOutput {
return o.ApplyT(func(v *Sku) *string {
if v == nil {
return nil
}
return v.Model
}).(pulumi.StringPtrOutput)
}
// The SKU name.
func (o SkuPtrOutput) Name() pulumi.StringPtrOutput {
return o.ApplyT(func(v *Sku) *string {
if v == nil {
return nil
}
return v.Name
}).(pulumi.StringPtrOutput)
}
// The SKU size.
func (o SkuPtrOutput) Size() pulumi.StringPtrOutput {
return o.ApplyT(func(v *Sku) *string {
if v == nil {
return nil
}
return v.Size
}).(pulumi.StringPtrOutput)
}
// The SKU tier.
func (o SkuPtrOutput) Tier() pulumi.StringPtrOutput {
return o.ApplyT(func(v *Sku) *string {
if v == nil {
return nil
}
return v.Tier
}).(pulumi.StringPtrOutput)
}
// SKU for the resource.
type SkuResponse struct {
// The SKU capacity.
Capacity *int `pulumi:"capacity"`
// The SKU family.
Family *string `pulumi:"family"`
// The SKU model.
Model *string `pulumi:"model"`
// The SKU name.
Name *string `pulumi:"name"`
// The SKU size.
Size *string `pulumi:"size"`
// The SKU tier.
Tier *string `pulumi:"tier"`
}
// SkuResponseInput is an input type that accepts SkuResponseArgs and SkuResponseOutput values.
// You can construct a concrete instance of `SkuResponseInput` via:
//
// SkuResponseArgs{...}
type SkuResponseInput interface {
pulumi.Input
ToSkuResponseOutput() SkuResponseOutput
ToSkuResponseOutputWithContext(context.Context) SkuResponseOutput
}
// SKU for the resource.
type SkuResponseArgs struct {
// The SKU capacity.
Capacity pulumi.IntPtrInput `pulumi:"capacity"`
// The SKU family.
Family pulumi.StringPtrInput `pulumi:"family"`
// The SKU model.
Model pulumi.StringPtrInput `pulumi:"model"`
// The SKU name.
Name pulumi.StringPtrInput `pulumi:"name"`
// The SKU size.
Size pulumi.StringPtrInput `pulumi:"size"`
// The SKU tier.
Tier pulumi.StringPtrInput `pulumi:"tier"`
}
func (SkuResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*SkuResponse)(nil)).Elem()
}
func (i SkuResponseArgs) ToSkuResponseOutput() SkuResponseOutput {
return i.ToSkuResponseOutputWithContext(context.Background())
}
func (i SkuResponseArgs) ToSkuResponseOutputWithContext(ctx context.Context) SkuResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(SkuResponseOutput)
}
func (i SkuResponseArgs) ToSkuResponsePtrOutput() SkuResponsePtrOutput {
return i.ToSkuResponsePtrOutputWithContext(context.Background())
}
func (i SkuResponseArgs) ToSkuResponsePtrOutputWithContext(ctx context.Context) SkuResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(SkuResponseOutput).ToSkuResponsePtrOutputWithContext(ctx)
}
// SkuResponsePtrInput is an input type that accepts SkuResponseArgs, SkuResponsePtr and SkuResponsePtrOutput values.
// You can construct a concrete instance of `SkuResponsePtrInput` via:
//
// SkuResponseArgs{...}
//
// or:
//
// nil
type SkuResponsePtrInput interface {
pulumi.Input
ToSkuResponsePtrOutput() SkuResponsePtrOutput
ToSkuResponsePtrOutputWithContext(context.Context) SkuResponsePtrOutput
}
type skuResponsePtrType SkuResponseArgs
func SkuResponsePtr(v *SkuResponseArgs) SkuResponsePtrInput {
return (*skuResponsePtrType)(v)
}
func (*skuResponsePtrType) ElementType() reflect.Type {
return reflect.TypeOf((**SkuResponse)(nil)).Elem()
}
func (i *skuResponsePtrType) ToSkuResponsePtrOutput() SkuResponsePtrOutput {
return i.ToSkuResponsePtrOutputWithContext(context.Background())
}
func (i *skuResponsePtrType) ToSkuResponsePtrOutputWithContext(ctx context.Context) SkuResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(SkuResponsePtrOutput)
}
// SKU for the resource.
type SkuResponseOutput struct{ *pulumi.OutputState }
func (SkuResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*SkuResponse)(nil)).Elem()
}
func (o SkuResponseOutput) ToSkuResponseOutput() SkuResponseOutput {
return o
}
func (o SkuResponseOutput) ToSkuResponseOutputWithContext(ctx context.Context) SkuResponseOutput {
return o
}
func (o SkuResponseOutput) ToSkuResponsePtrOutput() SkuResponsePtrOutput {
return o.ToSkuResponsePtrOutputWithContext(context.Background())
}
func (o SkuResponseOutput) ToSkuResponsePtrOutputWithContext(ctx context.Context) SkuResponsePtrOutput {
return o.ApplyT(func(v SkuResponse) *SkuResponse {
return &v
}).(SkuResponsePtrOutput)
}
// The SKU capacity.
func (o SkuResponseOutput) Capacity() pulumi.IntPtrOutput {
return o.ApplyT(func(v SkuResponse) *int { return v.Capacity }).(pulumi.IntPtrOutput)
}
// The SKU family.
func (o SkuResponseOutput) Family() pulumi.StringPtrOutput {
return o.ApplyT(func(v SkuResponse) *string { return v.Family }).(pulumi.StringPtrOutput)
}
// The SKU model.
func (o SkuResponseOutput) Model() pulumi.StringPtrOutput {
return o.ApplyT(func(v SkuResponse) *string { return v.Model }).(pulumi.StringPtrOutput)
}
// The SKU name.
func (o SkuResponseOutput) Name() pulumi.StringPtrOutput {
return o.ApplyT(func(v SkuResponse) *string { return v.Name }).(pulumi.StringPtrOutput)
}
// The SKU size.
func (o SkuResponseOutput) Size() pulumi.StringPtrOutput {
return o.ApplyT(func(v SkuResponse) *string { return v.Size }).(pulumi.StringPtrOutput)
}
// The SKU tier.
func (o SkuResponseOutput) Tier() pulumi.StringPtrOutput {
return o.ApplyT(func(v SkuResponse) *string { return v.Tier }).(pulumi.StringPtrOutput)
}
type SkuResponsePtrOutput struct{ *pulumi.OutputState }
func (SkuResponsePtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**SkuResponse)(nil)).Elem()
}
func (o SkuResponsePtrOutput) ToSkuResponsePtrOutput() SkuResponsePtrOutput {
return o
}
func (o SkuResponsePtrOutput) ToSkuResponsePtrOutputWithContext(ctx context.Context) SkuResponsePtrOutput {
return o
}
func (o SkuResponsePtrOutput) Elem() SkuResponseOutput {
return o.ApplyT(func(v *SkuResponse) SkuResponse { return *v }).(SkuResponseOutput)
}
// The SKU capacity.
func (o SkuResponsePtrOutput) Capacity() pulumi.IntPtrOutput {
return o.ApplyT(func(v *SkuResponse) *int {
if v == nil {
return nil
}
return v.Capacity
}).(pulumi.IntPtrOutput)
}
// The SKU family.
func (o SkuResponsePtrOutput) Family() pulumi.StringPtrOutput {
return o.ApplyT(func(v *SkuResponse) *string {
if v == nil {
return nil
}
return v.Family
}).(pulumi.StringPtrOutput)
}
// The SKU model.
func (o SkuResponsePtrOutput) Model() pulumi.StringPtrOutput {
return o.ApplyT(func(v *SkuResponse) *string {
if v == nil {
return nil
}
return v.Model
}).(pulumi.StringPtrOutput)
}
// The SKU name.
func (o SkuResponsePtrOutput) Name() pulumi.StringPtrOutput {
return o.ApplyT(func(v *SkuResponse) *string {
if v == nil {
return nil
}
return v.Name
}).(pulumi.StringPtrOutput)
}
// The SKU size.
func (o SkuResponsePtrOutput) Size() pulumi.StringPtrOutput {
return o.ApplyT(func(v *SkuResponse) *string {
if v == nil {
return nil
}
return v.Size
}).(pulumi.StringPtrOutput)
}
// The SKU tier.
func (o SkuResponsePtrOutput) Tier() pulumi.StringPtrOutput {
return o.ApplyT(func(v *SkuResponse) *string {
if v == nil {
return nil
}
return v.Tier
}).(pulumi.StringPtrOutput)
}
// Entity representing the reference to the template.
type TemplateLink struct {
// If included, must match the ContentVersion in the template.
ContentVersion *string `pulumi:"contentVersion"`
// The URI of the template to deploy.
Uri string `pulumi:"uri"`
}
// TemplateLinkInput is an input type that accepts TemplateLinkArgs and TemplateLinkOutput values.
// You can construct a concrete instance of `TemplateLinkInput` via:
//
// TemplateLinkArgs{...}
type TemplateLinkInput interface {
pulumi.Input
ToTemplateLinkOutput() TemplateLinkOutput
ToTemplateLinkOutputWithContext(context.Context) TemplateLinkOutput
}
// Entity representing the reference to the template.
type TemplateLinkArgs struct {
// If included, must match the ContentVersion in the template.
ContentVersion pulumi.StringPtrInput `pulumi:"contentVersion"`
// The URI of the template to deploy.
Uri pulumi.StringInput `pulumi:"uri"`
}
func (TemplateLinkArgs) ElementType() reflect.Type {
return reflect.TypeOf((*TemplateLink)(nil)).Elem()
}
func (i TemplateLinkArgs) ToTemplateLinkOutput() TemplateLinkOutput {
return i.ToTemplateLinkOutputWithContext(context.Background())
}
func (i TemplateLinkArgs) ToTemplateLinkOutputWithContext(ctx context.Context) TemplateLinkOutput {
return pulumi.ToOutputWithContext(ctx, i).(TemplateLinkOutput)
}
func (i TemplateLinkArgs) ToTemplateLinkPtrOutput() TemplateLinkPtrOutput {
return i.ToTemplateLinkPtrOutputWithContext(context.Background())
}
func (i TemplateLinkArgs) ToTemplateLinkPtrOutputWithContext(ctx context.Context) TemplateLinkPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(TemplateLinkOutput).ToTemplateLinkPtrOutputWithContext(ctx)
}
// TemplateLinkPtrInput is an input type that accepts TemplateLinkArgs, TemplateLinkPtr and TemplateLinkPtrOutput values.
// You can construct a concrete instance of `TemplateLinkPtrInput` via:
//
// TemplateLinkArgs{...}
//
// or:
//
// nil
type TemplateLinkPtrInput interface {
pulumi.Input
ToTemplateLinkPtrOutput() TemplateLinkPtrOutput
ToTemplateLinkPtrOutputWithContext(context.Context) TemplateLinkPtrOutput
}
type templateLinkPtrType TemplateLinkArgs
func TemplateLinkPtr(v *TemplateLinkArgs) TemplateLinkPtrInput {
return (*templateLinkPtrType)(v)
}
func (*templateLinkPtrType) ElementType() reflect.Type {
return reflect.TypeOf((**TemplateLink)(nil)).Elem()
}
func (i *templateLinkPtrType) ToTemplateLinkPtrOutput() TemplateLinkPtrOutput {
return i.ToTemplateLinkPtrOutputWithContext(context.Background())
}
func (i *templateLinkPtrType) ToTemplateLinkPtrOutputWithContext(ctx context.Context) TemplateLinkPtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(TemplateLinkPtrOutput)
}
// Entity representing the reference to the template.
type TemplateLinkOutput struct{ *pulumi.OutputState }
func (TemplateLinkOutput) ElementType() reflect.Type {
return reflect.TypeOf((*TemplateLink)(nil)).Elem()
}
func (o TemplateLinkOutput) ToTemplateLinkOutput() TemplateLinkOutput {
return o
}
func (o TemplateLinkOutput) ToTemplateLinkOutputWithContext(ctx context.Context) TemplateLinkOutput {
return o
}
func (o TemplateLinkOutput) ToTemplateLinkPtrOutput() TemplateLinkPtrOutput {
return o.ToTemplateLinkPtrOutputWithContext(context.Background())
}
func (o TemplateLinkOutput) ToTemplateLinkPtrOutputWithContext(ctx context.Context) TemplateLinkPtrOutput {
return o.ApplyT(func(v TemplateLink) *TemplateLink {
return &v
}).(TemplateLinkPtrOutput)
}
// If included, must match the ContentVersion in the template.
func (o TemplateLinkOutput) ContentVersion() pulumi.StringPtrOutput {
return o.ApplyT(func(v TemplateLink) *string { return v.ContentVersion }).(pulumi.StringPtrOutput)
}
// The URI of the template to deploy.
func (o TemplateLinkOutput) Uri() pulumi.StringOutput {
return o.ApplyT(func(v TemplateLink) string { return v.Uri }).(pulumi.StringOutput)
}
type TemplateLinkPtrOutput struct{ *pulumi.OutputState }
func (TemplateLinkPtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**TemplateLink)(nil)).Elem()
}
func (o TemplateLinkPtrOutput) ToTemplateLinkPtrOutput() TemplateLinkPtrOutput {
return o
}
func (o TemplateLinkPtrOutput) ToTemplateLinkPtrOutputWithContext(ctx context.Context) TemplateLinkPtrOutput {
return o
}
func (o TemplateLinkPtrOutput) Elem() TemplateLinkOutput {
return o.ApplyT(func(v *TemplateLink) TemplateLink { return *v }).(TemplateLinkOutput)
}
// If included, must match the ContentVersion in the template.
func (o TemplateLinkPtrOutput) ContentVersion() pulumi.StringPtrOutput {
return o.ApplyT(func(v *TemplateLink) *string {
if v == nil {
return nil
}
return v.ContentVersion
}).(pulumi.StringPtrOutput)
}
// The URI of the template to deploy.
func (o TemplateLinkPtrOutput) Uri() pulumi.StringPtrOutput {
return o.ApplyT(func(v *TemplateLink) *string {
if v == nil {
return nil
}
return &v.Uri
}).(pulumi.StringPtrOutput)
}
// Entity representing the reference to the template.
type TemplateLinkResponse struct {
// If included, must match the ContentVersion in the template.
ContentVersion *string `pulumi:"contentVersion"`
// The URI of the template to deploy.
Uri string `pulumi:"uri"`
}
// TemplateLinkResponseInput is an input type that accepts TemplateLinkResponseArgs and TemplateLinkResponseOutput values.
// You can construct a concrete instance of `TemplateLinkResponseInput` via:
//
// TemplateLinkResponseArgs{...}
type TemplateLinkResponseInput interface {
pulumi.Input
ToTemplateLinkResponseOutput() TemplateLinkResponseOutput
ToTemplateLinkResponseOutputWithContext(context.Context) TemplateLinkResponseOutput
}
// Entity representing the reference to the template.
type TemplateLinkResponseArgs struct {
// If included, must match the ContentVersion in the template.
ContentVersion pulumi.StringPtrInput `pulumi:"contentVersion"`
// The URI of the template to deploy.
Uri pulumi.StringInput `pulumi:"uri"`
}
func (TemplateLinkResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*TemplateLinkResponse)(nil)).Elem()
}
func (i TemplateLinkResponseArgs) ToTemplateLinkResponseOutput() TemplateLinkResponseOutput {
return i.ToTemplateLinkResponseOutputWithContext(context.Background())
}
func (i TemplateLinkResponseArgs) ToTemplateLinkResponseOutputWithContext(ctx context.Context) TemplateLinkResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(TemplateLinkResponseOutput)
}
func (i TemplateLinkResponseArgs) ToTemplateLinkResponsePtrOutput() TemplateLinkResponsePtrOutput {
return i.ToTemplateLinkResponsePtrOutputWithContext(context.Background())
}
func (i TemplateLinkResponseArgs) ToTemplateLinkResponsePtrOutputWithContext(ctx context.Context) TemplateLinkResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(TemplateLinkResponseOutput).ToTemplateLinkResponsePtrOutputWithContext(ctx)
}
// TemplateLinkResponsePtrInput is an input type that accepts TemplateLinkResponseArgs, TemplateLinkResponsePtr and TemplateLinkResponsePtrOutput values.
// You can construct a concrete instance of `TemplateLinkResponsePtrInput` via:
//
// TemplateLinkResponseArgs{...}
//
// or:
//
// nil
type TemplateLinkResponsePtrInput interface {
pulumi.Input
ToTemplateLinkResponsePtrOutput() TemplateLinkResponsePtrOutput
ToTemplateLinkResponsePtrOutputWithContext(context.Context) TemplateLinkResponsePtrOutput
}
type templateLinkResponsePtrType TemplateLinkResponseArgs
func TemplateLinkResponsePtr(v *TemplateLinkResponseArgs) TemplateLinkResponsePtrInput {
return (*templateLinkResponsePtrType)(v)
}
func (*templateLinkResponsePtrType) ElementType() reflect.Type {
return reflect.TypeOf((**TemplateLinkResponse)(nil)).Elem()
}
func (i *templateLinkResponsePtrType) ToTemplateLinkResponsePtrOutput() TemplateLinkResponsePtrOutput {
return i.ToTemplateLinkResponsePtrOutputWithContext(context.Background())
}
func (i *templateLinkResponsePtrType) ToTemplateLinkResponsePtrOutputWithContext(ctx context.Context) TemplateLinkResponsePtrOutput {
return pulumi.ToOutputWithContext(ctx, i).(TemplateLinkResponsePtrOutput)
}
// Entity representing the reference to the template.
type TemplateLinkResponseOutput struct{ *pulumi.OutputState }
func (TemplateLinkResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*TemplateLinkResponse)(nil)).Elem()
}
func (o TemplateLinkResponseOutput) ToTemplateLinkResponseOutput() TemplateLinkResponseOutput {
return o
}
func (o TemplateLinkResponseOutput) ToTemplateLinkResponseOutputWithContext(ctx context.Context) TemplateLinkResponseOutput {
return o
}
func (o TemplateLinkResponseOutput) ToTemplateLinkResponsePtrOutput() TemplateLinkResponsePtrOutput {
return o.ToTemplateLinkResponsePtrOutputWithContext(context.Background())
}
func (o TemplateLinkResponseOutput) ToTemplateLinkResponsePtrOutputWithContext(ctx context.Context) TemplateLinkResponsePtrOutput {
return o.ApplyT(func(v TemplateLinkResponse) *TemplateLinkResponse {
return &v
}).(TemplateLinkResponsePtrOutput)
}
// If included, must match the ContentVersion in the template.
func (o TemplateLinkResponseOutput) ContentVersion() pulumi.StringPtrOutput {
return o.ApplyT(func(v TemplateLinkResponse) *string { return v.ContentVersion }).(pulumi.StringPtrOutput)
}
// The URI of the template to deploy.
func (o TemplateLinkResponseOutput) Uri() pulumi.StringOutput {
return o.ApplyT(func(v TemplateLinkResponse) string { return v.Uri }).(pulumi.StringOutput)
}
type TemplateLinkResponsePtrOutput struct{ *pulumi.OutputState }
func (TemplateLinkResponsePtrOutput) ElementType() reflect.Type {
return reflect.TypeOf((**TemplateLinkResponse)(nil)).Elem()
}
func (o TemplateLinkResponsePtrOutput) ToTemplateLinkResponsePtrOutput() TemplateLinkResponsePtrOutput {
return o
}
func (o TemplateLinkResponsePtrOutput) ToTemplateLinkResponsePtrOutputWithContext(ctx context.Context) TemplateLinkResponsePtrOutput {
return o
}
func (o TemplateLinkResponsePtrOutput) Elem() TemplateLinkResponseOutput {
return o.ApplyT(func(v *TemplateLinkResponse) TemplateLinkResponse { return *v }).(TemplateLinkResponseOutput)
}
// If included, must match the ContentVersion in the template.
func (o TemplateLinkResponsePtrOutput) ContentVersion() pulumi.StringPtrOutput {
return o.ApplyT(func(v *TemplateLinkResponse) *string {
if v == nil {
return nil
}
return v.ContentVersion
}).(pulumi.StringPtrOutput)
}
// The URI of the template to deploy.
func (o TemplateLinkResponsePtrOutput) Uri() pulumi.StringPtrOutput {
return o.ApplyT(func(v *TemplateLinkResponse) *string {
if v == nil {
return nil
}
return &v.Uri
}).(pulumi.StringPtrOutput)
}
type ZoneMappingResponse struct {
// The location of the zone mapping.
Location *string `pulumi:"location"`
Zones []string `pulumi:"zones"`
}
// ZoneMappingResponseInput is an input type that accepts ZoneMappingResponseArgs and ZoneMappingResponseOutput values.
// You can construct a concrete instance of `ZoneMappingResponseInput` via:
//
// ZoneMappingResponseArgs{...}
type ZoneMappingResponseInput interface {
pulumi.Input
ToZoneMappingResponseOutput() ZoneMappingResponseOutput
ToZoneMappingResponseOutputWithContext(context.Context) ZoneMappingResponseOutput
}
type ZoneMappingResponseArgs struct {
// The location of the zone mapping.
Location pulumi.StringPtrInput `pulumi:"location"`
Zones pulumi.StringArrayInput `pulumi:"zones"`
}
func (ZoneMappingResponseArgs) ElementType() reflect.Type {
return reflect.TypeOf((*ZoneMappingResponse)(nil)).Elem()
}
func (i ZoneMappingResponseArgs) ToZoneMappingResponseOutput() ZoneMappingResponseOutput {
return i.ToZoneMappingResponseOutputWithContext(context.Background())
}
func (i ZoneMappingResponseArgs) ToZoneMappingResponseOutputWithContext(ctx context.Context) ZoneMappingResponseOutput {
return pulumi.ToOutputWithContext(ctx, i).(ZoneMappingResponseOutput)
}
// ZoneMappingResponseArrayInput is an input type that accepts ZoneMappingResponseArray and ZoneMappingResponseArrayOutput values.
// You can construct a concrete instance of `ZoneMappingResponseArrayInput` via:
//
// ZoneMappingResponseArray{ ZoneMappingResponseArgs{...} }
type ZoneMappingResponseArrayInput interface {
pulumi.Input
ToZoneMappingResponseArrayOutput() ZoneMappingResponseArrayOutput
ToZoneMappingResponseArrayOutputWithContext(context.Context) ZoneMappingResponseArrayOutput
}
type ZoneMappingResponseArray []ZoneMappingResponseInput
func (ZoneMappingResponseArray) ElementType() reflect.Type {
return reflect.TypeOf((*[]ZoneMappingResponse)(nil)).Elem()
}
func (i ZoneMappingResponseArray) ToZoneMappingResponseArrayOutput() ZoneMappingResponseArrayOutput {
return i.ToZoneMappingResponseArrayOutputWithContext(context.Background())
}
func (i ZoneMappingResponseArray) ToZoneMappingResponseArrayOutputWithContext(ctx context.Context) ZoneMappingResponseArrayOutput {
return pulumi.ToOutputWithContext(ctx, i).(ZoneMappingResponseArrayOutput)
}
type ZoneMappingResponseOutput struct{ *pulumi.OutputState }
func (ZoneMappingResponseOutput) ElementType() reflect.Type {
return reflect.TypeOf((*ZoneMappingResponse)(nil)).Elem()
}
func (o ZoneMappingResponseOutput) ToZoneMappingResponseOutput() ZoneMappingResponseOutput {
return o
}
func (o ZoneMappingResponseOutput) ToZoneMappingResponseOutputWithContext(ctx context.Context) ZoneMappingResponseOutput {
return o
}
// The location of the zone mapping.
func (o ZoneMappingResponseOutput) Location() pulumi.StringPtrOutput {
return o.ApplyT(func(v ZoneMappingResponse) *string { return v.Location }).(pulumi.StringPtrOutput)
}
func (o ZoneMappingResponseOutput) Zones() pulumi.StringArrayOutput {
return o.ApplyT(func(v ZoneMappingResponse) []string { return v.Zones }).(pulumi.StringArrayOutput)
}
type ZoneMappingResponseArrayOutput struct{ *pulumi.OutputState }
func (ZoneMappingResponseArrayOutput) ElementType() reflect.Type {
return reflect.TypeOf((*[]ZoneMappingResponse)(nil)).Elem()
}
func (o ZoneMappingResponseArrayOutput) ToZoneMappingResponseArrayOutput() ZoneMappingResponseArrayOutput {
return o
}
func (o ZoneMappingResponseArrayOutput) ToZoneMappingResponseArrayOutputWithContext(ctx context.Context) ZoneMappingResponseArrayOutput {
return o
}
func (o ZoneMappingResponseArrayOutput) Index(i pulumi.IntInput) ZoneMappingResponseOutput {
return pulumi.All(o, i).ApplyT(func(vs []interface{}) ZoneMappingResponse {
return vs[0].([]ZoneMappingResponse)[vs[1].(int)]
}).(ZoneMappingResponseOutput)
}
func init() {
pulumi.RegisterOutputType(AliasPathTypeResponseOutput{})
pulumi.RegisterOutputType(AliasPathTypeResponseArrayOutput{})
pulumi.RegisterOutputType(AliasTypeResponseOutput{})
pulumi.RegisterOutputType(AliasTypeResponseArrayOutput{})
pulumi.RegisterOutputType(BasicDependencyResponseOutput{})
pulumi.RegisterOutputType(BasicDependencyResponseArrayOutput{})
pulumi.RegisterOutputType(DebugSettingOutput{})
pulumi.RegisterOutputType(DebugSettingPtrOutput{})
pulumi.RegisterOutputType(DebugSettingResponseOutput{})
pulumi.RegisterOutputType(DebugSettingResponsePtrOutput{})
pulumi.RegisterOutputType(DependencyResponseOutput{})
pulumi.RegisterOutputType(DependencyResponseArrayOutput{})
pulumi.RegisterOutputType(DeploymentPropertiesOutput{})
pulumi.RegisterOutputType(DeploymentPropertiesPtrOutput{})
pulumi.RegisterOutputType(DeploymentPropertiesExtendedResponseOutput{})
pulumi.RegisterOutputType(DeploymentPropertiesExtendedResponsePtrOutput{})
pulumi.RegisterOutputType(IdentityOutput{})
pulumi.RegisterOutputType(IdentityPtrOutput{})
pulumi.RegisterOutputType(IdentityResponseOutput{})
pulumi.RegisterOutputType(IdentityResponsePtrOutput{})
pulumi.RegisterOutputType(IdentityResponseUserAssignedIdentitiesOutput{})
pulumi.RegisterOutputType(IdentityResponseUserAssignedIdentitiesMapOutput{})
pulumi.RegisterOutputType(OnErrorDeploymentOutput{})
pulumi.RegisterOutputType(OnErrorDeploymentPtrOutput{})
pulumi.RegisterOutputType(OnErrorDeploymentExtendedResponseOutput{})
pulumi.RegisterOutputType(OnErrorDeploymentExtendedResponsePtrOutput{})
pulumi.RegisterOutputType(ParametersLinkOutput{})
pulumi.RegisterOutputType(ParametersLinkPtrOutput{})
pulumi.RegisterOutputType(ParametersLinkResponseOutput{})
pulumi.RegisterOutputType(ParametersLinkResponsePtrOutput{})
pulumi.RegisterOutputType(PlanOutput{})
pulumi.RegisterOutputType(PlanPtrOutput{})
pulumi.RegisterOutputType(PlanResponseOutput{})
pulumi.RegisterOutputType(PlanResponsePtrOutput{})
pulumi.RegisterOutputType(ProviderResourceTypeResponseOutput{})
pulumi.RegisterOutputType(ProviderResourceTypeResponseArrayOutput{})
pulumi.RegisterOutputType(ProviderResponseOutput{})
pulumi.RegisterOutputType(ProviderResponseArrayOutput{})
pulumi.RegisterOutputType(ResourceGroupPropertiesResponseOutput{})
pulumi.RegisterOutputType(ResourceGroupPropertiesResponsePtrOutput{})
pulumi.RegisterOutputType(SkuOutput{})
pulumi.RegisterOutputType(SkuPtrOutput{})
pulumi.RegisterOutputType(SkuResponseOutput{})
pulumi.RegisterOutputType(SkuResponsePtrOutput{})
pulumi.RegisterOutputType(TemplateLinkOutput{})
pulumi.RegisterOutputType(TemplateLinkPtrOutput{})
pulumi.RegisterOutputType(TemplateLinkResponseOutput{})
pulumi.RegisterOutputType(TemplateLinkResponsePtrOutput{})
pulumi.RegisterOutputType(ZoneMappingResponseOutput{})
pulumi.RegisterOutputType(ZoneMappingResponseArrayOutput{})
}
| {
return nil
} |
plugins.py | import re
import time
import typing
import logging
from calendar import monthrange
from datetime import datetime
from collections import Iterable
from heapq import heappush, heappop
from . import types # noqa
from . exceptions import BrokerError
from . interfaces import App, Plugin, Logger
from . utils import cached_property, rewind
class MasterLogger(Plugin):
def __init__(self,
logger: typing.Union[logging.Logger, Logger],
**kwargs) -> None:
self.logger = logger
def register_master_handlers(self):
level = self.logger.level
ret = {}
if level <= logging.ERROR:
ret['task_exception'] = self.on_task_exception
ret['task_unknown'] = self.on_task_unknown
ret['worker_error'] = self.on_worker_error
ret['broker_error'] = self.on_broker_error
if level <= logging.INFO:
ret['worker_start'] = self.on_worker_start
ret['task_start'] = self.on_task_start
ret['task_done'] = self.on_task_done
ret['task_interrupt'] = self.on_task_interrupt
if level <= logging.DEBUG:
ret['task_expires'] = self.on_task_expires
return ret
def on_worker_start(self, w, **kwargs):
self.logger.info('worker process [%d] started.', w.pid)
def on_task_start(self, w, task_name, task_request, **kwargs):
self.logger.info('[%d] - received task: %s[%s].',
w.pid, task_name, task_request['id'])
def on_task_done(self, w, task_name, task_request, running_time, **kwargs):
self.logger.info('[%d] - task %s[%s] successed in %ss.',
w.pid, task_name, task_request['id'], running_time)
def on_task_interrupt(self, w, task_name, task_request, running_time,
**kwargs):
self.logger.info('[%d] - task %s[%s] killed in %ss.',
w.pid, task_name, task_request['id'], running_time)
def on_task_expires(self, w, task_name, task_request, **kwargs):
self.logger.debug('[%d] - task %s[%s] expires.',
w.pid, task_name, task_request['id'])
def on_task_unknown(self, w, task_name, **kwargs):
self.logger.error('[%d] - received unregistered task `%s`.',
w.pid, task_name)
def on_task_exception(self, w, task_name, task_request, exc, traceback,
running_time, **kwargs):
self.logger.error('[%d] - task %s[%s] raised exception: %s\n%s',
w.pid, task_name, task_request['id'], repr(exc),
traceback)
def on_broker_error(self, w, **kwargs):
self.logger.error('[%d] - broker error', w.pid)
def on_worker_error(self, w, exc, traceback, **kwargs):
self.logger.error('[%d] - got exception: %s\n%s',
w.pid, repr(exc), traceback)
class TaskKiller(Plugin):
def __init__(self,
app: App,
logger: typing.Union[logging.Logger, Logger],
**kwargs) -> None:
self.app = app
self.logger = logger
self.running_tasks = set() # type: typing.Set[types.TaskId]
self.heap = [] # type: typing.List[typing.Tuple[float, types.TaskId]]
def run_in_master(self, curtime):
if not self.heap:
return
while self.heap and self.heap[0][0] <= curtime:
tm, task_id = heappop(self.heap)
if task_id not in self.running_tasks:
continue
self.logger.debug('[taskkiller] - kill task %s due to time limit',
task_id)
if self.heap:
return self.heap[0][0] - time.time()
def on_task_start(self, w,
task_name,
task_id,
task_headers,
start_time,
**kwargs):
limit = task_headers.get('time_limit')
if limit is None:
return
self.running_tasks.add(task_id)
heappush(self.heap, (start_time + limit, task_id))
def on_task_done(self, w, task_name, task_id):
if task_id not in self.running_tasks:
return
self.running_tasks.remove(task_id)
class CronBeat(Plugin):
def __init__(self,
app: App,
schedule: str,
error_timeout: int,
logger: typing.Union[logging.Logger, Logger],
**kwargs) -> None:
self.app = app
self.logger = logger
self.error_timeout = error_timeout
self.schedule = schedule
self.next_run = 0
@classmethod
def add_console_args(cls, parser) -> None:
parser.add_argument('--schedule',
dest='schedule',
default='schedule.py',
help='Schedule rules')
def get_applied_conf(self):
return {
'schedule': self.schedule
}
@cached_property
def heap(self):
dct = {'crontab': crontab}
with open(self.schedule, 'rt') as f:
rules = eval(f.read(), dct)
if not isinstance(rules, dict):
raise TypeError('Must be a dict')
start = datetime.now()
heap = []
for key, entry in rules.items():
if not entry.get('task'):
raise TypeError('`task` must be set')
schedule = entry.get('schedule')
if not isinstance(schedule, crontab):
raise TypeError('`schedule` must be a crontab')
schedule = schedule.start(start)
heappush(heap, (next(schedule).timestamp(), schedule, entry))
return heap
def master_idle(self, curtime):
if not self.heap:
return
if self.next_run > curtime:
return self.next_run - curtime
task_sent = False
while self.heap and self.heap[0][0] <= curtime:
_, schedule, entry = self.heap[0]
try:
self.app.send_task(entry['task'],
args=entry.get('args', ()),
kwargs=entry.get('kwargs', {}))
except BrokerError:
self.logger.error('[beat] - cant send task, retry in %ss.',
self.error_timeout)
self.next_run = self.error_timeout + curtime
return self.error_timeout
else:
self.logger.debug('[beat] - %s sent.', entry['task'])
heappop(self.heap)
heappush(self.heap, (
next(schedule).timestamp(), schedule, entry))
task_sent = True
if self.heap:
self.next_run = self.heap[0][0]
timeout = self.next_run - curtime
if task_sent:
self.logger.debug('[beat] - next task in %fs.', timeout)
return timeout
class crontab_parser:
"""Parser for Crontab expressions."""
_range = r'(\d+?)-(\d+)'
_steps = r'/(\d+)'
_number = r'(\d+)'
_star = r'\*'
def __init__(self, min_, max_):
self.max_ = max_
self.min_ = min_
self.pats = (
(re.compile('^' + self._range + self._steps + '$'),
self._range_steps),
(re.compile('^' + self._range + '$'),
self._expand_range),
(re.compile('^' + self._star + self._steps + '$'),
self._star_steps),
(re.compile('^' + self._star + '$'),
self._expand_star),
(re.compile('^' + self._number + '$'),
self._expand_range)
)
def parse(self, spec):
acc = set()
for part in spec.split(','):
if not part:
raise ValueError('empty part')
acc |= set(self._parse_part(part))
return sorted(acc)
def _parse_part(self, part):
for regex, handler in self.pats:
m = regex.match(part)
if m:
return handler(m.groups())
raise ValueError('invalid filter: %r' % part)
def _expand_range(self, toks):
fr = self._expand_number(toks[0])
if len(toks) > 1:
to = self._expand_number(toks[1])
if to < fr:
raise ValueError('invalid range')
return list(range(fr, to + 1))
return [fr]
def _range_steps(self, toks):
if len(toks) != 3 or not toks[2]:
raise ValueError('empty filter')
return self._expand_range(toks[:2])[::int(toks[2])]
def _star_steps(self, toks):
if not toks or not toks[0]:
raise ValueError('empty filter')
return self._expand_star()[::int(toks[0])]
def _expand_star(self, *args):
return list(range(self.min_, self.max_ + self.min_ + 1))
def _expand_number(self, s):
try:
i = int(s)
except ValueError:
raise ValueError('invalid number: %r' % s)
if i > self.max_:
raise ValueError(
'invalid end range: {0} > {1}.'.format(i, self.max_))
if i < self.min_:
raise ValueError(
'invalid beginning range: {0} < {1}.'.format(i, self.min_))
return i
class crontab:
def __init__(self,
minute='*',
hour='*',
day_of_month='*',
month_of_year='*',
day_of_week='*'):
self._orig_minute = minute
self._orig_hour = hour
self._orig_day_of_week = day_of_week
self._orig_day_of_month = day_of_month
self._orig_month_of_year = month_of_year
self.hour = self._expand_spec(hour, 0, 23)
self.minute = self._expand_spec(minute, 0, 59)
self.day_of_week = self._expand_spec(day_of_week, 0, 6)
self.day_of_month = self._expand_spec(day_of_month, 1, 31)
self.month_of_year = self._expand_spec(month_of_year, 1, 12)
def __repr__(self):
|
@staticmethod
def _expand_spec(cronspec, min_, max_):
"""Expand cron specification."""
if isinstance(cronspec, int):
result = [cronspec]
elif isinstance(cronspec, str):
result = crontab_parser(min_, max_).parse(cronspec)
elif isinstance(cronspec, (list, tuple, set)):
result = sorted(cronspec)
elif isinstance(cronspec, Iterable):
result = sorted(cronspec)
else:
raise TypeError("Argument cronspec needs to be of any of the "
"following types: int, str, or an iterable type. "
"%r was given." % type(cronspec))
for number in result:
if not isinstance(number, int):
raise ValueError("Argument cronspec needs to be an int: "
"%r was given." % type(number))
for number in [result[0], result[-1]]:
if result[0] < min_ or result[0] > max_:
raise ValueError(
"Invalid crontab pattern. Valid range is {%d}-{%d}. "
"'%r' was found." % (min_, max_, result[0]))
return result
def start(self, start_date=None):
y = start_date.year
complete, (month_of_year, day_of_month, hour, minute) = rewind(
start_date.timetuple()[1:5], (
self.month_of_year,
self.day_of_month,
self.hour,
self.minute
))
if complete:
y += 1
while 1:
for m in month_of_year:
max_d = monthrange(y, m)[1]
for d in day_of_month:
if d > max_d:
break
for h in hour:
for mi in minute:
yield datetime(y, m, d, h, mi)
minute = self.minute
hour = self.hour
day_of_month = self.day_of_month
month_of_year = self.month_of_year
y += 1
| return ('<crontab: {0._orig_minute} {0._orig_hour} '
'{0._orig_day_of_week} {0._orig_day_of_month} '
'{0._orig_month_of_year}>').format(self) |
funcmap.go | //
// Copyright (C) 2019 Masatoshi Fukunaga
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
// Created by Masatoshi Fukunaga on 19/02/28
//
package theme
import (
"fmt"
"net/url"
"reflect"
"text/template"
)
func indirectInterface(v reflect.Value) reflect.Value {
if v.Kind() != reflect.Interface |
if v.IsNil() {
return reflect.Value{}
}
return v.Elem()
}
func fnIndirect(arg reflect.Value) reflect.Value {
return reflect.Indirect(arg)
}
func fnSlice(arg reflect.Value, s, e int) (reflect.Value, error) {
v := indirectInterface(arg)
if !v.IsValid() {
return reflect.Value{}, fmt.Errorf("index of untyped nil")
}
switch v.Kind() {
case reflect.Array, reflect.Slice, reflect.String:
n := v.Len()
if s < 0 {
s = 0
} else if s > n {
s = n
}
if e < 0 {
e = n
} else if e > n {
e = n
}
return v.Slice(s, e), nil
default:
return reflect.Value{}, fmt.Errorf("can't index item of type %s", v.Type())
}
}
func fnEscapePath(str string) string {
return url.PathEscape(str)
}
var defaultFuncMap = template.FuncMap{
"indirect": fnIndirect,
"slice": fnSlice,
"escapePath": fnEscapePath,
}
| {
return v
} |
store.go | package store
import "errors"
var urls []string
func Get(id int) (string, error) {
if (id - 1 >= len(urls)) |
return urls[id - 1], nil
}
func GetSize() int {
return len(urls)
}
func Put(url string) {
urls = append(urls, url)
}
| {
return "", errors.New("Not found")
} |
server.py | import uvicorn
class | (uvicorn.Server):
async def startup(self, sockets=None):
await super().startup(sockets=sockets)
for f in self.config.loaded_app.startup_funcs:
await f()
async def shutdown(self, sockets=None):
await super().shutdown(sockets=sockets)
for f in self.config.loaded_app.shutdown_funcs:
await f()
| Server |
context.go | package ginx
import (
"context"
"fmt"
"github.com/gin-gonic/gin"
)
var (
GinContextKey = "_GinCtxKey"
)
// GinContextToContext stores gin.Context in c.Request.Context
func GinContextToHttpContext(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), GinContextKey, c)
c.Request = c.Request.WithContext(ctx)
c.Next()
}
// GetGinContext gets gin.Context from context.Context
func GetGinContext(ctx context.Context) (*gin.Context, error) {
ginCtx := ctx.Value(GinContextKey)
if ginCtx == nil {
err := fmt.Errorf("could not retrieve gin.Context by %s", GinContextKey)
return nil, err
}
gc, ok := ginCtx.(*gin.Context)
if !ok {
err := fmt.Errorf("gin.Context has wrong type: %T", ginCtx)
return nil, err | }
func MustGetGinContext(ctx context.Context) *gin.Context {
gc, err := GetGinContext(ctx)
if err != nil {
panic(err)
}
return gc
} | }
return gc, nil |
button.component.ts | import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
@Component({
selector: 'app-button',
template: `
<!-- <button (click)= "handleRock()" > Rock </button>
<button (click)= "handlePaper()"> Paper </button>
<button (click)= "handleScissors()"> Scissors </button>
<p>{{mychoice}}</p> -->
<ng-content></ng-content>
`,
styles: [
`
button{
margin: 0;
position: relative;
left:40%;
height: 50px;
width: 100px;
}
`
]
})
export class | implements OnInit {
constructor() { }
// @Input('myChoice') myChoice :string = ''
// @Input('choice') choice :string = ''
// @Input('computerChoice') computerChoice :string = ''
// @Input('myArray') myArray :string = ''
// @Input('compare') compare :string = ''
// handleRock(){
// this.myChoice = choice.Rock
// this.computerChoice = this.myArray[Math.floor(Math.random()*this.myArray.length)];
// this.compare()
// }
// handlePaper(){
// this.myChoice = choice.Paper
// this.computerChoice = this.myArray[Math.floor(Math.random()*this.myArray.length)];
// this.compare()
// }
// handleScissors(){
// this.myChoice = choice.Scissors
// this.computerChoice = this.myArray[Math.floor(Math.random()*this.myArray.length)];
// this.compare()
// }
ngOnInit(): void {
}
}
| ButtonComponent |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.