code stringlengths 1 25.8M | language stringclasses 18 values | source stringclasses 4 values | repo stringclasses 78 values | path stringlengths 0 268 |
|---|---|---|---|---|
#ifndef DIRENT_H
#define DIRENT_H
typedef struct DIR DIR;
#define DT_UNKNOWN 0
#define DT_DIR 1
#define DT_REG 2
#define DT_LNK 3
struct dirent {
unsigned char d_type; /* file type to prevent lstat after readdir */
char d_name[MAX_PATH * 3]; /* file name (* 3 for UTF-8 conversion) */
};
DIR *opendir(const char *dirname);
struct dirent *readdir(DIR *dir);
int closedir(DIR *dir);
#endif /* DIRENT_H */ | c | github | https://github.com/git/git | compat/win32/dirent.h |
import numpy as np
import sympy as sp
def make(obj, exp):
for arg in range(obj.args):
print(arg.random())
class Addition(object):
def __init__(self):
self.args = [None] * 2
self.solution = None
def __getitem__(self, key):
return self.args[key]
def __setitem__(self, key, value):
self.args[key] = value
self.solve()
def __repr__(self):
pass
def make(self, addends, solution):
pass
def solve(self):
try:
self.solution = self.args[0] + self.args[1]
except TypeError:
pass
def expression(self):
return '%s + %s' % (sp.latex(self.args[0]), sp.latex(self.args[1]))
def equation(self, x=None):
s = '%s + %s = ' % (sp.latex(self.args[0]), sp.latex(self.args[1]))
if x is None:
return s
s += sp.latex(x)
return s
def solved(self):
return '%s + %s = %s' % (sp.latex(self.args[0]), sp.latex(self.args[1]), sp.latex(self.solution))
class Random(object):
def __call__(cls, min, max, dx):
return None
class Uniform(Random):
def __call__(cls, min, max, dx):
return np.random.rand() * (max - min) + min
class UniformInteger(Uniform):
def __call__(cls, min, max, dx):
return int(np.random.rand() * (max - min) / dx) * dx + min
class Number(object):
base = 10
min = None
max = None
dx = 1.
features = None
def __init__(self):
self.features = set()
self._random = Random()
def __iter__(self):
self.n = None
return self
def __next__(self):
if self.n is None:
self.n = self.min
else:
self.n += self.step
if self.n == self.max:
raise StopIteration
return self.n
def random(self):
"""
dist: generate a random variable on a distribution of [0, 1)
"""
return self._random(self.min, self.max, self.step)
def __repr__(self):
return '<%s %s-%s>' % (self.__class__.__name__, self.min, self.max)
def SingleDigit(obj=None):
obj.min = 0
obj.max = obj.base
obj.step = 1
obj.features.add('SingleDigit')
if issubclass(UniformInteger, obj._random.__class__):
obj._random = UniformInteger()
else:
raise Exception("Tried to subclass to UniformInteger from %s" % obj._random.__class__.__name__)
return obj
def addition2(limit):
a = int(np.random.randint(0, limit))
b = int(np.random.randint(0, limit))
if np.random.rand() < 0.9:
ques = "%d + %d = " % (a, b)
else:
ques = "%d more than %d = " % (a, b)
sol = a + b
q = Question(ques, sol)
return q
def subtraction(limit):
a = int(np.random.randint(0, limit))
b = int(np.random.randint(0, limit))
a, b = max([a, b]), min([a, b])
if np.random.rand() < 0.9:
ques = "%d - %d = " % (a, b)
else:
ques = "Take %d away from %d = " % (b, a)
sol = a - b
q = Question(ques, sol)
return q
def multiplication(limit):
a = int(np.random.randint(0, limit))
b = int(np.random.randint(0, limit))
if np.random.rand() < 0.9:
ques = "%d x %d = " % (a, b)
else:
ques = "%d groups of %d = " % (a, b)
sol = a * b
q = Question(ques, sol)
return q | unknown | codeparrot/codeparrot-clean | ||
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""
Counts words in new text files created in the given directory
Usage: hdfs_wordcount.py <directory>
<directory> is the directory that Spark Streaming will use to find and read new text files.
To run this on your local machine on directory `localdir`, run this example
$ bin/spark-submit examples/src/main/python/streaming/hdfs_wordcount.py localdir
Then create a text file in `localdir` and the words in the file will get counted.
"""
from __future__ import print_function
import sys
from pyspark import SparkContext
from pyspark.streaming import StreamingContext
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: hdfs_wordcount.py <directory>", file=sys.stderr)
exit(-1)
sc = SparkContext(appName="PythonStreamingHDFSWordCount")
ssc = StreamingContext(sc, 1)
lines = ssc.textFileStream(sys.argv[1])
counts = lines.flatMap(lambda line: line.split(" "))\
.map(lambda x: (x, 1))\
.reduceByKey(lambda a, b: a+b)
counts.pprint()
ssc.start()
ssc.awaitTermination() | unknown | codeparrot/codeparrot-clean | ||
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from collections import namedtuple
from contextlib import contextmanager
from pants.java.executor import SubprocessExecutor
from pants.util.contextutil import open_zip, temporary_file
# TODO(John Sirois): Support shading given an input jar and a set of user-supplied rules (these
# will come from target attributes) instead of only supporting auto-generating rules from the main
# class of the input jar.
class Shader(object):
"""Creates shaded jars."""
class Error(Exception):
"""Indicates an error shading a jar."""
class Rule(namedtuple('Rule', ['from_pattern', 'to_pattern'])):
"""Represents a transformation rule for a jar shading session."""
def render(self):
return 'rule {0} {1}\n'.format(self.from_pattern, self.to_pattern)
SHADE_PREFIX = '__shaded_by_pants__.'
"""The shading package."""
@classmethod
def _package_rule(cls, package_name=None, recursive=False, shade=False):
args = dict(package=package_name,
capture='**' if recursive else '*',
dest_prefix=cls.SHADE_PREFIX if shade else '')
if package_name:
return cls.Rule(from_pattern='{package}.{capture}'.format(**args),
to_pattern='{dest_prefix}{package}.@1'.format(**args))
else:
return cls.Rule(from_pattern='{capture}'.format(**args),
to_pattern='{dest_prefix}@1'.format(**args))
@classmethod
def _class_rule(cls, class_name, shade=False):
args = dict(class_name=class_name,
dest_prefix=cls.SHADE_PREFIX if shade else '')
return cls.Rule(from_pattern=class_name, to_pattern='{dest_prefix}{class_name}'.format(**args))
@classmethod
def exclude_package(cls, package_name=None, recursive=False):
"""Excludes the given fully qualified package name from shading.
:param unicode package_name: A fully qualified package_name; eg: `org.pantsbuild`; `None` for
the java default (root) package.
:param bool recursive: `True` to exclude any package with `package_name` as a proper prefix;
`False` by default.
:returns: A `Shader.Rule` describing the shading exclusion.
"""
return cls._package_rule(package_name, recursive, shade=False)
@classmethod
def exclude_class(cls, class_name):
"""Excludes the given fully qualified class name from shading.
:param unicode class_name: A fully qualified classname, eg: `org.pantsbuild.tools.jar.Main`.
:returns: A `Shader.Rule` describing the shading exclusion.
"""
return cls._class_rule(class_name, shade=False)
@classmethod
def shade_package(cls, package_name=None, recursive=False):
"""Includes the given fully qualified package name in shading.
:param unicode package_name: A fully qualified package_name; eg: `org.pantsbuild`; `None` for
the java default (root) package.
:param bool recursive: `True` to include any package with `package_name` as a proper prefix;
`False` by default.
:returns: A `Shader.Rule` describing the packages to be shaded.
"""
return cls._package_rule(package_name, recursive, shade=True)
@classmethod
def shade_class(cls, class_name):
"""Includes the given fully qualified class in shading.
:param unicode class_name: A fully qualified classname, eg: `org.pantsbuild.tools.jar.Main`.
:returns: A `Shader.Rule` describing the class shading.
"""
return cls._class_rule(class_name, shade=True)
@staticmethod
def _iter_packages(paths):
for path in paths:
yield path.replace('/', '.')
@staticmethod
def _potential_package_path(path):
# TODO(John Sirois): Implement a full valid java package name check, `-` just happens to get
# the common non-package cases like META-INF/...
return path.endswith('.class') or path.endswith('.java') and '-' not in path
@classmethod
def _iter_dir_packages(cls, path):
paths = set()
for root, dirs, files in os.walk(path):
for filename in files:
if cls._potential_package_path(filename):
package_path = os.path.dirname(os.path.join(root, filename))
paths.add(os.path.relpath(package_path, path))
return cls._iter_packages(paths)
@classmethod
def _iter_jar_packages(cls, path):
with open_zip(path) as jar:
paths = set()
for pathname in jar.namelist():
if cls._potential_package_path(pathname):
paths.add(os.path.dirname(pathname))
return cls._iter_packages(paths)
def __init__(self, jarjar, executor=None):
"""Creates a `Shader` the will use the given `jarjar` jar to create shaded jars.
:param unicode jarjar: The path to the jarjar jar.
:param executor: An optional java `Executor` to use to create shaded jar files. Defaults to a
`SubprocessExecutor` that uses the default java distribution.
"""
self._jarjar = jarjar
self._executor = executor or SubprocessExecutor()
self._system_packages = None
def _calculate_system_packages(self):
system_packages = set()
boot_classpath = self._executor.distribution.system_properties['sun.boot.class.path']
for path in boot_classpath.split(os.pathsep):
if os.path.exists(path):
if os.path.isdir(path):
system_packages.update(self._iter_dir_packages(path))
else:
system_packages.update(self._iter_jar_packages(path))
return system_packages
@property
def system_packages(self):
if self._system_packages is None:
self._system_packages = self._calculate_system_packages()
return self._system_packages
def assemble_binary_rules(self, main, jar, custom_rules=None):
"""Creates an ordered list of rules suitable for fully shading the given binary.
The default rules will ensure the `main` class name is un-changed along with a minimal set of
support classes but that everything else will be shaded.
Any `custom_rules` are given highest precedence and so they can interfere with this automatic
binary shading. In general it's safe to add exclusion rules to open up classes that need to be
shared between the binary and the code it runs over. An example would be excluding the
`org.junit.Test` annotation class from shading since a tool running junit needs to be able
to scan for this annotation inside the user code it tests.
:param unicode main: The main class to preserve as the entry point.
:param unicode jar: The path of the binary jar the `main` class lives in.
:param list custom_rules: An optional list of custom `Shader.Rule`s.
:returns: a precedence-ordered list of `Shader.Rule`s
"""
# If a class is matched by multiple rules, the 1st lexical match wins (see:
# https://code.google.com/p/jarjar/wiki/CommandLineDocs#Rules_file_format).
# As such we 1st ensure the `main` package and the jre packages have exclusion rules and
# then apply a final set of shading rules to everything else at lowest precedence.
# Custom rules take precedence.
rules = list(custom_rules or [])
# Exclude the main entrypoint's package from shading. There may be package-private classes that
# the main class accesses so we must preserve the whole package).
parts = main.rsplit('.', 1)
if len(parts) == 2:
main_package = parts[0]
else:
# There is no package component, so the main class is in the root (default) package.
main_package = None
rules.append(self.exclude_package(main_package))
rules.extend(self.exclude_package(system_pkg) for system_pkg in sorted(self.system_packages))
# Shade everything else.
#
# NB: A simpler way to do this jumps out - just emit 1 wildcard rule:
#
# rule **.* _shaded_.@1.@2
#
# Unfortunately, as of jarjar 1.4 this wildcard catch-all technique improperly transforms
# resources in the `main_package`. The jarjar binary jar itself has its command line help text
# stored as a resource in its main's package and so using a catch-all like this causes
# recursively shading jarjar with itself using this class to fail!
#
# As a result we explicitly shade all the non `main_package` packages in the binary jar instead
# which does support recursively shading jarjar.
rules.extend(self.shade_package(pkg) for pkg in sorted(self._iter_jar_packages(jar))
if pkg != main_package)
return rules
@contextmanager
def binary_shader(self, output_jar, main, jar, custom_rules=None, jvm_options=None):
"""Yields an `Executor.Runner` that will perform shading of the binary `jar` when `run()`.
The default rules will ensure the `main` class name is un-changed along with a minimal set of
support classes but that everything else will be shaded.
Any `custom_rules` are given highest precedence and so they can interfere with this automatic
binary shading. In general its safe to add exclusion rules to open up classes that need to be
shared between the binary and the code it runs over. An example would be excluding the
`org.junit.Test` annotation class from shading since both a tool running junit needs to be able
to scan for this annotation applied to the user code it tests.
:param unicode output_jar: The path to dump the shaded jar to; will be over-written if it
exists.
:param unicode main: The main class in the `jar` to preserve as the entry point.
:param unicode jar: The path to the jar file to shade.
:param list custom_rules: An optional list of custom `Shader.Rule`s.
:param list jvm_options: an optional sequence of options for the underlying jvm
:returns: An `Executor.Runner` that can be `run()` to shade the given `jar`.
"""
with temporary_file() as fp:
for rule in self.assemble_binary_rules(main, jar, custom_rules=custom_rules):
fp.write(rule.render())
fp.close()
yield self._executor.runner(classpath=[self._jarjar],
main='org.pantsbuild.jarjar.Main',
jvm_options=jvm_options,
args=['process', fp.name, jar, output_jar]) | unknown | codeparrot/codeparrot-clean | ||
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import os
from profile_chrome import controllers_unittest
from profile_chrome import systrace_controller
class SystraceControllerTest(controllers_unittest.BaseControllerTest):
def testGetCategories(self):
categories = \
systrace_controller.SystraceController.GetCategories(self.device)
self.assertTrue(categories)
assert 'gfx' in ' '.join(categories)
def testTracing(self):
categories = ['gfx', 'input', 'view']
ring_buffer = False
controller = systrace_controller.SystraceController(self.device,
categories,
ring_buffer)
interval = 1
try:
controller.StartTracing(interval)
finally:
controller.StopTracing()
result = controller.PullTrace()
try:
with open(result) as f:
self.assertTrue('CPU#' in f.read())
finally:
os.remove(result) | unknown | codeparrot/codeparrot-clean | ||
# This file is part of the Hotwire Shell project API.
# Copyright (C) 2007 Colin Walters <walters@verbum.org>
# 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 X CONSORTIUM 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 sys, logging, logging.config, StringIO
def log_except(logger=None, text=''):
def annotate(func):
def _exec_cb(*args, **kwargs):
try:
return func(*args, **kwargs)
except:
log_target = logger or logging
log_target.exception('Exception in callback%s', text and (': '+text) or '')
return _exec_cb
return annotate
def init(default_level, debug_modules, prefix=None):
rootlog = logging.getLogger()
fmt = logging.Formatter("%(asctime)s [%(thread)d] %(name)s %(levelname)s %(message)s",
"%H:%M:%S")
stderr_handler = logging.StreamHandler(sys.stderr)
stderr_handler.setFormatter(fmt)
rootlog.setLevel(default_level)
rootlog.addHandler(stderr_handler)
for logger in [logging.getLogger(prefix+x) for x in debug_modules]:
logger.setLevel(logging.DEBUG)
logging.debug("Initialized logging") | unknown | codeparrot/codeparrot-clean | ||
@file:Suppress("NAMED_ARGUMENTS_NOT_ALLOWED") // KT-21913
package kotlinx.coroutines.flow
import kotlinx.coroutines.testing.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlin.test.*
class FlowCallbackTest : TestBase() {
@Test
fun testClosedPrematurely() = runTest {
val outerScope = this
val flow = callbackFlow {
// ~ callback-based API
outerScope.launch(Job()) {
expect(2)
try {
send(1)
expectUnreached()
} catch (e: IllegalStateException) {
expect(3)
assertTrue(e.message!!.contains("awaitClose"))
}
}
expect(1)
}
try {
flow.collect()
} catch (e: IllegalStateException) {
expect(4)
assertTrue(e.message!!.contains("awaitClose"))
}
finish(5)
}
@Test
fun testNotClosedPrematurely() = runTest {
val outerScope = this
val flow = callbackFlow {
// ~ callback-based API
outerScope.launch(Job()) {
expect(2)
send(1)
close()
}
expect(1)
awaitClose()
}
assertEquals(listOf(1), flow.toList())
finish(3)
}
} | kotlin | github | https://github.com/Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/test/flow/channels/FlowCallbackTest.kt |
/*
Copyright 2016 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 authorizer
import (
"context"
"fmt"
"os"
"strings"
"time"
utilerrors "k8s.io/apimachinery/pkg/util/errors"
utilnet "k8s.io/apimachinery/pkg/util/net"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/wait"
authzconfig "k8s.io/apiserver/pkg/apis/apiserver"
"k8s.io/apiserver/pkg/apis/apiserver/load"
"k8s.io/apiserver/pkg/apis/apiserver/validation"
"k8s.io/apiserver/pkg/authorization/authorizer"
authorizationcel "k8s.io/apiserver/pkg/authorization/cel"
utilfeature "k8s.io/apiserver/pkg/util/feature"
versionedinformers "k8s.io/client-go/informers"
certinformersv1beta1 "k8s.io/client-go/informers/certificates/v1beta1"
resourceinformers "k8s.io/client-go/informers/resource/v1"
"k8s.io/kubernetes/pkg/auth/authorizer/abac"
"k8s.io/kubernetes/pkg/auth/nodeidentifier"
"k8s.io/kubernetes/pkg/features"
"k8s.io/kubernetes/pkg/kubeapiserver/authorizer/modes"
"k8s.io/kubernetes/plugin/pkg/auth/authorizer/node"
"k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac"
"k8s.io/kubernetes/plugin/pkg/auth/authorizer/rbac/bootstrappolicy"
)
// Config contains the data on how to authorize a request to the Kube API Server
type Config struct {
// Options for ModeABAC
// Path to an ABAC policy file.
PolicyFile string
// Options for ModeWebhook
// WebhookRetryBackoff specifies the backoff parameters for the authorization webhook retry logic.
// This allows us to configure the sleep time at each iteration and the maximum number of retries allowed
// before we fail the webhook call in order to limit the fan out that ensues when the system is degraded.
WebhookRetryBackoff *wait.Backoff
VersionedInformerFactory versionedinformers.SharedInformerFactory
// Optional field, custom dial function used to connect to webhook
CustomDial utilnet.DialFunc
// ReloadFile holds the filename to reload authorization configuration from
ReloadFile string
// AuthorizationConfiguration stores the configuration for the Authorizer chain
// It will deprecate most of the above flags when GA
AuthorizationConfiguration *authzconfig.AuthorizationConfiguration
// InitialAuthorizationConfigurationData holds the initial authorization configuration data
// that was read from the authorization configuration file.
InitialAuthorizationConfigurationData string
}
// New returns the right sort of union of multiple authorizer.Authorizer objects
// based on the authorizationMode or an error.
// stopCh is used to shut down config reload goroutines when the server is shutting down.
//
// Note: the cel compiler construction depends on feature gates and the compatibility version to be initialized.
func (config Config) New(ctx context.Context, serverID string) (authorizer.Authorizer, authorizer.RuleResolver, error) {
if len(config.AuthorizationConfiguration.Authorizers) == 0 {
return nil, nil, fmt.Errorf("at least one authorization mode must be passed")
}
r := &reloadableAuthorizerResolver{
initialConfig: config,
apiServerID: serverID,
lastLoadedConfig: config.AuthorizationConfiguration,
lastReadData: []byte(config.InitialAuthorizationConfigurationData),
reloadInterval: time.Minute,
compiler: authorizationcel.NewDefaultCompiler(),
}
seenTypes := sets.New[authzconfig.AuthorizerType]()
// Build and store authorizers which will persist across reloads
for _, configuredAuthorizer := range config.AuthorizationConfiguration.Authorizers {
seenTypes.Insert(configuredAuthorizer.Type)
// Keep cases in sync with constant list in k8s.io/kubernetes/pkg/kubeapiserver/authorizer/modes/modes.go.
switch configuredAuthorizer.Type {
case authzconfig.AuthorizerType(modes.ModeNode):
var slices resourceinformers.ResourceSliceInformer
if utilfeature.DefaultFeatureGate.Enabled(features.DynamicResourceAllocation) {
slices = config.VersionedInformerFactory.Resource().V1().ResourceSlices()
}
var podCertificateRequestInformer certinformersv1beta1.PodCertificateRequestInformer
if utilfeature.DefaultFeatureGate.Enabled(features.PodCertificateRequest) {
podCertificateRequestInformer = config.VersionedInformerFactory.Certificates().V1beta1().PodCertificateRequests()
}
node.RegisterMetrics()
graph := node.NewGraph()
node.AddGraphEventHandlers(
graph,
config.VersionedInformerFactory.Core().V1().Nodes(),
config.VersionedInformerFactory.Core().V1().Pods(),
config.VersionedInformerFactory.Core().V1().PersistentVolumes(),
config.VersionedInformerFactory.Storage().V1().VolumeAttachments(),
slices, // Nil check in AddGraphEventHandlers can be removed when always creating this.
podCertificateRequestInformer,
)
r.nodeAuthorizer = node.NewAuthorizer(graph, nodeidentifier.NewDefaultNodeIdentifier(), bootstrappolicy.NodeRules())
case authzconfig.AuthorizerType(modes.ModeABAC):
var err error
r.abacAuthorizer, err = abac.NewFromFile(config.PolicyFile)
if err != nil {
return nil, nil, err
}
case authzconfig.AuthorizerType(modes.ModeRBAC):
r.rbacAuthorizer = rbac.New(
&rbac.RoleGetter{Lister: config.VersionedInformerFactory.Rbac().V1().Roles().Lister()},
&rbac.RoleBindingLister{Lister: config.VersionedInformerFactory.Rbac().V1().RoleBindings().Lister()},
&rbac.ClusterRoleGetter{Lister: config.VersionedInformerFactory.Rbac().V1().ClusterRoles().Lister()},
&rbac.ClusterRoleBindingLister{Lister: config.VersionedInformerFactory.Rbac().V1().ClusterRoleBindings().Lister()},
)
}
}
// Require all non-webhook authorizer types to remain specified in the file on reload
seenTypes.Delete(authzconfig.TypeWebhook)
r.requireNonWebhookTypes = seenTypes
// Construct the authorizers / ruleResolvers for the given configuration
authorizer, ruleResolver, err := r.newForConfig(r.initialConfig.AuthorizationConfiguration)
if err != nil {
return nil, nil, err
}
r.current.Store(&authorizerResolver{
authorizer: authorizer,
ruleResolver: ruleResolver,
})
if r.initialConfig.ReloadFile != "" {
go r.runReload(ctx)
}
return r, r, nil
}
// RepeatableAuthorizerTypes is the list of Authorizer that can be repeated in the Authorization Config
var repeatableAuthorizerTypes = []string{modes.ModeWebhook}
// GetNameForAuthorizerMode returns the name to be set for the mode in AuthorizationConfiguration
// For now, lower cases the mode name
func GetNameForAuthorizerMode(mode string) string {
return strings.ToLower(mode)
}
func LoadAndValidateFile(configFile string, compiler authorizationcel.Compiler, requireNonWebhookTypes sets.Set[authzconfig.AuthorizerType]) (*authzconfig.AuthorizationConfiguration, string, error) {
data, err := os.ReadFile(configFile)
if err != nil {
return nil, "", err
}
config, err := LoadAndValidateData(data, compiler, requireNonWebhookTypes)
if err != nil {
return nil, "", err
}
return config, string(data), nil
}
func LoadAndValidateData(data []byte, compiler authorizationcel.Compiler, requireNonWebhookTypes sets.Set[authzconfig.AuthorizerType]) (*authzconfig.AuthorizationConfiguration, error) {
// load the file and check for errors
authorizationConfiguration, err := load.LoadFromData(data)
if err != nil {
return nil, fmt.Errorf("failed to load AuthorizationConfiguration from file: %w", err)
}
// validate the file and return any error
if errors := validation.ValidateAuthorizationConfiguration(compiler, nil, authorizationConfiguration,
sets.New(modes.AuthorizationModeChoices...),
sets.New(repeatableAuthorizerTypes...),
); len(errors) != 0 {
return nil, errors.ToAggregate()
}
// test to check if the authorizer names passed conform to the authorizers for type!=Webhook
// this test is only for kube-apiserver and hence checked here
// it preserves compatibility with o.buildAuthorizationConfiguration
var allErrors []error
seenModes := sets.New[authzconfig.AuthorizerType]()
for _, authorizer := range authorizationConfiguration.Authorizers {
if string(authorizer.Type) == modes.ModeWebhook {
continue
}
seenModes.Insert(authorizer.Type)
expectedName := GetNameForAuthorizerMode(string(authorizer.Type))
if expectedName != authorizer.Name {
allErrors = append(allErrors, fmt.Errorf("expected name %s for authorizer %s instead of %s", expectedName, authorizer.Type, authorizer.Name))
}
}
if missingTypes := requireNonWebhookTypes.Difference(seenModes); missingTypes.Len() > 0 {
allErrors = append(allErrors, fmt.Errorf("missing required types: %v", sets.List(missingTypes)))
}
if len(allErrors) > 0 {
return nil, utilerrors.NewAggregate(allErrors)
}
return authorizationConfiguration, nil
} | go | github | https://github.com/kubernetes/kubernetes | pkg/kubeapiserver/authorizer/config.go |
# Software License Agreement (BSD License)
#
# Copyright (c) 2013, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
# * Neither the name of Willow Garage, Inc. nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
from __future__ import print_function
from .common import BloomGenerator
from .common import GeneratorError
from .common import list_generators
from .common import load_generator
from .common import resolve_dependencies
from .common import update_rosdep
__all__ = [
'BloomGenerator', 'GeneratorError',
'list_generators', 'load_generator',
'resolve_dependencies', 'update_rosdep'
] | unknown | codeparrot/codeparrot-clean | ||
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: BUSL-1.1
package configs
import (
"bufio"
"bytes"
"os"
"path/filepath"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/hcl/v2"
)
// TestParseLoadConfigFileSuccess is a simple test that just verifies that
// a number of test configuration files (in testdata/valid-files) can
// be parsed without raising any diagnostics.
//
// This test does not verify that reading these files produces the correct
// file element contents. More detailed assertions may be made on some subset
// of these configuration files in other tests.
func TestParserLoadConfigFileSuccess(t *testing.T) {
files, err := os.ReadDir("testdata/valid-files")
if err != nil {
t.Fatal(err)
}
for _, info := range files {
name := info.Name()
t.Run(name, func(t *testing.T) {
src, err := os.ReadFile(filepath.Join("testdata/valid-files", name))
if err != nil {
t.Fatal(err)
}
parser := testParser(map[string]string{
name: string(src),
})
_, diags := parser.LoadConfigFile(name)
if len(diags) != 0 {
t.Errorf("unexpected diagnostics")
for _, diag := range diags {
t.Logf("- %s", diag)
}
}
})
}
}
// TestParseLoadConfigFileFailure is a simple test that just verifies that
// a number of test configuration files (in testdata/invalid-files)
// produce errors as expected.
//
// This test does not verify specific error messages, so more detailed
// assertions should be made on some subset of these configuration files in
// other tests.
func TestParserLoadConfigFileFailure(t *testing.T) {
files, err := os.ReadDir("testdata/invalid-files")
if err != nil {
t.Fatal(err)
}
for _, info := range files {
name := info.Name()
t.Run(name, func(t *testing.T) {
src, err := os.ReadFile(filepath.Join("testdata/invalid-files", name))
if err != nil {
t.Fatal(err)
}
parser := testParser(map[string]string{
name: string(src),
})
_, diags := parser.LoadConfigFile(name)
if !diags.HasErrors() {
t.Errorf("LoadConfigFile succeeded; want errors")
}
})
}
}
// This test uses a subset of the same fixture files as
// TestParserLoadConfigFileFailure, but additionally verifies that each
// file produces the expected diagnostic summary.
func TestParserLoadConfigFileFailureMessages(t *testing.T) {
tests := []struct {
Filename string
WantSeverity hcl.DiagnosticSeverity
WantDiag string
}{
{
"invalid-files/data-resource-lifecycle.tf",
hcl.DiagError,
"Invalid data resource lifecycle argument",
},
{
"invalid-files/variable-type-unknown.tf",
hcl.DiagError,
"Invalid type specification",
},
{
"invalid-files/unexpected-attr.tf",
hcl.DiagError,
"Unsupported argument",
},
{
"invalid-files/unexpected-block.tf",
hcl.DiagError,
"Unsupported block type",
},
{
"invalid-files/resource-count-and-for_each.tf",
hcl.DiagError,
`Invalid combination of "count" and "for_each"`,
},
{
"invalid-files/data-count-and-for_each.tf",
hcl.DiagError,
`Invalid combination of "count" and "for_each"`,
},
{
"invalid-files/resource-lifecycle-badbool.tf",
hcl.DiagError,
"Unsuitable value type",
},
}
for _, test := range tests {
t.Run(test.Filename, func(t *testing.T) {
src, err := os.ReadFile(filepath.Join("testdata", test.Filename))
if err != nil {
t.Fatal(err)
}
parser := testParser(map[string]string{
test.Filename: string(src),
})
_, diags := parser.LoadConfigFile(test.Filename)
if len(diags) != 1 {
t.Errorf("Wrong number of diagnostics %d; want 1", len(diags))
for _, diag := range diags {
t.Logf("- %s", diag)
}
return
}
if diags[0].Severity != test.WantSeverity {
t.Errorf("Wrong diagnostic severity %#v; want %#v", diags[0].Severity, test.WantSeverity)
}
if diags[0].Summary != test.WantDiag {
t.Errorf("Wrong diagnostic summary\ngot: %s\nwant: %s", diags[0].Summary, test.WantDiag)
}
})
}
}
// TestParseLoadConfigFileWarning is a test that verifies files from
// testdata/warning-files produce particular warnings.
//
// This test does not verify that reading these files produces the correct
// file element contents in spite of those warnings. More detailed assertions
// may be made on some subset of these configuration files in other tests.
func TestParserLoadConfigFileWarning(t *testing.T) {
files, err := os.ReadDir("testdata/warning-files")
if err != nil {
t.Fatal(err)
}
for _, info := range files {
name := info.Name()
t.Run(name, func(t *testing.T) {
src, err := os.ReadFile(filepath.Join("testdata/warning-files", name))
if err != nil {
t.Fatal(err)
}
// First we'll scan the file to see what warnings are expected.
// That's declared inside the files themselves by using the
// string "WARNING: " somewhere on each line that is expected
// to produce a warning, followed by the expected warning summary
// text. A single-line comment (with #) is the main way to do that.
const marker = "WARNING: "
sc := bufio.NewScanner(bytes.NewReader(src))
wantWarnings := make(map[int]string)
lineNum := 1
allowExperiments := false
for sc.Scan() {
lineText := sc.Text()
if idx := strings.Index(lineText, marker); idx != -1 {
summaryText := lineText[idx+len(marker):]
wantWarnings[lineNum] = summaryText
}
if lineText == "# ALLOW-LANGUAGE-EXPERIMENTS" {
allowExperiments = true
}
lineNum++
}
parser := testParser(map[string]string{
name: string(src),
})
// Some inputs use a special comment to request that they be
// permitted to use language experiments. We typically use that
// to test that the experiment opt-in is working and is causing
// the expected "you are using experimental features" warning.
parser.AllowLanguageExperiments(allowExperiments)
_, diags := parser.LoadConfigFile(name)
if diags.HasErrors() {
t.Errorf("unexpected error diagnostics")
for _, diag := range diags {
t.Logf("- %s", diag)
}
}
gotWarnings := make(map[int]string)
for _, diag := range diags {
if diag.Severity != hcl.DiagWarning || diag.Subject == nil {
continue
}
gotWarnings[diag.Subject.Start.Line] = diag.Summary
}
if diff := cmp.Diff(wantWarnings, gotWarnings); diff != "" {
t.Errorf("wrong warnings\n%s", diff)
}
})
}
}
// TestParseLoadConfigFileError is a test that verifies files from
// testdata/warning-files produce particular errors.
//
// This test does not verify that reading these files produces the correct
// file element contents in spite of those errors. More detailed assertions
// may be made on some subset of these configuration files in other tests.
func TestParserLoadConfigFileError(t *testing.T) {
files, err := os.ReadDir("testdata/error-files")
if err != nil {
t.Fatal(err)
}
for _, info := range files {
name := info.Name()
t.Run(name, func(t *testing.T) {
src, err := os.ReadFile(filepath.Join("testdata/error-files", name))
if err != nil {
t.Fatal(err)
}
// First we'll scan the file to see what warnings are expected.
// That's declared inside the files themselves by using the
// string "ERROR: " somewhere on each line that is expected
// to produce a warning, followed by the expected warning summary
// text. A single-line comment (with #) is the main way to do that.
const marker = "ERROR: "
sc := bufio.NewScanner(bytes.NewReader(src))
wantErrors := make(map[int]string)
lineNum := 1
for sc.Scan() {
lineText := sc.Text()
if idx := strings.Index(lineText, marker); idx != -1 {
summaryText := lineText[idx+len(marker):]
wantErrors[lineNum] = summaryText
}
lineNum++
}
parser := testParser(map[string]string{
name: string(src),
})
_, diags := parser.LoadConfigFile(name)
gotErrors := make(map[int]string)
for _, diag := range diags {
if diag.Severity != hcl.DiagError || diag.Subject == nil {
continue
}
gotErrors[diag.Subject.Start.Line] = diag.Summary
}
if diff := cmp.Diff(wantErrors, gotErrors); diff != "" {
t.Errorf("wrong errors\n%s", diff)
}
})
}
} | go | github | https://github.com/hashicorp/terraform | internal/configs/parser_config_test.go |
from django.shortcuts import get_object_or_404, render, RequestContext, render_to_response
from repo.forms import UserForm, UserEditForm
from reg.forms import MyRegistrationForm
from reg.models import UserProfile
from django.contrib.auth.models import User
from django.contrib.auth.views import password_reset
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.forms.models import inlineformset_factory
from django.core.exceptions import PermissionDenied
from django.views import generic
from hashids import Hashids
from django.contrib import messages
from django import forms as django_forms
# from django.contrib.auth.forms import UserCreationForm
hashids = Hashids(salt='2016-08-18 16:27:22 IiTNmll0 ATn1ViSu', alphabet='123456789abdefghijmdncklopqrstuvwxy0', min_length=7)
def home(request):
return render(request, 'reg/home.html')
def register(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('reg:home'))
if request.method == 'POST':
form = MyRegistrationForm(request.POST)
if form.is_valid():
user = form.save()
user = authenticate(username=form.cleaned_data.get('username'), password=form.cleaned_data.get('password1'))
login(request, user)
messages.success(request, 'Account created successful')
return HttpResponseRedirect(reverse('reg:index'))
messages.error(request, 'Registration failed. Check the listed errors')
else:
form = MyRegistrationForm()
return render(request, 'reg/register.html', {
'form': form,
})
def login_user(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('reg:home'))
if request.method == 'POST':
user = authenticate(username=request.POST.__getitem__('username'),
password=request.POST.__getitem__('password'))
if user is not None:
login(request, user)
messages.success(request, 'Login successful')
return HttpResponseRedirect(reverse('reg:index'))
messages.error(request, 'Login failed')
return render(request, 'reg/login.html', {'form': UserForm()})
@login_required(login_url='/login')
def logout_view(request):
logout(request)
messages.success(request, 'You have been logged out!')
return render(request, 'reg/home.html')
@login_required(login_url='/login')
def edit_user(request, pk):
try:
pk = hashids.decode(pk)[0]
except IndexError:
raise Http404
user = User.objects.get(pk=pk)
# Prepopulate UserProfileForm with retrieved user values from above.
user_form = UserEditForm(instance=user)
ProfileInlineFormset = inlineformset_factory(User, UserProfile,
fields=('website', 'bio', 'phone', 'city', 'country', 'organisation'),
widgets={
'website': django_forms.TextInput(attrs={'class': 'mdl-textfield__input'}),
'bio': django_forms.TextInput(attrs={'class': 'mdl-textfield__input'}),
'phone': django_forms.TextInput(attrs={'class': 'mdl-textfield__input'}),
'city': django_forms.TextInput(attrs={'class': 'mdl-textfield__input'}),
'country': django_forms.TextInput(attrs={'class': 'mdl-textfield__input'}),
'organisation': django_forms.TextInput(attrs={'class': 'mdl-textfield__input'})
})
formset = ProfileInlineFormset(instance=user)
if request.user.is_authenticated() and request.user.id == user.id:
if request.method == 'POST':
user_form = UserEditForm(request.POST, request.FILES, instance=user)
formset = ProfileInlineFormset(request.POST, request.FILES, instance=user)
if user_form.is_valid():
created_user = user_form.save(commit=False)
formset = ProfileInlineFormset(request.POST, request.FILES, instance=created_user)
if formset.is_valid():
created_user.save()
formset.save()
return HttpResponseRedirect(reverse('reg:profile', args=(hashids.encode(pk),)))
return render(request, "reg/account_update.html", {
"noodle": pk,
"noodle_form": user_form,
"formset": formset,
})
else:
raise PermissionDenied
def profile(request, pk):
try:
pk = hashids.decode(pk)[0]
except:
raise Http404
#user_data = get_object_or_404(User, pk=pk)
try:
user_profile = UserProfile.objects.select_related('user').get(user__pk=pk, user__is_active='TRUE')
user_data = User.objects.get(pk=pk)
except UserProfile.DoesNotExist or User.DoesNotExist:
raise Http404("Profile unavailable")
return render(request, 'reg/viewprofile.html', {
'user_profile': user_profile,
'user_data': user_data,
})
#def reset_pass(request):
# return password_reset(request,
# is_admin_site=False,
# template_name='reg/pass_reset.html',
# post_reset_redirect='reg/home',
# )
#
#def reset_confirm(request, uidb64=None, token=None):
# return password_reset_confirm(request, template_name='reset_confirm.html',
# uidb36=uidb36, token=token, post_reset_redirect='reg/home') | unknown | codeparrot/codeparrot-clean | ||
# Copyright 2011 OpenStack Foundation.
# 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.
from datetime import datetime
import eventlet
from neutron.db import common_db_mixin
from neutron_lib.db import api as db_api
from neutron_lib.services import base as service_base
from oslo_log import log
from oslo_serialization import jsonutils
from networking_bigswitch.plugins.bigswitch.db import consistency_db
from networking_bigswitch.plugins.bigswitch.db import network_template_db
from networking_bigswitch.plugins.bigswitch.db import reachability_test_db
from networking_bigswitch.plugins.bigswitch.db import tenant_policy_db
from networking_bigswitch.plugins.bigswitch.extensions \
import bsnserviceextension
from networking_bigswitch.plugins.bigswitch import servermanager
LOG = log.getLogger(__name__)
class BSNServicePlugin(service_base.ServicePluginBase,
bsnserviceextension.BSNServicePluginBase,
common_db_mixin.CommonDbMixin):
supported_extension_aliases = ["bsn-service-extension"]
def __init__(self):
super(BSNServicePlugin, self).__init__()
# initialize BCF server handler
self.servers = servermanager.ServerPool.get_instance()
self.networktemplate_db_mixin = network_template_db\
.NetworkTemplateDbMixin()
self.network_template_assignment_db_mixin = network_template_db\
.NetworkTemplateAssignmentDbMixin()
self.reachabilitytest_db_mixin = reachability_test_db\
.ReachabilityTestDbMixin()
self.reachabilityquicktest_db_mixin = reachability_test_db\
.ReachabilityQuickTestDbMixin()
self.tenantpolicy_db_mixin = tenant_policy_db.TenantPolicyDbMixin()
def get_plugin_type(self):
# Tell Neutron this is a BSN service plugin
return 'BSNSERVICEPLUGIN'
def get_plugin_name(self):
return 'bsn_service_extension'
def get_plugin_description(self):
return "BSN Service Plugin"
# public CRUD methods for network templates
def get_networktemplates(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
return self.networktemplate_db_mixin.get_networktemplates(
context=context, filters=filters, fields=fields, sorts=sorts,
limit=limit, marker=marker, page_reverse=page_reverse)
def get_networktemplate(self, context, id, fields=None):
return self.networktemplate_db_mixin.get_networktemplate(
context=context, id=id, fields=fields)
def create_networktemplate(self, context, networktemplate):
return self.networktemplate_db_mixin.create_networktemplate(
context=context, networktemplate=networktemplate)
def delete_networktemplate(self, context, id):
self.networktemplate_db_mixin.delete_networktemplate(
context=context, id=id)
def update_networktemplate(self, context, id, networktemplate):
return self.networktemplate_db_mixin.update_networktemplate(
context=context, id=id, networktemplate=networktemplate)
# public CRUD methods for Network Template Assignment
def get_networktemplateassignments(self, context, filters=None,
fields=None, sorts=None, limit=None,
marker=None, page_reverse=False):
return self.network_template_assignment_db_mixin\
.get_networktemplateassignments(
context=context, filters=filters, fields=fields, sorts=sorts,
limit=limit, marker=marker, page_reverse=page_reverse)
def get_networktemplateassignment(self, context, id, fields=None):
return self.network_template_assignment_db_mixin\
.get_networktemplateassignment(context=context, id=id,
fields=fields)
def create_networktemplateassignment(self, context,
networktemplateassignment):
return self.network_template_assignment_db_mixin\
.create_networktemplateassignment(
context=context,
networktemplateassignment=networktemplateassignment)
def delete_networktemplateassignment(self, context, id):
self.network_template_assignment_db_mixin\
.delete_networktemplateassignment(context=context, id=id)
def update_networktemplateassignment(self, context, id,
networktemplateassignment):
return self.network_template_assignment_db_mixin\
.update_networktemplateassignment(
context=context, id=id,
networktemplateassignment=networktemplateassignment)
# common method to parse response from the controller
def parse_result(self, response, expected_result):
if not response:
test_result = "fail"
detail = [{'path-index': "No result", 'hop-index': '',
'hop-name': ''}]
logical_path = [{'path-index': "No result", 'hop-index': '',
'hop-name': ''}]
return test_result, detail, logical_path
elif response[0].get("summary", [{}])[0].get("forward-result") != \
expected_result:
test_result = "fail"
detail = [{'path-index': "Expected: %s. Actual: %s" % (
expected_result,
response[0].get("summary", [{}])[0].get("forward-result"))}]
try:
detail[0]['path-index'] += \
" - " + response[0]['summary'][0]['logical-error']
except Exception:
pass
elif response[0].get("summary", [{}])[0].get("forward-result") == \
expected_result:
test_result = "pass"
detail = response[0].get("physical-path", [{}])
else:
try:
detail = [{'path-index':
response[0]['summary'][0]['logical-error']}]
except Exception:
detail = [{'path-index': jsonutils.dumps(response)}]
test_result = "fail"
detail[0]['path-index'] = detail[0].get('path-index', '')
detail[0]['hop-index'] = detail[0].get('hop-index', '')
detail[0]['hop-name'] = detail[0].get('hop-name', '')
# also get logical-path
logical_path = response[0].get("logical-path", [{}])
return test_result, detail, logical_path
# public CRUD methods for Reachability Test
def get_reachabilitytests(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
return self.reachabilitytest_db_mixin.get_reachabilitytests(
context, filters=filters, fields=fields, sorts=sorts, limit=limit,
marker=marker, page_reverse=page_reverse)
def get_reachabilitytest(self, context, id, fields=None):
return self.reachabilitytest_db_mixin.get_reachabilitytest(
context=context, id=id, fields=fields)
def create_reachabilitytest(self, context, reachabilitytest):
return self.reachabilitytest_db_mixin.create_reachabilitytest(
context=context, reachabilitytest=reachabilitytest)
def update_reachabilitytest(self, context, id, reachabilitytest):
reachabilitytest_data = reachabilitytest['reachabilitytest']
reachabilitytest = self.reachabilitytest_db_mixin\
._get_reachabilitytest(context, id)
if 'run_test' in reachabilitytest_data and \
reachabilitytest_data['run_test']:
# run test on the controller and get results
# update fields in reachabilitytest_data dict
src = reachabilitytest.get_connection_source(
unicode_mode=self.servers.is_unicode_enabled())
dst = reachabilitytest.get_connection_destination()
response = self.servers.rest_get_testpath(src, dst)
test_result, detail, logical_path = self.parse_result(
response, reachabilitytest.expected_result)
reachabilitytest_data['test_result'] = test_result
reachabilitytest_data['detail'] = detail
reachabilitytest_data['logical_path'] = logical_path
# reset run_test to false and set timestamp to now
reachabilitytest_data['run_test'] = False
reachabilitytest_data['test_time'] = datetime.now()
return self.reachabilitytest_db_mixin.update_reachabilitytest(
context=context, id=id,
reachabilitytest={'reachabilitytest': reachabilitytest_data})
def delete_reachabilitytest(self, context, id):
self.reachabilitytest_db_mixin.delete_reachabilitytest(
context=context, id=id)
# public CRUD methods for Reachability Quick Test
def get_reachabilityquicktests(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
return self.reachabilityquicktest_db_mixin.get_reachabilityquicktests(
context=context, filters=filters, fields=fields, sorts=sorts,
limit=limit, marker=marker, page_reverse=page_reverse)
def get_reachabilityquicktest(self, context, id, fields=None):
return self.reachabilityquicktest_db_mixin.get_reachabilityquicktest(
context=context, id=id, fields=fields)
def create_reachabilityquicktest(self, context, reachabilityquicktest):
return self.reachabilityquicktest_db_mixin\
.create_reachabilityquicktest(
context=context, reachabilityquicktest=reachabilityquicktest)
def update_reachabilityquicktest(self, context, id, reachabilityquicktest):
reachabilityquicktest_data = \
reachabilityquicktest['reachabilityquicktest']
reachabilityquicktest = self.reachabilityquicktest_db_mixin\
._get_reachabilityquicktest(context, id)
if 'save_test' in reachabilityquicktest_data and \
reachabilityquicktest_data['save_test']:
# just copy paste the test and return
quicktest = self.reachabilityquicktest_db_mixin\
._get_reachabilityquicktest(context, id)
# update name as given in the args, not the default name
quicktest.name = reachabilityquicktest_data['name']
# remove ID, as we want it to be unique per test
# not unique per tenant
quicktest_dict = self.reachabilityquicktest_db_mixin\
._make_reachabilityquicktest_dict(quicktest)
quicktest_dict.pop('id')
self.reachabilitytest_db_mixin.create_reachabilitytest_withresult(
context=context,
reachabilitytest={'reachabilitytest': quicktest_dict})
# reset the save_test flag
reachabilityquicktest_data['save_test'] = False
if 'run_test' in reachabilityquicktest_data and \
reachabilityquicktest_data['run_test']:
# run test on the controller and get results
# update fields in reachabilityquicktest_data dict
src = reachabilityquicktest.get_connection_source(
unicode_mode=self.servers.is_unicode_enabled())
dst = reachabilityquicktest.get_connection_destination()
response = self.servers.rest_get_testpath(src, dst)
test_result, detail, logical_path = self.parse_result(
response, reachabilityquicktest.expected_result)
reachabilityquicktest_data['test_result'] = test_result
reachabilityquicktest_data['detail'] = detail
reachabilityquicktest_data['logical_path'] = logical_path
# reset run_test to false and set timestamp to now
reachabilityquicktest_data['run_test'] = False
reachabilityquicktest_data['test_time'] = datetime.now()
return self.reachabilityquicktest_db_mixin\
.update_reachabilityquicktest(
context=context, id=id,
reachabilityquicktest={'reachabilityquicktest':
reachabilityquicktest_data})
def delete_reachabilityquicktest(self, context, id):
self.reachabilityquicktest_db_mixin.delete_reachabilityquicktest(
context=context, id=id)
# public CRUD methods for Tenant Policies
def get_tenantpolicies(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
return self.tenantpolicy_db_mixin.get_tenantpolicies(
context=context, filters=filters, fields=fields, sorts=sorts,
limit=limit, marker=marker, page_reverse=page_reverse)
def get_tenantpolicy(self, context, id, fields=None):
return self.tenantpolicy_db_mixin.get_tenantpolicy(
context=context, id=id, fields=fields)
def create_tenantpolicy(self, context, tenantpolicy):
with db_api.CONTEXT_WRITER.using(context):
tenantpolicy_dict = self.tenantpolicy_db_mixin.create_tenantpolicy(
context=context, tenantpolicy=tenantpolicy)
self.servers.rest_create_tenantpolicy(
tenantpolicy_dict['tenant_id'], tenantpolicy_dict)
return tenantpolicy_dict
def delete_tenantpolicy(self, context, id):
with db_api.CONTEXT_WRITER.using(context):
delete_policy = self.tenantpolicy_db_mixin._get_tenantpolicy(
context, id)
self.tenantpolicy_db_mixin.delete_tenantpolicy(
context=context, id=id)
self.servers.rest_delete_tenantpolicy(delete_policy['tenant_id'],
delete_policy['priority'])
def update_tenantpolicy(self, context, id, tenantpolicy):
with db_api.CONTEXT_WRITER.using(context):
updated_policy = self.tenantpolicy_db_mixin.update_tenantpolicy(
context=context, servers=self.servers, id=id,
tenantpolicy=tenantpolicy)
self.servers.rest_update_tenantpolicy(updated_policy['tenant_id'],
updated_policy)
return updated_policy
# public CRUD methods for Topology Sync command
def update_forcesynctopology(self, context, id, forcesynctopology):
eventlet.spawn(self.servers.force_topo_sync, **{'check_ts': False})
return {'id': '1',
'tenant_id': context.project_id,
'project_id': context.project_id,
'timestamp_ms': '0',
'timestamp_datetime': '0',
'status': 'Topology Sync scheduled for execution.'}
def get_forcesynctopologies(self, context, filters=None, fields=None,
sorts=None, limit=None, marker=None,
page_reverse=False):
with context.session.begin(subtransactions=True):
res = (context.session.query(consistency_db.ConsistencyHash).
filter_by(hash_id='1').first())
if res:
if 'TOPO_SYNC' in res.hash:
timestamp_ms = consistency_db.get_lock_owner(res.hash)
timestamp_datetime = consistency_db.convert_ts_to_datetime(
timestamp_ms)
result = 'Topology sync in progress..'
else:
timestamp_ms = res.hash
timestamp_datetime = consistency_db.convert_ts_to_datetime(
timestamp_ms)
result = 'Topology sync complete.'
# return the result
return [{'id': '1',
'tenant_id': context.project_id,
'project_id': context.project_id,
'timestamp_ms': timestamp_ms,
'timestamp_datetime': timestamp_datetime,
'status': result}]
else:
return [{'id': '1',
'tenant_id': context.project_id,
'project_id': context.project_id,
'timestamp_ms': '0',
'timestamp_datetime': '0',
'status': 'FAILURE'}]
def get_forcesynctopology(self, context, id, fields=None):
return self.get_forcesynctopologies(context=context)[0] | unknown | codeparrot/codeparrot-clean | ||
# frozen_string_literal: true
class Recipe < ActiveRecord::Base
belongs_to :chef
end | ruby | github | https://github.com/rails/rails | activerecord/test/models/recipe.rb |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# A top level slice of a main thread can cause the webapp to behave
# unresponsively if its thread duration is greater than or equals to
# USER_PERCEIVABLE_DELAY_THRESHOLD_MS. Human eyes can perceive delay at low as
# 100ms, but since we use thread time instead of wall-time, we reduce the
# threshold further to 50ms to make room for other OS's activities.
USER_PERCEIVABLE_DELAY_THRESHOLD_MS = 50
class _MainthreadJankStat(object):
"""A small wrapper class for storing mainthread jank stats computed for
single record.
"""
def __init__(self):
self.sum_big_top_slices_thread_time = 0
self.biggest_top_slice_thread_time = 0
def _ComputeMainthreadJankStatsForRecord(renderer_thread, record):
"""Computes the mainthread jank stat on a record range.
Returns:
An instance of _MainthreadJankStat, which has:
sum_big_top_slices_thread_time is the total thread duration of all top
slices whose thread time ranges overlapped with (thread_start, thread_end)
and the overlapped thread duration is greater than or equal
USER_PERCEIVABLE_DELAY_THRESHOLD_MS.
biggest_top_slice_thread_time is the biggest thread duration of all
top slices whose thread time ranges overlapped with
(thread_start, thread_end).
Note: thread duration of each slices is computed using overlapped range
with (thread_start, thread_end).
"""
stat = _MainthreadJankStat()
for s in renderer_thread.toplevel_slices:
jank_thread_duration = record.GetOverlappedThreadTimeForSlice(s)
stat.biggest_top_slice_thread_time = max(
stat.biggest_top_slice_thread_time, jank_thread_duration)
if jank_thread_duration >= USER_PERCEIVABLE_DELAY_THRESHOLD_MS:
stat.sum_big_top_slices_thread_time += jank_thread_duration
return stat
class MainthreadJankStats(object):
"""
Utility class for extracting main thread jank statistics from the timeline
(or other loggin facilities), and providing them in a common format to
classes that compute benchmark metrics from this data.
total_big_jank_thread_time is the total thread duration of all top
slices whose thread time ranges overlapped with any thread time ranges of
the records and the overlapped thread duration is greater than or equal
USER_PERCEIVABLE_DELAY_THRESHOLD_MS.
biggest_jank_thread_time is the biggest thread duration of all
top slices whose thread time ranges overlapped with any of records' thread
time ranges.
"""
def __init__(self, renderer_thread, interaction_records):
self._renderer_thread = renderer_thread
self._interaction_records = interaction_records
self._total_big_jank_thread_time = 0
self._biggest_jank_thread_time = 0
self._ComputeMainthreadJankStats()
@property
def total_big_jank_thread_time(self):
return self._total_big_jank_thread_time
@property
def biggest_jank_thread_time(self):
return self._biggest_jank_thread_time
def _ComputeMainthreadJankStats(self):
for record in self._interaction_records:
record_jank_stat = _ComputeMainthreadJankStatsForRecord(
self._renderer_thread, record)
self._total_big_jank_thread_time += (
record_jank_stat.sum_big_top_slices_thread_time)
self._biggest_jank_thread_time = (
max(self._biggest_jank_thread_time,
record_jank_stat.biggest_top_slice_thread_time)) | unknown | codeparrot/codeparrot-clean | ||
--
-- Test for various ALTER statements
--
-- clean-up in case a prior regression run failed
SET client_min_messages TO 'warning';
DROP DATABASE IF EXISTS sepgsql_test_regression_1;
DROP DATABASE IF EXISTS sepgsql_test_regression;
DROP USER IF EXISTS regress_sepgsql_test_user;
RESET client_min_messages;
-- @SECURITY-CONTEXT=unconfined_u:unconfined_r:sepgsql_regtest_superuser_t:s0
--
-- CREATE Objects to be altered (with debug_audit being silent)
--
CREATE DATABASE sepgsql_test_regression_1;
CREATE USER regress_sepgsql_test_user;
CREATE SCHEMA regtest_schema_1;
CREATE SCHEMA regtest_schema_2;
GRANT ALL ON SCHEMA regtest_schema_1 TO public;
GRANT ALL ON SCHEMA regtest_schema_2 TO public;
SET search_path = regtest_schema_1, regtest_schema_2, public;
CREATE TABLE regtest_table_1 (a int, b text);
CREATE TABLE regtest_table_2 (c text) inherits (regtest_table_1);
CREATE TABLE regtest_table_3 (x int primary key, y text);
---
-- partitioned table parent
CREATE TABLE regtest_ptable_1 (o int, p text) PARTITION BY RANGE (o);
-- partitioned table children
CREATE TABLE regtest_ptable_1_ones PARTITION OF regtest_ptable_1 FOR VALUES FROM ('0') TO ('10');
CREATE TABLE regtest_ptable_1_tens PARTITION OF regtest_ptable_1 FOR VALUES FROM ('10') TO ('100');
---
CREATE SEQUENCE regtest_seq_1;
CREATE VIEW regtest_view_1 AS SELECT * FROM regtest_table_1 WHERE a > 0;
CREATE FUNCTION regtest_func_1 (text) RETURNS bool
AS 'BEGIN RETURN true; END' LANGUAGE 'plpgsql';
-- switch on debug_audit
SET sepgsql.debug_audit = true;
SET client_min_messages = LOG;
--
-- ALTER xxx OWNER TO
--
-- XXX: It should take db_xxx:{setattr} permission checks even if
-- owner is not actually changed.
--
ALTER DATABASE sepgsql_test_regression_1 OWNER TO regress_sepgsql_test_user;
ALTER DATABASE sepgsql_test_regression_1 OWNER TO regress_sepgsql_test_user;
ALTER SCHEMA regtest_schema_1 OWNER TO regress_sepgsql_test_user;
ALTER SCHEMA regtest_schema_1 OWNER TO regress_sepgsql_test_user;
ALTER TABLE regtest_table_1 OWNER TO regress_sepgsql_test_user;
ALTER TABLE regtest_table_1 OWNER TO regress_sepgsql_test_user;
ALTER TABLE regtest_ptable_1 OWNER TO regress_sepgsql_test_user;
ALTER TABLE regtest_ptable_1_ones OWNER TO regress_sepgsql_test_user;
ALTER SEQUENCE regtest_seq_1 OWNER TO regress_sepgsql_test_user;
ALTER SEQUENCE regtest_seq_1 OWNER TO regress_sepgsql_test_user;
ALTER VIEW regtest_view_1 OWNER TO regress_sepgsql_test_user;
ALTER VIEW regtest_view_1 OWNER TO regress_sepgsql_test_user;
ALTER FUNCTION regtest_func_1(text) OWNER TO regress_sepgsql_test_user;
ALTER FUNCTION regtest_func_1(text) OWNER TO regress_sepgsql_test_user;
--
-- ALTER xxx SET SCHEMA
--
ALTER TABLE regtest_table_1 SET SCHEMA regtest_schema_2;
ALTER TABLE regtest_ptable_1 SET SCHEMA regtest_schema_2;
ALTER TABLE regtest_ptable_1_ones SET SCHEMA regtest_schema_2;
ALTER SEQUENCE regtest_seq_1 SET SCHEMA regtest_schema_2;
ALTER VIEW regtest_view_1 SET SCHEMA regtest_schema_2;
ALTER FUNCTION regtest_func_1(text) SET SCHEMA regtest_schema_2;
--
-- ALTER xxx RENAME TO
--
ALTER DATABASE sepgsql_test_regression_1 RENAME TO sepgsql_test_regression;
ALTER SCHEMA regtest_schema_1 RENAME TO regtest_schema;
ALTER TABLE regtest_table_1 RENAME TO regtest_table;
---
-- partitioned table parent
ALTER TABLE regtest_ptable_1 RENAME TO regtest_ptable;
-- partitioned table child
ALTER TABLE regtest_ptable_1_ones RENAME TO regtest_table_part;
---
ALTER SEQUENCE regtest_seq_1 RENAME TO regtest_seq;
ALTER VIEW regtest_view_1 RENAME TO regtest_view;
ALTER FUNCTION regtest_func_1(text) RENAME TO regtest_func;
SET search_path = regtest_schema, regtest_schema_2, public;
--
-- misc ALTER commands
--
ALTER DATABASE sepgsql_test_regression CONNECTION LIMIT 999;
ALTER DATABASE sepgsql_test_regression SET search_path TO regtest_schema, public; -- not supported yet
ALTER TABLE regtest_table ADD COLUMN d float;
ALTER TABLE regtest_table DROP COLUMN d;
ALTER TABLE regtest_table ALTER b SET DEFAULT 'abcd'; -- not supported yet
ALTER TABLE regtest_table ALTER b SET DEFAULT 'XYZ'; -- not supported yet
ALTER TABLE regtest_table ALTER b DROP DEFAULT; -- not supported yet
ALTER TABLE regtest_table ALTER b SET NOT NULL;
ALTER TABLE regtest_table ALTER b DROP NOT NULL;
ALTER TABLE regtest_table ALTER b SET STATISTICS -1;
ALTER TABLE regtest_table ALTER b SET (n_distinct = 999);
ALTER TABLE regtest_table ALTER b SET STORAGE PLAIN;
ALTER TABLE regtest_table ADD CONSTRAINT test_fk FOREIGN KEY (a) REFERENCES regtest_table_3(x); -- not supported
ALTER TABLE regtest_table ADD CONSTRAINT test_ck CHECK (b like '%abc%') NOT VALID; -- not supported
ALTER TABLE regtest_table VALIDATE CONSTRAINT test_ck; -- not supported
ALTER TABLE regtest_table DROP CONSTRAINT test_ck; -- not supported
CREATE TRIGGER regtest_test_trig BEFORE UPDATE ON regtest_table
FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger();
ALTER TABLE regtest_table DISABLE TRIGGER regtest_test_trig;
ALTER TABLE regtest_table ENABLE TRIGGER regtest_test_trig;
CREATE RULE regtest_test_rule AS ON INSERT TO regtest_table_3 DO ALSO NOTHING;
ALTER TABLE regtest_table_3 DISABLE RULE regtest_test_rule;
ALTER TABLE regtest_table_3 ENABLE RULE regtest_test_rule;
ALTER TABLE regtest_table SET (fillfactor = 75);
ALTER TABLE regtest_table RESET (fillfactor);
ALTER TABLE regtest_table_2 NO INHERIT regtest_table; -- not supported
ALTER TABLE regtest_table_2 INHERIT regtest_table; -- not supported
ALTER TABLE regtest_table SET TABLESPACE pg_default;
---
-- partitioned table parent
ALTER TABLE regtest_ptable ADD COLUMN d float;
ALTER TABLE regtest_ptable DROP COLUMN d;
ALTER TABLE regtest_ptable ALTER p SET DEFAULT 'abcd'; -- not supported by sepgsql
ALTER TABLE regtest_ptable ALTER p SET DEFAULT 'XYZ'; -- not supported by sepgsql
ALTER TABLE regtest_ptable ALTER p DROP DEFAULT; -- not supported by sepgsql
ALTER TABLE regtest_ptable ALTER p SET NOT NULL;
ALTER TABLE regtest_ptable ALTER p DROP NOT NULL;
ALTER TABLE regtest_ptable ALTER p SET STATISTICS -1;
ALTER TABLE regtest_ptable ALTER p SET (n_distinct = 999);
ALTER TABLE regtest_ptable ALTER p SET STORAGE PLAIN;
ALTER TABLE regtest_ptable ADD CONSTRAINT test_ck CHECK (p like '%abc%') NOT VALID; -- not supported by sepgsql
ALTER TABLE regtest_ptable DROP CONSTRAINT test_ck; -- not supported by sepgsql
ALTER TABLE regtest_ptable SET TABLESPACE pg_default;
-- partitioned table child
ALTER TABLE regtest_table_part ALTER p SET DEFAULT 'abcd'; -- not supported by sepgsql
ALTER TABLE regtest_table_part ALTER p SET DEFAULT 'XYZ'; -- not supported by sepgsql
ALTER TABLE regtest_table_part ALTER p DROP DEFAULT; -- not supported by sepgsql
ALTER TABLE regtest_table_part ALTER p SET NOT NULL;
ALTER TABLE regtest_table_part ALTER p DROP NOT NULL;
ALTER TABLE regtest_table_part ALTER p SET STATISTICS -1;
ALTER TABLE regtest_table_part ALTER p SET (n_distinct = 999);
ALTER TABLE regtest_table_part ALTER p SET STORAGE PLAIN;
ALTER TABLE regtest_table_part ADD CONSTRAINT test_ck CHECK (p like '%abc%') NOT VALID; -- not supported by sepgsql
ALTER TABLE regtest_table_part VALIDATE CONSTRAINT test_ck; -- not supported by sepgsql
ALTER TABLE regtest_table_part DROP CONSTRAINT test_ck; -- not supported by sepgsql
CREATE TRIGGER regtest_part_test_trig BEFORE UPDATE ON regtest_table_part
FOR EACH ROW EXECUTE PROCEDURE suppress_redundant_updates_trigger();
ALTER TABLE regtest_table_part DISABLE TRIGGER regtest_part_test_trig;
ALTER TABLE regtest_table_part ENABLE TRIGGER regtest_part_test_trig;
ALTER TABLE regtest_table_part SET (fillfactor = 75);
ALTER TABLE regtest_table_part RESET (fillfactor);
ALTER TABLE regtest_table_part SET TABLESPACE pg_default;
---
ALTER VIEW regtest_view SET (security_barrier);
ALTER SEQUENCE regtest_seq INCREMENT BY 10 START WITH 1000;
--
-- clean-up objects
--
RESET sepgsql.debug_audit;
RESET client_min_messages;
DROP DATABASE sepgsql_test_regression;
DROP SCHEMA regtest_schema CASCADE;
DROP SCHEMA regtest_schema_2 CASCADE;
DROP USER regress_sepgsql_test_user; | sql | github | https://github.com/postgres/postgres | contrib/sepgsql/sql/alter.sql |
# -*- coding: utf-8 -*-
"""
pygments.lexers.dotnet
~~~~~~~~~~~~~~~~~~~~~~
Lexers for .net languages.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, DelegatingLexer, bygroups, include, \
using, this
from pygments.token import Punctuation, \
Text, Comment, Operator, Keyword, Name, String, Number, Literal, Other
from pygments.util import get_choice_opt
from pygments import unistring as uni
from pygments.lexers.web import XmlLexer
__all__ = ['CSharpLexer', 'NemerleLexer', 'BooLexer', 'VbNetLexer',
'CSharpAspxLexer', 'VbNetAspxLexer', 'FSharpLexer']
class CSharpLexer(RegexLexer):
"""
For `C# <http://msdn2.microsoft.com/en-us/vcsharp/default.aspx>`_
source code.
Additional options accepted:
`unicodelevel`
Determines which Unicode characters this lexer allows for identifiers.
The possible values are:
* ``none`` -- only the ASCII letters and numbers are allowed. This
is the fastest selection.
* ``basic`` -- all Unicode characters from the specification except
category ``Lo`` are allowed.
* ``full`` -- all Unicode characters as specified in the C# specs
are allowed. Note that this means a considerable slowdown since the
``Lo`` category has more than 40,000 characters in it!
The default value is ``basic``.
*New in Pygments 0.8.*
"""
name = 'C#'
aliases = ['csharp', 'c#']
filenames = ['*.cs']
mimetypes = ['text/x-csharp'] # inferred
flags = re.MULTILINE | re.DOTALL | re.UNICODE
# for the range of allowed unicode characters in identifiers,
# see http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
levels = {
'none': '@?[_a-zA-Z][a-zA-Z0-9_]*',
'basic': ('@?[_' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl + ']' +
'[' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl +
uni.Nd + uni.Pc + uni.Cf + uni.Mn + uni.Mc + ']*'),
'full': ('@?(?:_|[^' +
uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl') + '])'
+ '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl',
'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'),
}
tokens = {}
token_variants = True
for levelname, cs_ident in list(levels.items()):
tokens[levelname] = {
'root': [
# method names
(r'^([ \t]*(?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type
r'(' + cs_ident + ')' # method name
r'(\s*)(\()', # signature start
bygroups(using(this), Name.Function, Text, Punctuation)),
(r'^\s*\[.*?\]', Name.Attribute),
(r'[^\S\n]+', Text),
(r'\\\n', Text), # line continuation
(r'//.*?\n', Comment.Single),
(r'/[*].*?[*]/', Comment.Multiline),
(r'\n', Text),
(r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation),
(r'[{}]', Punctuation),
(r'@"(""|[^"])*"', String),
(r'"(\\\\|\\"|[^"\n])*["\n]', String),
(r"'\\.'|'[^\\]'", String.Char),
(r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?"
r"[flFLdD]?|0[xX][0-9a-fA-F]+[Ll]?", Number),
(r'#[ \t]*(if|endif|else|elif|define|undef|'
r'line|error|warning|region|endregion|pragma)\b.*?\n',
Comment.Preproc),
(r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Text,
Keyword)),
(r'(abstract|as|async|await|base|break|case|catch|'
r'checked|const|continue|default|delegate|'
r'do|else|enum|event|explicit|extern|false|finally|'
r'fixed|for|foreach|goto|if|implicit|in|interface|'
r'internal|is|lock|new|null|operator|'
r'out|override|params|private|protected|public|readonly|'
r'ref|return|sealed|sizeof|stackalloc|static|'
r'switch|this|throw|true|try|typeof|'
r'unchecked|unsafe|virtual|void|while|'
r'get|set|new|partial|yield|add|remove|value|alias|ascending|'
r'descending|from|group|into|orderby|select|where|'
r'join|equals)\b', Keyword),
(r'(global)(::)', bygroups(Keyword, Punctuation)),
(r'(bool|byte|char|decimal|double|dynamic|float|int|long|object|'
r'sbyte|short|string|uint|ulong|ushort|var)\b\??', Keyword.Type),
(r'(class|struct)(\s+)', bygroups(Keyword, Text), 'class'),
(r'(namespace|using)(\s+)', bygroups(Keyword, Text), 'namespace'),
(cs_ident, Name),
],
'class': [
(cs_ident, Name.Class, '#pop')
],
'namespace': [
(r'(?=\()', Text, '#pop'), # using (resource)
('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop')
]
}
def __init__(self, **options):
level = get_choice_opt(options, 'unicodelevel', list(self.tokens.keys()), 'basic')
if level not in self._all_tokens:
# compile the regexes now
self._tokens = self.__class__.process_tokendef(level)
else:
self._tokens = self._all_tokens[level]
RegexLexer.__init__(self, **options)
class NemerleLexer(RegexLexer):
"""
For `Nemerle <http://nemerle.org>`_ source code.
Additional options accepted:
`unicodelevel`
Determines which Unicode characters this lexer allows for identifiers.
The possible values are:
* ``none`` -- only the ASCII letters and numbers are allowed. This
is the fastest selection.
* ``basic`` -- all Unicode characters from the specification except
category ``Lo`` are allowed.
* ``full`` -- all Unicode characters as specified in the C# specs
are allowed. Note that this means a considerable slowdown since the
``Lo`` category has more than 40,000 characters in it!
The default value is ``basic``.
*New in Pygments 1.5.*
"""
name = 'Nemerle'
aliases = ['nemerle']
filenames = ['*.n']
mimetypes = ['text/x-nemerle'] # inferred
flags = re.MULTILINE | re.DOTALL | re.UNICODE
# for the range of allowed unicode characters in identifiers, see
# http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-334.pdf
levels = dict(
none = '@?[_a-zA-Z][a-zA-Z0-9_]*',
basic = ('@?[_' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl + ']' +
'[' + uni.Lu + uni.Ll + uni.Lt + uni.Lm + uni.Nl +
uni.Nd + uni.Pc + uni.Cf + uni.Mn + uni.Mc + ']*'),
full = ('@?(?:_|[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo',
'Nl') + '])'
+ '[^' + uni.allexcept('Lu', 'Ll', 'Lt', 'Lm', 'Lo', 'Nl',
'Nd', 'Pc', 'Cf', 'Mn', 'Mc') + ']*'),
)
tokens = {}
token_variants = True
for levelname, cs_ident in list(levels.items()):
tokens[levelname] = {
'root': [
# method names
(r'^([ \t]*(?:' + cs_ident + r'(?:\[\])?\s+)+?)' # return type
r'(' + cs_ident + ')' # method name
r'(\s*)(\()', # signature start
bygroups(using(this), Name.Function, Text, Punctuation)),
(r'^\s*\[.*?\]', Name.Attribute),
(r'[^\S\n]+', Text),
(r'\\\n', Text), # line continuation
(r'//.*?\n', Comment.Single),
(r'/[*].*?[*]/', Comment.Multiline),
(r'\n', Text),
(r'\$\s*"', String, 'splice-string'),
(r'\$\s*<#', String, 'splice-string2'),
(r'<#', String, 'recursive-string'),
(r'(<\[)\s*(' + cs_ident + ':)?', Keyword),
(r'\]\>', Keyword),
# quasiquotation only
(r'\$' + cs_ident, Name),
(r'(\$)(\()', bygroups(Name, Punctuation),
'splice-string-content'),
(r'[~!%^&*()+=|\[\]:;,.<>/?-]', Punctuation),
(r'[{}]', Punctuation),
(r'@"(""|[^"])*"', String),
(r'"(\\\\|\\"|[^"\n])*["\n]', String),
(r"'\\.'|'[^\\]'", String.Char),
(r"0[xX][0-9a-fA-F]+[Ll]?", Number),
(r"[0-9](\.[0-9]*)?([eE][+-][0-9]+)?[flFLdD]?", Number),
(r'#[ \t]*(if|endif|else|elif|define|undef|'
r'line|error|warning|region|endregion|pragma)\b.*?\n',
Comment.Preproc),
(r'\b(extern)(\s+)(alias)\b', bygroups(Keyword, Text,
Keyword)),
(r'(abstract|and|as|base|catch|def|delegate|'
r'enum|event|extern|false|finally|'
r'fun|implements|interface|internal|'
r'is|macro|match|matches|module|mutable|new|'
r'null|out|override|params|partial|private|'
r'protected|public|ref|sealed|static|'
r'syntax|this|throw|true|try|type|typeof|'
r'virtual|volatile|when|where|with|'
r'assert|assert2|async|break|checked|continue|do|else|'
r'ensures|for|foreach|if|late|lock|new|nolate|'
r'otherwise|regexp|repeat|requires|return|surroundwith|'
r'unchecked|unless|using|while|yield)\b', Keyword),
(r'(global)(::)', bygroups(Keyword, Punctuation)),
(r'(bool|byte|char|decimal|double|float|int|long|object|sbyte|'
r'short|string|uint|ulong|ushort|void|array|list)\b\??',
Keyword.Type),
(r'(:>?)\s*(' + cs_ident + r'\??)',
bygroups(Punctuation, Keyword.Type)),
(r'(class|struct|variant|module)(\s+)',
bygroups(Keyword, Text), 'class'),
(r'(namespace|using)(\s+)', bygroups(Keyword, Text),
'namespace'),
(cs_ident, Name),
],
'class': [
(cs_ident, Name.Class, '#pop')
],
'namespace': [
(r'(?=\()', Text, '#pop'), # using (resource)
('(' + cs_ident + r'|\.)+', Name.Namespace, '#pop')
],
'splice-string': [
(r'[^"$]', String),
(r'\$' + cs_ident, Name),
(r'(\$)(\()', bygroups(Name, Punctuation),
'splice-string-content'),
(r'\\"', String),
(r'"', String, '#pop')
],
'splice-string2': [
(r'[^#<>$]', String),
(r'\$' + cs_ident, Name),
(r'(\$)(\()', bygroups(Name, Punctuation),
'splice-string-content'),
(r'<#', String, '#push'),
(r'#>', String, '#pop')
],
'recursive-string': [
(r'[^#<>]', String),
(r'<#', String, '#push'),
(r'#>', String, '#pop')
],
'splice-string-content': [
(r'if|match', Keyword),
(r'[~!%^&*+=|\[\]:;,.<>/?-\\"$ ]', Punctuation),
(cs_ident, Name),
(r'\d+', Number),
(r'\(', Punctuation, '#push'),
(r'\)', Punctuation, '#pop')
]
}
def __init__(self, **options):
level = get_choice_opt(options, 'unicodelevel', list(self.tokens.keys()),
'basic')
if level not in self._all_tokens:
# compile the regexes now
self._tokens = self.__class__.process_tokendef(level)
else:
self._tokens = self._all_tokens[level]
RegexLexer.__init__(self, **options)
class BooLexer(RegexLexer):
"""
For `Boo <http://boo.codehaus.org/>`_ source code.
"""
name = 'Boo'
aliases = ['boo']
filenames = ['*.boo']
mimetypes = ['text/x-boo']
tokens = {
'root': [
(r'\s+', Text),
(r'(#|//).*$', Comment.Single),
(r'/[*]', Comment.Multiline, 'comment'),
(r'[]{}:(),.;[]', Punctuation),
(r'\\\n', Text),
(r'\\', Text),
(r'(in|is|and|or|not)\b', Operator.Word),
(r'/(\\\\|\\/|[^/\s])/', String.Regex),
(r'@/(\\\\|\\/|[^/])*/', String.Regex),
(r'=~|!=|==|<<|>>|[-+/*%=<>&^|]', Operator),
(r'(as|abstract|callable|constructor|destructor|do|import|'
r'enum|event|final|get|interface|internal|of|override|'
r'partial|private|protected|public|return|set|static|'
r'struct|transient|virtual|yield|super|and|break|cast|'
r'continue|elif|else|ensure|except|for|given|goto|if|in|'
r'is|isa|not|or|otherwise|pass|raise|ref|try|unless|when|'
r'while|from|as)\b', Keyword),
(r'def(?=\s+\(.*?\))', Keyword),
(r'(def)(\s+)', bygroups(Keyword, Text), 'funcname'),
(r'(class)(\s+)', bygroups(Keyword, Text), 'classname'),
(r'(namespace)(\s+)', bygroups(Keyword, Text), 'namespace'),
(r'(?<!\.)(true|false|null|self|__eval__|__switch__|array|'
r'assert|checked|enumerate|filter|getter|len|lock|map|'
r'matrix|max|min|normalArrayIndexing|print|property|range|'
r'rawArrayIndexing|required|typeof|unchecked|using|'
r'yieldAll|zip)\b', Name.Builtin),
(r'"""(\\\\|\\"|.*?)"""', String.Double),
(r'"(\\\\|\\"|[^"]*?)"', String.Double),
(r"'(\\\\|\\'|[^']*?)'", String.Single),
(r'[a-zA-Z_][a-zA-Z0-9_]*', Name),
(r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float),
(r'[0-9][0-9\.]*(ms?|d|h|s)', Number),
(r'0\d+', Number.Oct),
(r'0x[a-fA-F0-9]+', Number.Hex),
(r'\d+L', Number.Integer.Long),
(r'\d+', Number.Integer),
],
'comment': [
('/[*]', Comment.Multiline, '#push'),
('[*]/', Comment.Multiline, '#pop'),
('[^/*]', Comment.Multiline),
('[*/]', Comment.Multiline)
],
'funcname': [
('[a-zA-Z_][a-zA-Z0-9_]*', Name.Function, '#pop')
],
'classname': [
('[a-zA-Z_][a-zA-Z0-9_]*', Name.Class, '#pop')
],
'namespace': [
('[a-zA-Z_][a-zA-Z0-9_.]*', Name.Namespace, '#pop')
]
}
class VbNetLexer(RegexLexer):
"""
For
`Visual Basic.NET <http://msdn2.microsoft.com/en-us/vbasic/default.aspx>`_
source code.
"""
name = 'VB.net'
aliases = ['vb.net', 'vbnet']
filenames = ['*.vb', '*.bas']
mimetypes = ['text/x-vbnet', 'text/x-vba'] # (?)
flags = re.MULTILINE | re.IGNORECASE
tokens = {
'root': [
(r'^\s*<.*?>', Name.Attribute),
(r'\s+', Text),
(r'\n', Text),
(r'rem\b.*?\n', Comment),
(r"'.*?\n", Comment),
(r'#If\s.*?\sThen|#ElseIf\s.*?\sThen|#End\s+If|#Const|'
r'#ExternalSource.*?\n|#End\s+ExternalSource|'
r'#Region.*?\n|#End\s+Region|#ExternalChecksum',
Comment.Preproc),
(r'[\(\){}!#,.:]', Punctuation),
(r'Option\s+(Strict|Explicit|Compare)\s+'
r'(On|Off|Binary|Text)', Keyword.Declaration),
(r'(?<!\.)(AddHandler|Alias|'
r'ByRef|ByVal|Call|Case|Catch|CBool|CByte|CChar|CDate|'
r'CDec|CDbl|CInt|CLng|CObj|Continue|CSByte|CShort|'
r'CSng|CStr|CType|CUInt|CULng|CUShort|Declare|'
r'Default|Delegate|DirectCast|Do|Each|Else|ElseIf|'
r'EndIf|Erase|Error|Event|Exit|False|Finally|For|'
r'Friend|Get|Global|GoSub|GoTo|Handles|If|'
r'Implements|Inherits|Interface|'
r'Let|Lib|Loop|Me|MustInherit|'
r'MustOverride|MyBase|MyClass|Narrowing|New|Next|'
r'Not|Nothing|NotInheritable|NotOverridable|Of|On|'
r'Operator|Option|Optional|Overloads|Overridable|'
r'Overrides|ParamArray|Partial|Private|Protected|'
r'Public|RaiseEvent|ReadOnly|ReDim|RemoveHandler|Resume|'
r'Return|Select|Set|Shadows|Shared|Single|'
r'Static|Step|Stop|SyncLock|Then|'
r'Throw|To|True|Try|TryCast|Wend|'
r'Using|When|While|Widening|With|WithEvents|'
r'WriteOnly)\b', Keyword),
(r'(?<!\.)End\b', Keyword, 'end'),
(r'(?<!\.)(Dim|Const)\b', Keyword, 'dim'),
(r'(?<!\.)(Function|Sub|Property)(\s+)',
bygroups(Keyword, Text), 'funcname'),
(r'(?<!\.)(Class|Structure|Enum)(\s+)',
bygroups(Keyword, Text), 'classname'),
(r'(?<!\.)(Module|Namespace|Imports)(\s+)',
bygroups(Keyword, Text), 'namespace'),
(r'(?<!\.)(Boolean|Byte|Char|Date|Decimal|Double|Integer|Long|'
r'Object|SByte|Short|Single|String|Variant|UInteger|ULong|'
r'UShort)\b', Keyword.Type),
(r'(?<!\.)(AddressOf|And|AndAlso|As|GetType|In|Is|IsNot|Like|Mod|'
r'Or|OrElse|TypeOf|Xor)\b', Operator.Word),
(r'&=|[*]=|/=|\\=|\^=|\+=|-=|<<=|>>=|<<|>>|:=|'
r'<=|>=|<>|[-&*/\\^+=<>]',
Operator),
('"', String, 'string'),
('[a-zA-Z_][a-zA-Z0-9_]*[%&@!#$]?', Name),
('#.*?#', Literal.Date),
(r'(\d+\.\d*|\d*\.\d+)([fF][+-]?[0-9]+)?', Number.Float),
(r'\d+([SILDFR]|US|UI|UL)?', Number.Integer),
(r'&H[0-9a-f]+([SILDFR]|US|UI|UL)?', Number.Integer),
(r'&O[0-7]+([SILDFR]|US|UI|UL)?', Number.Integer),
(r'_\n', Text), # Line continuation
],
'string': [
(r'""', String),
(r'"C?', String, '#pop'),
(r'[^"]+', String),
],
'dim': [
(r'[a-z_][a-z0-9_]*', Name.Variable, '#pop'),
(r'', Text, '#pop'), # any other syntax
],
'funcname': [
(r'[a-z_][a-z0-9_]*', Name.Function, '#pop'),
],
'classname': [
(r'[a-z_][a-z0-9_]*', Name.Class, '#pop'),
],
'namespace': [
(r'[a-z_][a-z0-9_.]*', Name.Namespace, '#pop'),
],
'end': [
(r'\s+', Text),
(r'(Function|Sub|Property|Class|Structure|Enum|Module|Namespace)\b',
Keyword, '#pop'),
(r'', Text, '#pop'),
]
}
class GenericAspxLexer(RegexLexer):
"""
Lexer for ASP.NET pages.
"""
name = 'aspx-gen'
filenames = []
mimetypes = []
flags = re.DOTALL
tokens = {
'root': [
(r'(<%[@=#]?)(.*?)(%>)', bygroups(Name.Tag, Other, Name.Tag)),
(r'(<script.*?>)(.*?)(</script>)', bygroups(using(XmlLexer),
Other,
using(XmlLexer))),
(r'(.+?)(?=<)', using(XmlLexer)),
(r'.+', using(XmlLexer)),
],
}
#TODO support multiple languages within the same source file
class CSharpAspxLexer(DelegatingLexer):
"""
Lexer for highligting C# within ASP.NET pages.
"""
name = 'aspx-cs'
aliases = ['aspx-cs']
filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd']
mimetypes = []
def __init__(self, **options):
super(CSharpAspxLexer, self).__init__(CSharpLexer,GenericAspxLexer,
**options)
def analyse_text(text):
if re.search(r'Page\s*Language="C#"', text, re.I) is not None:
return 0.2
elif re.search(r'script[^>]+language=["\']C#', text, re.I) is not None:
return 0.15
class VbNetAspxLexer(DelegatingLexer):
"""
Lexer for highligting Visual Basic.net within ASP.NET pages.
"""
name = 'aspx-vb'
aliases = ['aspx-vb']
filenames = ['*.aspx', '*.asax', '*.ascx', '*.ashx', '*.asmx', '*.axd']
mimetypes = []
def __init__(self, **options):
super(VbNetAspxLexer, self).__init__(VbNetLexer,GenericAspxLexer,
**options)
def analyse_text(text):
if re.search(r'Page\s*Language="Vb"', text, re.I) is not None:
return 0.2
elif re.search(r'script[^>]+language=["\']vb', text, re.I) is not None:
return 0.15
# Very close to functional.OcamlLexer
class FSharpLexer(RegexLexer):
"""
For the F# language (version 3.0).
*New in Pygments 1.5.*
"""
name = 'FSharp'
aliases = ['fsharp']
filenames = ['*.fs', '*.fsi']
mimetypes = ['text/x-fsharp']
keywords = [
'abstract', 'as', 'assert', 'base', 'begin', 'class', 'default',
'delegate', 'do!', 'do', 'done', 'downcast', 'downto', 'elif', 'else',
'end', 'exception', 'extern', 'false', 'finally', 'for', 'function',
'fun', 'global', 'if', 'inherit', 'inline', 'interface', 'internal',
'in', 'lazy', 'let!', 'let', 'match', 'member', 'module', 'mutable',
'namespace', 'new', 'null', 'of', 'open', 'override', 'private', 'public',
'rec', 'return!', 'return', 'select', 'static', 'struct', 'then', 'to',
'true', 'try', 'type', 'upcast', 'use!', 'use', 'val', 'void', 'when',
'while', 'with', 'yield!', 'yield',
]
# Reserved words; cannot hurt to color them as keywords too.
keywords += [
'atomic', 'break', 'checked', 'component', 'const', 'constraint',
'constructor', 'continue', 'eager', 'event', 'external', 'fixed',
'functor', 'include', 'method', 'mixin', 'object', 'parallel',
'process', 'protected', 'pure', 'sealed', 'tailcall', 'trait',
'virtual', 'volatile',
]
keyopts = [
'!=', '#', '&&', '&', '\(', '\)', '\*', '\+', ',', '-\.',
'->', '-', '\.\.', '\.', '::', ':=', ':>', ':', ';;', ';', '<-',
'<\]', '<', '>\]', '>', '\?\?', '\?', '\[<', '\[\|', '\[', '\]',
'_', '`', '{', '\|\]', '\|', '}', '~', '<@@', '<@', '=', '@>', '@@>',
]
operators = r'[!$%&*+\./:<=>?@^|~-]'
word_operators = ['and', 'or', 'not']
prefix_syms = r'[!?~]'
infix_syms = r'[=<>@^|&+\*/$%-]'
primitives = [
'sbyte', 'byte', 'char', 'nativeint', 'unativeint', 'float32', 'single',
'float', 'double', 'int8', 'uint8', 'int16', 'uint16', 'int32',
'uint32', 'int64', 'uint64', 'decimal', 'unit', 'bool', 'string',
'list', 'exn', 'obj', 'enum',
]
# See http://msdn.microsoft.com/en-us/library/dd233181.aspx and/or
# http://fsharp.org/about/files/spec.pdf for reference. Good luck.
tokens = {
'escape-sequence': [
(r'\\[\\\"\'ntbrafv]', String.Escape),
(r'\\[0-9]{3}', String.Escape),
(r'\\u[0-9a-fA-F]{4}', String.Escape),
(r'\\U[0-9a-fA-F]{8}', String.Escape),
],
'root': [
(r'\s+', Text),
(r'\(\)|\[\]', Name.Builtin.Pseudo),
(r'\b(?<!\.)([A-Z][A-Za-z0-9_\']*)(?=\s*\.)',
Name.Namespace, 'dotted'),
(r'\b([A-Z][A-Za-z0-9_\']*)', Name),
(r'///.*?\n', String.Doc),
(r'//.*?\n', Comment.Single),
(r'\(\*(?!\))', Comment, 'comment'),
(r'@"', String, 'lstring'),
(r'"""', String, 'tqs'),
(r'"', String, 'string'),
(r'\b(open|module)(\s+)([a-zA-Z0-9_.]+)',
bygroups(Keyword, Text, Name.Namespace)),
(r'\b(let!?)(\s+)([a-zA-Z0-9_]+)',
bygroups(Keyword, Text, Name.Variable)),
(r'\b(type)(\s+)([a-zA-Z0-9_]+)',
bygroups(Keyword, Text, Name.Class)),
(r'\b(member|override)(\s+)([a-zA-Z0-9_]+)(\.)([a-zA-Z0-9_]+)',
bygroups(Keyword, Text, Name, Punctuation, Name.Function)),
(r'\b(%s)\b' % '|'.join(keywords), Keyword),
(r'(%s)' % '|'.join(keyopts), Operator),
(r'(%s|%s)?%s' % (infix_syms, prefix_syms, operators), Operator),
(r'\b(%s)\b' % '|'.join(word_operators), Operator.Word),
(r'\b(%s)\b' % '|'.join(primitives), Keyword.Type),
(r'#[ \t]*(if|endif|else|line|nowarn|light|\d+)\b.*?\n',
Comment.Preproc),
(r"[^\W\d][\w']*", Name),
(r'\d[\d_]*[uU]?[yslLnQRZINGmM]?', Number.Integer),
(r'0[xX][\da-fA-F][\da-fA-F_]*[uU]?[yslLn]?[fF]?', Number.Hex),
(r'0[oO][0-7][0-7_]*[uU]?[yslLn]?', Number.Oct),
(r'0[bB][01][01_]*[uU]?[yslLn]?', Number.Binary),
(r'-?\d[\d_]*(.[\d_]*)?([eE][+\-]?\d[\d_]*)[fFmM]?',
Number.Float),
(r"'(?:(\\[\\\"'ntbr ])|(\\[0-9]{3})|(\\x[0-9a-fA-F]{2}))'B?",
String.Char),
(r"'.'", String.Char),
(r"'", Keyword), # a stray quote is another syntax element
(r'[~?][a-z][\w\']*:', Name.Variable),
],
'dotted': [
(r'\s+', Text),
(r'\.', Punctuation),
(r'[A-Z][A-Za-z0-9_\']*(?=\s*\.)', Name.Namespace),
(r'[A-Z][A-Za-z0-9_\']*', Name, '#pop'),
(r'[a-z_][A-Za-z0-9_\']*', Name, '#pop'),
],
'comment': [
(r'[^(*)@"]+', Comment),
(r'\(\*', Comment, '#push'),
(r'\*\)', Comment, '#pop'),
# comments cannot be closed within strings in comments
(r'@"', String, 'lstring'),
(r'"""', String, 'tqs'),
(r'"', String, 'string'),
(r'[(*)@]', Comment),
],
'string': [
(r'[^\\"]+', String),
include('escape-sequence'),
(r'\\\n', String),
(r'\n', String), # newlines are allowed in any string
(r'"B?', String, '#pop'),
],
'lstring': [
(r'[^"]+', String),
(r'\n', String),
(r'""', String),
(r'"B?', String, '#pop'),
],
'tqs': [
(r'[^"]+', String),
(r'\n', String),
(r'"""B?', String, '#pop'),
(r'"', String),
],
} | unknown | codeparrot/codeparrot-clean | ||
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Point of Sale',
'version': '1.0.1',
'category': 'Point Of Sale',
'sequence': 6,
'summary': 'Touchscreen Interface for Shops',
'description': """
Quick and Easy sale process
===========================
This module allows you to manage your shop sales very easily with a fully web based touchscreen interface.
It is compatible with all PC tablets and the iPad, offering multiple payment methods.
Product selection can be done in several ways:
* Using a barcode reader
* Browsing through categories of products or via a text search.
Main Features
-------------
* Fast encoding of the sale
* Choose one payment method (the quick way) or split the payment between several payment methods
* Computation of the amount of money to return
* Create and confirm the picking list automatically
* Allows the user to create an invoice automatically
* Refund previous sales
""",
'author': 'OpenERP SA',
'depends': ['sale_stock'],
'data': [
'data/report_paperformat.xml',
'security/point_of_sale_security.xml',
'security/ir.model.access.csv',
'wizard/pos_box.xml',
'wizard/pos_confirm.xml',
'wizard/pos_details.xml',
'wizard/pos_discount.xml',
'wizard/pos_open_statement.xml',
'wizard/pos_payment.xml',
'wizard/pos_session_opening.xml',
'views/templates.xml',
'point_of_sale_report.xml',
'point_of_sale_view.xml',
'point_of_sale_sequence.xml',
'point_of_sale_data.xml',
'report/pos_order_report_view.xml',
'point_of_sale_workflow.xml',
'account_statement_view.xml',
'account_statement_report.xml',
'res_users_view.xml',
'res_partner_view.xml',
'views/report_statement.xml',
'views/report_usersproduct.xml',
'views/report_receipt.xml',
'views/report_saleslines.xml',
'views/report_detailsofsales.xml',
'views/report_payment.xml',
'views/report_sessionsummary.xml',
'views/point_of_sale.xml',
],
'demo': [
'point_of_sale_demo.xml',
'account_statement_demo.xml',
],
'test': [
'test/00_register_open.yml',
'test/01_order_to_payment.yml',
'test/02_order_to_invoice.yml',
'test/point_of_sale_report.yml',
'test/account_statement_reports.yml',
],
'installable': True,
'application': True,
'qweb': ['static/src/xml/pos.xml'],
'website': 'https://www.odoo.com/page/point-of-sale',
'auto_install': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | unknown | codeparrot/codeparrot-clean | ||
// Copyright 2022 The Abseil 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
//
// 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.
#ifndef ABSL_LOG_INTERNAL_LOG_IMPL_H_
#define ABSL_LOG_INTERNAL_LOG_IMPL_H_
#include "absl/log/internal/conditions.h"
#include "absl/log/internal/log_message.h"
#include "absl/log/internal/strip.h"
// ABSL_LOG()
#define ABSL_LOG_INTERNAL_LOG_IMPL(severity) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATELESS, true) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
// ABSL_PLOG()
#define ABSL_LOG_INTERNAL_PLOG_IMPL(severity) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATELESS, true) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream() \
.WithPerror()
// ABSL_DLOG()
#ifndef NDEBUG
#define ABSL_LOG_INTERNAL_DLOG_IMPL(severity) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATELESS, true) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#else
#define ABSL_LOG_INTERNAL_DLOG_IMPL(severity) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATELESS, false) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#endif
#define ABSL_LOG_INTERNAL_LOG_IF_IMPL(severity, condition) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATELESS, condition) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_PLOG_IF_IMPL(severity, condition) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATELESS, condition) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream() \
.WithPerror()
#ifndef NDEBUG
#define ABSL_LOG_INTERNAL_DLOG_IF_IMPL(severity, condition) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATELESS, condition) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#else
#define ABSL_LOG_INTERNAL_DLOG_IF_IMPL(severity, condition) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATELESS, false && (condition)) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#endif
// ABSL_LOG_EVERY_N
#define ABSL_LOG_INTERNAL_LOG_EVERY_N_IMPL(severity, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, true)(EveryN, n) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
// ABSL_LOG_FIRST_N
#define ABSL_LOG_INTERNAL_LOG_FIRST_N_IMPL(severity, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, true)(FirstN, n) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
// ABSL_LOG_EVERY_POW_2
#define ABSL_LOG_INTERNAL_LOG_EVERY_POW_2_IMPL(severity) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, true)(EveryPow2) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
// ABSL_LOG_EVERY_N_SEC
#define ABSL_LOG_INTERNAL_LOG_EVERY_N_SEC_IMPL(severity, n_seconds) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, true)(EveryNSec, n_seconds) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_PLOG_EVERY_N_IMPL(severity, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, true)(EveryN, n) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream() \
.WithPerror()
#define ABSL_LOG_INTERNAL_PLOG_FIRST_N_IMPL(severity, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, true)(FirstN, n) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream() \
.WithPerror()
#define ABSL_LOG_INTERNAL_PLOG_EVERY_POW_2_IMPL(severity) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, true)(EveryPow2) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream() \
.WithPerror()
#define ABSL_LOG_INTERNAL_PLOG_EVERY_N_SEC_IMPL(severity, n_seconds) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, true)(EveryNSec, n_seconds) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream() \
.WithPerror()
#ifndef NDEBUG
#define ABSL_LOG_INTERNAL_DLOG_EVERY_N_IMPL(severity, n) \
ABSL_LOG_INTERNAL_CONDITION_INFO(STATEFUL, true) \
(EveryN, n) ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_FIRST_N_IMPL(severity, n) \
ABSL_LOG_INTERNAL_CONDITION_INFO(STATEFUL, true) \
(FirstN, n) ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_EVERY_POW_2_IMPL(severity) \
ABSL_LOG_INTERNAL_CONDITION_INFO(STATEFUL, true) \
(EveryPow2) ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_EVERY_N_SEC_IMPL(severity, n_seconds) \
ABSL_LOG_INTERNAL_CONDITION_INFO(STATEFUL, true) \
(EveryNSec, n_seconds) ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#else // def NDEBUG
#define ABSL_LOG_INTERNAL_DLOG_EVERY_N_IMPL(severity, n) \
ABSL_LOG_INTERNAL_CONDITION_INFO(STATEFUL, false) \
(EveryN, n) ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_FIRST_N_IMPL(severity, n) \
ABSL_LOG_INTERNAL_CONDITION_INFO(STATEFUL, false) \
(FirstN, n) ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_EVERY_POW_2_IMPL(severity) \
ABSL_LOG_INTERNAL_CONDITION_INFO(STATEFUL, false) \
(EveryPow2) ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_EVERY_N_SEC_IMPL(severity, n_seconds) \
ABSL_LOG_INTERNAL_CONDITION_INFO(STATEFUL, false) \
(EveryNSec, n_seconds) ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#endif // def NDEBUG
#define ABSL_LOG_INTERNAL_LOG_IF_EVERY_N_IMPL(severity, condition, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(EveryN, n) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_LOG_IF_FIRST_N_IMPL(severity, condition, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(FirstN, n) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_LOG_IF_EVERY_POW_2_IMPL(severity, condition) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(EveryPow2) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_LOG_IF_EVERY_N_SEC_IMPL(severity, condition, \
n_seconds) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(EveryNSec, \
n_seconds) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_PLOG_IF_EVERY_N_IMPL(severity, condition, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(EveryN, n) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream() \
.WithPerror()
#define ABSL_LOG_INTERNAL_PLOG_IF_FIRST_N_IMPL(severity, condition, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(FirstN, n) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream() \
.WithPerror()
#define ABSL_LOG_INTERNAL_PLOG_IF_EVERY_POW_2_IMPL(severity, condition) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(EveryPow2) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream() \
.WithPerror()
#define ABSL_LOG_INTERNAL_PLOG_IF_EVERY_N_SEC_IMPL(severity, condition, \
n_seconds) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(EveryNSec, \
n_seconds) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream() \
.WithPerror()
#ifndef NDEBUG
#define ABSL_LOG_INTERNAL_DLOG_IF_EVERY_N_IMPL(severity, condition, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(EveryN, n) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_IF_FIRST_N_IMPL(severity, condition, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(FirstN, n) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_IF_EVERY_POW_2_IMPL(severity, condition) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(EveryPow2) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_IF_EVERY_N_SEC_IMPL(severity, condition, \
n_seconds) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, condition)(EveryNSec, \
n_seconds) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#else // def NDEBUG
#define ABSL_LOG_INTERNAL_DLOG_IF_EVERY_N_IMPL(severity, condition, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, false && (condition))( \
EveryN, n) ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_IF_FIRST_N_IMPL(severity, condition, n) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, false && (condition))( \
FirstN, n) ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_IF_EVERY_POW_2_IMPL(severity, condition) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, false && (condition))( \
EveryPow2) ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#define ABSL_LOG_INTERNAL_DLOG_IF_EVERY_N_SEC_IMPL(severity, condition, \
n_seconds) \
ABSL_LOG_INTERNAL_CONDITION##severity(STATEFUL, false && (condition))( \
EveryNSec, n_seconds) \
ABSL_LOGGING_INTERNAL_LOG##severity.InternalStream()
#endif // def NDEBUG
#endif // ABSL_LOG_INTERNAL_LOG_IMPL_H_ | c | github | https://github.com/mysql/mysql-server | extra/abseil/abseil-cpp-20230802.1/absl/log/internal/log_impl.h |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the OpenCV Foundation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#include "test_precomp.hpp"
namespace opencv_test { namespace {
TEST(Core_LPSolver, regression_basic){
cv::Mat A,B,z,etalon_z;
#if 1
//cormen's example #1
A=(cv::Mat_<double>(3,1)<<3,1,2);
B=(cv::Mat_<double>(3,4)<<1,1,3,30,2,2,5,24,4,1,2,36);
std::cout<<"here A goes\n"<<A<<"\n";
cv::solveLP(A,B,z);
std::cout<<"here z goes\n"<<z<<"\n";
etalon_z=(cv::Mat_<double>(3,1)<<8,4,0);
ASSERT_LT(cvtest::norm(z, etalon_z, cv::NORM_L1), 1e-12);
#endif
#if 1
//cormen's example #2
A=(cv::Mat_<double>(1,2)<<18,12.5);
B=(cv::Mat_<double>(3,3)<<1,1,20,1,0,20,0,1,16);
std::cout<<"here A goes\n"<<A<<"\n";
cv::solveLP(A,B,z);
std::cout<<"here z goes\n"<<z<<"\n";
etalon_z=(cv::Mat_<double>(2,1)<<20,0);
ASSERT_LT(cvtest::norm(z, etalon_z, cv::NORM_L1), 1e-12);
#endif
#if 1
//cormen's example #3
A=(cv::Mat_<double>(1,2)<<5,-3);
B=(cv::Mat_<double>(2,3)<<1,-1,1,2,1,2);
std::cout<<"here A goes\n"<<A<<"\n";
cv::solveLP(A,B,z);
std::cout<<"here z goes\n"<<z<<"\n";
etalon_z=(cv::Mat_<double>(2,1)<<1,0);
ASSERT_LT(cvtest::norm(z, etalon_z, cv::NORM_L1), 1e-12);
#endif
}
TEST(Core_LPSolver, regression_init_unfeasible){
cv::Mat A,B,z,etalon_z;
#if 1
//cormen's example #4 - unfeasible
A=(cv::Mat_<double>(1,3)<<-1,-1,-1);
B=(cv::Mat_<double>(2,4)<<-2,-7.5,-3,-10000,-20,-5,-10,-30000);
std::cout<<"here A goes\n"<<A<<"\n";
cv::solveLP(A,B,z);
std::cout<<"here z goes\n"<<z<<"\n";
etalon_z=(cv::Mat_<double>(3,1)<<1250,1000,0);
ASSERT_LT(cvtest::norm(z, etalon_z, cv::NORM_L1), 1e-12);
#endif
}
TEST(DISABLED_Core_LPSolver, regression_absolutely_unfeasible){
cv::Mat A,B,z,etalon_z;
#if 1
//trivial absolutely unfeasible example
A=(cv::Mat_<double>(1,1)<<1);
B=(cv::Mat_<double>(2,2)<<1,-1);
std::cout<<"here A goes\n"<<A<<"\n";
int res=cv::solveLP(A,B,z);
ASSERT_EQ(res,-1);
#endif
}
TEST(Core_LPSolver, regression_multiple_solutions){
cv::Mat A,B,z,etalon_z;
#if 1
//trivial example with multiple solutions
A=(cv::Mat_<double>(2,1)<<1,1);
B=(cv::Mat_<double>(1,3)<<1,1,1);
std::cout<<"here A goes\n"<<A<<"\n";
int res=cv::solveLP(A,B,z);
printf("res=%d\n",res);
printf("scalar %g\n",z.dot(A));
std::cout<<"here z goes\n"<<z<<"\n";
ASSERT_EQ(res,1);
ASSERT_LT(fabs(z.dot(A) - 1), DBL_EPSILON);
#endif
}
TEST(Core_LPSolver, regression_cycling){
cv::Mat A,B,z,etalon_z;
#if 1
//example with cycling from http://people.orie.cornell.edu/miketodd/or630/SimplexCyclingExample.pdf
A=(cv::Mat_<double>(4,1)<<10,-57,-9,-24);
B=(cv::Mat_<double>(3,5)<<0.5,-5.5,-2.5,9,0,0.5,-1.5,-0.5,1,0,1,0,0,0,1);
std::cout<<"here A goes\n"<<A<<"\n";
int res=cv::solveLP(A,B,z);
printf("res=%d\n",res);
printf("scalar %g\n",z.dot(A));
std::cout<<"here z goes\n"<<z<<"\n";
ASSERT_LT(fabs(z.dot(A) - 1), DBL_EPSILON);
//ASSERT_EQ(res,1);
#endif
}
TEST(Core_LPSolver, issue_12337)
{
Mat A=(cv::Mat_<double>(3,1)<<3,1,2);
Mat B=(cv::Mat_<double>(3,4)<<1,1,3,30,2,2,5,24,4,1,2,36);
Mat1f z_float; cv::solveLP(A, B, z_float);
Mat1d z_double; cv::solveLP(A, B, z_double);
Mat1i z_int; cv::solveLP(A, B, z_int);
EXPECT_ANY_THROW(Mat1b z_8u; cv::solveLP(A, B, z_8u));
}
// NOTE: Test parameters found experimentally to get numerically inaccurate result.
// The test behaviour may change after algorithm tuning and may removed.
TEST(Core_LPSolver, issue_12343)
{
Mat A = (cv::Mat_<double>(4, 1) << 3., 3., 3., 4.);
Mat B = (cv::Mat_<double>(4, 5) << 0., 1., 4., 4., 3.,
3., 1., 2., 2., 3.,
4., 4., 0., 1., 4.,
4., 0., 4., 1., 4.);
Mat z;
int result = cv::solveLP(A, B, z);
EXPECT_EQ(SOLVELP_LOST, result);
}
}} // namespace | cpp | github | https://github.com/opencv/opencv | modules/core/test/test_lpsolver.cpp |
"""Forms for the ``paypal_express_checkout`` app."""
import httplib
import logging
import urllib2
import urlparse
from django import forms
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import redirect
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from .constants import PAYMENT_STATUS, PAYPAL_DEFAULTS
from .models import (
Item,
PaymentTransaction,
PaymentTransactionError,
PurchasedItem,
)
from .settings import API_URL, LOGIN_URL
from .utils import urlencode
logger = logging.getLogger(__name__)
CURRENCYCODE = getattr(settings, 'PAYPAL_CURRENCYCODE', 'USD')
class PayPalFormMixin(object):
"""Common methods for the PayPal forms."""
def call_paypal(self, api_url, post_data, transaction=None):
"""
Gets the PayPal API URL from the settings and posts ``post_data``.
:param api_url: The API endpoint that should be called.
:param post_data: The full post data for PayPal containing all needed
information for the current transaction step.
:param transaction: If you already have a transaction, pass it into
this method so that it can be logged in case of an error.
"""
data = urlencode(post_data)
try:
response = urllib2.urlopen(api_url, data=data)
except (
urllib2.HTTPError,
urllib2.URLError,
httplib.HTTPException) as ex:
self.log_error(
ex, api_url=api_url, request_data=data,
transaction=transaction)
else:
parsed_response = urlparse.parse_qs(response.read())
return parsed_response
def get_cancel_url(self):
"""Returns the paypal cancel url."""
return settings.HOSTNAME + reverse(
'paypal_canceled', kwargs=self.get_url_kwargs())
def get_error_url(self):
"""Returns the url of the payment error page."""
return reverse('paypal_error')
def get_notify_url(self):
"""Returns the notification (ipn) url."""
return settings.HOSTNAME + reverse('ipn_listener')
def get_return_url(self):
"""Returns the paypal return url."""
return settings.HOSTNAME + reverse(
'paypal_confirm', kwargs=self.get_url_kwargs())
def get_success_url(self):
"""Returns the url of the payment success page."""
return reverse('paypal_success')
def log_error(self, error_message, api_url=None, request_data=None,
transaction=None):
"""
Saves error information as a ``PaymentTransactionError`` object.
:param error_message: The message of the exception or response string
from PayPal.
"""
payment_error = PaymentTransactionError()
payment_error.user = self.user
payment_error.response = error_message
payment_error.paypal_api_url = api_url
payment_error.request_data = request_data
payment_error.transaction = transaction
payment_error.save()
return payment_error
class DoExpressCheckoutForm(PayPalFormMixin, forms.Form):
"""
Takes the input from the ``DoExpressCheckoutView``, validates it and
takes care of the PayPal API operations.
"""
token = forms.CharField()
PayerID = forms.CharField()
def __init__(self, user, *args, **kwargs):
self.user = user
super(DoExpressCheckoutForm, self).__init__(*args, **kwargs)
try:
self.transaction = PaymentTransaction.objects.get(
user=user, transaction_id=self.data['token'])
except PaymentTransaction.DoesNotExist:
raise Http404
def get_post_data(self):
"""Creates the post data dictionary to send to PayPal."""
post_data = PAYPAL_DEFAULTS.copy()
items = self.transaction.purchaseditem_set.all()
currency = None
if len(items) != 0:
if getattr(items[0].item, 'currency', None) is not None:
currency = items[0].item.currency
elif getattr(
items[0].content_object, 'currency', None) is not None:
currency = items[0].content_object.currency
if not currency:
currency = CURRENCYCODE
post_data.update({
'METHOD': 'DoExpressCheckoutPayment',
'TOKEN': self.transaction.transaction_id,
'PAYERID': self.data['PayerID'],
'PAYMENTREQUEST_0_AMT': self.transaction.value,
'PAYMENTREQUEST_0_NOTIFYURL': self.get_notify_url(),
'PAYMENTREQUEST_0_CURRENCYCODE': currency,
})
return post_data
def do_checkout(self):
"""Calls PayPal to make the 'DoExpressCheckoutPayment' procedure."""
post_data = self.get_post_data()
api_url = API_URL
parsed_response = self.call_paypal(api_url, post_data)
if parsed_response.get('ACK')[0] == 'Success':
transaction_id = parsed_response.get(
'PAYMENTINFO_0_TRANSACTIONID')[0]
self.transaction.transaction_id = transaction_id
self.transaction.status = PAYMENT_STATUS['pending']
self.transaction.save()
return redirect(self.get_success_url())
elif parsed_response.get('ACK')[0] == 'Failure':
self.transaction.status = PAYMENT_STATUS['canceled']
self.transaction.save()
# we have to do urlencode here to make the post data more readable
# in the error log
post_data_encoded = urlencode(post_data)
self.log_error(
parsed_response, api_url, request_data=post_data_encoded,
transaction=self.transaction)
return redirect(self.get_error_url())
class SetExpressCheckoutFormMixin(PayPalFormMixin, forms.Form):
"""
Base form class for all forms invoking the ``SetExpressCheckout`` PayPal
API operation, providing the general method skeleton.
Also this is to be used to construct custom forms.
:param user: The user making the purchase
:param redirect: If ``True``, the form will return a HttpResponseRedirect,
otherwise it will only return the redirect URL. This can be useful if
you want to use this form in an AJAX view.
"""
def __init__(self, user, redirect=True, *args, **kwargs):
self.redirect = redirect
self.user = user
super(SetExpressCheckoutFormMixin, self).__init__(*args, **kwargs)
def get_content_object(self):
"""
Can be overridden to return a different content object for the
PaymentTransaction model.
This is useful if you want e.g. have one of your models assigned to the
transaction for easier identification.
"""
# TODO for now it should return the user, although I know, that the
# user is already present in the user field of the PaymentTransaction
# model.
# Maybe we can remove the user field safely in exchange for the generic
# relation only.
return self.user
def get_item(self):
"""Obsolete. Just implement ``get_items_and_quantities``."""
raise NotImplementedError
def get_quantity(self):
"""Obsolete. Just implement ``get_items_and_quantities``."""
raise NotImplementedError
def get_items_and_quantities(self):
"""
Returns the items and quantities and content objects.
Content objects are optional, return None if you don't need it.
Should return a list of tuples:
``[(item, quantity, content_object), ]``
"""
logger.warning(
'Deprecation warning: Please implement get_items_and_quantities on'
' your SetExpressCheckoutForm. Do not use get_item and'
' get_quantity any more.')
return [(self.get_item(), self.get_quantity(), None), ]
def get_post_data(self, item_quantity_list):
"""Creates the post data dictionary to send to PayPal."""
post_data = PAYPAL_DEFAULTS.copy()
total_value = 0
item_index = 0
for item, quantity, content_type in item_quantity_list:
if not quantity:
# If a user chose quantity 0, we don't include it
continue
total_value += item.value * quantity
post_data.update({
'L_PAYMENTREQUEST_0_NAME{0}'.format(
item_index): item.name,
'L_PAYMENTREQUEST_0_DESC{0}'.format(
item_index): item.description,
'L_PAYMENTREQUEST_0_AMT{0}'.format(
item_index): item.value,
'L_PAYMENTREQUEST_0_QTY{0}'.format(
item_index): quantity,
})
item_index += 1
if (
len(item_quantity_list) != 0 and
getattr(item_quantity_list[0][0], 'currency') is not None):
currency = item_quantity_list[0][0].currency
else:
currency = CURRENCYCODE
post_data.update({
'METHOD': 'SetExpressCheckout',
'PAYMENTREQUEST_0_AMT': total_value,
'PAYMENTREQUEST_0_ITEMAMT': total_value,
'RETURNURL': self.get_return_url(),
'CANCELURL': self.get_cancel_url(),
'PAYMENTREQUEST_0_CURRENCYCODE': currency,
})
return post_data
def get_url_kwargs(self):
"""Provide additional url kwargs, by overriding this method."""
return {}
def post_transaction_save(self, transaction, item_quantity_list):
"""
Override this method if you need to create further objects.
Once we got a successful response from PayPal we can create a
Transaction with status "checkout". You might want to create or
manipulate further objects in your app at this point.
For example you might ask for user's the t-shirt size on your checkout
form. This a good place to save the user's choice on the UserProfile.
"""
return
def set_checkout(self):
"""
Calls PayPal to make the 'SetExpressCheckout' procedure.
:param items: A list of ``Item`` objects.
"""
item_quantity_list = self.get_items_and_quantities()
post_data = self.get_post_data(item_quantity_list)
api_url = API_URL
# making the post to paypal and handling the results
parsed_response = self.call_paypal(api_url, post_data)
if parsed_response.get('ACK')[0] == 'Success':
token = parsed_response.get('TOKEN')[0]
transaction = PaymentTransaction(
user=self.user,
date=now(),
transaction_id=token,
value=post_data['PAYMENTREQUEST_0_AMT'],
status=PAYMENT_STATUS['checkout'],
content_object=self.get_content_object(),
)
transaction.save()
self.post_transaction_save(transaction, item_quantity_list)
for item, quantity, content_object in item_quantity_list:
if not quantity:
continue
purchased_item_kwargs = {
'user': self.user,
'transaction': transaction,
'quantity': quantity,
'price': item.value,
'identifier': item.identifier,
}
if content_object:
purchased_item_kwargs.update({
'object_id': content_object.pk,
'content_type': ContentType.objects.get_for_model(
content_object),
})
if item.pk:
purchased_item_kwargs.update({'item': item, })
PurchasedItem.objects.create(**purchased_item_kwargs)
if self.redirect:
return redirect(LOGIN_URL + token)
return LOGIN_URL + token
elif parsed_response.get('ACK')[0] == 'Failure':
post_data_encoded = urlencode(post_data)
self.log_error(
parsed_response, api_url=api_url,
request_data=post_data_encoded)
return redirect(self.get_error_url())
class SetExpressCheckoutItemForm(SetExpressCheckoutFormMixin):
"""
Takes the input from the ``SetExpressCheckoutView``, validates it and
takes care of the PayPal API operations.
"""
item = forms.ModelChoiceField(
queryset=Item.objects.all(),
empty_label=None,
label=_('Item'),
)
quantity = forms.IntegerField(
label=_('Quantity'),
)
def get_item(self):
"""Keeping this for backwards compatibility."""
return self.cleaned_data.get('item')
def get_quantity(self):
"""Keeping this for backwards compatibility."""
return self.cleaned_data.get('quantity')
def get_items_and_quantities(self):
"""
Returns the items and quantities.
Should return a list of tuples.
"""
return [
(self.get_item(), self.get_quantity(), None),
] | unknown | codeparrot/codeparrot-clean | ||
##
# Copyright 2009-2015 Ghent University
#
# This file is part of EasyBuild,
# originally created by the HPC team of Ghent University (http://ugent.be/hpc/en),
# with support of Ghent University (http://ugent.be/hpc),
# the Flemish Supercomputer Centre (VSC) (https://vscentrum.be/nl/en),
# the Hercules foundation (http://www.herculesstichting.be/in_English)
# and the Department of Economy, Science and Innovation (EWI) (http://www.ewi-vlaanderen.be/en).
#
# http://github.com/hpcugent/easybuild
#
# EasyBuild is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation v2.
#
# EasyBuild is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with EasyBuild. If not, see <http://www.gnu.org/licenses/>.
##
"""
EasyBuild support for SCOTCH, implemented as an easyblock
@author: Stijn De Weirdt (Ghent University)
@author: Dries Verdegem (Ghent University)
@author: Kenneth Hoste (Ghent University)
@author: Pieter De Baets (Ghent University)
@author: Jens Timmerman (Ghent University)
"""
import fileinput
import os
import re
import sys
import shutil
from distutils.version import LooseVersion
import easybuild.tools.toolchain as toolchain
from easybuild.framework.easyblock import EasyBlock
from easybuild.tools.build_log import EasyBuildError
from easybuild.tools.filetools import copytree
from easybuild.tools.run import run_cmd
class EB_SCOTCH(EasyBlock):
"""Support for building/installing SCOTCH."""
def configure_step(self):
"""Configure SCOTCH build: locate the template makefile, copy it to a general Makefile.inc and patch it."""
# pick template makefile
comp_fam = self.toolchain.comp_family()
if comp_fam == toolchain.INTELCOMP: #@UndefinedVariable
makefilename = 'Makefile.inc.x86-64_pc_linux2.icc'
elif comp_fam == toolchain.GCC: #@UndefinedVariable
makefilename = 'Makefile.inc.x86-64_pc_linux2'
else:
raise EasyBuildError("Unknown compiler family used: %s", comp_fam)
# create Makefile.inc
try:
srcdir = os.path.join(self.cfg['start_dir'], 'src')
src = os.path.join(srcdir, 'Make.inc', makefilename)
dst = os.path.join(srcdir, 'Makefile.inc')
shutil.copy2(src, dst)
self.log.debug("Successfully copied Makefile.inc to src dir.")
except OSError:
raise EasyBuildError("Copying Makefile.inc to src dir failed.")
# the default behaviour of these makefiles is still wrong
# e.g., compiler settings, and we need -lpthread
try:
for line in fileinput.input(dst, inplace=1, backup='.orig.easybuild'):
# use $CC and the likes since we're at it.
line = re.sub(r"^CCS\s*=.*$", "CCS\t= $(CC)", line)
line = re.sub(r"^CCP\s*=.*$", "CCP\t= $(MPICC)", line)
line = re.sub(r"^CCD\s*=.*$", "CCD\t= $(MPICC)", line)
# append -lpthread to LDFLAGS
line = re.sub(r"^LDFLAGS\s*=(?P<ldflags>.*$)", "LDFLAGS\t=\g<ldflags> -lpthread", line)
sys.stdout.write(line)
except IOError, err:
raise EasyBuildError("Can't modify/write Makefile in 'Makefile.inc': %s", err)
# change to src dir for building
try:
os.chdir(srcdir)
self.log.debug("Changing to src dir.")
except OSError, err:
raise EasyBuildError("Failed to change to src dir: %s", err)
def build_step(self):
"""Build by running build_step, but with some special options for SCOTCH depending on the compiler."""
ccs = os.environ['CC']
ccp = os.environ['MPICC']
ccd = os.environ['MPICC']
cflags = "-fPIC -O3 -DCOMMON_FILE_COMPRESS_GZ -DCOMMON_PTHREAD -DCOMMON_RANDOM_FIXED_SEED -DSCOTCH_RENAME"
if self.toolchain.comp_family() == toolchain.GCC: #@UndefinedVariable
cflags += " -Drestrict=__restrict"
else:
cflags += " -restrict -DIDXSIZE64"
if not self.toolchain.mpi_family() in [toolchain.INTELMPI, toolchain.QLOGICMPI]: #@UndefinedVariable
cflags += " -DSCOTCH_PTHREAD"
# actually build
apps = ['scotch', 'ptscotch']
if LooseVersion(self.version) >= LooseVersion('6.0'):
# separate target for esmumps in recent versions
apps.extend(['esmumps', 'ptesmumps'])
for app in apps:
cmd = 'make CCS="%s" CCP="%s" CCD="%s" CFLAGS="%s" %s' % (ccs, ccp, ccd, cflags, app)
run_cmd(cmd, log_all=True, simple=True)
def install_step(self):
"""Install by copying files and creating group library file."""
self.log.debug("Installing SCOTCH")
# copy files to install dir
regmetis = re.compile(r".*metis.*")
try:
for d in ["include", "lib", "bin", "man"]:
src = os.path.join(self.cfg['start_dir'], d)
dst = os.path.join(self.installdir, d)
# we don't need any metis stuff from scotch!
copytree(src, dst, ignore=lambda path, files: [x for x in files if regmetis.match(x)])
except OSError, err:
raise EasyBuildError("Copying %s to installation dir %s failed: %s", src, dst, err)
# create group library file
scotchlibdir = os.path.join(self.installdir, 'lib')
scotchgrouplib = os.path.join(scotchlibdir, 'libscotch_group.a')
try:
line = ' '.join(os.listdir(scotchlibdir))
line = "GROUP (%s)" % line
f = open(scotchgrouplib, 'w')
f.write(line)
f.close()
self.log.info("Successfully written group lib file: %s" % scotchgrouplib)
except (IOError, OSError), err:
raise EasyBuildError("Can't write to file %s: %s", scotchgrouplib, err)
def sanity_check_step(self):
"""Custom sanity check for SCOTCH."""
custom_paths = {
'files': ['bin/%s' % x for x in ["acpl", "amk_fft2", "amk_hy", "amk_p2", "dggath",
"dgord", "dgscat", "gbase", "gmap", "gmk_m2",
"gmk_msh", "gmtst", "gotst", "gpart", "gtst",
"mmk_m2", "mord", "amk_ccc", "amk_grf", "amk_m2",
"atst", "dgmap", "dgpart", "dgtst", "gcv", "gmk_hy",
"gmk_m3", "gmk_ub2", "gord", "gout", "gscat", "mcv",
"mmk_m3", "mtst"]] +
['include/%s.h' % x for x in ["esmumps","ptscotchf", "ptscotch","scotchf",
"scotch"]] +
['lib/lib%s.a' % x for x in ["esmumps","ptscotch", "ptscotcherrexit",
"scotcherr", "scotch_group", "ptesmumps",
"ptscotcherr", "scotch", "scotcherrexit"]],
'dirs':[]
}
super(EB_SCOTCH, self).sanity_check_step(custom_paths=custom_paths) | unknown | codeparrot/codeparrot-clean | ||
# Copyright 2013 Openstack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import json
from quark.drivers import unmanaged
from quark import network_strategy
from quark.tests import test_base
class TestUnmanagedDriver(test_base.TestBase):
def setUp(self):
super(TestUnmanagedDriver, self).setUp()
self.strategy = {"public_network": {"bridge": "xenbr0"}}
strategy_json = json.dumps(self.strategy)
self.driver = unmanaged.UnmanagedDriver()
unmanaged.STRATEGY = network_strategy.JSONStrategy(strategy_json)
def test_load_config(self):
self.driver.load_config()
def test_get_name(self):
self.assertEqual(self.driver.get_name(), "UNMANAGED")
def test_get_connection(self):
self.driver.get_connection()
def test_create_network(self):
self.driver.create_network(context=self.context,
network_name="testwork")
def test_delete_network(self):
self.driver.delete_network(context=self.context, network_id=1)
def test_diag_network(self):
self.assertEqual(self.driver.diag_network(context=self.context,
network_id=2), {})
def test_diag_port(self):
self.assertEqual(self.driver.diag_port(context=self.context,
network_id=2), {})
def test_create_port(self):
self.driver.create_port(context=self.context,
network_id="public_network", port_id=2)
def test_update_port(self):
self.driver.update_port(context=self.context,
network_id="public_network", port_id=2)
def test_delete_port(self):
self.driver.delete_port(context=self.context, port_id=2)
def test_create_security_group(self):
self.driver.create_security_group(context=self.context,
group_name="mygroup")
def test_delete_security_group(self):
self.driver.delete_security_group(context=self.context,
group_id=3)
def test_update_security_group(self):
self.driver.update_security_group(context=self.context,
group_id=3)
def test_create_security_group_rule(self):
rule = {'ethertype': 'IPv4', 'direction': 'ingress'}
self.driver.create_security_group_rule(context=self.context,
group_id=3,
rule=rule)
def test_delete_security_group_rule(self):
rule = {'ethertype': 'IPv4', 'direction': 'ingress'}
self.driver.delete_security_group_rule(context=self.context,
group_id=3,
rule=rule) | unknown | codeparrot/codeparrot-clean | ||
from PIL import Image, ImageColor, ImageDraw, ImageFont
from utility.tools import TEMPDIR
import utility.logger
logger = utility.logger.getLogger(__name__)
BLACK = ImageColor.getrgb("black")
WHITE = ImageColor.getrgb("white")
# def draw_rotated_text(canvas: Image, text: str, font: ImageFont, xy: tuple, fill: ImageColor=BLACK, angle: int=-90):
def draw_rotated_text(canvas, text, font, xy, fill=BLACK, angle=-90):
# type: (Image, str, ImageFont, tuple, ImageColor, int)
"""Utility function draw rotated text"""
tmp_img = Image.new("RGBA", font.getsize(text), color=(0, 0, 0, 0))
draw_text = ImageDraw.Draw(tmp_img)
draw_text.text(text=text, xy=(0, 0), font=font, fill=fill)
tmp_img2 = tmp_img.rotate(angle, expand=1)
tmp_img2.save("/{0}/{1}.png".format(TEMPDIR, text), format="png")
canvas.paste(im=tmp_img2, box=tuple([int(i) for i in xy]))
# def draw_open_polygon(canvas: Image, xy: tuple, fill: ImageColor=WHITE, outline: ImageColor=BLACK):
def draw_open_polygon(canvas, xy, fill=None, outline=BLACK, width=0):
# type: (Image, tuple, ImageColor, ImageColor)
draw_ctx = ImageDraw.Draw(canvas)
draw_ctx.polygon(xy, fill=fill)
draw_ctx.line(xy, fill=outline, width=width) | unknown | codeparrot/codeparrot-clean | ||
export default function AuthorCard({ author }) {
return (
<a>
{author.first_name} {author.last_name}
</a>
);
} | javascript | github | https://github.com/vercel/next.js | examples/cms-buttercms/components/author-card.js |
from motuus.play.base_player import BasePlayer
class Player(BasePlayer):
"""This is the main class of motuus.
Use it to process Movement objects as they come in and to bind them to multimedia events.
An instance of this class is kept alive throughout every http session between the mobile device browser and the
computer.
If you need to store variables between inputs, you'll have to initialize them appropriately in the __init__ method.
Some useful variables are already present in the BasePlayer and can be called directly.
"""
def __init__(self, ):
# Calling super class init (ignore the following line):
super(Player, self).__init__(graph3D=True)
# Initialize here variables that might be used at every new event.
def play(self, mov):
"""This method is called anytime a new Movement input comes in from the device.
Use it to process every new mov and bind it to multimedia event, etc.
PLEASE NOTE that you should avoid long processing tasks within this method. If the device transmission
frequency is set to 5Hz (5 new inputs per second) the server will only have 0.2 seconds to receive and
process every input.
Do not overload it!
"""
# Calling super class play (ignore the following line):
super(Player, self).play(mov) | unknown | codeparrot/codeparrot-clean | ||
"""The tests the for Locative device tracker platform."""
from unittest.mock import patch
import pytest
from homeassistant import data_entry_flow
from homeassistant.components import locative
from homeassistant.components.device_tracker import DOMAIN as DEVICE_TRACKER_DOMAIN
from homeassistant.components.locative import DOMAIN, TRACKER_UPDATE
from homeassistant.config import async_process_ha_core_config
from homeassistant.const import HTTP_OK, HTTP_UNPROCESSABLE_ENTITY
from homeassistant.helpers.dispatcher import DATA_DISPATCHER
from homeassistant.setup import async_setup_component
# pylint: disable=redefined-outer-name
@pytest.fixture(autouse=True)
def mock_dev_track(mock_device_tracker_conf):
"""Mock device tracker config loading."""
pass
@pytest.fixture
async def locative_client(loop, hass, hass_client):
"""Locative mock client."""
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
with patch("homeassistant.components.device_tracker.legacy.update_config"):
return await hass_client()
@pytest.fixture
async def webhook_id(hass, locative_client):
"""Initialize the Geofency component and get the webhook_id."""
await async_process_ha_core_config(
hass,
{"internal_url": "http://example.local:8123"},
)
result = await hass.config_entries.flow.async_init(
"locative", context={"source": "user"}
)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM, result
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
await hass.async_block_till_done()
return result["result"].data["webhook_id"]
async def test_missing_data(locative_client, webhook_id):
"""Test missing data."""
url = f"/api/webhook/{webhook_id}"
data = {
"latitude": 1.0,
"longitude": 1.1,
"device": "123",
"id": "Home",
"trigger": "enter",
}
# No data
req = await locative_client.post(url)
assert req.status == HTTP_UNPROCESSABLE_ENTITY
# No latitude
copy = data.copy()
del copy["latitude"]
req = await locative_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY
# No device
copy = data.copy()
del copy["device"]
req = await locative_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY
# No location
copy = data.copy()
del copy["id"]
req = await locative_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY
# No trigger
copy = data.copy()
del copy["trigger"]
req = await locative_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY
# Test message
copy = data.copy()
copy["trigger"] = "test"
req = await locative_client.post(url, data=copy)
assert req.status == HTTP_OK
# Test message, no location
copy = data.copy()
copy["trigger"] = "test"
del copy["id"]
req = await locative_client.post(url, data=copy)
assert req.status == HTTP_OK
# Unknown trigger
copy = data.copy()
copy["trigger"] = "foobar"
req = await locative_client.post(url, data=copy)
assert req.status == HTTP_UNPROCESSABLE_ENTITY
async def test_enter_and_exit(hass, locative_client, webhook_id):
"""Test when there is a known zone."""
url = f"/api/webhook/{webhook_id}"
data = {
"latitude": 40.7855,
"longitude": -111.7367,
"device": "123",
"id": "Home",
"trigger": "enter",
}
# Enter the Home
req = await locative_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])
).state
assert state_name == "home"
data["id"] = "HOME"
data["trigger"] = "exit"
# Exit Home
req = await locative_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])
).state
assert state_name == "not_home"
data["id"] = "hOmE"
data["trigger"] = "enter"
# Enter Home again
req = await locative_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])
).state
assert state_name == "home"
data["trigger"] = "exit"
# Exit Home
req = await locative_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])
).state
assert state_name == "not_home"
data["id"] = "work"
data["trigger"] = "enter"
# Enter Work
req = await locative_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state_name = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"])
).state
assert state_name == "work"
async def test_exit_after_enter(hass, locative_client, webhook_id):
"""Test when an exit message comes after an enter message."""
url = f"/api/webhook/{webhook_id}"
data = {
"latitude": 40.7855,
"longitude": -111.7367,
"device": "123",
"id": "Home",
"trigger": "enter",
}
# Enter Home
req = await locative_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]))
assert state.state == "home"
data["id"] = "Work"
# Enter Work
req = await locative_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]))
assert state.state == "work"
data["id"] = "Home"
data["trigger"] = "exit"
# Exit Home
req = await locative_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]))
assert state.state == "work"
async def test_exit_first(hass, locative_client, webhook_id):
"""Test when an exit message is sent first on a new device."""
url = f"/api/webhook/{webhook_id}"
data = {
"latitude": 40.7855,
"longitude": -111.7367,
"device": "new_device",
"id": "Home",
"trigger": "exit",
}
# Exit Home
req = await locative_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]))
assert state.state == "not_home"
async def test_two_devices(hass, locative_client, webhook_id):
"""Test updating two different devices."""
url = f"/api/webhook/{webhook_id}"
data_device_1 = {
"latitude": 40.7855,
"longitude": -111.7367,
"device": "device_1",
"id": "Home",
"trigger": "exit",
}
# Exit Home
req = await locative_client.post(url, data=data_device_1)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_1["device"])
)
assert state.state == "not_home"
# Enter Home
data_device_2 = dict(data_device_1)
data_device_2["device"] = "device_2"
data_device_2["trigger"] = "enter"
req = await locative_client.post(url, data=data_device_2)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_2["device"])
)
assert state.state == "home"
state = hass.states.get(
"{}.{}".format(DEVICE_TRACKER_DOMAIN, data_device_1["device"])
)
assert state.state == "not_home"
@pytest.mark.xfail(
reason="The device_tracker component does not support unloading yet."
)
async def test_load_unload_entry(hass, locative_client, webhook_id):
"""Test that the appropriate dispatch signals are added and removed."""
url = f"/api/webhook/{webhook_id}"
data = {
"latitude": 40.7855,
"longitude": -111.7367,
"device": "new_device",
"id": "Home",
"trigger": "exit",
}
# Exit Home
req = await locative_client.post(url, data=data)
await hass.async_block_till_done()
assert req.status == HTTP_OK
state = hass.states.get("{}.{}".format(DEVICE_TRACKER_DOMAIN, data["device"]))
assert state.state == "not_home"
assert len(hass.data[DATA_DISPATCHER][TRACKER_UPDATE]) == 1
entry = hass.config_entries.async_entries(DOMAIN)[0]
await locative.async_unload_entry(hass, entry)
await hass.async_block_till_done()
assert not hass.data[DATA_DISPATCHER][TRACKER_UPDATE] | unknown | codeparrot/codeparrot-clean | ||
"""Feed generation core"""
from urlparse import urljoin
import datetime
import os
from django.conf import settings
from django.core.urlresolvers import reverse
from gruntle.memebot.models import SerializedData, Link
from gruntle.memebot.decorators import logged, locked
from gruntle.memebot.utils import AtomicWrite, first, plural, text, rss
class LinkItem(rss.Item):
"""A single Link feed item"""
def __init__(self, link, feed):
super(LinkItem, self).__init__(link.best_url,
title=link.get_title_display(),
desc=link.render(feed.format),
author=link.user.username,
guid=link.guid,
published=link.published)
class RSSFeed(rss.RSS):
"""A feed generator for Link objects"""
def __init__(self, feed):
super(RSSFeed, self).__init__(feed.reverse('memebot-view-rss-index'),
title=feed.title,
desc=feed.description,
language=feed.language,
copyright=feed.copyright,
rss_url=feed.reverse('memebot-view-rss', feed.name),
webmaster=feed.webmaster,
ttl=feed.ttl,
image=feed.image,
stylesheets=feed.get_stylesheets(),
add_atom=True,
add_dc=True,
extra_namespaces=feed.extra_namespaces)
for link in feed.links:
self.append(LinkItem(link, feed))
class BaseFeed(object):
"""Defines the interface and defaults for a content feed"""
# you must set these on the subclass
title = None
description = None
format = None
# the rest of these attributes can be overridden, these are just defaults
base_url = settings.FEED_BASE_URL
language = settings.LANGUAGE_CODE
copyright = settings.FEED_COPYRIGHT
webmaster = settings.FEED_WEBMASTER
ttl = settings.FEED_TTL
max_links = settings.FEED_MAX_LINKS
feed_dir = settings.FEED_DIR
stylesheets = settings.FEED_STYLESHEETS
extra_namespaces = settings.FEED_EXTRA_NAMESPACES
keep_xml_backup = settings.FEED_KEEP_XML_BACKUP
image_url = settings.FEED_IMAGE_URL
image_title = settings.FEED_IMAGE_TITLE
image_link = settings.FEED_IMAGE_LINK
image_width = settings.FEED_IMAGE_WIDTH
image_height = settings.FEED_IMAGE_HEIGHT
def __init__(self, name, published_links, logger):
self.name = name
self.published_links = published_links
self.log = logger.get_named_logger(name)
self._links = None
def get_stylesheets(self):
if self.stylesheets is not None:
return [rss.StyleSheet(**kwargs) for kwargs in self.stylesheets]
@property
def xml_file(self):
"""Location of file output"""
return os.path.join(self.feed_dir, self.name + '.xml')
@property
def image(self):
"""An Image object if an image_url is defined for this feed"""
if self.image_url is not None:
return rss.Image(url=self.image_url,
title=self.image_title,
link=self.image_link,
width=self.image_width,
height=self.image_height)
@property
def links(self):
"""Links valid for this feed"""
if self._links is None:
links = self.filter(self.published_links)
if self.max_links:
links = links[:self.max_links]
self._links = links
return self._links
@property
def key(self):
"""Our key in SerializedData"""
return self.name + '_last_published'
@property
def newest_publish_id(self):
if self.links.count():
return self.links[0].publish_id
@property
def last_publish_id(self):
last = SerializedData.data[self.key]
if last is None:
last = 0
return last
@property
def has_new_links(self):
"""True if there are newly published links that have not been exported"""
return self.last_publish_id < self.newest_publish_id
def reverse(self, view, *args, **kwargs):
"""Reverse look up a URL, fully qualified by base_url"""
return urljoin(self.base_url, reverse(view, args=args, kwargs=kwargs))
def generate(self, force=False, **kwargs):
"""Generate the feed"""
link_count = self.links.count()
if link_count:
if force or self.has_new_links:
self.log.info('Rebuilding feed with %d items', link_count)
xml = RSSFeed(self).tostring(**kwargs)
with AtomicWrite(self.xml_file, backup=self.keep_xml_backup, perms=0644) as fp:
fp.write(xml)
self.log.info('Wrote %d bytes to: %s', len(xml), self.xml_file)
SerializedData.data[self.key] = self.newest_publish_id
else:
self.log.info('No new links to publish')
else:
self.log.warn('No links valid for this feed')
def filter(self, published_links):
"""Override by subclasses to control what links get exported to the feed"""
return published_links
def get_feeds():
"""Import the feed models defined in settings.FEEDS"""
return [(path.rsplit('.', 1)[1], __import__(path, globals(), locals(), ['Feed']).Feed) for path in settings.FEEDS]
def get_feed_names():
"""Get just the name of the feeds"""
return [name for name, cls in get_feeds()]
@logged('feeds', append=True)
@locked('feeds', 0)
def run(logger, force=False):
"""Rebuild all feeds"""
feeds = get_feeds()
logger.info('Rebuilding %s', plural(len(feeds), 'feed'))
published_links = Link.objects.filter(state='published').order_by('-published')
for name, cls in feeds:
feed = cls(name, published_links, logger)
feed.generate(encoding=settings.FEED_ENCODING, force=force) | unknown | codeparrot/codeparrot-clean | ||
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: | unknown | codeparrot/codeparrot-clean | ||
from __future__ import annotations
import logging
from collections import defaultdict
from typing import TYPE_CHECKING, Any
from tldextract import TLDExtract
from scrapy.exceptions import NotConfigured
from scrapy.http import Response
from scrapy.http.cookies import CookieJar
from scrapy.utils.decorators import _warn_spider_arg
from scrapy.utils.httpobj import urlparse_cached
from scrapy.utils.python import to_unicode
if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from http.cookiejar import Cookie
# typing.Self requires Python 3.11
from typing_extensions import Self
from scrapy import Request, Spider
from scrapy.crawler import Crawler
from scrapy.http.request import VerboseCookie
logger = logging.getLogger(__name__)
_split_domain = TLDExtract(include_psl_private_domains=True)
_UNSET = object()
def _is_public_domain(domain: str) -> bool:
parts = _split_domain(domain)
return not parts.domain
class CookiesMiddleware:
"""This middleware enables working with sites that need cookies"""
crawler: Crawler
def __init__(self, debug: bool = False):
self.jars: defaultdict[Any, CookieJar] = defaultdict(CookieJar)
self.debug: bool = debug
@classmethod
def from_crawler(cls, crawler: Crawler) -> Self:
if not crawler.settings.getbool("COOKIES_ENABLED"):
raise NotConfigured
o = cls(crawler.settings.getbool("COOKIES_DEBUG"))
o.crawler = crawler
return o
def _process_cookies(
self, cookies: Iterable[Cookie], *, jar: CookieJar, request: Request
) -> None:
for cookie in cookies:
cookie_domain = cookie.domain
cookie_domain = cookie_domain.removeprefix(".")
hostname = urlparse_cached(request).hostname
assert hostname is not None
request_domain = hostname.lower()
if cookie_domain and _is_public_domain(cookie_domain):
if cookie_domain != request_domain:
continue
cookie.domain = request_domain
jar.set_cookie_if_ok(cookie, request)
@_warn_spider_arg
def process_request(
self, request: Request, spider: Spider | None = None
) -> Request | Response | None:
if request.meta.get("dont_merge_cookies", False):
return None
cookiejarkey = request.meta.get("cookiejar")
jar = self.jars[cookiejarkey]
cookies = self._get_request_cookies(jar, request)
self._process_cookies(cookies, jar=jar, request=request)
# set Cookie header
request.headers.pop("Cookie", None)
jar.add_cookie_header(request)
self._debug_cookie(request)
return None
@_warn_spider_arg
def process_response(
self, request: Request, response: Response, spider: Spider | None = None
) -> Request | Response:
if request.meta.get("dont_merge_cookies", False):
return response
# extract cookies from Set-Cookie and drop invalid/expired cookies
cookiejarkey = request.meta.get("cookiejar")
jar = self.jars[cookiejarkey]
cookies = jar.make_cookies(response, request)
self._process_cookies(cookies, jar=jar, request=request)
self._debug_set_cookie(response)
return response
def _debug_cookie(self, request: Request) -> None:
if self.debug:
cl = [
to_unicode(c, errors="replace")
for c in request.headers.getlist("Cookie")
]
if cl:
cookies = "\n".join(f"Cookie: {c}\n" for c in cl)
msg = f"Sending cookies to: {request}\n{cookies}"
logger.debug(msg, extra={"spider": self.crawler.spider})
def _debug_set_cookie(self, response: Response) -> None:
if self.debug:
cl = [
to_unicode(c, errors="replace")
for c in response.headers.getlist("Set-Cookie")
]
if cl:
cookies = "\n".join(f"Set-Cookie: {c}\n" for c in cl)
msg = f"Received cookies from: {response}\n{cookies}"
logger.debug(msg, extra={"spider": self.crawler.spider})
def _format_cookie(self, cookie: VerboseCookie, request: Request) -> str | None:
"""
Given a dict consisting of cookie components, return its string representation.
Decode from bytes if necessary.
"""
decoded = {}
flags = set()
for key in ("name", "value", "path", "domain"):
value = cookie.get(key)
if value is None:
if key in ("name", "value"):
msg = f"Invalid cookie found in request {request}: {cookie} ('{key}' is missing)"
logger.warning(msg)
return None
continue
if isinstance(value, (bool, float, int, str)):
decoded[key] = str(value)
else:
assert isinstance(value, bytes)
try:
decoded[key] = value.decode("utf8")
except UnicodeDecodeError:
logger.warning(
"Non UTF-8 encoded cookie found in request %s: %s",
request,
cookie,
)
decoded[key] = value.decode("latin1", errors="replace")
for flag in ("secure",):
value = cookie.get(flag, _UNSET)
if value is _UNSET or not value:
continue
flags.add(flag)
cookie_str = f"{decoded.pop('name')}={decoded.pop('value')}"
for key, value in decoded.items(): # path, domain
cookie_str += f"; {key.capitalize()}={value}"
for flag in flags: # secure
cookie_str += f"; {flag.capitalize()}"
return cookie_str
def _get_request_cookies(
self, jar: CookieJar, request: Request
) -> Sequence[Cookie]:
"""
Extract cookies from the Request.cookies attribute
"""
if not request.cookies:
return []
cookies: Iterable[VerboseCookie]
if isinstance(request.cookies, dict):
cookies = tuple({"name": k, "value": v} for k, v in request.cookies.items())
else:
cookies = request.cookies
for cookie in cookies:
cookie.setdefault("secure", urlparse_cached(request).scheme == "https")
formatted = filter(None, (self._format_cookie(c, request) for c in cookies))
response = Response(request.url, headers={"Set-Cookie": formatted})
return jar.make_cookies(response, request) | python | github | https://github.com/scrapy/scrapy | scrapy/downloadermiddlewares/cookies.py |
"""OpenSSL/M2Crypto 3DES implementation."""
from cryptomath import *
from TripleDES import *
if m2cryptoLoaded:
def new(key, mode, IV):
return OpenSSL_TripleDES(key, mode, IV)
class OpenSSL_TripleDES(TripleDES):
def __init__(self, key, mode, IV):
TripleDES.__init__(self, key, mode, IV, "openssl")
self.key = key
self.IV = IV
def _createContext(self, encrypt):
context = m2.cipher_ctx_new()
cipherType = m2.des_ede3_cbc()
m2.cipher_init(context, cipherType, self.key, self.IV, encrypt)
return context
def encrypt(self, plaintext):
TripleDES.encrypt(self, plaintext)
context = self._createContext(1)
ciphertext = m2.cipher_update(context, plaintext)
m2.cipher_ctx_free(context)
self.IV = ciphertext[-self.block_size:]
return ciphertext
def decrypt(self, ciphertext):
TripleDES.decrypt(self, ciphertext)
context = self._createContext(0)
#I think M2Crypto has a bug - it fails to decrypt and return the last block passed in.
#To work around this, we append sixteen zeros to the string, below:
plaintext = m2.cipher_update(context, ciphertext+('\0'*16))
#If this bug is ever fixed, then plaintext will end up having a garbage
#plaintext block on the end. That's okay - the below code will ignore it.
plaintext = plaintext[:len(ciphertext)]
m2.cipher_ctx_free(context)
self.IV = ciphertext[-self.block_size:]
return plaintext | unknown | codeparrot/codeparrot-clean | ||
---
name: Bug Report
about: Create a bug report.
---
Your issue may already be reported! Please search on the [Actix Web issue tracker](https://github.com/actix/actix-web/issues) before creating one.
## Expected Behavior
<!--- If you're describing a bug, tell us what should happen -->
<!--- If you're suggesting a change/improvement, tell us how it should work -->
## Current Behavior
<!--- If describing a bug, tell us what happens instead of the expected behavior -->
<!--- If suggesting a change/improvement, explain the difference from current behavior -->
## Possible Solution
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
<!--- or ideas how to implement the addition or change -->
## Steps to Reproduce (for bugs)
<!--- Provide a link to a live example, or an unambiguous set of steps to -->
<!--- reproduce this bug. Include code to reproduce, if relevant -->
1.
2.
3.
4.
## Context
<!--- How has this issue affected you? What are you trying to accomplish? -->
<!--- Providing context helps us come up with a solution that is most useful in the real world -->
## Your Environment
<!--- Include as many relevant details about the environment you experienced the bug in -->
- Rust Version (I.e, output of `rustc -V`):
- Actix Web Version: | unknown | github | https://github.com/actix/actix-web | .github/ISSUE_TEMPLATE/bug_report.md |
from cmparser import zpool_status,zpool_list_h, zpool_autoreplace, diskmap
from notifier import mail_notification
from daemon import Daemon
import time
from config import config
import logging
class zpoold(Daemon):
def run(self):
self.setUp()
def setUp(self):
logging.basicConfig(filename='log.txt', level=logging.DEBUG)
zl = zpool_list_h()
zs = zpool_status()
dm = diskmap()
self.id_unv = ''
zname = [zname['name'] for zname in zl.get_zpool_list_h()]
logging.debug('get full list of avialable zpool names')
logging.debug(zname)
zconf = []
disk_names = []
for name in zname:
zconf.append(zs.get_zpool_status(name))
logging.debug('zpool status')
logging.debug(zs.get_zpool_status(name))
for z in zconf:
conf = z['config']
logging.debug('pool config')
logging.debug(conf)
for name in conf:
logging.debug('name')
logging.debug(name)
for n in name:
disk_names.append(n['name'])
logging.debug('disk names')
logging.debug(disk_names)
if n['state'] == 'UNAVAIL':
mail = mail_notification()
mail.sendNotification(message = str(disk_names), subj=n['state'])
oldpath = dm.findIdBySymLinks((dm.findPathByName(n['name'])))['by-path']
logging.debug('old path:')
logging.debug(oldpath)
if self.id_unv == '':
self.id_unv = dm.findIdBySymLinks((dm.findPathByName(n['name'])))['by-id']
logging.debug('id unv:')
logging.debug(self.id_unv)
elif self.id_unv != dm.findIdBySymLinks((dm.findPathByName(n['name'])))['by-id']:
logging.debug('Startinf replacing:')
zs.replaceDisk(zname, oldpath)
full_paths = []
logging.debug('get full paths of the disks')
for disk in disk_names:
full_paths.append(dm.findPathByName(disk))
logging.debug(full_paths)
ids = []
for p in [path for path in full_paths if path!='']:
ids.append(dm.findIdBySymLinks(p))
logging.debug('ids:')
logging.debug(ids)
logging.debug('disk map:')
logging.debug(dm.getdiskMap(disk_names))
if __name__ == '__main__':
import sys
z = zpoold(config['daemon']['pid_path'])
if len(sys.argv) == 2:
if 'start' == sys.argv[1]:
z.start()
elif 'stop' == sys.argv[1]:
z.stop()
elif 'restart' == sys.argv[1]:
z.restart()
else:
print "Unknown command"
sys.exit(2)
else:
print "usage: %s start|stop|restart" % sys.argv[0]
sys.exit(2) | unknown | codeparrot/codeparrot-clean | ||
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from optparse import make_option
from collections import OrderedDict
from importlib import import_module
import itertools
import traceback
from django.apps import apps
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from django.core.management.color import no_style
from django.core.management.sql import custom_sql_for_model, emit_post_migrate_signal, emit_pre_migrate_signal
from django.db import connections, router, transaction, DEFAULT_DB_ALIAS
from django.db.migrations.executor import MigrationExecutor
from django.db.migrations.loader import MigrationLoader, AmbiguityError
from django.db.migrations.state import ProjectState
from django.db.migrations.autodetector import MigrationAutodetector
from django.utils.module_loading import module_has_submodule
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--noinput', action='store_false', dest='interactive', default=True,
help='Tells Django to NOT prompt the user for input of any kind.'),
make_option('--no-initial-data', action='store_false', dest='load_initial_data', default=True,
help='Tells Django not to load any initial data after database synchronization.'),
make_option('--database', action='store', dest='database',
default=DEFAULT_DB_ALIAS, help='Nominates a database to synchronize. '
'Defaults to the "default" database.'),
make_option('--fake', action='store_true', dest='fake', default=False,
help='Mark migrations as run without actually running them'),
make_option('--list', '-l', action='store_true', dest='list', default=False,
help='Show a list of all known migrations and which are applied'),
)
help = "Updates database schema. Manages both apps with migrations and those without."
args = "[app_label] [migration_name]"
def handle(self, *args, **options):
self.verbosity = int(options.get('verbosity'))
self.interactive = options.get('interactive')
self.show_traceback = options.get('traceback')
self.load_initial_data = options.get('load_initial_data')
self.test_database = options.get('test_database', False)
# Import the 'management' module within each installed app, to register
# dispatcher events.
for app_config in apps.get_app_configs():
if module_has_submodule(app_config.module, "management"):
import_module('.management', app_config.name)
# Get the database we're operating from
db = options.get('database')
connection = connections[db]
# If they asked for a migration listing, quit main execution flow and show it
if options.get("list", False):
return self.show_migration_list(connection, args)
# Work out which apps have migrations and which do not
executor = MigrationExecutor(connection, self.migration_progress_callback)
# Before anything else, see if there's conflicting apps and drop out
# hard if there are any
conflicts = executor.loader.detect_conflicts()
if conflicts:
name_str = "; ".join(
"%s in %s" % (", ".join(names), app)
for app, names in conflicts.items()
)
raise CommandError("Conflicting migrations detected (%s).\nTo fix them run 'python manage.py makemigrations --merge'" % name_str)
# If they supplied command line arguments, work out what they mean.
run_syncdb = False
target_app_labels_only = True
if len(args) > 2:
raise CommandError("Too many command-line arguments (expecting 'app_label' or 'app_label migrationname')")
elif len(args) == 2:
app_label, migration_name = args
if app_label not in executor.loader.migrated_apps:
raise CommandError("App '%s' does not have migrations (you cannot selectively sync unmigrated apps)" % app_label)
if migration_name == "zero":
targets = [(app_label, None)]
else:
try:
migration = executor.loader.get_migration_by_prefix(app_label, migration_name)
except AmbiguityError:
raise CommandError("More than one migration matches '%s' in app '%s'. Please be more specific." % (
migration_name, app_label))
except KeyError:
raise CommandError("Cannot find a migration matching '%s' from app '%s'." % (
migration_name, app_label))
targets = [(app_label, migration.name)]
target_app_labels_only = False
elif len(args) == 1:
app_label = args[0]
if app_label not in executor.loader.migrated_apps:
raise CommandError("App '%s' does not have migrations (you cannot selectively sync unmigrated apps)" % app_label)
targets = [key for key in executor.loader.graph.leaf_nodes() if key[0] == app_label]
else:
targets = executor.loader.graph.leaf_nodes()
run_syncdb = True
plan = executor.migration_plan(targets)
# Print some useful info
if self.verbosity >= 1:
self.stdout.write(self.style.MIGRATE_HEADING("Operations to perform:"))
if run_syncdb and executor.loader.unmigrated_apps:
self.stdout.write(self.style.MIGRATE_LABEL(" Synchronize unmigrated apps: ") + (", ".join(executor.loader.unmigrated_apps)))
if target_app_labels_only:
self.stdout.write(self.style.MIGRATE_LABEL(" Apply all migrations: ") + (", ".join(set(a for a, n in targets)) or "(none)"))
else:
if targets[0][1] is None:
self.stdout.write(self.style.MIGRATE_LABEL(" Unapply all migrations: ") + "%s" % (targets[0][0], ))
else:
self.stdout.write(self.style.MIGRATE_LABEL(" Target specific migration: ") + "%s, from %s" % (targets[0][1], targets[0][0]))
# Run the syncdb phase.
# If you ever manage to get rid of this, I owe you many, many drinks.
# Note that pre_migrate is called from inside here, as it needs
# the list of models about to be installed.
if run_syncdb and executor.loader.unmigrated_apps:
if self.verbosity >= 1:
self.stdout.write(self.style.MIGRATE_HEADING("Synchronizing apps without migrations:"))
created_models = self.sync_apps(connection, executor.loader.unmigrated_apps)
else:
created_models = []
emit_pre_migrate_signal([], self.verbosity, self.interactive, connection.alias)
# The test runner requires us to flush after a syncdb but before migrations,
# so do that here.
if options.get("test_flush", False):
call_command(
'flush',
verbosity=max(self.verbosity - 1, 0),
interactive=False,
database=db,
reset_sequences=False,
inhibit_post_migrate=True,
)
# Migrate!
if self.verbosity >= 1:
self.stdout.write(self.style.MIGRATE_HEADING("Running migrations:"))
if not plan:
if self.verbosity >= 1:
self.stdout.write(" No migrations to apply.")
# If there's changes that aren't in migrations yet, tell them how to fix it.
autodetector = MigrationAutodetector(
executor.loader.project_state(),
ProjectState.from_apps(apps),
)
changes = autodetector.changes(graph=executor.loader.graph)
if changes:
self.stdout.write(self.style.NOTICE(" Your models have changes that are not yet reflected in a migration, and so won't be applied."))
self.stdout.write(self.style.NOTICE(" Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them."))
else:
executor.migrate(targets, plan, fake=options.get("fake", False))
# Send the post_migrate signal, so individual apps can do whatever they need
# to do at this point.
emit_post_migrate_signal(created_models, self.verbosity, self.interactive, connection.alias)
def migration_progress_callback(self, action, migration, fake=False):
if self.verbosity >= 1:
if action == "apply_start":
self.stdout.write(" Applying %s..." % migration, ending="")
self.stdout.flush()
elif action == "apply_success":
if fake:
self.stdout.write(self.style.MIGRATE_SUCCESS(" FAKED"))
else:
self.stdout.write(self.style.MIGRATE_SUCCESS(" OK"))
elif action == "unapply_start":
self.stdout.write(" Unapplying %s..." % migration, ending="")
self.stdout.flush()
elif action == "unapply_success":
if fake:
self.stdout.write(self.style.MIGRATE_SUCCESS(" FAKED"))
else:
self.stdout.write(self.style.MIGRATE_SUCCESS(" OK"))
def sync_apps(self, connection, app_labels):
"Runs the old syncdb-style operation on a list of app_labels."
cursor = connection.cursor()
try:
# Get a list of already installed *models* so that references work right.
tables = connection.introspection.table_names(cursor)
seen_models = connection.introspection.installed_models(tables)
created_models = set()
pending_references = {}
# Build the manifest of apps and models that are to be synchronized
all_models = [
(app_config.label,
router.get_migratable_models(app_config, connection.alias, include_auto_created=True))
for app_config in apps.get_app_configs()
if app_config.models_module is not None and app_config.label in app_labels
]
def model_installed(model):
opts = model._meta
converter = connection.introspection.table_name_converter
# Note that if a model is unmanaged we short-circuit and never try to install it
return not ((converter(opts.db_table) in tables) or
(opts.auto_created and converter(opts.auto_created._meta.db_table) in tables))
manifest = OrderedDict(
(app_name, list(filter(model_installed, model_list)))
for app_name, model_list in all_models
)
create_models = set(itertools.chain(*manifest.values()))
emit_pre_migrate_signal(create_models, self.verbosity, self.interactive, connection.alias)
# Create the tables for each model
if self.verbosity >= 1:
self.stdout.write(" Creating tables...\n")
with transaction.atomic(using=connection.alias, savepoint=False):
for app_name, model_list in manifest.items():
for model in model_list:
# Create the model's database table, if it doesn't already exist.
if self.verbosity >= 3:
self.stdout.write(" Processing %s.%s model\n" % (app_name, model._meta.object_name))
sql, references = connection.creation.sql_create_model(model, no_style(), seen_models)
seen_models.add(model)
created_models.add(model)
for refto, refs in references.items():
pending_references.setdefault(refto, []).extend(refs)
if refto in seen_models:
sql.extend(connection.creation.sql_for_pending_references(refto, no_style(), pending_references))
sql.extend(connection.creation.sql_for_pending_references(model, no_style(), pending_references))
if self.verbosity >= 1 and sql:
self.stdout.write(" Creating table %s\n" % model._meta.db_table)
for statement in sql:
cursor.execute(statement)
tables.append(connection.introspection.table_name_converter(model._meta.db_table))
# We force a commit here, as that was the previous behavior.
# If you can prove we don't need this, remove it.
transaction.set_dirty(using=connection.alias)
finally:
cursor.close()
# The connection may have been closed by a syncdb handler.
cursor = connection.cursor()
try:
# Install custom SQL for the app (but only if this
# is a model we've just created)
if self.verbosity >= 1:
self.stdout.write(" Installing custom SQL...\n")
for app_name, model_list in manifest.items():
for model in model_list:
if model in created_models:
custom_sql = custom_sql_for_model(model, no_style(), connection)
if custom_sql:
if self.verbosity >= 2:
self.stdout.write(" Installing custom SQL for %s.%s model\n" % (app_name, model._meta.object_name))
try:
with transaction.commit_on_success_unless_managed(using=connection.alias):
for sql in custom_sql:
cursor.execute(sql)
except Exception as e:
self.stderr.write(" Failed to install custom SQL for %s.%s model: %s\n" % (app_name, model._meta.object_name, e))
if self.show_traceback:
traceback.print_exc()
else:
if self.verbosity >= 3:
self.stdout.write(" No custom SQL for %s.%s model\n" % (app_name, model._meta.object_name))
if self.verbosity >= 1:
self.stdout.write(" Installing indexes...\n")
# Install SQL indices for all newly created models
for app_name, model_list in manifest.items():
for model in model_list:
if model in created_models:
index_sql = connection.creation.sql_indexes_for_model(model, no_style())
if index_sql:
if self.verbosity >= 2:
self.stdout.write(" Installing index for %s.%s model\n" % (app_name, model._meta.object_name))
try:
with transaction.commit_on_success_unless_managed(using=connection.alias):
for sql in index_sql:
cursor.execute(sql)
except Exception as e:
self.stderr.write(" Failed to install index for %s.%s model: %s\n" % (app_name, model._meta.object_name, e))
finally:
cursor.close()
# Load initial_data fixtures (unless that has been disabled)
if self.load_initial_data:
for app_label in app_labels:
call_command('loaddata', 'initial_data', verbosity=self.verbosity, database=connection.alias, skip_validation=True, app_label=app_label, hide_empty=True)
return created_models
def show_migration_list(self, connection, app_names=None):
"""
Shows a list of all migrations on the system, or only those of
some named apps.
"""
# Load migrations from disk/DB
loader = MigrationLoader(connection, ignore_no_migrations=True)
graph = loader.graph
# If we were passed a list of apps, validate it
if app_names:
invalid_apps = []
for app_name in app_names:
if app_name not in loader.migrated_apps:
invalid_apps.append(app_name)
if invalid_apps:
raise CommandError("No migrations present for: %s" % (", ".join(invalid_apps)))
# Otherwise, show all apps in alphabetic order
else:
app_names = sorted(loader.migrated_apps)
# For each app, print its migrations in order from oldest (roots) to
# newest (leaves).
for app_name in app_names:
self.stdout.write(app_name, self.style.MIGRATE_LABEL)
shown = set()
for node in graph.leaf_nodes(app_name):
for plan_node in graph.forwards_plan(node):
if plan_node not in shown and plan_node[0] == app_name:
# Give it a nice title if it's a squashed one
title = plan_node[1]
if graph.nodes[plan_node].replaces:
title += " (%s squashed migrations)" % len(graph.nodes[plan_node].replaces)
# Mark it as applied/unapplied
if plan_node in loader.applied_migrations:
self.stdout.write(" [X] %s" % title)
else:
self.stdout.write(" [ ] %s" % title)
shown.add(plan_node)
# If we didn't print anything, then a small message
if not shown:
self.stdout.write(" (no migrations)", self.style.MIGRATE_FAILURE) | unknown | codeparrot/codeparrot-clean | ||
"""
Unit tests for calc.py
"""
import unittest
import numpy
import calc
from pyparsing import ParseException
# numpy's default behavior when it evaluates a function outside its domain
# is to raise a warning (not an exception) which is then printed to STDOUT.
# To prevent this from polluting the output of the tests, configure numpy to
# ignore it instead.
# See http://docs.scipy.org/doc/numpy/reference/generated/numpy.seterr.html
numpy.seterr(all='ignore') # Also: 'ignore', 'warn' (default), 'raise'
class EvaluatorTest(unittest.TestCase):
"""
Run tests for calc.evaluator
Go through all functionalities as specifically as possible--
work from number input to functions and complex expressions
Also test custom variable substitutions (i.e.
`evaluator({'x':3.0}, {}, '3*x')`
gives 9.0) and more.
"""
def test_number_input(self):
"""
Test different kinds of float inputs
See also
test_trailing_period (slightly different)
test_exponential_answer
test_si_suffix
"""
easy_eval = lambda x: calc.evaluator({}, {}, x)
self.assertEqual(easy_eval("13"), 13)
self.assertEqual(easy_eval("3.14"), 3.14)
self.assertEqual(easy_eval(".618033989"), 0.618033989)
self.assertEqual(easy_eval("-13"), -13)
self.assertEqual(easy_eval("-3.14"), -3.14)
self.assertEqual(easy_eval("-.618033989"), -0.618033989)
def test_period(self):
"""
The string '.' should not evaluate to anything.
"""
with self.assertRaises(ParseException):
calc.evaluator({}, {}, '.')
with self.assertRaises(ParseException):
calc.evaluator({}, {}, '1+.')
def test_trailing_period(self):
"""
Test that things like '4.' will be 4 and not throw an error
"""
self.assertEqual(4.0, calc.evaluator({}, {}, '4.'))
def test_exponential_answer(self):
"""
Test for correct interpretation of scientific notation
"""
answer = 50
correct_responses = [
"50", "50.0", "5e1", "5e+1",
"50e0", "50.0e0", "500e-1"
]
incorrect_responses = ["", "3.9", "4.1", "0", "5.01e1"]
for input_str in correct_responses:
result = calc.evaluator({}, {}, input_str)
fail_msg = "Expected '{0}' to equal {1}".format(
input_str, answer
)
self.assertEqual(answer, result, msg=fail_msg)
for input_str in incorrect_responses:
result = calc.evaluator({}, {}, input_str)
fail_msg = "Expected '{0}' to not equal {1}".format(
input_str, answer
)
self.assertNotEqual(answer, result, msg=fail_msg)
def test_si_suffix(self):
"""
Test calc.py's unique functionality of interpreting si 'suffixes'.
For instance 'k' stand for 'kilo-' so '1k' should be 1,000
"""
test_mapping = [
('4.2%', 0.042), ('2.25k', 2250), ('8.3M', 8300000),
('9.9G', 9.9e9), ('1.2T', 1.2e12), ('7.4c', 0.074),
('5.4m', 0.0054), ('8.7u', 0.0000087),
('5.6n', 5.6e-9), ('4.2p', 4.2e-12)
]
for (expr, answer) in test_mapping:
tolerance = answer * 1e-6 # Make rel. tolerance, because of floats
fail_msg = "Failure in testing suffix '{0}': '{1}' was not {2}"
fail_msg = fail_msg.format(expr[-1], expr, answer)
self.assertAlmostEqual(
calc.evaluator({}, {}, expr), answer,
delta=tolerance, msg=fail_msg
)
def test_operator_sanity(self):
"""
Test for simple things like '5+2' and '5/2'
"""
var1 = 5.0
var2 = 2.0
operators = [('+', 7), ('-', 3), ('*', 10), ('/', 2.5), ('^', 25)]
for (operator, answer) in operators:
input_str = "{0} {1} {2}".format(var1, operator, var2)
result = calc.evaluator({}, {}, input_str)
fail_msg = "Failed on operator '{0}': '{1}' was not {2}".format(
operator, input_str, answer
)
self.assertEqual(answer, result, msg=fail_msg)
def test_raises_zero_division_err(self):
"""
Ensure division by zero gives an error
"""
with self.assertRaises(ZeroDivisionError):
calc.evaluator({}, {}, '1/0')
with self.assertRaises(ZeroDivisionError):
calc.evaluator({}, {}, '1/0.0')
with self.assertRaises(ZeroDivisionError):
calc.evaluator({'x': 0.0}, {}, '1/x')
def test_parallel_resistors(self):
"""
Test the parallel resistor operator ||
The formula is given by
a || b || c ...
= 1 / (1/a + 1/b + 1/c + ...)
It is the resistance of a parallel circuit of resistors with resistance
a, b, c, etc&. See if this evaulates correctly.
"""
self.assertEqual(calc.evaluator({}, {}, '1||1'), 0.5)
self.assertEqual(calc.evaluator({}, {}, '1||1||2'), 0.4)
self.assertEqual(calc.evaluator({}, {}, "j||1"), 0.5 + 0.5j)
def test_parallel_resistors_with_zero(self):
"""
Check the behavior of the || operator with 0
"""
self.assertTrue(numpy.isnan(calc.evaluator({}, {}, '0||1')))
self.assertTrue(numpy.isnan(calc.evaluator({}, {}, '0.0||1')))
self.assertTrue(numpy.isnan(calc.evaluator({'x': 0.0}, {}, 'x||1')))
def assert_function_values(self, fname, ins, outs, tolerance=1e-3):
"""
Helper function to test many values at once
Test the accuracy of evaluator's use of the function given by fname
Specifically, the equality of `fname(ins[i])` against outs[i].
This is used later to test a whole bunch of f(x) = y at a time
"""
for (arg, val) in zip(ins, outs):
input_str = "{0}({1})".format(fname, arg)
result = calc.evaluator({}, {}, input_str)
fail_msg = "Failed on function {0}: '{1}' was not {2}".format(
fname, input_str, val
)
self.assertAlmostEqual(val, result, delta=tolerance, msg=fail_msg)
def test_trig_functions(self):
"""
Test the trig functions provided in calc.py
which are: sin, cos, tan, arccos, arcsin, arctan
"""
angles = ['-pi/4', '0', 'pi/6', 'pi/5', '5*pi/4', '9*pi/4', '1 + j']
sin_values = [-0.707, 0, 0.5, 0.588, -0.707, 0.707, 1.298 + 0.635j]
cos_values = [0.707, 1, 0.866, 0.809, -0.707, 0.707, 0.834 - 0.989j]
tan_values = [-1, 0, 0.577, 0.727, 1, 1, 0.272 + 1.084j]
# Cannot test tan(pi/2) b/c pi/2 is a float and not precise...
self.assert_function_values('sin', angles, sin_values)
self.assert_function_values('cos', angles, cos_values)
self.assert_function_values('tan', angles, tan_values)
# Include those where the real part is between -pi/2 and pi/2
arcsin_inputs = ['-0.707', '0', '0.5', '0.588', '1.298 + 0.635*j']
arcsin_angles = [-0.785, 0, 0.524, 0.629, 1 + 1j]
self.assert_function_values('arcsin', arcsin_inputs, arcsin_angles)
# Rather than a complex number, numpy.arcsin gives nan
self.assertTrue(numpy.isnan(calc.evaluator({}, {}, 'arcsin(-1.1)')))
self.assertTrue(numpy.isnan(calc.evaluator({}, {}, 'arcsin(1.1)')))
# Include those where the real part is between 0 and pi
arccos_inputs = ['1', '0.866', '0.809', '0.834-0.989*j']
arccos_angles = [0, 0.524, 0.628, 1 + 1j]
self.assert_function_values('arccos', arccos_inputs, arccos_angles)
self.assertTrue(numpy.isnan(calc.evaluator({}, {}, 'arccos(-1.1)')))
self.assertTrue(numpy.isnan(calc.evaluator({}, {}, 'arccos(1.1)')))
# Has the same range as arcsin
arctan_inputs = ['-1', '0', '0.577', '0.727', '0.272 + 1.084*j']
arctan_angles = arcsin_angles
self.assert_function_values('arctan', arctan_inputs, arctan_angles)
def test_reciprocal_trig_functions(self):
"""
Test the reciprocal trig functions provided in calc.py
which are: sec, csc, cot, arcsec, arccsc, arccot
"""
angles = ['-pi/4', 'pi/6', 'pi/5', '5*pi/4', '9*pi/4', '1 + j']
sec_values = [1.414, 1.155, 1.236, -1.414, 1.414, 0.498 + 0.591j]
csc_values = [-1.414, 2, 1.701, -1.414, 1.414, 0.622 - 0.304j]
cot_values = [-1, 1.732, 1.376, 1, 1, 0.218 - 0.868j]
self.assert_function_values('sec', angles, sec_values)
self.assert_function_values('csc', angles, csc_values)
self.assert_function_values('cot', angles, cot_values)
arcsec_inputs = ['1.1547', '1.2361', '2', '-2', '-1.4142', '0.4983+0.5911*j']
arcsec_angles = [0.524, 0.628, 1.047, 2.094, 2.356, 1 + 1j]
self.assert_function_values('arcsec', arcsec_inputs, arcsec_angles)
arccsc_inputs = ['-1.1547', '-1.4142', '2', '1.7013', '1.1547', '0.6215-0.3039*j']
arccsc_angles = [-1.047, -0.785, 0.524, 0.628, 1.047, 1 + 1j]
self.assert_function_values('arccsc', arccsc_inputs, arccsc_angles)
# Has the same range as arccsc
arccot_inputs = ['-0.5774', '-1', '1.7321', '1.3764', '0.5774', '(0.2176-0.868*j)']
arccot_angles = arccsc_angles
self.assert_function_values('arccot', arccot_inputs, arccot_angles)
def test_hyperbolic_functions(self):
"""
Test the hyperbolic functions
which are: sinh, cosh, tanh, sech, csch, coth
"""
inputs = ['0', '0.5', '1', '2', '1+j']
neg_inputs = ['0', '-0.5', '-1', '-2', '-1-j']
negate = lambda x: [-k for k in x]
# sinh is odd
sinh_vals = [0, 0.521, 1.175, 3.627, 0.635 + 1.298j]
self.assert_function_values('sinh', inputs, sinh_vals)
self.assert_function_values('sinh', neg_inputs, negate(sinh_vals))
# cosh is even - do not negate
cosh_vals = [1, 1.128, 1.543, 3.762, 0.834 + 0.989j]
self.assert_function_values('cosh', inputs, cosh_vals)
self.assert_function_values('cosh', neg_inputs, cosh_vals)
# tanh is odd
tanh_vals = [0, 0.462, 0.762, 0.964, 1.084 + 0.272j]
self.assert_function_values('tanh', inputs, tanh_vals)
self.assert_function_values('tanh', neg_inputs, negate(tanh_vals))
# sech is even - do not negate
sech_vals = [1, 0.887, 0.648, 0.266, 0.498 - 0.591j]
self.assert_function_values('sech', inputs, sech_vals)
self.assert_function_values('sech', neg_inputs, sech_vals)
# the following functions do not have 0 in their domain
inputs = inputs[1:]
neg_inputs = neg_inputs[1:]
# csch is odd
csch_vals = [1.919, 0.851, 0.276, 0.304 - 0.622j]
self.assert_function_values('csch', inputs, csch_vals)
self.assert_function_values('csch', neg_inputs, negate(csch_vals))
# coth is odd
coth_vals = [2.164, 1.313, 1.037, 0.868 - 0.218j]
self.assert_function_values('coth', inputs, coth_vals)
self.assert_function_values('coth', neg_inputs, negate(coth_vals))
def test_hyperbolic_inverses(self):
"""
Test the inverse hyperbolic functions
which are of the form arc[X]h
"""
results = [0, 0.5, 1, 2, 1 + 1j]
sinh_vals = ['0', '0.5211', '1.1752', '3.6269', '0.635+1.2985*j']
self.assert_function_values('arcsinh', sinh_vals, results)
cosh_vals = ['1', '1.1276', '1.5431', '3.7622', '0.8337+0.9889*j']
self.assert_function_values('arccosh', cosh_vals, results)
tanh_vals = ['0', '0.4621', '0.7616', '0.964', '1.0839+0.2718*j']
self.assert_function_values('arctanh', tanh_vals, results)
sech_vals = ['1.0', '0.8868', '0.6481', '0.2658', '0.4983-0.5911*j']
self.assert_function_values('arcsech', sech_vals, results)
results = results[1:]
csch_vals = ['1.919', '0.8509', '0.2757', '0.3039-0.6215*j']
self.assert_function_values('arccsch', csch_vals, results)
coth_vals = ['2.164', '1.313', '1.0373', '0.868-0.2176*j']
self.assert_function_values('arccoth', coth_vals, results)
def test_other_functions(self):
"""
Test the non-trig functions provided in calc.py
Specifically:
sqrt, log10, log2, ln, abs,
fact, factorial
"""
# Test sqrt
self.assert_function_values(
'sqrt',
[0, 1, 2, 1024], # -1
[0, 1, 1.414, 32] # 1j
)
# sqrt(-1) is NAN not j (!!).
# Test logs
self.assert_function_values(
'log10',
[0.1, 1, 3.162, 1000000, '1+j'],
[-1, 0, 0.5, 6, 0.151 + 0.341j]
)
self.assert_function_values(
'log2',
[0.5, 1, 1.414, 1024, '1+j'],
[-1, 0, 0.5, 10, 0.5 + 1.133j]
)
self.assert_function_values(
'ln',
[0.368, 1, 1.649, 2.718, 42, '1+j'],
[-1, 0, 0.5, 1, 3.738, 0.347 + 0.785j]
)
# Test abs
self.assert_function_values('abs', [-1, 0, 1, 'j'], [1, 0, 1, 1])
# Test factorial
fact_inputs = [0, 1, 3, 7]
fact_values = [1, 1, 6, 5040]
self.assert_function_values('fact', fact_inputs, fact_values)
self.assert_function_values('factorial', fact_inputs, fact_values)
self.assertRaises(ValueError, calc.evaluator, {}, {}, "fact(-1)")
self.assertRaises(ValueError, calc.evaluator, {}, {}, "fact(0.5)")
self.assertRaises(ValueError, calc.evaluator, {}, {}, "factorial(-1)")
self.assertRaises(ValueError, calc.evaluator, {}, {}, "factorial(0.5)")
def test_constants(self):
"""
Test the default constants provided in calc.py
which are: j (complex number), e, pi, k, c, T, q
"""
# Of the form ('expr', python value, tolerance (or None for exact))
default_variables = [
('i', 1j, None),
('j', 1j, None),
('e', 2.7183, 1e-4),
('pi', 3.1416, 1e-4),
('k', 1.3806488e-23, 1e-26), # Boltzmann constant (Joules/Kelvin)
('c', 2.998e8, 1e5), # Light Speed in (m/s)
('T', 298.15, 0.01), # Typical room temperature (Kelvin)
('q', 1.602176565e-19, 1e-22) # Fund. Charge (Coulombs)
]
for (variable, value, tolerance) in default_variables:
fail_msg = "Failed on constant '{0}', not within bounds".format(
variable
)
result = calc.evaluator({}, {}, variable)
if tolerance is None:
self.assertEqual(value, result, msg=fail_msg)
else:
self.assertAlmostEqual(
value, result,
delta=tolerance, msg=fail_msg
)
def test_complex_expression(self):
"""
Calculate combinations of operators and default functions
"""
self.assertAlmostEqual(
calc.evaluator({}, {}, "(2^2+1.0)/sqrt(5e0)*5-1"),
10.180,
delta=1e-3
)
self.assertAlmostEqual(
calc.evaluator({}, {}, "1+1/(1+1/(1+1/(1+1)))"),
1.6,
delta=1e-3
)
self.assertAlmostEqual(
calc.evaluator({}, {}, "10||sin(7+5)"),
-0.567, delta=0.01
)
self.assertAlmostEqual(
calc.evaluator({}, {}, "sin(e)"),
0.41, delta=0.01
)
self.assertAlmostEqual(
calc.evaluator({}, {}, "k*T/q"),
0.025, delta=1e-3
)
self.assertAlmostEqual(
calc.evaluator({}, {}, "e^(j*pi)"),
-1, delta=1e-5
)
def test_explicit_sci_notation(self):
"""
Expressions like 1.6*10^-3 (not 1.6e-3) it should evaluate.
"""
self.assertEqual(
calc.evaluator({}, {}, "-1.6*10^-3"),
-0.0016
)
self.assertEqual(
calc.evaluator({}, {}, "-1.6*10^(-3)"),
-0.0016
)
self.assertEqual(
calc.evaluator({}, {}, "-1.6*10^3"),
-1600
)
self.assertEqual(
calc.evaluator({}, {}, "-1.6*10^(3)"),
-1600
)
def test_simple_vars(self):
"""
Substitution of variables into simple equations
"""
variables = {'x': 9.72, 'y': 7.91, 'loooooong': 6.4}
# Should not change value of constant
# even with different numbers of variables...
self.assertEqual(calc.evaluator({'x': 9.72}, {}, '13'), 13)
self.assertEqual(calc.evaluator({'x': 9.72, 'y': 7.91}, {}, '13'), 13)
self.assertEqual(calc.evaluator(variables, {}, '13'), 13)
# Easy evaluation
self.assertEqual(calc.evaluator(variables, {}, 'x'), 9.72)
self.assertEqual(calc.evaluator(variables, {}, 'y'), 7.91)
self.assertEqual(calc.evaluator(variables, {}, 'loooooong'), 6.4)
# Test a simple equation
self.assertAlmostEqual(
calc.evaluator(variables, {}, '3*x-y'),
21.25, delta=0.01 # = 3 * 9.72 - 7.91
)
self.assertAlmostEqual(
calc.evaluator(variables, {}, 'x*y'),
76.89, delta=0.01
)
self.assertEqual(calc.evaluator({'x': 9.72, 'y': 7.91}, {}, "13"), 13)
self.assertEqual(calc.evaluator(variables, {}, "13"), 13)
self.assertEqual(
calc.evaluator(
{'a': 2.2997471478310274, 'k': 9, 'm': 8, 'x': 0.6600949841121},
{}, "5"
),
5
)
def test_variable_case_sensitivity(self):
"""
Test the case sensitivity flag and corresponding behavior
"""
self.assertEqual(
calc.evaluator({'R1': 2.0, 'R3': 4.0}, {}, "r1*r3"),
8.0
)
variables = {'t': 1.0}
self.assertEqual(calc.evaluator(variables, {}, "t"), 1.0)
self.assertEqual(calc.evaluator(variables, {}, "T"), 1.0)
self.assertEqual(
calc.evaluator(variables, {}, "t", case_sensitive=True),
1.0
)
# Recall 'T' is a default constant, with value 298.15
self.assertAlmostEqual(
calc.evaluator(variables, {}, "T", case_sensitive=True),
298, delta=0.2
)
def test_simple_funcs(self):
"""
Subsitution of custom functions
"""
variables = {'x': 4.712}
functions = {'id': lambda x: x}
self.assertEqual(calc.evaluator({}, functions, 'id(2.81)'), 2.81)
self.assertEqual(calc.evaluator({}, functions, 'id(2.81)'), 2.81)
self.assertEqual(calc.evaluator(variables, functions, 'id(x)'), 4.712)
functions.update({'f': numpy.sin})
self.assertAlmostEqual(
calc.evaluator(variables, functions, 'f(x)'),
-1, delta=1e-3
)
def test_function_case_insensitive(self):
"""
Test case insensitive evaluation
Normal functions with some capitals should be fine
"""
self.assertAlmostEqual(
-0.28,
calc.evaluator({}, {}, 'SiN(6)', case_sensitive=False),
delta=1e-3
)
def test_function_case_sensitive(self):
"""
Test case sensitive evaluation
Incorrectly capitilized should fail
Also, it should pick the correct version of a function.
"""
with self.assertRaisesRegexp(calc.UndefinedVariable, 'SiN'):
calc.evaluator({}, {}, 'SiN(6)', case_sensitive=True)
# With case sensitive turned on, it should pick the right function
functions = {'f': lambda x: x, 'F': lambda x: x + 1}
self.assertEqual(
6, calc.evaluator({}, functions, 'f(6)', case_sensitive=True)
)
self.assertEqual(
7, calc.evaluator({}, functions, 'F(6)', case_sensitive=True)
)
def test_undefined_vars(self):
"""
Check to see if the evaluator catches undefined variables
"""
variables = {'R1': 2.0, 'R3': 4.0}
with self.assertRaisesRegexp(calc.UndefinedVariable, 'QWSEKO'):
calc.evaluator({}, {}, "5+7*QWSEKO")
with self.assertRaisesRegexp(calc.UndefinedVariable, 'r2'):
calc.evaluator({'r1': 5}, {}, "r1+r2")
with self.assertRaisesRegexp(calc.UndefinedVariable, 'r1 r3'):
calc.evaluator(variables, {}, "r1*r3", case_sensitive=True) | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python
# vim:fileencoding=UTF-8:ts=4:sw=4:sta:et:sts=4:ai
from __future__ import (unicode_literals, division, absolute_import,
print_function)
__license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
from datetime import datetime, timedelta
from collections import defaultdict
from calibre.constants import plugins
from calibre.utils.date import parse_date, UNDEFINED_DATE, utc_tz
from calibre.ebooks.metadata import author_to_author_sort
_c_speedup = plugins['speedup'][0].parse_date
def c_parse(val):
try:
year, month, day, hour, minutes, seconds, tzsecs = _c_speedup(val)
except (AttributeError, TypeError):
# If a value like 2001 is stored in the column, apsw will return it as
# an int
if isinstance(val, (int, float)):
return datetime(int(val), 1, 3, tzinfo=utc_tz)
if val is None:
return UNDEFINED_DATE
except:
pass
else:
try:
ans = datetime(year, month, day, hour, minutes, seconds, tzinfo=utc_tz)
if tzsecs is not 0:
ans -= timedelta(seconds=tzsecs)
except OverflowError:
ans = UNDEFINED_DATE
return ans
try:
return parse_date(val, as_utc=True, assume_utc=True)
except (ValueError, TypeError):
return UNDEFINED_DATE
ONE_ONE, MANY_ONE, MANY_MANY = xrange(3)
null = object()
class Table(object):
def __init__(self, name, metadata, link_table=None):
self.name, self.metadata = name, metadata
self.sort_alpha = metadata.get('is_multiple', False) and metadata.get('display', {}).get('sort_alpha', False)
# self.unserialize() maps values from the db to python objects
self.unserialize = {
'datetime': c_parse,
'bool': bool
}.get(metadata['datatype'], None)
if name == 'authors':
# Legacy
self.unserialize = lambda x: x.replace('|', ',') if x else ''
self.link_table = (link_table if link_table else
'books_%s_link'%self.metadata['table'])
def remove_books(self, book_ids, db):
return set()
def fix_link_table(self, db):
pass
def fix_case_duplicates(self, db):
''' If this table contains entries that differ only by case, then merge
those entries. This can happen in databases created with old versions
of calibre and non-ascii values, since sqlite's NOCASE only works with
ascii text. '''
pass
class VirtualTable(Table):
'''
A dummy table used for fields that only exist in memory like ondevice
'''
def __init__(self, name, table_type=ONE_ONE, datatype='text'):
metadata = {'datatype':datatype, 'table':name}
self.table_type = table_type
Table.__init__(self, name, metadata)
class OneToOneTable(Table):
'''
Represents data that is unique per book (it may not actually be unique) but
each item is assigned to a book in a one-to-one mapping. For example: uuid,
timestamp, size, etc.
'''
table_type = ONE_ONE
def read(self, db):
idcol = 'id' if self.metadata['table'] == 'books' else 'book'
query = db.execute('SELECT {0}, {1} FROM {2}'.format(idcol,
self.metadata['column'], self.metadata['table']))
if self.unserialize is None:
try:
self.book_col_map = dict(query)
except UnicodeDecodeError:
# The db is damaged, try to work around it by ignoring
# failures to decode utf-8
query = db.execute('SELECT {0}, cast({1} as blob) FROM {2}'.format(idcol,
self.metadata['column'], self.metadata['table']))
self.book_col_map = {k:bytes(val).decode('utf-8', 'replace') for k, val in query}
else:
us = self.unserialize
self.book_col_map = {book_id:us(val) for book_id, val in query}
def remove_books(self, book_ids, db):
clean = set()
for book_id in book_ids:
val = self.book_col_map.pop(book_id, null)
if val is not null:
clean.add(val)
return clean
class PathTable(OneToOneTable):
def set_path(self, book_id, path, db):
self.book_col_map[book_id] = path
db.execute('UPDATE books SET path=? WHERE id=?',
(path, book_id))
class SizeTable(OneToOneTable):
def read(self, db):
query = db.execute(
'SELECT books.id, (SELECT MAX(uncompressed_size) FROM data '
'WHERE data.book=books.id) FROM books')
self.book_col_map = dict(query)
def update_sizes(self, size_map):
self.book_col_map.update(size_map)
class UUIDTable(OneToOneTable):
def read(self, db):
OneToOneTable.read(self, db)
self.uuid_to_id_map = {v:k for k, v in self.book_col_map.iteritems()}
def update_uuid_cache(self, book_id_val_map):
for book_id, uuid in book_id_val_map.iteritems():
self.uuid_to_id_map.pop(self.book_col_map.get(book_id, None), None) # discard old uuid
self.uuid_to_id_map[uuid] = book_id
def remove_books(self, book_ids, db):
clean = set()
for book_id in book_ids:
val = self.book_col_map.pop(book_id, null)
if val is not null:
self.uuid_to_id_map.pop(val, None)
clean.add(val)
return clean
def lookup_by_uuid(self, uuid):
return self.uuid_to_id_map.get(uuid, None)
class CompositeTable(OneToOneTable):
def read(self, db):
self.book_col_map = {}
d = self.metadata['display']
self.composite_template = ['composite_template']
self.contains_html = d.get('contains_html', False)
self.make_category = d.get('make_category', False)
self.composite_sort = d.get('composite_sort', False)
self.use_decorations = d.get('use_decorations', False)
def remove_books(self, book_ids, db):
return set()
class ManyToOneTable(Table):
'''
Represents data where one data item can map to many books, for example:
series or publisher.
Each book however has only one value for data of this type.
'''
table_type = MANY_ONE
def read(self, db):
self.id_map = {}
self.col_book_map = defaultdict(set)
self.book_col_map = {}
self.read_id_maps(db)
self.read_maps(db)
def read_id_maps(self, db):
query = db.execute('SELECT id, {0} FROM {1}'.format(
self.metadata['column'], self.metadata['table']))
if self.unserialize is None:
self.id_map = dict(query)
else:
us = self.unserialize
self.id_map = {book_id:us(val) for book_id, val in query}
def read_maps(self, db):
cbm = self.col_book_map
bcm = self.book_col_map
for book, item_id in db.execute(
'SELECT book, {0} FROM {1}'.format(
self.metadata['link_column'], self.link_table)):
cbm[item_id].add(book)
bcm[book] = item_id
def fix_link_table(self, db):
linked_item_ids = {item_id for item_id in self.book_col_map.itervalues()}
extra_item_ids = linked_item_ids - set(self.id_map)
if extra_item_ids:
for item_id in extra_item_ids:
book_ids = self.col_book_map.pop(item_id, ())
for book_id in book_ids:
self.book_col_map.pop(book_id, None)
db.executemany('DELETE FROM {0} WHERE {1}=?'.format(
self.link_table, self.metadata['link_column']), tuple((x,) for x in extra_item_ids))
def fix_case_duplicates(self, db):
case_map = defaultdict(set)
for item_id, val in self.id_map.iteritems():
case_map[icu_lower(val)].add(item_id)
for v in case_map.itervalues():
if len(v) > 1:
main_id = min(v)
v.discard(main_id)
for item_id in v:
self.id_map.pop(item_id, None)
books = self.col_book_map.pop(item_id, set())
for book_id in books:
self.book_col_map[book_id] = main_id
db.executemany('UPDATE {0} SET {1}=? WHERE {1}=?'.format(
self.link_table, self.metadata['link_column']),
tuple((main_id, x) for x in v))
db.executemany('DELETE FROM {0} WHERE id=?'.format(self.metadata['table']),
tuple((x,) for x in v))
def remove_books(self, book_ids, db):
clean = set()
for book_id in book_ids:
item_id = self.book_col_map.pop(book_id, None)
if item_id is not None:
try:
self.col_book_map[item_id].discard(book_id)
except KeyError:
if self.id_map.pop(item_id, null) is not null:
clean.add(item_id)
else:
if not self.col_book_map[item_id]:
del self.col_book_map[item_id]
if self.id_map.pop(item_id, null) is not null:
clean.add(item_id)
if clean:
db.executemany(
'DELETE FROM {0} WHERE id=?'.format(self.metadata['table']),
[(x,) for x in clean])
return clean
def remove_items(self, item_ids, db):
affected_books = set()
for item_id in item_ids:
val = self.id_map.pop(item_id, null)
if val is null:
continue
book_ids = self.col_book_map.pop(item_id, set())
for book_id in book_ids:
self.book_col_map.pop(book_id, None)
affected_books.update(book_ids)
item_ids = tuple((x,) for x in item_ids)
db.executemany('DELETE FROM {0} WHERE {1}=?'.format(self.link_table, self.metadata['link_column']), item_ids)
db.executemany('DELETE FROM {0} WHERE id=?'.format(self.metadata['table']), item_ids)
return affected_books
def rename_item(self, item_id, new_name, db):
rmap = {icu_lower(v):k for k, v in self.id_map.iteritems()}
existing_item = rmap.get(icu_lower(new_name), None)
table, col, lcol = self.metadata['table'], self.metadata['column'], self.metadata['link_column']
affected_books = self.col_book_map.get(item_id, set())
new_id = item_id
if existing_item is None or existing_item == item_id:
# A simple rename will do the trick
self.id_map[item_id] = new_name
db.execute('UPDATE {0} SET {1}=? WHERE id=?'.format(table, col), (new_name, item_id))
else:
# We have to replace
new_id = existing_item
self.id_map.pop(item_id, None)
books = self.col_book_map.pop(item_id, set())
for book_id in books:
self.book_col_map[book_id] = existing_item
self.col_book_map[existing_item].update(books)
# For custom series this means that the series index can
# potentially have duplicates/be incorrect, but there is no way to
# handle that in this context.
db.execute('UPDATE {0} SET {1}=? WHERE {1}=?; DELETE FROM {2} WHERE id=?'.format(
self.link_table, lcol, table), (existing_item, item_id, item_id))
return affected_books, new_id
class RatingTable(ManyToOneTable):
def read_id_maps(self, db):
ManyToOneTable.read_id_maps(self, db)
# Ensure there are no records with rating=0 in the table. These should
# be represented as rating:None instead.
bad_ids = {item_id for item_id, rating in self.id_map.iteritems() if rating == 0}
if bad_ids:
self.id_map = {item_id:rating for item_id, rating in self.id_map.iteritems() if rating != 0}
db.executemany('DELETE FROM {0} WHERE {1}=?'.format(self.link_table, self.metadata['link_column']),
tuple((x,) for x in bad_ids))
db.execute('DELETE FROM {0} WHERE {1}=0'.format(
self.metadata['table'], self.metadata['column']))
class ManyToManyTable(ManyToOneTable):
'''
Represents data that has a many-to-many mapping with books. i.e. each book
can have more than one value and each value can be mapped to more than one
book. For example: tags or authors.
'''
table_type = MANY_MANY
selectq = 'SELECT book, {0} FROM {1} ORDER BY id'
do_clean_on_remove = True
def read_maps(self, db):
bcm = defaultdict(list)
cbm = self.col_book_map
for book, item_id in db.execute(
self.selectq.format(self.metadata['link_column'], self.link_table)):
cbm[item_id].add(book)
bcm[book].append(item_id)
self.book_col_map = {k:tuple(v) for k, v in bcm.iteritems()}
def fix_link_table(self, db):
linked_item_ids = {item_id for item_ids in self.book_col_map.itervalues() for item_id in item_ids}
extra_item_ids = linked_item_ids - set(self.id_map)
if extra_item_ids:
for item_id in extra_item_ids:
book_ids = self.col_book_map.pop(item_id, ())
for book_id in book_ids:
self.book_col_map[book_id] = tuple(iid for iid in self.book_col_map.pop(book_id, ()) if iid not in extra_item_ids)
db.executemany('DELETE FROM {0} WHERE {1}=?'.format(
self.link_table, self.metadata['link_column']), tuple((x,) for x in extra_item_ids))
def remove_books(self, book_ids, db):
clean = set()
for book_id in book_ids:
item_ids = self.book_col_map.pop(book_id, ())
for item_id in item_ids:
try:
self.col_book_map[item_id].discard(book_id)
except KeyError:
if self.id_map.pop(item_id, null) is not null:
clean.add(item_id)
else:
if not self.col_book_map[item_id]:
del self.col_book_map[item_id]
if self.id_map.pop(item_id, null) is not null:
clean.add(item_id)
if clean and self.do_clean_on_remove:
db.executemany(
'DELETE FROM {0} WHERE id=?'.format(self.metadata['table']),
[(x,) for x in clean])
return clean
def remove_items(self, item_ids, db):
affected_books = set()
for item_id in item_ids:
val = self.id_map.pop(item_id, null)
if val is null:
continue
book_ids = self.col_book_map.pop(item_id, set())
for book_id in book_ids:
self.book_col_map[book_id] = tuple(x for x in self.book_col_map.get(book_id, ()) if x != item_id)
affected_books.update(book_ids)
item_ids = tuple((x,) for x in item_ids)
db.executemany('DELETE FROM {0} WHERE {1}=?'.format(self.link_table, self.metadata['link_column']), item_ids)
db.executemany('DELETE FROM {0} WHERE id=?'.format(self.metadata['table']), item_ids)
return affected_books
def rename_item(self, item_id, new_name, db):
rmap = {icu_lower(v):k for k, v in self.id_map.iteritems()}
existing_item = rmap.get(icu_lower(new_name), None)
table, col, lcol = self.metadata['table'], self.metadata['column'], self.metadata['link_column']
affected_books = self.col_book_map.get(item_id, set())
new_id = item_id
if existing_item is None or existing_item == item_id:
# A simple rename will do the trick
self.id_map[item_id] = new_name
db.execute('UPDATE {0} SET {1}=? WHERE id=?'.format(table, col), (new_name, item_id))
else:
# We have to replace
new_id = existing_item
self.id_map.pop(item_id, None)
books = self.col_book_map.pop(item_id, set())
# Replacing item_id with existing_item could cause the same id to
# appear twice in the book list. Handle that by removing existing
# item from the book list before replacing.
for book_id in books:
self.book_col_map[book_id] = tuple((existing_item if x == item_id else x) for x in self.book_col_map.get(book_id, ()) if x != existing_item)
self.col_book_map[existing_item].update(books)
db.executemany('DELETE FROM {0} WHERE book=? AND {1}=?'.format(self.link_table, lcol), [
(book_id, existing_item) for book_id in books])
db.execute('UPDATE {0} SET {1}=? WHERE {1}=?; DELETE FROM {2} WHERE id=?'.format(
self.link_table, lcol, table), (existing_item, item_id, item_id))
return affected_books, new_id
def fix_case_duplicates(self, db):
from calibre.db.write import uniq
case_map = defaultdict(set)
for item_id, val in self.id_map.iteritems():
case_map[icu_lower(val)].add(item_id)
for v in case_map.itervalues():
if len(v) > 1:
done_books = set()
main_id = min(v)
v.discard(main_id)
for item_id in v:
self.id_map.pop(item_id, None)
books = self.col_book_map.pop(item_id, set())
for book_id in books:
if book_id in done_books:
continue
done_books.add(book_id)
orig = self.book_col_map.get(book_id, ())
if not orig:
continue
vals = uniq(tuple(main_id if x in v else x for x in orig))
self.book_col_map[book_id] = vals
if len(orig) == len(vals):
# We have a simple replacement
db.executemany(
'UPDATE {0} SET {1}=? WHERE {1}=? AND book=?'.format(
self.link_table, self.metadata['link_column']),
tuple((main_id, x, book_id) for x in v))
else:
# duplicates
db.execute('DELETE FROM {0} WHERE book=?'.format(self.link_table), (book_id,))
db.executemany(
'INSERT INTO {0} (book,{1}) VALUES (?,?)'.format(self.link_table, self.metadata['link_column']),
tuple((book_id, x) for x in vals))
db.executemany('DELETE FROM {0} WHERE id=?'.format(self.metadata['table']),
tuple((x,) for x in v))
class AuthorsTable(ManyToManyTable):
def read_id_maps(self, db):
self.alink_map = lm = {}
self.asort_map = sm = {}
self.id_map = im = {}
us = self.unserialize
for aid, name, sort, link in db.execute(
'SELECT id, name, sort, link FROM authors'):
name = us(name)
im[aid] = name
sm[aid] = (sort or author_to_author_sort(name))
lm[aid] = link
def set_sort_names(self, aus_map, db):
aus_map = {aid:(a or '').strip() for aid, a in aus_map.iteritems()}
aus_map = {aid:a for aid, a in aus_map.iteritems() if a != self.asort_map.get(aid, None)}
self.asort_map.update(aus_map)
db.executemany('UPDATE authors SET sort=? WHERE id=?',
[(v, k) for k, v in aus_map.iteritems()])
return aus_map
def set_links(self, link_map, db):
link_map = {aid:(l or '').strip() for aid, l in link_map.iteritems()}
link_map = {aid:l for aid, l in link_map.iteritems() if l != self.alink_map.get(aid, None)}
self.alink_map.update(link_map)
db.executemany('UPDATE authors SET link=? WHERE id=?',
[(v, k) for k, v in link_map.iteritems()])
return link_map
def remove_books(self, book_ids, db):
clean = ManyToManyTable.remove_books(self, book_ids, db)
for item_id in clean:
self.alink_map.pop(item_id, None)
self.asort_map.pop(item_id, None)
return clean
def rename_item(self, item_id, new_name, db):
ret = ManyToManyTable.rename_item(self, item_id, new_name, db)
if item_id not in self.id_map:
self.alink_map.pop(item_id, None)
self.asort_map.pop(item_id, None)
else:
# Was a simple rename, update the author sort value
self.set_sort_names({item_id:author_to_author_sort(new_name)}, db)
return ret
def remove_items(self, item_ids, db):
raise ValueError('Direct removal of authors is not allowed')
class FormatsTable(ManyToManyTable):
do_clean_on_remove = False
def read_id_maps(self, db):
pass
def fix_case_duplicates(self, db):
pass
def read_maps(self, db):
self.fname_map = fnm = defaultdict(dict)
self.size_map = sm = defaultdict(dict)
self.col_book_map = cbm = defaultdict(set)
bcm = defaultdict(list)
for book, fmt, name, sz in db.execute('SELECT book, format, name, uncompressed_size FROM data'):
if fmt is not None:
fmt = fmt.upper()
cbm[fmt].add(book)
bcm[book].append(fmt)
fnm[book][fmt] = name
sm[book][fmt] = sz
self.book_col_map = {k:tuple(sorted(v)) for k, v in bcm.iteritems()}
def remove_books(self, book_ids, db):
clean = ManyToManyTable.remove_books(self, book_ids, db)
for book_id in book_ids:
self.fname_map.pop(book_id, None)
self.size_map.pop(book_id, None)
return clean
def set_fname(self, book_id, fmt, fname, db):
self.fname_map[book_id][fmt] = fname
db.execute('UPDATE data SET name=? WHERE book=? AND format=?',
(fname, book_id, fmt))
def remove_formats(self, formats_map, db):
for book_id, fmts in formats_map.iteritems():
self.book_col_map[book_id] = [fmt for fmt in self.book_col_map.get(book_id, []) if fmt not in fmts]
for m in (self.fname_map, self.size_map):
m[book_id] = {k:v for k, v in m[book_id].iteritems() if k not in fmts}
for fmt in fmts:
try:
self.col_book_map[fmt].discard(book_id)
except KeyError:
pass
db.executemany('DELETE FROM data WHERE book=? AND format=?',
[(book_id, fmt) for book_id, fmts in formats_map.iteritems() for fmt in fmts])
def zero_max(book_id):
try:
return max(self.size_map[book_id].itervalues())
except ValueError:
return 0
return {book_id:zero_max(book_id) for book_id in formats_map}
def remove_items(self, item_ids, db):
raise NotImplementedError('Cannot delete a format directly')
def rename_item(self, item_id, new_name, db):
raise NotImplementedError('Cannot rename formats')
def update_fmt(self, book_id, fmt, fname, size, db):
fmts = list(self.book_col_map.get(book_id, []))
try:
fmts.remove(fmt)
except ValueError:
pass
fmts.append(fmt)
self.book_col_map[book_id] = tuple(fmts)
try:
self.col_book_map[fmt].add(book_id)
except KeyError:
self.col_book_map[fmt] = {book_id}
self.fname_map[book_id][fmt] = fname
self.size_map[book_id][fmt] = size
db.execute('INSERT OR REPLACE INTO data (book,format,uncompressed_size,name) VALUES (?,?,?,?)',
(book_id, fmt, size, fname))
return max(self.size_map[book_id].itervalues())
class IdentifiersTable(ManyToManyTable):
def read_id_maps(self, db):
pass
def fix_case_duplicates(self, db):
pass
def read_maps(self, db):
self.book_col_map = defaultdict(dict)
self.col_book_map = defaultdict(set)
for book, typ, val in db.execute('SELECT book, type, val FROM identifiers'):
if typ is not None and val is not None:
self.col_book_map[typ].add(book)
self.book_col_map[book][typ] = val
def remove_books(self, book_ids, db):
clean = set()
for book_id in book_ids:
item_map = self.book_col_map.pop(book_id, {})
for item_id in item_map:
try:
self.col_book_map[item_id].discard(book_id)
except KeyError:
clean.add(item_id)
else:
if not self.col_book_map[item_id]:
del self.col_book_map[item_id]
clean.add(item_id)
return clean
def remove_items(self, item_ids, db):
raise NotImplementedError('Direct deletion of identifiers is not implemented')
def rename_item(self, item_id, new_name, db):
raise NotImplementedError('Cannot rename identifiers')
def all_identifier_types(self):
return frozenset(k for k, v in self.col_book_map.iteritems() if v) | unknown | codeparrot/codeparrot-clean | ||
"""
This file defines base tests for CoderBot
in order to test its functionality
The function run_test(varargin) lanuches tests
according to required test from the front-end.
e.g. varagrin = ["motor_test", "sonar_test"]
__test_encoder() and __test_sonar() will be launched.
If something goes wrong a -1 is returned for the correspondent failed test.
If a test passes for correspondent component, a 1 is returned.
If no test was executed on that component, 0 is preserved.
"""
from coderbot import CoderBot
c = CoderBot.get_instance()
# Single components tests
# encoder motors
def __test_encoder():
try:
# moving both wheels at speed 100 clockwise
print("moving both wheels at speed 100 clockwise")
assert(c.speed() == 0)
c.move(speed=100, elapse=2)
assert(c.distance() != 0)
assert (c.speed() == 0)
# moving both wheels at speed 40 clockwise
print("moving both wheels at speed 40 clockwise")
assert(c.speed() == 0)
c.move(speed=40, elapse=2)
assert(c.distance() != 0)
assert (c.speed() == 0)
# moving both wheels at speed 100 counter-clockwise
print("moving both wheels at speed 100 counter-clockwise")
assert(c.speed() == 0)
c.move(speed=-100, elapse=2)
assert(c.distance() != 0)
assert (c.speed() == 0)
# moving both wheels at speed 40 counter-clockwise
print("moving both wheels at speed 40 counter-clockwise")
assert(c.speed() == 0)
c.move(speed=-40, elapse=2)
assert(c.distance() != 0)
assert (c.speed() == 0)
# moving forward
print("moving forward")
assert(c.speed() == 0)
c.forward(speed=100, elapse=2)
assert(c.distance() != 0)
assert (c.speed() == 0)
# moving backwards
print("moving backwards")
assert(c.speed() == 0)
c.backward(speed=100, elapse=2)
assert(c.distance() != 0)
assert (c.speed() == 0)
# moving forward for 1 meter
print("moving forward for 1 meter")
assert(c.speed() == 0)
c.forward(speed=100, distance=1000)
assert(c.distance() != 0)
assert (c.speed() == 0)
# moving backwards for 1 meter
print("moving backwards for 1 meter")
assert(c.speed() == 0)
c.backward(speed=100, distance=1000)
assert(c.distance() != 0)
assert (c.speed() == 0)
# turning left
print("turning left")
assert(c.speed() == 0)
c.left(speed=100, elapse=2)
assert(c.distance() != 0)
assert (c.speed() == 0)
# turning right
print("turning right")
assert(c.speed() == 0)
c.right(speed=100, elapse=2)
assert(c.distance() != 0)
assert (c.speed() == 0)
return 1
except:
return -1
# sonar
def __testSonar():
return 1
# speaker
def __test_speaker():
return 1
# OCR
def __test_OCR():
return 1
# add more tests here
""" Main test function
it launches tests to test single components individually.
A dictionary is returned monitoring the state of the
tests for each component.
Varargin is a list of strings that indicates which test
to run. """
def run_test(varargin):
# state for each executed test
# 0 = component not tested
# 1 = test passed
# -1 = test failed
tests_state = {
"motors": 0,
"sonar": 0,
"speaker": 0,
"OCR": 0
# add more tests state here
}
# running chosen tests
for test in varargin:
if(test == 'motors'):
tests_state[test] = __test_encoder()
elif(test == 'sonar'):
tests_state[test] = __testSonar()
elif (test == 'speaker'):
tests_state[test] = __test_speaker()
elif(test == 'ocr'):
tests_state[test] = __test_OCR()
#add more test cases here
return tests_state | unknown | codeparrot/codeparrot-clean | ||
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_title01.xlsx'
test_dir = 'xlsxwriter/test/comparison/'
self.got_filename = test_dir + '_test_' + filename
self.exp_filename = test_dir + 'xlsx_files/' + filename
self.ignore_files = []
self.ignore_elements = {}
def test_create_file(self):
"""Test the creation of an XlsxWriter file with default title."""
workbook = Workbook(self.got_filename)
worksheet = workbook.add_worksheet()
chart = workbook.add_chart({'type': 'column'})
chart.axis_ids = [46165376, 54462720]
data = [
[1, 2, 3, 4, 5],
[2, 4, 6, 8, 10],
[3, 6, 9, 12, 15],
]
worksheet.write_column('A1', data[0])
worksheet.write_column('B1', data[1])
worksheet.write_column('C1', data[2])
chart.add_series({'values': '=Sheet1!$A$1:$A$5',
'name': 'Foo'})
chart.set_title({'none': True})
worksheet.insert_chart('E9', chart)
workbook.close()
self.assertExcelEqual() | unknown | codeparrot/codeparrot-clean | ||
// Copyright © 2022 Apple Inc.
#define AT_DISPATCH_MPS_TYPES(TYPE, NAME, ...) \
AT_DISPATCH_SWITCH( \
TYPE, \
NAME, \
AT_DISPATCH_CASE(at::ScalarType::Float, __VA_ARGS__) AT_DISPATCH_CASE( \
at::ScalarType::Half, \
__VA_ARGS__) AT_DISPATCH_CASE(at::ScalarType::BFloat16, __VA_ARGS__) \
AT_DISPATCH_CASE(at::ScalarType::Long, __VA_ARGS__) \
AT_DISPATCH_CASE(at::ScalarType::Int, __VA_ARGS__) \
AT_DISPATCH_CASE(at::ScalarType::Short, __VA_ARGS__) \
AT_DISPATCH_CASE(at::ScalarType::Char, __VA_ARGS__) \
AT_DISPATCH_CASE(at::ScalarType::Byte, __VA_ARGS__)) | c | github | https://github.com/pytorch/pytorch | aten/src/ATen/native/mps/TensorFactory.h |
# -*- coding: utf-8 -*-
"""
pygments.formatters.bbcode
~~~~~~~~~~~~~~~~~~~~~~~~~~
BBcode formatter.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.formatter import Formatter
from pygments.util import get_bool_opt
__all__ = ['BBCodeFormatter']
class BBCodeFormatter(Formatter):
"""
Format tokens with BBcodes. These formatting codes are used by many
bulletin boards, so you can highlight your sourcecode with pygments before
posting it there.
This formatter has no support for background colors and borders, as there
are no common BBcode tags for that.
Some board systems (e.g. phpBB) don't support colors in their [code] tag,
so you can't use the highlighting together with that tag.
Text in a [code] tag usually is shown with a monospace font (which this
formatter can do with the ``monofont`` option) and no spaces (which you
need for indentation) are removed.
Additional options accepted:
`style`
The style to use, can be a string or a Style subclass (default:
``'default'``).
`codetag`
If set to true, put the output into ``[code]`` tags (default:
``false``)
`monofont`
If set to true, add a tag to show the code with a monospace font
(default: ``false``).
"""
name = 'BBCode'
aliases = ['bbcode', 'bb']
filenames = []
def __init__(self, **options):
Formatter.__init__(self, **options)
self._code = get_bool_opt(options, 'codetag', False)
self._mono = get_bool_opt(options, 'monofont', False)
self.styles = {}
self._make_styles()
def _make_styles(self):
for ttype, ndef in self.style:
start = end = ''
if ndef['color']:
start += '[color=#%s]' % ndef['color']
end = '[/color]' + end
if ndef['bold']:
start += '[b]'
end = '[/b]' + end
if ndef['italic']:
start += '[i]'
end = '[/i]' + end
if ndef['underline']:
start += '[u]'
end = '[/u]' + end
# there are no common BBcodes for background-color and border
self.styles[ttype] = start, end
def format_unencoded(self, tokensource, outfile):
if self._code:
outfile.write('[code]')
if self._mono:
outfile.write('[font=monospace]')
lastval = ''
lasttype = None
for ttype, value in tokensource:
while ttype not in self.styles:
ttype = ttype.parent
if ttype == lasttype:
lastval += value
else:
if lastval:
start, end = self.styles[lasttype]
outfile.write(''.join((start, lastval, end)))
lastval = value
lasttype = ttype
if lastval:
start, end = self.styles[lasttype]
outfile.write(''.join((start, lastval, end)))
if self._mono:
outfile.write('[/font]')
if self._code:
outfile.write('[/code]')
if self._code or self._mono:
outfile.write('\n') | unknown | codeparrot/codeparrot-clean | ||
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_PLATFORM_PREFETCH_H_
#define TENSORFLOW_CORE_PLATFORM_PREFETCH_H_
#include "xla/tsl/platform/prefetch.h"
namespace tensorflow {
namespace port {
// NOLINTBEGIN(misc-unused-using-decls)
using ::tsl::port::prefetch;
using ::tsl::port::PREFETCH_HINT_NTA;
using ::tsl::port::PREFETCH_HINT_T0;
using ::tsl::port::PrefetchHint;
// NOLINTEND(misc-unused-using-decls)
} // namespace port
} // namespace tensorflow
#endif // TENSORFLOW_CORE_PLATFORM_PREFETCH_H_ | c | github | https://github.com/tensorflow/tensorflow | tensorflow/core/platform/prefetch.h |
from django.db.backends.creation import BaseDatabaseCreation
from django.db.backends.util import truncate_name
class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their associated PostgreSQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be interpolated against the values of Field.__dict__ before being output.
# If a column type is set to None, it won't be included in the output.
data_types = {
'AutoField': 'serial',
'BinaryField': 'bytea',
'BooleanField': 'boolean',
'CharField': 'varchar(%(max_length)s)',
'CommaSeparatedIntegerField': 'varchar(%(max_length)s)',
'DateField': 'date',
'DateTimeField': 'timestamp with time zone',
'DecimalField': 'numeric(%(max_digits)s, %(decimal_places)s)',
'FileField': 'varchar(%(max_length)s)',
'FilePathField': 'varchar(%(max_length)s)',
'FloatField': 'double precision',
'IntegerField': 'integer',
'BigIntegerField': 'bigint',
'IPAddressField': 'inet',
'GenericIPAddressField': 'inet',
'NullBooleanField': 'boolean',
'OneToOneField': 'integer',
'PositiveIntegerField': 'integer CHECK ("%(column)s" >= 0)',
'PositiveSmallIntegerField': 'smallint CHECK ("%(column)s" >= 0)',
'SlugField': 'varchar(%(max_length)s)',
'SmallIntegerField': 'smallint',
'TextField': 'text',
'TimeField': 'time',
}
def sql_table_creation_suffix(self):
assert self.connection.settings_dict['TEST_COLLATION'] is None, "PostgreSQL does not support collation setting at database creation time."
if self.connection.settings_dict['TEST_CHARSET']:
return "WITH ENCODING '%s'" % self.connection.settings_dict['TEST_CHARSET']
return ''
def sql_indexes_for_field(self, model, f, style):
output = []
if f.db_index or f.unique:
qn = self.connection.ops.quote_name
db_table = model._meta.db_table
tablespace = f.db_tablespace or model._meta.db_tablespace
if tablespace:
tablespace_sql = self.connection.ops.tablespace_sql(tablespace)
if tablespace_sql:
tablespace_sql = ' ' + tablespace_sql
else:
tablespace_sql = ''
def get_index_sql(index_name, opclass=''):
return (style.SQL_KEYWORD('CREATE INDEX') + ' ' +
style.SQL_TABLE(qn(truncate_name(index_name,self.connection.ops.max_name_length()))) + ' ' +
style.SQL_KEYWORD('ON') + ' ' +
style.SQL_TABLE(qn(db_table)) + ' ' +
"(%s%s)" % (style.SQL_FIELD(qn(f.column)), opclass) +
"%s;" % tablespace_sql)
if not f.unique:
output = [get_index_sql('%s_%s' % (db_table, f.column))]
# Fields with database column types of `varchar` and `text` need
# a second index that specifies their operator class, which is
# needed when performing correct LIKE queries outside the
# C locale. See #12234.
db_type = f.db_type(connection=self.connection)
if db_type.startswith('varchar'):
output.append(get_index_sql('%s_%s_like' % (db_table, f.column),
' varchar_pattern_ops'))
elif db_type.startswith('text'):
output.append(get_index_sql('%s_%s_like' % (db_table, f.column),
' text_pattern_ops'))
return output | unknown | codeparrot/codeparrot-clean | ||
"""
Library Content XBlock Wrapper
"""
from __future__ import absolute_import
from bok_choy.page_object import PageObject
class LibraryContentXBlockWrapper(PageObject):
"""
A PageObject representing a wrapper around a LibraryContent block seen in the LMS
"""
url = None
BODY_SELECTOR = '.xblock-student_view div'
def __init__(self, browser, locator):
super(LibraryContentXBlockWrapper, self).__init__(browser)
self.locator = locator
def is_browser_on_page(self):
"""
Checks if page is opened
"""
return self.q(css='{}[data-id="{}"]'.format(self.BODY_SELECTOR, self.locator)).present
def _bounded_selector(self, selector):
"""
Return `selector`, but limited to this particular block's context
"""
return u'{}[data-id="{}"] {}'.format(
self.BODY_SELECTOR,
self.locator,
selector
)
@property
def children_contents(self):
"""
Gets contents of all child XBlocks as list of strings
"""
child_blocks = self.q(css=self._bounded_selector("div[data-id]"))
return frozenset(child.text for child in child_blocks)
@property
def children_headers(self):
"""
Gets headers of all child XBlocks as list of strings
"""
child_blocks_headers = self.q(css=self._bounded_selector("div[data-id] .problem-header"))
return frozenset(child.text for child in child_blocks_headers) | unknown | codeparrot/codeparrot-clean | ||
//===--- APIDiffMigratorPass.cpp ------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/USRGeneration.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Frontend/Frontend.h"
#include "swift/IDE/APIDigesterData.h"
#include "swift/IDE/Utils.h"
#include "swift/Migrator/ASTMigratorPass.h"
#include "swift/Migrator/EditorAdapter.h"
#include "swift/Migrator/FixitApplyDiagnosticConsumer.h"
#include "swift/Migrator/Migrator.h"
#include "swift/Migrator/RewriteBufferEditsReceiver.h"
#include "swift/Parse/Lexer.h"
#include "swift/Sema/IDETypeChecking.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Edit/EditedSource.h"
#include "llvm/ADT/RewriteBuffer.h"
#include "llvm/Support/FileSystem.h"
using namespace swift;
using namespace swift::migrator;
using namespace swift::ide;
using namespace swift::ide::api;
namespace {
struct FoundResult {
SourceRange TokenRange;
bool Optional; // Range includes a trailing ? or !, e.g. [SomeType!]
bool Suffixable; // No need to wrap parens when adding optionality
bool Suffixed; // Range is followed by a trailing ? or !, e.g. [SomeType]!
bool isValid() const { return TokenRange.isValid(); }
};
class ChildIndexFinder : public TypeReprVisitor<ChildIndexFinder, FoundResult> {
ArrayRef<uint8_t> ChildIndices;
bool ParentIsOptional;
bool IsFunctionTypeArgument;
public:
ChildIndexFinder(ArrayRef<uint8_t> ChildIndices)
: ChildIndices(ChildIndices), ParentIsOptional(false),
IsFunctionTypeArgument(false) {}
FoundResult findChild(AbstractFunctionDecl *Parent) {
auto NextIndex = consumeNext();
if (!NextIndex) {
if (auto Func = dyn_cast<FuncDecl>(Parent)) {
if (auto *const TyRepr = Func->getResultTypeRepr())
return visit(TyRepr);
} else if (auto Init = dyn_cast<ConstructorDecl>(Parent)) {
SourceLoc End = Init->getFailabilityLoc();
bool Optional = End.isValid();
if (!Optional)
End = Init->getNameLoc();
return {SourceRange(Init->getNameLoc(), End), Optional,
/*suffixable=*/true, /*suffixed=*/false};
}
return {SourceRange(), false, false, false};
}
for (auto *Param: *Parent->getParameters()) {
if (!--NextIndex) {
return visit(Param->getTypeRepr());
}
}
llvm_unreachable("child index out of bounds");
}
private:
bool hasNextIndex() const {
return !ChildIndices.empty();
}
unsigned consumeNext() {
unsigned Next = ChildIndices.front();
ChildIndices = ChildIndices.drop_front();
return Next;
}
bool isUserTypeAlias(TypeRepr *T) const {
if (auto *DeclRefTR = dyn_cast<DeclRefTypeRepr>(T)) {
if (auto *Bound = DeclRefTR->getBoundDecl()) {
return isa<TypeAliasDecl>(Bound) &&
!Bound->getModuleContext()->isSystemModule();
}
}
return false;
}
public:
template<typename T>
FoundResult handleParent(TypeRepr *Parent, const ArrayRef<T> Children,
bool Optional = false, bool Suffixable = true) {
if (!hasNextIndex())
return {
Parent->getSourceRange(),
Optional, Suffixable, /*Suffixed=*/ParentIsOptional
};
auto NextIndex = consumeNext();
if (isUserTypeAlias(Parent))
return {SourceRange(), false, false, false};
assert(NextIndex < Children.size());
TypeRepr *Child = Children[NextIndex];
ParentIsOptional = Optional;
IsFunctionTypeArgument = NextIndex == 1 && isa<FunctionTypeRepr>(Parent);
return visit(Child);
}
FoundResult handleParent(TypeRepr *Parent, TypeRepr *FirstChild,
TypeRepr *SecondChild, bool Optional = false,
bool Suffixable = true) {
TypeRepr *Children[] = {FirstChild, SecondChild};
return handleParent(Parent, llvm::ArrayRef(Children), Optional, Suffixable);
}
FoundResult handleParent(TypeRepr *Parent, TypeRepr *Base,
bool Optional = false, bool Suffixable = true) {
return handleParent(Parent, llvm::ArrayRef(Base), Optional, Suffixable);
}
FoundResult visitTypeRepr(TypeRepr *T) {
llvm_unreachable("unexpected typerepr");
}
FoundResult visitErrorTypeRepr(ErrorTypeRepr *T) {
return {SourceRange(), false, false, false};
}
FoundResult visitAttributedTypeRepr(AttributedTypeRepr *T) {
return visit(T->getTypeRepr());
}
FoundResult visitOwnershipTypeRepr(OwnershipTypeRepr *T) {
return visit(T->getBase());
}
FoundResult visitIsolatedTypeRepr(IsolatedTypeRepr *T) {
return visit(T->getBase());
}
FoundResult visitSendingTypeRepr(SendingTypeRepr *T) {
return visit(T->getBase());
}
FoundResult visitCallerIsolatedTypeRepr(CallerIsolatedTypeRepr *T) {
return visit(T->getBase());
}
FoundResult visitArrayTypeRepr(ArrayTypeRepr *T) {
return handleParent(T, T->getBase());
}
FoundResult visitInlineArrayTypeRepr(InlineArrayTypeRepr *T) {
return handleParent(T, T->getCount(), T->getElement());
}
FoundResult visitDictionaryTypeRepr(DictionaryTypeRepr *T) {
return handleParent(T, T->getKey(), T->getValue());
}
FoundResult visitTupleTypeRepr(TupleTypeRepr *T) {
// Paren TupleTypeReprs may be arbitrarily nested so don't count as their
// own index level except in the case of function type argument parens
if (T->isParenType() && !IsFunctionTypeArgument) {
ParentIsOptional = false;
return visit(T->getElementType(0));
}
IsFunctionTypeArgument = false;
llvm::SmallVector<TypeRepr *, 8> Children;
T->getElementTypes(Children);
return handleParent(T, ArrayRef<TypeRepr *>(Children));
}
FoundResult visitFunctionTypeRepr(FunctionTypeRepr *T) {
return handleParent(T, T->getResultTypeRepr(), T->getArgsTypeRepr(),
/*Optional=*/false, /*Suffixable=*/false);
}
FoundResult visitCompositionTypeRepr(CompositionTypeRepr *T) {
return handleParent(T, T->getTypes(), /*Optional=*/false,
/*Suffixable=*/false);
}
FoundResult visitDeclRefTypeRepr(DeclRefTypeRepr *T) {
return handleParent(T, T->getGenericArgs());
}
FoundResult visitOptionalTypeRepr(OptionalTypeRepr *T) {
return handleParent(T, T->getBase(), /*Optional=*/true);
}
FoundResult visitImplicitlyUnwrappedOptionalTypeRepr(ImplicitlyUnwrappedOptionalTypeRepr *T) {
return handleParent(T, T->getBase(), /*Optional=*/true);
}
FoundResult visitProtocolTypeRepr(ProtocolTypeRepr *T) {
return handleParent(T, T->getBase());
}
FoundResult visitMetatypeTypeRepr(MetatypeTypeRepr *T) {
return handleParent(T, T->getBase());
}
FoundResult visitFixedTypeRepr(FixedTypeRepr *T) {
return handleParent(T, ArrayRef<TypeRepr*>());
}
FoundResult visitSelfTypeRepr(SelfTypeRepr *T) {
return handleParent(T, ArrayRef<TypeRepr*>());
}
};
struct ConversionFunctionInfo {
Expr *ExpressionToWrap;
SmallString<256> Buffer;
unsigned FuncNameStart;
unsigned FuncNameEnd;
ConversionFunctionInfo(Expr *ExpressionToWrap):
ExpressionToWrap(ExpressionToWrap) {}
StringRef getFuncDef() const { return Buffer.str(); }
StringRef getFuncName() const {
return Buffer.substr(FuncNameStart, FuncNameEnd - FuncNameStart);
}
};
struct APIDiffMigratorPass : public ASTMigratorPass, public SourceEntityWalker {
APIDiffItemStore DiffStore;
bool isNilExpr(Expr *E) {
auto Range = E->getSourceRange();
return Range.isValid() && Lexer::getCharSourceRangeFromSourceRange(
SF->getASTContext().SourceMgr, Range).str() == "nil";
}
bool isDotMember(CharSourceRange Range) {
auto S = Range.str();
return S.starts_with(".") && S.substr(1).find(".") == StringRef::npos;
}
bool isDotMember(SourceRange Range) {
return isDotMember(Lexer::getCharSourceRangeFromSourceRange(
SF->getASTContext().SourceMgr, Range));
}
bool isDotMember(Expr *E) {
auto Range = E->getSourceRange();
return Range.isValid() && isDotMember(Range);
}
std::vector<APIDiffItem*> getRelatedDiffItems(ValueDecl *VD) {
std::vector<APIDiffItem*> results;
if (!VD)
return results;
auto addDiffItems = [&](ValueDecl *VD) {
llvm::SmallString<64> Buffer;
llvm::raw_svector_ostream OS(Buffer);
if (swift::ide::printValueDeclUSR(VD, OS))
return;
auto Items = DiffStore.getDiffItems(Buffer.str());
results.insert(results.end(), Items.begin(), Items.end());
};
addDiffItems(VD);
for (auto *Overridden: collectAllOverriddenDecls(VD,
/*IncludeProtocolReqs=*/true,
/*Transitive=*/true)) {
addDiffItems(Overridden);
}
return results;
}
DeclNameViewer getFuncRename(ValueDecl *VD, llvm::SmallString<32> &Buffer,
bool &IgnoreBase) {
for (auto *Item: getRelatedDiffItems(VD)) {
if (auto *CI = dyn_cast<CommonDiffItem>(Item)) {
if (CI->isRename()) {
IgnoreBase = true;
switch(CI->NodeKind) {
case SDKNodeKind::DeclFunction:
IgnoreBase = false;
LLVM_FALLTHROUGH;
case SDKNodeKind::DeclConstructor:
return DeclNameViewer(CI->getNewName());
default:
return DeclNameViewer();
}
}
}
if (auto *MI = dyn_cast<TypeMemberDiffItem>(Item)) {
if (MI->Subkind == TypeMemberDiffItemSubKind::FuncRename) {
llvm::raw_svector_ostream OS(Buffer);
OS << MI->getNewTypeAndDot() << MI->newPrintedName;
return DeclNameViewer(OS.str());
}
}
}
return DeclNameViewer();
}
bool isSimpleReplacement(APIDiffItem *Item, bool isDotMember, std::string &Text) {
if (auto *MD = dyn_cast<TypeMemberDiffItem>(Item)) {
if (MD->Subkind == TypeMemberDiffItemSubKind::SimpleReplacement) {
bool NeedNoTypeName = isDotMember &&
MD->oldPrintedName == MD->newPrintedName;
if (NeedNoTypeName) {
Text = (llvm::Twine(MD->isNewNameGlobal() ? "" : ".") +
MD->getNewName().base()).str();
} else {
Text = (llvm::Twine(MD->getNewTypeAndDot()) +
MD->getNewName().base()).str();
}
return true;
}
}
// Simple rename.
if (auto CI = dyn_cast<CommonDiffItem>(Item)) {
if (CI->isRename() && (CI->NodeKind == SDKNodeKind::DeclVar ||
CI->NodeKind == SDKNodeKind::DeclType)) {
Text = CI->getNewName().str();
return true;
}
}
return false;
}
std::vector<ConversionFunctionInfo> HelperFuncInfo;
SourceLoc FileEndLoc;
llvm::StringSet<> OverridingRemoveNames;
/// For a given expression, check whether the type of this expression is
/// type alias type, and the type alias type is known to change to raw
/// representable type.
bool isRecognizedTypeAliasChange(Expr *E) {
if (auto Ty = E->getType()) {
if (auto *NT = dyn_cast<TypeAliasType>(Ty.getPointer())) {
for (auto Item: getRelatedDiffItems(NT->getDecl())) {
if (auto CI = dyn_cast<CommonDiffItem>(Item)) {
if (CI->DiffKind == NodeAnnotation::TypeAliasDeclToRawRepresentable) {
return true;
}
}
}
}
}
return false;
}
APIDiffMigratorPass(EditorAdapter &Editor, SourceFile *SF,
const MigratorOptions &Opts):
ASTMigratorPass(Editor, SF, Opts), DiffStore(Diags),
FileEndLoc(SM.getRangeForBuffer(BufferID).getEnd()),
OverridingRemoveNames(funcNamesForOverrideRemoval()) {}
~APIDiffMigratorPass() {
Editor.disableCache();
SWIFT_DEFER { Editor.enableCache(); };
// Collect inserted functions to avoid re-insertion.
std::set<std::string> InsertedFunctions;
SmallVector<Decl*, 16> TopDecls;
SF->getTopLevelDecls(TopDecls);
for (auto *D: TopDecls) {
if (auto *FD = dyn_cast<FuncDecl>(D)) {
InsertedFunctions.insert(
std::string(FD->getBaseIdentifier()));
}
}
// Handle helper functions without wrappees first.
for (auto &Cur: HelperFuncInfo) {
if (Cur.ExpressionToWrap)
continue;
auto FuncName = Cur.getFuncName().str();
// Avoid inserting the helper function if it's already present.
if (!InsertedFunctions.count(FuncName)) {
Editor.insert(FileEndLoc, Cur.getFuncDef());
InsertedFunctions.insert(FuncName);
}
}
// Remove all helper functions that're without expressions to wrap.
HelperFuncInfo.erase(std::remove_if(HelperFuncInfo.begin(),
HelperFuncInfo.end(), [](const ConversionFunctionInfo& Info) {
return !Info.ExpressionToWrap;
}), HelperFuncInfo.end());
for (auto &Cur: HelperFuncInfo) {
assert(Cur.ExpressionToWrap);
// Avoid wrapping nil expression.
if (isNilExpr(Cur.ExpressionToWrap))
continue;
// Avoid wrapping a single expression with multiple conversion functions.
auto count = std::count_if(HelperFuncInfo.begin(), HelperFuncInfo.end(),
[&] (ConversionFunctionInfo &Info) {
return Info.ExpressionToWrap->getSourceRange() ==
Cur.ExpressionToWrap->getSourceRange();
});
if (count > 1)
continue;
assert(count == 1);
// A conversion function will be redundant if the expression will change
// from type alias to raw-value representable.
if (isRecognizedTypeAliasChange(Cur.ExpressionToWrap))
continue;
auto FuncName = Cur.getFuncName().str();
// Avoid inserting the helper function if it's already present.
if (!InsertedFunctions.count(FuncName)) {
Editor.insert(FileEndLoc, Cur.getFuncDef());
InsertedFunctions.insert(FuncName);
}
Editor.insertBefore(Cur.ExpressionToWrap->getStartLoc(),
(Twine(FuncName) + "(").str());
Editor.insertAfterToken(Cur.ExpressionToWrap->getEndLoc(), ")");
}
}
void run() {
if (Opts.APIDigesterDataStorePaths.empty())
return;
for (auto Path : Opts.APIDigesterDataStorePaths)
DiffStore.addStorePath(Path);
DiffStore.printIncomingUsr(Opts.DumpUsr);
walk(SF);
}
bool updateStringRepresentableDeclRef(APIDiffItem *Diff,
CharSourceRange Range) {
auto *CD = dyn_cast<CommonDiffItem>(Diff);
if (!CD)
return false;
if (CD->NodeKind != SDKNodeKind::DeclVar)
return false;
if (!CD->isStringRepresentableChange())
return false;
switch(CD->DiffKind) {
case NodeAnnotation::SimpleStringRepresentableUpdate:
Editor.insert(Range.getEnd(), ".rawValue");
return true;
default:
return false;
}
}
bool visitDeclReference(ValueDecl *D, SourceRange Range, TypeDecl *CtorTyRef,
ExtensionDecl *ExtTyRef, Type T,
ReferenceMetaData Data) override {
CharSourceRange CharRange = Lexer::getCharSourceRangeFromSourceRange(
D->getASTContext().SourceMgr, Range);
if (Data.isImplicit)
return true;
for (auto *Item: getRelatedDiffItems(CtorTyRef ? CtorTyRef: D)) {
std::string RepText;
if (isSimpleReplacement(Item, isDotMember(CharRange), RepText)) {
Editor.replace(CharRange, RepText);
return true;
}
}
return true;
}
struct ReferenceCollector : public SourceEntityWalker {
ValueDecl *Target;
CharSourceRange Result;
ReferenceCollector(ValueDecl* Target) : Target(Target) {}
bool visitDeclReference(ValueDecl *D, SourceRange Range,
TypeDecl *CtorTyRef, ExtensionDecl *ExtTyRef,
Type T, ReferenceMetaData Data) override {
if (D == Target && !Data.isImplicit && Range.isValid()) {
Result = Lexer::getCharSourceRangeFromSourceRange(
D->getASTContext().SourceMgr, Range);
return false;
}
return true;
}
};
void emitRenameLabelChanges(ArgumentList *Args, DeclNameViewer NewName,
llvm::ArrayRef<unsigned> IgnoreArgIndex) {
unsigned Idx = 0;
auto Ranges = getCallArgLabelRanges(SM, Args,
LabelRangeEndAt::LabelNameOnly);
llvm::SmallVector<uint8_t, 2> ToRemoveIndices;
for (unsigned I = 0; I < Ranges.first.size(); I ++) {
if (std::any_of(IgnoreArgIndex.begin(), IgnoreArgIndex.end(),
[I](unsigned Ig) { return Ig == I; }))
continue;
// Ignore the first trailing closure label
if (Ranges.second && I == Ranges.second)
continue;
auto LR = Ranges.first[I];
if (Idx < NewName.argSize()) {
auto Label = NewName.args()[Idx++];
if (!Label.empty()) {
if (LR.getByteLength())
Editor.replace(LR, Label);
else
Editor.insert(LR.getStart(), (llvm::Twine(Label) + ": ").str());
} else if (LR.getByteLength()){
// New label is "_" however the old label is explicit.
ToRemoveIndices.push_back(I);
}
}
}
if (!ToRemoveIndices.empty()) {
auto Ranges = getCallArgLabelRanges(SM, Args,
LabelRangeEndAt::BeforeElemStart);
for (auto I : ToRemoveIndices) {
Editor.remove(Ranges.first[I]);
}
}
}
void handleFuncRename(ValueDecl *FD, Expr* FuncRefContainer,
ArgumentList *Args) {
bool IgnoreBase = false;
llvm::SmallString<32> Buffer;
if (auto View = getFuncRename(FD, Buffer, IgnoreBase)) {
if (!IgnoreBase) {
ReferenceCollector Walker(FD);
Walker.walk(FuncRefContainer);
Editor.replace(Walker.Result, View.base());
}
emitRenameLabelChanges(Args, View, {});
}
}
bool handleQualifiedReplacement(Expr* Call) {
auto handleDecl = [&](ValueDecl *VD, SourceRange ToReplace) {
for (auto *I: getRelatedDiffItems(VD)) {
if (auto *Item = dyn_cast<TypeMemberDiffItem>(I)) {
if (Item->Subkind == TypeMemberDiffItemSubKind::QualifiedReplacement) {
bool NeedNoTypeName = isDotMember(ToReplace) &&
Item->oldPrintedName == Item->newPrintedName;
if (NeedNoTypeName) {
Editor.replace(ToReplace,
(llvm::Twine(Item->isNewNameGlobal() ? "" : ".") +
Item->getNewName().base()).str());
} else {
Editor.replace(ToReplace,
(llvm::Twine(Item->getNewTypeAndDot()) +
Item->getNewName().base()).str());
}
return true;
}
}
}
return false;
};
if (auto *VD = getReferencedDecl(Call, /*semantic=*/false).second.getDecl())
if (handleDecl(VD, Call->getSourceRange()))
return true;
return false;
}
bool handleSpecialCases(ValueDecl *FD, CallExpr* Call, ArgumentList *Args) {
SpecialCaseDiffItem *Item = nullptr;
for (auto *I: getRelatedDiffItems(FD)) {
Item = dyn_cast<SpecialCaseDiffItem>(I);
if (Item)
break;
}
if (!Item)
return false;
std::vector<CallArgInfo> AllArgs =
getCallArgInfo(SM, Args, LabelRangeEndAt::LabelNameOnly);
switch(Item->caseId) {
case SpecialCaseId::NSOpenGLSetOption: {
// swift 3.2:
// NSOpenGLSetOption(NSOpenGLGOFormatCacheSize, 5)
// swift 4:
// NSOpenGLGOFormatCacheSize.globalValue = 5
CallArgInfo &FirstArg = AllArgs[0];
CallArgInfo &SecondArg = AllArgs[1];
Editor.remove(CharSourceRange(SM, Call->getStartLoc(),
FirstArg.ArgExp->getStartLoc()));
Editor.replace(CharSourceRange(SM, Lexer::getLocForEndOfToken(SM,
FirstArg.ArgExp->getEndLoc()), SecondArg.LabelRange.getStart()),
".globalValue = ");
Editor.remove(Call->getEndLoc());
return true;
}
case SpecialCaseId::NSOpenGLGetOption: {
// swift 3.2:
// NSOpenGLGetOption(NSOpenGLGOFormatCacheSize, &cacheSize)
// swift 4:
// cacheSize = NSOpenGLGOFormatCacheSize.globalValue
CallArgInfo &FirstArg = AllArgs[0];
CallArgInfo &SecondArg = AllArgs[1];
StringRef SecondArgContent = SecondArg.getEntireCharRange(SM).str();
if (SecondArgContent[0] == '&')
SecondArgContent = SecondArgContent.substr(1);
Editor.replace(CharSourceRange(SM, Call->getStartLoc(),
FirstArg.ArgExp->getStartLoc()),
(llvm::Twine(SecondArgContent) + " = ").str());
Editor.replace(CharSourceRange(SM, FirstArg.getEntireCharRange(SM).getEnd(),
Lexer::getLocForEndOfToken(SM, Call->getEndLoc())),
".globalValue");
return true;
}
case SpecialCaseId::StaticAbsToSwiftAbs:
// swift 3:
// CGFloat.abs(1.0)
// Float.abs(1.0)
// Double.abs(1.0)
// Float80.abs(1.0)
//
// swift 4:
// Swift.abs(1.0)
// Swift.abs(1.0)
// Swift.abs(1.0)
// Swift.abs(1.0)
Editor.replace(Call->getFn()->getSourceRange(), "Swift.abs");
return true;
case SpecialCaseId::ToUIntMax:
if (const auto *DotCall = dyn_cast<DotSyntaxCallExpr>(Call->getFn())) {
Editor.insert(DotCall->getStartLoc(), "UInt64(");
Editor.replace({ DotCall->getDotLoc(), Call->getEndLoc() }, ")");
return true;
}
return false;
case SpecialCaseId::ToIntMax:
if (const auto *DotCall = dyn_cast<DotSyntaxCallExpr>(Call->getFn())) {
Editor.insert(DotCall->getStartLoc(), "Int64(");
Editor.replace({ DotCall->getDotLoc(), Call->getEndLoc() }, ")");
return true;
}
return false;
case SpecialCaseId::NSOpenGLGetVersion: {
if (Args->size() != 2)
return false;
auto extractArg = [](const Expr *Arg) -> const DeclRefExpr * {
while (const auto *ICE = dyn_cast<ImplicitConversionExpr>(Arg)) {
Arg = ICE->getSubExpr();
}
if (const auto *IOE = dyn_cast<InOutExpr>(Arg)) {
return dyn_cast<DeclRefExpr>(IOE->getSubExpr());
}
return nullptr;
};
const auto *Arg0 = extractArg(Args->getExpr(0));
const auto *Arg1 = extractArg(Args->getExpr(1));
if (!(Arg0 && Arg1)) {
return false;
}
SmallString<256> Scratch;
llvm::raw_svector_ostream OS(Scratch);
auto StartLoc = Call->getStartLoc();
Editor.insert(StartLoc, "(");
Editor.insert(StartLoc,
SM.extractText(Lexer::getCharSourceRangeFromSourceRange(SM,
Arg0->getSourceRange())));
Editor.insert(StartLoc, ", ");
Editor.insert(StartLoc,
SM.extractText(Lexer::getCharSourceRangeFromSourceRange(SM,
Arg1->getSourceRange())));
Editor.insert(StartLoc, ") = ");
Editor.replace(Call->getSourceRange(), "NSOpenGLContext.openGLVersion");
return true;
}
case SpecialCaseId::UIApplicationMain: {
// If the first argument is CommandLine.argc, replace the second argument
// with CommandLine.unsafeArgv
CallArgInfo &FirstArg = AllArgs[0];
// handle whitespace/line splits around the first arg when matching
auto FirstArgSplit =
SM.extractText(FirstArg.getEntireCharRange(SM)).rsplit('.');
if (!FirstArgSplit.second.empty() &&
FirstArgSplit.first.trim() == "CommandLine" &&
FirstArgSplit.second.trim() == "argc") {
CallArgInfo &SecondArg = AllArgs[1];
Editor.replace(SecondArg.getEntireCharRange(SM),
"CommandLine.unsafeArgv");
return true;
}
return false;
}
}
llvm_unreachable("unhandled case");
}
bool handleTypeHoist(ValueDecl *FD, CallExpr* Call, ArgumentList *Args) {
TypeMemberDiffItem *Item = nullptr;
for (auto *I: getRelatedDiffItems(FD)) {
Item = dyn_cast<TypeMemberDiffItem>(I);
if (Item)
break;
}
if (!Item)
return false;
if (Item->Subkind == TypeMemberDiffItemSubKind::SimpleReplacement ||
Item->Subkind == TypeMemberDiffItemSubKind::QualifiedReplacement ||
Item->Subkind == TypeMemberDiffItemSubKind::FuncRename)
return false;
if (Item->Subkind == TypeMemberDiffItemSubKind::GlobalFuncToStaticProperty) {
Editor.replace(Call->getSourceRange(),
(llvm::Twine(Item->getNewTypeAndDot()) + Item->getNewName().base()).str());
return true;
}
if (*Item->selfIndex)
return false;
std::vector<CallArgInfo> AllArgs =
getCallArgInfo(SM, Args, LabelRangeEndAt::LabelNameOnly);
if (!AllArgs.size())
return false;
assert(*Item->selfIndex == 0 && "we cannot handle otherwise");
DeclNameViewer NewName = Item->getNewName();
llvm::SmallVector<unsigned, 2> IgnoredArgIndices;
IgnoredArgIndices.push_back(*Item->selfIndex);
if (auto RI = Item->removedIndex)
IgnoredArgIndices.push_back(*RI);
emitRenameLabelChanges(Args, NewName, IgnoredArgIndices);
auto *SelfExpr = AllArgs[0].ArgExp;
if (auto *IOE = dyn_cast<InOutExpr>(SelfExpr))
SelfExpr = IOE->getSubExpr();
const bool NeedParen = !SelfExpr->canAppendPostfixExpression();
// Remove the global function name: "Foo(a, b..." to "a, b..."
Editor.remove(CharSourceRange(SM, Call->getStartLoc(),
SelfExpr->getStartLoc()));
if (NeedParen)
Editor.insert(SelfExpr->getStartLoc(), "(");
std::string MemberFuncBase;
if (Item->Subkind == TypeMemberDiffItemSubKind::HoistSelfAndUseProperty)
MemberFuncBase = (llvm::Twine(NeedParen ? ")." : ".") + Item->getNewName().
base()).str();
else
MemberFuncBase = (llvm::Twine(NeedParen ? ")." : ".") + Item->getNewName().
base() + "(").str();
if (AllArgs.size() > 1) {
Editor.replace(CharSourceRange(SM, Lexer::getLocForEndOfToken(SM,
SelfExpr->getEndLoc()), AllArgs[1].LabelRange.getStart()),
MemberFuncBase);
} else {
Editor.insert(Lexer::getLocForEndOfToken(SM, SelfExpr->getEndLoc()),
MemberFuncBase);
}
switch (Item->Subkind) {
case TypeMemberDiffItemSubKind::FuncRename:
case TypeMemberDiffItemSubKind::GlobalFuncToStaticProperty:
case TypeMemberDiffItemSubKind::SimpleReplacement:
case TypeMemberDiffItemSubKind::QualifiedReplacement:
llvm_unreachable("should be handled elsewhere");
case TypeMemberDiffItemSubKind::HoistSelfOnly:
// we are done here.
return true;
case TypeMemberDiffItemSubKind::HoistSelfAndRemoveParam: {
unsigned RI = *Item->removedIndex;
CallArgInfo &ToRemove = AllArgs[RI];
if (AllArgs.size() == RI + 1) {
Editor.remove(ToRemove.getEntireCharRange(SM));
} else {
CallArgInfo &AfterToRemove = AllArgs[RI + 1];
Editor.remove(CharSourceRange(SM, ToRemove.LabelRange.getStart(),
AfterToRemove.LabelRange.getStart()));
}
return true;
}
case TypeMemberDiffItemSubKind::HoistSelfAndUseProperty:
// Remove ).
Editor.remove(Args->getEndLoc());
return true;
}
llvm_unreachable("unhandled subkind");
}
void handleFunctionCallToPropertyChange(ValueDecl *FD, Expr* FuncRefContainer,
ArgumentList *Args) {
for (auto *Item : getRelatedDiffItems(FD)) {
if (auto *CD = dyn_cast<CommonDiffItem>(Item)) {
switch (CD->DiffKind) {
case NodeAnnotation::GetterToProperty: {
// Remove "()"
Editor.remove(Lexer::getCharSourceRangeFromSourceRange(SM,
Args->getSourceRange()));
return;
}
case NodeAnnotation::SetterToProperty: {
ReferenceCollector Walker(FD);
Walker.walk(FuncRefContainer);
auto ReplaceRange = CharSourceRange(SM, Walker.Result.getStart(),
Args->getStartLoc().getAdvancedLoc(1));
// Replace "x.getY(" with "x.Y =".
auto Replacement = (llvm::Twine(Walker.Result.str()
.substr(3)) + " = ").str();
SmallString<64> Scratch;
Editor.replace(ReplaceRange,
camel_case::toLowercaseInitialisms(Replacement, Scratch));
// Remove ")"
Editor.remove(CharSourceRange(SM, Args->getEndLoc(),
Args->getEndLoc().getAdvancedLoc(1)));
return;
}
default:
break;
}
}
}
}
void replaceExpr(Expr* E, StringRef Text) {
Editor.replace(CharSourceRange(SM, E->getStartLoc(),
Lexer::getLocForEndOfToken(SM, E->getEndLoc())), Text);
}
bool wrapAttributeReference(Expr *Reference, Expr *WrapperTarget,
bool FromString) {
auto *RD = Reference->getReferencedDecl().getDecl();
if (!RD)
return false;
std::string Rename;
std::optional<NodeAnnotation> Kind;
StringRef LeftComment;
StringRef RightComment;
for (auto *Item: getRelatedDiffItems(RD)) {
if (isSimpleReplacement(Item, isDotMember(Reference), Rename)) {
} else if (auto *CI = dyn_cast<CommonDiffItem>(Item)) {
if (CI->isStringRepresentableChange() &&
CI->NodeKind == SDKNodeKind::DeclVar) {
Kind = CI->DiffKind;
LeftComment = CI->LeftComment;
RightComment = CI->RightComment;
}
}
}
if (!Kind.has_value())
return false;
if (Kind) {
insertHelperFunction(*Kind, LeftComment, RightComment, FromString,
WrapperTarget);
}
if (!Rename.empty()) {
replaceExpr(Reference, Rename);
}
return true;
}
bool handleAssignDestMigration(Expr *E) {
auto *ASE = dyn_cast<AssignExpr>(E);
if (!ASE || !ASE->getDest() || !ASE->getSrc())
return false;
auto *Dest = ASE->getDest();
auto Src = ASE->getSrc();
if (wrapAttributeReference(Dest, Src, true)) {
// We should handle the assignment source here since we won't visit
// the children with present changes.
handleAttributeReference(Src);
return true;
}
return false;
}
bool handleAttributeReference(Expr *E) {
return wrapAttributeReference(E, E, false);
}
ConversionFunctionInfo &insertHelperFunction(NodeAnnotation Anno,
StringRef RawType,
StringRef NewType,
bool FromString,
Expr *Wrappee) {
HelperFuncInfo.emplace_back(Wrappee);
ConversionFunctionInfo &Info = HelperFuncInfo.back();
llvm::raw_svector_ostream OS(Info.Buffer);
OS << "\n";
OS << "// Helper function inserted by Swift 4.2 migrator.\n";
OS << "fileprivate func ";
Info.FuncNameStart = Info.Buffer.size();
OS << (FromString ? "convertTo" : "convertFrom");
SmallVector<std::string, 8> Segs;
StringRef guard = "\tguard let input = input else { return nil }\n";
switch(Anno) {
case NodeAnnotation::OptionalArrayMemberUpdate:
Segs = {"Optional", "Array", (Twine("[") + RawType + "]?").str()};
Segs.push_back((Twine("[") + NewType +"]?").str());
Segs.push_back((Twine(guard) + "\treturn input.map { key in " + NewType +"(key) }").str());
Segs.push_back((Twine(guard) + "\treturn input.map { key in key.rawValue }").str());
break;
case NodeAnnotation::OptionalDictionaryKeyUpdate:
Segs = {"Optional", "Dictionary", (Twine("[") + RawType + ": Any]?").str()};
Segs.push_back((Twine("[") + NewType +": Any]?").str());
Segs.push_back((Twine(guard) +
"\treturn Dictionary(uniqueKeysWithValues: input.map"
" { key, value in (" + NewType + "(rawValue: key), value)})").str());
Segs.push_back((Twine(guard) +
"\treturn Dictionary(uniqueKeysWithValues: input.map"
" {key, value in (key.rawValue, value)})").str());
break;
case NodeAnnotation::ArrayMemberUpdate:
Segs = {"", "Array", (Twine("[") + RawType + "]").str()};
Segs.push_back((Twine("[") + NewType +"]").str());
Segs.push_back((Twine("\treturn input.map { key in ") + NewType +"(key) }").str());
Segs.push_back("\treturn input.map { key in key.rawValue }");
break;
case NodeAnnotation::DictionaryKeyUpdate:
Segs = {"", "Dictionary", (Twine("[") + RawType + ": Any]").str()};
Segs.push_back((Twine("[") + NewType +": Any]").str());
Segs.push_back((Twine("\treturn Dictionary(uniqueKeysWithValues: input.map"
" { key, value in (") + NewType + "(rawValue: key), value)})").str());
Segs.push_back("\treturn Dictionary(uniqueKeysWithValues: input.map"
" {key, value in (key.rawValue, value)})");
break;
case NodeAnnotation::SimpleStringRepresentableUpdate:
Segs = {"", "", RawType.str()};
Segs.push_back(NewType.str());
Segs.push_back((Twine("\treturn ") + NewType + "(rawValue: input)").str());
Segs.push_back("\treturn input.rawValue");
break;
case NodeAnnotation::SimpleOptionalStringRepresentableUpdate:
Segs = {"Optional", "", (Twine(RawType) +"?").str()};
Segs.push_back((Twine(NewType) +"?").str());
Segs.push_back((Twine(guard) + "\treturn " + NewType + "(rawValue: input)").str());
Segs.push_back((Twine(guard) + "\treturn input.rawValue").str());
break;
default:
llvm_unreachable("shouldn't handle this key.");
}
assert(Segs.size() == 6);
OS << Segs[0];
SmallVector<StringRef, 4> Parts;
NewType.split(Parts, '.');
for (auto P: Parts)
OS << P;
OS << Segs[1];
Info.FuncNameEnd = Info.Buffer.size();
if (FromString) {
OS << "(_ input: " << Segs[2] << ") -> " << Segs[3] << " {\n";
OS << Segs[4] << "\n}\n";
} else {
OS << "(_ input: " << Segs[3] << ") -> " << Segs[2] << " {\n";
OS << Segs[5] << "\n}\n";
}
return Info;
}
void handleStringRepresentableArg(ValueDecl *FD, ArgumentList *Args,
Expr *Call) {
NodeAnnotation Kind;
StringRef RawType;
StringRef NewAttributeType;
uint8_t ArgIdx;
for (auto Item: getRelatedDiffItems(FD)) {
if (auto *CI = dyn_cast<CommonDiffItem>(Item)) {
if (CI->isStringRepresentableChange()) {
Kind = CI->DiffKind;
RawType = CI->LeftComment;
NewAttributeType = CI->RightComment;
assert(CI->getChildIndices().size() == 1);
ArgIdx = CI->getChildIndices().front();
break;
}
}
}
if (NewAttributeType.empty())
return;
Expr *WrapTarget = Call;
bool FromString = false;
if (ArgIdx) {
ArgIdx --;
FromString = true;
auto AllArgs = getCallArgInfo(SM, Args, LabelRangeEndAt::LabelNameOnly);
if (AllArgs.size() <= ArgIdx)
return;
WrapTarget = AllArgs[ArgIdx].ArgExp;
}
assert(WrapTarget);
insertHelperFunction(Kind, RawType, NewAttributeType, FromString, WrapTarget);
}
bool hasRevertRawRepresentableChange(ValueDecl *VD) {
for (auto Item: getRelatedDiffItems(VD)) {
if (auto *CI = dyn_cast<CommonDiffItem>(Item)) {
if (CI->DiffKind ==
NodeAnnotation::RevertTypeAliasDeclToRawRepresentable)
return true;
}
}
return false;
}
bool handleRevertRawRepresentable(Expr *E) {
// Change attribute.rawValue to attribute
if (auto *MRE = dyn_cast<MemberRefExpr>(E)) {
auto Found = false;
if (auto *Base = MRE->getBase()) {
if (hasRevertRawRepresentableChange(Base->getType()->getAnyNominal())) {
Found = true;
}
}
if (!Found)
return false;
auto NL = MRE->getNameLoc().getStartLoc();
auto DL = MRE->getDotLoc();
if (NL.isInvalid() || DL.isInvalid())
return false;
CharSourceRange Range = Lexer::getCharSourceRangeFromSourceRange(SM, {DL, NL});
if (Range.str() == ".rawValue") {
Editor.remove(Range);
return true;
}
}
// Change attribute(rawValue: "value") to "value"
// Change attribute("value") to "value"
if (auto *CE = dyn_cast<CallExpr>(E)) {
auto Found = false;
if (auto *CRC = dyn_cast<ConstructorRefCallExpr>(CE->getFn())) {
if (auto *TE = dyn_cast<TypeExpr>(CRC->getBase())) {
if (hasRevertRawRepresentableChange(TE->getInstanceType()->getAnyNominal()))
Found = true;
}
}
if (!Found)
return false;
std::vector<CallArgInfo> AllArgs =
getCallArgInfo(SM, CE->getArgs(), LabelRangeEndAt::LabelNameOnly);
if (AllArgs.size() == 1) {
auto Label = AllArgs.front().LabelRange.str();
if (Label == "rawValue" || Label.empty()) {
Editor.replace(CE->getSourceRange(),
Lexer::getCharSourceRangeFromSourceRange(SM,
AllArgs.front().ArgExp->getSourceRange()).str());
return true;
}
}
}
return false;
}
void handleResultTypeChange(ValueDecl *FD, Expr *Call) {
std::optional<NodeAnnotation> ChangeKind;
// look for related change item for the function decl.
for (auto Item: getRelatedDiffItems(FD)) {
if (auto *CI = dyn_cast<CommonDiffItem>(Item)) {
// check if the function's return type has been changed from nonnull
// to nullable.
if (CI->DiffKind == NodeAnnotation::WrapOptional &&
CI->getChildIndices().size() == 1 &&
CI->getChildIndices().front() == 0) {
ChangeKind = NodeAnnotation::WrapOptional;
break;
}
}
}
if (!ChangeKind.has_value())
return;
// If a function's return type has been changed from nonnull to nullable,
// append ! to the original call expression.
if (*ChangeKind == NodeAnnotation::WrapOptional) {
Editor.insertAfterToken(Call->getSourceRange().End, "!");
}
}
// If a property has changed from nonnull to nullable, we should add ! to the
// reference of the property.
bool handlePropertyTypeChange(Expr *E) {
if (auto MRE = dyn_cast<MemberRefExpr>(E)) {
if (auto *VD = MRE->getMember().getDecl()) {
for (auto *I: getRelatedDiffItems(VD)) {
if (auto *Item = dyn_cast<CommonDiffItem>(I)) {
if (Item->DiffKind == NodeAnnotation::WrapOptional &&
Item->NodeKind == SDKNodeKind::DeclVar) {
Editor.insertAfterToken(E->getEndLoc(), "!");
return true;
}
}
}
}
}
return false;
}
bool walkToExprPre(Expr *E) override {
if (E->getSourceRange().isInvalid())
return false;
if (handleRevertRawRepresentable(E)) {
// The name may also change, so we should keep visiting.
return true;
}
if (handleQualifiedReplacement(E))
return false;
if (handleAssignDestMigration(E))
return false;
if (handleAttributeReference(E))
return false;
if (handlePropertyTypeChange(E))
return false;
if (auto *CE = dyn_cast<CallExpr>(E)) {
auto Fn = CE->getFn();
auto Args = CE->getArgs();
if (auto *DRE = dyn_cast<DeclRefExpr>(Fn)) {
if (auto *VD = DRE->getDecl()) {
if (VD->getNumCurryLevels() == 1) {
handleFuncRename(VD, Fn, Args);
handleTypeHoist(VD, CE, Args);
handleSpecialCases(VD, CE, Args);
handleStringRepresentableArg(VD, Args, CE);
handleResultTypeChange(VD, CE);
}
}
}
if (auto *SelfApply = dyn_cast<ApplyExpr>(Fn)) {
if (auto VD = SelfApply->getFn()->getReferencedDecl().getDecl()) {
if (VD->getNumCurryLevels() == 2) {
handleFuncRename(VD, SelfApply->getFn(), Args);
handleFunctionCallToPropertyChange(VD, SelfApply->getFn(), Args);
handleSpecialCases(VD, CE, Args);
handleStringRepresentableArg(VD, Args, CE);
handleResultTypeChange(VD, CE);
}
}
}
}
return true;
}
static void collectParameters(AbstractFunctionDecl *AFD,
SmallVectorImpl<ParamDecl*> &Results) {
for (auto PD : *AFD->getParameters()) {
Results.push_back(PD);
}
}
void handleFuncDeclRename(AbstractFunctionDecl *AFD,
CharSourceRange NameRange) {
bool IgnoreBase = false;
llvm::SmallString<32> Buffer;
if (auto View = getFuncRename(AFD, Buffer, IgnoreBase)) {
if (!IgnoreBase)
Editor.replace(NameRange, View.base());
unsigned Index = 0;
SmallVector<ParamDecl*, 4> Params;
collectParameters(AFD, Params);
for (auto *PD: Params) {
if (Index == View.argSize())
break;
StringRef NewArg = View.args()[Index++];
auto ArgLoc = PD->getArgumentNameLoc();
// Represent empty label with underscore.
if (NewArg.empty())
NewArg = "_";
// If the argument name is not specified, add the argument name before
// the parameter name.
if (ArgLoc.isInvalid())
Editor.insertBefore(PD->getNameLoc(),
(llvm::Twine(NewArg) + " ").str());
else {
// Otherwise, replace the argument name directly.
Editor.replaceToken(ArgLoc, NewArg);
}
}
}
}
bool typeReplacementMayNeedParens(StringRef Replacement) const {
return Replacement.contains('&') || Replacement.contains("->");
}
void handleOverridingTypeChange(AbstractFunctionDecl *AFD,
CommonDiffItem *DiffItem) {
assert(AFD);
assert(DiffItem->isTypeChange());
ChildIndexFinder Finder(DiffItem->getChildIndices());
auto Result = Finder.findChild(AFD);
if (!Result.isValid())
return;
switch (DiffItem->DiffKind) {
case ide::api::NodeAnnotation::WrapOptional:
if (Result.Suffixable) {
Editor.insertAfterToken(Result.TokenRange.End, "?");
} else {
Editor.insertWrap("(", Result.TokenRange, ")?");
}
break;
case ide::api::NodeAnnotation::WrapImplicitOptional:
if (Result.Suffixable) {
Editor.insertAfterToken(Result.TokenRange.End, "!");
} else {
Editor.insertWrap("(", Result.TokenRange, (")!"));
}
break;
case ide::api::NodeAnnotation::UnwrapOptional:
if (Result.Optional)
Editor.remove(Result.TokenRange.End);
break;
case ide::api::NodeAnnotation::ImplicitOptionalToOptional:
if (Result.Optional)
Editor.replace(Result.TokenRange.End, "?");
break;
case ide::api::NodeAnnotation::TypeRewritten:
Editor.replace(Result.TokenRange, DiffItem->RightComment);
if (Result.Suffixed && typeReplacementMayNeedParens(DiffItem->RightComment)) {
Editor.insertBefore(Result.TokenRange.Start, "(");
Editor.insertAfterToken(Result.TokenRange.End, ")");
}
break;
default:
break;
}
}
void handleOverridingPropertyChange(AbstractFunctionDecl *AFD,
CommonDiffItem *DiffItem) {
assert(AFD);
assert(DiffItem->isToPropertyChange());
auto FD = dyn_cast<FuncDecl>(AFD);
if (!FD)
return;
switch (DiffItem->DiffKind) {
case NodeAnnotation::GetterToProperty: {
auto FuncLoc = FD->getFuncLoc();
auto ReturnTyLoc = FD->getResultTypeSourceRange().Start;
auto NameLoc = FD->getNameLoc();
if (FuncLoc.isInvalid() || ReturnTyLoc.isInvalid() || NameLoc.isInvalid())
break;
// Replace "func" with "var"
Editor.replaceToken(FuncLoc, "var");
// Replace "() -> " with ": "
Editor.replace(CharSourceRange(SM, Lexer::getLocForEndOfToken(SM, NameLoc),
ReturnTyLoc), ": ");
break;
}
case NodeAnnotation::SetterToProperty: {
// FIXME: we should migrate this case too.
break;
}
default:
llvm_unreachable("should not be handled here.");
}
}
// When users override a SDK function whose parameter types have been changed,
// we should introduce a local variable in the body of the function definition
// to shadow the changed parameter. Also, a proper conversion function should
// be defined to bridge the parameter to the local variable.
void handleLocalParameterBridge(AbstractFunctionDecl *AFD,
CommonDiffItem *DiffItem) {
assert(AFD);
assert(DiffItem->isStringRepresentableChange());
// We only handle top-level parameter type change.
if (DiffItem->getChildIndices().size() != 1)
return;
auto Idx = DiffItem->getChildIndices().front();
// We don't handle return type change.
if (Idx == 0)
return;
Idx --;
SmallVector<ParamDecl*, 4> Params;
collectParameters(AFD, Params);
if (Params.size() <= Idx)
return;
// Get the internal name of the changed parameter.
auto VariableName = Params[Idx]->getParameterName().str();
// Insert the helper function to convert the type back to raw types.
auto &Info = insertHelperFunction(DiffItem->DiffKind, DiffItem->LeftComment,
DiffItem->RightComment, /*From String*/false,
/*No expression to wrap*/nullptr);
auto BL = AFD->getBodySourceRange().Start;
if (BL.isValid()) {
// Insert the local variable declaration after the opening brace.
Editor.insertAfterToken(BL,
(llvm::Twine("\n// Local variable inserted by Swift 4.2 migrator.") +
"\nlet " + VariableName + " = " + Info.getFuncName() + "(" +
VariableName + ")\n").str());
}
}
llvm::StringSet<> funcNamesForOverrideRemoval() {
llvm::StringSet<> Results;
Results.insert("c:objc(cs)NSObject(im)application:delegateHandlesKey:");
Results.insert("c:objc(cs)NSObject(im)changeColor:");
Results.insert("c:objc(cs)NSObject(im)controlTextDidBeginEditing:");
Results.insert("c:objc(cs)NSObject(im)controlTextDidEndEditing:");
Results.insert("c:objc(cs)NSObject(im)controlTextDidChange:");
Results.insert("c:objc(cs)NSObject(im)changeFont:");
Results.insert("c:objc(cs)NSObject(im)validModesForFontPanel:");
Results.insert("c:objc(cs)NSObject(im)discardEditing");
Results.insert("c:objc(cs)NSObject(im)commitEditing");
Results.insert("c:objc(cs)NSObject(im)commitEditingWithDelegate:didCommitSelector:contextInfo:");
Results.insert("c:objc(cs)NSObject(im)commitEditingAndReturnError:");
Results.insert("c:objc(cs)NSObject(im)objectDidBeginEditing:");
Results.insert("c:objc(cs)NSObject(im)objectDidEndEditing:");
Results.insert("c:objc(cs)NSObject(im)validateMenuItem:");
Results.insert("c:objc(cs)NSObject(im)pasteboard:provideDataForType:");
Results.insert("c:objc(cs)NSObject(im)pasteboardChangedOwner:");
Results.insert("c:objc(cs)NSObject(im)validateToolbarItem:");
Results.insert("c:objc(cs)NSObject(im)layer:shouldInheritContentsScale:fromWindow:");
Results.insert("c:objc(cs)NSObject(im)view:stringForToolTip:point:userData:");
return Results;
}
SourceLoc shouldRemoveOverride(AbstractFunctionDecl *AFD) {
if (AFD->getKind() != DeclKind::Func)
return SourceLoc();
SourceLoc OverrideLoc;
// Get the location of override keyword.
if (auto *Override = AFD->getAttrs().getAttribute<OverrideAttr>()) {
if (Override->getRange().isValid()) {
OverrideLoc = Override->getLocation();
}
}
if (OverrideLoc.isInvalid())
return SourceLoc();
auto *OD = AFD->getOverriddenDecl();
llvm::SmallString<64> Buffer;
llvm::raw_svector_ostream OS(Buffer);
if (swift::ide::printValueDeclUSR(OD, OS))
return SourceLoc();
return OverridingRemoveNames.contains(OS.str()) ? OverrideLoc : SourceLoc();
}
struct SuperRemoval: public ASTWalker {
EditorAdapter &Editor;
llvm::StringSet<> &USRs;
SuperRemoval(EditorAdapter &Editor, llvm::StringSet<> &USRs):
Editor(Editor), USRs(USRs) {}
/// Walk everything in a macro.
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
}
bool isSuperExpr(Expr *E) {
if (E->isImplicit())
return false;
// Check if the expression is super.foo().
if (auto *CE = dyn_cast<CallExpr>(E)) {
if (auto *DSC = dyn_cast<DotSyntaxCallExpr>(CE->getFn())) {
if (!isa<SuperRefExpr>(DSC->getBase()))
return false;
llvm::SmallString<64> Buffer;
llvm::raw_svector_ostream OS(Buffer);
auto *RD = DSC->getFn()->getReferencedDecl().getDecl();
if (swift::ide::printValueDeclUSR(RD, OS))
return false;
return USRs.contains(OS.str());
}
}
// We should handle try super.foo() too.
if (auto *TE = dyn_cast<AnyTryExpr>(E)) {
return isSuperExpr(TE->getSubExpr());
}
return false;
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
if (auto *BS = dyn_cast<BraceStmt>(S)) {
for(auto Ele: BS->getElements()) {
if (isa<Expr *>(Ele) && isSuperExpr(cast<Expr *>(Ele))) {
Editor.remove(Ele.getSourceRange());
}
}
}
// We only handle top-level expressions, so avoid visiting further.
return Action::SkipNode(S);
}
};
bool walkToDeclPre(Decl *D, CharSourceRange Range) override {
if (D->isImplicit())
return true;
if (auto *AFD = dyn_cast<AbstractFunctionDecl>(D)) {
handleFuncDeclRename(AFD, Range);
for (auto *Item: getRelatedDiffItems(AFD)) {
if (auto *DiffItem = dyn_cast<CommonDiffItem>(Item)) {
if (DiffItem->isTypeChange())
handleOverridingTypeChange(AFD, DiffItem);
else if (DiffItem->isToPropertyChange())
handleOverridingPropertyChange(AFD, DiffItem);
else if (DiffItem->isStringRepresentableChange())
handleLocalParameterBridge(AFD, DiffItem);
}
}
auto OverrideLoc = shouldRemoveOverride(AFD);
if (OverrideLoc.isValid()) {
// Remove override keyword.
Editor.remove(OverrideLoc);
// Remove super-dot call.
SuperRemoval Removal(Editor, OverridingRemoveNames);
D->walk(Removal);
}
}
// Handle property overriding migration.
if (auto *VD = dyn_cast<VarDecl>(D)) {
for (auto *Item: getRelatedDiffItems(VD)) {
if (auto *CD = dyn_cast<CommonDiffItem>(Item)) {
// If the overridden property has been renamed, we should rename
// this property decl as well.
if (CD->isRename() && VD->getNameLoc().isValid()) {
Editor.replaceToken(VD->getNameLoc(), CD->getNewName());
}
}
}
}
return true;
}
};
} // end anonymous namespace
void migrator::runAPIDiffMigratorPass(EditorAdapter &Editor,
SourceFile *SF,
const MigratorOptions &Opts) {
APIDiffMigratorPass { Editor, SF, Opts }.run();
} | cpp | github | https://github.com/apple/swift | lib/Migrator/APIDiffMigratorPass.cpp |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""GTFlow Model definitions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
from tensorflow.contrib import learn
from tensorflow.contrib.boosted_trees.estimator_batch import estimator_utils
from tensorflow.contrib.boosted_trees.estimator_batch import trainer_hooks
from tensorflow.contrib.boosted_trees.python.ops import model_ops
from tensorflow.contrib.boosted_trees.python.training.functions import gbdt_batch
from tensorflow.python.framework import ops
from tensorflow.python.ops import state_ops
from tensorflow.python.training import training_util
class ModelBuilderOutputType(object):
MODEL_FN_OPS = 0
ESTIMATOR_SPEC = 1
def model_builder(features,
labels,
mode,
params,
config,
output_type=ModelBuilderOutputType.MODEL_FN_OPS):
"""Multi-machine batch gradient descent tree model.
Args:
features: `Tensor` or `dict` of `Tensor` objects.
labels: Labels used to train on.
mode: Mode we are in. (TRAIN/EVAL/INFER)
params: A dict of hyperparameters.
The following hyperparameters are expected:
* head: A `Head` instance.
* learner_config: A config for the learner.
* feature_columns: An iterable containing all the feature columns used by
the model.
* examples_per_layer: Number of examples to accumulate before growing a
layer. It can also be a function that computes the number of examples
based on the depth of the layer that's being built.
* weight_column_name: The name of weight column.
* center_bias: Whether a separate tree should be created for first fitting
the bias.
config: `RunConfig` of the estimator.
Returns:
A `ModelFnOps` object.
Raises:
ValueError: if inputs are not valid.
"""
head = params["head"]
learner_config = params["learner_config"]
examples_per_layer = params["examples_per_layer"]
feature_columns = params["feature_columns"]
weight_column_name = params["weight_column_name"]
num_trees = params["num_trees"]
use_core_libs = params["use_core_libs"]
logits_modifier_function = params["logits_modifier_function"]
output_leaf_index = params["output_leaf_index"]
if features is None:
raise ValueError("At least one feature must be specified.")
if config is None:
raise ValueError("Missing estimator RunConfig.")
center_bias = params["center_bias"]
if isinstance(features, ops.Tensor):
features = {features.name: features}
# Make a shallow copy of features to ensure downstream usage
# is unaffected by modifications in the model function.
training_features = copy.copy(features)
training_features.pop(weight_column_name, None)
global_step = training_util.get_global_step()
with ops.device(global_step.device):
ensemble_handle = model_ops.tree_ensemble_variable(
stamp_token=0,
tree_ensemble_config="", # Initialize an empty ensemble.
name="ensemble_model")
# Create GBDT model.
gbdt_model = gbdt_batch.GradientBoostedDecisionTreeModel(
is_chief=config.is_chief,
num_ps_replicas=config.num_ps_replicas,
ensemble_handle=ensemble_handle,
center_bias=center_bias,
examples_per_layer=examples_per_layer,
learner_config=learner_config,
feature_columns=feature_columns,
logits_dimension=head.logits_dimension,
features=training_features,
use_core_columns=use_core_libs,
output_leaf_index=output_leaf_index)
with ops.name_scope("gbdt", "gbdt_optimizer"):
predictions_dict = gbdt_model.predict(mode)
logits = predictions_dict["predictions"]
if logits_modifier_function:
logits = logits_modifier_function(logits, features, mode)
def _train_op_fn(loss):
"""Returns the op to optimize the loss."""
update_op = gbdt_model.train(loss, predictions_dict, labels)
with ops.control_dependencies(
[update_op]), (ops.colocate_with(global_step)):
update_op = state_ops.assign_add(global_step, 1).op
return update_op
create_estimator_spec_op = getattr(head, "create_estimator_spec", None)
if num_trees:
if center_bias:
num_trees += 1
finalized_trees, attempted_trees = gbdt_model.get_number_of_trees_tensor()
training_hooks = [
trainer_hooks.StopAfterNTrees(num_trees, attempted_trees,
finalized_trees)
]
if output_type == ModelBuilderOutputType.MODEL_FN_OPS:
if use_core_libs and callable(create_estimator_spec_op):
model_fn_ops = head.create_estimator_spec(
features=features,
mode=mode,
labels=labels,
train_op_fn=_train_op_fn,
logits=logits)
model_fn_ops = estimator_utils.estimator_spec_to_model_fn_ops(
model_fn_ops)
else:
model_fn_ops = head.create_model_fn_ops(
features=features,
mode=mode,
labels=labels,
train_op_fn=_train_op_fn,
logits=logits)
if output_leaf_index and gbdt_batch.LEAF_INDEX in predictions_dict:
model_fn_ops.predictions[gbdt_batch.LEAF_INDEX] = predictions_dict[
gbdt_batch.LEAF_INDEX]
model_fn_ops.training_hooks.extend(training_hooks)
return model_fn_ops
elif output_type == ModelBuilderOutputType.ESTIMATOR_SPEC:
assert callable(create_estimator_spec_op)
estimator_spec = head.create_estimator_spec(
features=features,
mode=mode,
labels=labels,
train_op_fn=_train_op_fn,
logits=logits)
estimator_spec = estimator_spec._replace(
training_hooks=training_hooks + list(estimator_spec.training_hooks))
return estimator_spec
return model_fn_ops
def ranking_model_builder(features, labels, mode, params, config):
"""Multi-machine batch gradient descent tree model for ranking.
Args:
features: `Tensor` or `dict` of `Tensor` objects.
labels: Labels used to train on.
mode: Mode we are in. (TRAIN/EVAL/INFER)
params: A dict of hyperparameters.
The following hyperparameters are expected:
* head: A `Head` instance.
* learner_config: A config for the learner.
* feature_columns: An iterable containing all the feature columns used by
the model.
* examples_per_layer: Number of examples to accumulate before growing a
layer. It can also be a function that computes the number of examples
based on the depth of the layer that's being built.
* weight_column_name: The name of weight column.
* center_bias: Whether a separate tree should be created for first fitting
the bias.
* ranking_model_pair_keys (Optional): Keys to distinguish between features
for left and right part of the training pairs for ranking. For example,
for an Example with features "a.f1" and "b.f1", the keys would be
("a", "b").
config: `RunConfig` of the estimator.
Returns:
A `ModelFnOps` object.
Raises:
ValueError: if inputs are not valid.
"""
head = params["head"]
learner_config = params["learner_config"]
examples_per_layer = params["examples_per_layer"]
feature_columns = params["feature_columns"]
weight_column_name = params["weight_column_name"]
num_trees = params["num_trees"]
use_core_libs = params["use_core_libs"]
logits_modifier_function = params["logits_modifier_function"]
output_leaf_index = params["output_leaf_index"]
ranking_model_pair_keys = params["ranking_model_pair_keys"]
if features is None:
raise ValueError("At least one feature must be specified.")
if config is None:
raise ValueError("Missing estimator RunConfig.")
center_bias = params["center_bias"]
if isinstance(features, ops.Tensor):
features = {features.name: features}
# Make a shallow copy of features to ensure downstream usage
# is unaffected by modifications in the model function.
training_features = copy.copy(features)
training_features.pop(weight_column_name, None)
global_step = training_util.get_global_step()
with ops.device(global_step.device):
ensemble_handle = model_ops.tree_ensemble_variable(
stamp_token=0,
tree_ensemble_config="", # Initialize an empty ensemble.
name="ensemble_model")
# Extract the features.
if mode == learn.ModeKeys.TRAIN or mode == learn.ModeKeys.EVAL:
# For ranking pairwise training, we extract two sets of features.
if len(ranking_model_pair_keys) != 2:
raise ValueError("You must provide keys for ranking.")
left_pair_key = ranking_model_pair_keys[0]
right_pair_key = ranking_model_pair_keys[1]
if left_pair_key is None or right_pair_key is None:
raise ValueError("Both pair keys should be provided for ranking.")
features_1 = {}
features_2 = {}
for name in training_features:
feature = training_features[name]
new_name = name[2:]
if name.startswith(left_pair_key + "."):
features_1[new_name] = feature
else:
assert name.startswith(right_pair_key + ".")
features_2[new_name] = feature
main_features = features_1
supplementary_features = features_2
else:
# For non-ranking or inference ranking, we have only 1 set of features.
main_features = training_features
# Create GBDT model.
gbdt_model_main = gbdt_batch.GradientBoostedDecisionTreeModel(
is_chief=config.is_chief,
num_ps_replicas=config.num_ps_replicas,
ensemble_handle=ensemble_handle,
center_bias=center_bias,
examples_per_layer=examples_per_layer,
learner_config=learner_config,
feature_columns=feature_columns,
logits_dimension=head.logits_dimension,
features=main_features,
use_core_columns=use_core_libs,
output_leaf_index=output_leaf_index)
with ops.name_scope("gbdt", "gbdt_optimizer"):
# Logits for inference.
if mode == learn.ModeKeys.INFER:
predictions_dict = gbdt_model_main.predict(mode)
logits = predictions_dict[gbdt_batch.PREDICTIONS]
if logits_modifier_function:
logits = logits_modifier_function(logits, features, mode)
else:
gbdt_model_supplementary = gbdt_batch.GradientBoostedDecisionTreeModel(
is_chief=config.is_chief,
num_ps_replicas=config.num_ps_replicas,
ensemble_handle=ensemble_handle,
center_bias=center_bias,
examples_per_layer=examples_per_layer,
learner_config=learner_config,
feature_columns=feature_columns,
logits_dimension=head.logits_dimension,
features=supplementary_features,
use_core_columns=use_core_libs,
output_leaf_index=output_leaf_index)
# Logits for train and eval.
if not supplementary_features:
raise ValueError("Features for ranking must be specified.")
predictions_dict_1 = gbdt_model_main.predict(mode)
predictions_1 = predictions_dict_1[gbdt_batch.PREDICTIONS]
predictions_dict_2 = gbdt_model_supplementary.predict(mode)
predictions_2 = predictions_dict_2[gbdt_batch.PREDICTIONS]
logits = predictions_1 - predictions_2
if logits_modifier_function:
logits = logits_modifier_function(logits, features, mode)
predictions_dict = predictions_dict_1
predictions_dict[gbdt_batch.PREDICTIONS] = logits
def _train_op_fn(loss):
"""Returns the op to optimize the loss."""
update_op = gbdt_model_main.train(loss, predictions_dict, labels)
with ops.control_dependencies(
[update_op]), (ops.colocate_with(global_step)):
update_op = state_ops.assign_add(global_step, 1).op
return update_op
create_estimator_spec_op = getattr(head, "create_estimator_spec", None)
if use_core_libs and callable(create_estimator_spec_op):
model_fn_ops = head.create_estimator_spec(
features=features,
mode=mode,
labels=labels,
train_op_fn=_train_op_fn,
logits=logits)
model_fn_ops = estimator_utils.estimator_spec_to_model_fn_ops(model_fn_ops)
else:
model_fn_ops = head.create_model_fn_ops(
features=features,
mode=mode,
labels=labels,
train_op_fn=_train_op_fn,
logits=logits)
if output_leaf_index and gbdt_batch.LEAF_INDEX in predictions_dict:
model_fn_ops.predictions[gbdt_batch.LEAF_INDEX] = predictions_dict[
gbdt_batch.LEAF_INDEX]
if num_trees:
if center_bias:
num_trees += 1
finalized_trees, attempted_trees = (
gbdt_model_main.get_number_of_trees_tensor())
model_fn_ops.training_hooks.append(
trainer_hooks.StopAfterNTrees(num_trees, attempted_trees,
finalized_trees))
return model_fn_ops | unknown | codeparrot/codeparrot-clean | ||
# This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
import sys
import os
import shutil
import inspect
import tempfile
import subprocess
from contextlib import contextmanager
from functools import wraps
import numpy as np
import h5py
import unittest as ut
# Check if non-ascii filenames are supported
# Evidently this is the most reliable way to check
# See also h5py issue #263 and ipython #466
# To test for this, run the testsuite with LC_ALL=C
try:
testfile, fname = tempfile.mkstemp(chr(0x03b7))
except UnicodeError:
UNICODE_FILENAMES = False
else:
UNICODE_FILENAMES = True
os.close(testfile)
os.unlink(fname)
del fname
del testfile
class TestCase(ut.TestCase):
"""
Base class for unit tests.
"""
@classmethod
def setUpClass(cls):
cls.tempdir = tempfile.mkdtemp(prefix='h5py-test_')
@classmethod
def tearDownClass(cls):
shutil.rmtree(cls.tempdir)
def mktemp(self, suffix='.hdf5', prefix='', dir=None):
if dir is None:
dir = self.tempdir
return tempfile.mktemp(suffix, prefix, dir=dir)
def mktemp_mpi(self, comm=None, suffix='.hdf5', prefix='', dir=None):
if comm is None:
from mpi4py import MPI
comm = MPI.COMM_WORLD
fname = None
if comm.Get_rank() == 0:
fname = self.mktemp(suffix, prefix, dir)
fname = comm.bcast(fname, 0)
return fname
def setUp(self):
self.f = h5py.File(self.mktemp(), 'w')
def tearDown(self):
try:
if self.f:
self.f.close()
except:
pass
def assertSameElements(self, a, b):
for x in a:
match = False
for y in b:
if x == y:
match = True
if not match:
raise AssertionError("Item '%s' appears in a but not b" % x)
for x in b:
match = False
for y in a:
if x == y:
match = True
if not match:
raise AssertionError("Item '%s' appears in b but not a" % x)
def assertArrayEqual(self, dset, arr, message=None, precision=None):
""" Make sure dset and arr have the same shape, dtype and contents, to
within the given precision.
Note that dset may be a NumPy array or an HDF5 dataset.
"""
if precision is None:
precision = 1e-5
if message is None:
message = ''
else:
message = ' (%s)' % message
if np.isscalar(dset) or np.isscalar(arr):
assert np.isscalar(dset) and np.isscalar(arr), \
'Scalar/array mismatch ("%r" vs "%r")%s' % (dset, arr, message)
assert dset - arr < precision, \
"Scalars differ by more than %.3f%s" % (precision, message)
return
assert dset.shape == arr.shape, \
"Shape mismatch (%s vs %s)%s" % (dset.shape, arr.shape, message)
assert dset.dtype == arr.dtype, \
"Dtype mismatch (%s vs %s)%s" % (dset.dtype, arr.dtype, message)
if arr.dtype.names is not None:
for n in arr.dtype.names:
message = '[FIELD %s] %s' % (n, message)
self.assertArrayEqual(dset[n], arr[n], message=message, precision=precision)
elif arr.dtype.kind in ('i', 'f'):
assert np.all(np.abs(dset[...] - arr[...]) < precision), \
"Arrays differ by more than %.3f%s" % (precision, message)
else:
assert np.all(dset[...] == arr[...]), \
"Arrays are not equal (dtype %s) %s" % (arr.dtype.str, message)
def assertNumpyBehavior(self, dset, arr, s):
""" Apply slicing arguments "s" to both dset and arr.
Succeeds if the results of the slicing are identical, or the
exception raised is of the same type for both.
"arr" must be a Numpy array; "dset" may be a NumPy array or dataset.
"""
exc = None
try:
arr_result = arr[s]
except Exception as e:
exc = type(e)
if exc is None:
self.assertArrayEqual(dset[s], arr_result)
else:
with self.assertRaises(exc):
dset[s]
NUMPY_RELEASE_VERSION = tuple([int(i) for i in np.__version__.split(".")[0:2]])
@contextmanager
def closed_tempfile(suffix='', text=None):
"""
Context manager which yields the path to a closed temporary file with the
suffix `suffix`. The file will be deleted on exiting the context. An
additional argument `text` can be provided to have the file contain `text`.
"""
with tempfile.NamedTemporaryFile(
'w+t', suffix=suffix, delete=False
) as test_file:
file_name = test_file.name
if text is not None:
test_file.write(text)
test_file.flush()
yield file_name
shutil.rmtree(file_name, ignore_errors=True)
def insubprocess(f):
"""Runs a test in its own subprocess"""
@wraps(f)
def wrapper(request, *args, **kwargs):
curr_test = inspect.getsourcefile(f) + "::" + request.node.name
# get block around test name
insub = "IN_SUBPROCESS_" + curr_test
for c in "/\\,:.":
insub = insub.replace(c, "_")
defined = os.environ.get(insub, None)
# fork process
if defined:
return f(request, *args, **kwargs)
else:
os.environ[insub] = '1'
env = os.environ.copy()
env[insub] = '1'
env.update(getattr(f, 'subproc_env', {}))
with closed_tempfile() as stdout:
with open(stdout, 'w+t') as fh:
rtn = subprocess.call([sys.executable, '-m', 'pytest', curr_test],
stdout=fh, stderr=fh, env=env)
with open(stdout, 'rt') as fh:
out = fh.read()
assert rtn == 0, "\n" + out
return wrapper
def subproc_env(d):
"""Set environment variables for the @insubprocess decorator"""
def decorator(f):
f.subproc_env = d
return f
return decorator | unknown | codeparrot/codeparrot-clean | ||
//
// Request+AlamofireTests.swift
//
// Copyright (c) 2022 Alamofire Software Foundation (http://alamofire.org/)
//
// 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 Alamofire
extension DataRequest {
/// Adds a validator which executes a closure before calling `validate()`.
///
/// - Parameter closure: Closure to perform before validation.
/// - Returns: The `DataRequest`.
func validate(performing closure: @escaping () -> Void) -> Self {
validate { _, _, _ in
closure()
return .success(())
}
.validate()
}
} | swift | github | https://github.com/Alamofire/Alamofire | Tests/Request+AlamofireTests.swift |
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
from models import DiscussionMarker
import re
from database import db_session
import sys
def main():
parser = argparse.ArgumentParser()
parser.add_argument('identifiers', type=str, nargs='*',
help='Disqus identifiers to create markers for')
args = parser.parse_args()
identifiers = args.identifiers if args.identifiers else sys.stdin
for identifier in identifiers:
m = re.match('\((\d+\.\d+),\s*(\d+\.\d+)\)', identifier)
if not m:
print("Failed processing: " + identifier)
continue
(latitude, longitude) = m.group(1, 2)
marker = DiscussionMarker.parse({
'latitude': latitude,
'longitude': longitude,
'title': identifier,
'identifier': identifier
})
try:
db_session.add(marker)
db_session.commit()
print("Added: " + identifier, end="")
except:
db_session.rollback()
print("Failed: " + identifier, end="")
if __name__ == "__main__":
main() | unknown | codeparrot/codeparrot-clean | ||
/*
Copyright 2014 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 types
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
v1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/apis/scheduling"
)
var (
systemPriority = scheduling.SystemCriticalPriority
systemPriorityUpper = systemPriority + 1000
)
// getTestPod generates a new instance of an empty test Pod
func getTestPod(annotations map[string]string, podPriority *int32, priorityClassName string) *v1.Pod {
pod := v1.Pod{
TypeMeta: metav1.TypeMeta{
Kind: "Pod",
APIVersion: "v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "default",
},
}
// Set pod Priority in Spec if exists
if podPriority != nil {
pod.Spec = v1.PodSpec{
Priority: podPriority,
}
}
pod.Spec.PriorityClassName = priorityClassName
// Set annotations if exists
if annotations != nil {
pod.Annotations = annotations
}
return &pod
}
func configSourceAnnotation(source string) map[string]string {
return map[string]string{ConfigSourceAnnotationKey: source}
}
func configMirrorAnnotation() map[string]string {
return map[string]string{ConfigMirrorAnnotationKey: "true"}
}
func TestGetValidatedSources(t *testing.T) {
tests := []struct {
name string
sources []string
errExpected bool
sourcesLen int
}{
{
name: "empty source",
sources: []string{""},
errExpected: false,
sourcesLen: 0,
},
{
name: "file and apiserver source",
sources: []string{FileSource, ApiserverSource},
errExpected: false,
sourcesLen: 2,
},
{
name: "all source",
sources: []string{AllSource},
errExpected: false,
sourcesLen: 3,
},
{
name: "unknown source",
sources: []string{"unknown"},
errExpected: true,
sourcesLen: 0,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
sources, err := GetValidatedSources(test.sources)
if test.errExpected {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
assert.Len(t, sources, test.sourcesLen)
})
}
}
func TestGetPodSource(t *testing.T) {
tests := []struct {
name string
pod *v1.Pod
expected string
errExpected bool
}{
{
name: "cannot get pod source",
pod: getTestPod(nil, nil, ""),
expected: "",
errExpected: true,
},
{
name: "valid annotation returns the source",
pod: getTestPod(configSourceAnnotation("host-ipc-sources"), nil, ""),
expected: "host-ipc-sources",
errExpected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
source, err := GetPodSource(test.pod)
if test.errExpected {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
assert.Equal(t, test.expected, source)
})
}
}
func TestString(t *testing.T) {
tests := []struct {
sp SyncPodType
expected string
}{
{
sp: SyncPodCreate,
expected: "create",
},
{
sp: SyncPodUpdate,
expected: "update",
},
{
sp: SyncPodSync,
expected: "sync",
},
{
sp: SyncPodKill,
expected: "kill",
},
{
sp: 50,
expected: "unknown",
},
}
for _, test := range tests {
t.Run(test.expected, func(t *testing.T) {
syncPodString := test.sp.String()
assert.Equal(t, test.expected, syncPodString)
})
}
}
func TestIsMirrorPod(t *testing.T) {
tests := []struct {
name string
pod *v1.Pod
expected bool
}{
{
name: "mirror pod",
pod: getTestPod(configMirrorAnnotation(), nil, ""),
expected: true,
},
{
name: "not a mirror pod",
pod: getTestPod(nil, nil, ""),
expected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
isMirrorPod := IsMirrorPod(test.pod)
assert.Equal(t, test.expected, isMirrorPod)
})
}
}
func TestIsStaticPod(t *testing.T) {
tests := []struct {
name string
pod *v1.Pod
expected bool
}{
{
name: "static pod with file source",
pod: getTestPod(configSourceAnnotation(FileSource), nil, ""),
expected: true,
},
{
name: "static pod with http source",
pod: getTestPod(configSourceAnnotation(HTTPSource), nil, ""),
expected: true,
},
{
name: "static pod with api server source",
pod: getTestPod(configSourceAnnotation(ApiserverSource), nil, ""),
expected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
isStaticPod := IsStaticPod(test.pod)
assert.Equal(t, test.expected, isStaticPod)
})
}
}
func TestIsCriticalPod(t *testing.T) {
tests := []struct {
name string
pod *v1.Pod
expected bool
}{
{
name: "critical pod with file source",
pod: getTestPod(configSourceAnnotation(FileSource), nil, ""),
expected: true,
},
{
name: "critical pod with mirror annotation",
pod: getTestPod(configMirrorAnnotation(), nil, ""),
expected: true,
},
{
name: "critical pod using system priority",
pod: getTestPod(nil, &systemPriority, ""),
expected: true,
},
{
name: "critical pod using greater than system priority",
pod: getTestPod(nil, &systemPriorityUpper, ""),
expected: true,
},
{
name: "not a critical pod with api server annotation",
pod: getTestPod(configSourceAnnotation(ApiserverSource), nil, ""),
expected: false,
},
{
name: "not critical if not static, mirror or without a priority",
pod: getTestPod(nil, nil, ""),
expected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
isCriticalPod := IsCriticalPod(test.pod)
assert.Equal(t, test.expected, isCriticalPod)
})
}
}
func TestPreemptable(t *testing.T) {
tests := []struct {
name string
preemptor *v1.Pod
preemptee *v1.Pod
expected bool
}{
{
name: "a critical preemptor pod preempts a non critical pod",
preemptor: getTestPod(configSourceAnnotation(FileSource), nil, ""),
preemptee: getTestPod(nil, nil, ""),
expected: true,
},
{
name: "a preemptor pod with higher priority preempts a critical pod",
preemptor: getTestPod(configSourceAnnotation(FileSource), &systemPriorityUpper, ""),
preemptee: getTestPod(configSourceAnnotation(FileSource), &systemPriority, ""),
expected: true,
},
{
name: "a not critical pod with higher priority preempts a critical pod",
preemptor: getTestPod(configSourceAnnotation(ApiserverSource), &systemPriorityUpper, ""),
preemptee: getTestPod(configSourceAnnotation(FileSource), &systemPriority, ""),
expected: true,
},
{
name: "a critical pod with less priority do not preempts a critical pod",
preemptor: getTestPod(configSourceAnnotation(FileSource), &systemPriority, ""),
preemptee: getTestPod(configSourceAnnotation(FileSource), &systemPriorityUpper, ""),
expected: false,
},
{
name: "a critical pod without priority do not preempts a critical pod without priority",
preemptor: getTestPod(configSourceAnnotation(FileSource), nil, ""),
preemptee: getTestPod(configSourceAnnotation(FileSource), nil, ""),
expected: false,
},
{
name: "a critical pod with priority do not preempts a critical pod with the same priority",
preemptor: getTestPod(configSourceAnnotation(FileSource), &systemPriority, ""),
preemptee: getTestPod(configSourceAnnotation(FileSource), &systemPriority, ""),
expected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
isPreemtable := Preemptable(test.preemptor, test.preemptee)
assert.Equal(t, test.expected, isPreemtable)
})
}
}
func TestIsCriticalPodBasedOnPriority(t *testing.T) {
tests := []struct {
priority int32
name string
expected bool
}{
{
name: "a system critical pod",
priority: systemPriority,
expected: true,
},
{
name: "a non system critical pod",
priority: scheduling.HighestUserDefinablePriority,
expected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
actual := IsCriticalPodBasedOnPriority(test.priority)
if actual != test.expected {
t.Errorf("IsCriticalPodBased on priority should have returned %v for test %v but got %v", test.expected, test.name, actual)
}
})
}
}
func TestIsNodeCriticalPod(t *testing.T) {
tests := []struct {
name string
pod *v1.Pod
expected bool
}{
{
name: "critical pod with file source and systemNodeCritical",
pod: getTestPod(configSourceAnnotation(FileSource), nil, scheduling.SystemNodeCritical),
expected: true,
},
{
name: "critical pod with mirror annotation and systemNodeCritical",
pod: getTestPod(configMirrorAnnotation(), nil, scheduling.SystemNodeCritical),
expected: true,
},
{
name: "critical pod using system priority and systemNodeCritical",
pod: getTestPod(nil, &systemPriority, scheduling.SystemNodeCritical),
expected: true,
},
{
name: "critical pod using greater than system priority and systemNodeCritical",
pod: getTestPod(nil, &systemPriorityUpper, scheduling.SystemNodeCritical),
expected: true,
},
{
name: "not a critical pod with api server annotation and systemNodeCritical",
pod: getTestPod(configSourceAnnotation(ApiserverSource), nil, scheduling.SystemNodeCritical),
expected: false,
},
{
name: "not critical if not static, mirror or without a priority and systemNodeCritical",
pod: getTestPod(nil, nil, scheduling.SystemNodeCritical),
expected: false,
},
{
name: "not critical if not static, mirror or without a priority",
pod: getTestPod(nil, nil, ""),
expected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
isNodeCriticalPod := IsNodeCriticalPod(test.pod)
require.Equal(t, test.expected, isNodeCriticalPod)
})
}
}
func TestHasRestartableInitContainer(t *testing.T) {
containerRestartPolicyAlways := v1.ContainerRestartPolicyAlways
tests := []struct {
name string
pod *v1.Pod
expected bool
}{
{
name: "pod without init containers",
pod: &v1.Pod{
Spec: v1.PodSpec{
Containers: []v1.Container{
{Name: "container1"},
},
},
},
expected: false,
},
{
name: "pod with regular init containers only",
pod: &v1.Pod{
Spec: v1.PodSpec{
InitContainers: []v1.Container{
{Name: "init1"},
{Name: "init2"},
},
Containers: []v1.Container{
{Name: "container1"},
},
},
},
expected: false,
},
{
name: "pod with one restartable init container",
pod: &v1.Pod{
Spec: v1.PodSpec{
InitContainers: []v1.Container{
{Name: "restartable-init", RestartPolicy: &containerRestartPolicyAlways},
},
Containers: []v1.Container{
{Name: "container1"},
},
},
},
expected: true,
},
{
name: "pod with mixed init containers (regular and restartable)",
pod: &v1.Pod{
Spec: v1.PodSpec{
InitContainers: []v1.Container{
{Name: "init1"},
{Name: "restartable-init", RestartPolicy: &containerRestartPolicyAlways},
{Name: "init2"},
},
Containers: []v1.Container{
{Name: "container1"},
},
},
},
expected: true,
},
{
name: "pod with multiple restartable init containers",
pod: &v1.Pod{
Spec: v1.PodSpec{
InitContainers: []v1.Container{
{Name: "restartable-init1", RestartPolicy: &containerRestartPolicyAlways},
{Name: "restartable-init2", RestartPolicy: &containerRestartPolicyAlways},
},
Containers: []v1.Container{
{Name: "container1"},
},
},
},
expected: true,
},
{
name: "pod with init container having nil restart policy",
pod: &v1.Pod{
Spec: v1.PodSpec{
InitContainers: []v1.Container{
{Name: "init1", RestartPolicy: nil},
},
Containers: []v1.Container{
{Name: "container1"},
},
},
},
expected: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
hasRestartableInitContainer := HasRestartableInitContainer(test.pod)
require.Equal(t, test.expected, hasRestartableInitContainer)
})
}
} | go | github | https://github.com/kubernetes/kubernetes | pkg/kubelet/types/pod_update_test.go |
import {mutate} from 'shared-runtime';
function component(a) {
let x = {a};
let y = {};
(function () {
let a = y;
a['x'] = x;
})();
mutate(y);
return y;
}
export const FIXTURE_ENTRYPOINT = {
fn: component,
params: ['foo'],
}; | javascript | github | https://github.com/facebook/react | compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/capturing-func-alias-receiver-computed-mutate-iife.js |
// Copyright 2019 The Go 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 runtime_test
import (
"fmt"
"internal/goos"
"internal/runtime/atomic"
"math"
"math/rand"
. "runtime"
"testing"
"time"
)
// makePallocData produces an initialized PallocData by setting
// the ranges of described in alloc and scavenge.
func makePallocData(alloc, scavenged []BitRange) *PallocData {
b := new(PallocData)
for _, v := range alloc {
if v.N == 0 {
// Skip N==0. It's harmless and allocRange doesn't
// handle this case.
continue
}
b.AllocRange(v.I, v.N)
}
for _, v := range scavenged {
if v.N == 0 {
// See the previous loop.
continue
}
b.ScavengedSetRange(v.I, v.N)
}
return b
}
func TestFillAligned(t *testing.T) {
fillAlignedSlow := func(x uint64, m uint) uint64 {
if m == 1 {
return x
}
out := uint64(0)
for i := uint(0); i < 64; i += m {
for j := uint(0); j < m; j++ {
if x&(uint64(1)<<(i+j)) != 0 {
out |= ((uint64(1) << m) - 1) << i
break
}
}
}
return out
}
check := func(x uint64, m uint) {
want := fillAlignedSlow(x, m)
if got := FillAligned(x, m); got != want {
t.Logf("got: %064b", got)
t.Logf("want: %064b", want)
t.Errorf("bad fillAligned(%016x, %d)", x, m)
}
}
for m := uint(1); m <= 64; m *= 2 {
tests := []uint64{
0x0000000000000000,
0x00000000ffffffff,
0xffffffff00000000,
0x8000000000000001,
0xf00000000000000f,
0xf00000010050000f,
0xffffffffffffffff,
0x0000000000000001,
0x0000000000000002,
0x0000000000000008,
uint64(1) << (m - 1),
uint64(1) << m,
// Try a few fixed arbitrary examples.
0xb02b9effcf137016,
0x3975a076a9fbff18,
0x0f8c88ec3b81506e,
0x60f14d80ef2fa0e6,
}
for _, test := range tests {
check(test, m)
}
for i := 0; i < 1000; i++ {
// Try a pseudo-random numbers.
check(rand.Uint64(), m)
if m > 1 {
// For m != 1, let's construct a slightly more interesting
// random test. Generate a bitmap which is either 0 or
// randomly set bits for each m-aligned group of m bits.
val := uint64(0)
for n := uint(0); n < 64; n += m {
// For each group of m bits, flip a coin:
// * Leave them as zero.
// * Set them randomly.
if rand.Uint64()%2 == 0 {
val |= (rand.Uint64() & ((1 << m) - 1)) << n
}
}
check(val, m)
}
}
}
}
func TestPallocDataFindScavengeCandidate(t *testing.T) {
type test struct {
alloc, scavenged []BitRange
min, max uintptr
want BitRange
}
tests := map[string]test{
"MixedMin1": {
alloc: []BitRange{{0, 40}, {42, PallocChunkPages - 42}},
scavenged: []BitRange{{0, 41}, {42, PallocChunkPages - 42}},
min: 1,
max: PallocChunkPages,
want: BitRange{41, 1},
},
}
if PallocChunkPages >= 512 {
// avoid constant overflow when PallocChunkPages is small
var pallocChunkPages uint = PallocChunkPages
tests["MultiMin1"] = test{
alloc: []BitRange{{0, 63}, {65, 20}, {87, pallocChunkPages - 87}},
scavenged: []BitRange{{86, 1}},
min: 1,
max: PallocChunkPages,
want: BitRange{85, 1},
}
}
// Try out different page minimums.
for m := uintptr(1); m <= 64; m *= 2 {
suffix := fmt.Sprintf("Min%d", m)
tests["AllFree"+suffix] = test{
min: m,
max: PallocChunkPages,
want: BitRange{0, PallocChunkPages},
}
tests["AllScavenged"+suffix] = test{
scavenged: []BitRange{{0, PallocChunkPages}},
min: m,
max: PallocChunkPages,
want: BitRange{0, 0},
}
tests["NoneFree"+suffix] = test{
alloc: []BitRange{{0, PallocChunkPages}},
scavenged: []BitRange{{PallocChunkPages / 2, PallocChunkPages / 2}},
min: m,
max: PallocChunkPages,
want: BitRange{0, 0},
}
tests["StartFree"+suffix] = test{
alloc: []BitRange{{uint(m), PallocChunkPages - uint(m)}},
min: m,
max: PallocChunkPages,
want: BitRange{0, uint(m)},
}
tests["EndFree"+suffix] = test{
alloc: []BitRange{{0, PallocChunkPages - uint(m)}},
min: m,
max: PallocChunkPages,
want: BitRange{PallocChunkPages - uint(m), uint(m)},
}
if PallocChunkPages >= 512 {
tests["Straddle64"+suffix] = test{
alloc: []BitRange{{0, 64 - uint(m)}, {64 + uint(m), PallocChunkPages - (64 + uint(m))}},
min: m,
max: 2 * m,
want: BitRange{64 - uint(m), 2 * uint(m)},
}
tests["BottomEdge64WithFull"+suffix] = test{
alloc: []BitRange{{64, 64}, {128 + 3*uint(m), PallocChunkPages - (128 + 3*uint(m))}},
scavenged: []BitRange{{1, 10}},
min: m,
max: 3 * m,
want: BitRange{128, 3 * uint(m)},
}
tests["BottomEdge64WithPocket"+suffix] = test{
alloc: []BitRange{{64, 62}, {127, 1}, {128 + 3*uint(m), PallocChunkPages - (128 + 3*uint(m))}},
scavenged: []BitRange{{1, 10}},
min: m,
max: 3 * m,
want: BitRange{128, 3 * uint(m)},
}
}
tests["Max0"+suffix] = test{
scavenged: []BitRange{{0, PallocChunkPages - uint(m)}},
min: m,
max: 0,
want: BitRange{PallocChunkPages - uint(m), uint(m)},
}
if m <= 8 {
tests["OneFree"] = test{
alloc: []BitRange{{0, 40}, {40 + uint(m), PallocChunkPages - (40 + uint(m))}},
min: m,
max: PallocChunkPages,
want: BitRange{40, uint(m)},
}
tests["OneScavenged"] = test{
alloc: []BitRange{{0, 40}, {40 + uint(m), PallocChunkPages - (40 + uint(m))}},
scavenged: []BitRange{{40, 1}},
min: m,
max: PallocChunkPages,
want: BitRange{0, 0},
}
}
if m > 1 {
if PallocChunkPages >= m*2 {
tests["MaxUnaligned"+suffix] = test{
scavenged: []BitRange{{0, PallocChunkPages - uint(m*2-1)}},
min: m,
max: m - 2,
want: BitRange{PallocChunkPages - uint(m), uint(m)},
}
}
if PallocChunkPages >= 512 {
// avoid constant overflow when PallocChunkPages is small
var PallocChunkPages uint = PallocChunkPages
tests["SkipSmall"+suffix] = test{
alloc: []BitRange{{0, 64 - uint(m)}, {64, 5}, {70, 11}, {82, PallocChunkPages - 82}},
min: m,
max: m,
want: BitRange{64 - uint(m), uint(m)},
}
tests["SkipMisaligned"+suffix] = test{
alloc: []BitRange{{0, 64 - uint(m)}, {64, 63}, {127 + uint(m), PallocChunkPages - (127 + uint(m))}},
min: m,
max: m,
want: BitRange{64 - uint(m), uint(m)},
}
}
tests["MaxLessThan"+suffix] = test{
scavenged: []BitRange{{0, PallocChunkPages - uint(m)}},
min: m,
max: 1,
want: BitRange{PallocChunkPages - uint(m), uint(m)},
}
}
}
if PhysHugePageSize > uintptr(PageSize) {
// Check hugepage preserving behavior.
bits := uint(PhysHugePageSize / uintptr(PageSize))
if bits < PallocChunkPages {
tests["PreserveHugePageBottom"] = test{
alloc: []BitRange{{bits + 2, PallocChunkPages - (bits + 2)}},
min: 1,
max: 3, // Make it so that max would have us try to break the huge page.
want: BitRange{0, bits + 2},
}
if 3*bits < PallocChunkPages {
// We need at least 3 huge pages in a chunk for this test to make sense.
tests["PreserveHugePageMiddle"] = test{
alloc: []BitRange{{0, bits - 10}, {2*bits + 10, PallocChunkPages - (2*bits + 10)}},
min: 1,
max: 12, // Make it so that max would have us try to break the huge page.
want: BitRange{bits, bits + 10},
}
}
tests["PreserveHugePageTop"] = test{
alloc: []BitRange{{0, PallocChunkPages - bits}},
min: 1,
max: 1, // Even one page would break a huge page in this case.
want: BitRange{PallocChunkPages - bits, bits},
}
} else if bits == PallocChunkPages {
tests["PreserveHugePageAll"] = test{
min: 1,
max: 1, // Even one page would break a huge page in this case.
want: BitRange{0, PallocChunkPages},
}
} else {
// The huge page size is greater than pallocChunkPages, so it should
// be effectively disabled. There's no way we can possible scavenge
// a huge page out of this bitmap chunk.
tests["PreserveHugePageNone"] = test{
min: 1,
max: 1,
want: BitRange{PallocChunkPages - 1, 1},
}
}
}
for name, v := range tests {
t.Run(name, func(t *testing.T) {
b := makePallocData(v.alloc, v.scavenged)
start, size := b.FindScavengeCandidate(PallocChunkPages-1, v.min, v.max)
got := BitRange{start, size}
if !(got.N == 0 && v.want.N == 0) && got != v.want {
t.Fatalf("candidate mismatch: got %v, want %v", got, v.want)
}
})
}
}
// Tests end-to-end scavenging on a pageAlloc.
func TestPageAllocScavenge(t *testing.T) {
if GOOS == "openbsd" && testing.Short() {
t.Skip("skipping because virtual memory is limited; see #36210")
}
type test struct {
request, expect uintptr
}
minPages := PhysPageSize / PageSize
if minPages < 1 {
minPages = 1
}
type setup struct {
beforeAlloc map[ChunkIdx][]BitRange
beforeScav map[ChunkIdx][]BitRange
expect []test
afterScav map[ChunkIdx][]BitRange
}
tests := map[string]setup{
"AllFreeUnscavExhaust": {
beforeAlloc: map[ChunkIdx][]BitRange{
BaseChunkIdx: {},
BaseChunkIdx + 1: {},
BaseChunkIdx + 2: {},
},
beforeScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {},
BaseChunkIdx + 1: {},
BaseChunkIdx + 2: {},
},
expect: []test{
{^uintptr(0), 3 * PallocChunkPages * PageSize},
},
afterScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {{0, PallocChunkPages}},
BaseChunkIdx + 1: {{0, PallocChunkPages}},
BaseChunkIdx + 2: {{0, PallocChunkPages}},
},
},
"NoneFreeUnscavExhaust": {
beforeAlloc: map[ChunkIdx][]BitRange{
BaseChunkIdx: {{0, PallocChunkPages}},
BaseChunkIdx + 1: {},
BaseChunkIdx + 2: {{0, PallocChunkPages}},
},
beforeScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {},
BaseChunkIdx + 1: {{0, PallocChunkPages}},
BaseChunkIdx + 2: {},
},
expect: []test{
{^uintptr(0), 0},
},
afterScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {},
BaseChunkIdx + 1: {{0, PallocChunkPages}},
BaseChunkIdx + 2: {},
},
},
"ScavHighestPageFirst": {
beforeAlloc: map[ChunkIdx][]BitRange{
BaseChunkIdx: {},
},
beforeScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {{uint(minPages), PallocChunkPages - uint(2*minPages)}},
},
expect: []test{
{1, minPages * PageSize},
},
afterScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {{uint(minPages), PallocChunkPages - uint(minPages)}},
},
},
"ScavMultiple": {
beforeAlloc: map[ChunkIdx][]BitRange{
BaseChunkIdx: {},
},
beforeScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {{uint(minPages), PallocChunkPages - uint(2*minPages)}},
},
expect: []test{
{minPages * PageSize, minPages * PageSize},
{minPages * PageSize, minPages * PageSize},
},
afterScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {{0, PallocChunkPages}},
},
},
"ScavMultiple2": {
beforeAlloc: map[ChunkIdx][]BitRange{
BaseChunkIdx: {},
BaseChunkIdx + 1: {},
},
beforeScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {{uint(minPages), PallocChunkPages - uint(2*minPages)}},
BaseChunkIdx + 1: {{0, PallocChunkPages - uint(2*minPages)}},
},
expect: []test{
{2 * minPages * PageSize, 2 * minPages * PageSize},
{minPages * PageSize, minPages * PageSize},
{minPages * PageSize, minPages * PageSize},
},
afterScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {{0, PallocChunkPages}},
BaseChunkIdx + 1: {{0, PallocChunkPages}},
},
},
"ScavDiscontiguous": {
beforeAlloc: map[ChunkIdx][]BitRange{
BaseChunkIdx: {},
BaseChunkIdx + 0xe: {},
},
beforeScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {{uint(minPages), PallocChunkPages - uint(2*minPages)}},
BaseChunkIdx + 0xe: {{uint(2 * minPages), PallocChunkPages - uint(2*minPages)}},
},
expect: []test{
{2 * minPages * PageSize, 2 * minPages * PageSize},
{^uintptr(0), 2 * minPages * PageSize},
{^uintptr(0), 0},
},
afterScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {{0, PallocChunkPages}},
BaseChunkIdx + 0xe: {{0, PallocChunkPages}},
},
},
}
// Disable these tests on iOS since we have a small address space.
// See #46860.
if PageAlloc64Bit != 0 && goos.IsIos == 0 {
tests["ScavAllVeryDiscontiguous"] = setup{
beforeAlloc: map[ChunkIdx][]BitRange{
BaseChunkIdx: {},
BaseChunkIdx + 0x1000: {},
},
beforeScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {},
BaseChunkIdx + 0x1000: {},
},
expect: []test{
{^uintptr(0), 2 * PallocChunkPages * PageSize},
{^uintptr(0), 0},
},
afterScav: map[ChunkIdx][]BitRange{
BaseChunkIdx: {{0, PallocChunkPages}},
BaseChunkIdx + 0x1000: {{0, PallocChunkPages}},
},
}
}
for name, v := range tests {
t.Run(name, func(t *testing.T) {
b := NewPageAlloc(v.beforeAlloc, v.beforeScav)
defer FreePageAlloc(b)
for iter, h := range v.expect {
if got := b.Scavenge(h.request); got != h.expect {
t.Fatalf("bad scavenge #%d: want %d, got %d", iter+1, h.expect, got)
}
}
want := NewPageAlloc(v.beforeAlloc, v.afterScav)
defer FreePageAlloc(want)
checkPageAlloc(t, want, b)
})
}
}
func TestScavenger(t *testing.T) {
// workedTime is a standard conversion of bytes of scavenge
// work to time elapsed.
workedTime := func(bytes uintptr) int64 {
return int64((bytes+4095)/4096) * int64(10*time.Microsecond)
}
// Set up a bunch of state that we're going to track and verify
// throughout the test.
totalWork := uint64(64<<20 - 3*PhysPageSize)
var totalSlept, totalWorked atomic.Int64
var availableWork atomic.Uint64
var stopAt atomic.Uint64 // How much available work to stop at.
// Set up the scavenger.
var s Scavenger
s.Sleep = func(ns int64) int64 {
totalSlept.Add(ns)
return ns
}
s.Scavenge = func(bytes uintptr) (uintptr, int64) {
avail := availableWork.Load()
if uint64(bytes) > avail {
bytes = uintptr(avail)
}
t := workedTime(bytes)
if bytes != 0 {
availableWork.Add(-int64(bytes))
totalWorked.Add(t)
}
return bytes, t
}
s.ShouldStop = func() bool {
if availableWork.Load() <= stopAt.Load() {
return true
}
return false
}
s.GoMaxProcs = func() int32 {
return 1
}
// Define a helper for verifying that various properties hold.
verifyScavengerState := func(t *testing.T, expWork uint64) {
t.Helper()
// Check to make sure it did the amount of work we expected.
if workDone := uint64(s.Released()); workDone != expWork {
t.Errorf("want %d bytes of work done, got %d", expWork, workDone)
}
// Check to make sure the scavenger is meeting its CPU target.
idealFraction := float64(ScavengePercent) / 100.0
cpuFraction := float64(totalWorked.Load()) / float64(totalWorked.Load()+totalSlept.Load())
if cpuFraction < idealFraction-0.005 || cpuFraction > idealFraction+0.005 {
t.Errorf("want %f CPU fraction, got %f", idealFraction, cpuFraction)
}
}
// Start the scavenger.
s.Start()
// Set up some work and let the scavenger run to completion.
availableWork.Store(totalWork)
s.Wake()
if !s.BlockUntilParked(2e9 /* 2 seconds */) {
t.Fatal("timed out waiting for scavenger to run to completion")
}
// Run a check.
verifyScavengerState(t, totalWork)
// Now let's do it again and see what happens when we have no work to do.
// It should've gone right back to sleep.
s.Wake()
if !s.BlockUntilParked(2e9 /* 2 seconds */) {
t.Fatal("timed out waiting for scavenger to run to completion")
}
// Run another check.
verifyScavengerState(t, totalWork)
// One more time, this time doing the same amount of work as the first time.
// Let's see if we can get the scavenger to continue.
availableWork.Store(totalWork)
s.Wake()
if !s.BlockUntilParked(2e9 /* 2 seconds */) {
t.Fatal("timed out waiting for scavenger to run to completion")
}
// Run another check.
verifyScavengerState(t, 2*totalWork)
// This time, let's stop after a certain amount of work.
//
// Pick a stopping point such that when subtracted from totalWork
// we get a multiple of a relatively large power of 2. verifyScavengerState
// always makes an exact check, but the scavenger might go a little over,
// which is OK. If this breaks often or gets annoying to maintain, modify
// verifyScavengerState.
availableWork.Store(totalWork)
stoppingPoint := uint64(1<<20 - 3*PhysPageSize)
stopAt.Store(stoppingPoint)
s.Wake()
if !s.BlockUntilParked(2e9 /* 2 seconds */) {
t.Fatal("timed out waiting for scavenger to run to completion")
}
// Run another check.
verifyScavengerState(t, 2*totalWork+(totalWork-stoppingPoint))
// Clean up.
s.Stop()
}
func TestScavengeIndex(t *testing.T) {
// This test suite tests the scavengeIndex data structure.
// markFunc is a function that makes the address range [base, limit)
// available for scavenging in a test index.
type markFunc func(base, limit uintptr)
// findFunc is a function that searches for the next available page
// to scavenge in the index. It asserts that the page is found in
// chunk "ci" at page "offset."
type findFunc func(ci ChunkIdx, offset uint)
// The structure of the tests below is as follows:
//
// setup creates a fake scavengeIndex that can be mutated and queried by
// the functions it returns. Those functions capture the testing.T that
// setup is called with, so they're bound to the subtest they're created in.
//
// Tests are then organized into test cases which mark some pages as
// scavenge-able then try to find them. Tests expect that the initial
// state of the scavengeIndex has all of the chunks as dense in the last
// generation and empty to the scavenger.
//
// There are a few additional tests that interleave mark and find operations,
// so they're defined separately, but use the same infrastructure.
setup := func(t *testing.T, force bool) (mark markFunc, find findFunc, nextGen func()) {
t.Helper()
// Pick some reasonable bounds. We don't need a huge range just to test.
si := NewScavengeIndex(BaseChunkIdx, BaseChunkIdx+64)
// Initialize all the chunks as dense and empty.
//
// Also, reset search addresses so that we can get page offsets.
si.AllocRange(PageBase(BaseChunkIdx, 0), PageBase(BaseChunkIdx+64, 0))
si.NextGen()
si.FreeRange(PageBase(BaseChunkIdx, 0), PageBase(BaseChunkIdx+64, 0))
for ci := BaseChunkIdx; ci < BaseChunkIdx+64; ci++ {
si.SetEmpty(ci)
}
si.ResetSearchAddrs()
// Create and return test functions.
mark = func(base, limit uintptr) {
t.Helper()
si.AllocRange(base, limit)
si.FreeRange(base, limit)
}
find = func(want ChunkIdx, wantOffset uint) {
t.Helper()
got, gotOffset := si.Find(force)
if want != got {
t.Errorf("find: wanted chunk index %d, got %d", want, got)
}
if wantOffset != gotOffset {
t.Errorf("find: wanted page offset %d, got %d", wantOffset, gotOffset)
}
if t.Failed() {
t.FailNow()
}
si.SetEmpty(got)
}
nextGen = func() {
t.Helper()
si.NextGen()
}
return
}
// Each of these test cases calls mark and then find once.
type testCase struct {
name string
mark func(markFunc)
find func(findFunc)
}
tests := []testCase{
{
name: "Uninitialized",
mark: func(_ markFunc) {},
find: func(_ findFunc) {},
},
{
name: "OnePage",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx, 3), PageBase(BaseChunkIdx, 4))
},
find: func(find findFunc) {
find(BaseChunkIdx, 3)
},
},
{
name: "FirstPage",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx, 0), PageBase(BaseChunkIdx, 1))
},
find: func(find findFunc) {
find(BaseChunkIdx, 0)
},
},
{
name: "SeveralPages",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx, 9), PageBase(BaseChunkIdx, 14))
},
find: func(find findFunc) {
find(BaseChunkIdx, 13)
},
},
{
name: "WholeChunk",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx, 0), PageBase(BaseChunkIdx+1, 0))
},
find: func(find findFunc) {
find(BaseChunkIdx, PallocChunkPages-1)
},
},
{
name: "LastPage",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx, PallocChunkPages-1), PageBase(BaseChunkIdx+1, 0))
},
find: func(find findFunc) {
find(BaseChunkIdx, PallocChunkPages-1)
},
},
{
name: "SevenChunksOffset",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx+6, 11), PageBase(BaseChunkIdx+13, 15))
},
find: func(find findFunc) {
find(BaseChunkIdx+13, 14)
for i := BaseChunkIdx + 12; i >= BaseChunkIdx+6; i-- {
find(i, PallocChunkPages-1)
}
},
},
{
name: "ThirtyTwoChunks",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx, 0), PageBase(BaseChunkIdx+32, 0))
},
find: func(find findFunc) {
for i := BaseChunkIdx + 31; i >= BaseChunkIdx; i-- {
find(i, PallocChunkPages-1)
}
},
},
{
name: "ThirtyTwoChunksOffset",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx+3, 0), PageBase(BaseChunkIdx+35, 0))
},
find: func(find findFunc) {
for i := BaseChunkIdx + 34; i >= BaseChunkIdx+3; i-- {
find(i, PallocChunkPages-1)
}
},
},
{
name: "Mark",
mark: func(mark markFunc) {
for i := BaseChunkIdx; i < BaseChunkIdx+32; i++ {
mark(PageBase(i, 0), PageBase(i+1, 0))
}
},
find: func(find findFunc) {
for i := BaseChunkIdx + 31; i >= BaseChunkIdx; i-- {
find(i, PallocChunkPages-1)
}
},
},
{
name: "MarkIdempotentOneChunk",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx, 0), PageBase(BaseChunkIdx+1, 0))
mark(PageBase(BaseChunkIdx, 0), PageBase(BaseChunkIdx+1, 0))
},
find: func(find findFunc) {
find(BaseChunkIdx, PallocChunkPages-1)
},
},
{
name: "MarkIdempotentThirtyTwoChunks",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx, 0), PageBase(BaseChunkIdx+32, 0))
mark(PageBase(BaseChunkIdx, 0), PageBase(BaseChunkIdx+32, 0))
},
find: func(find findFunc) {
for i := BaseChunkIdx + 31; i >= BaseChunkIdx; i-- {
find(i, PallocChunkPages-1)
}
},
},
{
name: "MarkIdempotentThirtyTwoChunksOffset",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx+4, 0), PageBase(BaseChunkIdx+31, 0))
mark(PageBase(BaseChunkIdx+5, 0), PageBase(BaseChunkIdx+36, 0))
},
find: func(find findFunc) {
for i := BaseChunkIdx + 35; i >= BaseChunkIdx+4; i-- {
find(i, PallocChunkPages-1)
}
},
},
}
if PallocChunkPages >= 512 {
tests = append(tests,
testCase{
name: "TwoChunks",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx, 128), PageBase(BaseChunkIdx+1, 128))
},
find: func(find findFunc) {
find(BaseChunkIdx+1, 127)
find(BaseChunkIdx, PallocChunkPages-1)
},
},
testCase{
name: "TwoChunksOffset",
mark: func(mark markFunc) {
mark(PageBase(BaseChunkIdx+7, 128), PageBase(BaseChunkIdx+8, 129))
},
find: func(find findFunc) {
find(BaseChunkIdx+8, 128)
find(BaseChunkIdx+7, PallocChunkPages-1)
},
},
)
}
for _, test := range tests {
t.Run("Bg/"+test.name, func(t *testing.T) {
mark, find, nextGen := setup(t, false)
test.mark(mark)
find(0, 0) // Make sure we find nothing at this point.
nextGen() // Move to the next generation.
test.find(find) // Now we should be able to find things.
find(0, 0) // The test should always fully exhaust the index.
})
t.Run("Force/"+test.name, func(t *testing.T) {
mark, find, _ := setup(t, true)
test.mark(mark)
test.find(find) // Finding should always work when forced.
find(0, 0) // The test should always fully exhaust the index.
})
}
t.Run("Bg/MarkInterleaved", func(t *testing.T) {
mark, find, nextGen := setup(t, false)
for i := BaseChunkIdx; i < BaseChunkIdx+32; i++ {
mark(PageBase(i, 0), PageBase(i+1, 0))
nextGen()
find(i, PallocChunkPages-1)
}
find(0, 0)
})
t.Run("Force/MarkInterleaved", func(t *testing.T) {
mark, find, _ := setup(t, true)
for i := BaseChunkIdx; i < BaseChunkIdx+32; i++ {
mark(PageBase(i, 0), PageBase(i+1, 0))
find(i, PallocChunkPages-1)
}
find(0, 0)
})
}
func TestScavChunkDataPack(t *testing.T) {
if PallocChunkPages >= 512 {
if !CheckPackScavChunkData(1918237402, 512, 512, 0b11) {
t.Error("failed pack/unpack check for scavChunkData 1")
}
}
if !CheckPackScavChunkData(^uint32(0), 12, 0, 0b00) {
t.Error("failed pack/unpack check for scavChunkData 2")
}
}
func FuzzPIController(f *testing.F) {
isNormal := func(x float64) bool {
return !math.IsInf(x, 0) && !math.IsNaN(x)
}
isPositive := func(x float64) bool {
return isNormal(x) && x > 0
}
// Seed with constants from controllers in the runtime.
// It's not critical that we keep these in sync, they're just
// reasonable seed inputs.
f.Add(0.3375, 3.2e6, 1e9, 0.001, 1000.0, 0.01)
f.Add(0.9, 4.0, 1000.0, -1000.0, 1000.0, 0.84)
f.Fuzz(func(t *testing.T, kp, ti, tt, min, max, setPoint float64) {
// Ignore uninteresting invalid parameters. These parameters
// are constant, so in practice surprising values will be documented
// or will be other otherwise immediately visible.
//
// We just want to make sure that given a non-Inf, non-NaN input,
// we always get a non-Inf, non-NaN output.
if !isPositive(kp) || !isPositive(ti) || !isPositive(tt) {
return
}
if !isNormal(min) || !isNormal(max) || min > max {
return
}
// Use a random source, but make it deterministic.
rs := rand.New(rand.NewSource(800))
randFloat64 := func() float64 {
return math.Float64frombits(rs.Uint64())
}
p := NewPIController(kp, ti, tt, min, max)
state := float64(0)
for i := 0; i < 100; i++ {
input := randFloat64()
// Ignore the "ok" parameter. We're just trying to break it.
// state is intentionally completely uncorrelated with the input.
var ok bool
state, ok = p.Next(input, setPoint, 1.0)
if !isNormal(state) {
t.Fatalf("got NaN or Inf result from controller: %f %v", state, ok)
}
}
})
} | go | github | https://github.com/golang/go | src/runtime/mgcscavenge_test.go |
#!/usr/bin/env bash
# Copyright 2022 The Cockroach Authors.
#
# Use of this software is governed by the CockroachDB Software License
# included in the /LICENSE file.
set -euo pipefail
dir="$(dirname $(dirname $(dirname $(dirname $(dirname "${0}")))))"
source "$dir/teamcity-support.sh" # For $root
source "$dir/teamcity-bazel-support.sh" # For run_bazel
tc_start_block "Run unit tests"
BAZEL_SUPPORT_EXTRA_DOCKER_ARGS="-e TC_BUILD_BRANCH -e GITHUB_API_TOKEN -e BUILD_VCS_NUMBER -e TC_BUILD_ID -e TC_SERVER_URL -e TC_BUILDTYPE_ID -e GITHUB_REPO" run_bazel build/teamcity/cockroach/ci/tests-ibm-cloud-linux-s390x/unit_tests_impl.sh
tc_end_block "Run unit tests" | unknown | github | https://github.com/cockroachdb/cockroach | build/teamcity/cockroach/ci/tests-ibm-cloud-linux-s390x/unit_tests.sh |
<?php
namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Illuminate\Contracts\Console\Kernel as ConsoleKernelContract;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Arr;
use LogicException;
use Symfony\Component\Console\Attribute\AsCommand;
use Throwable;
#[AsCommand(name: 'config:cache')]
class ConfigCacheCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'config:cache';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Create a cache file for faster configuration loading';
/**
* The filesystem instance.
*
* @var \Illuminate\Filesystem\Filesystem
*/
protected $files;
/**
* Create a new config cache command instance.
*
* @param \Illuminate\Filesystem\Filesystem $files
*/
public function __construct(Filesystem $files)
{
parent::__construct();
$this->files = $files;
}
/**
* Execute the console command.
*
* @return void
*
* @throws \LogicException
*/
public function handle()
{
$this->callSilent('config:clear');
$config = $this->getFreshConfiguration();
$configPath = $this->laravel->getCachedConfigPath();
$this->files->put(
$configPath, '<?php return '.var_export($config, true).';'.PHP_EOL
);
try {
require $configPath;
} catch (Throwable $e) {
$this->files->delete($configPath);
foreach (Arr::dot($config) as $key => $value) {
try {
eval(var_export($value, true).';');
} catch (Throwable $e) {
throw new LogicException("Your configuration files could not be serialized because the value at \"{$key}\" is non-serializable.", 0, $e);
}
}
throw new LogicException('Your configuration files are not serializable.', 0, $e);
}
$this->components->info('Configuration cached successfully.');
}
/**
* Boot a fresh copy of the application configuration.
*
* @return array
*/
protected function getFreshConfiguration()
{
$app = require $this->laravel->bootstrapPath('app.php');
$app->useStoragePath($this->laravel->storagePath());
$app->make(ConsoleKernelContract::class)->bootstrap();
return $app['config']->all();
}
} | php | github | https://github.com/laravel/framework | src/Illuminate/Foundation/Console/ConfigCacheCommand.php |
/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_INTERFACE_H_
#define TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_INTERFACE_H_
#include <functional>
#include "absl/synchronization/notification.h"
#include "tensorflow/core/distributed_runtime/call_options.h"
#include "tensorflow/core/distributed_runtime/message_wrappers.h"
#include "tensorflow/core/lib/core/notification.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/protobuf/worker.pb.h"
namespace tensorflow {
// Status callback.
typedef std::function<void(const absl::Status&)> StatusCallback;
// Custom decoder for a response to RecvTensorAsync.
class TensorResponse;
// Interface for talking with the TensorFlow Worker service.
class WorkerInterface {
public:
virtual void GetStatusAsync(CallOptions* opts,
const GetStatusRequest* request,
GetStatusResponse* response, bool fail_fast,
StatusCallback done) = 0;
virtual void CreateWorkerSessionAsync(
const CreateWorkerSessionRequest* request,
CreateWorkerSessionResponse* response, StatusCallback done) = 0;
virtual void DeleteWorkerSessionAsync(
CallOptions* opts, const DeleteWorkerSessionRequest* request,
DeleteWorkerSessionResponse* response, StatusCallback done) = 0;
virtual void RegisterGraphAsync(const RegisterGraphRequest* request,
RegisterGraphResponse* response,
StatusCallback done) = 0;
virtual void DeregisterGraphAsync(const DeregisterGraphRequest* request,
DeregisterGraphResponse* response,
StatusCallback done) = 0;
virtual void RunGraphAsync(CallOptions* opts, RunGraphRequestWrapper* request,
MutableRunGraphResponseWrapper* response,
StatusCallback done) = 0;
virtual void RunGraphAsync(CallOptions* opts, const RunGraphRequest* request,
RunGraphResponse* response, StatusCallback done) {
RunGraphRequestWrapper* wrapped_request = new ProtoRunGraphRequest(request);
MutableRunGraphResponseWrapper* wrapped_response =
new NonOwnedProtoRunGraphResponse(response);
RunGraphAsync(opts, wrapped_request, wrapped_response,
[wrapped_request, wrapped_response,
done = std::move(done)](const absl::Status& s) {
done(s);
delete wrapped_request;
delete wrapped_response;
});
}
// Returns a request object for use in calls to
// `RunGraphAsync()`. Ownership is transferred to the caller.
//
// The message returned from this method must only be used in a
// `RunGraph()` call on the same `WorkerInterface` instance.
virtual MutableRunGraphRequestWrapper* CreateRunGraphRequest() {
return new MutableProtoRunGraphRequest;
}
// Returns a response object for use in calls to
// `RunGraphAsync()`. Ownership is transferred to the caller.
//
// The message returned from this method must only be used in a
// `RunGraph()` call on the same `WorkerInterface` instance.
virtual MutableRunGraphResponseWrapper* CreateRunGraphResponse() {
return new OwnedProtoRunGraphResponse;
}
virtual void CleanupGraphAsync(const CleanupGraphRequest* request,
CleanupGraphResponse* response,
StatusCallback done) = 0;
virtual void CleanupAllAsync(const CleanupAllRequest* request,
CleanupAllResponse* response,
StatusCallback done) = 0;
virtual void RecvTensorAsync(CallOptions* opts,
const RecvTensorRequest* request,
TensorResponse* response,
StatusCallback done) = 0;
virtual void LoggingAsync(const LoggingRequest* request,
LoggingResponse* response, StatusCallback done) = 0;
virtual void TracingAsync(const TracingRequest* request,
TracingResponse* response, StatusCallback done) = 0;
virtual void RecvBufAsync(CallOptions* opts, const RecvBufRequest* request,
RecvBufResponse* response, StatusCallback done) = 0;
virtual void CompleteGroupAsync(CallOptions* opts,
const CompleteGroupRequest* request,
CompleteGroupResponse* response,
StatusCallback done) = 0;
virtual void CompleteInstanceAsync(CallOptions* ops,
const CompleteInstanceRequest* request,
CompleteInstanceResponse* response,
StatusCallback done) = 0;
virtual void GetStepSequenceAsync(const GetStepSequenceRequest* request,
GetStepSequenceResponse* response,
StatusCallback done) = 0;
absl::Status GetStatus(const GetStatusRequest* request,
GetStatusResponse* response) {
absl::Status ret;
absl::Notification n;
GetStatusAsync(/*opts=*/nullptr, request, response, /*fail_fast=*/true,
[&ret, &n](const absl::Status& s) {
ret = s;
n.Notify();
});
n.WaitForNotification();
return ret;
}
absl::Status CreateWorkerSession(const CreateWorkerSessionRequest* request,
CreateWorkerSessionResponse* response) {
return CallAndWait(&ME::CreateWorkerSessionAsync, request, response);
}
absl::Status DeleteWorkerSession(const DeleteWorkerSessionRequest* request,
DeleteWorkerSessionResponse* response) {
return CallAndWaitWithOptions(&ME::DeleteWorkerSessionAsync, request,
response);
}
absl::Status RegisterGraph(const RegisterGraphRequest* request,
RegisterGraphResponse* response) {
return CallAndWait(&ME::RegisterGraphAsync, request, response);
}
absl::Status DeregisterGraph(const DeregisterGraphRequest* request,
DeregisterGraphResponse* response) {
return CallAndWait(&ME::DeregisterGraphAsync, request, response);
}
absl::Status CleanupGraph(const CleanupGraphRequest* request,
CleanupGraphResponse* response) {
return CallAndWait(&ME::CleanupGraphAsync, request, response);
}
absl::Status CleanupAll(const CleanupAllRequest* request,
CleanupAllResponse* response) {
return CallAndWait(&ME::CleanupAllAsync, request, response);
}
absl::Status Logging(const LoggingRequest* request,
LoggingResponse* response) {
return CallAndWait(&ME::LoggingAsync, request, response);
}
absl::Status Tracing(const TracingRequest* request,
TracingResponse* response) {
return CallAndWait(&ME::TracingAsync, request, response);
}
absl::Status GetStepSequence(const GetStepSequenceRequest* request,
GetStepSequenceResponse* response) {
return CallAndWait(&ME::GetStepSequenceAsync, request, response);
}
protected:
// Instances of WorkerInterface must be deleted by a call to
// WorkerCacheInterface::ReleaseWorker().
virtual ~WorkerInterface() {}
friend class WorkerCacheInterface;
// NOTE: This should only be called by implementations of this
// interface whose CreateRunGraphResponse() method returns a
// proto-based wrappers for the RunGraphResponse message.
RunGraphResponse* get_proto_from_wrapper(
MutableRunGraphResponseWrapper* wrapper) {
return wrapper->get_proto();
}
private:
typedef WorkerInterface ME;
template <typename Method, typename Req, typename Resp>
absl::Status CallAndWait(Method func, const Req* req, Resp* resp) {
absl::Status ret;
absl::Notification n;
(this->*func)(req, resp, [&ret, &n](const absl::Status& s) {
ret = s;
n.Notify();
});
n.WaitForNotification();
return ret;
}
template <typename Method, typename Req, typename Resp>
absl::Status CallAndWaitWithOptions(Method func, const Req* req, Resp* resp) {
CallOptions call_opts;
absl::Status ret;
absl::Notification n;
(this->*func)(&call_opts, req, resp, [&ret, &n](const absl::Status& s) {
ret = s;
n.Notify();
});
n.WaitForNotification();
return ret;
}
};
} // namespace tensorflow
#endif // TENSORFLOW_CORE_DISTRIBUTED_RUNTIME_WORKER_INTERFACE_H_ | c | github | https://github.com/tensorflow/tensorflow | tensorflow/core/distributed_runtime/worker_interface.h |
"""Generic socket server classes.
This module tries to capture the various aspects of defining a server:
For socket-based servers:
- address family:
- AF_INET{,6}: IP (Internet Protocol) sockets (default)
- AF_UNIX: Unix domain sockets
- others, e.g. AF_DECNET are conceivable (see <socket.h>
- socket type:
- SOCK_STREAM (reliable stream, e.g. TCP)
- SOCK_DGRAM (datagrams, e.g. UDP)
For request-based servers (including socket-based):
- client address verification before further looking at the request
(This is actually a hook for any processing that needs to look
at the request before anything else, e.g. logging)
- how to handle multiple requests:
- synchronous (one request is handled at a time)
- forking (each request is handled by a new process)
- threading (each request is handled by a new thread)
The classes in this module favor the server type that is simplest to
write: a synchronous TCP/IP server. This is bad class design, but
save some typing. (There's also the issue that a deep class hierarchy
slows down method lookups.)
There are five classes in an inheritance diagram, four of which represent
synchronous servers of four types:
+------------+
| BaseServer |
+------------+
|
v
+-----------+ +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+ +------------------+
|
v
+-----------+ +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+ +--------------------+
Note that UnixDatagramServer derives from UDPServer, not from
UnixStreamServer -- the only difference between an IP and a Unix
stream server is the address family, which is simply repeated in both
unix server classes.
Forking and threading versions of each type of server can be created
using the ForkingMixIn and ThreadingMixIn mix-in classes. For
instance, a threading UDP server class is created as follows:
class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
The Mix-in class must come first, since it overrides a method defined
in UDPServer! Setting the various member variables also changes
the behavior of the underlying server mechanism.
To implement a service, you must derive a class from
BaseRequestHandler and redefine its handle() method. You can then run
various versions of the service by combining one of the server classes
with your request handler class.
The request handler class must be different for datagram or stream
services. This can be hidden by using the request handler
subclasses StreamRequestHandler or DatagramRequestHandler.
Of course, you still have to use your head!
For instance, it makes no sense to use a forking server if the service
contains state in memory that can be modified by requests (since the
modifications in the child process would never reach the initial state
kept in the parent process and passed to each child). In this case,
you can use a threading server, but you will probably have to use
locks to avoid two requests that come in nearly simultaneous to apply
conflicting changes to the server state.
On the other hand, if you are building e.g. an HTTP server, where all
data is stored externally (e.g. in the file system), a synchronous
class will essentially render the service "deaf" while one request is
being handled -- which may be for a very long time if a client is slow
to reqd all the data it has requested. Here a threading or forking
server is appropriate.
In some cases, it may be appropriate to process part of a request
synchronously, but to finish processing in a forked child depending on
the request data. This can be implemented by using a synchronous
server and doing an explicit fork in the request handler class
handle() method.
Another approach to handling multiple simultaneous requests in an
environment that supports neither threads nor fork (or where these are
too expensive or inappropriate for the service) is to maintain an
explicit table of partially finished requests and to use select() to
decide which request to work on next (or whether to handle a new
incoming request). This is particularly important for stream services
where each client can potentially be connected for a long time (if
threads or subprocesses cannot be used).
Future work:
- Standard classes for Sun RPC (which uses either UDP or TCP)
- Standard mix-in classes to implement various authentication
and encryption schemes
- Standard framework for select-based multiplexing
XXX Open problems:
- What to do with out-of-band data?
BaseServer:
- split generic "request" functionality out into BaseServer class.
Copyright (C) 2000 Luke Kenneth Casson Leighton <lkcl@samba.org>
example: read entries from a SQL database (requires overriding
get_request() to return a table entry from the database).
entry is processed by a RequestHandlerClass.
"""
# Author of the BaseServer patch: Luke Kenneth Casson Leighton
# XXX Warning!
# There is a test suite for this module, but it cannot be run by the
# standard regression test.
# To run it manually, run Lib/test/test_socketserver.py.
__version__ = "0.4"
import socket
import select
import sys
import os
try:
import threading
except ImportError:
import dummy_threading as threading
__all__ = ["TCPServer","UDPServer","ForkingUDPServer","ForkingTCPServer",
"ThreadingUDPServer","ThreadingTCPServer","BaseRequestHandler",
"StreamRequestHandler","DatagramRequestHandler",
"ThreadingMixIn", "ForkingMixIn"]
if hasattr(socket, "AF_UNIX"):
__all__.extend(["UnixStreamServer","UnixDatagramServer",
"ThreadingUnixStreamServer",
"ThreadingUnixDatagramServer"])
class BaseServer:
"""Base class for server classes.
Methods for the caller:
- __init__(server_address, RequestHandlerClass)
- serve_forever(poll_interval=0.5)
- shutdown()
- handle_request() # if you do not use serve_forever()
- fileno() -> int # for select()
Methods that may be overridden:
- server_bind()
- server_activate()
- get_request() -> request, client_address
- handle_timeout()
- verify_request(request, client_address)
- server_close()
- process_request(request, client_address)
- shutdown_request(request)
- close_request(request)
- handle_error()
Methods for derived classes:
- finish_request(request, client_address)
Class variables that may be overridden by derived classes or
instances:
- timeout
- address_family
- socket_type
- allow_reuse_address
Instance variables:
- RequestHandlerClass
- socket
"""
timeout = None
def __init__(self, server_address, RequestHandlerClass):
"""Constructor. May be extended, do not override."""
self.server_address = server_address
self.RequestHandlerClass = RequestHandlerClass
self.__is_shut_down = threading.Event()
self.__shutdown_request = False
def server_activate(self):
"""Called by constructor to activate the server.
May be overridden.
"""
pass
def serve_forever(self, poll_interval=0.5):
"""Handle one request at a time until shutdown.
Polls for shutdown every poll_interval seconds. Ignores
self.timeout. If you need to do periodic tasks, do them in
another thread.
"""
self.__is_shut_down.clear()
try:
while not self.__shutdown_request:
# XXX: Consider using another file descriptor or
# connecting to the socket to wake this up instead of
# polling. Polling reduces our responsiveness to a
# shutdown request and wastes cpu at all other times.
r, w, e = select.select([self], [], [], poll_interval)
if self in r:
self._handle_request_noblock()
finally:
self.__shutdown_request = False
self.__is_shut_down.set()
def shutdown(self):
"""Stops the serve_forever loop.
Blocks until the loop has finished. This must be called while
serve_forever() is running in another thread, or it will
deadlock.
"""
self.__shutdown_request = True
self.__is_shut_down.wait()
# The distinction between handling, getting, processing and
# finishing a request is fairly arbitrary. Remember:
#
# - handle_request() is the top-level call. It calls
# select, get_request(), verify_request() and process_request()
# - get_request() is different for stream or datagram sockets
# - process_request() is the place that may fork a new process
# or create a new thread to finish the request
# - finish_request() instantiates the request handler class;
# this constructor will handle the request all by itself
def handle_request(self):
"""Handle one request, possibly blocking.
Respects self.timeout.
"""
# Support people who used socket.settimeout() to escape
# handle_request before self.timeout was available.
timeout = self.socket.gettimeout()
if timeout is None:
timeout = self.timeout
elif self.timeout is not None:
timeout = min(timeout, self.timeout)
fd_sets = select.select([self], [], [], timeout)
if not fd_sets[0]:
self.handle_timeout()
return
self._handle_request_noblock()
def _handle_request_noblock(self):
"""Handle one request, without blocking.
I assume that select.select has returned that the socket is
readable before this function was called, so there should be
no risk of blocking in get_request().
"""
try:
request, client_address = self.get_request()
except socket.error:
return
if self.verify_request(request, client_address):
try:
self.process_request(request, client_address)
except:
self.handle_error(request, client_address)
self.shutdown_request(request)
def handle_timeout(self):
"""Called if no new request arrives within self.timeout.
Overridden by ForkingMixIn.
"""
pass
def verify_request(self, request, client_address):
"""Verify the request. May be overridden.
Return True if we should proceed with this request.
"""
return True
def process_request(self, request, client_address):
"""Call finish_request.
Overridden by ForkingMixIn and ThreadingMixIn.
"""
self.finish_request(request, client_address)
self.shutdown_request(request)
def server_close(self):
"""Called to clean-up the server.
May be overridden.
"""
pass
def finish_request(self, request, client_address):
"""Finish one request by instantiating RequestHandlerClass."""
self.RequestHandlerClass(request, client_address, self)
def shutdown_request(self, request):
"""Called to shutdown and close an individual request."""
self.close_request(request)
def close_request(self, request):
"""Called to clean up an individual request."""
pass
def handle_error(self, request, client_address):
"""Handle an error gracefully. May be overridden.
The default is to print a traceback and continue.
"""
print '-'*40
print 'Exception happened during processing of request from',
print client_address
import traceback
traceback.print_exc() # XXX But this goes to stderr!
print '-'*40
class TCPServer(BaseServer):
"""Base class for various socket-based server classes.
Defaults to synchronous IP stream (i.e., TCP).
Methods for the caller:
- __init__(server_address, RequestHandlerClass, bind_and_activate=True)
- serve_forever(poll_interval=0.5)
- shutdown()
- handle_request() # if you don't use serve_forever()
- fileno() -> int # for select()
Methods that may be overridden:
- server_bind()
- server_activate()
- get_request() -> request, client_address
- handle_timeout()
- verify_request(request, client_address)
- process_request(request, client_address)
- shutdown_request(request)
- close_request(request)
- handle_error()
Methods for derived classes:
- finish_request(request, client_address)
Class variables that may be overridden by derived classes or
instances:
- timeout
- address_family
- socket_type
- request_queue_size (only for stream sockets)
- allow_reuse_address
Instance variables:
- server_address
- RequestHandlerClass
- socket
"""
address_family = socket.AF_INET
socket_type = socket.SOCK_STREAM
request_queue_size = 5
allow_reuse_address = False
def __init__(self, server_address, RequestHandlerClass, bind_and_activate=True):
"""Constructor. May be extended, do not override."""
BaseServer.__init__(self, server_address, RequestHandlerClass)
self.socket = socket.socket(self.address_family,
self.socket_type)
if bind_and_activate:
self.server_bind()
self.server_activate()
def server_bind(self):
"""Called by constructor to bind the socket.
May be overridden.
"""
if self.allow_reuse_address:
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind(self.server_address)
self.server_address = self.socket.getsockname()
def server_activate(self):
"""Called by constructor to activate the server.
May be overridden.
"""
self.socket.listen(self.request_queue_size)
def server_close(self):
"""Called to clean-up the server.
May be overridden.
"""
self.socket.close()
def fileno(self):
"""Return socket file number.
Interface required by select().
"""
return self.socket.fileno()
def get_request(self):
"""Get the request and client address from the socket.
May be overridden.
"""
return self.socket.accept()
def shutdown_request(self, request):
"""Called to shutdown and close an individual request."""
try:
#explicitly shutdown. socket.close() merely releases
#the socket and waits for GC to perform the actual close.
request.shutdown(socket.SHUT_WR)
except socket.error:
pass #some platforms may raise ENOTCONN here
self.close_request(request)
def close_request(self, request):
"""Called to clean up an individual request."""
request.close()
class UDPServer(TCPServer):
"""UDP server class."""
allow_reuse_address = False
socket_type = socket.SOCK_DGRAM
max_packet_size = 8192
def get_request(self):
data, client_addr = self.socket.recvfrom(self.max_packet_size)
return (data, self.socket), client_addr
def server_activate(self):
# No need to call listen() for UDP.
pass
def shutdown_request(self, request):
# No need to shutdown anything.
self.close_request(request)
def close_request(self, request):
# No need to close anything.
pass
class ForkingMixIn:
"""Mix-in class to handle each request in a new process."""
timeout = 300
active_children = None
max_children = 40
def collect_children(self):
"""Internal routine to wait for children that have exited."""
if self.active_children is None: return
while len(self.active_children) >= self.max_children:
# XXX: This will wait for any child process, not just ones
# spawned by this library. This could confuse other
# libraries that expect to be able to wait for their own
# children.
try:
pid, status = os.waitpid(0, 0)
except os.error:
pid = None
if pid not in self.active_children: continue
self.active_children.remove(pid)
# XXX: This loop runs more system calls than it ought
# to. There should be a way to put the active_children into a
# process group and then use os.waitpid(-pgid) to wait for any
# of that set, but I couldn't find a way to allocate pgids
# that couldn't collide.
for child in self.active_children:
try:
pid, status = os.waitpid(child, os.WNOHANG)
except os.error:
pid = None
if not pid: continue
try:
self.active_children.remove(pid)
except ValueError, e:
raise ValueError('%s. x=%d and list=%r' % (e.message, pid,
self.active_children))
def handle_timeout(self):
"""Wait for zombies after self.timeout seconds of inactivity.
May be extended, do not override.
"""
self.collect_children()
def process_request(self, request, client_address):
"""Fork a new subprocess to process the request."""
self.collect_children()
pid = os.fork()
if pid:
# Parent process
if self.active_children is None:
self.active_children = []
self.active_children.append(pid)
self.close_request(request) #close handle in parent process
return
else:
# Child process.
# This must never return, hence os._exit()!
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
os._exit(0)
except:
try:
self.handle_error(request, client_address)
self.shutdown_request(request)
finally:
os._exit(1)
class ThreadingMixIn:
"""Mix-in class to handle each request in a new thread."""
# Decides how threads will act upon termination of the
# main process
daemon_threads = False
def process_request_thread(self, request, client_address):
"""Same as in BaseServer but as a thread.
In addition, exception handling is done here.
"""
try:
self.finish_request(request, client_address)
self.shutdown_request(request)
except:
self.handle_error(request, client_address)
self.shutdown_request(request)
def process_request(self, request, client_address):
"""Start a new thread to process the request."""
t = threading.Thread(target = self.process_request_thread,
args = (request, client_address))
if self.daemon_threads:
t.setDaemon (1)
t.start()
class ForkingUDPServer(ForkingMixIn, UDPServer): pass
class ForkingTCPServer(ForkingMixIn, TCPServer): pass
class ThreadingUDPServer(ThreadingMixIn, UDPServer): pass
class ThreadingTCPServer(ThreadingMixIn, TCPServer): pass
if hasattr(socket, 'AF_UNIX'):
class UnixStreamServer(TCPServer):
address_family = socket.AF_UNIX
class UnixDatagramServer(UDPServer):
address_family = socket.AF_UNIX
class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): pass
class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): pass
class BaseRequestHandler:
"""Base class for request handler classes.
This class is instantiated for each request to be handled. The
constructor sets the instance variables request, client_address
and server, and then calls the handle() method. To implement a
specific service, all you need to do is to derive a class which
defines a handle() method.
The handle() method can find the request as self.request, the
client address as self.client_address, and the server (in case it
needs access to per-server information) as self.server. Since a
separate instance is created for each request, the handle() method
can define arbitrary other instance variariables.
"""
def __init__(self, request, client_address, server):
self.request = request
self.client_address = client_address
self.server = server
self.setup()
try:
self.handle()
finally:
self.finish()
def setup(self):
pass
def handle(self):
pass
def finish(self):
pass
# The following two classes make it possible to use the same service
# class for stream or datagram servers.
# Each class sets up these instance variables:
# - rfile: a file object from which receives the request is read
# - wfile: a file object to which the reply is written
# When the handle() method returns, wfile is flushed properly
class StreamRequestHandler(BaseRequestHandler):
"""Define self.rfile and self.wfile for stream sockets."""
# Default buffer sizes for rfile, wfile.
# We default rfile to buffered because otherwise it could be
# really slow for large data (a getc() call per byte); we make
# wfile unbuffered because (a) often after a write() we want to
# read and we need to flush the line; (b) big writes to unbuffered
# files are typically optimized by stdio even when big reads
# aren't.
rbufsize = -1
wbufsize = 0
# A timeout to apply to the request socket, if not None.
timeout = None
# Disable nagle algorithm for this socket, if True.
# Use only when wbufsize != 0, to avoid small packets.
disable_nagle_algorithm = False
def setup(self):
self.connection = self.request
if self.timeout is not None:
self.connection.settimeout(self.timeout)
if self.disable_nagle_algorithm:
self.connection.setsockopt(socket.IPPROTO_TCP,
socket.TCP_NODELAY, True)
self.rfile = self.connection.makefile('rb', self.rbufsize)
self.wfile = self.connection.makefile('wb', self.wbufsize)
def finish(self):
if not self.wfile.closed:
self.wfile.flush()
self.wfile.close()
self.rfile.close()
class DatagramRequestHandler(BaseRequestHandler):
# XXX Regrettably, I cannot get this working on Linux;
# s.recvfrom() doesn't return a meaningful client address.
"""Define self.rfile and self.wfile for datagram sockets."""
def setup(self):
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
self.packet, self.socket = self.request
self.rfile = StringIO(self.packet)
self.wfile = StringIO()
def finish(self):
self.socket.sendto(self.wfile.getvalue(), self.client_address) | unknown | codeparrot/codeparrot-clean | ||
"""Energy Goal Test"""
import datetime
from apps.managers.team_mgr.models import Group
from apps.managers.player_mgr.models import Profile
from django.test import TransactionTestCase
from django.contrib.auth.models import User
from apps.managers.team_mgr.models import Team
from apps.utils import test_utils
from apps.widgets.resource_goal import resource_goal
from apps.widgets.resource_goal.models import EnergyGoalSetting, EnergyBaselineDaily, EnergyGoal
from apps.managers.resource_mgr.models import EnergyUsage
class TeamEnergyGoalTest(TransactionTestCase):
"""Team Energy Goal Test"""
def setUp(self):
"""setup"""
test_utils.set_competition_round()
group = Group.objects.create(name="Test Group")
group.save()
self.team = Team.objects.create(
group=group,
name="A"
)
self.user = User.objects.create_user("user", "user@test.com")
profile = self.user.get_profile()
profile.team = self.team
profile.save()
def testTeamEnergyGoal(self):
"""Test energy goal"""
profile = self.user.get_profile()
points = profile.points()
goal_settings = EnergyGoalSetting.objects.filter(team=self.team)
if not goal_settings:
goal_settings = EnergyGoalSetting(team=self.team,
goal_percent_reduction=5,
goal_points=20,
baseline_method="Fixed",
manual_entry=True,
manual_entry_time=datetime.time(hour=15),
)
goal_settings.save()
else:
goal_settings = goal_settings[0]
goal_baseline = EnergyBaselineDaily(
team=self.team,
day=datetime.date.today().weekday(),
usage=150,
)
goal_baseline.save()
energy_data = EnergyUsage(
team=self.team,
date=datetime.date.today(),
time=datetime.time(hour=15),
usage=100,
)
energy_data.save()
today = datetime.date.today()
resource_goal.check_team_resource_goal("energy", self.team, today)
profile = Profile.objects.get(user__username="user")
self.assertEqual(profile.points(), points,
"User that did not complete the setup process should not be awarded points.")
profile.setup_complete = True
profile.save()
energy_data.usage = 150
energy_data.save()
EnergyGoal.objects.filter(team=self.team, date=today).delete()
resource_goal.check_team_resource_goal("energy", self.team, today)
profile = Profile.objects.get(user__username="user")
self.assertEqual(profile.points(), points,
"Team that failed the goal should not be awarded any points.")
energy_data.usage = 100
energy_data.save()
EnergyGoal.objects.filter(team=self.team, date=today).delete()
resource_goal.check_team_resource_goal("energy", self.team, today)
profile = Profile.objects.get(user__username="user")
self.assertEqual(profile.points(), points + goal_settings.goal_points,
"User that setup their profile should be awarded points.") | unknown | codeparrot/codeparrot-clean | ||
{
"__schema": {
"queryType": {
"name": "Query"
},
"mutationType": null,
"subscriptionType": null,
"types": [
{
"kind": "SCALAR",
"name": "String",
"description": null,
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Boolean",
"description": null,
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Float",
"description": null,
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Int",
"description": null,
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "ID",
"description": null,
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Date",
"description": "The `Date` scalar type represents a year, month and day in accordance with the [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) standard.",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "DateTime",
"description": "The `DateTime` scalar type represents a date and time. `DateTime` expects timestamps to be formatted in accordance with the [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) standard.",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "DateTimeOffset",
"description": "The `DateTimeOffset` scalar type represents a date, time and offset from UTC. `DateTimeOffset` expects timestamps to be formatted in accordance with the [ISO-8601](https://en.wikipedia.org/wiki/ISO_8601) standard.",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Seconds",
"description": "The `Seconds` scalar type represents a period of time represented as the total number of seconds.",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Milliseconds",
"description": "The `Milliseconds` scalar type represents a period of time represented as the total number of milliseconds.",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Decimal",
"description": null,
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "__Schema",
"description": "A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.",
"fields": [
{
"name": "directives",
"description": "A list of all directives supported by this server.",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__Directive",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "mutationType",
"description": "If this server supports mutation, the type that mutation operations will be rooted at.",
"args": [],
"type": {
"kind": "OBJECT",
"name": "__Type",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "queryType",
"description": "The type that query operations will be rooted at.",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__Type",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "subscriptionType",
"description": "If this server supports subscription, the type that subscription operations will be rooted at.",
"args": [],
"type": {
"kind": "OBJECT",
"name": "__Type",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "types",
"description": "A list of all types supported by this server.",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__Type",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "__Type",
"description": "The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\r\n\r\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name and description, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.",
"fields": [
{
"name": "description",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "enumValues",
"description": null,
"args": [
{
"name": "includeDeprecated",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__EnumValue",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "includeDeprecated",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__Field",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "inputFields",
"description": null,
"args": [],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__InputValue",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "interfaces",
"description": null,
"args": [],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__Type",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "kind",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "ENUM",
"name": "__TypeKind",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "ofType",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "__Type",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "possibleTypes",
"description": null,
"args": [],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__Type",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "ENUM",
"name": "__TypeKind",
"description": "An enum describing what kind of type a given __Type is.",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": [
{
"name": "SCALAR",
"description": "Indicates this type is a scalar.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "OBJECT",
"description": "Indicates this type is an object. `fields` and `possibleTypes` are valid fields.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "INTERFACE",
"description": "Indicates this type is an interface. `fields` and `possibleTypes` are valid fields.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "UNION",
"description": "Indicates this type is a union. `possibleTypes` is a valid field.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "ENUM",
"description": "Indicates this type is an num. `enumValues` is a valid field.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "INPUT_OBJECT",
"description": "Indicates this type is an input object. `inputFields` is a valid field.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "LIST",
"description": "Indicates this type is a list. `ofType` is a valid field.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "NON_NULL",
"description": "Indicates this type is a non-null. `ofType` is a valid field.",
"isDeprecated": false,
"deprecationReason": null
}
],
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "__Field",
"description": "Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.",
"fields": [
{
"name": "args",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__InputValue",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "deprecationReason",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "isDeprecated",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "type",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__Type",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "__InputValue",
"description": "Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.",
"fields": [
{
"name": "defaultValue",
"description": "A GraphQL-formatted string representing the default value for this input value.",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "type",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__Type",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "__EnumValue",
"description": "One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.",
"fields": [
{
"name": "deprecationReason",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "isDeprecated",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "__Directive",
"description": "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\r\n\r\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.",
"fields": [
{
"name": "args",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "__InputValue",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "locations",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "ENUM",
"name": "__DirectiveLocation",
"ofType": null
}
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "onField",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": true,
"deprecationReason": "Use 'locations'."
},
{
"name": "onFragment",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": true,
"deprecationReason": "Use 'locations'."
},
{
"name": "onOperation",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": true,
"deprecationReason": "Use 'locations'."
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "ENUM",
"name": "__DirectiveLocation",
"description": "A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.",
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": [
{
"name": "QUERY",
"description": "Location adjacent to a query operation.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "MUTATION",
"description": "Location adjacent to a mutation operation.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "SUBSCRIPTION",
"description": "Location adjacent to a subscription operation.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "FIELD",
"description": "Location adjacent to a field.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "FRAGMENT_DEFINITION",
"description": "Location adjacent to a fragment definition.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "FRAGMENT_SPREAD",
"description": "Location adjacent to a fragment spread.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "INLINE_FRAGMENT",
"description": "Location adjacent to an inline fragment.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "SCHEMA",
"description": "Location adjacent to a schema definition.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "SCALAR",
"description": "Location adjacent to a scalar definition.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "OBJECT",
"description": "Location adjacent to an object type definition.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "FIELD_DEFINITION",
"description": "Location adjacent to a field definition.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "ARGUMENT_DEFINITION",
"description": "Location adjacent to an argument definition.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "INTERFACE",
"description": "Location adjacent to an interface definition.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "UNION",
"description": "Location adjacent to a union definition.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "ENUM",
"description": "Location adjacent to an enum definition",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "ENUM_VALUE",
"description": "Location adjacent to an enum value definition",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "INPUT_OBJECT",
"description": "Location adjacent to an input object type definition.",
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "INPUT_FIELD_DEFINITION",
"description": "Location adjacent to an input object field definition.",
"isDeprecated": false,
"deprecationReason": null
}
],
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "ItemTemplateField",
"description": null,
"fields": [
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "section",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sectionSortOrder",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "shared",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sortOrder",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "source",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "title",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "type",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "unversioned",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "JSON",
"description": null,
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "INTERFACE",
"name": "ItemField",
"description": null,
"fields": [
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": [
{
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
{
"kind": "OBJECT",
"name": "NumberField",
"ofType": null
},
{
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
{
"kind": "OBJECT",
"name": "LookupField",
"ofType": null
},
{
"kind": "OBJECT",
"name": "LinkField",
"ofType": null
},
{
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
{
"kind": "OBJECT",
"name": "IntegerField",
"ofType": null
},
{
"kind": "OBJECT",
"name": "ImageField",
"ofType": null
},
{
"kind": "OBJECT",
"name": "DateField",
"ofType": null
},
{
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
{
"kind": "OBJECT",
"name": "NameValueListField",
"ofType": null
}
]
},
{
"kind": "OBJECT",
"name": "PageInfo",
"description": null,
"fields": [
{
"name": "endCursor",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasNext",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "ItemTemplate",
"description": null,
"fields": [
{
"name": "baseTemplates",
"description": null,
"args": [],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "ownFields",
"description": null,
"args": [],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "ItemUrl",
"description": null,
"fields": [
{
"name": "hostName",
"description": "The host name of the item’s site, as resolved during export",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": "The URL path of the item (without URL or scheme)",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "scheme",
"description": "The scheme (http or https) of the item’s site, as resolved during export",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "siteName",
"description": "The name of the resolved site of the item",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": "The full URL of the item, as resolved during export",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "ItemLanguage",
"description": null,
"fields": [
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "englishName",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "nativeName",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "INTERFACE",
"name": "Item",
"description": null,
"fields": [
{
"name": "ancestors",
"description": "Child items in the content hierarchy",
"args": [
{
"name": "hasLayout",
"description": "If set only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": "Child items in the content hierarchy",
"args": [
{
"name": "hasLayout",
"description": "If set only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": "Display name of the item",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": "Single field by name or ID",
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": "All item fields. Fields can be treated as their type to get detailed info.",
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": "Uniquely identifies id, lang, version",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": "Returns other language versions of this item",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": "Parent in the content hierarchy.",
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": "Presentation of the item",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": "Defines item fields",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": "Gets a URL link to the item",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": [
{
"kind": "OBJECT",
"name": "UnknownItem",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideComponentParamsRenderingParameters",
"ofType": null
},
{
"kind": "OBJECT",
"name": "C__StandardTemplate",
"ofType": null
},
{
"kind": "OBJECT",
"name": "C__Route",
"ofType": null
},
{
"kind": "OBJECT",
"name": "RenderEngineType",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideTracking",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideSitecoreContext",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideSection",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideRouteFields",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideMultilingual",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideLayoutTabsTab",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideLayoutTabs",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideLayoutReuse",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideItemLinkItemTemplate",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageText",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageRichText",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageNumber",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageLink",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageItemLink",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageImage",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageFile",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageDate",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageCustom",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageContentList",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageCheckbox",
"ofType": null
},
{
"kind": "OBJECT",
"name": "C__StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideContentListItemTemplate",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideComponentParams",
"ofType": null
},
{
"kind": "OBJECT",
"name": "GraphQLIntegratedDemo",
"ofType": null
},
{
"kind": "OBJECT",
"name": "GraphQLConnectedDemo",
"ofType": null
},
{
"kind": "OBJECT",
"name": "ExampleCustomRouteType",
"ofType": null
},
{
"kind": "OBJECT",
"name": "ContentBlock",
"ofType": null
},
{
"kind": "OBJECT",
"name": "C__AppRoute",
"ofType": null
},
{
"kind": "OBJECT",
"name": "JsonRendering",
"ofType": null
},
{
"kind": "OBJECT",
"name": "JavaScriptRendering",
"ofType": null
},
{
"kind": "OBJECT",
"name": "JSSLayout",
"ofType": null
},
{
"kind": "OBJECT",
"name": "App",
"ofType": null
}
]
},
{
"kind": "OBJECT",
"name": "ItemSearchResults",
"description": null,
"fields": [
{
"name": "pageInfo",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "PageInfo",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "results",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "total",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "RichTextField",
"description": null,
"fields": [
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "NumberField",
"description": null,
"fields": [
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "numberValue",
"description": "The field's value as a floating-point number",
"args": [],
"type": {
"kind": "SCALAR",
"name": "Float",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "MultilistField",
"description": null,
"fields": [
{
"name": "count",
"description": "The number of items that this field references",
"args": [],
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "targetIds",
"description": "The IDs of the referenced items",
"args": [],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "targetItems",
"description": "The item(s) that this field references",
"args": [],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "LookupField",
"description": null,
"fields": [
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "targetId",
"description": "The item ID that this field references",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "targetItem",
"description": "The item that this field references",
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "LinkField",
"description": null,
"fields": [
{
"name": "anchor",
"description": "The anchor name this link points to (e.g. #foo)",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "className",
"description": "The CSS class on this link",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "linkType",
"description": "The type of link this is (e.g. 'external')",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "queryString",
"description": "The query string on this link",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "target",
"description": "The HTML target attribute of the link (e.g. __blank)",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "targetItem",
"description": "The internal item that this link targets (null for external or other link types)",
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "text",
"description": "The body text of the link",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": "The URL/href of this link",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "TextField",
"description": null,
"fields": [
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "IntegerField",
"description": null,
"fields": [
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "intValue",
"description": "The field's value as an integer",
"args": [],
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "ImageField",
"description": null,
"fields": [
{
"name": "alt",
"description": "The alternate text for the image",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "The description of the media item",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "extension",
"description": "The extension of the media item (e.g. 'jpg', 'gif')",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "height",
"description": "Height of the image at full size",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "keywords",
"description": "The keywords of the media item",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "mimeType",
"description": "The MIME type of the media item (e.g. 'image/jpeg')",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "size",
"description": "The size, in bytes, of the media item",
"args": [],
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "src",
"description": "The URL to the media item",
"args": [
{
"name": "maxWidth",
"description": "The max width of the resulting image in px (server rescaled if needed) - Note: Size requested must be on whitelist",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "maxHeight",
"description": "The max height of the resulting image in px (server rescaled if needed) - Note: Size requested must be on whitelist",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "title",
"description": "The title of the media item",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "width",
"description": "Width of the image at full size",
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "SCALAR",
"name": "Long",
"description": null,
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "DateField",
"description": null,
"fields": [
{
"name": "dateValue",
"description": "The field's value as a UTC epoch date suitable for constructing a Javascript Date",
"args": [],
"type": {
"kind": "SCALAR",
"name": "Long",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "formattedDateValue",
"description": "The field's value as a preformatted date.",
"args": [
{
"name": "format",
"description": "A .NET-style date formatting string to format the date with",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"g\""
},
{
"name": "offset",
"description": "The offset from UTC to format the time with, in minutes. Can be used with JS' getTimezoneOffset() to format local times using the browser's configured timezone",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "0"
}
],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "CheckboxField",
"description": null,
"fields": [
{
"name": "boolValue",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "LayoutData",
"description": null,
"fields": [
{
"name": "item",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "UnknownItem",
"description": "Represents a Sitecore item whose template is not included in the schema. If you receive results of this type, consider expanding your included templates.",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideComponentParamsRenderingParameters",
"description": "/sitecore/templates/Project//Styleguide-ComponentParams Rendering Parameters template (ID: {57F1C4D3-6494-5339-A7DD-C67586B5CE4F}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "columns",
"description": "columns (ID: {80BA921F-CE56-555E-B9B7-1C6F6067D102}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "cssClass",
"description": "cssClass (ID: {E8A18F3F-6537-5B29-801E-6A6A83C46FE2}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "useCallToAction",
"description": "useCallToAction (ID: {FD936C81-D2CD-5049-85AE-E91DEBB5B34B}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "C__StandardTemplate",
"description": "/sitecore/templates/System/Templates/Standard template template (ID: {1930BBEB-7805-471A-A3BE-4858AC7CF696}). NOTE: This is a concrete type. Favor using interfaces instead of this type (e.g. StandardTemplate) for reliable querying.",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "C__Route",
"description": "/sitecore/templates/Foundation/JavaScript Services/Route template (ID: {B36BA9FD-0DC0-49C8-BEA2-E55D70E6AF28}). NOTE: This is a concrete type. Favor using interfaces instead of this type (e.g. Route) for reliable querying.",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "RenderEngineType",
"description": "/sitecore/templates/Foundation/JavaScript Services/Render Engine Type template (ID: {7FEC3963-0AC6-4743-B02C-35E6971300ED}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "engineTypeName",
"description": "Engine Type Name (ID: {90C6AAF1-9962-4DC9-A730-5E5952B3AE51}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideTracking",
"description": "/sitecore/templates/Project//-Styleguide-Tracking template (ID: {06A0F451-50F5-57BC-BC7C-02CED260FF55}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideSitecoreContext",
"description": "/sitecore/templates/Project//-Styleguide-SitecoreContext template (ID: {9896119B-75EF-5E12-A7F2-A67DBA5B59B1}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideSection",
"description": "/sitecore/templates/Project//-Styleguide-Section template (ID: {8A6F9728-6099-5F93-B782-078C0BF4D968}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {D271C160-3D12-54E2-8814-E5293C0031CC}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideRouteFields",
"description": "/sitecore/templates/Project//-Styleguide-RouteFields template (ID: {DDEDAFB7-128D-5E06-8196-FAA170B3D03C}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideMultilingual",
"description": "/sitecore/templates/Project//-Styleguide-Multilingual template (ID: {CFBD0888-3BC0-575A-8EBE-7D9CEDD341C0}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample",
"description": "This field has a translated value (ID: {A5FDEDAA-C5E4-5631-9C66-D60B1B33787F}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideLayoutTabsTab",
"description": "/sitecore/templates/Project//-Styleguide-Layout-Tabs-Tab template (ID: {2DF24150-746E-538F-9B5A-8525A4CCFDEC}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "content",
"description": "content (ID: {4A21F7E0-AF00-5E5C-9F71-2C11DA277A9B}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "title",
"description": "title (ID: {574F41F8-9EEA-54B3-BE90-5F42DE09CD88}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideLayoutTabs",
"description": "/sitecore/templates/Project//-Styleguide-Layout-Tabs template (ID: {5EC1815B-EA00-5E25-AFE0-DD92D2302EC2}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideLayoutReuse",
"description": "/sitecore/templates/Project//-Styleguide-Layout-Reuse template (ID: {251DE221-673B-5F04-B617-D8D1A020DFDD}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideItemLinkItemTemplate",
"description": "/sitecore/templates/Project//-Styleguide-ItemLink-Item-Template template (ID: {ED79C212-F8D4-5762-B160-769427A8570B}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "textField",
"description": "textField (ID: {A717C599-7639-5463-92CD-4CB470CA24FB}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageText",
"description": "/sitecore/templates/Project//-Styleguide-FieldUsage-Text template (ID: {004A5769-7C65-5E5A-8375-4311BC50481F}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample",
"description": "sample (ID: {5348E323-E7EC-5252-ACDA-0B9C79ED8704}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample2",
"description": "Customize Name Shown in Sitecore (ID: {4158F4D5-4967-5090-A3F1-3F89A9862EAE}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageRichText",
"description": "/sitecore/templates/Project//-Styleguide-FieldUsage-RichText template (ID: {E1AD788D-5496-573C-AC80-D7692143816C}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample",
"description": "sample (ID: {0B3878C5-8CC1-5A7D-B7D0-867247E5B67E}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample2",
"description": "Customize Name Shown in Sitecore (ID: {616133EB-A9A6-594A-B819-E3BF325BA394}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageNumber",
"description": "/sitecore/templates/Project//-Styleguide-FieldUsage-Number template (ID: {B0681769-342B-505E-8392-9C0A3BBDC0B0}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample",
"description": "sample (ID: {92E59006-679F-56BF-8BF4-14D427801001}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "NumberField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageLink",
"description": "/sitecore/templates/Project//-Styleguide-FieldUsage-Link template (ID: {8CFE0D37-E726-59CD-821C-6839BF2CE36D}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "emailLink",
"description": "emailLink (ID: {49EA1788-FD15-51AA-9D6B-DE5EB5D584CB}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LinkField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "externalLink",
"description": "externalLink (ID: {F190B7D9-0F2A-5B78-B938-04668F5B3C70}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LinkField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "internalLink",
"description": "internalLink (ID: {98E7F657-C3D6-52F3-BD0B-F3FCAD7C555A}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LinkField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "paramsLink",
"description": "paramsLink (ID: {84ABF43C-C93A-5680-9CC6-1285F857D256}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LinkField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageItemLink",
"description": "/sitecore/templates/Project//-Styleguide-FieldUsage-ItemLink template (ID: {8EF4CB39-9119-5153-A002-161B89E56347}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "localItemLink",
"description": "localItemLink (ID: {3A4C684F-231D-56ED-B96F-B05B20EED106}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LookupField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sharedItemLink",
"description": "sharedItemLink (ID: {1671D658-050F-51C8-9B2F-7C88239E9762}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LookupField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageImage",
"description": "/sitecore/templates/Project//-Styleguide-FieldUsage-Image template (ID: {5FF73BC4-BB50-5B16-BC22-B6244CFB5A73}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample1",
"description": "sample1 (ID: {6F0C73BD-496A-5948-9BC6-479FEC065F1B}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "ImageField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample2",
"description": "sample2 (ID: {30D8FEA1-0577-54C1-B171-5D00DBB52546}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "ImageField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageFile",
"description": "/sitecore/templates/Project//-Styleguide-FieldUsage-File template (ID: {1564AFF5-19A9-56ED-9D73-C55F40D574FD}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "file",
"description": "file (ID: {F6B2247E-B5A4-5BB3-A7CE-FD03B963CC3A}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageDate",
"description": "/sitecore/templates/Project//-Styleguide-FieldUsage-Date template (ID: {1847C9C2-9B05-5860-8207-B240D7A5B820}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "date",
"description": "date (ID: {90D59C1F-040A-5686-85C8-41BB9B7DC7C5}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "DateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "dateTime",
"description": "dateTime (ID: {9BBB647F-2BD5-5CA8-B6FC-3A5CD215D69E}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "DateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageCustom",
"description": "/sitecore/templates/Project//-Styleguide-FieldUsage-Custom template (ID: {EEA463CD-9696-5BDA-83E2-043A32DEA7D4}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "customIntField",
"description": "customIntField (ID: {992A3CC7-8F71-584B-8ADD-2056CDC3468B}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "IntegerField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageContentList",
"description": "/sitecore/templates/Project//-Styleguide-FieldUsage-ContentList template (ID: {CB2CFFE6-5481-541C-8F0C-25F248FDEB22}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "localContentList",
"description": "localContentList (ID: {78C6F9A5-3F45-5C78-8E0D-FB47E25C30B1}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sharedContentList",
"description": "sharedContentList (ID: {F7CE0AE0-AD5A-5548-824B-9F4DF15DFD60}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageCheckbox",
"description": "/sitecore/templates/Project//-Styleguide-FieldUsage-Checkbox template (ID: {41A681D2-0725-5987-ADD5-6D51CAC9F548}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "checkbox",
"description": "checkbox (ID: {CF8FED8A-51A2-58AF-A8F1-8C5D06968C5F}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "checkbox2",
"description": "checkbox2 (ID: {BF69BF19-B2F1-574D-B67E-2251978D726A}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "C__StyleguideExplanatoryComponent",
"description": "/sitecore/templates/Project//-Styleguide-Explanatory-Component template (ID: {02DBD562-2D01-5472-A7B0-54A6508AC665}). NOTE: This is a concrete type. Favor using interfaces instead of this type (e.g. StyleguideExplanatoryComponent) for reliable querying.",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideContentListItemTemplate",
"description": "/sitecore/templates/Project//-Styleguide-ContentList-Item-Template template (ID: {783417BF-451E-5AB1-AD45-EF26DCBAEC53}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "textField",
"description": "textField (ID: {5EE30CE5-99D4-55D3-A9DB-B2A22CF1B29A}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "StyleguideComponentParams",
"description": "/sitecore/templates/Project//-Styleguide-ComponentParams template (ID: {A724031B-12A6-5E05-A249-B2F0F017F5EF}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "GraphQLIntegratedDemo",
"description": "/sitecore/templates/Project//-GraphQL-IntegratedDemo template (ID: {C23F5BA8-08EA-57CC-BC17-39ECF5B512E5}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample1",
"description": "sample1 (ID: {F8F10505-6DEA-599C-B59B-0E3AC3411853}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample2",
"description": "sample2 (ID: {150FEE73-741F-51C3-8C5F-4B5F9E70626A}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LinkField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "GraphQLConnectedDemo",
"description": "/sitecore/templates/Project//-GraphQL-ConnectedDemo template (ID: {2C3D6270-6FBC-519C-8404-E92CDAD92FF5}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample1",
"description": "sample1 (ID: {F974EA20-88F4-5AA9-B102-70D033DFDA94}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "sample2",
"description": "sample2 (ID: {BB936728-192A-5723-8FDF-99981DAF4F62}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LinkField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "ExampleCustomRouteType",
"description": "/sitecore/templates/Project//-ExampleCustomRouteType template (ID: {F15CE080-38CE-5A69-BF36-6F5A50D84DBD}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "author",
"description": "author (ID: {4A3B2B16-CF1C-5084-A133-4DEC9031003B}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "content",
"description": "content (ID: {E52B47D4-B129-52E9-9B61-835920D5229C}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "headline",
"description": "headline (ID: {617B4083-A4DC-5E1F-80B7-71C11C550051}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "pageTitle",
"description": "Page Title (ID: {F8171ECB-37C5-54EE-BFED-F689C878B6E2}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "AppRoute",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "ContentBlock",
"description": "/sitecore/templates/Project//-ContentBlock template (ID: {1AEE8B0E-8DB8-58A3-805F-0092B5582459}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "content",
"description": "content (ID: {0C9E51EE-23C1-51C5-8B44-D2398BDC4F36}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {D59ADFAA-B381-5B1D-9CAD-260CCF8CEB9C}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "C__AppRoute",
"description": "/sitecore/templates/Project//-App Route template (ID: {787584C0-A057-5876-9836-F8B3708F0CAF}). NOTE: This is a concrete type. Favor using interfaces instead of this type (e.g. AppRoute) for reliable querying.",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "pageTitle",
"description": "Page Title (ID: {F8171ECB-37C5-54EE-BFED-F689C878B6E2}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "AppRoute",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "JsonRendering",
"description": "/sitecore/templates/Foundation/JavaScript Services/Json Rendering template (ID: {04646A89-996F-4EE7-878A-FFDBF1F0EF0D}).",
"fields": [
{
"name": "addFieldEditorButton",
"description": "AddFieldEditorButton (ID: {C39A90CE-0035-41BB-90F6-3C8A6EA87797}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "cacheable",
"description": "Cacheable (ID: {3D08DB46-2267-41B0-BC52-BE69FD618633}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "cacheClearingBehavior",
"description": "CacheClearingBehavior (ID: {A6D4FC1D-0803-4E0A-9145-B8C6121D6F26}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "clearOnIndexUpdate",
"description": "ClearOnIndexUpdate (ID: {F3E7E552-D7C8-469B-A150-69E4E14AB35C}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "compatibleRenderings",
"description": "Compatible Renderings (ID: {E441ABE7-2CA3-4640-AE26-3789967925D7}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "componentName",
"description": "componentName (ID: {037FE404-DD19-4BF7-8E30-4DADF68B27B0}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "componentQuery",
"description": "ComponentQuery (ID: {17BB046A-A32A-41B3-8315-81217947611B}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "customizePage",
"description": "Customize Page (ID: {705A4365-065A-4104-B755-7363F455EBC6}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "dataSource",
"description": "Data source (ID: {003A72CD-4CD6-4392-9862-41D4159929CD}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "datasourceLocation",
"description": "Datasource Location (ID: {B5B27AF1-25EF-405C-87CE-369B3A004016}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "datasourceTemplate",
"description": "Datasource Template (ID: {1A7C85E5-DC0B-490D-9187-BB1DBCB4C72F}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "Description (ID: {56E4618A-F3F2-4CB5-B69A-8A45DE578902}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "editable",
"description": "Editable (ID: {308E88F5-CD6E-4F8F-BAFE-95A47DEDEFDC}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "enableDatasourceQuery",
"description": "Enable Datasource Query (ID: {F172B787-7B88-4BD5-AE4D-6308E102EF11}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fieldEditorFields",
"description": "FieldEditorFields (ID: {C7B72114-3F04-45A0-BA43-3856A9C9FEB3}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "openPropertiesAfterAdd",
"description": "Open Properties after Add (ID: {7D8AE35F-9ED1-43B5-96A2-0A5F040D4E4E}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "pageEditorButtons",
"description": "Page Editor Buttons (ID: {A2F5D9DF-8CBA-4A1D-99EB-51ACB94CB057}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parameters",
"description": "Parameters (ID: {D01DF626-2284-4BC6-A6CA-C0A3E6D2E844}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parametersTemplate",
"description": "Parameters Template (ID: {A77E8568-1AB3-44F1-A664-B7C37EC7810D}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LookupField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "placeholder",
"description": "Placeholder (ID: {592A1CE7-ABE0-4986-9783-0A34F3961DC0}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "placeholders",
"description": "Placeholders (ID: {069A8361-B1CD-437C-8C32-A3BE78941446}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "renderAsHTML",
"description": "Render as HTML (ID: {BBB8A1E0-F966-4710-B4F4-42F267598127}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "renderingContentsResolver",
"description": "Rendering Contents Resolver (ID: {B0B15510-B138-470E-8F33-8DA2E228AAFE}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LookupField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByData",
"description": "VaryByData (ID: {8B6D532B-6128-4486-A044-CA06D90948BA}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByDevice",
"description": "VaryByDevice (ID: {C98CF969-BA71-42DA-833D-B3FC1368BA27}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByLogin",
"description": "VaryByLogin (ID: {8D9232B0-613F-440B-A2FA-DCDD80FBD33E}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByParm",
"description": "VaryByParm (ID: {3AD2506A-DC39-4B1E-959F-9D524ADDBF50}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByQueryString",
"description": "VaryByQueryString (ID: {1084D3D2-0457-456A-ABBC-EB4CC0966072}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByUser",
"description": "VaryByUser (ID: {0E54A8DC-72AD-4372-A7C7-BB4773FAD44D}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "RenderingOptions",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Caching",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "JavaScriptRendering",
"description": "/sitecore/templates/Foundation/JavaScript Services/JavaScript Rendering template (ID: {B1C80C94-792D-44DA-861E-557C6E1915F2}).",
"fields": [
{
"name": "addFieldEditorButton",
"description": "AddFieldEditorButton (ID: {19D095B4-7621-4222-A89B-505289650792}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "cacheable",
"description": "Cacheable (ID: {3D08DB46-2267-41B0-BC52-BE69FD618633}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "cacheClearingBehavior",
"description": "CacheClearingBehavior (ID: {A6D4FC1D-0803-4E0A-9145-B8C6121D6F26}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "clearOnIndexUpdate",
"description": "ClearOnIndexUpdate (ID: {F3E7E552-D7C8-469B-A150-69E4E14AB35C}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "clientScriptPath",
"description": "Client Script Path (ID: {125BB7B7-5D7D-42F3-A314-480799A9643E}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "compatibleRenderings",
"description": "Compatible Renderings (ID: {E441ABE7-2CA3-4640-AE26-3789967925D7}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "componentName",
"description": "Component Name (ID: {E6779F24-A474-4F29-A60F-83182CD1993A}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "componentQuery",
"description": "ComponentQuery (ID: {4528B82B-E79E-4BD9-820D-1BAD26260342}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "customizePage",
"description": "Customize Page (ID: {DAF096B4-BBE3-4FB1-9B2E-774A37FCCEC6}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "dataSource",
"description": "Data source (ID: {35F7859C-1E7F-4E86-87BD-65BFCF8679D8}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "datasourceLocation",
"description": "Datasource Location (ID: {B5B27AF1-25EF-405C-87CE-369B3A004016}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "datasourceTemplate",
"description": "Datasource Template (ID: {1A7C85E5-DC0B-490D-9187-BB1DBCB4C72F}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "description",
"description": "Description (ID: {1127DFEE-0183-4A10-964A-00CCEA2121AC}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "editable",
"description": "Editable (ID: {308E88F5-CD6E-4F8F-BAFE-95A47DEDEFDC}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "enableDatasourceQuery",
"description": "Enable Datasource Query (ID: {F172B787-7B88-4BD5-AE4D-6308E102EF11}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "exportedFunctionName",
"description": "Exported Function Name (ID: {E61F6FEA-BA01-44CF-A50B-369D7B18ADDA}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fieldEditorFields",
"description": "FieldEditorFields (ID: {9F069AF7-A5A1-4143-A641-14735D50B1E8}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "openPropertiesAfterAdd",
"description": "Open Properties after Add (ID: {C60E2D02-5F62-4DCF-A281-29005272C101}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "pageEditorButtons",
"description": "Page Editor Buttons (ID: {A2F5D9DF-8CBA-4A1D-99EB-51ACB94CB057}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parameters",
"description": "Parameters (ID: {BEE1D4B3-CDFC-4A2D-AA19-6775C59CAE7B}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parametersTemplate",
"description": "Parameters Template (ID: {5391FAAC-6C16-42B3-A411-49109A8502A3}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LookupField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "placeholder",
"description": "Placeholder (ID: {DA298A61-8CEB-4FA5-9A56-90F531B1C105}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "placeholders",
"description": "Placeholders (ID: {069A8361-B1CD-437C-8C32-A3BE78941446}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "renderAsHTML",
"description": "Render as HTML (ID: {BBB8A1E0-F966-4710-B4F4-42F267598127}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "renderEngineInstanceConfigurationId",
"description": "Render Engine Instance Configuration Id (ID: {1E0EBAA2-DEC4-4756-A510-2A20A4951E2D}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "renderEngineType",
"description": "Render Engine Type (ID: {135C8B8A-9F55-4B2D-9EA1-333320BADE0C}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LookupField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "renderingContentsResolver",
"description": "Rendering Contents Resolver (ID: {B0B15510-B138-470E-8F33-8DA2E228AAFE}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LookupField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "serverScriptPath",
"description": "Server Script Path (ID: {7EDACBF4-CD65-44D6-B524-3A5ED411AE05}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByData",
"description": "VaryByData (ID: {8B6D532B-6128-4486-A044-CA06D90948BA}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByDevice",
"description": "VaryByDevice (ID: {C98CF969-BA71-42DA-833D-B3FC1368BA27}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByLogin",
"description": "VaryByLogin (ID: {8D9232B0-613F-440B-A2FA-DCDD80FBD33E}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByParm",
"description": "VaryByParm (ID: {3AD2506A-DC39-4B1E-959F-9D524ADDBF50}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByQueryString",
"description": "VaryByQueryString (ID: {1084D3D2-0457-456A-ABBC-EB4CC0966072}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByUser",
"description": "VaryByUser (ID: {0E54A8DC-72AD-4372-A7C7-BB4773FAD44D}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "RenderingOptions",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Caching",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "JSSLayout",
"description": "/sitecore/templates/Foundation/JavaScript Services/JSS Layout template (ID: {35C61E90-47DD-43DD-83A8-D1C4D5119720}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "area",
"description": "Area (ID: {70DC08D9-CDA2-4F04-AA35-C11FD7138066}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "model",
"description": "Model (ID: {E9CC5A73-3C8A-4D7D-92AC-3B88C18A996A}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path_a036b2bcba0444f6a75fbae6cd242abf",
"description": "Path (ID: {A036B2BC-BA04-44F6-A75F-BAE6CD242ABF}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "placeholders",
"description": "Placeholders (ID: {80334869-86DC-4472-AA89-44CF1B2F6C9B}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Layout",
"ofType": null
},
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "App",
"description": "/sitecore/templates/Foundation/JavaScript Services/App template (ID: {061CBA15-5474-4B91-8A06-17903B102B82}).",
"fields": [
{
"name": "ancestors",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "children",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
},
{
"name": "first",
"description": "Limits the results to the first n children. Use with after for pagination.",
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "after",
"description": "Cursor value. Use with first for pagination.",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "displayName",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "field",
"description": null,
"args": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "fields",
"description": null,
"args": [
{
"name": "ownFields",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "false"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "hasChildren",
"description": null,
"args": [
{
"name": "hasLayout",
"description": "If set to true only items with existing presentation are returned",
"type": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "includeTemplateIDs",
"description": "Only consider child items with these template IDs.",
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "[]"
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": null,
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "itemUri",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "language",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemLanguage",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "languages",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "parent",
"description": null,
"args": [],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "rendered",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "template",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemTemplate",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "url",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "ItemUrl",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "version",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "Item",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "INTERFACE",
"name": "RenderingOptions",
"description": "/sitecore/templates/System/Layout/Sections/Rendering Options template (ID: {D1592226-3898-4CE2-B190-090FD5F84A4C}).",
"fields": [
{
"name": "compatibleRenderings",
"description": "Compatible Renderings (ID: {E441ABE7-2CA3-4640-AE26-3789967925D7}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "datasourceLocation",
"description": "Datasource Location (ID: {B5B27AF1-25EF-405C-87CE-369B3A004016}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "datasourceTemplate",
"description": "Datasource Template (ID: {1A7C85E5-DC0B-490D-9187-BB1DBCB4C72F}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "editable",
"description": "Editable (ID: {308E88F5-CD6E-4F8F-BAFE-95A47DEDEFDC}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "enableDatasourceQuery",
"description": "Enable Datasource Query (ID: {F172B787-7B88-4BD5-AE4D-6308E102EF11}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "pageEditorButtons",
"description": "Page Editor Buttons (ID: {A2F5D9DF-8CBA-4A1D-99EB-51ACB94CB057}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "placeholders",
"description": "Placeholders (ID: {069A8361-B1CD-437C-8C32-A3BE78941446}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "renderAsHTML",
"description": "Render as HTML (ID: {BBB8A1E0-F966-4710-B4F4-42F267598127}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "renderingContentsResolver",
"description": "Rendering Contents Resolver (ID: {B0B15510-B138-470E-8F33-8DA2E228AAFE}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "LookupField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": [
{
"kind": "OBJECT",
"name": "JsonRendering",
"ofType": null
},
{
"kind": "OBJECT",
"name": "JavaScriptRendering",
"ofType": null
}
]
},
{
"kind": "INTERFACE",
"name": "Layout",
"description": "/sitecore/templates/System/Layout/Layout template (ID: {3A45A723-64EE-4919-9D41-02FD40FD1466}).",
"fields": [
{
"name": "area",
"description": "Area (ID: {70DC08D9-CDA2-4F04-AA35-C11FD7138066}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "model",
"description": "Model (ID: {E9CC5A73-3C8A-4D7D-92AC-3B88C18A996A}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "path_a036b2bcba0444f6a75fbae6cd242abf",
"description": "Path (ID: {A036B2BC-BA04-44F6-A75F-BAE6CD242ABF}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "placeholders",
"description": "Placeholders (ID: {80334869-86DC-4472-AA89-44CF1B2F6C9B}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "MultilistField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": [
{
"kind": "OBJECT",
"name": "JSSLayout",
"ofType": null
}
]
},
{
"kind": "INTERFACE",
"name": "StyleguideExplanatoryComponent",
"description": "/sitecore/templates/Project//-Styleguide-Explanatory-Component template (ID: {02DBD562-2D01-5472-A7B0-54A6508AC665}).",
"fields": [
{
"name": "description",
"description": "description (ID: {C7115FA3-A53A-5994-BAC5-617F4095E835}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "RichTextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "heading",
"description": "heading (ID: {4724A46A-3F20-5AAA-8180-CBD31D08E478}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": [
{
"kind": "OBJECT",
"name": "StyleguideTracking",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideSitecoreContext",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideRouteFields",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideMultilingual",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideLayoutTabs",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideLayoutReuse",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageText",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageRichText",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageNumber",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageLink",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageItemLink",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageImage",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageFile",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageDate",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageCustom",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageContentList",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideFieldUsageCheckbox",
"ofType": null
},
{
"kind": "OBJECT",
"name": "C__StyleguideExplanatoryComponent",
"ofType": null
},
{
"kind": "OBJECT",
"name": "StyleguideComponentParams",
"ofType": null
}
]
},
{
"kind": "INTERFACE",
"name": "AppRoute",
"description": "/sitecore/templates/Project//-App Route template (ID: {787584C0-A057-5876-9836-F8B3708F0CAF}). Also implements Route.",
"fields": [
{
"name": "pageTitle",
"description": "Page Title (ID: {F8171ECB-37C5-54EE-BFED-F689C878B6E2}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": [
{
"kind": "OBJECT",
"name": "ExampleCustomRouteType",
"ofType": null
},
{
"kind": "OBJECT",
"name": "C__AppRoute",
"ofType": null
}
]
},
{
"kind": "INTERFACE",
"name": "Caching",
"description": "/sitecore/templates/System/Layout/Sections/Caching template (ID: {E8D2DD19-1347-4562-AE3F-310DC0B21A6C}).",
"fields": [
{
"name": "cacheable",
"description": "Cacheable (ID: {3D08DB46-2267-41B0-BC52-BE69FD618633}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "cacheClearingBehavior",
"description": "CacheClearingBehavior (ID: {A6D4FC1D-0803-4E0A-9145-B8C6121D6F26}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "TextField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "clearOnIndexUpdate",
"description": "ClearOnIndexUpdate (ID: {F3E7E552-D7C8-469B-A150-69E4E14AB35C}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByData",
"description": "VaryByData (ID: {8B6D532B-6128-4486-A044-CA06D90948BA}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByDevice",
"description": "VaryByDevice (ID: {C98CF969-BA71-42DA-833D-B3FC1368BA27}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByLogin",
"description": "VaryByLogin (ID: {8D9232B0-613F-440B-A2FA-DCDD80FBD33E}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByParm",
"description": "VaryByParm (ID: {3AD2506A-DC39-4B1E-959F-9D524ADDBF50}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByQueryString",
"description": "VaryByQueryString (ID: {1084D3D2-0457-456A-ABBC-EB4CC0966072}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "varyByUser",
"description": "VaryByUser (ID: {0E54A8DC-72AD-4372-A7C7-BB4773FAD44D}).",
"args": [],
"type": {
"kind": "OBJECT",
"name": "CheckboxField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": null,
"enumValues": null,
"possibleTypes": [
{
"kind": "OBJECT",
"name": "JsonRendering",
"ofType": null
},
{
"kind": "OBJECT",
"name": "JavaScriptRendering",
"ofType": null
}
]
},
{
"kind": "OBJECT",
"name": "NameValueListValue",
"description": null,
"fields": [
{
"name": "name",
"description": "The name of the name-value pair",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": "The value of the name-value pair",
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "NameValueListField",
"description": null,
"fields": [
{
"name": "definition",
"description": null,
"args": [],
"type": {
"kind": "OBJECT",
"name": "ItemTemplateField",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "id",
"description": "The GUID of this field.",
"args": [
{
"name": "format",
"description": ".NET GUID format to use. N = short id, B = long id, etc",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"N\""
}
],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "ID",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "jsonValue",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "JSON",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "name",
"description": null,
"args": [],
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "value",
"description": null,
"args": [],
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "values",
"description": "The key-value pairs in this field",
"args": [],
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "OBJECT",
"name": "NameValueListValue",
"ofType": null
}
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [
{
"kind": "INTERFACE",
"name": "ItemField",
"ofType": null
}
],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "OBJECT",
"name": "Query",
"description": null,
"fields": [
{
"name": "item",
"description": "Allows querying items from the content tree",
"args": [
{
"name": "path",
"description": "The item path or ID to get",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "language",
"description": "The item language to request (defaults to the default language)",
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "INTERFACE",
"name": "Item",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "layout",
"description": "Allows querying layout data for the item",
"args": [
{
"name": "site",
"description": "Site",
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
},
{
"name": "routePath",
"description": "Route path",
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
},
{
"name": "language",
"description": "Language",
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
}
],
"type": {
"kind": "OBJECT",
"name": "LayoutData",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "search",
"description": "Allows to query items through the search",
"args": [
{
"name": "where",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "INPUT_OBJECT",
"name": "ItemSearchPredicateGraphType",
"ofType": null
}
},
"defaultValue": "null"
},
{
"name": "after",
"description": null,
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "first",
"description": null,
"type": {
"kind": "SCALAR",
"name": "Int",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "orderBy",
"description": null,
"type": {
"kind": "INPUT_OBJECT",
"name": "ItemSearchOrderBy",
"ofType": null
},
"defaultValue": "null"
}
],
"type": {
"kind": "OBJECT",
"name": "ItemSearchResults",
"ofType": null
},
"isDeprecated": false,
"deprecationReason": null
}
],
"inputFields": null,
"interfaces": [],
"enumValues": null,
"possibleTypes": null
},
{
"kind": "INPUT_OBJECT",
"name": "ItemSearchPredicateGraphType",
"description": null,
"fields": null,
"inputFields": [
{
"name": "name",
"description": null,
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "value",
"description": null,
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "null"
},
{
"name": "AND",
"description": null,
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INPUT_OBJECT",
"name": "ItemSearchPredicateGraphType",
"ofType": null
}
},
"defaultValue": "null"
},
{
"name": "OR",
"description": null,
"type": {
"kind": "LIST",
"name": null,
"ofType": {
"kind": "INPUT_OBJECT",
"name": "ItemSearchPredicateGraphType",
"ofType": null
}
},
"defaultValue": "null"
},
{
"name": "operator",
"description": null,
"type": {
"kind": "ENUM",
"name": "ItemSearchOperator",
"ofType": null
},
"defaultValue": "null"
}
],
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "ENUM",
"name": "ItemSearchOperator",
"description": null,
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": [
{
"name": "EQ",
"description": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "CONTAINS",
"description": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "NEQ",
"description": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "NCONTAINS",
"description": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"possibleTypes": null
},
{
"kind": "INPUT_OBJECT",
"name": "ItemSearchOrderBy",
"description": null,
"fields": null,
"inputFields": [
{
"name": "name",
"description": null,
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "String",
"ofType": null
}
},
"defaultValue": "null"
},
{
"name": "direction",
"description": null,
"type": {
"kind": "ENUM",
"name": "Ordering",
"ofType": null
},
"defaultValue": "null"
}
],
"interfaces": null,
"enumValues": null,
"possibleTypes": null
},
{
"kind": "ENUM",
"name": "Ordering",
"description": null,
"fields": null,
"inputFields": null,
"interfaces": null,
"enumValues": [
{
"name": "ASC",
"description": null,
"isDeprecated": false,
"deprecationReason": null
},
{
"name": "DESC",
"description": null,
"isDeprecated": false,
"deprecationReason": null
}
],
"possibleTypes": null
}
],
"directives": [
{
"name": "include",
"description": "Directs the executor to include this field or fragment only when the 'if' argument is true.",
"locations": ["FIELD", "FRAGMENT_SPREAD", "INLINE_FRAGMENT"],
"args": [
{
"name": "if",
"description": "Included when true.",
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"defaultValue": "null"
}
]
},
{
"name": "skip",
"description": "Directs the executor to skip this field or fragment when the 'if' argument is true.",
"locations": ["FIELD", "FRAGMENT_SPREAD", "INLINE_FRAGMENT"],
"args": [
{
"name": "if",
"description": "Skipped when true.",
"type": {
"kind": "NON_NULL",
"name": null,
"ofType": {
"kind": "SCALAR",
"name": "Boolean",
"ofType": null
}
},
"defaultValue": "null"
}
]
},
{
"name": "deprecated",
"description": "Marks an element of a GraphQL schema as no longer supported.",
"locations": ["FIELD_DEFINITION", "ENUM_VALUE"],
"args": [
{
"name": "reason",
"description": "Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted in [Markdown](https://daringfireball.net/projects/markdown/).",
"type": {
"kind": "SCALAR",
"name": "String",
"ofType": null
},
"defaultValue": "\"No longer supported\""
}
]
}
]
}
} | json | github | https://github.com/vercel/next.js | examples/cms-sitecore-xmcloud/src/temp/GraphQLIntrospectionResult.json |
<% 1001.times do |i| %>
fixture_no_<%= i %>:
id: <%= i %>
book_id: <%= i*i %>
<% end %> | unknown | github | https://github.com/rails/rails | activerecord/test/fixtures/paragraphs.yml |
from decimal import Decimal
from sys import float_info
from unittest import TestCase
from django.utils.numberformat import format as nformat
class TestNumberFormat(TestCase):
def test_format_number(self):
self.assertEqual(nformat(1234, '.'), '1234')
self.assertEqual(nformat(1234.2, '.'), '1234.2')
self.assertEqual(nformat(1234, '.', decimal_pos=2), '1234.00')
self.assertEqual(nformat(1234, '.', grouping=2, thousand_sep=','), '1234')
self.assertEqual(nformat(1234, '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34')
self.assertEqual(nformat(-1234.33, '.', decimal_pos=1), '-1234.3')
def test_format_string(self):
self.assertEqual(nformat('1234', '.'), '1234')
self.assertEqual(nformat('1234.2', '.'), '1234.2')
self.assertEqual(nformat('1234', '.', decimal_pos=2), '1234.00')
self.assertEqual(nformat('1234', '.', grouping=2, thousand_sep=','), '1234')
self.assertEqual(nformat('1234', '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34')
self.assertEqual(nformat('-1234.33', '.', decimal_pos=1), '-1234.3')
self.assertEqual(nformat('10000', '.', grouping=3, thousand_sep='comma', force_grouping=True), '10comma000')
def test_large_number(self):
most_max = (
'{}179769313486231570814527423731704356798070567525844996'
'598917476803157260780028538760589558632766878171540458953'
'514382464234321326889464182768467546703537516986049910576'
'551282076245490090389328944075868508455133942304583236903'
'222948165808559332123348274797826204144723168738177180919'
'29988125040402618412485836{}'
)
most_max2 = (
'{}35953862697246314162905484746340871359614113505168999'
'31978349536063145215600570775211791172655337563430809179'
'07028764928468642653778928365536935093407075033972099821'
'15310256415249098018077865788815173701691026788460916647'
'38064458963316171186642466965495956524082894463374763543'
'61838599762500808052368249716736'
)
int_max = int(float_info.max)
self.assertEqual(nformat(int_max, '.'), most_max.format('', '8'))
self.assertEqual(nformat(int_max + 1, '.'), most_max.format('', '9'))
self.assertEqual(nformat(int_max * 2, '.'), most_max2.format(''))
self.assertEqual(nformat(0 - int_max, '.'), most_max.format('-', '8'))
self.assertEqual(nformat(-1 - int_max, '.'), most_max.format('-', '9'))
self.assertEqual(nformat(-2 * int_max, '.'), most_max2.format('-'))
def test_float_numbers(self):
# A float without a fractional part (3.) results in a ".0" when no
# deimal_pos is given. Contrast that with the Decimal('3.') case in
# test_decimal_numbers which doesn't return a fractional part.
self.assertEqual(nformat(3., '.'), '3.0')
def test_decimal_numbers(self):
self.assertEqual(nformat(Decimal('1234'), '.'), '1234')
self.assertEqual(nformat(Decimal('1234.2'), '.'), '1234.2')
self.assertEqual(nformat(Decimal('1234'), '.', decimal_pos=2), '1234.00')
self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=','), '1234')
self.assertEqual(nformat(Decimal('1234'), '.', grouping=2, thousand_sep=',', force_grouping=True), '12,34')
self.assertEqual(nformat(Decimal('-1234.33'), '.', decimal_pos=1), '-1234.3')
self.assertEqual(nformat(Decimal('0.00000001'), '.', decimal_pos=8), '0.00000001')
self.assertEqual(nformat(Decimal('9e-19'), '.', decimal_pos=2), '0.00')
self.assertEqual(nformat(Decimal('.00000000000099'), '.', decimal_pos=0), '0')
self.assertEqual(
nformat(Decimal('1e16'), '.', thousand_sep=',', grouping=3, force_grouping=True),
'10,000,000,000,000,000'
)
self.assertEqual(
nformat(Decimal('1e16'), '.', decimal_pos=2, thousand_sep=',', grouping=3, force_grouping=True),
'10,000,000,000,000,000.00'
)
self.assertEqual(nformat(Decimal('3.'), '.'), '3')
self.assertEqual(nformat(Decimal('3.0'), '.'), '3.0')
def test_decimal_subclass(self):
class EuroDecimal(Decimal):
"""
Wrapper for Decimal which prefixes each amount with the € symbol.
"""
def __format__(self, specifier, **kwargs):
amount = super().__format__(specifier, **kwargs)
return '€ {}'.format(amount)
price = EuroDecimal('1.23')
self.assertEqual(nformat(price, ','), '€ 1,23') | unknown | codeparrot/codeparrot-clean | ||
#! /usr/bin/python
import os
import sys
import glob
import optparse
import tempfile
import logging
import shutil
import ConfigParser
class Fail(Exception):
def __init__(self, test, msg):
self.msg = msg
self.test = test
def getMsg(self):
return '\'%s\' - %s' % (self.test.path, self.msg)
class Unsup(Exception):
def __init__(self, test):
self.test = test
def getMsg(self):
return '\'%s\'' % self.test.path
class Event(dict):
terms = [
'flags',
'type',
'size',
'config',
'sample_period',
'sample_type',
'read_format',
'disabled',
'inherit',
'pinned',
'exclusive',
'exclude_user',
'exclude_kernel',
'exclude_hv',
'exclude_idle',
'mmap',
'comm',
'freq',
'inherit_stat',
'enable_on_exec',
'task',
'watermark',
'precise_ip',
'mmap_data',
'sample_id_all',
'exclude_host',
'exclude_guest',
'exclude_callchain_kernel',
'exclude_callchain_user',
'wakeup_events',
'bp_type',
'config1',
'config2',
'branch_sample_type',
'sample_regs_user',
'sample_stack_user',
]
def add(self, data):
for key, val in data:
log.debug(" %s = %s" % (key, val))
self[key] = val
def __init__(self, name, data, base):
log.info(" Event %s" % name);
self.name = name;
self.group = ''
self.add(base)
self.add(data)
def compare_data(self, a, b):
# Allow multiple values in assignment separated by '|'
a_list = a.split('|')
b_list = b.split('|')
for a_item in a_list:
for b_item in b_list:
if (a_item == b_item):
return True
elif (a_item == '*') or (b_item == '*'):
return True
return False
def equal(self, other):
for t in Event.terms:
log.debug(" [%s] %s %s" % (t, self[t], other[t]));
if not self.has_key(t) or not other.has_key(t):
return False
if not self.compare_data(self[t], other[t]):
return False
return True
# Test file description needs to have following sections:
# [config]
# - just single instance in file
# - needs to specify:
# 'command' - perf command name
# 'args' - special command arguments
# 'ret' - expected command return value (0 by default)
#
# [eventX:base]
# - one or multiple instances in file
# - expected values assignments
class Test(object):
def __init__(self, path, options):
parser = ConfigParser.SafeConfigParser()
parser.read(path)
log.warning("running '%s'" % path)
self.path = path
self.test_dir = options.test_dir
self.perf = options.perf
self.command = parser.get('config', 'command')
self.args = parser.get('config', 'args')
try:
self.ret = parser.get('config', 'ret')
except:
self.ret = 0
self.expect = {}
self.result = {}
log.info(" loading expected events");
self.load_events(path, self.expect)
def is_event(self, name):
if name.find("event") == -1:
return False
else:
return True
def load_events(self, path, events):
parser_event = ConfigParser.SafeConfigParser()
parser_event.read(path)
# The event record section header contains 'event' word,
# optionaly followed by ':' allowing to load 'parent
# event' first as a base
for section in filter(self.is_event, parser_event.sections()):
parser_items = parser_event.items(section);
base_items = {}
# Read parent event if there's any
if (':' in section):
base = section[section.index(':') + 1:]
parser_base = ConfigParser.SafeConfigParser()
parser_base.read(self.test_dir + '/' + base)
base_items = parser_base.items('event')
e = Event(section, parser_items, base_items)
events[section] = e
def run_cmd(self, tempdir):
cmd = "PERF_TEST_ATTR=%s %s %s -o %s/perf.data %s" % (tempdir,
self.perf, self.command, tempdir, self.args)
ret = os.WEXITSTATUS(os.system(cmd))
log.info(" running '%s' ret %d " % (cmd, ret))
if ret != int(self.ret):
raise Unsup(self)
def compare(self, expect, result):
match = {}
log.info(" compare");
# For each expected event find all matching
# events in result. Fail if there's not any.
for exp_name, exp_event in expect.items():
exp_list = []
log.debug(" matching [%s]" % exp_name)
for res_name, res_event in result.items():
log.debug(" to [%s]" % res_name)
if (exp_event.equal(res_event)):
exp_list.append(res_name)
log.debug(" ->OK")
else:
log.debug(" ->FAIL");
log.info(" match: [%s] matches %s" % (exp_name, str(exp_list)))
# we did not any matching event - fail
if (not exp_list):
raise Fail(self, 'match failure');
match[exp_name] = exp_list
# For each defined group in the expected events
# check we match the same group in the result.
for exp_name, exp_event in expect.items():
group = exp_event.group
if (group == ''):
continue
for res_name in match[exp_name]:
res_group = result[res_name].group
if res_group not in match[group]:
raise Fail(self, 'group failure')
log.info(" group: [%s] matches group leader %s" %
(exp_name, str(match[group])))
log.info(" matched")
def resolve_groups(self, events):
for name, event in events.items():
group_fd = event['group_fd'];
if group_fd == '-1':
continue;
for iname, ievent in events.items():
if (ievent['fd'] == group_fd):
event.group = iname
log.debug('[%s] has group leader [%s]' % (name, iname))
break;
def run(self):
tempdir = tempfile.mkdtemp();
try:
# run the test script
self.run_cmd(tempdir);
# load events expectation for the test
log.info(" loading result events");
for f in glob.glob(tempdir + '/event*'):
self.load_events(f, self.result);
# resolve group_fd to event names
self.resolve_groups(self.expect);
self.resolve_groups(self.result);
# do the expectation - results matching - both ways
self.compare(self.expect, self.result)
self.compare(self.result, self.expect)
finally:
# cleanup
shutil.rmtree(tempdir)
def run_tests(options):
for f in glob.glob(options.test_dir + '/' + options.test):
try:
Test(f, options).run()
except Unsup, obj:
log.warning("unsupp %s" % obj.getMsg())
def setup_log(verbose):
global log
level = logging.CRITICAL
if verbose == 1:
level = logging.WARNING
if verbose == 2:
level = logging.INFO
if verbose >= 3:
level = logging.DEBUG
log = logging.getLogger('test')
log.setLevel(level)
ch = logging.StreamHandler()
ch.setLevel(level)
formatter = logging.Formatter('%(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)
USAGE = '''%s [OPTIONS]
-d dir # tests dir
-p path # perf binary
-t test # single test
-v # verbose level
''' % sys.argv[0]
def main():
parser = optparse.OptionParser(usage=USAGE)
parser.add_option("-t", "--test",
action="store", type="string", dest="test")
parser.add_option("-d", "--test-dir",
action="store", type="string", dest="test_dir")
parser.add_option("-p", "--perf",
action="store", type="string", dest="perf")
parser.add_option("-v", "--verbose",
action="count", dest="verbose")
options, args = parser.parse_args()
if args:
parser.error('FAILED wrong arguments %s' % ' '.join(args))
return -1
setup_log(options.verbose)
if not options.test_dir:
print 'FAILED no -d option specified'
sys.exit(-1)
if not options.test:
options.test = 'test*'
try:
run_tests(options)
except Fail, obj:
print "FAILED %s" % obj.getMsg();
sys.exit(-1)
sys.exit(0)
if __name__ == '__main__':
main() | unknown | codeparrot/codeparrot-clean | ||
import {mutate} from 'shared-runtime';
function useFoo(props) {
let x = [];
x.push(props.bar);
if (props.cond) {
x = {};
x = [];
x.push(props.foo);
}
mutate(x);
return x;
}
export const FIXTURE_ENTRYPOINT = {
fn: useFoo,
params: [{bar: 'bar', foo: 'foo', cond: true}],
sequentialRenders: [
{bar: 'bar', foo: 'foo', cond: true},
{bar: 'bar', foo: 'foo', cond: true},
{bar: 'bar', foo: 'foo', cond: false},
],
}; | javascript | github | https://github.com/facebook/react | compiler/packages/babel-plugin-react-compiler/src/__tests__/fixtures/compiler/ssa-renaming-with-mutation.js |
# Node.js C++ codebase
Hi! 👋 You've found the C++ code backing Node.js. This README aims to help you
get started working on it and document some idioms you may encounter while
doing so.
## Coding style
Node.js has a document detailing its [C++ coding style][]
that can be helpful as a reference for stylistic issues.
## V8 API documentation
A lot of the Node.js codebase is around what the underlying JavaScript engine,
V8, provides through its API for embedders. Knowledge of this API can also be
useful when working with native addons for Node.js written in C++, although for
new projects [N-API][] is typically the better alternative.
V8 does not provide much public API documentation beyond what is
available in its C++ header files, most importantly `v8.h`, which can be
accessed online in the following locations:
* On GitHub: [`v8.h` in Node.js][]
* On GitHub: [`v8.h` in V8][]
* On the Chromium project's Code Search application: [`v8.h` in Code Search][]
V8 also provides an [introduction for V8 embedders][],
which can be useful for understanding some of the concepts it uses in its
embedder API.
Important concepts when using V8 are the ones of [`Isolate`][]s and
[JavaScript value handles][].
V8 supports [fast API calls][], which can be useful for improving the
performance in certain cases.
## libuv API documentation
The other major dependency of Node.js is [libuv][], providing
the [event loop][] and other operating system abstractions to Node.js.
There is a [reference documentation for the libuv API][].
## File structure
The Node.js C++ files follow this structure:
The `.h` header files contain declarations, and sometimes definitions that don't
require including other headers (e.g. getters, setters, etc.). They should only
include other `.h` header files and nothing else.
The `-inl.h` header files contain definitions of inline functions from the
corresponding `.h` header file (e.g. functions marked `inline` in the
declaration or `template` functions). They always include the corresponding
`.h` header file, and can include other `.h` and `-inl.h` header files as
needed. It is not mandatory to split out the definitions from the `.h` file
into an `-inl.h` file, but it becomes necessary when there are multiple
definitions and contents of other `-inl.h` files start being used. Therefore, it
is recommended to split a `-inl.h` file when inline functions become longer than
a few lines to keep the corresponding `.h` file readable and clean. All visible
definitions from the `-inl.h` file should be declared in the corresponding `.h`
header file.
The `.cc` files contain definitions of non-inline functions from the
corresponding `.h` header file. They always include the corresponding `.h`
header file, and can include other `.h` and `-inl.h` header files as needed.
## Helpful concepts
A number of concepts are involved in putting together Node.js on top of V8 and
libuv. This section aims to explain some of them and how they work together.
<a id="isolate"></a>
### `Isolate`
The `v8::Isolate` class represents a single JavaScript engine instance, in
particular a set of JavaScript objects that can refer to each other
(the “heap”).
The `v8::Isolate` is often passed to other V8 API functions, and provides some
APIs for managing the behaviour of the JavaScript engine or querying about its
current state or statistics such as memory usage.
V8 APIs are not thread-safe unless explicitly specified. In a typical Node.js
application, the main thread and any `Worker` threads each have one `Isolate`,
and JavaScript objects from one `Isolate` cannot refer to objects from
another `Isolate`.
Garbage collection, as well as other operations that affect the entire heap,
happen on a per-`Isolate` basis.
Typical ways of accessing the current `Isolate` in the Node.js code are:
* Given a `FunctionCallbackInfo` for a [binding function][],
using `args.GetIsolate()`.
* Given a [`Environment`][], using `env->isolate()`.
* Given a [`Realm`][], using `realm->isolate()`.
* Calling `Isolate::GetCurrent()`.
### V8 JavaScript values
V8 provides classes that mostly correspond to JavaScript types; for example,
`v8::Value` is a class representing any kind of JavaScript type, with
subclasses such as `v8::Number` (which in turn has subclasses like `v8::Int32`),
`v8::Boolean` or `v8::Object`. Most types are represented by subclasses
of `v8::Object`, e.g. `v8::Uint8Array` or `v8::Date`.
<a id="internal-fields"></a>
### Internal fields
V8 provides the ability to store data in so-called “internal fields” inside
`v8::Object`s that were created as instances of C++-backed classes. The number
of fields needs to be defined when creating that class.
Both JavaScript values and `void*` pointers may be stored in such fields.
In most native Node.js objects, the first internal field is used to store a
pointer to a [`BaseObject`][] subclass, which then contains all relevant
information associated with the JavaScript object.
Typical ways of working with internal fields are:
* `obj->InternalFieldCount()` to look up the number of internal fields for an
object (`0` for regular JavaScript objects).
* `obj->GetInternalField(i)` to get a JavaScript value from an internal field.
* `obj->SetInternalField(i, v)` to store a JavaScript value in an
internal field.
* `obj->GetAlignedPointerFromInternalField(i, EmbedderDataTag::kDefault)` to get
a `void*` pointer from an internal field.
* `obj->SetAlignedPointerInInternalField(i, p, EmbedderDataTag::kDefault)` to store
a `void*` pointer in an internal field.
[`Context`][]s provide the same feature under the name “embedder data”.
<a id="js-handles"></a>
### JavaScript value handles
All JavaScript values are accessed through the V8 API through so-called handles,
of which there are two types: [`Local`][]s and [`Global`][]s.
<a id="local-handles"></a>
#### `Local` handles
A `v8::Local` handle is a temporary pointer to a JavaScript object, where
“temporary” usually means that is no longer needed after the current function
is done executing. `Local` handles can only be allocated on the C++ stack.
Most of the V8 API uses `Local` handles to work with JavaScript values or return
them from functions.
Additionally, according to [V8 public API documentation][`v8::Local<T>`], local handles
(`v8::Local<T>`) should **never** be allocated on the heap.
This disallows heap-allocated data structures containing instances of `v8::Local`
For example:
```cpp
// Don't do this
std::vector<v8::Local<v8::Value>> v1;
```
Instead, it is recommended to use `v8::LocalVector<T>` provided by V8
for such scenarios:
```cpp
v8::LocalVector<v8::Value> v1(isolate);
```
Whenever a `Local` handle is created, a `v8::HandleScope` or
`v8::EscapableHandleScope` object must exist on the stack. The `Local` is then
added to that scope and deleted along with it.
When inside a [binding function][], a `HandleScope` already exists outside of
it, so there is no need to explicitly create one.
`EscapableHandleScope`s can be used to allow a single `Local` handle to be
passed to the outer scope. This is useful when a function returns a `Local`.
The following JavaScript and C++ functions are mostly equivalent:
```js
function getFoo(obj) {
return obj.foo;
}
```
```cpp
v8::Local<v8::Value> GetFoo(v8::Local<v8::Context> context,
v8::Local<v8::Object> obj) {
v8::Isolate* isolate = Isolate::GetCurrent();
v8::EscapableHandleScope handle_scope(isolate);
// The 'foo_string' handle cannot be returned from this function because
// it is not “escaped” with `.Escape()`.
v8::Local<v8::String> foo_string =
v8::String::NewFromUtf8(isolate, "foo").ToLocalChecked();
v8::Local<v8::Value> return_value;
if (obj->Get(context, foo_string).ToLocal(&return_value)) {
return handle_scope.Escape(return_value);
} else {
// There was a JS exception! Handle it somehow.
return v8::Local<v8::Value>();
}
}
```
See [exception handling][] for more information about the usage of `.To()`,
`.ToLocalChecked()`, `v8::Maybe` and `v8::MaybeLocal` usage.
##### Casting local handles
If it is known that a `Local<Value>` refers to a more specific type, it can
be cast to that type using `.As<...>()`:
```cpp
v8::Local<v8::Value> some_value;
// CHECK() is a Node.js utilitity that works similar to assert().
CHECK(some_value->IsUint8Array());
v8::Local<v8::Uint8Array> as_uint8 = some_value.As<v8::Uint8Array>();
```
Generally, using `val.As<v8::X>()` is only valid if `val->IsX()` is true, and
failing to follow that rule may lead to crashes.
##### Detecting handle leaks
If it is expected that no `Local` handles should be created within a given
scope unless explicitly within a `HandleScope`, a `SealHandleScope` can be used.
For example, there is a `SealHandleScope` around the event loop, forcing
any functions that are called from the event loop and want to run or access
JavaScript code to create `HandleScope`s.
<a id="global-handles"></a>
#### `Global` handles
A `v8::Global` handle (sometimes also referred to by the name of its parent
class `Persistent`, although use of that is discouraged in Node.js) is a
reference to a JavaScript object that can remain active as long as the engine
instance is active.
Global handles can be either strong or weak. Strong global handles are so-called
“GC roots”, meaning that they will keep the JavaScript object they refer to
alive even if no other objects refer to them. Weak global handles do not do
that, and instead optionally call a callback when the object they refer to
is garbage-collected.
```cpp
v8::Global<v8::Object> reference;
void StoreReference(v8::Isolate* isolate, v8::Local<v8::Object> obj) {
// Create a strong reference to `obj`.
reference.Reset(isolate, obj);
}
// Must be called with a HandleScope around it.
v8::Local<v8::Object> LoadReference(v8::Isolate* isolate) {
return reference.Get(isolate);
}
```
##### `Eternal` handles
`v8::Eternal` handles are a special kind of handles similar to `v8::Global`
handles, with the exception that the values they point to are never
garbage-collected while the JavaScript Engine instance is alive, even if
the `v8::Eternal` itself is destroyed at some point. This type of handle
is rarely used.
<a id="context"></a>
### `Context`
JavaScript allows multiple global objects and sets of built-in JavaScript
objects (like the `Object` or `Array` functions) to coexist inside the same
heap. Node.js exposes this ability through the [`vm` module][].
V8 refers to each of these global objects and their associated builtins as a
`Context`.
Currently, in Node.js there is one main `Context` associated with the
principal [`Realm`][] of an [`Environment`][] instance, and a number of
subsidiary `Context`s that are created with `vm.Context` or associated with
[`ShadowRealm`][].
Most Node.js features will only work inside a context associated with a
`Realm`. The only exception at the time of writing are [`MessagePort`][]
objects. This restriction is not inherent to the design of Node.js, and a
sufficiently committed person could restructure Node.js to provide built-in
modules inside of `vm.Context`s.
Often, the `Context` is passed around for [exception handling][].
Typical ways of accessing the current `Context` in the Node.js code are:
* Given an [`Isolate`][], using `isolate->GetCurrentContext()`.
* Given an [`Environment`][], using `env->context()` to get the `Environment`'s
principal [`Realm`][]'s context.
* Given a [`Realm`][], using `realm->context()` to get the `Realm`'s
context.
<a id="event-loop"></a>
### Event loop
The main abstraction for an event loop inside Node.js is the `uv_loop_t` struct.
Typically, there is one event loop per thread. This includes not only the main
thread and Workers, but also helper threads that may occasionally be spawned
in the course of running a Node.js program.
The current event loop can be accessed using `env->event_loop()` given an
[`Environment`][] instance. The restriction of using a single event loop
is not inherent to the design of Node.js, and a sufficiently committed person
could restructure Node.js to provide e.g. the ability to run parts of Node.js
inside an event loop separate from the active thread's event loop.
<a id="environment"></a>
### `Environment`
Node.js instances are represented by the `Environment` class.
Currently, every `Environment` class is associated with:
* One [event loop][]
* One [`Isolate`][]
* One principal [`Realm`][]
The `Environment` class contains a large number of different fields for
different built-in modules that can be shared across different `Realm`
instances, for example, the inspector agent, async hooks info.
Typical ways of accessing the current `Environment` in the Node.js code are:
* Given a `FunctionCallbackInfo` for a [binding function][],
using `Environment::GetCurrent(args)`.
* Given a [`BaseObject`][], using `env()` or `self->env()`.
* Given a [`Context`][], using `Environment::GetCurrent(context)`.
This requires that `context` has been associated with the `Environment`
instance, e.g. is the main `Context` for the `Environment` or one of its
`vm.Context`s.
* Given an [`Isolate`][], using `Environment::GetCurrent(isolate)`. This looks
up the current [`Context`][] and then uses that.
<a id="realm"></a>
### `Realm`
The `Realm` class is a container for a set of JavaScript objects and functions
that are associated with a particular [ECMAScript realm][].
Each ECMAScript realm comes with a global object and a set of intrinsic
objects. An ECMAScript realm has a `[[HostDefined]]` field, which represents
the Node.js [`Realm`][] object.
Every `Realm` instance is created for a particular [`Context`][]. A `Realm`
can be a principal realm or a synthetic realm. A principal realm is created
for each `Environment`'s main [`Context`][]. A synthetic realm is created
for the [`Context`][] of each [`ShadowRealm`][] constructed from the JS API. No
`Realm` is created for the [`Context`][] of a `vm.Context`.
Native bindings and built-in modules can be evaluated in either a principal
realm or a synthetic realm.
The `Realm` class contains a large number of different fields for
different built-in modules, for example the memory for a `Uint32Array` that
the `url` module uses for storing data returned from a
`urlBinding.update()` call.
It also provides [cleanup hooks][] and maintains a list of [`BaseObject`][]
instances.
Typical ways of accessing the current `Realm` in the Node.js code are:
* Given a `FunctionCallbackInfo` for a [binding function][],
using `Realm::GetCurrent(args)`.
* Given a [`BaseObject`][], using `realm()` or `self->realm()`.
* Given a [`Context`][], using `Realm::GetCurrent(context)`.
This requires that `context` has been associated with the `Realm`
instance, e.g. is the principal `Realm` for the `Environment`.
* Given an [`Isolate`][], using `Realm::GetCurrent(isolate)`. This looks
up the current [`Context`][] and then uses its `Realm`.
<a id="isolate-data"></a>
### `IsolateData`
Every Node.js instance ([`Environment`][]) is associated with one `IsolateData`
instance that contains information about or associated with a given
[`Isolate`][].
#### String table
`IsolateData` contains a list of strings that can be quickly accessed
inside Node.js code, e.g. given an `Environment` instance `env` the JavaScript
string “name” can be accessed through `env->name_string()` without actually
creating a new JavaScript string.
### Platform
Every process that uses V8 has a `v8::Platform` instance that provides some
functionalities to V8, most importantly the ability to schedule work on
background threads.
Node.js provides a `NodePlatform` class that implements the `v8::Platform`
interface and uses libuv for providing background threading abilities.
The platform can be accessed through `isolate_data->platform()` given an
[`IsolateData`][] instance, although that only works when:
* The current Node.js instance was not started by an embedder; or
* The current Node.js instance was started by an embedder whose `v8::Platform`
implementation also implement's the `node::MultiIsolatePlatform` interface
and who passed this to Node.js.
<a id="binding-functions"></a>
### Binding functions
C++ functions exposed to JS follow a specific signature. The following example
is from `node_util.cc`:
```cpp
void ArrayBufferViewHasBuffer(const FunctionCallbackInfo<Value>& args) {
CHECK(args[0]->IsArrayBufferView());
args.GetReturnValue().Set(args[0].As<ArrayBufferView>()->HasBuffer());
}
```
(Namespaces are usually omitted through the use of `using` statements in the
Node.js source code.)
`args[n]` is a `Local<Value>` that represents the n-th argument passed to the
function. `args.This()` is the `this` value inside this function call.
`args.GetReturnValue()` is a placeholder for the return value of the function,
and provides a `.Set()` method that can be called with a boolean, integer,
floating-point number or a `Local<Value>` to set the return value.
Node.js provides various helpers for building JS classes in C++ and/or attaching
C++ functions to the exports of a built-in module:
```cpp
void Initialize(Local<Object> target,
Local<Value> unused,
Local<Context> context,
void* priv) {
Environment* env = Environment::GetCurrent(context);
SetMethod(context, target, "getaddrinfo", GetAddrInfo);
SetMethod(context, target, "getnameinfo", GetNameInfo);
// 'SetMethodNoSideEffect' means that debuggers can safely execute this
// function for e.g. previews.
SetMethodNoSideEffect(context, target, "canonicalizeIP", CanonicalizeIP);
// ... more code ...
Isolate* isolate = env->isolate();
// Building the `ChannelWrap` class for JS:
Local<FunctionTemplate> channel_wrap =
NewFunctionTemplate(isolate, ChannelWrap::New);
// Allow for 1 internal field, see `BaseObject` for details on this:
channel_wrap->InstanceTemplate()->SetInternalFieldCount(1);
channel_wrap->Inherit(AsyncWrap::GetConstructorTemplate(env));
// Set various methods on the class (i.e. on the prototype):
SetProtoMethod(isolate, channel_wrap, "queryAny", Query<QueryAnyWrap>);
SetProtoMethod(isolate, channel_wrap, "queryA", Query<QueryAWrap>);
// ...
SetProtoMethod(isolate, channel_wrap, "querySoa", Query<QuerySoaWrap>);
SetProtoMethod(isolate, channel_wrap, "getHostByAddr", Query<QueryReverseWrap>);
SetProtoMethodNoSideEffect(isolate, channel_wrap, "getServers", GetServers);
SetConstructorFunction(context, target, "ChannelWrap", channel_wrap);
}
// Run the `Initialize` function when loading this binding through
// `internalBinding('cares_wrap')` in Node.js's built-in JavaScript code:
NODE_BINDING_CONTEXT_AWARE_INTERNAL(cares_wrap, Initialize)
```
#### Registering binding functions used in bootstrap
If the C++ binding is loaded during bootstrap, in addition to registering it
using `NODE_BINDING_CONTEXT_AWARE_INTERNAL` for `internalBinding()` lookup,
it also needs to be registered with `NODE_BINDING_EXTERNAL_REFERENCE` so that
the external references can be resolved from the built-in snapshot, like this:
```cpp
#include "node_external_reference.h"
namespace node {
namespace util {
void RegisterExternalReferences(ExternalReferenceRegistry* registry) {
registry->Register(GetHiddenValue);
registry->Register(SetHiddenValue);
// ... register all C++ functions used to create FunctionTemplates.
}
} // namespace util
} // namespace node
NODE_BINDING_EXTERNAL_REFERENCE(util, node::util::RegisterExternalReferences)
```
And add the first argument passed to `NODE_BINDING_EXTERNAL_REFERENCE` to
the list of external references in `src/node_external_reference.h`:
```cpp
#define EXTERNAL_REFERENCE_LIST_BASE(V) \
V(util) \
```
Otherwise, you might see an error message like this when building the
executables:
```console
FAILED: gen/node_snapshot.cc
cd ../../; out/Release/node_mksnapshot out/Release/gen/node_snapshot.cc
Unknown external reference 0x107769200.
<unresolved>
/bin/sh: line 1: 6963 Illegal instruction: 4 out/Release/node_mksnapshot out/Release/gen/node_snapshot.cc
```
You can try using a debugger to symbolicate the external reference in order to find
out the binding functions that you forget to register. For example,
with lldb's `image lookup --address` command (with gdb it's `info symbol`):
```console
$ lldb -- out/Release/node_mksnapshot out/Release/gen/node_snapshot.cc
(lldb) run
Process 7012 launched: '/Users/joyee/projects/node/out/Release/node_mksnapshot' (x86_64)
Unknown external reference 0x1004c8200.
<unresolved>
Process 7012 stopped
(lldb) image lookup --address 0x1004c8200
Address: node_mksnapshot[0x00000001004c8200] (node_mksnapshot.__TEXT.__text + 5009920)
Summary: node_mksnapshot`node::util::GetHiddenValue(v8::FunctionCallbackInfo<v8::Value> const&) at node_util.cc:159
```
Which explains that the unregistered external reference is
`node::util::GetHiddenValue` defined in `node_util.cc`, and should be registered
using `registry->Register()` in a registration function marked by
`NODE_BINDING_EXTERNAL_REFERENCE`.
<a id="per-binding-state"></a>
#### Per-binding state
Some internal bindings, such as the HTTP parser, maintain internal state that
only affects that particular binding. In that case, one common way to store
that state is through the use of `Realm::AddBindingData`, which gives
binding functions access to an object for storing such state.
That object is always a [`BaseObject`][].
In the binding, call `SET_BINDING_ID()` with an identifier for the binding
type. For example, for `http_parser::BindingData`, the identifier can be
`http_parser_binding_data`.
If the binding should be supported in a snapshot, the id and the
fully-specified class name should be added to the `SERIALIZABLE_BINDING_TYPES`
list in `base_object_types.h`, and the class should implement the serialization
and deserialization methods. See the comments of `SnapshotableObject` on how to
implement them. Otherwise, add the id and the class name to the
`UNSERIALIZABLE_BINDING_TYPES` list instead.
```cpp
// In base_object_types.h, add the binding to either
// UNSERIALIZABLE_BINDING_TYPES or SERIALIZABLE_BINDING_TYPES.
// The second parameter is a descriptive name of the class, which is
// usually the fully-specified class name.
#define UNSERIALIZABLE_BINDING_TYPES(V) \
V(http_parser_binding_data, http_parser::BindingData)
// In the HTTP parser source code file:
class BindingData : public BaseObject {
public:
BindingData(Realm* realm, Local<Object> obj) : BaseObject(realm, obj) {}
SET_BINDING_ID(http_parser_binding_data)
std::vector<char> parser_buffer;
bool parser_buffer_in_use = false;
// ...
};
// Available for binding functions, e.g. the HTTP Parser constructor:
static void New(const FunctionCallbackInfo<Value>& args) {
BindingData* binding_data = Realm::GetBindingData<BindingData>(args);
new Parser(binding_data, args.This());
}
// ... because the initialization function told the Realm to store the
// BindingData object:
void InitializeHttpParser(Local<Object> target,
Local<Value> unused,
Local<Context> context,
void* priv) {
Realm* realm = Realm::GetCurrent(context);
BindingData* const binding_data = realm->AddBindingData<BindingData>(target);
if (binding_data == nullptr) return;
Local<FunctionTemplate> t = NewFunctionTemplate(realm->isolate(), Parser::New);
...
}
```
### Argument validation in public APIs vs. internal code
#### Public API argument sanitization
When arguments come directly from user code, Node.js will typically validate them at the
JavaScript layer and throws user-friendly
[errors](https://github.com/nodejs/node/blob/main/doc/contributing/using-internal-errors.md)
(e.g., `ERR_INVALID_*`), if they are invalid. This helps end users
quickly understand and fix mistakes in their own code.
This approach ensures that the error message pinpoints which argument is wrong
and how it should be fixed. Additionally, problems in user code do not cause
mysterious crashes or hard-to-diagnose failures deeper in the engine.
Example from `zlib.js`:
```js
function crc32(data, value = 0) {
if (typeof data !== 'string' && !isArrayBufferView(data)) {
throw new ERR_INVALID_ARG_TYPE('data', ['Buffer', 'TypedArray', 'DataView','string'], data);
}
validateUint32(value, 'value');
return crc32Native(data, value);
}
```
The corresponding C++ assertion code for the above example from it's binding `node_zlib.cc`:
```cpp
CHECK(args[0]->IsArrayBufferView() || args[0]->IsString());
CHECK(args[1]->IsUint32());
```
#### Internal code and C++ binding checks
Inside Node.js’s internal layers, especially the C++ [binding function][]s
typically assume their arguments have already been checked and sanitized
by the upper-level (JavaScript) callers. As a result, internal C++ code
often just uses `CHECK()` or similar assertions to confirm that the
types/values passed in are correct. If that assertion fails, Node.js will
crash or abort with an internal diagnostic message. This is to avoid
re-validating every internal function argument repeatedly which can slow
down the system.
However, in a less common case where the API is implemented completely in
C++, the arguments would be validated directly in C++, with the errors
thrown using `THROW_ERR_INVALID_*` macros from `src/node_errors.h`.
For example in `worker_threads.moveMessagePortToContext`:
```cpp
void MessagePort::MoveToContext(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
if (!args[0]->IsObject() ||
!env->message_port_constructor_template()->HasInstance(args[0])) {
return THROW_ERR_INVALID_ARG_TYPE(env,
"The \"port\" argument must be a MessagePort instance");
}
// ...
}
```
<a id="exception-handling"></a>
### Exception handling
The V8 engine provides multiple features to work with JavaScript exceptions,
as C++ exceptions are disabled inside of Node.js:
#### Maybe types
V8 provides the `v8::Maybe<T>` and `v8::MaybeLocal<T>` types, typically used
as return values from API functions that can run JavaScript code and therefore
can throw exceptions.
Conceptually, the idea is that every `v8::Maybe<T>` is either empty (checked
through `.IsNothing()`) or holds a value of type `T` (checked through
`.IsJust()`). If the `Maybe` is empty, then a JavaScript exception is pending.
A typical way of accessing the value is using the `.To()` function, which
returns a boolean indicating success of the operation (i.e. the `Maybe` not
being empty) and taking a pointer to a `T` to store the value if there is one.
##### Checked conversion
`maybe.Check()` can be used to assert that the maybe is not empty, i.e. crash
the process otherwise. `maybe.FromJust()` (aka `maybe.ToChecked()`) can be used
to access the value and crash the process if it is not set.
This should only be performed if it is actually sure that the operation has
not failed. A lot of the Node.js source code does **not** follow this rule, and
can be brought to crash through this.
In particular, it is often not safe to assume that an operation does not throw
an exception, even if it seems like it would not do that.
The most common reasons for this are:
* Calls to functions like `object->Get(...)` or `object->Set(...)` may fail on
most objects, if the `Object.prototype` object has been modified from userland
code that added getters or setters.
* Calls that invoke _any_ JavaScript code, including JavaScript code that is
provided from Node.js internals or V8 internals, will fail when JavaScript
execution is being terminated. This typically happens inside Workers when
`worker.terminate()` is called, but it can also affect the main thread when
e.g. Node.js is used as an embedded library. These exceptions can happen at
any point.
It is not always obvious whether a V8 call will enter JavaScript. In addition
to unexpected getters and setters, accessing some types of built-in objects
like `Map`s and `Set`s can also run V8-internal JavaScript code.
##### MaybeLocal
`v8::MaybeLocal<T>` is a variant of `v8::Maybe<T>` that is either empty or
holds a value of type `Local<T>`. It has methods that perform the same
operations as the methods of `v8::Maybe`, but with different names:
| `Maybe` | `MaybeLocal` |
| -------------------- | ------------------------------ |
| `maybe.IsNothing()` | `maybe_local.IsEmpty()` |
| `maybe.IsJust()` | `!maybe_local.IsEmpty()` |
| `maybe.To(&value)` | `maybe_local.ToLocal(&local)` |
| `maybe.ToChecked()` | `maybe_local.ToLocalChecked()` |
| `maybe.FromJust()` | `maybe_local.ToLocalChecked()` |
| `maybe.Check()` | – |
| `v8::Nothing<T>()` | `v8::MaybeLocal<T>()` |
| `v8::Just<T>(value)` | `v8::MaybeLocal<T>(value)` |
##### Handling empty `Maybe`s
Usually, the best approach to encountering an empty `Maybe` is to just return
from the current function as soon as possible, and let execution in JavaScript
land resume. If the empty `Maybe` is encountered inside a nested function,
is may be a good idea to use a `Maybe` or `MaybeLocal` for the return type
of that function and pass information about pending JavaScript exceptions along
that way.
Generally, when an empty `Maybe` is encountered, it is not valid to attempt
to perform further calls to APIs that return `Maybe`s.
A typical pattern for dealing with APIs that return `Maybe` and `MaybeLocal` is
using `.ToLocal()` and `.To()` and returning early in case there is an error:
```cpp
// This could also return a v8::MaybeLocal<v8::Number>, for example.
v8::Maybe<double> SumNumbers(v8::Local<v8::Context> context,
v8::Local<v8::Array> array_of_integers) {
v8::Isolate* isolate = Isolate::GetCurrent();
v8::HandleScope handle_scope(isolate);
double sum = 0;
for (uint32_t i = 0; i < array_of_integers->Length(); i++) {
v8::Local<v8::Value> entry;
if (!array_of_integers->Get(context, i).ToLocal(&entry)) {
// Oops, we might have hit a getter that throws an exception!
// It's better to not continue return an empty (“nothing”) Maybe.
return v8::Nothing<double>();
}
if (!entry->IsNumber()) {
// Let's just skip any non-numbers. It would also be reasonable to throw
// an exception here, e.g. using the error system in src/node_errors.h,
// and then to return an empty Maybe again.
continue;
}
// This cast is valid, because we've made sure it's really a number.
v8::Local<v8::Number> entry_as_number = entry.As<v8::Number>();
sum += entry_as_number->Value();
}
return v8::Just(sum);
}
// Function that is exposed to JS:
void SumNumbers(const v8::FunctionCallbackInfo<v8::Value>& args) {
// This will crash if the first argument is not an array. Let's assume we
// have performed type checking in a JavaScript wrapper function.
CHECK(args[0]->IsArray());
double sum;
if (!SumNumbers(args.GetIsolate()->GetCurrentContext(),
args[0].As<v8::Array>()).To(&sum)) {
// Nothing to do, we can just return directly to JavaScript.
return;
}
args.GetReturnValue().Set(sum);
}
```
#### TryCatch
If there is a need to catch JavaScript exceptions in C++, V8 provides the
`v8::TryCatch` type for doing so, which we wrap into our own
`node::errors::TryCatchScope` in Node.js. The latter has the additional feature
of providing the ability to shut down the program in the typical Node.js way
(printing the exception + stack trace) if an exception is caught.
A `TryCatch` will catch regular JavaScript exceptions, as well as termination
exceptions such as the ones thrown by `worker.terminate()` calls.
In the latter case, the `try_catch.HasTerminated()` function will return `true`,
and the exception object will not be a meaningful JavaScript value.
`try_catch.ReThrow()` should not be used in this case.
<a id="libuv-handles-and-requests"></a>
### libuv handles and requests
Two central concepts when working with libuv are handles and requests.
Handles are subclasses of the `uv_handle_t` “class”, and generally refer to
long-lived objects that can emit events multiple times, such as network sockets
or file system watchers.
In Node.js, handles are often managed through a [`HandleWrap`][] subclass.
Requests are one-time asynchronous function calls on the event loop, such as
file system requests or network write operations, that either succeed or fail.
In Node.js, requests are often managed through a [`ReqWrap`][] subclass.
### Environment cleanup
When a Node.js [`Environment`][] is destroyed, it generally needs to clean up
any resources owned by it, e.g. memory or libuv requests/handles.
<a id="cleanup-hooks"></a>
#### Cleanup hooks
Cleanup hooks are provided that run before the [`Environment`][] or the
[`Realm`][] is destroyed. They can be added and removed by using
`env->AddCleanupHook(callback, hint);` and
`env->RemoveCleanupHook(callback, hint);`, or
`realm->AddCleanupHook(callback, hint);` and
`realm->RemoveCleanupHook(callback, hint);` respectively, where callback takes
a `void* hint` argument.
Inside these cleanup hooks, new asynchronous operations _may_ be started on the
event loop, although ideally that is avoided as much as possible.
For every [`ReqWrap`][] and [`HandleWrap`][] instance, the cleanup of the
associated libuv objects is performed automatically, i.e. handles are closed
and requests are cancelled if possible.
#### Cleanup realms and BaseObjects
Realm cleanup depends on the realm types. All realms are destroyed when the
[`Environment`][] is destroyed with the cleanup hook. A [`ShadowRealm`][] can
also be destroyed by the garbage collection when there is no strong reference
to it.
Every [`BaseObject`][] is tracked with its creation realm and will be destroyed
when the realm is tearing down.
#### Closing libuv handles
If a libuv handle is not managed through a [`HandleWrap`][] instance,
it needs to be closed explicitly. Do not use `uv_close()` for that, but rather
`env->CloseHandle()`, which works the same way but keeps track of the number
of handles that are still closing.
#### Closing libuv requests
There is no way to abort libuv requests in general. If a libuv request is not
managed through a [`ReqWrap`][] instance, the
`env->IncreaseWaitingRequestCounter()` and
`env->DecreaseWaitingRequestCounter()` functions need to be used to keep track
of the number of active libuv requests.
#### Calling into JavaScript
Calling into JavaScript is not allowed during cleanup. Worker threads explicitly
forbid this during their shutdown sequence, but the main thread does not for
backwards compatibility reasons.
When calling into JavaScript without using [`MakeCallback()`][], check the
`env->can_call_into_js()` flag and do not proceed if it is set to `false`.
## Classes associated with JavaScript objects
### `MemoryRetainer`
A large number of classes in the Node.js C++ codebase refer to other objects.
The `MemoryRetainer` class is a helper for annotating C++ classes with
information that can be used by the heap snapshot builder in V8, so that
memory retained by C++ can be tracked in V8 heap snapshots captured in
Node.js applications.
Inheriting from the `MemoryRetainer` class enables objects (both from JavaScript
and C++) to refer to instances of that class, and in turn enables that class
to point to other objects as well, including native C++ types
such as `std::string` and track their memory usage.
This can be useful for debugging memory leaks.
The [`memory_tracker.h`][] header file explains how to use this class.
<a id="baseobject"></a>
### `BaseObject`
A frequently recurring situation is that a JavaScript object and a C++ object
need to be tied together. `BaseObject` is the main abstraction for that in
Node.js, and most classes that are associated with JavaScript objects are
subclasses of it. It is defined in [`base_object.h`][].
Every `BaseObject` is associated with one [`Realm`][] and one
`v8::Object`. The `v8::Object` needs to have at least one [internal field][]
that is used for storing the pointer to the C++ object. In order to ensure this,
the V8 `SetInternalFieldCount()` function is usually used when setting up the
class from C++.
The JavaScript object can be accessed as a `v8::Local<v8::Object>` by using
`self->object()`, given a `BaseObject` named `self`.
Accessing a `BaseObject` from a `v8::Local<v8::Object>` (frequently that is
`args.This()` in a [binding function][]) can be done using
the `Unwrap<T>(obj)` function, where `T` is a subclass of `BaseObject`.
A helper for this is the `ASSIGN_OR_RETURN_UNWRAP` macro that returns from the
current function if unwrapping fails (typically that means that the `BaseObject`
has been deleted earlier).
```cpp
void Http2Session::Request(const FunctionCallbackInfo<Value>& args) {
Http2Session* session;
ASSIGN_OR_RETURN_UNWRAP(&session, args.This());
Environment* env = session->env();
Local<Context> context = env->context();
Isolate* isolate = env->isolate();
// ...
// The actual function body, which can now use the `session` object.
// ...
}
```
#### Lifetime management
The `BaseObject` class comes with a set of features that allow managing the
lifetime of its instances, either associating it with the lifetime of the
corresponding JavaScript object or untying the two.
The `BaseObject::MakeWeak()` method turns the underlying [`Global`][] handle
into a weak one, and makes it so that the `BaseObject::OnGCCollect()` virtual
method is called when the JavaScript object is garbage collected. By default,
that methods deletes the `BaseObject` instance.
`BaseObject::ClearWeak()` undoes this effect.
It generally makes sense to call `MakeWeak()` in the constructor of a
`BaseObject` subclass, unless that subclass is referred to by e.g. the event
loop, as is the case for the [`HandleWrap`][] and [`ReqWrap`][] classes.
In addition, there are two kinds of smart pointers that can be used to refer
to `BaseObject`s.
`BaseObjectWeakPtr<T>` is similar to `std::weak_ptr<T>`, but holds on to
an object of a `BaseObject` subclass `T` and integrates with the lifetime
management of the former. When the `BaseObject` no longer exists, e.g. when
it was garbage collected, accessing it through `weak_ptr.get()` will return
`nullptr`.
`BaseObjectPtr<T>` is similar to `std::shared_ptr<T>`, but also holds on to
objects of a `BaseObject` subclass `T`. While there are `BaseObjectPtr`s
pointing to a given object, the `BaseObject` will always maintain a strong
reference to its associated JavaScript object. This can be useful when one
`BaseObject` refers to another `BaseObject` and wants to make sure it stays
alive during the lifetime of that reference.
A `BaseObject` can be “detached” through the `BaseObject::Detach()` method.
In this case, it will be deleted once the last `BaseObjectPtr` referring to
it is destroyed. There must be at least one such pointer when `Detach()` is
called. This can be useful when one `BaseObject` fully owns another
`BaseObject`.
<a id="asyncwrap"></a>
### `AsyncWrap`
`AsyncWrap` is a subclass of `BaseObject` that additionally provides tracking
functions for asynchronous calls. It is commonly used for classes whose methods
make calls into JavaScript without any JavaScript stack below, i.e. more or less
directly from the event loop. It is defined in [`async_wrap.h`][].
Every `AsyncWrap` subclass has a “provider type”. A list of provider types is
maintained in `src/async_wrap.h`.
Every `AsyncWrap` instance is associated with two numbers, the “async id”
and the “async trigger id”. The “async id” is generally unique per `AsyncWrap`
instance, and only changes when the object is re-used in some way.
See the [`async_hooks` module][] documentation for more information about how
this information is provided to async tracking tools.
<a id="makecallback"></a>
#### `MakeCallback`
The `AsyncWrap` class has a set of methods called `MakeCallback()`, with the
intention of the naming being that it is used to “make calls back into
JavaScript” from the event loop, rather than making callbacks in some way.
(As the naming has made its way into the Node.js public API, it's not worth
the breakage of fixing it).
`MakeCallback()` generally calls a method on the JavaScript object associated
with the current `AsyncWrap`, and informs async tracking code about these calls
as well as takes care of running the `process.nextTick()` and `Promise` task
queues once it returns.
Before calling `MakeCallback()`, it is typically necessary to enter both a
`HandleScope` and a `Context::Scope`.
```cpp
void StatWatcher::Callback(uv_fs_poll_t* handle,
int status,
const uv_stat_t* prev,
const uv_stat_t* curr) {
// Get the StatWatcher instance associated with this call from libuv,
// StatWatcher is a subclass of AsyncWrap.
StatWatcher* wrap = ContainerOf(&StatWatcher::watcher_, handle);
Environment* env = wrap->env();
HandleScope handle_scope(env->isolate());
Context::Scope context_scope(env->context());
// Transform 'prev' and 'curr' into an array:
Local<Value> arr = ...;
Local<Value> argv[] = { Integer::New(env->isolate(), status), arr };
wrap->MakeCallback(env->onchange_string(), arraysize(argv), argv);
}
```
See [Callback scopes][] for more information.
<a id="handlewrap"></a>
### `HandleWrap`
`HandleWrap` is a subclass of `AsyncWrap` specifically designed to make working
with [libuv handles][] easier. It provides the `.ref()`, `.unref()` and
`.hasRef()` methods as well as `.close()` to enable easier lifetime management
from JavaScript. It is defined in [`handle_wrap.h`][].
`HandleWrap` instances are [cleaned up][cleanup hooks] automatically when the
current Node.js [`Environment`][] is destroyed, e.g. when a Worker thread stops.
`HandleWrap` also provides facilities for diagnostic tooling to get an
overview over libuv handles managed by Node.js.
<a id="reqwrap"></a>
### `ReqWrap`
`ReqWrap` is a subclass of `AsyncWrap` specifically designed to make working
with [libuv requests][] easier. It is defined in [`req_wrap.h`][].
In particular, its `Dispatch()` method is designed to avoid the need to keep
track of the current count of active libuv requests.
`ReqWrap` also provides facilities for diagnostic tooling to get an
overview over libuv handles managed by Node.js.
<a id="callback-scopes"></a>
### `CppgcMixin`
V8 comes with a trace-based C++ garbage collection library called
[Oilpan][], whose API is in headers under`deps/v8/include/cppgc`.
In this document we refer to it as `cppgc` since that's the namespace
of the library.
C++ objects managed using `cppgc` are allocated in the V8 heap
and traced by V8's garbage collector. The `cppgc` library provides
APIs for embedders to create references between cppgc-managed objects
and other objects in the V8 heap (such as JavaScript objects or other
objects in the V8 C++ API that can be passed around with V8 handles)
in a way that's understood by V8's garbage collector.
This helps avoiding accidental memory leaks and use-after-frees coming
from incorrect cross-heap reference tracking, especially when there are
cyclic references. This is what powers the
[unified heap design in Chromium][] to avoid cross-heap memory issues,
and it's being rolled out in Node.js to reap similar benefits.
For general guidance on how to use `cppgc`, see the
[Oilpan documentation in Chromium][]. In Node.js there is a helper
mixin `node::CppgcMixin` from `cppgc_helpers.h` to help implementing
`cppgc`-managed wrapper objects with a [`BaseObject`][]-like interface.
`cppgc`-manged objects in Node.js internals should extend this mixin,
while non-`cppgc`-managed objects typically extend `BaseObject` - the
latter are being migrated to be `cppgc`-managed wherever it's beneficial
and practical. Typically `cppgc`-managed objects are more efficient to
keep track of (which lowers initialization cost) and work better
with V8's GC scheduling.
A `cppgc`-managed native wrapper should look something like this:
```cpp
#include "cppgc_helpers.h"
// CPPGC_MIXIN is a helper macro for inheriting from cppgc::GarbageCollected,
// cppgc::NameProvider and public CppgcMixin. Per cppgc rules, it must be
// placed at the left-most position in the class hierarchy.
class MyWrap final : CPPGC_MIXIN(MyWrap) {
public:
SET_CPPGC_NAME(MyWrap) // Sets the heap snapshot name to "Node / MyWrap"
// The constructor can only be called by `cppgc::MakeGarbageCollected()`.
MyWrap(Environment* env, v8::Local<v8::Object> object);
// Helper for constructing MyWrap via `cppgc::MakeGarbageCollected()`.
// Can be invoked by other C++ code outside of this class if necessary.
// In that case the raw pointer returned may need to be managed by
// cppgc::Persistent<> or cppgc::Member<> with corresponding tracing code.
static MyWrap* New(Environment* env, v8::Local<v8::Object> object);
// Binding method to help constructing MyWrap in JavaScript.
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
void Trace(cppgc::Visitor* visitor) const final;
}
```
If the wrapper needs to perform cleanups when it's destroyed and that
cleanup relies on a living Node.js `Realm`, it should implement a
pattern like this:
```cpp
~MyWrap() { this->Finalize(); }
void Clean(Realm* env) override {
// Do cleanup that relies on a living Realm.
}
```
`cppgc::GarbageCollected` types are expected to implement a
`void Trace(cppgc::Visitor* visitor) const` method. When they are the
final class in the hierarchy, this method must be marked `final`. For
classes extending `node::CppgcMixn`, this should typically dispatch a
call to `CppgcMixin::Trace()` first, then trace any additional owned data
it has. See `deps/v8/include/cppgc/garbage-collected.h` see what types of
data can be traced.
```cpp
void MyWrap::Trace(cppgc::Visitor* visitor) const {
CppgcMixin::Trace(visitor);
visitor->Trace(...); // Trace any additional data MyWrap has
}
```
#### Constructing and wrapping `cppgc`-managed objects
C++ objects subclassing `node::CppgcMixin` have a counterpart JavaScript object.
The two references each other internally - this cycle is well-understood by V8's
garbage collector and can be managed properly.
Similar to `BaseObject`s, `cppgc`-managed wrappers objects must be created from
object templates with at least `node::CppgcMixin::kInternalFieldCount` internal
fields. To unify handling of the wrappers, the internal fields of
`node::CppgcMixin` wrappers would have the same layout as `BaseObject`.
```cpp
// To create the v8::FunctionTemplate that can be used to instantiate a
// v8::Function for that serves as the JavaScript constructor of MyWrap:
Local<FunctionTemplate> ctor_template = NewFunctionTemplate(isolate, MyWrap::New);
ctor_template->InstanceTemplate()->SetInternalFieldCount(
ContextifyScript::kInternalFieldCount);
```
`cppgc::GarbageCollected` objects should not be allocated with usual C++
primitives (e.g. using `new` or `std::make_unique` is forbidden). Instead
they must be allocated using `cppgc::MakeGarbageCollected` - this would
allocate them in the V8 heap and allow V8's garbage collector to trace them.
It's recommended to use a `New` method to wrap the `cppgc::MakeGarbageCollected`
call so that external C++ code does not need to know about its memory management
scheme to construct it.
```cpp
MyWrap* MyWrap::New(Environment* env, v8::Local<v8::Object> object) {
// Per cppgc rules, the constructor of MyWrap cannot be invoked directly.
// It's recommended to implement a New() static method that prepares
// and forwards the necessary arguments to cppgc::MakeGarbageCollected()
// and just return the raw pointer around - do not use any C++ smart
// pointer with this, as this is not managed by the native memory
// allocator but by V8.
return cppgc::MakeGarbageCollected<MyWrap>(
env->cppgc_allocation_handle(), env, object);
}
// Binding method to be invoked by JavaScript.
void MyWrap::New(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
Isolate* isolate = env->isolate();
Local<Context> context = env->context();
CHECK(args.IsConstructCall());
// Get more arguments from JavaScript land if necessary.
New(env, args.This());
}
```
In the constructor of `node::CppgcMixin` types, use
`node::CppgcMixin::Wrap()` to finish the wrapping so that
V8 can trace the C++ object from the JavaScript object.
```cpp
MyWrap::MyWrap(Environment* env, v8::Local<v8::Object> object) {
// This cannot invoke the mixin constructor and has to invoke via a static
// method from it, per cppgc rules.
CppgcMixin::Wrap(this, env, object);
}
```
#### Unwrapping `cppgc`-managed wrapper objects
When given a `v8::Local<v8::Object>` that is known to be the JavaScript
wrapper object for `MyWrap`, uses the `node::CppgcMixin::Unwrap()` to
get the C++ object from it:
```cpp
v8::Local<v8::Object> object = ...; // Obtain the JavaScript from somewhere.
MyWrap* wrap = CppgcMixin::Unwrap<MyWrap>(object);
```
Similar to `ASSIGN_OR_RETURN_UNWRAP`, there is a `ASSIGN_OR_RETURN_UNWRAP_CPPGC`
that can be used in binding methods to return early if the JavaScript object does
not wrap the desired type. And similar to `BaseObject`, `node::CppgcMixin`
provides `env()` and `object()` methods to quickly access the associated
`node::Environment` and its JavaScript wrapper object.
```cpp
ASSIGN_OR_RETURN_UNWRAP_CPPGC(&wrap, object);
CHECK_EQ(wrap->object(), object);
```
#### Creating C++ to JavaScript references in cppgc-managed objects
Unlike `BaseObject` which typically uses a `v8::Global` (either weak or strong)
to reference an object from the V8 heap, cppgc-managed objects are expected to
use `v8::TracedReference` (which supports any `v8::Data`). For example if the
`MyWrap` object owns a `v8::UnboundScript`, in the class body the reference
should be declared as
```cpp
class MyWrap : ... {
v8::TracedReference<v8::UnboundScript> script;
}
```
V8's garbage collector traces the references from `MyWrap` through the
`MyWrap::Trace()` method, which should call `cppgc::Visitor::Trace` on the
`v8::TracedReference`.
```cpp
void MyWrap::Trace(cppgc::Visitor* visitor) const {
CppgcMixin::Trace(visitor);
visitor->Trace(script); // v8::TracedReference is supported by cppgc::Visitor
}
```
As long as a `MyWrap` object is alive, the `v8::UnboundScript` in its
`v8::TracedReference` will be kept alive. When the `MyWrap` object is no longer
reachable from the V8 heap, and there are no other references to the
`v8::UnboundScript` it owns, the `v8::UnboundScript` will be garbage collected
along with its owning `MyWrap`. The reference will also be automatically
captured in the heap snapshots.
#### Creating JavaScript to C++ references for cppgc-managed objects
To create a reference from another JavaScript object to a C++ wrapper
extending `node::CppgcMixin`, just create a JavaScript to JavaScript
reference using the JavaScript side of the wrapper, which can be accessed
using `node::CppgcMixin::object()`.
```cpp
MyWrap* wrap = ....; // Obtain a reference to the cppgc-managed object.
Local<Object> referrer = ...; // This is the referrer object.
// To reference the C++ wrap from the JavaScript referrer, simply creates
// a usual JavaScript property reference - the key can be a symbol or a
// number too if necessary, or it can be a private symbol property added
// using SetPrivate(). wrap->object() can also be passed to the JavaScript
// land, which can be referenced by any JavaScript objects in an invisible
// manner using a WeakMap or being inside a closure.
referrer->Set(
context, FIXED_ONE_BYTE_STRING(isolate, "ref"), wrap->object()
).ToLocalChecked();
```
#### Creating references between cppgc-managed objects and `BaseObject`s
This is currently unsupported with the existing helpers. If this has
to be done, new helpers must be implemented first. Consult the cppgc
headers when trying to implement it.
Another way to work around it is to always do the migration bottom-to-top.
If a cppgc-managed object needs to reference a `BaseObject`, convert
that `BaseObject` to be cppgc-managed first, and then use `cppgc::Member`
to create the references.
#### Lifetime and cleanups of cppgc-managed objects
Typically, a newly created cppgc-managed wrapper object should be held alive
by the JavaScript land (for example, by being returned by a method and
staying alive in a closure). Long-lived cppgc objects can also
be held alive from C++ using persistent handles (see
`deps/v8/include/cppgc/persistent.h`) or as members of other living
cppgc-managed objects (see `deps/v8/include/cppgc/member.h`) if necessary.
When a cppgc-managed object is no longer reachable in the heap, its destructor
will be invoked by the garbage collection, which can happen after the `Realm`
is already gone, or after any object it references is gone. It is therefore
unsafe to invoke V8 APIs directly in the destructors. To ensure safety,
the cleanups of a cppgc-managed object should adhere to different patterns,
depending on what it needs to do:
1. If it does not need to do any non-trivial cleanup, nor does its members, just use
the default destructor. Cleanup of `v8::TracedReference` and
`cppgc::Member` are already handled automatically by V8 so if they are all the
non-trivial members the class has, this case applies.
2. If the cleanup relies on a living `Realm`, but does not need to access V8
APIs, the class should use this pattern in its class body:
```cpp
~MyWrap() { this->Finalize(); }
void Clean(Realm* env) override {
// Do cleanup that relies on a living Realm. This would be
// called by CppgcMixin::Finalize() first during Realm shutdown,
// while the Realm is still alive. If the destructor calls
// Finalize() again later during garbage collection that happens after
// Realm shutdown, Clean() would be skipped, preventing
// invalid access to the Realm.
}
```
If implementers want to call `Finalize()` from `Clean()` again, they
need to make sure that calling `Clean()` recursively is safe.
3. If the cleanup relies on access to the V8 heap, including using any V8
handles, in addition to 2, it should use the `CPPGC_USING_PRE_FINALIZER`
macro (from the [`cppgc/prefinalizer.h` header][]) in the private
section of its class body:
```cpp
private:
CPPGC_USING_PRE_FINALIZER(MyWrap, Finalize);
```
Both the destructor and the pre-finalizer are always called on the thread
in which the object is created.
It's worth noting that the use of pre-finalizers would have a negative impact
on the garbage collection performance as V8 needs to scan all of them during
each sweeping. If the object is expected to be created frequently in large
amounts in the application, it's better to avoid access to the V8 heap in its
cleanup to avoid having to use a pre-finalizer.
For more information about the cleanup of cppgc-managed objects and
what can be done in a pre-finalizer, see the [cppgc documentation][] and
the [`cppgc/prefinalizer.h` header][].
### Callback scopes
The public `CallbackScope` and the internally used `InternalCallbackScope`
classes provide the same facilities as [`MakeCallback()`][], namely:
* Emitting the `'before'` event for async tracking when entering the scope
* Setting the current async IDs to the ones passed to the constructor
* Emitting the `'after'` event for async tracking when leaving the scope
* Running the `process.nextTick()` queue
* Running microtasks, in particular `Promise` callbacks and async/await
functions
Usually, using `AsyncWrap::MakeCallback()` or using the constructor taking
an `AsyncWrap*` argument (i.e. used as
`InternalCallbackScope callback_scope(this);`) suffices inside of the Node.js
C++ codebase.
## C++ utilities
Node.js uses a few custom C++ utilities, mostly defined in [`util.h`][].
### Memory allocation
Node.js provides `Malloc()`, `Realloc()` and `Calloc()` functions that work
like their C stdlib counterparts, but crash if memory cannot be allocated.
(As V8 does not handle out-of-memory situations gracefully, it does not make
sense for Node.js to attempt to do so in all cases.)
The `UncheckedMalloc()`, `UncheckedRealloc()` and `UncheckedCalloc()` functions
return `nullptr` in these cases (or when `size == 0`).
#### Optional stack-based memory allocation
The `MaybeStackBuffer` class provides a way to allocate memory on the stack
if it is smaller than a given limit, and falls back to allocating it on the
heap if it is larger. This can be useful for performantly allocating temporary
data if it is typically expected to be small (e.g. file paths).
The `Utf8Value`, `TwoByteValue` (i.e. UTF-16 value) and `BufferValue`
(`Utf8Value` but copy data from a `Buffer` if one is passed) helpers
inherit from this class and allow accessing the characters in a JavaScript
string this way.
```cpp
static void Chdir(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
// ...
CHECK(args[0]->IsString());
Utf8Value path(env->isolate(), args[0]);
int err = uv_chdir(*path);
if (err) {
// ... error handling ...
}
}
```
### Assertions
Node.js provides a few macros that behave similar to `assert()`:
* `CHECK(expression)` aborts the process with a stack trace
if `expression` is false.
* `CHECK_EQ(a, b)` checks for `a == b`
* `CHECK_GE(a, b)` checks for `a >= b`
* `CHECK_GT(a, b)` checks for `a > b`
* `CHECK_LE(a, b)` checks for `a <= b`
* `CHECK_LT(a, b)` checks for `a < b`
* `CHECK_NE(a, b)` checks for `a != b`
* `CHECK_NULL(val)` checks for `a == nullptr`
* `CHECK_NOT_NULL(val)` checks for `a != nullptr`
* `CHECK_IMPLIES(a, b)` checks that `b` is true if `a` is true.
* `UNREACHABLE([message])` aborts the process if it is reached.
`CHECK`s are always enabled. For checks that should only run in debug mode, use
`DCHECK()`, `DCHECK_EQ()`, etc.
### Scope-based cleanup
The `OnScopeLeave()` function can be used to run a piece of code when leaving
the current C++ scope.
```cpp
static void GetUserInfo(const FunctionCallbackInfo<Value>& args) {
Environment* env = Environment::GetCurrent(args);
uv_passwd_t pwd;
// ...
const int err = uv_os_get_passwd(&pwd);
if (err) {
// ... error handling, return early ...
}
auto free_passwd = OnScopeLeave([&]() { uv_os_free_passwd(&pwd); });
// ...
// Turn `pwd` into a JavaScript object now; whenever we return from this
// function, `uv_os_free_passwd()` will be called.
// ...
}
```
[C++ coding style]: ../doc/contributing/cpp-style-guide.md
[Callback scopes]: #callback-scopes
[ECMAScript realm]: https://tc39.es/ecma262/#sec-code-realms
[JavaScript value handles]: #js-handles
[N-API]: https://nodejs.org/api/n-api.html
[Oilpan]: https://v8.dev/blog/oilpan-library
[Oilpan documentation in Chromium]: https://chromium.googlesource.com/v8/v8/+/main/include/cppgc/README.md
[`BaseObject`]: #baseobject
[`Context`]: #context
[`Environment`]: #environment
[`Global`]: #global-handles
[`HandleWrap`]: #handlewrap
[`IsolateData`]: #isolate-data
[`Isolate`]: #isolate
[`Local`]: #local-handles
[`MakeCallback()`]: #makecallback
[`MessagePort`]: https://nodejs.org/api/worker_threads.html#worker_threads_class_messageport
[`Realm`]: #realm
[`ReqWrap`]: #reqwrap
[`ShadowRealm`]: https://github.com/tc39/proposal-shadowrealm
[`async_hooks` module]: https://nodejs.org/api/async_hooks.html
[`async_wrap.h`]: async_wrap.h
[`base_object.h`]: base_object.h
[`cppgc/prefinalizer.h` header]: ../deps/v8/include/cppgc/prefinalizer.h
[`handle_wrap.h`]: handle_wrap.h
[`memory_tracker.h`]: memory_tracker.h
[`req_wrap.h`]: req_wrap.h
[`util.h`]: util.h
[`v8.h` in Code Search]: https://cs.chromium.org/chromium/src/v8/include/v8.h
[`v8.h` in Node.js]: https://github.com/nodejs/node/blob/HEAD/deps/v8/include/v8.h
[`v8.h` in V8]: https://github.com/v8/v8/blob/HEAD/include/v8.h
[`v8::Local<T>`]: https://v8.github.io/api/head/classv8_1_1Local.html
[`vm` module]: https://nodejs.org/api/vm.html
[binding function]: #binding-functions
[cleanup hooks]: #cleanup-hooks
[cppgc documentation]: ../deps/v8/include/cppgc/README.md
[event loop]: #event-loop
[exception handling]: #exception-handling
[fast API calls]: ../doc/contributing/adding-v8-fast-api.md
[internal field]: #internal-fields
[introduction for V8 embedders]: https://v8.dev/docs/embed
[libuv]: https://libuv.org/
[libuv handles]: #libuv-handles-and-requests
[libuv requests]: #libuv-handles-and-requests
[reference documentation for the libuv API]: http://docs.libuv.org/en/v1.x/
[unified heap design in Chromium]: https://docs.google.com/document/d/1Hs60Zx1WPJ_LUjGvgzt1OQ5Cthu-fG-zif-vquUH_8c/edit | unknown | github | https://github.com/nodejs/node | src/README.md |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from sentry.models import Rule
from sentry.plugins import plugins
from sentry.testutils import TestCase
from sentry.rules.processor import RuleProcessor
class RuleProcessorTest(TestCase):
# this test relies on a few other tests passing
def test_integrated(self):
event = self.create_event()
action_data = {
'id': 'sentry.rules.actions.notify_event.NotifyEventAction',
}
condition_data = {
'id': 'sentry.rules.conditions.every_event.EveryEventCondition',
}
Rule.objects.filter(project=event.project).delete()
rule = Rule.objects.create(
project=event.project,
data={
'conditions': [condition_data],
'actions': [action_data],
}
)
rp = RuleProcessor(event, is_new=True, is_regression=True, is_sample=False)
results = list(rp.apply())
assert len(results) == 1
callback, futures = results[0]
assert callback == plugins.get('mail').rule_notify
assert len(futures) == 1
assert futures[0].rule == rule
assert futures[0].kwargs == {} | unknown | codeparrot/codeparrot-clean | ||
"""
Tests for digital signatures used to validate messages to/from credit providers.
"""
from django.test import TestCase
from django.test.utils import override_settings
from openedx.core.djangoapps.credit import signature
@override_settings(CREDIT_PROVIDER_SECRET_KEYS={
"asu": 'abcd1234'
})
class SignatureTest(TestCase):
"""
Tests for digital signatures.
"""
def test_unicode_secret_key(self):
# Test a key that has type `unicode` but consists of ASCII characters
# (This can happen, for example, when loading the key from a JSON configuration file)
# When retrieving the shared secret, the type should be converted to `str`
key = signature.get_shared_secret_key("asu")
sig = signature.signature({}, key)
assert sig == '7d70a26b834d9881cc14466eceac8d39188fc5ef5ffad9ab281a8327c2c0d093'
@override_settings(CREDIT_PROVIDER_SECRET_KEYS={
"asu": '\u4567'
})
def test_non_ascii_unicode_secret_key(self):
# Test a key that contains non-ASCII unicode characters
# This should return `None` and log an error; the caller
# is then responsible for logging the appropriate errors
# so we can fix the misconfiguration.
key = signature.get_shared_secret_key("asu")
assert key is None
def test_unicode_data(self):
""" Verify the signature generation method supports Unicode data. """
key = signature.get_shared_secret_key("asu")
sig = signature.signature({'name': 'Ed Xavíer'}, key)
assert sig == '76b6c9a657000829253d7c23977b35b34ad750c5681b524d7fdfb25cd5273cec'
@override_settings(CREDIT_PROVIDER_SECRET_KEYS={
"asu": 'abcd1234',
})
def test_get_shared_secret_key_string(self):
"""
get_shared_secret_key should return ascii encoded string if provider
secret is stored as a single key.
"""
key = signature.get_shared_secret_key("asu")
assert key == 'abcd1234'
@override_settings(CREDIT_PROVIDER_SECRET_KEYS={
"asu": ['abcd1234', 'zyxw9876']
})
def test_get_shared_secret_key_string_multiple_keys(self):
"""
get_shared_secret_key should return ascii encoded strings if provider
secret is stored as a list for multiple key support.
"""
key = signature.get_shared_secret_key("asu")
assert key == ['abcd1234', 'zyxw9876']
@override_settings(CREDIT_PROVIDER_SECRET_KEYS={
"asu": ['\u4567', 'zyxw9876']
})
def test_get_shared_secret_key_string_multiple_keys_with_none(self):
"""
get_shared_secret_key should return ascii encoded string if provider
secret is stored as a list for multiple key support, replacing None
for unencodable strings.
"""
key = signature.get_shared_secret_key("asu")
assert key == [None, 'zyxw9876'] | unknown | codeparrot/codeparrot-clean | ||
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2011, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
#ifndef IMFOUTPUTSTREAMMUTEX_H_
#define IMFOUTPUTSTREAMMUTEX_H_
#include <vector>
#include "ImfIO.h"
#include "IlmThreadMutex.h"
#include "ImfGenericOutputFile.h"
#include "ImfNamespace.h"
OPENEXR_IMF_INTERNAL_NAMESPACE_HEADER_ENTER
using ILMTHREAD_NAMESPACE::Mutex;
//
// Used to wrap OPENEXR_IMF_INTERNAL_NAMESPACE::OStream as a Mutex.
//
struct OutputStreamMutex : public Mutex
{
OPENEXR_IMF_INTERNAL_NAMESPACE::OStream* os;
Int64 currentPosition;
OutputStreamMutex()
{
os = 0;
currentPosition = 0;
}
};
OPENEXR_IMF_INTERNAL_NAMESPACE_HEADER_EXIT
#endif /* IMFOUTPUTSTREAMMUTEX_H_ */ | c | github | https://github.com/opencv/opencv | 3rdparty/openexr/IlmImf/ImfOutputStreamMutex.h |
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_MAGICNUMBERSCHECK_H
#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_MAGICNUMBERSCHECK_H
#include "../ClangTidyCheck.h"
#include "clang/Lex/Lexer.h"
#include <llvm/ADT/APFloat.h>
#include <llvm/ADT/SmallVector.h>
namespace clang::tidy::readability {
/// Detects magic numbers, integer and floating point literals embedded in code.
///
/// For the user-facing documentation see:
/// https://clang.llvm.org/extra/clang-tidy/checks/readability/magic-numbers.html
class MagicNumbersCheck : public ClangTidyCheck {
public:
MagicNumbersCheck(StringRef Name, ClangTidyContext *Context);
void storeOptions(ClangTidyOptions::OptionMap &Opts) override;
void registerMatchers(ast_matchers::MatchFinder *Finder) override;
void check(const ast_matchers::MatchFinder::MatchResult &Result) override;
private:
bool isConstant(const clang::ast_matchers::MatchFinder::MatchResult &Result,
const clang::Expr &ExprResult) const;
bool isIgnoredValue(const IntegerLiteral *Literal) const;
bool isIgnoredValue(const FloatingLiteral *Literal) const;
bool isSyntheticValue(const clang::SourceManager *,
const FloatingLiteral *) const {
return false;
}
bool isSyntheticValue(const clang::SourceManager *SourceManager,
const IntegerLiteral *Literal) const;
bool isBitFieldWidth(const clang::ast_matchers::MatchFinder::MatchResult &,
const FloatingLiteral &) const {
return false;
}
bool
isBitFieldWidth(const clang::ast_matchers::MatchFinder::MatchResult &Result,
const IntegerLiteral &Literal) const;
bool isUserDefinedLiteral(
const clang::ast_matchers::MatchFinder::MatchResult &Result,
const clang::Expr &Literal) const;
template <typename L>
void checkBoundMatch(const ast_matchers::MatchFinder::MatchResult &Result,
const char *BoundName) {
const L *MatchedLiteral = Result.Nodes.getNodeAs<L>(BoundName);
if (!MatchedLiteral)
return;
if (Result.SourceManager->isMacroBodyExpansion(
MatchedLiteral->getLocation()))
return;
if (isIgnoredValue(MatchedLiteral))
return;
if (isConstant(Result, *MatchedLiteral))
return;
if (isSyntheticValue(Result.SourceManager, MatchedLiteral))
return;
if (isBitFieldWidth(Result, *MatchedLiteral))
return;
if (IgnoreUserDefinedLiterals &&
isUserDefinedLiteral(Result, *MatchedLiteral))
return;
const StringRef LiteralSourceText = Lexer::getSourceText(
CharSourceRange::getTokenRange(MatchedLiteral->getSourceRange()),
*Result.SourceManager, getLangOpts());
diag(MatchedLiteral->getLocation(),
"%0 is a magic number; consider replacing it with a named constant")
<< LiteralSourceText;
}
const bool IgnoreAllFloatingPointValues;
const bool IgnoreBitFieldsWidths;
const bool IgnorePowersOf2IntegerValues;
const bool IgnoreTypeAliases;
const bool IgnoreUserDefinedLiterals;
const StringRef RawIgnoredIntegerValues;
const StringRef RawIgnoredFloatingPointValues;
constexpr static unsigned SensibleNumberOfMagicValueExceptions = 16;
constexpr static llvm::APFloat::roundingMode DefaultRoundingMode =
llvm::APFloat::rmNearestTiesToEven;
llvm::SmallVector<int64_t, SensibleNumberOfMagicValueExceptions>
IgnoredIntegerValues;
llvm::SmallVector<float, SensibleNumberOfMagicValueExceptions>
IgnoredFloatingPointValues;
llvm::SmallVector<double, SensibleNumberOfMagicValueExceptions>
IgnoredDoublePointValues;
};
} // namespace clang::tidy::readability
#endif // LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_READABILITY_MAGICNUMBERSCHECK_H | c | github | https://github.com/llvm/llvm-project | clang-tools-extra/clang-tidy/readability/MagicNumbersCheck.h |
use std::cell::UnsafeCell;
use std::fmt;
use std::ops::Deref;
use std::panic;
/// `AtomicU32` providing an additional `unsync_load` function.
pub(crate) struct AtomicU32 {
inner: UnsafeCell<std::sync::atomic::AtomicU32>,
}
unsafe impl Send for AtomicU32 {}
unsafe impl Sync for AtomicU32 {}
impl panic::RefUnwindSafe for AtomicU32 {}
impl panic::UnwindSafe for AtomicU32 {}
impl AtomicU32 {
pub(crate) const fn new(val: u32) -> AtomicU32 {
let inner = UnsafeCell::new(std::sync::atomic::AtomicU32::new(val));
AtomicU32 { inner }
}
/// Performs an unsynchronized load.
///
/// # Safety
///
/// All mutations must have happened before the unsynchronized load.
/// Additionally, there must be no concurrent mutations.
pub(crate) unsafe fn unsync_load(&self) -> u32 {
unsafe { core::ptr::read(self.inner.get() as *const u32) }
}
}
impl Deref for AtomicU32 {
type Target = std::sync::atomic::AtomicU32;
fn deref(&self) -> &Self::Target {
// safety: it is always safe to access `&self` fns on the inner value as
// we never perform unsafe mutations.
unsafe { &*self.inner.get() }
}
}
impl fmt::Debug for AtomicU32 {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
self.deref().fmt(fmt)
}
} | rust | github | https://github.com/tokio-rs/tokio | tokio/src/loom/std/atomic_u32.rs |
from __future__ import unicode_literals
from django.apps.registry import apps as global_apps
from django.db import migrations
from .loader import MigrationLoader
from .recorder import MigrationRecorder
from .state import ProjectState
class MigrationExecutor(object):
"""
End-to-end migration execution - loads migrations, and runs them
up or down to a specified set of targets.
"""
def __init__(self, connection, progress_callback=None):
self.connection = connection
self.loader = MigrationLoader(self.connection)
self.recorder = MigrationRecorder(self.connection)
self.progress_callback = progress_callback
def migration_plan(self, targets, clean_start=False):
"""
Given a set of targets, returns a list of (Migration instance, backwards?).
"""
plan = []
if clean_start:
applied = set()
else:
applied = set(self.loader.applied_migrations)
for target in targets:
# If the target is (app_label, None), that means unmigrate everything
if target[1] is None:
for root in self.loader.graph.root_nodes():
if root[0] == target[0]:
for migration in self.loader.graph.backwards_plan(root):
if migration in applied:
plan.append((self.loader.graph.nodes[migration], True))
applied.remove(migration)
# If the migration is already applied, do backwards mode,
# otherwise do forwards mode.
elif target in applied:
# Don't migrate backwards all the way to the target node (that
# may roll back dependencies in other apps that don't need to
# be rolled back); instead roll back through target's immediate
# child(ren) in the same app, and no further.
next_in_app = sorted(
n for n in
self.loader.graph.node_map[target].children
if n[0] == target[0]
)
for node in next_in_app:
for migration in self.loader.graph.backwards_plan(node):
if migration in applied:
plan.append((self.loader.graph.nodes[migration], True))
applied.remove(migration)
else:
for migration in self.loader.graph.forwards_plan(target):
if migration not in applied:
plan.append((self.loader.graph.nodes[migration], False))
applied.add(migration)
return plan
def migrate(self, targets, plan=None, fake=False, fake_initial=False):
"""
Migrates the database up to the given targets.
Django first needs to create all project states before a migration is
(un)applied and in a second step run all the database operations.
"""
if plan is None:
plan = self.migration_plan(targets)
migrations_to_run = {m[0] for m in plan}
# Create the forwards plan Django would follow on an empty database
full_plan = self.migration_plan(self.loader.graph.leaf_nodes(), clean_start=True)
# Holds all states right before a migration is applied
# if the migration is being run.
states = {}
state = ProjectState(real_apps=list(self.loader.unmigrated_apps))
if self.progress_callback:
self.progress_callback("render_start")
# Phase 1 -- Store all project states of migrations right before they
# are applied. The first migration that will be applied in phase 2 will
# trigger the rendering of the initial project state. From this time on
# models will be recursively reloaded as explained in
# `django.db.migrations.state.get_related_models_recursive()`.
for migration, _ in full_plan:
if not migrations_to_run:
# We remove every migration whose state was already computed
# from the set below (`migrations_to_run.remove(migration)`).
# If no states for migrations must be computed, we can exit
# this loop. Migrations that occur after the latest migration
# that is about to be applied would only trigger unneeded
# mutate_state() calls.
break
do_run = migration in migrations_to_run
if do_run:
if 'apps' not in state.__dict__:
state.apps # Render all real_apps -- performance critical
states[migration] = state.clone()
migrations_to_run.remove(migration)
# Only preserve the state if the migration is being run later
state = migration.mutate_state(state, preserve=do_run)
if self.progress_callback:
self.progress_callback("render_success")
# Phase 2 -- Run the migrations
for migration, backwards in plan:
if not backwards:
self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
else:
self.unapply_migration(states[migration], migration, fake=fake)
self.check_replacements()
def collect_sql(self, plan):
"""
Takes a migration plan and returns a list of collected SQL
statements that represent the best-efforts version of that plan.
"""
statements = []
state = None
for migration, backwards in plan:
with self.connection.schema_editor(collect_sql=True) as schema_editor:
if state is None:
state = self.loader.project_state((migration.app_label, migration.name), at_end=False)
if not backwards:
state = migration.apply(state, schema_editor, collect_sql=True)
else:
state = migration.unapply(state, schema_editor, collect_sql=True)
statements.extend(schema_editor.collected_sql)
return statements
def apply_migration(self, state, migration, fake=False, fake_initial=False):
"""
Runs a migration forwards.
"""
if self.progress_callback:
self.progress_callback("apply_start", migration, fake)
if not fake:
if fake_initial:
# Test to see if this is an already-applied initial migration
applied, state = self.detect_soft_applied(state, migration)
if applied:
fake = True
if not fake:
# Alright, do it normally
with self.connection.schema_editor() as schema_editor:
state = migration.apply(state, schema_editor)
# For replacement migrations, record individual statuses
if migration.replaces:
for app_label, name in migration.replaces:
self.recorder.record_applied(app_label, name)
else:
self.recorder.record_applied(migration.app_label, migration.name)
# Report progress
if self.progress_callback:
self.progress_callback("apply_success", migration, fake)
return state
def unapply_migration(self, state, migration, fake=False):
"""
Runs a migration backwards.
"""
if self.progress_callback:
self.progress_callback("unapply_start", migration, fake)
if not fake:
with self.connection.schema_editor() as schema_editor:
state = migration.unapply(state, schema_editor)
# For replacement migrations, record individual statuses
if migration.replaces:
for app_label, name in migration.replaces:
self.recorder.record_unapplied(app_label, name)
else:
self.recorder.record_unapplied(migration.app_label, migration.name)
# Report progress
if self.progress_callback:
self.progress_callback("unapply_success", migration, fake)
return state
def check_replacements(self):
"""
Mark replacement migrations applied if their replaced set all are.
We do this unconditionally on every migrate, rather than just when
migrations are applied or unapplied, so as to correctly handle the case
when a new squash migration is pushed to a deployment that already had
all its replaced migrations applied. In this case no new migration will
be applied, but we still want to correctly maintain the applied state
of the squash migration.
"""
applied = self.recorder.applied_migrations()
for key, migration in self.loader.replacements.items():
all_applied = all(m in applied for m in migration.replaces)
if all_applied and key not in applied:
self.recorder.record_applied(*key)
def detect_soft_applied(self, project_state, migration):
"""
Tests whether a migration has been implicitly applied - that the
tables it would create exist. This is intended only for use
on initial migrations (as it only looks for CreateModel).
"""
# Bail if the migration isn't the first one in its app
if [name for app, name in migration.dependencies if app == migration.app_label]:
return False, project_state
if project_state is None:
after_state = self.loader.project_state((migration.app_label, migration.name), at_end=True)
else:
after_state = migration.mutate_state(project_state)
apps = after_state.apps
found_create_migration = False
# Make sure all create model are done
for operation in migration.operations:
if isinstance(operation, migrations.CreateModel):
model = apps.get_model(migration.app_label, operation.name)
if model._meta.swapped:
# We have to fetch the model to test with from the
# main app cache, as it's not a direct dependency.
model = global_apps.get_model(model._meta.swapped)
if model._meta.db_table not in self.connection.introspection.table_names(self.connection.cursor()):
return False, project_state
found_create_migration = True
# If we get this far and we found at least one CreateModel migration,
# the migration is considered implicitly applied.
return found_create_migration, after_state | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python
# http://www.gavinj.net/2012/06/building-python-daemon-process.html
import os
import time
import logging
import rrdtool
# third party libs
from daemon import runner
# for solar monitoring
import socket
import re
import struct
##########################################################################
##########################################################################
##########################################################################
##########################################################################
RANGES = {'voltage': (0, 500),
'current': (0, 100),
'power': (0, 4000),
'frequency': (0, 100),
'temperature': (-50, 200),
'energy': (0, 10000000)}
DAILY_PROFILES = ('voltage_1', 'voltage_2',
'current_1', 'current_2',
'power_1', 'power_2',
'power_total')
DAILY_ENERGY = ('energy_total', 'energy_daily')
DAILY_GRID = ('temperature_intern',
'frequency_grid',
'voltage_grid',
'current_grid')
# aggregates
SHORT_TERM_DAYS = 7
MEDIUM_TERM_DAYS = 30
LONG_TERM_DAYS = 90
# number of readings and periods in days for profiles
SHORT_TERM_VALUES_PER_AGGREGATE = 1
SHORT_TERM_NUM_VALUES = SHORT_TERM_DAYS * \
24 * 60 // SHORT_TERM_VALUES_PER_AGGREGATE
MEDIUM_TERM_VALUES_PER_AGGREGATE = 5
MEDIUM_TERM_NUM_VALUES = MEDIUM_TERM_DAYS * \
24 * 60 // MEDIUM_TERM_VALUES_PER_AGGREGATE
LONG_TERM_VALUES_PER_AGGREGATE = 10
LONG_TERM_NUM_VALUES = LONG_TERM_DAYS * \
24 * 60 // LONG_TERM_VALUES_PER_AGGREGATE
##########################################################################
##########################################################################
##########################################################################
##########################################################################
# Send UDP broadcast packets
##########################################################################
UDP_PORT = 1300
UDP_MESSAGE = "55 aa 00 40 02 00 0b 49 20 41 4d 20 53 45 52 56 45 52 04 3a"
UDP_REPEATS = 1
SOLAR_HOST = '192.168.0.45' # The remote host
# TCP connection settings
TCP_HOST = '' # Symbolic name meaning the local host
TCP_PORT = 1200 # The same port as used by the server
TCP_MESSAGE_QUERY1 = "55 aa 01 03 02 00 00 01 05"
TCP_MESSAGE_QUERY2 = "55 aa 01 00 02 00 00 01 02"
TCP_MESSAGE_QUERY3 = "55 aa 04 00 02 00 00 01 05"
TCP_MESSAGE_QUERY_DATA = "55 aa 01 02 02 00 00 01 04"
# Gather every 60 seconds
HEART_BEAT = 10
##########################################################################
def toMsg(data):
'''convert data to message.'''
return re.sub(" ", "", data).decode('hex')
def fromMsg(data):
'''decode message from SAMIL Inverter'''
result = Result()
result.fromData(data)
return result
class Result:
'''Container for SAMIL Inverter Status.'''
def fromData(self, data):
assert len(data) == 63
fmt = "!7shhhhhhhhh20shhhhhhih"
# A, B, C, D, E are unknown content
# missing: operating time
# heat sink temperature
(A, self.internal_temperature,
self.voltage1, self.voltage2,
self.current1, self.current2,
B, C, D,
self.energy_today, D,
self.power1, self.power2,
self.grid_current, self.grid_voltage, self.grid_frequency,
self.power_total, self.energy_total, self.E) = struct.unpack(fmt, data)
# unit conversion
self.internal_temperature *= 0.1 # Celsius
self.voltage1 *= 0.1 # V
self.voltage2 *= 0.1 # V
self.current1 *= 0.1 # A
self.current2 *= 0.1 # A
self.power1 *= 1.0 # W
self.power2 *= 1.0 # W
self.grid_frequency *= 0.01 # Hz
self.grid_current *= 0.1 # A
self.grid_voltage *= 0.1 # V
self.power_total *= 1.0 # W
self.energy_today *= 0.01 # kWh
self.energy_total *= 0.1 # kWh
@classmethod
def header(cls):
return "\t".join(('T [C]',
'V1 [V]',
'V2 [V]',
'A1 [A]',
'A2 [A]',
'P1 [W]',
'P2 [W]',
'P [W]'
'Ed [kWh]',
'E [kWh]',
'GV [V]',
'GA [A]',
'Gf [Hz]'))
def __str__(self):
return "\t".join(map(str, (
self.internal_temperature,
self.voltage1,
self.voltage2,
self.current1,
self.current2,
self.power1,
self.power2,
self.power_total,
self.energy_today,
self.energy_total,
self.grid_voltage,
self.grid_current,
self.grid_frequency)))
##########################################################################
##########################################################################
##########################################################################
##########################################################################
# Daemon part
##########################################################################
class App():
def __init__(self):
self.stdin_path = '/dev/null'
# tty not available as init script
self.stdout_path = '/dev/null'
self.stderr_path = '/dev/null'
self.pidfile_path = '/mnt/ramdisk/solardaemon.pid'
self.pidfile_timeout = 5
# open tcp connection
self.connection = None
# rrd database names to store data into
self.rrd_directory = "/mnt/ramdisk"
self.rrd_power = os.path.join(self.rrd_directory, 'solar_power.rrd')
self.rrd_energy = os.path.join(self.rrd_directory, 'solar_energy.rrd')
self.rrd_grid = os.path.join(self.rrd_directory, 'solar_grid.rrd')
def setup_connection(self):
logger.debug("TCP:%i opening" % TCP_PORT)
tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
while True:
try:
tcp.bind((TCP_HOST, TCP_PORT))
except socket.error, msg:
logger.debug("error connecting: %s - retry in 20s" % msg)
time.sleep(20)
continue
break
logger.debug("TCP:%i listening" % TCP_PORT)
tcp.settimeout(20)
while True:
pid = os.fork()
if pid == 0:
logger.debug("UDP:%i sending welcome" % UDP_PORT)
# wait 1 second
time.sleep(1)
udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
udp.bind(('', 0))
udp.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
udp.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
udp.sendto(toMsg(UDP_MESSAGE), ('<broadcast>', UDP_PORT))
udp.close()
logger.debug("UDP:%i closed" % UDP_PORT)
# exit child process
os._exit(0)
else:
logger.debug("TCP: waiting for contact from inverter")
try:
tcp.listen(1)
conn, addr = tcp.accept()
except socket.timeout:
logger.debug("no connection - retrying")
continue
logger.debug('TCP: connected to inverter: %s:%s' %
(str(addr), str(conn)))
logger.debug("sent message 1")
conn.send(toMsg(TCP_MESSAGE_QUERY1))
data = conn.recv(1024)
logger.debug("sent message 2")
conn.send(toMsg(TCP_MESSAGE_QUERY2))
data = conn.recv(1024)
logger.debug("sent message 3")
conn.send(toMsg(TCP_MESSAGE_QUERY3))
data = conn.recv(1024)
break
return tcp, conn
def run(self):
'''main loop.
'''
self.createDatabase()
while True:
logger.info("connecting to inverter")
tcp, conn = self.setup_connection()
self.connection = conn
while True:
try:
logger.debug("getting data")
conn.send(toMsg(TCP_MESSAGE_QUERY_DATA))
data = conn.recv(1024)
except OSError:
break
if len(data) == 63:
values = fromMsg(data)
logger.info("%s" % str(values))
logger.info("status: solar=ok")
else:
logger.debug("received %i bytes" % len(data))
values = None
logger.info("status: solar=fail")
if values:
self.updateDatabase(values)
if len(data) == 0:
logger.warn(
"received 0 bytes - closing connection and restarting")
conn.close()
tcp.close()
break
time.sleep(HEART_BEAT)
logger.warn("lost connection - will retry")
def updateDatabase(self, values):
'''update rrd database with values'''
rrdtool.update(self.rrd_power,
"N:" + ":".join(map(str, (values.voltage1,
values.voltage2,
values.current1,
values.current2,
values.power1,
values.power2,
values.power_total))))
rrdtool.update(self.rrd_energy,
"N:" + ":".join((map(str, (values.energy_total,
values.energy_today)))))
rrdtool.update(self.rrd_grid,
"N:" + ":".join((map(str, (values.internal_temperature,
values.grid_frequency,
values.grid_voltage,
values.grid_current)))))
def createDatabase(self):
'''create rrd databases. Existing databases will not be overwritten'''
params = globals()
params.update(locals())
if not os.path.exists(self.rrd_power):
logging.info("creating new rrd database %s" % self.rrd_power)
data_sources = []
for profile in DAILY_PROFILES:
prefix, suffix = profile.split("_")
mi, ma = RANGES[prefix]
data_sources.append(
'DS:%s:GAUGE:120:%i:%i' % (profile, mi, ma))
rra = [
# short-term
'RRA:AVERAGE:0.5:%(SHORT_TERM_VALUES_PER_AGGREGATE)i:%(SHORT_TERM_NUM_VALUES)i',
# medium term
'RRA:AVERAGE:0.5:%(MEDIUM_TERM_VALUES_PER_AGGREGATE)i:%(MEDIUM_TERM_NUM_VALUES)i',
'RRA:MIN:0.5:%(MEDIUM_TERM_VALUES_PER_AGGREGATE)i:%(MEDIUM_TERM_NUM_VALUES)i',
'RRA:MAX:0.5:%(MEDIUM_TERM_VALUES_PER_AGGREGATE)i:%(MEDIUM_TERM_NUM_VALUES)i',
# longterm profile
'RRA:AVERAGE:0.5:%(LONG_TERM_VALUES_PER_AGGREGATE)i:%(LONG_TERM_NUM_VALUES)i',
'RRA:MIN:0.5:%(LONG_TERM_VALUES_PER_AGGREGATE)i:%(LONG_TERM_NUM_VALUES)i',
'RRA:MAX:0.5:%(LONG_TERM_VALUES_PER_AGGREGATE)i:%(LONG_TERM_NUM_VALUES)i',
]
rra = [x % params for x in rra]
rrdtool.create(self.rrd_power,
'--step', str(HEART_BEAT),
*data_sources + rra)
if not os.path.exists(self.rrd_energy):
logging.info("creating new rrd database %s" % self.rrd_energy)
data_sources = []
for profile in DAILY_ENERGY:
prefix, suffix = profile.split("_")
mi, ma = RANGES[prefix]
data_sources.append(
'DS:%s:GAUGE:1400:%i:%i' % (profile, mi, ma))
rra = [
'RRA:MAX:0.5:1440:7300']
rrdtool.create(self.rrd_energy,
'--step', '60',
*data_sources + rra)
if not os.path.exists(self.rrd_grid):
logging.info("creating new rrd database %s" % self.rrd_grid)
data_sources = []
for profile in DAILY_GRID:
prefix, suffix = profile.split("_")
mi, ma = RANGES[prefix]
data_sources.append(
'DS:%s:GAUGE:120:%i:%i' % (profile, mi, ma))
lt_values_per_aggregate = 24 * 60
params.update(locals())
rra = [
# medium term - 5 minute min/max/average
'RRA:AVERAGE:0.5:%(MEDIUM_TERM_VALUES_PER_AGGREGATE)i:%(MEDIUM_TERM_NUM_VALUES)i',
'RRA:MIN:0.5:%(MEDIUM_TERM_VALUES_PER_AGGREGATE)i:%(MEDIUM_TERM_NUM_VALUES)i',
'RRA:MAX:0.5:%(MEDIUM_TERM_VALUES_PER_AGGREGATE)i:%(MEDIUM_TERM_NUM_VALUES)i',
# long-term - keep daily min/max/average
'RRA:MIN:0.5:%(lt_values_per_aggregate)i:%(LONG_TERM_DAYS)i',
'RRA:MAX:0.5:%(lt_values_per_aggregate)i:%(LONG_TERM_DAYS)i',
'RRA:AVERAGE:0.5:%(lt_values_per_aggregate)i:%(LONG_TERM_DAYS)i']
rra = [x % params for x in rra]
rrdtool.create(self.rrd_grid,
'--step', '60',
*data_sources + rra)
def __del__(self):
if self.connection:
self.connection.close()
app = App()
logger = logging.getLogger("DaemonLog")
logger.setLevel(logging.INFO)
formatter = logging.Formatter(
"%(asctime)s - %(name)s - %(levelname)s - %(message)s")
handler = logging.FileHandler("/mnt/ramdisk/solar.log")
handler.setFormatter(formatter)
logger.addHandler(handler)
daemon_runner = runner.DaemonRunner(app)
# This ensures that the logger file handle does not get closed during
# daemonization
daemon_runner.daemon_context.files_preserve = [handler.stream]
daemon_runner.do_action() | unknown | codeparrot/codeparrot-clean | ||
//! This module contains information need to view information about how the
//! runtime is performing.
//!
//! **Note**: This is an [unstable API][unstable]. The public API of types in
//! this module may break in 1.x releases. See [the documentation on unstable
//! features][unstable] for details.
//!
//! [unstable]: crate#unstable-features
#![allow(clippy::module_inception)]
mod runtime;
pub use runtime::RuntimeMetrics;
mod batch;
pub(crate) use batch::MetricsBatch;
mod worker;
pub(crate) use worker::WorkerMetrics;
cfg_unstable_metrics! {
mod histogram;
pub(crate) use histogram::{Histogram, HistogramBatch, HistogramBuilder};
#[allow(unreachable_pub)] // rust-lang/rust#57411
pub use histogram::{HistogramScale, HistogramConfiguration, LogHistogram, LogHistogramBuilder, InvalidHistogramConfiguration};
mod scheduler;
pub(crate) use scheduler::SchedulerMetrics;
cfg_net! {
mod io;
pub(crate) use io::IoDriverMetrics;
}
}
cfg_not_unstable_metrics! {
mod mock;
pub(crate) use mock::{SchedulerMetrics, HistogramBuilder};
} | rust | github | https://github.com/tokio-rs/tokio | tokio/src/runtime/metrics/mod.rs |
/*-------------------------------------------------------------------------
*
* indexing.c
* This file contains routines to support indexes defined on system
* catalogs.
*
* Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, Regents of the University of California
*
*
* IDENTIFICATION
* src/backend/catalog/indexing.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/htup_details.h"
#include "access/xact.h"
#include "catalog/index.h"
#include "catalog/indexing.h"
#include "executor/executor.h"
#include "utils/rel.h"
/*
* CatalogOpenIndexes - open the indexes on a system catalog.
*
* When inserting or updating tuples in a system catalog, call this
* to prepare to update the indexes for the catalog.
*
* In the current implementation, we share code for opening/closing the
* indexes with execUtils.c. But we do not use ExecInsertIndexTuples,
* because we don't want to create an EState. This implies that we
* do not support partial or expressional indexes on system catalogs,
* nor can we support generalized exclusion constraints.
* This could be fixed with localized changes here if we wanted to pay
* the extra overhead of building an EState.
*/
CatalogIndexState
CatalogOpenIndexes(Relation heapRel)
{
ResultRelInfo *resultRelInfo;
resultRelInfo = makeNode(ResultRelInfo);
resultRelInfo->ri_RangeTableIndex = 0; /* dummy */
resultRelInfo->ri_RelationDesc = heapRel;
resultRelInfo->ri_TrigDesc = NULL; /* we don't fire triggers */
ExecOpenIndices(resultRelInfo, false);
return resultRelInfo;
}
/*
* CatalogCloseIndexes - clean up resources allocated by CatalogOpenIndexes
*/
void
CatalogCloseIndexes(CatalogIndexState indstate)
{
ExecCloseIndices(indstate);
pfree(indstate);
}
/*
* CatalogIndexInsert - insert index entries for one catalog tuple
*
* This should be called for each inserted or updated catalog tuple.
*
* This is effectively a cut-down version of ExecInsertIndexTuples.
*/
static void
CatalogIndexInsert(CatalogIndexState indstate, HeapTuple heapTuple,
TU_UpdateIndexes updateIndexes)
{
int i;
int numIndexes;
RelationPtr relationDescs;
Relation heapRelation;
TupleTableSlot *slot;
IndexInfo **indexInfoArray;
Datum values[INDEX_MAX_KEYS];
bool isnull[INDEX_MAX_KEYS];
bool onlySummarized = (updateIndexes == TU_Summarizing);
/*
* HOT update does not require index inserts. But with asserts enabled we
* want to check that it'd be legal to currently insert into the
* table/index.
*/
#ifndef USE_ASSERT_CHECKING
if (HeapTupleIsHeapOnly(heapTuple) && !onlySummarized)
return;
#endif
/* When only updating summarized indexes, the tuple has to be HOT. */
Assert((!onlySummarized) || HeapTupleIsHeapOnly(heapTuple));
/*
* Get information from the state structure. Fall out if nothing to do.
*/
numIndexes = indstate->ri_NumIndices;
if (numIndexes == 0)
return;
relationDescs = indstate->ri_IndexRelationDescs;
indexInfoArray = indstate->ri_IndexRelationInfo;
heapRelation = indstate->ri_RelationDesc;
/* Need a slot to hold the tuple being examined */
slot = MakeSingleTupleTableSlot(RelationGetDescr(heapRelation),
&TTSOpsHeapTuple);
ExecStoreHeapTuple(heapTuple, slot, false);
/*
* for each index, form and insert the index tuple
*/
for (i = 0; i < numIndexes; i++)
{
IndexInfo *indexInfo;
Relation index;
indexInfo = indexInfoArray[i];
index = relationDescs[i];
/* If the index is marked as read-only, ignore it */
if (!indexInfo->ii_ReadyForInserts)
continue;
/*
* Expressional and partial indexes on system catalogs are not
* supported, nor exclusion constraints, nor deferred uniqueness
*/
Assert(indexInfo->ii_Expressions == NIL);
Assert(indexInfo->ii_Predicate == NIL);
Assert(indexInfo->ii_ExclusionOps == NULL);
Assert(index->rd_index->indimmediate);
Assert(indexInfo->ii_NumIndexKeyAttrs != 0);
/* see earlier check above */
#ifdef USE_ASSERT_CHECKING
if (HeapTupleIsHeapOnly(heapTuple) && !onlySummarized)
{
Assert(!ReindexIsProcessingIndex(RelationGetRelid(index)));
continue;
}
#endif /* USE_ASSERT_CHECKING */
/*
* Skip insertions into non-summarizing indexes if we only need to
* update summarizing indexes.
*/
if (onlySummarized && !indexInfo->ii_Summarizing)
continue;
/*
* FormIndexDatum fills in its values and isnull parameters with the
* appropriate values for the column(s) of the index.
*/
FormIndexDatum(indexInfo,
slot,
NULL, /* no expression eval to do */
values,
isnull);
/*
* The index AM does the rest.
*/
index_insert(index, /* index relation */
values, /* array of index Datums */
isnull, /* is-null flags */
&(heapTuple->t_self), /* tid of heap tuple */
heapRelation,
index->rd_index->indisunique ?
UNIQUE_CHECK_YES : UNIQUE_CHECK_NO,
false,
indexInfo);
}
ExecDropSingleTupleTableSlot(slot);
}
/*
* Subroutine to verify that catalog constraints are honored.
*
* Tuples inserted via CatalogTupleInsert/CatalogTupleUpdate are generally
* "hand made", so that it's possible that they fail to satisfy constraints
* that would be checked if they were being inserted by the executor. That's
* a coding error, so we only bother to check for it in assert-enabled builds.
*/
#ifdef USE_ASSERT_CHECKING
static void
CatalogTupleCheckConstraints(Relation heapRel, HeapTuple tup)
{
/*
* Currently, the only constraints implemented for system catalogs are
* attnotnull constraints.
*/
if (HeapTupleHasNulls(tup))
{
TupleDesc tupdesc = RelationGetDescr(heapRel);
bits8 *bp = tup->t_data->t_bits;
for (int attnum = 0; attnum < tupdesc->natts; attnum++)
{
Form_pg_attribute thisatt = TupleDescAttr(tupdesc, attnum);
Assert(!(thisatt->attnotnull && att_isnull(attnum, bp)));
}
}
}
#else /* !USE_ASSERT_CHECKING */
#define CatalogTupleCheckConstraints(heapRel, tup) ((void) 0)
#endif /* USE_ASSERT_CHECKING */
/*
* CatalogTupleInsert - do heap and indexing work for a new catalog tuple
*
* Insert the tuple data in "tup" into the specified catalog relation.
*
* This is a convenience routine for the common case of inserting a single
* tuple in a system catalog; it inserts a new heap tuple, keeping indexes
* current. Avoid using it for multiple tuples, since opening the indexes
* and building the index info structures is moderately expensive.
* (Use CatalogTupleInsertWithInfo in such cases.)
*/
void
CatalogTupleInsert(Relation heapRel, HeapTuple tup)
{
CatalogIndexState indstate;
CatalogTupleCheckConstraints(heapRel, tup);
indstate = CatalogOpenIndexes(heapRel);
simple_heap_insert(heapRel, tup);
CatalogIndexInsert(indstate, tup, TU_All);
CatalogCloseIndexes(indstate);
}
/*
* CatalogTupleInsertWithInfo - as above, but with caller-supplied index info
*
* This should be used when it's important to amortize CatalogOpenIndexes/
* CatalogCloseIndexes work across multiple insertions. At some point we
* might cache the CatalogIndexState data somewhere (perhaps in the relcache)
* so that callers needn't trouble over this ... but we don't do so today.
*/
void
CatalogTupleInsertWithInfo(Relation heapRel, HeapTuple tup,
CatalogIndexState indstate)
{
CatalogTupleCheckConstraints(heapRel, tup);
simple_heap_insert(heapRel, tup);
CatalogIndexInsert(indstate, tup, TU_All);
}
/*
* CatalogTuplesMultiInsertWithInfo - as above, but for multiple tuples
*
* Insert multiple tuples into the given catalog relation at once, with an
* amortized cost of CatalogOpenIndexes.
*/
void
CatalogTuplesMultiInsertWithInfo(Relation heapRel, TupleTableSlot **slot,
int ntuples, CatalogIndexState indstate)
{
/* Nothing to do */
if (ntuples <= 0)
return;
heap_multi_insert(heapRel, slot, ntuples,
GetCurrentCommandId(true), 0, NULL);
/*
* There is no equivalent to heap_multi_insert for the catalog indexes, so
* we must loop over and insert individually.
*/
for (int i = 0; i < ntuples; i++)
{
bool should_free;
HeapTuple tuple;
tuple = ExecFetchSlotHeapTuple(slot[i], true, &should_free);
tuple->t_tableOid = slot[i]->tts_tableOid;
CatalogIndexInsert(indstate, tuple, TU_All);
if (should_free)
heap_freetuple(tuple);
}
}
/*
* CatalogTupleUpdate - do heap and indexing work for updating a catalog tuple
*
* Update the tuple identified by "otid", replacing it with the data in "tup".
*
* This is a convenience routine for the common case of updating a single
* tuple in a system catalog; it updates one heap tuple, keeping indexes
* current. Avoid using it for multiple tuples, since opening the indexes
* and building the index info structures is moderately expensive.
* (Use CatalogTupleUpdateWithInfo in such cases.)
*/
void
CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
{
CatalogIndexState indstate;
TU_UpdateIndexes updateIndexes = TU_All;
CatalogTupleCheckConstraints(heapRel, tup);
indstate = CatalogOpenIndexes(heapRel);
simple_heap_update(heapRel, otid, tup, &updateIndexes);
CatalogIndexInsert(indstate, tup, updateIndexes);
CatalogCloseIndexes(indstate);
}
/*
* CatalogTupleUpdateWithInfo - as above, but with caller-supplied index info
*
* This should be used when it's important to amortize CatalogOpenIndexes/
* CatalogCloseIndexes work across multiple updates. At some point we
* might cache the CatalogIndexState data somewhere (perhaps in the relcache)
* so that callers needn't trouble over this ... but we don't do so today.
*/
void
CatalogTupleUpdateWithInfo(Relation heapRel, const ItemPointerData *otid, HeapTuple tup,
CatalogIndexState indstate)
{
TU_UpdateIndexes updateIndexes = TU_All;
CatalogTupleCheckConstraints(heapRel, tup);
simple_heap_update(heapRel, otid, tup, &updateIndexes);
CatalogIndexInsert(indstate, tup, updateIndexes);
}
/*
* CatalogTupleDelete - do heap and indexing work for deleting a catalog tuple
*
* Delete the tuple identified by "tid" in the specified catalog.
*
* With Postgres heaps, there is no index work to do at deletion time;
* cleanup will be done later by VACUUM. However, callers of this function
* shouldn't have to know that; we'd like a uniform abstraction for all
* catalog tuple changes. Hence, provide this currently-trivial wrapper.
*
* The abstraction is a bit leaky in that we don't provide an optimized
* CatalogTupleDeleteWithInfo version, because there is currently nothing to
* optimize. If we ever need that, rather than touching a lot of call sites,
* it might be better to do something about caching CatalogIndexState.
*/
void
CatalogTupleDelete(Relation heapRel, const ItemPointerData *tid)
{
simple_heap_delete(heapRel, tid);
} | c | github | https://github.com/postgres/postgres | src/backend/catalog/indexing.c |
from langchain_core.prompts import PromptTemplate
DEFAULT_REFINE_PROMPT_TMPL = (
"The original question is as follows: {question}\n"
"We have provided an existing answer, including sources: {existing_answer}\n"
"We have the opportunity to refine the existing answer"
"(only if needed) with some more context below.\n"
"------------\n"
"{context_str}\n"
"------------\n"
"Given the new context, refine the original answer to better "
"answer the question. "
"If you do update it, please update the sources as well. "
"If the context isn't useful, return the original answer."
)
DEFAULT_REFINE_PROMPT = PromptTemplate(
input_variables=["question", "existing_answer", "context_str"],
template=DEFAULT_REFINE_PROMPT_TMPL,
)
DEFAULT_TEXT_QA_PROMPT_TMPL = (
"Context information is below. \n"
"---------------------\n"
"{context_str}"
"\n---------------------\n"
"Given the context information and not prior knowledge, "
"answer the question: {question}\n"
)
DEFAULT_TEXT_QA_PROMPT = PromptTemplate(
input_variables=["context_str", "question"], template=DEFAULT_TEXT_QA_PROMPT_TMPL
)
EXAMPLE_PROMPT = PromptTemplate(
template="Content: {page_content}\nSource: {source}",
input_variables=["page_content", "source"],
) | python | github | https://github.com/langchain-ai/langchain | libs/langchain/langchain_classic/chains/qa_with_sources/refine_prompts.py |
// Code generated by "stringer -type=Severity"; DO NOT EDIT.
package tfdiags
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[Error-69]
_ = x[Warning-87]
}
const (
_Severity_name_0 = "Error"
_Severity_name_1 = "Warning"
)
func (i Severity) String() string {
switch {
case i == 69:
return _Severity_name_0
case i == 87:
return _Severity_name_1
default:
return "Severity(" + strconv.FormatInt(int64(i), 10) + ")"
}
} | go | github | https://github.com/hashicorp/terraform | internal/tfdiags/severity_string.go |
#!/usr/bin/env python3
#
#===- clang-format-diff.py - ClangFormat Diff Reformatter ----*- python -*--===#
#
# The LLVM Compiler Infrastructure
#
# This file is distributed under the University of Illinois Open Source
# License.
#
# ============================================================
#
# University of Illinois/NCSA
# Open Source License
#
# Copyright (c) 2007-2015 University of Illinois at Urbana-Champaign.
# All rights reserved.
#
# Developed by:
#
# LLVM Team
#
# University of Illinois at Urbana-Champaign
#
# http://llvm.org
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal with
# 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:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimers.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimers in the
# documentation and/or other materials provided with the distribution.
#
# * Neither the names of the LLVM Team, University of Illinois at
# Urbana-Champaign, nor the names of its contributors may be used to
# endorse or promote products derived from this Software without specific
# prior written permission.
#
# 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
# CONTRIBUTORS 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 WITH THE
# SOFTWARE.
#
# ============================================================
#
#===------------------------------------------------------------------------===#
r"""
ClangFormat Diff Reformatter
============================
This script reads input from a unified diff and reformats all the changed
lines. This is useful to reformat all the lines touched by a specific patch.
Example usage for git/svn users:
git diff -U0 HEAD^ | clang-format-diff.py -p1 -i
svn diff --diff-cmd=diff -x-U0 | clang-format-diff.py -i
"""
import argparse
import difflib
import io
import re
import subprocess
import sys
# Change this to the full path if clang-format is not on the path.
binary = 'clang-format'
def main():
parser = argparse.ArgumentParser(description=
'Reformat changed lines in diff. Without -i '
'option just output the diff that would be '
'introduced.')
parser.add_argument('-i', action='store_true', default=False,
help='apply edits to files instead of displaying a diff')
parser.add_argument('-p', metavar='NUM', default=0,
help='strip the smallest prefix containing P slashes')
parser.add_argument('-regex', metavar='PATTERN', default=None,
help='custom pattern selecting file paths to reformat '
'(case sensitive, overrides -iregex)')
parser.add_argument('-iregex', metavar='PATTERN', default=
r'.*\.(cpp|cc|c\+\+|cxx|c|cl|h|hpp|m|mm|inc|js|ts|proto'
r'|protodevel|java)',
help='custom pattern selecting file paths to reformat '
'(case insensitive, overridden by -regex)')
parser.add_argument('-sort-includes', action='store_true', default=False,
help='let clang-format sort include blocks')
parser.add_argument('-v', '--verbose', action='store_true',
help='be more verbose, ineffective without -i')
args = parser.parse_args()
# Extract changed lines for each file.
filename = None
lines_by_file = {}
for line in sys.stdin:
match = re.search('^\+\+\+\ (.*?/){%s}(\S*)' % args.p, line)
if match:
filename = match.group(2)
if filename == None:
continue
if args.regex is not None:
if not re.match('^%s$' % args.regex, filename):
continue
else:
if not re.match('^%s$' % args.iregex, filename, re.IGNORECASE):
continue
match = re.search('^@@.*\+(\d+)(,(\d+))?', line)
if match:
start_line = int(match.group(1))
line_count = 1
if match.group(3):
line_count = int(match.group(3))
if line_count == 0:
continue
end_line = start_line + line_count - 1
lines_by_file.setdefault(filename, []).extend(
['-lines', str(start_line) + ':' + str(end_line)])
# Reformat files containing changes in place.
for filename, lines in lines_by_file.items():
if args.i and args.verbose:
print('Formatting {}'.format(filename))
command = [binary, filename]
if args.i:
command.append('-i')
if args.sort_includes:
command.append('-sort-includes')
command.extend(lines)
command.extend(['-style=file', '-fallback-style=none'])
p = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=None,
stdin=subprocess.PIPE,
universal_newlines=True)
stdout, stderr = p.communicate()
if p.returncode != 0:
sys.exit(p.returncode)
if not args.i:
with open(filename, encoding="utf8") as f:
code = f.readlines()
formatted_code = io.StringIO(stdout).readlines()
diff = difflib.unified_diff(code, formatted_code,
filename, filename,
'(before formatting)', '(after formatting)')
diff_string = ''.join(diff)
if len(diff_string) > 0:
sys.stdout.write(diff_string)
if __name__ == '__main__':
main() | unknown | codeparrot/codeparrot-clean | ||
"""
per-test stdout/stderr capturing mechanism.
"""
from __future__ import absolute_import, division, print_function
import collections
import contextlib
import sys
import os
import io
from io import UnsupportedOperation
from tempfile import TemporaryFile
import six
import pytest
from _pytest.compat import CaptureIO
patchsysdict = {0: "stdin", 1: "stdout", 2: "stderr"}
def pytest_addoption(parser):
group = parser.getgroup("general")
group._addoption(
"--capture",
action="store",
default="fd" if hasattr(os, "dup") else "sys",
metavar="method",
choices=["fd", "sys", "no"],
help="per-test capturing method: one of fd|sys|no.",
)
group._addoption(
"-s",
action="store_const",
const="no",
dest="capture",
help="shortcut for --capture=no.",
)
@pytest.hookimpl(hookwrapper=True)
def pytest_load_initial_conftests(early_config, parser, args):
ns = early_config.known_args_namespace
if ns.capture == "fd":
_py36_windowsconsoleio_workaround(sys.stdout)
_colorama_workaround()
_readline_workaround()
pluginmanager = early_config.pluginmanager
capman = CaptureManager(ns.capture)
pluginmanager.register(capman, "capturemanager")
# make sure that capturemanager is properly reset at final shutdown
early_config.add_cleanup(capman.stop_global_capturing)
# make sure logging does not raise exceptions at the end
def silence_logging_at_shutdown():
if "logging" in sys.modules:
sys.modules["logging"].raiseExceptions = False
early_config.add_cleanup(silence_logging_at_shutdown)
# finally trigger conftest loading but while capturing (issue93)
capman.start_global_capturing()
outcome = yield
out, err = capman.suspend_global_capture()
if outcome.excinfo is not None:
sys.stdout.write(out)
sys.stderr.write(err)
class CaptureManager(object):
"""
Capture plugin, manages that the appropriate capture method is enabled/disabled during collection and each
test phase (setup, call, teardown). After each of those points, the captured output is obtained and
attached to the collection/runtest report.
There are two levels of capture:
* global: which is enabled by default and can be suppressed by the ``-s`` option. This is always enabled/disabled
during collection and each test phase.
* fixture: when a test function or one of its fixture depend on the ``capsys`` or ``capfd`` fixtures. In this
case special handling is needed to ensure the fixtures take precedence over the global capture.
"""
def __init__(self, method):
self._method = method
self._global_capturing = None
def _getcapture(self, method):
if method == "fd":
return MultiCapture(out=True, err=True, Capture=FDCapture)
elif method == "sys":
return MultiCapture(out=True, err=True, Capture=SysCapture)
elif method == "no":
return MultiCapture(out=False, err=False, in_=False)
else:
raise ValueError("unknown capturing method: %r" % method)
def start_global_capturing(self):
assert self._global_capturing is None
self._global_capturing = self._getcapture(self._method)
self._global_capturing.start_capturing()
def stop_global_capturing(self):
if self._global_capturing is not None:
self._global_capturing.pop_outerr_to_orig()
self._global_capturing.stop_capturing()
self._global_capturing = None
def resume_global_capture(self):
self._global_capturing.resume_capturing()
def suspend_global_capture(self, item=None, in_=False):
if item is not None:
self.deactivate_fixture(item)
cap = getattr(self, "_global_capturing", None)
if cap is not None:
try:
outerr = cap.readouterr()
finally:
cap.suspend_capturing(in_=in_)
return outerr
def activate_fixture(self, item):
"""If the current item is using ``capsys`` or ``capfd``, activate them so they take precedence over
the global capture.
"""
fixture = getattr(item, "_capture_fixture", None)
if fixture is not None:
fixture._start()
def deactivate_fixture(self, item):
"""Deactivates the ``capsys`` or ``capfd`` fixture of this item, if any."""
fixture = getattr(item, "_capture_fixture", None)
if fixture is not None:
fixture.close()
@pytest.hookimpl(hookwrapper=True)
def pytest_make_collect_report(self, collector):
if isinstance(collector, pytest.File):
self.resume_global_capture()
outcome = yield
out, err = self.suspend_global_capture()
rep = outcome.get_result()
if out:
rep.sections.append(("Captured stdout", out))
if err:
rep.sections.append(("Captured stderr", err))
else:
yield
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_setup(self, item):
self.resume_global_capture()
# no need to activate a capture fixture because they activate themselves during creation; this
# only makes sense when a fixture uses a capture fixture, otherwise the capture fixture will
# be activated during pytest_runtest_call
yield
self.suspend_capture_item(item, "setup")
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_call(self, item):
self.resume_global_capture()
# it is important to activate this fixture during the call phase so it overwrites the "global"
# capture
self.activate_fixture(item)
yield
self.suspend_capture_item(item, "call")
@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_teardown(self, item):
self.resume_global_capture()
self.activate_fixture(item)
yield
self.suspend_capture_item(item, "teardown")
@pytest.hookimpl(tryfirst=True)
def pytest_keyboard_interrupt(self, excinfo):
self.stop_global_capturing()
@pytest.hookimpl(tryfirst=True)
def pytest_internalerror(self, excinfo):
self.stop_global_capturing()
def suspend_capture_item(self, item, when, in_=False):
out, err = self.suspend_global_capture(item, in_=in_)
item.add_report_section(when, "stdout", out)
item.add_report_section(when, "stderr", err)
capture_fixtures = {"capfd", "capfdbinary", "capsys", "capsysbinary"}
def _ensure_only_one_capture_fixture(request, name):
fixtures = set(request.fixturenames) & capture_fixtures - {name}
if fixtures:
fixtures = sorted(fixtures)
fixtures = fixtures[0] if len(fixtures) == 1 else fixtures
raise request.raiseerror(
"cannot use {} and {} at the same time".format(fixtures, name)
)
@pytest.fixture
def capsys(request):
"""Enable capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
captured output available via ``capsys.readouterr()`` method calls
which return a ``(out, err)`` namedtuple. ``out`` and ``err`` will be ``text``
objects.
"""
_ensure_only_one_capture_fixture(request, "capsys")
with _install_capture_fixture_on_item(request, SysCapture) as fixture:
yield fixture
@pytest.fixture
def capsysbinary(request):
"""Enable capturing of writes to ``sys.stdout`` and ``sys.stderr`` and make
captured output available via ``capsys.readouterr()`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be ``bytes``
objects.
"""
_ensure_only_one_capture_fixture(request, "capsysbinary")
# Currently, the implementation uses the python3 specific `.buffer`
# property of CaptureIO.
if sys.version_info < (3,):
raise request.raiseerror("capsysbinary is only supported on python 3")
with _install_capture_fixture_on_item(request, SysCaptureBinary) as fixture:
yield fixture
@pytest.fixture
def capfd(request):
"""Enable capturing of writes to file descriptors ``1`` and ``2`` and make
captured output available via ``capfd.readouterr()`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be ``text``
objects.
"""
_ensure_only_one_capture_fixture(request, "capfd")
if not hasattr(os, "dup"):
pytest.skip(
"capfd fixture needs os.dup function which is not available in this system"
)
with _install_capture_fixture_on_item(request, FDCapture) as fixture:
yield fixture
@pytest.fixture
def capfdbinary(request):
"""Enable capturing of write to file descriptors 1 and 2 and make
captured output available via ``capfdbinary.readouterr`` method calls
which return a ``(out, err)`` tuple. ``out`` and ``err`` will be
``bytes`` objects.
"""
_ensure_only_one_capture_fixture(request, "capfdbinary")
if not hasattr(os, "dup"):
pytest.skip(
"capfdbinary fixture needs os.dup function which is not available in this system"
)
with _install_capture_fixture_on_item(request, FDCaptureBinary) as fixture:
yield fixture
@contextlib.contextmanager
def _install_capture_fixture_on_item(request, capture_class):
"""
Context manager which creates a ``CaptureFixture`` instance and "installs" it on
the item/node of the given request. Used by ``capsys`` and ``capfd``.
The CaptureFixture is added as attribute of the item because it needs to accessed
by ``CaptureManager`` during its ``pytest_runtest_*`` hooks.
"""
request.node._capture_fixture = fixture = CaptureFixture(capture_class, request)
capmanager = request.config.pluginmanager.getplugin("capturemanager")
# need to active this fixture right away in case it is being used by another fixture (setup phase)
# if this fixture is being used only by a test function (call phase), then we wouldn't need this
# activation, but it doesn't hurt
capmanager.activate_fixture(request.node)
yield fixture
fixture.close()
del request.node._capture_fixture
class CaptureFixture(object):
"""
Object returned by :py:func:`capsys`, :py:func:`capsysbinary`, :py:func:`capfd` and :py:func:`capfdbinary`
fixtures.
"""
def __init__(self, captureclass, request):
self.captureclass = captureclass
self.request = request
def _start(self):
self._capture = MultiCapture(
out=True, err=True, in_=False, Capture=self.captureclass
)
self._capture.start_capturing()
def close(self):
cap = self.__dict__.pop("_capture", None)
if cap is not None:
self._outerr = cap.pop_outerr_to_orig()
cap.stop_capturing()
def readouterr(self):
"""Read and return the captured output so far, resetting the internal buffer.
:return: captured content as a namedtuple with ``out`` and ``err`` string attributes
"""
try:
return self._capture.readouterr()
except AttributeError:
return self._outerr
@contextlib.contextmanager
def disabled(self):
"""Temporarily disables capture while inside the 'with' block."""
self._capture.suspend_capturing()
capmanager = self.request.config.pluginmanager.getplugin("capturemanager")
capmanager.suspend_global_capture(item=None, in_=False)
try:
yield
finally:
capmanager.resume_global_capture()
self._capture.resume_capturing()
def safe_text_dupfile(f, mode, default_encoding="UTF8"):
""" return an open text file object that's a duplicate of f on the
FD-level if possible.
"""
encoding = getattr(f, "encoding", None)
try:
fd = f.fileno()
except Exception:
if "b" not in getattr(f, "mode", "") and hasattr(f, "encoding"):
# we seem to have a text stream, let's just use it
return f
else:
newfd = os.dup(fd)
if "b" not in mode:
mode += "b"
f = os.fdopen(newfd, mode, 0) # no buffering
return EncodedFile(f, encoding or default_encoding)
class EncodedFile(object):
errors = "strict" # possibly needed by py3 code (issue555)
def __init__(self, buffer, encoding):
self.buffer = buffer
self.encoding = encoding
def write(self, obj):
if isinstance(obj, six.text_type):
obj = obj.encode(self.encoding, "replace")
self.buffer.write(obj)
def writelines(self, linelist):
data = "".join(linelist)
self.write(data)
@property
def name(self):
"""Ensure that file.name is a string."""
return repr(self.buffer)
def __getattr__(self, name):
return getattr(object.__getattribute__(self, "buffer"), name)
CaptureResult = collections.namedtuple("CaptureResult", ["out", "err"])
class MultiCapture(object):
out = err = in_ = None
def __init__(self, out=True, err=True, in_=True, Capture=None):
if in_:
self.in_ = Capture(0)
if out:
self.out = Capture(1)
if err:
self.err = Capture(2)
def start_capturing(self):
if self.in_:
self.in_.start()
if self.out:
self.out.start()
if self.err:
self.err.start()
def pop_outerr_to_orig(self):
""" pop current snapshot out/err capture and flush to orig streams. """
out, err = self.readouterr()
if out:
self.out.writeorg(out)
if err:
self.err.writeorg(err)
return out, err
def suspend_capturing(self, in_=False):
if self.out:
self.out.suspend()
if self.err:
self.err.suspend()
if in_ and self.in_:
self.in_.suspend()
self._in_suspended = True
def resume_capturing(self):
if self.out:
self.out.resume()
if self.err:
self.err.resume()
if hasattr(self, "_in_suspended"):
self.in_.resume()
del self._in_suspended
def stop_capturing(self):
""" stop capturing and reset capturing streams """
if hasattr(self, "_reset"):
raise ValueError("was already stopped")
self._reset = True
if self.out:
self.out.done()
if self.err:
self.err.done()
if self.in_:
self.in_.done()
def readouterr(self):
""" return snapshot unicode value of stdout/stderr capturings. """
return CaptureResult(
self.out.snap() if self.out is not None else "",
self.err.snap() if self.err is not None else "",
)
class NoCapture(object):
__init__ = start = done = suspend = resume = lambda *args: None
class FDCaptureBinary(object):
"""Capture IO to/from a given os-level filedescriptor.
snap() produces `bytes`
"""
def __init__(self, targetfd, tmpfile=None):
self.targetfd = targetfd
try:
self.targetfd_save = os.dup(self.targetfd)
except OSError:
self.start = lambda: None
self.done = lambda: None
else:
if targetfd == 0:
assert not tmpfile, "cannot set tmpfile with stdin"
tmpfile = open(os.devnull, "r")
self.syscapture = SysCapture(targetfd)
else:
if tmpfile is None:
f = TemporaryFile()
with f:
tmpfile = safe_text_dupfile(f, mode="wb+")
if targetfd in patchsysdict:
self.syscapture = SysCapture(targetfd, tmpfile)
else:
self.syscapture = NoCapture()
self.tmpfile = tmpfile
self.tmpfile_fd = tmpfile.fileno()
def __repr__(self):
return "<FDCapture %s oldfd=%s>" % (self.targetfd, self.targetfd_save)
def start(self):
""" Start capturing on targetfd using memorized tmpfile. """
try:
os.fstat(self.targetfd_save)
except (AttributeError, OSError):
raise ValueError("saved filedescriptor not valid anymore")
os.dup2(self.tmpfile_fd, self.targetfd)
self.syscapture.start()
def snap(self):
self.tmpfile.seek(0)
res = self.tmpfile.read()
self.tmpfile.seek(0)
self.tmpfile.truncate()
return res
def done(self):
""" stop capturing, restore streams, return original capture file,
seeked to position zero. """
targetfd_save = self.__dict__.pop("targetfd_save")
os.dup2(targetfd_save, self.targetfd)
os.close(targetfd_save)
self.syscapture.done()
_attempt_to_close_capture_file(self.tmpfile)
def suspend(self):
self.syscapture.suspend()
os.dup2(self.targetfd_save, self.targetfd)
def resume(self):
self.syscapture.resume()
os.dup2(self.tmpfile_fd, self.targetfd)
def writeorg(self, data):
""" write to original file descriptor. """
if isinstance(data, six.text_type):
data = data.encode("utf8") # XXX use encoding of original stream
os.write(self.targetfd_save, data)
class FDCapture(FDCaptureBinary):
"""Capture IO to/from a given os-level filedescriptor.
snap() produces text
"""
def snap(self):
res = FDCaptureBinary.snap(self)
enc = getattr(self.tmpfile, "encoding", None)
if enc and isinstance(res, bytes):
res = six.text_type(res, enc, "replace")
return res
class SysCapture(object):
def __init__(self, fd, tmpfile=None):
name = patchsysdict[fd]
self._old = getattr(sys, name)
self.name = name
if tmpfile is None:
if name == "stdin":
tmpfile = DontReadFromInput()
else:
tmpfile = CaptureIO()
self.tmpfile = tmpfile
def start(self):
setattr(sys, self.name, self.tmpfile)
def snap(self):
res = self.tmpfile.getvalue()
self.tmpfile.seek(0)
self.tmpfile.truncate()
return res
def done(self):
setattr(sys, self.name, self._old)
del self._old
_attempt_to_close_capture_file(self.tmpfile)
def suspend(self):
setattr(sys, self.name, self._old)
def resume(self):
setattr(sys, self.name, self.tmpfile)
def writeorg(self, data):
self._old.write(data)
self._old.flush()
class SysCaptureBinary(SysCapture):
def snap(self):
res = self.tmpfile.buffer.getvalue()
self.tmpfile.seek(0)
self.tmpfile.truncate()
return res
class DontReadFromInput(six.Iterator):
"""Temporary stub class. Ideally when stdin is accessed, the
capturing should be turned off, with possibly all data captured
so far sent to the screen. This should be configurable, though,
because in automated test runs it is better to crash than
hang indefinitely.
"""
encoding = None
def read(self, *args):
raise IOError("reading from stdin while output is captured")
readline = read
readlines = read
__next__ = read
def __iter__(self):
return self
def fileno(self):
raise UnsupportedOperation("redirected stdin is pseudofile, " "has no fileno()")
def isatty(self):
return False
def close(self):
pass
@property
def buffer(self):
if sys.version_info >= (3, 0):
return self
else:
raise AttributeError("redirected stdin has no attribute buffer")
def _colorama_workaround():
"""
Ensure colorama is imported so that it attaches to the correct stdio
handles on Windows.
colorama uses the terminal on import time. So if something does the
first import of colorama while I/O capture is active, colorama will
fail in various ways.
"""
if not sys.platform.startswith("win32"):
return
try:
import colorama # noqa
except ImportError:
pass
def _readline_workaround():
"""
Ensure readline is imported so that it attaches to the correct stdio
handles on Windows.
Pdb uses readline support where available--when not running from the Python
prompt, the readline module is not imported until running the pdb REPL. If
running pytest with the --pdb option this means the readline module is not
imported until after I/O capture has been started.
This is a problem for pyreadline, which is often used to implement readline
support on Windows, as it does not attach to the correct handles for stdout
and/or stdin if they have been redirected by the FDCapture mechanism. This
workaround ensures that readline is imported before I/O capture is setup so
that it can attach to the actual stdin/out for the console.
See https://github.com/pytest-dev/pytest/pull/1281
"""
if not sys.platform.startswith("win32"):
return
try:
import readline # noqa
except ImportError:
pass
def _py36_windowsconsoleio_workaround(stream):
"""
Python 3.6 implemented unicode console handling for Windows. This works
by reading/writing to the raw console handle using
``{Read,Write}ConsoleW``.
The problem is that we are going to ``dup2`` over the stdio file
descriptors when doing ``FDCapture`` and this will ``CloseHandle`` the
handles used by Python to write to the console. Though there is still some
weirdness and the console handle seems to only be closed randomly and not
on the first call to ``CloseHandle``, or maybe it gets reopened with the
same handle value when we suspend capturing.
The workaround in this case will reopen stdio with a different fd which
also means a different handle by replicating the logic in
"Py_lifecycle.c:initstdio/create_stdio".
:param stream: in practice ``sys.stdout`` or ``sys.stderr``, but given
here as parameter for unittesting purposes.
See https://github.com/pytest-dev/py/issues/103
"""
if not sys.platform.startswith("win32") or sys.version_info[:2] < (3, 6):
return
# bail out if ``stream`` doesn't seem like a proper ``io`` stream (#2666)
if not hasattr(stream, "buffer"):
return
buffered = hasattr(stream.buffer, "raw")
raw_stdout = stream.buffer.raw if buffered else stream.buffer
if not isinstance(raw_stdout, io._WindowsConsoleIO):
return
def _reopen_stdio(f, mode):
if not buffered and mode[0] == "w":
buffering = 0
else:
buffering = -1
return io.TextIOWrapper(
open(os.dup(f.fileno()), mode, buffering),
f.encoding,
f.errors,
f.newlines,
f.line_buffering,
)
sys.__stdin__ = sys.stdin = _reopen_stdio(sys.stdin, "rb")
sys.__stdout__ = sys.stdout = _reopen_stdio(sys.stdout, "wb")
sys.__stderr__ = sys.stderr = _reopen_stdio(sys.stderr, "wb")
def _attempt_to_close_capture_file(f):
"""Suppress IOError when closing the temporary file used for capturing streams in py27 (#2370)"""
if six.PY2:
try:
f.close()
except IOError:
pass
else:
f.close() | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python3
# Copyright (c) 2015-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test behavior of -maxuploadtarget.
* Verify that getdata requests for old blocks (>1week) are dropped
if uploadtarget has been reached.
* Verify that getdata requests for recent blocks are respected even
if uploadtarget has been reached.
* Verify that the upload counters are reset after 24 hours.
"""
from collections import defaultdict
import time
from test_framework.messages import CInv, msg_getdata
from test_framework.mininode import P2PInterface
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, mine_large_block
class TestP2PConn(P2PInterface):
def __init__(self):
super().__init__()
self.block_receive_map = defaultdict(int)
def on_inv(self, message):
pass
def on_block(self, message):
message.block.calc_sha256()
self.block_receive_map[message.block.sha256] += 1
class MaxUploadTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = True
self.num_nodes = 1
self.extra_args = [["-maxuploadtarget=800", "-acceptnonstdtxn=1"]]
# Cache for utxos, as the listunspent may take a long time later in the test
self.utxo_cache = []
def skip_test_if_missing_module(self):
self.skip_if_no_wallet()
def run_test(self):
# Before we connect anything, we first set the time on the node
# to be in the past, otherwise things break because the CNode
# time counters can't be reset backward after initialization
old_time = int(time.time() - 2*60*60*24*7)
self.nodes[0].setmocktime(old_time)
# Generate some old blocks
self.nodes[0].generate(130)
# p2p_conns[0] will only request old blocks
# p2p_conns[1] will only request new blocks
# p2p_conns[2] will test resetting the counters
p2p_conns = []
for _ in range(3):
p2p_conns.append(self.nodes[0].add_p2p_connection(TestP2PConn()))
# Now mine a big block
mine_large_block(self.nodes[0], self.utxo_cache)
# Store the hash; we'll request this later
big_old_block = self.nodes[0].getbestblockhash()
old_block_size = self.nodes[0].getblock(big_old_block, True)['size']
big_old_block = int(big_old_block, 16)
# Advance to two days ago
self.nodes[0].setmocktime(int(time.time()) - 2*60*60*24)
# Mine one more block, so that the prior block looks old
mine_large_block(self.nodes[0], self.utxo_cache)
# We'll be requesting this new block too
big_new_block = self.nodes[0].getbestblockhash()
big_new_block = int(big_new_block, 16)
# p2p_conns[0] will test what happens if we just keep requesting the
# the same big old block too many times (expect: disconnect)
getdata_request = msg_getdata()
getdata_request.inv.append(CInv(2, big_old_block))
max_bytes_per_day = 800*1024*1024
daily_buffer = 144 * 4000000
max_bytes_available = max_bytes_per_day - daily_buffer
success_count = max_bytes_available // old_block_size
# 576MB will be reserved for relaying new blocks, so expect this to
# succeed for ~235 tries.
for i in range(success_count):
p2p_conns[0].send_message(getdata_request)
p2p_conns[0].sync_with_ping()
assert_equal(p2p_conns[0].block_receive_map[big_old_block], i+1)
assert_equal(len(self.nodes[0].getpeerinfo()), 3)
# At most a couple more tries should succeed (depending on how long
# the test has been running so far).
for i in range(3):
p2p_conns[0].send_message(getdata_request)
p2p_conns[0].wait_for_disconnect()
assert_equal(len(self.nodes[0].getpeerinfo()), 2)
self.log.info("Peer 0 disconnected after downloading old block too many times")
# Requesting the current block on p2p_conns[1] should succeed indefinitely,
# even when over the max upload target.
# We'll try 800 times
getdata_request.inv = [CInv(2, big_new_block)]
for i in range(800):
p2p_conns[1].send_message(getdata_request)
p2p_conns[1].sync_with_ping()
assert_equal(p2p_conns[1].block_receive_map[big_new_block], i+1)
self.log.info("Peer 1 able to repeatedly download new block")
# But if p2p_conns[1] tries for an old block, it gets disconnected too.
getdata_request.inv = [CInv(2, big_old_block)]
p2p_conns[1].send_message(getdata_request)
p2p_conns[1].wait_for_disconnect()
assert_equal(len(self.nodes[0].getpeerinfo()), 1)
self.log.info("Peer 1 disconnected after trying to download old block")
self.log.info("Advancing system time on node to clear counters...")
# If we advance the time by 24 hours, then the counters should reset,
# and p2p_conns[2] should be able to retrieve the old block.
self.nodes[0].setmocktime(int(time.time()))
p2p_conns[2].sync_with_ping()
p2p_conns[2].send_message(getdata_request)
p2p_conns[2].sync_with_ping()
assert_equal(p2p_conns[2].block_receive_map[big_old_block], 1)
self.log.info("Peer 2 able to download old block")
self.nodes[0].disconnect_p2ps()
#stop and start node 0 with 1MB maxuploadtarget, whitelist 127.0.0.1
self.log.info("Restarting nodes with -whitelist=127.0.0.1")
self.stop_node(0)
self.start_node(0, ["-whitelist=127.0.0.1", "-maxuploadtarget=1"])
# Reconnect to self.nodes[0]
self.nodes[0].add_p2p_connection(TestP2PConn())
#retrieve 20 blocks which should be enough to break the 1MB limit
getdata_request.inv = [CInv(2, big_new_block)]
for i in range(20):
self.nodes[0].p2p.send_message(getdata_request)
self.nodes[0].p2p.sync_with_ping()
assert_equal(self.nodes[0].p2p.block_receive_map[big_new_block], i+1)
getdata_request.inv = [CInv(2, big_old_block)]
self.nodes[0].p2p.send_and_ping(getdata_request)
assert_equal(len(self.nodes[0].getpeerinfo()), 1) #node is still connected because of the whitelist
self.log.info("Peer still connected after trying to download old block (whitelisted)")
if __name__ == '__main__':
MaxUploadTest().main() | unknown | codeparrot/codeparrot-clean | ||
# Copyright 2014 OpenStack Foundation
#
# 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.
#
# Initial operations for the Mellanox plugin
from alembic import op
import sqlalchemy as sa
def upgrade():
op.create_table(
'segmentation_id_allocation',
sa.Column('physical_network', sa.String(length=64), nullable=False),
sa.Column('segmentation_id', sa.Integer(), autoincrement=False,
nullable=False),
sa.Column('allocated', sa.Boolean(), nullable=False,
server_default=sa.sql.false()),
sa.PrimaryKeyConstraint('physical_network', 'segmentation_id'))
op.create_table(
'mlnx_network_bindings',
sa.Column('network_id', sa.String(length=36), nullable=False),
sa.Column('network_type', sa.String(length=32), nullable=False),
sa.Column('physical_network', sa.String(length=64), nullable=True),
sa.Column('segmentation_id', sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(['network_id'], ['networks.id'],
ondelete='CASCADE'),
sa.PrimaryKeyConstraint('network_id'))
op.create_table(
'port_profile',
sa.Column('port_id', sa.String(length=36), nullable=False),
sa.Column('vnic_type', sa.String(length=32), nullable=False),
sa.ForeignKeyConstraint(['port_id'], ['ports.id'],
ondelete='CASCADE'),
sa.PrimaryKeyConstraint('port_id')) | unknown | codeparrot/codeparrot-clean | ||
from django.core.management.base import LabelCommand, CommandError
from django.utils.encoding import force_unicode
class Command(LabelCommand):
help = "Outputs the specified model as a form definition to the shell."
args = "[app.model]"
label = 'application name and model name'
requires_model_validation = True
can_import_settings = True
def handle_label(self, label, **options):
return describe_form(label)
def describe_form(label, fields=None):
"""
Returns a string describing a form based on the model
"""
from django.db.models.loading import get_model
try:
app_name, model_name = label.split('.')[-2:]
except (IndexError, ValueError):
raise CommandError("Need application and model name in the form: appname.model")
model = get_model(app_name, model_name)
opts = model._meta
field_list = []
for f in opts.fields + opts.many_to_many:
if not f.editable:
continue
if fields and not f.name in fields:
continue
formfield = f.formfield()
if not '__dict__' in dir(formfield):
continue
attrs = {}
valid_fields = ['required', 'initial', 'max_length', 'min_length', 'max_value', 'min_value', 'max_digits', 'decimal_places', 'choices', 'help_text', 'label']
for k, v in formfield.__dict__.items():
if k in valid_fields and v != None:
# ignore defaults, to minimize verbosity
if k == 'required' and v:
continue
if k == 'help_text' and not v:
continue
if k == 'widget':
attrs[k] = v.__class__
elif k in ['help_text', 'label']:
attrs[k] = force_unicode(v).strip()
else:
attrs[k] = v
params = ', '.join(['%s=%r' % (k, v) for k, v in attrs.items()])
field_list.append(' %(field_name)s = forms.%(field_type)s(%(params)s)' % {'field_name': f.name,
'field_type': formfield.__class__.__name__,
'params': params})
return '''
from django import forms
from %(app_name)s.models import %(object_name)s
class %(object_name)sForm(forms.Form):
%(field_list)s
''' % {'app_name': app_name, 'object_name': opts.object_name, 'field_list': '\n'.join(field_list)} | unknown | codeparrot/codeparrot-clean | ||
import subprocess
from typing import Dict, List, Union
from flask import url_for
from sqlalchemy import create_engine
from sqlalchemy_utils import create_database, database_exists
from shared import configuration
from shared_web.flask_app import PDFlask
APP = PDFlask(__name__)
APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
APP.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://{user}:{password}@{host}:{port}/{db}'.format(
user=configuration.get('mysql_user'),
password=configuration.get('mysql_passwd'),
host=configuration.get('mysql_host'),
port=configuration.get('mysql_port'),
db=configuration.get('logsite_database'))
from . import db, stats, api, views # isort:skip # pylint: disable=wrong-import-position, unused-import
def __create_schema() -> None:
engine = create_engine(APP.config['SQLALCHEMY_DATABASE_URI'])
if not database_exists(engine.url):
create_database(engine.url)
db.DB.create_all()
engine.dispose()
APP.config['commit-id'] = subprocess.check_output(['git', 'rev-parse', 'HEAD'])
APP.config['branch'] = subprocess.check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip().decode()
APP.config['SECRET_KEY'] = configuration.get('oauth2_client_secret')
def build_menu() -> List[Dict[str, str]]:
menu = [
{'name': 'Home', 'url': url_for('home')},
{'name': 'Matches', 'url': url_for('matches')},
{'name': 'People', 'url': url_for('people')},
{'name': 'Stats', 'url': url_for('charts')},
{'name': 'About', 'url': url_for('about')},
]
return menu
APP.config['menu'] = build_menu
__create_schema() | unknown | codeparrot/codeparrot-clean | ||
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 OpenStack Foundation
# 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.
"""
SchedulerOptions monitors a local .json file for changes and loads
it if needed. This file is converted to a data structure and passed
into the filtering and weighing functions which can use it for
dynamic configuration.
"""
import datetime
import json
import os
from oslo.config import cfg
from nova.openstack.common import excutils
from nova.openstack.common import log as logging
from nova.openstack.common import timeutils
scheduler_json_config_location_opt = cfg.StrOpt(
'scheduler_json_config_location',
default='',
help='Absolute path to scheduler configuration JSON file.')
CONF = cfg.CONF
CONF.register_opt(scheduler_json_config_location_opt)
LOG = logging.getLogger(__name__)
class SchedulerOptions(object):
"""
SchedulerOptions monitors a local .json file for changes and loads it
if needed. This file is converted to a data structure and passed into
the filtering and weighing functions which can use it for dynamic
configuration.
"""
def __init__(self):
super(SchedulerOptions, self).__init__()
self.data = {}
self.last_modified = None
self.last_checked = None
def _get_file_handle(self, filename):
"""Get file handle. Broken out for testing."""
return open(filename)
def _get_file_timestamp(self, filename):
"""Get the last modified datetime. Broken out for testing."""
try:
return os.path.getmtime(filename)
except os.error, e:
with excutils.save_and_reraise_exception():
LOG.exception(_("Could not stat scheduler options file "
"%(filename)s: '%(e)s'"), locals())
def _load_file(self, handle):
"""Decode the JSON file. Broken out for testing."""
try:
return json.load(handle)
except ValueError, e:
LOG.exception(_("Could not decode scheduler options: "
"'%(e)s'") % locals())
return {}
def _get_time_now(self):
"""Get current UTC. Broken out for testing."""
return timeutils.utcnow()
def get_configuration(self, filename=None):
"""Check the json file for changes and load it if needed."""
if not filename:
filename = CONF.scheduler_json_config_location
if not filename:
return self.data
if self.last_checked:
now = self._get_time_now()
if now - self.last_checked < datetime.timedelta(minutes=5):
return self.data
last_modified = self._get_file_timestamp(filename)
if (not last_modified or not self.last_modified or
last_modified > self.last_modified):
self.data = self._load_file(self._get_file_handle(filename))
self.last_modified = last_modified
if not self.data:
self.data = {}
return self.data | unknown | codeparrot/codeparrot-clean | ||
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('twitterclone', '0010_auto_20150331_1958'),
]
operations = [
migrations.CreateModel(
name='Photo',
fields=[
('id', models.AutoField(serialize=False, primary_key=True)),
('url', models.URLField(max_length=255, blank=True)),
('server', models.CharField(max_length=255, blank=True)),
('farm', models.CharField(max_length=255, blank=True)),
('secret', models.CharField(max_length=255, blank=True)),
('flickrid', models.CharField(max_length=255, blank=True)),
],
options={
},
bases=(models.Model,),
),
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(serialize=False, primary_key=True)),
('title', models.CharField(unique=True, max_length=200)),
('message', models.TextField(max_length=1024)),
('created_date', models.DateTimeField()),
('photo_id', models.CharField(max_length=50)),
('tags', models.CharField(max_length=200)),
('userId', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
options={
},
bases=(models.Model,),
),
migrations.AddField(
model_name='photo',
name='post',
field=models.ForeignKey(to='twitterclone.Post'),
preserve_default=True,
),
] | unknown | codeparrot/codeparrot-clean | ||
import pickle
import io
from test import support
from test.pickletester import AbstractPickleTests
from test.pickletester import AbstractPickleModuleTests
from test.pickletester import AbstractPersistentPicklerTests
from test.pickletester import AbstractPicklerUnpicklerObjectTests
try:
import _pickle
has_c_implementation = True
except ImportError:
has_c_implementation = False
class PickleTests(AbstractPickleModuleTests):
pass
class PyPicklerTests(AbstractPickleTests):
pickler = pickle._Pickler
unpickler = pickle._Unpickler
def dumps(self, arg, proto=None):
f = io.BytesIO()
p = self.pickler(f, proto)
p.dump(arg)
f.seek(0)
return bytes(f.read())
def loads(self, buf):
f = io.BytesIO(buf)
u = self.unpickler(f)
return u.load()
class PyPersPicklerTests(AbstractPersistentPicklerTests):
pickler = pickle._Pickler
unpickler = pickle._Unpickler
def dumps(self, arg, proto=None):
class PersPickler(self.pickler):
def persistent_id(subself, obj):
return self.persistent_id(obj)
f = io.BytesIO()
p = PersPickler(f, proto)
p.dump(arg)
f.seek(0)
return f.read()
def loads(self, buf):
class PersUnpickler(self.unpickler):
def persistent_load(subself, obj):
return self.persistent_load(obj)
f = io.BytesIO(buf)
u = PersUnpickler(f)
return u.load()
class PyPicklerUnpicklerObjectTests(AbstractPicklerUnpicklerObjectTests):
pickler_class = pickle._Pickler
unpickler_class = pickle._Unpickler
if has_c_implementation:
class CPicklerTests(PyPicklerTests):
pickler = _pickle.Pickler
unpickler = _pickle.Unpickler
class CPersPicklerTests(PyPersPicklerTests):
pickler = _pickle.Pickler
unpickler = _pickle.Unpickler
class CDumpPickle_LoadPickle(PyPicklerTests):
pickler = _pickle.Pickler
unpickler = pickle._Unpickler
class DumpPickle_CLoadPickle(PyPicklerTests):
pickler = pickle._Pickler
unpickler = _pickle.Unpickler
class CPicklerUnpicklerObjectTests(AbstractPicklerUnpicklerObjectTests):
pickler_class = _pickle.Pickler
unpickler_class = _pickle.Unpickler
def test_main():
tests = [PickleTests, PyPicklerTests, PyPersPicklerTests]
if has_c_implementation:
tests.extend([CPicklerTests, CPersPicklerTests,
CDumpPickle_LoadPickle, DumpPickle_CLoadPickle,
PyPicklerUnpicklerObjectTests,
CPicklerUnpicklerObjectTests])
support.run_unittest(*tests)
support.run_doctest(pickle)
if __name__ == "__main__":
test_main() | unknown | codeparrot/codeparrot-clean | ||
# urllib3/util.py
# Copyright 2008-2012 Andrey Petrov and contributors (see CONTRIBUTORS.txt)
#
# This module is part of urllib3 and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from base64 import b64encode
from collections import namedtuple
from socket import error as SocketError
from hashlib import md5, sha1
from binascii import hexlify, unhexlify
try:
from select import poll, POLLIN
except ImportError: # `poll` doesn't exist on OSX and other platforms
poll = False
try:
from select import select
except ImportError: # `select` doesn't exist on AppEngine.
select = False
try: # Test for SSL features
SSLContext = None
HAS_SNI = False
import ssl
from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23
from ssl import SSLContext # Modern SSL?
from ssl import HAS_SNI # Has SNI?
except ImportError:
pass
from .packages import six
from .exceptions import LocationParseError, SSLError
class Url(namedtuple('Url', ['scheme', 'auth', 'host', 'port', 'path', 'query', 'fragment'])):
"""
Datastructure for representing an HTTP URL. Used as a return value for
:func:`parse_url`.
"""
slots = ()
def __new__(cls, scheme=None, auth=None, host=None, port=None, path=None, query=None, fragment=None):
return super(Url, cls).__new__(cls, scheme, auth, host, port, path, query, fragment)
@property
def hostname(self):
"""For backwards-compatibility with urlparse. We're nice like that."""
return self.host
@property
def request_uri(self):
"""Absolute path including the query string."""
uri = self.path or '/'
if self.query is not None:
uri += '?' + self.query
return uri
def split_first(s, delims):
"""
Given a string and an iterable of delimiters, split on the first found
delimiter. Return two split parts and the matched delimiter.
If not found, then the first part is the full input string.
Example: ::
>>> split_first('foo/bar?baz', '?/=')
('foo', 'bar?baz', '/')
>>> split_first('foo/bar?baz', '123')
('foo/bar?baz', '', None)
Scales linearly with number of delims. Not ideal for large number of delims.
"""
min_idx = None
min_delim = None
for d in delims:
idx = s.find(d)
if idx < 0:
continue
if min_idx is None or idx < min_idx:
min_idx = idx
min_delim = d
if min_idx is None or min_idx < 0:
return s, '', None
return s[:min_idx], s[min_idx+1:], min_delim
def parse_url(url):
"""
Given a url, return a parsed :class:`.Url` namedtuple. Best-effort is
performed to parse incomplete urls. Fields not provided will be None.
Partly backwards-compatible with :mod:`urlparse`.
Example: ::
>>> parse_url('http://google.com/mail/')
Url(scheme='http', host='google.com', port=None, path='/', ...)
>>> parse_url('google.com:80')
Url(scheme=None, host='google.com', port=80, path=None, ...)
>>> parse_url('/foo?bar')
Url(scheme=None, host=None, port=None, path='/foo', query='bar', ...)
"""
# While this code has overlap with stdlib's urlparse, it is much
# simplified for our needs and less annoying.
# Additionally, this imeplementations does silly things to be optimal
# on CPython.
scheme = None
auth = None
host = None
port = None
path = None
fragment = None
query = None
# Scheme
if '://' in url:
scheme, url = url.split('://', 1)
# Find the earliest Authority Terminator
# (http://tools.ietf.org/html/rfc3986#section-3.2)
url, path_, delim = split_first(url, ['/', '?', '#'])
if delim:
# Reassemble the path
path = delim + path_
# Auth
if '@' in url:
auth, url = url.split('@', 1)
# IPv6
if url and url[0] == '[':
host, url = url[1:].split(']', 1)
# Port
if ':' in url:
_host, port = url.split(':', 1)
if not host:
host = _host
if not port.isdigit():
raise LocationParseError("Failed to parse: %s" % url)
port = int(port)
elif not host and url:
host = url
if not path:
return Url(scheme, auth, host, port, path, query, fragment)
# Fragment
if '#' in path:
path, fragment = path.split('#', 1)
# Query
if '?' in path:
path, query = path.split('?', 1)
return Url(scheme, auth, host, port, path, query, fragment)
def get_host(url):
"""
Deprecated. Use :func:`.parse_url` instead.
"""
p = parse_url(url)
return p.scheme or 'http', p.hostname, p.port
def make_headers(keep_alive=None, accept_encoding=None, user_agent=None,
basic_auth=None):
"""
Shortcuts for generating request headers.
:param keep_alive:
If ``True``, adds 'connection: keep-alive' header.
:param accept_encoding:
Can be a boolean, list, or string.
``True`` translates to 'gzip,deflate'.
List will get joined by comma.
String will be used as provided.
:param user_agent:
String representing the user-agent you want, such as
"python-urllib3/0.6"
:param basic_auth:
Colon-separated username:password string for 'authorization: basic ...'
auth header.
Example: ::
>>> make_headers(keep_alive=True, user_agent="Batman/1.0")
{'connection': 'keep-alive', 'user-agent': 'Batman/1.0'}
>>> make_headers(accept_encoding=True)
{'accept-encoding': 'gzip,deflate'}
"""
headers = {}
if accept_encoding:
if isinstance(accept_encoding, str):
pass
elif isinstance(accept_encoding, list):
accept_encoding = ','.join(accept_encoding)
else:
accept_encoding = 'gzip,deflate'
headers['accept-encoding'] = accept_encoding
if user_agent:
headers['user-agent'] = user_agent
if keep_alive:
headers['connection'] = 'keep-alive'
if basic_auth:
headers['authorization'] = 'Basic ' + \
b64encode(six.b(basic_auth)).decode('utf-8')
return headers
def is_connection_dropped(conn): # Platform-specific
"""
Returns True if the connection is dropped and should be closed.
:param conn:
:class:`httplib.HTTPConnection` object.
Note: For platforms like AppEngine, this will always return ``False`` to
let the platform handle connection recycling transparently for us.
"""
sock = getattr(conn, 'sock', False)
if not sock: # Platform-specific: AppEngine
return False
if not poll:
if not select: # Platform-specific: AppEngine
return False
try:
return select([sock], [], [], 0.0)[0]
except SocketError:
return True
# This version is better on platforms that support it.
p = poll()
p.register(sock, POLLIN)
for (fno, ev) in p.poll(0.0):
if fno == sock.fileno():
# Either data is buffered (bad), or the connection is dropped.
return True
def resolve_cert_reqs(candidate):
"""
Resolves the argument to a numeric constant, which can be passed to
the wrap_socket function/method from the ssl module.
Defaults to :data:`ssl.CERT_NONE`.
If given a string it is assumed to be the name of the constant in the
:mod:`ssl` module or its abbrevation.
(So you can specify `REQUIRED` instead of `CERT_REQUIRED`.
If it's neither `None` nor a string we assume it is already the numeric
constant which can directly be passed to wrap_socket.
"""
if candidate is None:
return CERT_NONE
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'CERT_' + candidate)
return res
return candidate
def resolve_ssl_version(candidate):
"""
like resolve_cert_reqs
"""
if candidate is None:
return PROTOCOL_SSLv23
if isinstance(candidate, str):
res = getattr(ssl, candidate, None)
if res is None:
res = getattr(ssl, 'PROTOCOL_' + candidate)
return res
return candidate
def assert_fingerprint(cert, fingerprint):
"""
Checks if given fingerprint matches the supplied certificate.
:param cert:
Certificate as bytes object.
:param fingerprint:
Fingerprint as string of hexdigits, can be interspersed by colons.
"""
# Maps the length of a digest to a possible hash function producing
# this digest.
hashfunc_map = {
16: md5,
20: sha1
}
fingerprint = fingerprint.replace(':', '').lower()
digest_length, rest = divmod(len(fingerprint), 2)
if rest or digest_length not in hashfunc_map:
raise SSLError('Fingerprint is of invalid length.')
# We need encode() here for py32; works on py2 and p33.
fingerprint_bytes = unhexlify(fingerprint.encode())
hashfunc = hashfunc_map[digest_length]
cert_digest = hashfunc(cert).digest()
if not cert_digest == fingerprint_bytes:
raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
.format(hexlify(fingerprint_bytes),
hexlify(cert_digest)))
if SSLContext is not None: # Python 3.2+
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None):
"""
All arguments except `server_hostname` have the same meaning as for
:func:`ssl.wrap_socket`
:param server_hostname:
Hostname of the expected certificate
"""
context = SSLContext(ssl_version)
context.verify_mode = cert_reqs
if ca_certs:
try:
context.load_verify_locations(ca_certs)
# Py32 raises IOError
# Py33 raises FileNotFoundError
except Exception as e: # Reraise as SSLError
raise SSLError(e)
if certfile:
# FIXME: This block needs a test.
context.load_cert_chain(certfile, keyfile)
if HAS_SNI: # Platform-specific: OpenSSL with enabled SNI
return context.wrap_socket(sock, server_hostname=server_hostname)
return context.wrap_socket(sock)
else: # Python 3.1 and earlier
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None,
ca_certs=None, server_hostname=None,
ssl_version=None):
return wrap_socket(sock, keyfile=keyfile, certfile=certfile,
ca_certs=ca_certs, cert_reqs=cert_reqs,
ssl_version=ssl_version) | unknown | codeparrot/codeparrot-clean | ||
import os.path
import numpy as np
from numpy.testing import (assert_, assert_array_almost_equal, assert_equal,
assert_almost_equal, assert_array_equal,
suppress_warnings)
from pytest import raises as assert_raises
import scipy.ndimage as ndimage
from . import types
class Test_measurements_stats:
"""ndimage.measurements._stats() is a utility used by other functions."""
def test_a(self):
x = [0, 1, 2, 6]
labels = [0, 0, 1, 1]
index = [0, 1]
for shp in [(4,), (2, 2)]:
x = np.array(x).reshape(shp)
labels = np.array(labels).reshape(shp)
counts, sums = ndimage.measurements._stats(
x, labels=labels, index=index)
assert_array_equal(counts, [2, 2])
assert_array_equal(sums, [1.0, 8.0])
def test_b(self):
# Same data as test_a, but different labels. The label 9 exceeds the
# length of 'labels', so this test will follow a different code path.
x = [0, 1, 2, 6]
labels = [0, 0, 9, 9]
index = [0, 9]
for shp in [(4,), (2, 2)]:
x = np.array(x).reshape(shp)
labels = np.array(labels).reshape(shp)
counts, sums = ndimage.measurements._stats(
x, labels=labels, index=index)
assert_array_equal(counts, [2, 2])
assert_array_equal(sums, [1.0, 8.0])
def test_a_centered(self):
x = [0, 1, 2, 6]
labels = [0, 0, 1, 1]
index = [0, 1]
for shp in [(4,), (2, 2)]:
x = np.array(x).reshape(shp)
labels = np.array(labels).reshape(shp)
counts, sums, centers = ndimage.measurements._stats(
x, labels=labels, index=index, centered=True)
assert_array_equal(counts, [2, 2])
assert_array_equal(sums, [1.0, 8.0])
assert_array_equal(centers, [0.5, 8.0])
def test_b_centered(self):
x = [0, 1, 2, 6]
labels = [0, 0, 9, 9]
index = [0, 9]
for shp in [(4,), (2, 2)]:
x = np.array(x).reshape(shp)
labels = np.array(labels).reshape(shp)
counts, sums, centers = ndimage.measurements._stats(
x, labels=labels, index=index, centered=True)
assert_array_equal(counts, [2, 2])
assert_array_equal(sums, [1.0, 8.0])
assert_array_equal(centers, [0.5, 8.0])
def test_nonint_labels(self):
x = [0, 1, 2, 6]
labels = [0.0, 0.0, 9.0, 9.0]
index = [0.0, 9.0]
for shp in [(4,), (2, 2)]:
x = np.array(x).reshape(shp)
labels = np.array(labels).reshape(shp)
counts, sums, centers = ndimage.measurements._stats(
x, labels=labels, index=index, centered=True)
assert_array_equal(counts, [2, 2])
assert_array_equal(sums, [1.0, 8.0])
assert_array_equal(centers, [0.5, 8.0])
class Test_measurements_select:
"""ndimage.measurements._select() is a utility used by other functions."""
def test_basic(self):
x = [0, 1, 6, 2]
cases = [
([0, 0, 1, 1], [0, 1]), # "Small" integer labels
([0, 0, 9, 9], [0, 9]), # A label larger than len(labels)
([0.0, 0.0, 7.0, 7.0], [0.0, 7.0]), # Non-integer labels
]
for labels, index in cases:
result = ndimage.measurements._select(
x, labels=labels, index=index)
assert_(len(result) == 0)
result = ndimage.measurements._select(
x, labels=labels, index=index, find_max=True)
assert_(len(result) == 1)
assert_array_equal(result[0], [1, 6])
result = ndimage.measurements._select(
x, labels=labels, index=index, find_min=True)
assert_(len(result) == 1)
assert_array_equal(result[0], [0, 2])
result = ndimage.measurements._select(
x, labels=labels, index=index, find_min=True,
find_min_positions=True)
assert_(len(result) == 2)
assert_array_equal(result[0], [0, 2])
assert_array_equal(result[1], [0, 3])
assert_equal(result[1].dtype.kind, 'i')
result = ndimage.measurements._select(
x, labels=labels, index=index, find_max=True,
find_max_positions=True)
assert_(len(result) == 2)
assert_array_equal(result[0], [1, 6])
assert_array_equal(result[1], [1, 2])
assert_equal(result[1].dtype.kind, 'i')
def test_label01():
data = np.ones([])
out, n = ndimage.label(data)
assert_array_almost_equal(out, 1)
assert_equal(n, 1)
def test_label02():
data = np.zeros([])
out, n = ndimage.label(data)
assert_array_almost_equal(out, 0)
assert_equal(n, 0)
def test_label03():
data = np.ones([1])
out, n = ndimage.label(data)
assert_array_almost_equal(out, [1])
assert_equal(n, 1)
def test_label04():
data = np.zeros([1])
out, n = ndimage.label(data)
assert_array_almost_equal(out, [0])
assert_equal(n, 0)
def test_label05():
data = np.ones([5])
out, n = ndimage.label(data)
assert_array_almost_equal(out, [1, 1, 1, 1, 1])
assert_equal(n, 1)
def test_label06():
data = np.array([1, 0, 1, 1, 0, 1])
out, n = ndimage.label(data)
assert_array_almost_equal(out, [1, 0, 2, 2, 0, 3])
assert_equal(n, 3)
def test_label07():
data = np.array([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
out, n = ndimage.label(data)
assert_array_almost_equal(out, [[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
assert_equal(n, 0)
def test_label08():
data = np.array([[1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0]])
out, n = ndimage.label(data)
assert_array_almost_equal(out, [[1, 0, 0, 0, 0, 0],
[0, 0, 2, 2, 0, 0],
[0, 0, 2, 2, 2, 0],
[3, 3, 0, 0, 0, 0],
[3, 3, 0, 0, 0, 0],
[0, 0, 0, 4, 4, 0]])
assert_equal(n, 4)
def test_label09():
data = np.array([[1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0]])
struct = ndimage.generate_binary_structure(2, 2)
out, n = ndimage.label(data, struct)
assert_array_almost_equal(out, [[1, 0, 0, 0, 0, 0],
[0, 0, 2, 2, 0, 0],
[0, 0, 2, 2, 2, 0],
[2, 2, 0, 0, 0, 0],
[2, 2, 0, 0, 0, 0],
[0, 0, 0, 3, 3, 0]])
assert_equal(n, 3)
def test_label10():
data = np.array([[0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0]])
struct = ndimage.generate_binary_structure(2, 2)
out, n = ndimage.label(data, struct)
assert_array_almost_equal(out, [[0, 0, 0, 0, 0, 0],
[0, 1, 1, 0, 1, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0]])
assert_equal(n, 1)
def test_label11():
for type in types:
data = np.array([[1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0]], type)
out, n = ndimage.label(data)
expected = [[1, 0, 0, 0, 0, 0],
[0, 0, 2, 2, 0, 0],
[0, 0, 2, 2, 2, 0],
[3, 3, 0, 0, 0, 0],
[3, 3, 0, 0, 0, 0],
[0, 0, 0, 4, 4, 0]]
assert_array_almost_equal(out, expected)
assert_equal(n, 4)
def test_label11_inplace():
for type in types:
data = np.array([[1, 0, 0, 0, 0, 0],
[0, 0, 1, 1, 0, 0],
[0, 0, 1, 1, 1, 0],
[1, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0]], type)
n = ndimage.label(data, output=data)
expected = [[1, 0, 0, 0, 0, 0],
[0, 0, 2, 2, 0, 0],
[0, 0, 2, 2, 2, 0],
[3, 3, 0, 0, 0, 0],
[3, 3, 0, 0, 0, 0],
[0, 0, 0, 4, 4, 0]]
assert_array_almost_equal(data, expected)
assert_equal(n, 4)
def test_label12():
for type in types:
data = np.array([[0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 0]], type)
out, n = ndimage.label(data)
expected = [[0, 0, 0, 0, 1, 1],
[0, 0, 0, 0, 0, 1],
[0, 0, 1, 0, 1, 1],
[0, 0, 1, 1, 1, 1],
[0, 0, 0, 1, 1, 0]]
assert_array_almost_equal(out, expected)
assert_equal(n, 1)
def test_label13():
for type in types:
data = np.array([[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
[1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]],
type)
out, n = ndimage.label(data)
expected = [[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
[1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
assert_array_almost_equal(out, expected)
assert_equal(n, 1)
def test_label_output_typed():
data = np.ones([5])
for t in types:
output = np.zeros([5], dtype=t)
n = ndimage.label(data, output=output)
assert_array_almost_equal(output, 1)
assert_equal(n, 1)
def test_label_output_dtype():
data = np.ones([5])
for t in types:
output, n = ndimage.label(data, output=t)
assert_array_almost_equal(output, 1)
assert output.dtype == t
def test_label_output_wrong_size():
data = np.ones([5])
for t in types:
output = np.zeros([10], t)
assert_raises((RuntimeError, ValueError),
ndimage.label, data, output=output)
def test_label_structuring_elements():
data = np.loadtxt(os.path.join(os.path.dirname(
__file__), "data", "label_inputs.txt"))
strels = np.loadtxt(os.path.join(
os.path.dirname(__file__), "data", "label_strels.txt"))
results = np.loadtxt(os.path.join(
os.path.dirname(__file__), "data", "label_results.txt"))
data = data.reshape((-1, 7, 7))
strels = strels.reshape((-1, 3, 3))
results = results.reshape((-1, 7, 7))
r = 0
for i in range(data.shape[0]):
d = data[i, :, :]
for j in range(strels.shape[0]):
s = strels[j, :, :]
assert_equal(ndimage.label(d, s)[0], results[r, :, :])
r += 1
def test_ticket_742():
def SE(img, thresh=.7, size=4):
mask = img > thresh
rank = len(mask.shape)
la, co = ndimage.label(mask,
ndimage.generate_binary_structure(rank, rank))
_ = ndimage.find_objects(la)
if np.dtype(np.intp) != np.dtype('i'):
shape = (3, 1240, 1240)
a = np.random.rand(np.prod(shape)).reshape(shape)
# shouldn't crash
SE(a)
def test_gh_issue_3025():
"""Github issue #3025 - improper merging of labels"""
d = np.zeros((60, 320))
d[:, :257] = 1
d[:, 260:] = 1
d[36, 257] = 1
d[35, 258] = 1
d[35, 259] = 1
assert ndimage.label(d, np.ones((3, 3)))[1] == 1
def test_label_default_dtype():
test_array = np.random.rand(10, 10)
label, no_features = ndimage.label(test_array > 0.5)
assert_(label.dtype in (np.int32, np.int64))
# Shouldn't raise an exception
ndimage.find_objects(label)
def test_find_objects01():
data = np.ones([], dtype=int)
out = ndimage.find_objects(data)
assert_(out == [()])
def test_find_objects02():
data = np.zeros([], dtype=int)
out = ndimage.find_objects(data)
assert_(out == [])
def test_find_objects03():
data = np.ones([1], dtype=int)
out = ndimage.find_objects(data)
assert_equal(out, [(slice(0, 1, None),)])
def test_find_objects04():
data = np.zeros([1], dtype=int)
out = ndimage.find_objects(data)
assert_equal(out, [])
def test_find_objects05():
data = np.ones([5], dtype=int)
out = ndimage.find_objects(data)
assert_equal(out, [(slice(0, 5, None),)])
def test_find_objects06():
data = np.array([1, 0, 2, 2, 0, 3])
out = ndimage.find_objects(data)
assert_equal(out, [(slice(0, 1, None),),
(slice(2, 4, None),),
(slice(5, 6, None),)])
def test_find_objects07():
data = np.array([[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0]])
out = ndimage.find_objects(data)
assert_equal(out, [])
def test_find_objects08():
data = np.array([[1, 0, 0, 0, 0, 0],
[0, 0, 2, 2, 0, 0],
[0, 0, 2, 2, 2, 0],
[3, 3, 0, 0, 0, 0],
[3, 3, 0, 0, 0, 0],
[0, 0, 0, 4, 4, 0]])
out = ndimage.find_objects(data)
assert_equal(out, [(slice(0, 1, None), slice(0, 1, None)),
(slice(1, 3, None), slice(2, 5, None)),
(slice(3, 5, None), slice(0, 2, None)),
(slice(5, 6, None), slice(3, 5, None))])
def test_find_objects09():
data = np.array([[1, 0, 0, 0, 0, 0],
[0, 0, 2, 2, 0, 0],
[0, 0, 2, 2, 2, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 4, 4, 0]])
out = ndimage.find_objects(data)
assert_equal(out, [(slice(0, 1, None), slice(0, 1, None)),
(slice(1, 3, None), slice(2, 5, None)),
None,
(slice(5, 6, None), slice(3, 5, None))])
def test_sum01():
for type in types:
input = np.array([], type)
output = ndimage.sum(input)
assert_equal(output, 0.0)
def test_sum02():
for type in types:
input = np.zeros([0, 4], type)
output = ndimage.sum(input)
assert_equal(output, 0.0)
def test_sum03():
for type in types:
input = np.ones([], type)
output = ndimage.sum(input)
assert_almost_equal(output, 1.0)
def test_sum04():
for type in types:
input = np.array([1, 2], type)
output = ndimage.sum(input)
assert_almost_equal(output, 3.0)
def test_sum05():
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.sum(input)
assert_almost_equal(output, 10.0)
def test_sum06():
labels = np.array([], bool)
for type in types:
input = np.array([], type)
output = ndimage.sum(input, labels=labels)
assert_equal(output, 0.0)
def test_sum07():
labels = np.ones([0, 4], bool)
for type in types:
input = np.zeros([0, 4], type)
output = ndimage.sum(input, labels=labels)
assert_equal(output, 0.0)
def test_sum08():
labels = np.array([1, 0], bool)
for type in types:
input = np.array([1, 2], type)
output = ndimage.sum(input, labels=labels)
assert_equal(output, 1.0)
def test_sum09():
labels = np.array([1, 0], bool)
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.sum(input, labels=labels)
assert_almost_equal(output, 4.0)
def test_sum10():
labels = np.array([1, 0], bool)
input = np.array([[1, 2], [3, 4]], bool)
output = ndimage.sum(input, labels=labels)
assert_almost_equal(output, 2.0)
def test_sum11():
labels = np.array([1, 2], np.int8)
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.sum(input, labels=labels,
index=2)
assert_almost_equal(output, 6.0)
def test_sum12():
labels = np.array([[1, 2], [2, 4]], np.int8)
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.sum(input, labels=labels, index=[4, 8, 2])
assert_array_almost_equal(output, [4.0, 0.0, 5.0])
def test_sum_labels():
labels = np.array([[1, 2], [2, 4]], np.int8)
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output_sum = ndimage.sum(input, labels=labels, index=[4, 8, 2])
output_labels = ndimage.sum_labels(
input, labels=labels, index=[4, 8, 2])
assert (output_sum == output_labels).all()
assert_array_almost_equal(output_labels, [4.0, 0.0, 5.0])
def test_mean01():
labels = np.array([1, 0], bool)
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.mean(input, labels=labels)
assert_almost_equal(output, 2.0)
def test_mean02():
labels = np.array([1, 0], bool)
input = np.array([[1, 2], [3, 4]], bool)
output = ndimage.mean(input, labels=labels)
assert_almost_equal(output, 1.0)
def test_mean03():
labels = np.array([1, 2])
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.mean(input, labels=labels,
index=2)
assert_almost_equal(output, 3.0)
def test_mean04():
labels = np.array([[1, 2], [2, 4]], np.int8)
with np.errstate(all='ignore'):
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.mean(input, labels=labels,
index=[4, 8, 2])
assert_array_almost_equal(output[[0, 2]], [4.0, 2.5])
assert_(np.isnan(output[1]))
def test_minimum01():
labels = np.array([1, 0], bool)
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.minimum(input, labels=labels)
assert_almost_equal(output, 1.0)
def test_minimum02():
labels = np.array([1, 0], bool)
input = np.array([[2, 2], [2, 4]], bool)
output = ndimage.minimum(input, labels=labels)
assert_almost_equal(output, 1.0)
def test_minimum03():
labels = np.array([1, 2])
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.minimum(input, labels=labels,
index=2)
assert_almost_equal(output, 2.0)
def test_minimum04():
labels = np.array([[1, 2], [2, 3]])
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.minimum(input, labels=labels,
index=[2, 3, 8])
assert_array_almost_equal(output, [2.0, 4.0, 0.0])
def test_maximum01():
labels = np.array([1, 0], bool)
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.maximum(input, labels=labels)
assert_almost_equal(output, 3.0)
def test_maximum02():
labels = np.array([1, 0], bool)
input = np.array([[2, 2], [2, 4]], bool)
output = ndimage.maximum(input, labels=labels)
assert_almost_equal(output, 1.0)
def test_maximum03():
labels = np.array([1, 2])
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.maximum(input, labels=labels,
index=2)
assert_almost_equal(output, 4.0)
def test_maximum04():
labels = np.array([[1, 2], [2, 3]])
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.maximum(input, labels=labels,
index=[2, 3, 8])
assert_array_almost_equal(output, [3.0, 4.0, 0.0])
def test_maximum05():
# Regression test for ticket #501 (Trac)
x = np.array([-3, -2, -1])
assert_equal(ndimage.maximum(x), -1)
def test_median01():
a = np.array([[1, 2, 0, 1],
[5, 3, 0, 4],
[0, 0, 0, 7],
[9, 3, 0, 0]])
labels = np.array([[1, 1, 0, 2],
[1, 1, 0, 2],
[0, 0, 0, 2],
[3, 3, 0, 0]])
output = ndimage.median(a, labels=labels, index=[1, 2, 3])
assert_array_almost_equal(output, [2.5, 4.0, 6.0])
def test_median02():
a = np.array([[1, 2, 0, 1],
[5, 3, 0, 4],
[0, 0, 0, 7],
[9, 3, 0, 0]])
output = ndimage.median(a)
assert_almost_equal(output, 1.0)
def test_median03():
a = np.array([[1, 2, 0, 1],
[5, 3, 0, 4],
[0, 0, 0, 7],
[9, 3, 0, 0]])
labels = np.array([[1, 1, 0, 2],
[1, 1, 0, 2],
[0, 0, 0, 2],
[3, 3, 0, 0]])
output = ndimage.median(a, labels=labels)
assert_almost_equal(output, 3.0)
def test_median_gh12836_bool():
# test boolean addition fix on example from gh-12836
a = np.asarray([1, 1], dtype=bool)
output = ndimage.median(a, labels=np.ones((2,)), index=[1])
assert_array_almost_equal(output, [1.0])
def test_median_no_int_overflow():
# test integer overflow fix on example from gh-12836
a = np.asarray([65, 70], dtype=np.int8)
output = ndimage.median(a, labels=np.ones((2,)), index=[1])
assert_array_almost_equal(output, [67.5])
def test_variance01():
with np.errstate(all='ignore'):
for type in types:
input = np.array([], type)
with suppress_warnings() as sup:
sup.filter(RuntimeWarning, "Mean of empty slice")
output = ndimage.variance(input)
assert_(np.isnan(output))
def test_variance02():
for type in types:
input = np.array([1], type)
output = ndimage.variance(input)
assert_almost_equal(output, 0.0)
def test_variance03():
for type in types:
input = np.array([1, 3], type)
output = ndimage.variance(input)
assert_almost_equal(output, 1.0)
def test_variance04():
input = np.array([1, 0], bool)
output = ndimage.variance(input)
assert_almost_equal(output, 0.25)
def test_variance05():
labels = [2, 2, 3]
for type in types:
input = np.array([1, 3, 8], type)
output = ndimage.variance(input, labels, 2)
assert_almost_equal(output, 1.0)
def test_variance06():
labels = [2, 2, 3, 3, 4]
with np.errstate(all='ignore'):
for type in types:
input = np.array([1, 3, 8, 10, 8], type)
output = ndimage.variance(input, labels, [2, 3, 4])
assert_array_almost_equal(output, [1.0, 1.0, 0.0])
def test_standard_deviation01():
with np.errstate(all='ignore'):
for type in types:
input = np.array([], type)
with suppress_warnings() as sup:
sup.filter(RuntimeWarning, "Mean of empty slice")
output = ndimage.standard_deviation(input)
assert_(np.isnan(output))
def test_standard_deviation02():
for type in types:
input = np.array([1], type)
output = ndimage.standard_deviation(input)
assert_almost_equal(output, 0.0)
def test_standard_deviation03():
for type in types:
input = np.array([1, 3], type)
output = ndimage.standard_deviation(input)
assert_almost_equal(output, np.sqrt(1.0))
def test_standard_deviation04():
input = np.array([1, 0], bool)
output = ndimage.standard_deviation(input)
assert_almost_equal(output, 0.5)
def test_standard_deviation05():
labels = [2, 2, 3]
for type in types:
input = np.array([1, 3, 8], type)
output = ndimage.standard_deviation(input, labels, 2)
assert_almost_equal(output, 1.0)
def test_standard_deviation06():
labels = [2, 2, 3, 3, 4]
with np.errstate(all='ignore'):
for type in types:
input = np.array([1, 3, 8, 10, 8], type)
output = ndimage.standard_deviation(input, labels, [2, 3, 4])
assert_array_almost_equal(output, [1.0, 1.0, 0.0])
def test_standard_deviation07():
labels = [1]
with np.errstate(all='ignore'):
for type in types:
input = np.array([-0.00619519], type)
output = ndimage.standard_deviation(input, labels, [1])
assert_array_almost_equal(output, [0])
def test_minimum_position01():
labels = np.array([1, 0], bool)
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.minimum_position(input, labels=labels)
assert_equal(output, (0, 0))
def test_minimum_position02():
for type in types:
input = np.array([[5, 4, 2, 5],
[3, 7, 0, 2],
[1, 5, 1, 1]], type)
output = ndimage.minimum_position(input)
assert_equal(output, (1, 2))
def test_minimum_position03():
input = np.array([[5, 4, 2, 5],
[3, 7, 0, 2],
[1, 5, 1, 1]], bool)
output = ndimage.minimum_position(input)
assert_equal(output, (1, 2))
def test_minimum_position04():
input = np.array([[5, 4, 2, 5],
[3, 7, 1, 2],
[1, 5, 1, 1]], bool)
output = ndimage.minimum_position(input)
assert_equal(output, (0, 0))
def test_minimum_position05():
labels = [1, 2, 0, 4]
for type in types:
input = np.array([[5, 4, 2, 5],
[3, 7, 0, 2],
[1, 5, 2, 3]], type)
output = ndimage.minimum_position(input, labels)
assert_equal(output, (2, 0))
def test_minimum_position06():
labels = [1, 2, 3, 4]
for type in types:
input = np.array([[5, 4, 2, 5],
[3, 7, 0, 2],
[1, 5, 1, 1]], type)
output = ndimage.minimum_position(input, labels, 2)
assert_equal(output, (0, 1))
def test_minimum_position07():
labels = [1, 2, 3, 4]
for type in types:
input = np.array([[5, 4, 2, 5],
[3, 7, 0, 2],
[1, 5, 1, 1]], type)
output = ndimage.minimum_position(input, labels,
[2, 3])
assert_equal(output[0], (0, 1))
assert_equal(output[1], (1, 2))
def test_maximum_position01():
labels = np.array([1, 0], bool)
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output = ndimage.maximum_position(input,
labels=labels)
assert_equal(output, (1, 0))
def test_maximum_position02():
for type in types:
input = np.array([[5, 4, 2, 5],
[3, 7, 8, 2],
[1, 5, 1, 1]], type)
output = ndimage.maximum_position(input)
assert_equal(output, (1, 2))
def test_maximum_position03():
input = np.array([[5, 4, 2, 5],
[3, 7, 8, 2],
[1, 5, 1, 1]], bool)
output = ndimage.maximum_position(input)
assert_equal(output, (0, 0))
def test_maximum_position04():
labels = [1, 2, 0, 4]
for type in types:
input = np.array([[5, 4, 2, 5],
[3, 7, 8, 2],
[1, 5, 1, 1]], type)
output = ndimage.maximum_position(input, labels)
assert_equal(output, (1, 1))
def test_maximum_position05():
labels = [1, 2, 0, 4]
for type in types:
input = np.array([[5, 4, 2, 5],
[3, 7, 8, 2],
[1, 5, 1, 1]], type)
output = ndimage.maximum_position(input, labels, 1)
assert_equal(output, (0, 0))
def test_maximum_position06():
labels = [1, 2, 0, 4]
for type in types:
input = np.array([[5, 4, 2, 5],
[3, 7, 8, 2],
[1, 5, 1, 1]], type)
output = ndimage.maximum_position(input, labels,
[1, 2])
assert_equal(output[0], (0, 0))
assert_equal(output[1], (1, 1))
def test_maximum_position07():
# Test float labels
labels = np.array([1.0, 2.5, 0.0, 4.5])
for type in types:
input = np.array([[5, 4, 2, 5],
[3, 7, 8, 2],
[1, 5, 1, 1]], type)
output = ndimage.maximum_position(input, labels,
[1.0, 4.5])
assert_equal(output[0], (0, 0))
assert_equal(output[1], (0, 3))
def test_extrema01():
labels = np.array([1, 0], bool)
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output1 = ndimage.extrema(input, labels=labels)
output2 = ndimage.minimum(input, labels=labels)
output3 = ndimage.maximum(input, labels=labels)
output4 = ndimage.minimum_position(input,
labels=labels)
output5 = ndimage.maximum_position(input,
labels=labels)
assert_equal(output1, (output2, output3, output4, output5))
def test_extrema02():
labels = np.array([1, 2])
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output1 = ndimage.extrema(input, labels=labels,
index=2)
output2 = ndimage.minimum(input, labels=labels,
index=2)
output3 = ndimage.maximum(input, labels=labels,
index=2)
output4 = ndimage.minimum_position(input,
labels=labels, index=2)
output5 = ndimage.maximum_position(input,
labels=labels, index=2)
assert_equal(output1, (output2, output3, output4, output5))
def test_extrema03():
labels = np.array([[1, 2], [2, 3]])
for type in types:
input = np.array([[1, 2], [3, 4]], type)
output1 = ndimage.extrema(input, labels=labels,
index=[2, 3, 8])
output2 = ndimage.minimum(input, labels=labels,
index=[2, 3, 8])
output3 = ndimage.maximum(input, labels=labels,
index=[2, 3, 8])
output4 = ndimage.minimum_position(input,
labels=labels, index=[2, 3, 8])
output5 = ndimage.maximum_position(input,
labels=labels, index=[2, 3, 8])
assert_array_almost_equal(output1[0], output2)
assert_array_almost_equal(output1[1], output3)
assert_array_almost_equal(output1[2], output4)
assert_array_almost_equal(output1[3], output5)
def test_extrema04():
labels = [1, 2, 0, 4]
for type in types:
input = np.array([[5, 4, 2, 5],
[3, 7, 8, 2],
[1, 5, 1, 1]], type)
output1 = ndimage.extrema(input, labels, [1, 2])
output2 = ndimage.minimum(input, labels, [1, 2])
output3 = ndimage.maximum(input, labels, [1, 2])
output4 = ndimage.minimum_position(input, labels,
[1, 2])
output5 = ndimage.maximum_position(input, labels,
[1, 2])
assert_array_almost_equal(output1[0], output2)
assert_array_almost_equal(output1[1], output3)
assert_array_almost_equal(output1[2], output4)
assert_array_almost_equal(output1[3], output5)
def test_center_of_mass01():
expected = [0.0, 0.0]
for type in types:
input = np.array([[1, 0], [0, 0]], type)
output = ndimage.center_of_mass(input)
assert_array_almost_equal(output, expected)
def test_center_of_mass02():
expected = [1, 0]
for type in types:
input = np.array([[0, 0], [1, 0]], type)
output = ndimage.center_of_mass(input)
assert_array_almost_equal(output, expected)
def test_center_of_mass03():
expected = [0, 1]
for type in types:
input = np.array([[0, 1], [0, 0]], type)
output = ndimage.center_of_mass(input)
assert_array_almost_equal(output, expected)
def test_center_of_mass04():
expected = [1, 1]
for type in types:
input = np.array([[0, 0], [0, 1]], type)
output = ndimage.center_of_mass(input)
assert_array_almost_equal(output, expected)
def test_center_of_mass05():
expected = [0.5, 0.5]
for type in types:
input = np.array([[1, 1], [1, 1]], type)
output = ndimage.center_of_mass(input)
assert_array_almost_equal(output, expected)
def test_center_of_mass06():
expected = [0.5, 0.5]
input = np.array([[1, 2], [3, 1]], bool)
output = ndimage.center_of_mass(input)
assert_array_almost_equal(output, expected)
def test_center_of_mass07():
labels = [1, 0]
expected = [0.5, 0.0]
input = np.array([[1, 2], [3, 1]], bool)
output = ndimage.center_of_mass(input, labels)
assert_array_almost_equal(output, expected)
def test_center_of_mass08():
labels = [1, 2]
expected = [0.5, 1.0]
input = np.array([[5, 2], [3, 1]], bool)
output = ndimage.center_of_mass(input, labels, 2)
assert_array_almost_equal(output, expected)
def test_center_of_mass09():
labels = [1, 2]
expected = [(0.5, 0.0), (0.5, 1.0)]
input = np.array([[1, 2], [1, 1]], bool)
output = ndimage.center_of_mass(input, labels, [1, 2])
assert_array_almost_equal(output, expected)
def test_histogram01():
expected = np.ones(10)
input = np.arange(10)
output = ndimage.histogram(input, 0, 10, 10)
assert_array_almost_equal(output, expected)
def test_histogram02():
labels = [1, 1, 1, 1, 2, 2, 2, 2]
expected = [0, 2, 0, 1, 1]
input = np.array([1, 1, 3, 4, 3, 3, 3, 3])
output = ndimage.histogram(input, 0, 4, 5, labels, 1)
assert_array_almost_equal(output, expected)
def test_histogram03():
labels = [1, 0, 1, 1, 2, 2, 2, 2]
expected1 = [0, 1, 0, 1, 1]
expected2 = [0, 0, 0, 3, 0]
input = np.array([1, 1, 3, 4, 3, 5, 3, 3])
output = ndimage.histogram(input, 0, 4, 5, labels, (1, 2))
assert_array_almost_equal(output[0], expected1)
assert_array_almost_equal(output[1], expected2)
def test_stat_funcs_2d():
a = np.array([[5, 6, 0, 0, 0], [8, 9, 0, 0, 0], [0, 0, 0, 3, 5]])
lbl = np.array([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 2, 2]])
mean = ndimage.mean(a, labels=lbl, index=[1, 2])
assert_array_equal(mean, [7.0, 4.0])
var = ndimage.variance(a, labels=lbl, index=[1, 2])
assert_array_equal(var, [2.5, 1.0])
std = ndimage.standard_deviation(a, labels=lbl, index=[1, 2])
assert_array_almost_equal(std, np.sqrt([2.5, 1.0]))
med = ndimage.median(a, labels=lbl, index=[1, 2])
assert_array_equal(med, [7.0, 4.0])
min = ndimage.minimum(a, labels=lbl, index=[1, 2])
assert_array_equal(min, [5, 3])
max = ndimage.maximum(a, labels=lbl, index=[1, 2])
assert_array_equal(max, [9, 5])
class TestWatershedIft:
def test_watershed_ift01(self):
data = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], np.uint8)
markers = np.array([[-1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], np.int8)
out = ndimage.watershed_ift(data, markers, structure=[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
expected = [[-1, -1, -1, -1, -1, -1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1]]
assert_array_almost_equal(out, expected)
def test_watershed_ift02(self):
data = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], np.uint8)
markers = np.array([[-1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], np.int8)
out = ndimage.watershed_ift(data, markers)
expected = [[-1, -1, -1, -1, -1, -1, -1],
[-1, -1, 1, 1, 1, -1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, -1, 1, 1, 1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1]]
assert_array_almost_equal(out, expected)
def test_watershed_ift03(self):
data = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0]], np.uint8)
markers = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 2, 0, 3, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, -1]], np.int8)
out = ndimage.watershed_ift(data, markers)
expected = [[-1, -1, -1, -1, -1, -1, -1],
[-1, -1, 2, -1, 3, -1, -1],
[-1, 2, 2, 3, 3, 3, -1],
[-1, 2, 2, 3, 3, 3, -1],
[-1, 2, 2, 3, 3, 3, -1],
[-1, -1, 2, -1, 3, -1, -1],
[-1, -1, -1, -1, -1, -1, -1]]
assert_array_almost_equal(out, expected)
def test_watershed_ift04(self):
data = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0]], np.uint8)
markers = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 2, 0, 3, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, -1]],
np.int8)
out = ndimage.watershed_ift(data, markers,
structure=[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
expected = [[-1, -1, -1, -1, -1, -1, -1],
[-1, 2, 2, 3, 3, 3, -1],
[-1, 2, 2, 3, 3, 3, -1],
[-1, 2, 2, 3, 3, 3, -1],
[-1, 2, 2, 3, 3, 3, -1],
[-1, 2, 2, 3, 3, 3, -1],
[-1, -1, -1, -1, -1, -1, -1]]
assert_array_almost_equal(out, expected)
def test_watershed_ift05(self):
data = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 1, 0, 1, 0, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0]], np.uint8)
markers = np.array([[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 3, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, -1]],
np.int8)
out = ndimage.watershed_ift(data, markers,
structure=[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
expected = [[-1, -1, -1, -1, -1, -1, -1],
[-1, 3, 3, 2, 2, 2, -1],
[-1, 3, 3, 2, 2, 2, -1],
[-1, 3, 3, 2, 2, 2, -1],
[-1, 3, 3, 2, 2, 2, -1],
[-1, 3, 3, 2, 2, 2, -1],
[-1, -1, -1, -1, -1, -1, -1]]
assert_array_almost_equal(out, expected)
def test_watershed_ift06(self):
data = np.array([[0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], np.uint8)
markers = np.array([[-1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], np.int8)
out = ndimage.watershed_ift(data, markers,
structure=[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
expected = [[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1]]
assert_array_almost_equal(out, expected)
def test_watershed_ift07(self):
shape = (7, 6)
data = np.zeros(shape, dtype=np.uint8)
data = data.transpose()
data[...] = np.array([[0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 1, 0],
[0, 1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], np.uint8)
markers = np.array([[-1, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0]], np.int8)
out = np.zeros(shape, dtype=np.int16)
out = out.transpose()
ndimage.watershed_ift(data, markers,
structure=[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]],
output=out)
expected = [[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, 1, 1, 1, 1, 1, -1],
[-1, -1, -1, -1, -1, -1, -1],
[-1, -1, -1, -1, -1, -1, -1]]
assert_array_almost_equal(out, expected)
def test_watershed_ift08(self):
# Test cost larger than uint8. See gh-10069.
shape = (2, 2)
data = np.array([[256, 0],
[0, 0]], np.uint16)
markers = np.array([[1, 0],
[0, 0]], np.int8)
out = ndimage.watershed_ift(data, markers)
expected = [[1, 1],
[1, 1]]
assert_array_almost_equal(out, expected) | unknown | codeparrot/codeparrot-clean | ||
# encoding: utf-8
"""
Copyright 2013 Jérémie BOUTOILLE
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
from struct import unpack
from viper.modules.pymacho.MachOLoadCommand import MachOLoadCommand
from viper.modules.pymacho.Utils import green
class MachORPathCommand(MachOLoadCommand):
path_offset = 0
path = ""
def __init__(self, macho_file=None, cmd=0):
self.cmd = cmd
if macho_file is not None:
self.parse(macho_file)
def parse(self, macho_file):
# get cmdsize
macho_file.seek(-4, 1)
cmdsize = unpack('<I', macho_file.read(4))[0]
# get string offset
self.path_offset = unpack('<I', macho_file.read(4))[0]
strlen = cmdsize - self.path_offset
# get path
extract = "<%s" % ('s'*strlen)
self.path = "".join(unpack(extract, macho_file.read(strlen)))
def write(self, macho_file):
before = macho_file.tell()
macho_file.write(pack('<II', self.cmd, 0x0))
macho_file.write(pack('<I', self.path_offset))
extract = "<"+str(len(self.path))+"s"
macho_file.write(pack(extract, self.path))
after = macho_file.tell()
macho_file.seek(before+4)
macho_file.write(pack('<I', after-before))
macho_file.seek(after)
def display(self, before=''):
print before + green("[+]")+" LC_RPATH"
print before + "\t- path : %s" % repr(self.path) | unknown | codeparrot/codeparrot-clean | ||
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import page as page_module
from telemetry import story
from page_sets import webgl_supported_shared_state
class MapsPage(page_module.Page):
def __init__(self, page_set):
super(MapsPage, self).__init__(
url='http://localhost:10020/tracker.html',
page_set=page_set,
name='Maps.maps_002',
shared_page_state_class=(
webgl_supported_shared_state.WebGLSupportedSharedState))
self.archive_data_file = 'data/maps.json'
@property
def skipped_gpus(self):
# Skip this intensive test on low-end devices. crbug.com/464731
return ['arm']
def RunNavigateSteps(self, action_runner):
super(MapsPage, self).RunNavigateSteps(action_runner)
action_runner.Wait(3)
def RunPageInteractions(self, action_runner):
with action_runner.CreateInteraction('MapAnimation'):
action_runner.WaitForJavaScriptCondition('window.testDone', 120)
class MapsPageSet(story.StorySet):
""" Google Maps examples """
def __init__(self):
super(MapsPageSet, self).__init__(
archive_data_file='data/maps.json',
cloud_storage_bucket=story.PUBLIC_BUCKET)
self.AddStory(MapsPage(self)) | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/python
import glob
import os
import sys
# This script is run from Build/<target>_default.build/$(PX4_BASE)/Firmware/src/systemcmds/topic_listener
# argv[1] must be the full path of the top Firmware dir
raw_messages = glob.glob(sys.argv[1]+"/msg/*.msg")
messages = []
message_elements = []
for index,m in enumerate(raw_messages):
temp_list_floats = []
temp_list_uint64 = []
temp_list_bool = []
if("pwm_input" not in m and "position_setpoint" not in m):
temp_list = []
f = open(m,'r')
for line in f.readlines():
if ('float32[' in line.split(' ')[0]):
num_floats = int(line.split(" ")[0].split("[")[1].split("]")[0])
temp_list.append(("float_array",line.split(' ')[1].split('\t')[0].split('\n')[0],num_floats))
elif ('float64[' in line.split(' ')[0]):
num_floats = int(line.split(" ")[0].split("[")[1].split("]")[0])
temp_list.append(("double_array",line.split(' ')[1].split('\t')[0].split('\n')[0],num_floats))
elif ('uint64[' in line.split(' ')[0]):
num_floats = int(line.split(" ")[0].split("[")[1].split("]")[0])
temp_list.append(("uint64_array",line.split(' ')[1].split('\t')[0].split('\n')[0],num_floats))
elif(line.split(' ')[0] == "float32"):
temp_list.append(("float",line.split(' ')[1].split('\t')[0].split('\n')[0]))
elif(line.split(' ')[0] == "float64"):
temp_list.append(("double",line.split(' ')[1].split('\t')[0].split('\n')[0]))
elif(line.split(' ')[0] == "uint64") and len(line.split('=')) == 1:
temp_list.append(("uint64",line.split(' ')[1].split('\t')[0].split('\n')[0]))
elif(line.split(' ')[0] == "uint32") and len(line.split('=')) == 1:
temp_list.append(("uint32",line.split(' ')[1].split('\t')[0].split('\n')[0]))
elif(line.split(' ')[0] == "uint16") and len(line.split('=')) == 1:
temp_list.append(("uint16",line.split(' ')[1].split('\t')[0].split('\n')[0]))
elif(line.split(' ')[0] == "int64") and len(line.split('=')) == 1:
temp_list.append(("int64",line.split(' ')[1].split('\t')[0].split('\n')[0]))
elif(line.split(' ')[0] == "int32") and len(line.split('=')) == 1:
temp_list.append(("int32",line.split(' ')[1].split('\t')[0].split('\n')[0]))
elif(line.split(' ')[0] == "int16") and len(line.split('=')) == 1:
temp_list.append(("int16",line.split(' ')[1].split('\t')[0].split('\n')[0]))
elif (line.split(' ')[0] == "bool") and len(line.split('=')) == 1:
temp_list.append(("bool",line.split(' ')[1].split('\t')[0].split('\n')[0]))
elif (line.split(' ')[0] == "uint8") and len(line.split('=')) == 1:
temp_list.append(("uint8",line.split(' ')[1].split('\t')[0].split('\n')[0]))
elif (line.split(' ')[0] == "int8") and len(line.split('=')) == 1:
temp_list.append(("int8",line.split(' ')[1].split('\t')[0].split('\n')[0]))
f.close()
(m_head, m_tail) = os.path.split(m)
message = m_tail.split('.')[0]
if message != "actuator_controls":
messages.append(message)
message_elements.append(temp_list)
#messages.append(m.split('/')[-1].split('.')[0])
num_messages = len(messages);
print("""
/****************************************************************************
*
* Copyright (c) 2015 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
/**
* @file topic_listener.cpp
*
* Autogenerated by Tools/generate_listener.py
*
* Tool for listening to topics when running flight stack on linux.
*/
#include <px4_middleware.h>
#include <px4_app.h>
#include <px4_config.h>
#include <uORB/uORB.h>
#include <string.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#define __STDC_FORMAT_MACROS
#include <inttypes.h>
#ifndef PRIu64
#define PRIu64 "llu"
#endif
#ifndef PRId64
#define PRId64 "lld"
#endif
""")
for m in messages:
print("#include <uORB/topics/%s.h>" % m)
print("""
extern "C" __EXPORT int listener_main(int argc, char *argv[]);
int listener_main(int argc, char *argv[]) {
int sub = -1;
orb_id_t ID;
if(argc < 2) {
printf("need at least two arguments: topic name. [optional number of messages to print]\\n");
return 1;
}
""")
print("\tunsigned num_msgs = (argc > 2) ? atoi(argv[2]) : 1;")
print("\tif (strncmp(argv[1],\"%s\",50) == 0) {" % messages[0])
print("\t\tsub = orb_subscribe(ORB_ID(%s));" % messages[0])
print("\t\tID = ORB_ID(%s);" % messages[0])
print("\t\tstruct %s_s container;" % messages[0])
print("\t\tmemset(&container, 0, sizeof(container));")
for index,m in enumerate(messages[1:]):
print("\t} else if (strncmp(argv[1],\"%s\",50) == 0) {" % m)
print("\t\tsub = orb_subscribe(ORB_ID(%s));" % m)
print("\t\tID = ORB_ID(%s);" % m)
print("\t\tstruct %s_s container;" % m)
print("\t\tmemset(&container, 0, sizeof(container));")
print("\t\tbool updated;")
print("\t\tunsigned i = 0;")
print("\t\twhile(i < num_msgs) {")
print("\t\t\torb_check(sub,&updated);")
print("\t\t\tif (i == 0) { updated = true; } else { usleep(500); }")
print("\t\t\ti++;")
print("\t\t\tif (updated) {")
print("\t\tprintf(\"\\nTOPIC: %s #%%d\\n\", i);" % m)
print("\t\t\torb_copy(ID,sub,&container);")
for item in message_elements[index+1]:
if item[0] == "float":
print("\t\t\tprintf(\"%s: %%8.4f\\n\",(double)container.%s);" % (item[1], item[1]))
elif item[0] == "float_array":
print("\t\t\tprintf(\"%s: \");" % item[1])
print("\t\t\tfor (int j = 0; j < %d; j++) {" % item[2])
print("\t\t\t\tprintf(\"%%8.4f \",(double)container.%s[j]);" % item[1])
print("\t\t\t}")
print("\t\t\tprintf(\"\\n\");")
elif item[0] == "double":
print("\t\t\tprintf(\"%s: %%8.4f\\n\",(double)container.%s);" % (item[1], item[1]))
elif item[0] == "double_array":
print("\t\t\tprintf(\"%s: \");" % item[1])
print("\t\t\tfor (int j = 0; j < %d; j++) {" % item[2])
print("\t\t\t\tprintf(\"%%8.4f \",(double)container.%s[j]);" % item[1])
print("\t\t\t}")
print("\t\t\tprintf(\"\\n\");")
elif item[0] == "uint64":
print("\t\t\tprintf(\"%s: %%\" PRIu64 \"\\n\",container.%s);" % (item[1], item[1]))
elif item[0] == "uint64_array":
print("\t\t\tprintf(\"%s: \");" % item[1])
print("\t\t\tfor (int j = 0; j < %d; j++) {" % item[2])
print("\t\t\t\tprintf(\"%%\" PRIu64 \"\",container.%s[j]);" % item[1])
print("\t\t\t}")
print("\t\t\tprintf(\"\\n\");")
elif item[0] == "int64":
print("\t\t\tprintf(\"%s: %%\" PRId64 \"\\n\",container.%s);" % (item[1], item[1]))
elif item[0] == "int32":
print("\t\t\tprintf(\"%s: %%d\\n\",container.%s);" % (item[1], item[1]))
elif item[0] == "uint32":
print("\t\t\tprintf(\"%s: %%u\\n\",container.%s);" % (item[1], item[1]))
elif item[0] == "int16":
print("\t\t\tprintf(\"%s: %%d\\n\",(int)container.%s);" % (item[1], item[1]))
elif item[0] == "uint16":
print("\t\t\tprintf(\"%s: %%u\\n\",(unsigned)container.%s);" % (item[1], item[1]))
elif item[0] == "int8":
print("\t\t\tprintf(\"%s: %%d\\n\",(int)container.%s);" % (item[1], item[1]))
elif item[0] == "uint8":
print("\t\t\tprintf(\"%s: %%u\\n\",(unsigned)container.%s);" % (item[1], item[1]))
elif item[0] == "bool":
print("\t\t\tprintf(\"%s: %%s\\n\",container.%s ? \"True\" : \"False\");" % (item[1], item[1]))
print("\t\t\t}")
print("\t\t}")
print("\t} else {")
print("\t\t printf(\" Topic did not match any known topics\\n\");")
print("\t}")
print("\t\torb_unsubscribe(sub);")
print("\t return 0;")
print("}") | unknown | codeparrot/codeparrot-clean | ||
import squeakspace.common.util as ut
import squeakspace.common.util_http as ht
import squeakspace.proxy.server.db_sqlite3 as db
import squeakspace.common.squeak_ex as ex
import config
def post_handler(environ):
query = ht.parse_post_request(environ)
cookies = ht.parse_cookies(environ)
user_id = ht.get_required_cookie(cookies, 'user_id')
session_id = ht.get_required_cookie(cookies, 'session_id')
public_key_hash = ht.get_required(query, 'public_key_hash')
data = ht.get_required(query, 'data')
passphrase = ht.get_optional(query, 'passphrase')
conn = db.connect(config.db_path)
try:
c = db.cursor(conn)
signature = db.sign(c, user_id, session_id, public_key_hash, data, passphrase)
raise ht.ok_json({'status' : 'ok', 'signature' : signature})
except ex.SqueakException as e:
raise ht.convert_squeak_exception(e)
finally:
db.close(conn)
def main_handler(environ):
ht.dispatch_on_method(environ, {
'POST' : post_handler})
def application(environ, start_response):
return ht.respond_with_handler(environ, start_response, main_handler) | unknown | codeparrot/codeparrot-clean | ||
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import annotations
from ansible.module_utils.facts.network.base import NetworkCollector
from ansible.module_utils.facts.network.generic_bsd import GenericBsdIfconfigNetwork
class NetBSDNetwork(GenericBsdIfconfigNetwork):
"""
This is the NetBSD Network Class.
It uses the GenericBsdIfconfigNetwork
"""
platform = 'NetBSD'
def parse_media_line(self, words, current_if, ips):
# example of line:
# $ ifconfig
# ne0: flags=8863<UP,BROADCAST,NOTRAILERS,RUNNING,SIMPLEX,MULTICAST> mtu 1500
# ec_capabilities=1<VLAN_MTU>
# ec_enabled=0
# address: 00:20:91:45:00:78
# media: Ethernet 10baseT full-duplex
# inet 192.168.156.29 netmask 0xffffff00 broadcast 192.168.156.255
current_if['media'] = words[1]
if len(words) > 2:
current_if['media_type'] = words[2]
if len(words) > 3:
current_if['media_options'] = words[3].split(',')
class NetBSDNetworkCollector(NetworkCollector):
_fact_class = NetBSDNetwork
_platform = 'NetBSD' | python | github | https://github.com/ansible/ansible | lib/ansible/module_utils/facts/network/netbsd.py |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'about.ui',
# licensing of 'about.ui' applies.
#
# Created: Wed Nov 21 18:09:38 2018
# by: pyside2-uic running on PySide2 5.11.2
#
# WARNING! All changes made in this file will be lost!
from PySide2 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(756, 395)
self.gridLayout = QtWidgets.QGridLayout(Dialog)
self.gridLayout.setObjectName("gridLayout")
self.labelVersion = QtWidgets.QLabel(Dialog)
self.labelVersion.setObjectName("labelVersion")
self.gridLayout.addWidget(self.labelVersion, 0, 0, 1, 1)
self.labelSupport = QtWidgets.QLabel(Dialog)
self.labelSupport.setObjectName("labelSupport")
self.gridLayout.addWidget(self.labelSupport, 1, 0, 1, 1)
self.labelLicense = QtWidgets.QLabel(Dialog)
self.labelLicense.setObjectName("labelLicense")
self.gridLayout.addWidget(self.labelLicense, 2, 0, 1, 1)
self.pushButton = QtWidgets.QPushButton(Dialog)
self.pushButton.setText("")
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(":/icon/mpowertcx icon flat.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.pushButton.setIcon(icon)
self.pushButton.setIconSize(QtCore.QSize(256, 256))
self.pushButton.setFlat(True)
self.pushButton.setObjectName("pushButton")
self.gridLayout.addWidget(self.pushButton, 3, 1, 1, 1)
spacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Expanding)
self.gridLayout.addItem(spacerItem, 4, 1, 1, 1)
self.licenseEdit = QtWidgets.QPlainTextEdit(Dialog)
self.licenseEdit.setFrameShape(QtWidgets.QFrame.NoFrame)
self.licenseEdit.setReadOnly(True)
self.licenseEdit.setObjectName("licenseEdit")
self.gridLayout.addWidget(self.licenseEdit, 3, 0, 2, 1)
self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Ok)
self.buttonBox.setCenterButtons(True)
self.buttonBox.setObjectName("buttonBox")
self.gridLayout.addWidget(self.buttonBox, 5, 0, 1, 2)
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtWidgets.QApplication.translate("Dialog", "MPowerTCX: About", None, -1))
self.labelVersion.setText(QtWidgets.QApplication.translate("Dialog", "Version:", None, -1))
self.labelSupport.setText(QtWidgets.QApplication.translate("Dialog", "Support: j33433@gmail.com", None, -1))
self.labelLicense.setText(QtWidgets.QApplication.translate("Dialog", "License:", None, -1))
#import images_rc | unknown | codeparrot/codeparrot-clean | ||
#!/usr/bin/env python
from ansible.module_utils.hashivault import hashivault_argspec
from ansible.module_utils.hashivault import hashivault_auth_client
from ansible.module_utils.hashivault import hashivault_init
from ansible.module_utils.hashivault import hashiwrapper
ANSIBLE_METADATA = {'status': ['deprecated'], 'supported_by': 'community', 'version': '1.1'}
DOCUMENTATION = '''
---
module: hashivault_audit_enable
version_added: "2.2.0"
short_description: Hashicorp Vault audit enable module
description:
- Module to enable audit backends in Hashicorp Vault. Use hashivault_audit instead.
options:
name:
description:
- name of auditor
description:
description:
- description of auditor
options:
description:
- options for auditor
extends_documentation_fragment: hashivault
'''
EXAMPLES = '''
---
- hosts: localhost
tasks:
- hashivault_audit_enable:
name: "syslog"
'''
def main():
argspec = hashivault_argspec()
argspec['name'] = dict(required=True, type='str')
argspec['description'] = dict(required=False, type='str')
argspec['options'] = dict(required=False, type='dict')
module = hashivault_init(argspec)
result = hashivault_audit_enable(module.params)
if result.get('failed'):
module.fail_json(**result)
else:
module.exit_json(**result)
@hashiwrapper
def hashivault_audit_enable(params):
client = hashivault_auth_client(params)
name = params.get('name')
description = params.get('description')
options = params.get('options')
backends = client.sys.list_enabled_audit_devices()
backends = backends.get('data', backends)
path = name + "/"
if path in backends and backends[path]["options"] == options:
return {'changed': False}
client.sys.enable_audit_device(name, description=description, options=options)
return {'changed': True}
if __name__ == '__main__':
main() | unknown | codeparrot/codeparrot-clean | ||
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the "Elastic License
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
* Public License v 1"; you may not use this file except in compliance with, at
* your election, the "Elastic License 2.0", the "GNU Affero General Public
* License v3.0 only", or the "Server Side Public License, v 1".
*/
package org.elasticsearch.plugins.cli.test_model;
import org.elasticsearch.plugin.Extensible;
@Extensible
public interface ExtensibleInterface {} | java | github | https://github.com/elastic/elasticsearch | distribution/tools/plugin-cli/src/test/java/org/elasticsearch/plugins/cli/test_model/ExtensibleInterface.java |
"""Locations where we look for configs, install stuff, etc"""
from __future__ import absolute_import
import os
import os.path
import site
import sys
from distutils import sysconfig
from distutils.command.install import install, SCHEME_KEYS # noqa
from pip.compat import WINDOWS, expanduser
from pip.utils import appdirs
# Application Directories
USER_CACHE_DIR = appdirs.user_cache_dir("pip")
DELETE_MARKER_MESSAGE = '''\
This file is placed here by pip to indicate the source was put
here by pip.
Once this package is successfully installed this source code will be
deleted (unless you remove this file).
'''
PIP_DELETE_MARKER_FILENAME = 'pip-delete-this-directory.txt'
def write_delete_marker_file(directory):
"""
Write the pip delete marker file into this directory.
"""
filepath = os.path.join(directory, PIP_DELETE_MARKER_FILENAME)
with open(filepath, 'w') as marker_fp:
marker_fp.write(DELETE_MARKER_MESSAGE)
def running_under_virtualenv():
"""
Return True if we're running inside a virtualenv, False otherwise.
"""
if hasattr(sys, 'real_prefix'):
return True
elif sys.prefix != getattr(sys, "base_prefix", sys.prefix):
return True
return False
def virtualenv_no_global():
"""
Return True if in a venv and no system site packages.
"""
# this mirrors the logic in virtualenv.py for locating the
# no-global-site-packages.txt file
site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))
no_global_file = os.path.join(site_mod_dir, 'no-global-site-packages.txt')
if running_under_virtualenv() and os.path.isfile(no_global_file):
return True
if running_under_virtualenv():
src_prefix = os.path.join(sys.prefix, 'src')
else:
# FIXME: keep src in cwd for now (it is not a temporary folder)
try:
src_prefix = os.path.join(os.getcwd(), 'src')
except OSError:
# In case the current working directory has been renamed or deleted
sys.exit(
"The folder you are executing pip from can no longer be found."
)
# under Mac OS X + virtualenv sys.prefix is not properly resolved
# it is something like /path/to/python/bin/..
# Note: using realpath due to tmp dirs on OSX being symlinks
src_prefix = os.path.abspath(src_prefix)
# FIXME doesn't account for venv linked to global site-packages
site_packages = sysconfig.get_python_lib()
user_site = site.USER_SITE
user_dir = expanduser('~')
if WINDOWS:
bin_py = os.path.join(sys.prefix, 'Scripts')
bin_user = os.path.join(user_site, 'Scripts')
# buildout uses 'bin' on Windows too?
if not os.path.exists(bin_py):
bin_py = os.path.join(sys.prefix, 'bin')
bin_user = os.path.join(user_site, 'bin')
config_basename = 'pip.ini'
legacy_storage_dir = os.path.join(user_dir, 'pip')
legacy_config_file = os.path.join(
legacy_storage_dir,
config_basename,
)
else:
bin_py = os.path.join(sys.prefix, 'bin')
bin_user = os.path.join(user_site, 'bin')
config_basename = 'pip.conf'
legacy_storage_dir = os.path.join(user_dir, '.pip')
legacy_config_file = os.path.join(
legacy_storage_dir,
config_basename,
)
# Forcing to use /usr/local/bin for standard Mac OS X framework installs
# Also log to ~/Library/Logs/ for use with the Console.app log viewer
if sys.platform[:6] == 'darwin' and sys.prefix[:16] == '/System/Library/':
bin_py = '/usr/local/bin'
site_config_files = [
os.path.join(path, config_basename)
for path in appdirs.site_config_dirs('pip')
]
def distutils_scheme(dist_name, user=False, home=None, root=None,
isolated=False, prefix=None):
"""
Return a distutils install scheme
"""
from distutils.dist import Distribution
scheme = {}
if isolated:
extra_dist_args = {"script_args": ["--no-user-cfg"]}
else:
extra_dist_args = {}
dist_args = {'name': dist_name}
dist_args.update(extra_dist_args)
d = Distribution(dist_args)
d.parse_config_files()
i = d.get_command_obj('install', create=True)
# NOTE: setting user or home has the side-effect of creating the home dir
# or user base for installations during finalize_options()
# ideally, we'd prefer a scheme class that has no side-effects.
assert not (user and prefix), "user={0} prefix={1}".format(user, prefix)
i.user = user or i.user
if user:
i.prefix = ""
i.prefix = prefix or i.prefix
i.home = home or i.home
i.root = root or i.root
i.finalize_options()
for key in SCHEME_KEYS:
scheme[key] = getattr(i, 'install_' + key)
# install_lib specified in setup.cfg should install *everything*
# into there (i.e. it takes precedence over both purelib and
# platlib). Note, i.install_lib is *always* set after
# finalize_options(); we only want to override here if the user
# has explicitly requested it hence going back to the config
if 'install_lib' in d.get_option_dict('install'):
scheme.update(dict(purelib=i.install_lib, platlib=i.install_lib))
if running_under_virtualenv():
scheme['headers'] = os.path.join(
sys.prefix,
'include',
'site',
'python' + sys.version[:3],
dist_name,
)
if root is not None:
path_no_drive = os.path.splitdrive(
os.path.abspath(scheme["headers"]))[1]
scheme["headers"] = os.path.join(
root,
path_no_drive[1:],
)
return scheme | unknown | codeparrot/codeparrot-clean | ||
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
function newName(param: boolean) {
if (param) {
return false;
}
return true;
} | typescript | github | https://github.com/angular/angular | adev/shared-docs/pipeline/shared/marked/test/docs-code/new-code.ts |
# SPDX-License-Identifier: (GPL-2.0 OR BSD-2-Clause)
# Copyright 2019 BayLibre, SAS
%YAML 1.2
---
$id: http://devicetree.org/schemas/net/amlogic,meson-dwmac.yaml#
$schema: http://devicetree.org/meta-schemas/core.yaml#
title: Amlogic Meson DWMAC Ethernet controller
maintainers:
- Neil Armstrong <neil.armstrong@linaro.org>
- Martin Blumenstingl <martin.blumenstingl@googlemail.com>
# We need a select here so we don't match all nodes with 'snps,dwmac'
select:
properties:
compatible:
contains:
enum:
- amlogic,meson6-dwmac
- amlogic,meson8b-dwmac
- amlogic,meson8m2-dwmac
- amlogic,meson-gxbb-dwmac
- amlogic,meson-axg-dwmac
- amlogic,meson-g12a-dwmac
required:
- compatible
allOf:
- $ref: snps,dwmac.yaml#
- if:
properties:
compatible:
contains:
enum:
- amlogic,meson8b-dwmac
- amlogic,meson8m2-dwmac
- amlogic,meson-gxbb-dwmac
- amlogic,meson-axg-dwmac
- amlogic,meson-g12a-dwmac
then:
properties:
clocks:
minItems: 3
items:
- description: GMAC main clock
- description: First parent clock of the internal mux
- description: Second parent clock of the internal mux
- description: The clock which drives the timing adjustment logic
clock-names:
minItems: 3
items:
- const: stmmaceth
- const: clkin0
- const: clkin1
- const: timing-adjustment
amlogic,tx-delay-ns:
enum: [0, 2, 4, 6]
default: 2
description:
The internal RGMII TX clock delay (provided by this driver)
in nanoseconds. When phy-mode is set to "rgmii" then the TX
delay should be explicitly configured. When the phy-mode is
set to either "rgmii-id" or "rgmii-txid" the TX clock delay
is already provided by the PHY. In that case this property
should be set to 0ns (which disables the TX clock delay in
the MAC to prevent the clock from going off because both
PHY and MAC are adding a delay). Any configuration is
ignored when the phy-mode is set to "rmii".
amlogic,rx-delay-ns:
deprecated: true
enum:
- 0
- 2
default: 0
description:
The internal RGMII RX clock delay in nanoseconds. Deprecated, use
rx-internal-delay-ps instead.
rx-internal-delay-ps:
default: 0
- if:
properties:
compatible:
contains:
enum:
- amlogic,meson8b-dwmac
- amlogic,meson8m2-dwmac
- amlogic,meson-gxbb-dwmac
- amlogic,meson-axg-dwmac
then:
properties:
rx-internal-delay-ps:
enum:
- 0
- 2000
- if:
properties:
compatible:
contains:
enum:
- amlogic,meson-g12a-dwmac
then:
properties:
rx-internal-delay-ps:
enum:
- 0
- 200
- 400
- 600
- 800
- 1000
- 1200
- 1400
- 1600
- 1800
- 2000
- 2200
- 2400
- 2600
- 2800
- 3000
properties:
compatible:
additionalItems: true
maxItems: 3
items:
- enum:
- amlogic,meson6-dwmac
- amlogic,meson8b-dwmac
- amlogic,meson8m2-dwmac
- amlogic,meson-gxbb-dwmac
- amlogic,meson-axg-dwmac
- amlogic,meson-g12a-dwmac
contains:
enum:
- snps,dwmac-3.70a
- snps,dwmac
reg:
items:
- description:
The first register range should be the one of the DWMAC controller
- description:
The second range is for the Amlogic specific configuration
(for example the PRG_ETHERNET register range on Meson8b and newer)
interrupts:
maxItems: 1
interrupt-names:
const: macirq
required:
- compatible
- reg
- interrupts
- interrupt-names
- clocks
- clock-names
- phy-mode
unevaluatedProperties: false
examples:
- |
ethmac: ethernet@c9410000 {
compatible = "amlogic,meson-gxbb-dwmac", "snps,dwmac";
reg = <0xc9410000 0x10000>, <0xc8834540 0x8>;
interrupts = <8>;
interrupt-names = "macirq";
clocks = <&clk_eth>, <&clk_fclk_div2>, <&clk_mpll2>, <&clk_fclk_div2>;
clock-names = "stmmaceth", "clkin0", "clkin1", "timing-adjustment";
phy-mode = "rgmii";
}; | unknown | github | https://github.com/torvalds/linux | Documentation/devicetree/bindings/net/amlogic,meson-dwmac.yaml |
"""
Form classes
"""
from __future__ import absolute_import, unicode_literals
import copy
from django.core.exceptions import ValidationError
from django.forms.fields import Field, FileField
from django.forms.util import flatatt, ErrorDict, ErrorList
from django.forms.widgets import Media, media_property, TextInput, Textarea
from django.utils.datastructures import SortedDict
from django.utils.html import conditional_escape, format_html
from django.utils.encoding import smart_text, force_text, python_2_unicode_compatible
from django.utils.safestring import mark_safe
from django.utils import six
__all__ = ('BaseForm', 'Form')
NON_FIELD_ERRORS = '__all__'
def pretty_name(name):
"""Converts 'first_name' to 'First name'"""
if not name:
return ''
return name.replace('_', ' ').capitalize()
def get_declared_fields(bases, attrs, with_base_fields=True):
"""
Create a list of form field instances from the passed in 'attrs', plus any
similar fields on the base classes (in 'bases'). This is used by both the
Form and ModelForm metclasses.
If 'with_base_fields' is True, all fields from the bases are used.
Otherwise, only fields in the 'declared_fields' attribute on the bases are
used. The distinction is useful in ModelForm subclassing.
Also integrates any additional media definitions
"""
fields = [(field_name, attrs.pop(field_name)) for field_name, obj in list(six.iteritems(attrs)) if isinstance(obj, Field)]
fields.sort(key=lambda x: x[1].creation_counter)
# If this class is subclassing another Form, add that Form's fields.
# Note that we loop over the bases in *reverse*. This is necessary in
# order to preserve the correct order of fields.
if with_base_fields:
for base in bases[::-1]:
if hasattr(base, 'base_fields'):
fields = list(six.iteritems(base.base_fields)) + fields
else:
for base in bases[::-1]:
if hasattr(base, 'declared_fields'):
fields = list(six.iteritems(base.declared_fields)) + fields
return SortedDict(fields)
class DeclarativeFieldsMetaclass(type):
"""
Metaclass that converts Field attributes to a dictionary called
'base_fields', taking into account parent class 'base_fields' as well.
"""
def __new__(cls, name, bases, attrs):
attrs['base_fields'] = get_declared_fields(bases, attrs)
new_class = super(DeclarativeFieldsMetaclass,
cls).__new__(cls, name, bases, attrs)
if 'media' not in attrs:
new_class.media = media_property(new_class)
return new_class
@python_2_unicode_compatible
class BaseForm(object):
# This is the main implementation of all the Form logic. Note that this
# class is different than Form. See the comments by the Form class for more
# information. Any improvements to the form API should be made to *this*
# class, not to the Form class.
def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=':',
empty_permitted=False):
self.is_bound = data is not None or files is not None
self.data = data or {}
self.files = files or {}
self.auto_id = auto_id
self.prefix = prefix
self.initial = initial or {}
self.error_class = error_class
self.label_suffix = label_suffix
self.empty_permitted = empty_permitted
self._errors = None # Stores the errors after clean() has been called.
self._changed_data = None
# The base_fields class attribute is the *class-wide* definition of
# fields. Because a particular *instance* of the class might want to
# alter self.fields, we create self.fields here by copying base_fields.
# Instances should always modify self.fields; they should not modify
# self.base_fields.
self.fields = copy.deepcopy(self.base_fields)
def __str__(self):
return self.as_table()
def __iter__(self):
for name in self.fields:
yield self[name]
def __getitem__(self, name):
"Returns a BoundField with the given name."
try:
field = self.fields[name]
except KeyError:
raise KeyError('Key %r not found in Form' % name)
return BoundField(self, field, name)
def _get_errors(self):
"Returns an ErrorDict for the data provided for the form"
if self._errors is None:
self.full_clean()
return self._errors
errors = property(_get_errors)
def is_valid(self):
"""
Returns True if the form has no errors. Otherwise, False. If errors are
being ignored, returns False.
"""
return self.is_bound and not bool(self.errors)
def add_prefix(self, field_name):
"""
Returns the field name with a prefix appended, if this Form has a
prefix set.
Subclasses may wish to override.
"""
return self.prefix and ('%s-%s' % (self.prefix, field_name)) or field_name
def add_initial_prefix(self, field_name):
"""
Add a 'initial' prefix for checking dynamic initial values
"""
return 'initial-%s' % self.add_prefix(field_name)
def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
"Helper function for outputting HTML. Used by as_table(), as_ul(), as_p()."
top_errors = self.non_field_errors() # Errors that should be displayed above all fields.
output, hidden_fields = [], []
for name, field in self.fields.items():
html_class_attr = ''
bf = self[name]
bf_errors = self.error_class([conditional_escape(error) for error in bf.errors]) # Escape and cache in local variable.
if bf.is_hidden:
if bf_errors:
top_errors.extend(['(Hidden field %s) %s' % (name, force_text(e)) for e in bf_errors])
hidden_fields.append(six.text_type(bf))
else:
# Create a 'class="..."' atribute if the row should have any
# CSS classes applied.
css_classes = bf.css_classes()
if css_classes:
html_class_attr = ' class="%s"' % css_classes
if errors_on_separate_row and bf_errors:
output.append(error_row % force_text(bf_errors))
if bf.label:
label = conditional_escape(force_text(bf.label))
# Only add the suffix if the label does not end in
# punctuation.
if self.label_suffix:
if label[-1] not in ':?.!':
label = format_html('{0}{1}', label, self.label_suffix)
label = bf.label_tag(label) or ''
else:
label = ''
if field.help_text:
help_text = help_text_html % force_text(field.help_text)
else:
help_text = ''
output.append(normal_row % {
'errors': force_text(bf_errors),
'label': force_text(label),
'field': six.text_type(bf),
'help_text': help_text,
'html_class_attr': html_class_attr
})
if top_errors:
output.insert(0, error_row % force_text(top_errors))
if hidden_fields: # Insert any hidden fields in the last row.
str_hidden = ''.join(hidden_fields)
if output:
last_row = output[-1]
# Chop off the trailing row_ender (e.g. '</td></tr>') and
# insert the hidden fields.
if not last_row.endswith(row_ender):
# This can happen in the as_p() case (and possibly others
# that users write): if there are only top errors, we may
# not be able to conscript the last row for our purposes,
# so insert a new, empty row.
last_row = (normal_row % {'errors': '', 'label': '',
'field': '', 'help_text':'',
'html_class_attr': html_class_attr})
output.append(last_row)
output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender
else:
# If there aren't any rows in the output, just append the
# hidden fields.
output.append(str_hidden)
return mark_safe('\n'.join(output))
def as_table(self):
"Returns this form rendered as HTML <tr>s -- excluding the <table></table>."
return self._html_output(
normal_row = '<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
error_row = '<tr><td colspan="2">%s</td></tr>',
row_ender = '</td></tr>',
help_text_html = '<br /><span class="helptext">%s</span>',
errors_on_separate_row = False)
def as_ul(self):
"Returns this form rendered as HTML <li>s -- excluding the <ul></ul>."
return self._html_output(
normal_row = '<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
error_row = '<li>%s</li>',
row_ender = '</li>',
help_text_html = ' <span class="helptext">%s</span>',
errors_on_separate_row = False)
def as_p(self):
"Returns this form rendered as HTML <p>s."
return self._html_output(
normal_row = '<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
error_row = '%s',
row_ender = '</p>',
help_text_html = ' <span class="helptext">%s</span>',
errors_on_separate_row = True)
def non_field_errors(self):
"""
Returns an ErrorList of errors that aren't associated with a particular
field -- i.e., from Form.clean(). Returns an empty ErrorList if there
are none.
"""
return self.errors.get(NON_FIELD_ERRORS, self.error_class())
def _raw_value(self, fieldname):
"""
Returns the raw_value for a particular field name. This is just a
convenient wrapper around widget.value_from_datadict.
"""
field = self.fields[fieldname]
prefix = self.add_prefix(fieldname)
return field.widget.value_from_datadict(self.data, self.files, prefix)
def full_clean(self):
"""
Cleans all of self.data and populates self._errors and
self.cleaned_data.
"""
self._errors = ErrorDict()
if not self.is_bound: # Stop further processing.
return
self.cleaned_data = {}
# If the form is permitted to be empty, and none of the form data has
# changed from the initial data, short circuit any validation.
if self.empty_permitted and not self.has_changed():
return
self._clean_fields()
self._clean_form()
self._post_clean()
def _clean_fields(self):
for name, field in self.fields.items():
# value_from_datadict() gets the data from the data dictionaries.
# Each widget type knows how to retrieve its own data, because some
# widgets split data over several HTML fields.
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
try:
if isinstance(field, FileField):
initial = self.initial.get(name, field.initial)
value = field.clean(value, initial)
else:
value = field.clean(value)
self.cleaned_data[name] = value
if hasattr(self, 'clean_%s' % name):
value = getattr(self, 'clean_%s' % name)()
self.cleaned_data[name] = value
except ValidationError as e:
self._errors[name] = self.error_class(e.messages)
if name in self.cleaned_data:
del self.cleaned_data[name]
def _clean_form(self):
try:
self.cleaned_data = self.clean()
except ValidationError as e:
self._errors[NON_FIELD_ERRORS] = self.error_class(e.messages)
def _post_clean(self):
"""
An internal hook for performing additional cleaning after form cleaning
is complete. Used for model validation in model forms.
"""
pass
def clean(self):
"""
Hook for doing any extra form-wide cleaning after Field.clean() been
called on every field. Any ValidationError raised by this method will
not be associated with a particular field; it will have a special-case
association with the field named '__all__'.
"""
return self.cleaned_data
def has_changed(self):
"""
Returns True if data differs from initial.
"""
return bool(self.changed_data)
def _get_changed_data(self):
if self._changed_data is None:
self._changed_data = []
# XXX: For now we're asking the individual widgets whether or not the
# data has changed. It would probably be more efficient to hash the
# initial data, store it in a hidden field, and compare a hash of the
# submitted data, but we'd need a way to easily get the string value
# for a given field. Right now, that logic is embedded in the render
# method of each widget.
for name, field in self.fields.items():
prefixed_name = self.add_prefix(name)
data_value = field.widget.value_from_datadict(self.data, self.files, prefixed_name)
if not field.show_hidden_initial:
initial_value = self.initial.get(name, field.initial)
else:
initial_prefixed_name = self.add_initial_prefix(name)
hidden_widget = field.hidden_widget()
initial_value = hidden_widget.value_from_datadict(
self.data, self.files, initial_prefixed_name)
if field.widget._has_changed(initial_value, data_value):
self._changed_data.append(name)
return self._changed_data
changed_data = property(_get_changed_data)
def _get_media(self):
"""
Provide a description of all media required to render the widgets on this form
"""
media = Media()
for field in self.fields.values():
media = media + field.widget.media
return media
media = property(_get_media)
def is_multipart(self):
"""
Returns True if the form needs to be multipart-encoded, i.e. it has
FileInput. Otherwise, False.
"""
for field in self.fields.values():
if field.widget.needs_multipart_form:
return True
return False
def hidden_fields(self):
"""
Returns a list of all the BoundField objects that are hidden fields.
Useful for manual form layout in templates.
"""
return [field for field in self if field.is_hidden]
def visible_fields(self):
"""
Returns a list of BoundField objects that aren't hidden fields.
The opposite of the hidden_fields() method.
"""
return [field for field in self if not field.is_hidden]
class Form(six.with_metaclass(DeclarativeFieldsMetaclass, BaseForm)):
"A collection of Fields, plus their associated data."
# This is a separate class from BaseForm in order to abstract the way
# self.fields is specified. This class (Form) is the one that does the
# fancy metaclass stuff purely for the semantic sugar -- it allows one
# to define a form using declarative syntax.
# BaseForm itself has no way of designating self.fields.
@python_2_unicode_compatible
class BoundField(object):
"A Field plus data"
def __init__(self, form, field, name):
self.form = form
self.field = field
self.name = name
self.html_name = form.add_prefix(name)
self.html_initial_name = form.add_initial_prefix(name)
self.html_initial_id = form.add_initial_prefix(self.auto_id)
if self.field.label is None:
self.label = pretty_name(name)
else:
self.label = self.field.label
self.help_text = field.help_text or ''
def __str__(self):
"""Renders this field as an HTML widget."""
if self.field.show_hidden_initial:
return self.as_widget() + self.as_hidden(only_initial=True)
return self.as_widget()
def __iter__(self):
"""
Yields rendered strings that comprise all widgets in this BoundField.
This really is only useful for RadioSelect widgets, so that you can
iterate over individual radio buttons in a template.
"""
for subwidget in self.field.widget.subwidgets(self.html_name, self.value()):
yield subwidget
def __len__(self):
return len(list(self.__iter__()))
def __getitem__(self, idx):
return list(self.__iter__())[idx]
def _errors(self):
"""
Returns an ErrorList for this field. Returns an empty ErrorList
if there are none.
"""
return self.form.errors.get(self.name, self.form.error_class())
errors = property(_errors)
def as_widget(self, widget=None, attrs=None, only_initial=False):
"""
Renders the field by rendering the passed widget, adding any HTML
attributes passed as attrs. If no widget is specified, then the
field's default widget will be used.
"""
if not widget:
widget = self.field.widget
attrs = attrs or {}
auto_id = self.auto_id
if auto_id and 'id' not in attrs and 'id' not in widget.attrs:
if not only_initial:
attrs['id'] = auto_id
else:
attrs['id'] = self.html_initial_id
if not only_initial:
name = self.html_name
else:
name = self.html_initial_name
return widget.render(name, self.value(), attrs=attrs)
def as_text(self, attrs=None, **kwargs):
"""
Returns a string of HTML for representing this as an <input type="text">.
"""
return self.as_widget(TextInput(), attrs, **kwargs)
def as_textarea(self, attrs=None, **kwargs):
"Returns a string of HTML for representing this as a <textarea>."
return self.as_widget(Textarea(), attrs, **kwargs)
def as_hidden(self, attrs=None, **kwargs):
"""
Returns a string of HTML for representing this as an <input type="hidden">.
"""
return self.as_widget(self.field.hidden_widget(), attrs, **kwargs)
def _data(self):
"""
Returns the data for this BoundField, or None if it wasn't given.
"""
return self.field.widget.value_from_datadict(self.form.data, self.form.files, self.html_name)
data = property(_data)
def value(self):
"""
Returns the value for this BoundField, using the initial value if
the form is not bound or the data otherwise.
"""
if not self.form.is_bound:
data = self.form.initial.get(self.name, self.field.initial)
if callable(data):
data = data()
else:
data = self.field.bound_data(
self.data, self.form.initial.get(self.name, self.field.initial)
)
return self.field.prepare_value(data)
def label_tag(self, contents=None, attrs=None):
"""
Wraps the given contents in a <label>, if the field has an ID attribute.
contents should be 'mark_safe'd to avoid HTML escaping. If contents
aren't given, uses the field's HTML-escaped label.
If attrs are given, they're used as HTML attributes on the <label> tag.
"""
contents = contents or self.label
widget = self.field.widget
id_ = widget.attrs.get('id') or self.auto_id
if id_:
attrs = attrs and flatatt(attrs) or ''
contents = format_html('<label for="{0}"{1}>{2}</label>',
widget.id_for_label(id_), attrs, contents
)
else:
contents = conditional_escape(contents)
return mark_safe(contents)
def css_classes(self, extra_classes=None):
"""
Returns a string of space-separated CSS classes for this field.
"""
if hasattr(extra_classes, 'split'):
extra_classes = extra_classes.split()
extra_classes = set(extra_classes or [])
if self.errors and hasattr(self.form, 'error_css_class'):
extra_classes.add(self.form.error_css_class)
if self.field.required and hasattr(self.form, 'required_css_class'):
extra_classes.add(self.form.required_css_class)
return ' '.join(extra_classes)
def _is_hidden(self):
"Returns True if this BoundField's widget is hidden."
return self.field.widget.is_hidden
is_hidden = property(_is_hidden)
def _auto_id(self):
"""
Calculates and returns the ID attribute for this BoundField, if the
associated Form has specified auto_id. Returns an empty string otherwise.
"""
auto_id = self.form.auto_id
if auto_id and '%s' in smart_text(auto_id):
return smart_text(auto_id) % self.html_name
elif auto_id:
return self.html_name
return ''
auto_id = property(_auto_id)
def _id_for_label(self):
"""
Wrapper around the field widget's `id_for_label` method.
Useful, for example, for focusing on this field regardless of whether
it has a single widget or a MutiWidget.
"""
widget = self.field.widget
id_ = widget.attrs.get('id') or self.auto_id
return widget.id_for_label(id_)
id_for_label = property(_id_for_label) | unknown | codeparrot/codeparrot-clean | ||
// Copyright IBM Corp. 2016, 2025
// SPDX-License-Identifier: BUSL-1.1
package agent
import (
"context"
"errors"
"fmt"
"os"
"path/filepath"
"testing"
"time"
ctconfig "github.com/hashicorp/consul-template/config"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/vault/api"
agentConfig "github.com/hashicorp/vault/command/agent/config"
"github.com/hashicorp/vault/command/agent/template"
"github.com/hashicorp/vault/command/agentproxyshared/auth"
tokenfile "github.com/hashicorp/vault/command/agentproxyshared/auth/token-file"
"github.com/hashicorp/vault/command/agentproxyshared/sink"
"github.com/hashicorp/vault/command/agentproxyshared/sink/file"
"github.com/hashicorp/vault/helper/testhelpers/corehelpers"
"github.com/hashicorp/vault/helper/testhelpers/minimal"
"github.com/hashicorp/vault/sdk/helper/pointerutil"
"github.com/stretchr/testify/require"
)
// TestAutoAuthSelfHealing_TokenFileAuth_SinkOutput tests that
// if the token is revoked, Auto Auth is re-triggered and a valid new token
// is written to a sink, and the template is correctly rendered with the new token
func TestAutoAuthSelfHealing_TokenFileAuth_SinkOutput(t *testing.T) {
// Unset the environment variable so that agent picks up the right test cluster address
t.Setenv(api.EnvVaultAddress, "")
cluster := minimal.NewTestSoloCluster(t, nil)
logger := corehelpers.NewTestLogger(t)
serverClient := cluster.Cores[0].Client
// Create token
secret, err := serverClient.Auth().Token().Create(&api.TokenCreateRequest{})
require.NoError(t, err)
require.NotNil(t, secret)
require.NotNil(t, secret.Auth)
require.NotEmpty(t, secret.Auth.ClientToken)
token := secret.Auth.ClientToken
// Write token to the auto-auth token file
pathVaultToken := makeTempFile(t, "token-file", token)
// Give us some leeway of 3 errors 1 from each of: auth handler, sink server template server.
errCh := make(chan error, 3)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
// Create auth handler
am, err := tokenfile.NewTokenFileAuthMethod(&auth.AuthConfig{
Logger: logger.Named("auth.method"),
Config: map[string]interface{}{
"token_file_path": pathVaultToken,
},
})
require.NoError(t, err)
// Create sink file
pathSinkFile := makeTempFile(t, "sink-file", "")
require.NoError(t, err)
ahConfig := &auth.AuthHandlerConfig{
Logger: logger.Named("auth.handler"),
Client: serverClient,
EnableExecTokenCh: true,
EnableTemplateTokenCh: true,
EnableReauthOnNewCredentials: true,
ExitOnError: false,
}
ah := auth.NewAuthHandler(ahConfig)
go func() {
errCh <- ah.Run(ctx, am)
}()
config := &sink.SinkConfig{
Logger: logger.Named("sink.file"),
Config: map[string]interface{}{
"path": pathSinkFile,
},
}
fs, err := file.NewFileSink(config)
require.NoError(t, err)
config.Sink = fs
ss := sink.NewSinkServer(&sink.SinkServerConfig{
Logger: logger.Named("sink.server"),
Client: serverClient,
})
go func() {
errCh <- ss.Run(ctx, ah.OutputCh, []*sink.SinkConfig{config}, ah.AuthInProgress)
}()
// Create template server
sc := &template.ServerConfig{
Logger: logger.Named("template.server"),
AgentConfig: &agentConfig.Config{
Vault: &agentConfig.Vault{
Address: serverClient.Address(),
TLSSkipVerify: true,
},
TemplateConfig: &agentConfig.TemplateConfig{
StaticSecretRenderInt: 1 * time.Second,
},
AutoAuth: &agentConfig.AutoAuth{
Sinks: []*agentConfig.Sink{
{
Type: "file",
Config: map[string]interface{}{
"path": pathSinkFile,
},
},
},
},
ExitAfterAuth: false,
},
LogLevel: hclog.Trace,
LogWriter: hclog.DefaultOutput,
ExitAfterAuth: false,
}
pathTemplateOutput := makeTempFile(t, "template-output", "")
require.NoError(t, err)
templateTest := &ctconfig.TemplateConfig{
Contents: pointerutil.StringPtr(`{{ with secret "auth/token/lookup-self" }}{{ .Data.id }}{{ end }}`),
Destination: pointerutil.StringPtr(pathTemplateOutput),
}
templatesToRender := []*ctconfig.TemplateConfig{templateTest}
server := template.NewServer(sc)
go func() {
errCh <- server.Run(ctx, ah.TemplateTokenCh, templatesToRender, ah.AuthInProgress, ah.InvalidToken)
}()
// Send token to template channel, and wait for the template to render
ah.TemplateTokenCh <- token
err = waitForFileContent(t, pathTemplateOutput, token)
// Revoke Token
err = serverClient.Auth().Token().RevokeOrphan(token)
require.NoError(t, err)
// Create new token
tokenSecret, err := serverClient.Auth().Token().Create(&api.TokenCreateRequest{})
require.NoError(t, err)
require.NotNil(t, tokenSecret)
require.NotNil(t, tokenSecret.Auth)
require.NotEmpty(t, tokenSecret.Auth.ClientToken)
newToken := tokenSecret.Auth.ClientToken
// Write token to file
err = os.WriteFile(pathVaultToken, []byte(newToken), 0o600)
require.NoError(t, err)
// Wait for auto-auth to complete and verify token has been written to the sink
// and the template has been re-rendered
err = waitForFileContent(t, pathSinkFile, newToken)
require.NoError(t, err)
err = waitForFileContent(t, pathTemplateOutput, newToken)
require.NoError(t, err)
// Calling cancel will stop the 'Run' funcs we started in Goroutines, we should
// then check that there were no errors in our channel.
cancel()
wrapUpTimeout := 5 * time.Second
for {
select {
case <-time.After(wrapUpTimeout):
t.Fatal("test timed out")
case err := <-errCh:
require.NoError(t, err)
case <-ctx.Done():
// We can finish the test ourselves
return
}
}
}
// Test_NoAutoAuthSelfHealing_BadPolicy tests that auto auth
// is not re-triggered if a token with incorrect policy access
// is used to render a template
func Test_NoAutoAuthSelfHealing_BadPolicy(t *testing.T) {
// Unset the environment variable so that agent picks up the right test cluster address
t.Setenv(api.EnvVaultAddress, "")
policyName := "kv-access"
cluster := minimal.NewTestSoloCluster(t, nil)
logger := corehelpers.NewTestLogger(t)
serverClient := cluster.Cores[0].Client
// Write a policy with correct access to the secrets
err := serverClient.Sys().PutPolicy(policyName, `
path "/kv/*" {
capabilities = ["create", "read", "update", "delete", "list"]
}
path "/secret/*" {
capabilities = ["create", "read", "update", "delete", "list"]
}`)
require.NoError(t, err)
// Create a token without enough policy access to the kv secrets
secret, err := serverClient.Auth().Token().Create(&api.TokenCreateRequest{
Policies: []string{"default"},
})
require.NoError(t, err)
require.NotNil(t, secret)
require.NotNil(t, secret.Auth)
require.NotEmpty(t, secret.Auth.ClientToken)
require.Len(t, secret.Auth.Policies, 1)
require.Contains(t, secret.Auth.Policies, "default")
token := secret.Auth.ClientToken
// Write token to vault-token file
pathVaultToken := makeTempFile(t, "vault-token", token)
// Give us some leeway of 3 errors 1 from each of: auth handler, sink server template server.
errCh := make(chan error, 3)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
// Create auth handler
am, err := tokenfile.NewTokenFileAuthMethod(&auth.AuthConfig{
Logger: logger.Named("auth.method"),
Config: map[string]interface{}{
"token_file_path": pathVaultToken,
},
})
require.NoError(t, err)
ahConfig := &auth.AuthHandlerConfig{
Logger: logger.Named("auth.handler"),
Client: serverClient,
EnableExecTokenCh: true,
EnableReauthOnNewCredentials: true,
ExitOnError: false,
}
ah := auth.NewAuthHandler(ahConfig)
go func() {
errCh <- ah.Run(ctx, am)
}()
// Create sink file
pathSinkFile := makeTempFile(t, "sink-file", "")
config := &sink.SinkConfig{
Logger: logger.Named("sink.file"),
Config: map[string]interface{}{
"path": pathSinkFile,
},
}
fs, err := file.NewFileSink(config)
require.NoError(t, err)
config.Sink = fs
ss := sink.NewSinkServer(&sink.SinkServerConfig{
Logger: logger.Named("sink.server"),
Client: serverClient,
})
go func() {
errCh <- ss.Run(ctx, ah.OutputCh, []*sink.SinkConfig{config}, ah.AuthInProgress)
}()
// Create template server
sc := template.ServerConfig{
Logger: logger.Named("template.server"),
AgentConfig: &agentConfig.Config{
Vault: &agentConfig.Vault{
Address: serverClient.Address(),
TLSSkipVerify: true,
},
TemplateConfig: &agentConfig.TemplateConfig{
StaticSecretRenderInt: 1 * time.Second,
},
// Need to create at least one sink output so that it does not exit after rendering
AutoAuth: &agentConfig.AutoAuth{
Sinks: []*agentConfig.Sink{
{
Type: "file",
Config: map[string]interface{}{
"path": pathSinkFile,
},
},
},
},
ExitAfterAuth: false,
},
LogLevel: hclog.Trace,
LogWriter: hclog.DefaultOutput,
ExitAfterAuth: false,
}
pathTemplateDestination := makeTempFile(t, "kv-data", "")
templateTest := &ctconfig.TemplateConfig{
Contents: pointerutil.StringPtr(`"{{ with secret "secret/data/otherapp" }}{{ .Data.data.username }}{{ end }}"`),
Destination: pointerutil.StringPtr(pathTemplateDestination),
}
templatesToRender := []*ctconfig.TemplateConfig{templateTest}
server := template.NewServer(&sc)
go func() {
errCh <- server.Run(ctx, ah.TemplateTokenCh, templatesToRender, ah.AuthInProgress, ah.InvalidToken)
}()
// Send token to the template channel
ah.TemplateTokenCh <- token
// Create new token with the correct policy access
tokenSecret, err := serverClient.Auth().Token().Create(&api.TokenCreateRequest{
Policies: []string{policyName},
})
require.NoError(t, err)
require.NotNil(t, tokenSecret)
require.NotNil(t, tokenSecret.Auth)
require.NotEmpty(t, tokenSecret.Auth.ClientToken)
require.Len(t, tokenSecret.Auth.Policies, 2)
require.Contains(t, tokenSecret.Auth.Policies, "default")
require.Contains(t, tokenSecret.Auth.Policies, policyName)
newToken := tokenSecret.Auth.ClientToken
// Write new token to token file (where Agent would re-auto-auth from if
// it were triggered)
err = os.WriteFile(pathVaultToken, []byte(newToken), 0o600)
require.NoError(t, err)
// Wait for any potential *incorrect* re-triggers of auto auth
time.Sleep(time.Second * 3)
// Auto auth should not have been re-triggered because of just a permission denied error
// Verify that the new token has NOT been written to the token sink
tokenInSink, err := os.ReadFile(pathSinkFile)
require.NoError(t, err)
require.Equal(t, token, string(tokenInSink))
// Validate that the template still hasn't been rendered.
templateContent, err := os.ReadFile(pathTemplateDestination)
require.NoError(t, err)
require.Equal(t, "", string(templateContent))
cancel()
wrapUpTimeout := 5 * time.Second
for {
select {
case <-time.After(wrapUpTimeout):
t.Fatal("test timed out")
case err := <-errCh:
require.NoError(t, err)
case <-ctx.Done():
// We can finish the test ourselves
return
}
}
}
// waitForFileContent waits for the file at filePath to exist and contain fileContent
// or it will return in an error. Waits for five seconds, with 100ms intervals.
// Returns nil if content became the same, or non-nil if it didn't.
func waitForFileContent(t *testing.T, filePath, expectedContent string) error {
t.Helper()
var err error
tick := time.Tick(100 * time.Millisecond)
timeout := time.After(5 * time.Second)
// We need to wait for the files to be updated...
for {
select {
case <-timeout:
return fmt.Errorf("timed out waiting for file content, last error: %w", err)
case <-tick:
}
content, err := os.ReadFile(filePath)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
continue
}
return err
}
stringContent := string(content)
if stringContent != expectedContent {
err = fmt.Errorf("content not yet the same, expectedContent=%s, content=%s", expectedContent, stringContent)
continue
}
return nil
}
}
// makeTempFile creates a temp file with the specified name, populates it with the
// supplied contents and closes it. The path to the file is returned, also the file
// will be automatically removed when the test which created it, finishes.
func makeTempFile(t *testing.T, name, contents string) string {
t.Helper()
f, err := os.Create(filepath.Join(t.TempDir(), name))
require.NoError(t, err)
path := f.Name()
_, err = f.WriteString(contents)
require.NoError(t, err)
err = f.Close()
require.NoError(t, err)
return path
} | go | github | https://github.com/hashicorp/vault | command/agent/agent_auto_auth_self_heal_test.go |
// Copyright 2019 The Go 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 runtime
import "unsafe"
func checkptrAlignment(p unsafe.Pointer, elem *_type, n uintptr) {
// nil pointer is always suitably aligned (#47430).
if p == nil {
return
}
// Check that (*[n]elem)(p) is appropriately aligned.
// Note that we allow unaligned pointers if the types they point to contain
// no pointers themselves. See issue 37298.
// TODO(mdempsky): What about fieldAlign?
if elem.Pointers() && uintptr(p)&(uintptr(elem.Align_)-1) != 0 {
throw("checkptr: misaligned pointer conversion")
}
// Check that (*[n]elem)(p) doesn't straddle multiple heap objects.
// TODO(mdempsky): Fix #46938 so we don't need to worry about overflow here.
if checkptrStraddles(p, n*elem.Size_) {
throw("checkptr: converted pointer straddles multiple allocations")
}
}
// checkptrStraddles reports whether the first size-bytes of memory
// addressed by ptr is known to straddle more than one Go allocation.
func checkptrStraddles(ptr unsafe.Pointer, size uintptr) bool {
if size <= 1 {
return false
}
// Check that add(ptr, size-1) won't overflow. This avoids the risk
// of producing an illegal pointer value (assuming ptr is legal).
if uintptr(ptr) >= -(size - 1) {
return true
}
end := add(ptr, size-1)
// TODO(mdempsky): Detect when [ptr, end] contains Go allocations,
// but neither ptr nor end point into one themselves.
return checkptrBase(ptr) != checkptrBase(end)
}
func checkptrArithmetic(p unsafe.Pointer, originals []unsafe.Pointer) {
if 0 < uintptr(p) && uintptr(p) < minLegalPointer {
throw("checkptr: pointer arithmetic computed bad pointer value")
}
// Check that if the computed pointer p points into a heap
// object, then one of the original pointers must have pointed
// into the same object.
base := checkptrBase(p)
if base == 0 {
return
}
for _, original := range originals {
if base == checkptrBase(original) {
return
}
}
throw("checkptr: pointer arithmetic result points to invalid allocation")
}
// checkptrBase returns the base address for the allocation containing
// the address p.
//
// Importantly, if p1 and p2 point into the same variable, then
// checkptrBase(p1) == checkptrBase(p2). However, the converse/inverse
// is not necessarily true as allocations can have trailing padding,
// and multiple variables may be packed into a single allocation.
//
// checkptrBase should be an internal detail,
// but widely used packages access it using linkname.
// Notable members of the hall of shame include:
// - github.com/bytedance/sonic
//
// Do not remove or change the type signature.
// See go.dev/issue/67401.
//
//go:linkname checkptrBase
func checkptrBase(p unsafe.Pointer) uintptr {
// stack
if gp := getg(); gp.stack.lo <= uintptr(p) && uintptr(p) < gp.stack.hi {
// TODO(mdempsky): Walk the stack to identify the
// specific stack frame or even stack object that p
// points into.
//
// In the mean time, use "1" as a pseudo-address to
// represent the stack. This is an invalid address on
// all platforms, so it's guaranteed to be distinct
// from any of the addresses we might return below.
return 1
}
// heap (must check after stack because of #35068)
if base, _, _ := findObject(uintptr(p), 0, 0); base != 0 {
return base
}
// data or bss
for _, datap := range activeModules() {
if datap.data <= uintptr(p) && uintptr(p) < datap.edata {
return datap.data
}
if datap.bss <= uintptr(p) && uintptr(p) < datap.ebss {
return datap.bss
}
}
return 0
} | go | github | https://github.com/golang/go | src/runtime/checkptr.go |
/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_CORE_TPU_TPU_INIT_MODE_H_
#define TENSORFLOW_CORE_TPU_TPU_INIT_MODE_H_
#include "absl/status/status.h"
#include "tensorflow/core/platform/status.h"
namespace tensorflow {
enum class TPUInitMode : int { kNone, kGlobal, kRegular };
// Sets the TPU initialization mode appropriately.
//
// Requires that mode is not kNone, and mode doesn't transition kGlobal
// <-> kRegular.
//
// IMPLEMENTATION DETAILS:
// Used internally to record the current mode and type of API used for TPU
// initialization in a global static variable.
absl::Status SetTPUInitMode(TPUInitMode mode);
// Returns the current TPUInitMode.
TPUInitMode GetTPUInitMode();
namespace test {
// Forces the tpu init mode to be changed.
void ForceSetTPUInitMode(TPUInitMode mode);
} // namespace test
} // namespace tensorflow
#endif // TENSORFLOW_CORE_TPU_TPU_INIT_MODE_H_ | c | github | https://github.com/tensorflow/tensorflow | tensorflow/core/tpu/tpu_init_mode.h |
/*
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 options
import (
"testing"
)
func TestGetServiceIPAndRanges(t *testing.T) {
tests := []struct {
body string
apiServerServiceIP string
primaryServiceIPRange string
secondaryServiceIPRange string
expectedError bool
}{
{"", "10.0.0.1", "10.0.0.0/24", "<nil>", false},
{"192.0.2.1/24", "192.0.2.1", "192.0.2.0/24", "<nil>", false},
{"192.0.2.1/24,192.168.128.0/17", "192.0.2.1", "192.0.2.0/24", "192.168.128.0/17", false},
// Dual stack IPv4/IPv6
{"192.0.2.1/24,2001:db2:1:3:4::1/112", "192.0.2.1", "192.0.2.0/24", "2001:db2:1:3:4::/112", false},
// Dual stack IPv6/IPv4
{"2001:db2:1:3:4::1/112,192.0.2.1/24", "2001:db2:1:3:4::1", "2001:db2:1:3:4::/112", "192.0.2.0/24", false},
{"192.0.2.1/30,192.168.128.0/17", "<nil>", "<nil>", "<nil>", true},
// Invalid ip range[0] IPv4 mask
{"192.0.2.1/33,192.168.128.0/17", "<nil>", "<nil>", "<nil>", true},
// Invalid ip range[1] IPv4 mask
{"192.0.2.1/24,192.168.128.0/33", "<nil>", "<nil>", "<nil>", true},
// Invalid ip range[0] IPv6 mask
{"2001:db2:1:3:4::1/129,192.0.2.1/24", "<nil>", "<nil>", "<nil>", true},
// Invalid ip range[1] IPv6 mask
{"192.0.2.1/24,2001:db2:1:3:4::1/129", "<nil>", "<nil>", "<nil>", true},
// Invalid ip range[0] missing IPv4 mask
{"192.0.2.1,192.168.128.0/17", "<nil>", "<nil>", "<nil>", true},
// Invalid ip range[1] missing IPv4 mask
{"192.0.2.1/24,192.168.128.1", "<nil>", "<nil>", "<nil>", true},
// Invalid ip range[0] missing IPv6 mask
{"2001:db2:1:3:4::1,192.0.2.1/24", "<nil>", "<nil>", "<nil>", true},
// Invalid ip range[1] missing IPv6 mask
{"192.0.2.1/24,2001:db2:1:3:4::1", "<nil>", "<nil>", "<nil>", true},
// Invalid ip range[0] IP address format
{"bad.ip.range,192.168.0.2/24", "<nil>", "<nil>", "<nil>", true},
// Invalid ip range[1] IP address format
{"192.168.0.2/24,bad.ip.range", "<nil>", "<nil>", "<nil>", true},
}
for _, test := range tests {
apiServerServiceIP, primaryServiceIPRange, secondaryServiceIPRange, err := getServiceIPAndRanges(test.body)
if apiServerServiceIP.String() != test.apiServerServiceIP {
t.Errorf("expected apiServerServiceIP: %s, got: %s", test.apiServerServiceIP, apiServerServiceIP.String())
}
if primaryServiceIPRange.String() != test.primaryServiceIPRange {
t.Errorf("expected primaryServiceIPRange: %s, got: %s", test.primaryServiceIPRange, primaryServiceIPRange.String())
}
if secondaryServiceIPRange.String() != test.secondaryServiceIPRange {
t.Errorf("expected secondaryServiceIPRange: %s, got: %s", test.secondaryServiceIPRange, secondaryServiceIPRange.String())
}
if (err == nil) == test.expectedError {
t.Errorf("expected err to be: %t, but it was %t", test.expectedError, !test.expectedError)
}
}
} | go | github | https://github.com/kubernetes/kubernetes | cmd/kube-apiserver/app/options/completion_test.go |
<!---
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
-->
# Apache Hadoop 0.13.0 Release Notes
These release notes cover new developer and user-facing incompatibilities, important issues, features, and major improvements.
---
* [HADOOP-1063](https://issues.apache.org/jira/browse/HADOOP-1063) | *Major* | **MiniDFSCluster exists a race condition that lead to data node resources are not properly released**
Resolved race condition in shutting down MiniDFSCluster data node that prevented resources from being deallocated properly. | unknown | github | https://github.com/apache/hadoop | hadoop-common-project/hadoop-common/src/site/markdown/release/0.13.0/RELEASENOTES.0.13.0.md |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.