text
stringlengths 2
100k
| meta
dict |
---|---|
X:1
T:Emigrant's -- Reel
R:reel
B:Ryan's Mammoth Collection
N: 287
O:SCOTCH
Z: Contributed by Ray Davies, ray:davies99.freeserve.co.uk
M:C|
L:1/8
K:F
vAccB dfcf | dfcf (eg)g2 | AccB dfcf | BGcB (AF)F2 |
AccB dfcf | dfcf (eg)g2 | AccB dfcf | BGcB (AF)F2:|
|:vafef dfcf | afef (eg)g2 | afef dfcf | BGcB (AF)F2 |
afef dfcf | afef (eg)g2 | ((3agf)((3gfe) ((3fed)((3edc) |\
((3Bcd) (cB) (AF)F2 :|
| {
"pile_set_name": "Github"
} |
// (C) Copyright Jeremy Siek 2001.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <boost/config.hpp>
#include <iostream>
#include <boost/graph/isomorphism.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_utility.hpp>
/*
Sample output:
isomorphic? 1
f: 9 10 11 0 1 3 2 4 6 8 7 5
*/
int main()
{
using namespace boost;
const int n = 12;
typedef adjacency_list< vecS, listS, undirectedS,
property< vertex_index_t, int > >
graph_t;
graph_t g1(n), g2(n);
std::vector< graph_traits< graph_t >::vertex_descriptor > v1(n), v2(n);
property_map< graph_t, vertex_index_t >::type v1_index_map
= get(vertex_index, g1),
v2_index_map = get(vertex_index, g2);
graph_traits< graph_t >::vertex_iterator i, end;
int id = 0;
for (boost::tie(i, end) = vertices(g1); i != end; ++i, ++id)
{
put(v1_index_map, *i, id);
v1[id] = *i;
}
id = 0;
for (boost::tie(i, end) = vertices(g2); i != end; ++i, ++id)
{
put(v2_index_map, *i, id);
v2[id] = *i;
}
add_edge(v1[0], v1[1], g1);
add_edge(v1[1], v1[2], g1);
add_edge(v1[0], v1[2], g1);
add_edge(v1[3], v1[4], g1);
add_edge(v1[4], v1[5], g1);
add_edge(v1[5], v1[6], g1);
add_edge(v1[6], v1[3], g1);
add_edge(v1[7], v1[8], g1);
add_edge(v1[8], v1[9], g1);
add_edge(v1[9], v1[10], g1);
add_edge(v1[10], v1[11], g1);
add_edge(v1[11], v1[7], g1);
add_edge(v2[9], v2[10], g2);
add_edge(v2[10], v2[11], g2);
add_edge(v2[11], v2[9], g2);
add_edge(v2[0], v2[1], g2);
add_edge(v2[1], v2[3], g2);
add_edge(v2[3], v2[2], g2);
add_edge(v2[2], v2[0], g2);
add_edge(v2[4], v2[5], g2);
add_edge(v2[5], v2[7], g2);
add_edge(v2[7], v2[8], g2);
add_edge(v2[8], v2[6], g2);
add_edge(v2[6], v2[4], g2);
std::vector< graph_traits< graph_t >::vertex_descriptor > f(n);
#if defined(BOOST_MSVC) && BOOST_MSVC <= 1300
bool ret = isomorphism(g1, g2,
make_iterator_property_map(f.begin(), v1_index_map, f[0]),
degree_vertex_invariant(), get(vertex_index, g1),
get(vertex_index, g2));
#else
bool ret = isomorphism(g1, g2,
isomorphism_map(
make_iterator_property_map(f.begin(), v1_index_map, f[0])));
#endif
std::cout << "isomorphic? " << ret << std::endl;
std::cout << "f: ";
for (std::size_t v = 0; v != f.size(); ++v)
std::cout << get(get(vertex_index, g2), f[v]) << " ";
std::cout << std::endl;
return 0;
}
| {
"pile_set_name": "Github"
} |
# coding: utf-8
# Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class ConsoleHistory(object):
"""
An instance's serial console data. It includes configuration messages that occur when the
instance boots, such as kernel and BIOS messages, and is useful for checking the status of
the instance or diagnosing problems. The console data is minimally formatted ASCII text.
**Warning:** Oracle recommends that you avoid using any confidential information when you
supply string values using the API.
"""
#: A constant which can be used with the lifecycle_state property of a ConsoleHistory.
#: This constant has a value of "REQUESTED"
LIFECYCLE_STATE_REQUESTED = "REQUESTED"
#: A constant which can be used with the lifecycle_state property of a ConsoleHistory.
#: This constant has a value of "GETTING-HISTORY"
LIFECYCLE_STATE_GETTING_HISTORY = "GETTING-HISTORY"
#: A constant which can be used with the lifecycle_state property of a ConsoleHistory.
#: This constant has a value of "SUCCEEDED"
LIFECYCLE_STATE_SUCCEEDED = "SUCCEEDED"
#: A constant which can be used with the lifecycle_state property of a ConsoleHistory.
#: This constant has a value of "FAILED"
LIFECYCLE_STATE_FAILED = "FAILED"
def __init__(self, **kwargs):
"""
Initializes a new ConsoleHistory object with values from keyword arguments.
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param availability_domain:
The value to assign to the availability_domain property of this ConsoleHistory.
:type availability_domain: str
:param compartment_id:
The value to assign to the compartment_id property of this ConsoleHistory.
:type compartment_id: str
:param defined_tags:
The value to assign to the defined_tags property of this ConsoleHistory.
:type defined_tags: dict(str, dict(str, object))
:param display_name:
The value to assign to the display_name property of this ConsoleHistory.
:type display_name: str
:param freeform_tags:
The value to assign to the freeform_tags property of this ConsoleHistory.
:type freeform_tags: dict(str, str)
:param id:
The value to assign to the id property of this ConsoleHistory.
:type id: str
:param instance_id:
The value to assign to the instance_id property of this ConsoleHistory.
:type instance_id: str
:param lifecycle_state:
The value to assign to the lifecycle_state property of this ConsoleHistory.
Allowed values for this property are: "REQUESTED", "GETTING-HISTORY", "SUCCEEDED", "FAILED", 'UNKNOWN_ENUM_VALUE'.
Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.
:type lifecycle_state: str
:param time_created:
The value to assign to the time_created property of this ConsoleHistory.
:type time_created: datetime
"""
self.swagger_types = {
'availability_domain': 'str',
'compartment_id': 'str',
'defined_tags': 'dict(str, dict(str, object))',
'display_name': 'str',
'freeform_tags': 'dict(str, str)',
'id': 'str',
'instance_id': 'str',
'lifecycle_state': 'str',
'time_created': 'datetime'
}
self.attribute_map = {
'availability_domain': 'availabilityDomain',
'compartment_id': 'compartmentId',
'defined_tags': 'definedTags',
'display_name': 'displayName',
'freeform_tags': 'freeformTags',
'id': 'id',
'instance_id': 'instanceId',
'lifecycle_state': 'lifecycleState',
'time_created': 'timeCreated'
}
self._availability_domain = None
self._compartment_id = None
self._defined_tags = None
self._display_name = None
self._freeform_tags = None
self._id = None
self._instance_id = None
self._lifecycle_state = None
self._time_created = None
@property
def availability_domain(self):
"""
**[Required]** Gets the availability_domain of this ConsoleHistory.
The availability domain of an instance.
Example: `Uocm:PHX-AD-1`
:return: The availability_domain of this ConsoleHistory.
:rtype: str
"""
return self._availability_domain
@availability_domain.setter
def availability_domain(self, availability_domain):
"""
Sets the availability_domain of this ConsoleHistory.
The availability domain of an instance.
Example: `Uocm:PHX-AD-1`
:param availability_domain: The availability_domain of this ConsoleHistory.
:type: str
"""
self._availability_domain = availability_domain
@property
def compartment_id(self):
"""
**[Required]** Gets the compartment_id of this ConsoleHistory.
The OCID of the compartment.
:return: The compartment_id of this ConsoleHistory.
:rtype: str
"""
return self._compartment_id
@compartment_id.setter
def compartment_id(self, compartment_id):
"""
Sets the compartment_id of this ConsoleHistory.
The OCID of the compartment.
:param compartment_id: The compartment_id of this ConsoleHistory.
:type: str
"""
self._compartment_id = compartment_id
@property
def defined_tags(self):
"""
Gets the defined_tags of this ConsoleHistory.
Defined tags for this resource. Each key is predefined and scoped to a
namespace. For more information, see `Resource Tags`__.
Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The defined_tags of this ConsoleHistory.
:rtype: dict(str, dict(str, object))
"""
return self._defined_tags
@defined_tags.setter
def defined_tags(self, defined_tags):
"""
Sets the defined_tags of this ConsoleHistory.
Defined tags for this resource. Each key is predefined and scoped to a
namespace. For more information, see `Resource Tags`__.
Example: `{\"Operations\": {\"CostCenter\": \"42\"}}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param defined_tags: The defined_tags of this ConsoleHistory.
:type: dict(str, dict(str, object))
"""
self._defined_tags = defined_tags
@property
def display_name(self):
"""
Gets the display_name of this ConsoleHistory.
A user-friendly name. Does not have to be unique, and it's changeable.
Avoid entering confidential information.
Example: `My console history metadata`
:return: The display_name of this ConsoleHistory.
:rtype: str
"""
return self._display_name
@display_name.setter
def display_name(self, display_name):
"""
Sets the display_name of this ConsoleHistory.
A user-friendly name. Does not have to be unique, and it's changeable.
Avoid entering confidential information.
Example: `My console history metadata`
:param display_name: The display_name of this ConsoleHistory.
:type: str
"""
self._display_name = display_name
@property
def freeform_tags(self):
"""
Gets the freeform_tags of this ConsoleHistory.
Free-form tags for this resource. Each tag is a simple key-value pair with no
predefined name, type, or namespace. For more information, see `Resource Tags`__.
Example: `{\"Department\": \"Finance\"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The freeform_tags of this ConsoleHistory.
:rtype: dict(str, str)
"""
return self._freeform_tags
@freeform_tags.setter
def freeform_tags(self, freeform_tags):
"""
Sets the freeform_tags of this ConsoleHistory.
Free-form tags for this resource. Each tag is a simple key-value pair with no
predefined name, type, or namespace. For more information, see `Resource Tags`__.
Example: `{\"Department\": \"Finance\"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param freeform_tags: The freeform_tags of this ConsoleHistory.
:type: dict(str, str)
"""
self._freeform_tags = freeform_tags
@property
def id(self):
"""
**[Required]** Gets the id of this ConsoleHistory.
The OCID of the console history metadata object.
:return: The id of this ConsoleHistory.
:rtype: str
"""
return self._id
@id.setter
def id(self, id):
"""
Sets the id of this ConsoleHistory.
The OCID of the console history metadata object.
:param id: The id of this ConsoleHistory.
:type: str
"""
self._id = id
@property
def instance_id(self):
"""
**[Required]** Gets the instance_id of this ConsoleHistory.
The OCID of the instance this console history was fetched from.
:return: The instance_id of this ConsoleHistory.
:rtype: str
"""
return self._instance_id
@instance_id.setter
def instance_id(self, instance_id):
"""
Sets the instance_id of this ConsoleHistory.
The OCID of the instance this console history was fetched from.
:param instance_id: The instance_id of this ConsoleHistory.
:type: str
"""
self._instance_id = instance_id
@property
def lifecycle_state(self):
"""
**[Required]** Gets the lifecycle_state of this ConsoleHistory.
The current state of the console history.
Allowed values for this property are: "REQUESTED", "GETTING-HISTORY", "SUCCEEDED", "FAILED", 'UNKNOWN_ENUM_VALUE'.
Any unrecognized values returned by a service will be mapped to 'UNKNOWN_ENUM_VALUE'.
:return: The lifecycle_state of this ConsoleHistory.
:rtype: str
"""
return self._lifecycle_state
@lifecycle_state.setter
def lifecycle_state(self, lifecycle_state):
"""
Sets the lifecycle_state of this ConsoleHistory.
The current state of the console history.
:param lifecycle_state: The lifecycle_state of this ConsoleHistory.
:type: str
"""
allowed_values = ["REQUESTED", "GETTING-HISTORY", "SUCCEEDED", "FAILED"]
if not value_allowed_none_or_none_sentinel(lifecycle_state, allowed_values):
lifecycle_state = 'UNKNOWN_ENUM_VALUE'
self._lifecycle_state = lifecycle_state
@property
def time_created(self):
"""
**[Required]** Gets the time_created of this ConsoleHistory.
The date and time the history was created, in the format defined by `RFC3339`__.
Example: `2016-08-25T21:10:29.600Z`
__ https://tools.ietf.org/html/rfc3339
:return: The time_created of this ConsoleHistory.
:rtype: datetime
"""
return self._time_created
@time_created.setter
def time_created(self, time_created):
"""
Sets the time_created of this ConsoleHistory.
The date and time the history was created, in the format defined by `RFC3339`__.
Example: `2016-08-25T21:10:29.600Z`
__ https://tools.ietf.org/html/rfc3339
:param time_created: The time_created of this ConsoleHistory.
:type: datetime
"""
self._time_created = time_created
def __repr__(self):
return formatted_flat_dict(self)
def __eq__(self, other):
if other is None:
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8" ?>
<plugin pluginId="Gallio.MSpecAdapter"
recommendedInstallationPath="MSpec"
xmlns="http://www.gallio.org/">
<traits>
<name>Machine Specifications Adapter Plugin</name>
<version>0.3.0.0</version>
<description>Provides support for running MSpec within gallio. Requires the assemblies from MSpec.</description>
</traits>
<dependencies>
<dependency pluginId="Gallio" />
</dependencies>
<files>
<file path="Machine.Specifications.dll" />
<file path="Machine.Specifications.GallioAdapter.plugin" />
<file path="Machine.Specifications.GallioAdapter.3.1.dll" />
<!--<file path="Readme.txt" />-->
</files>
<assemblies>
<assembly fullName="Machine.Specifications.GallioAdapter.3.1, Version=0.3.0.0, Culture=neutral, PublicKeyToken=null"
codeBase="Machine.Specifications.GallioAdapter.3.1.dll"
qualifyPartialName="true" />
<assembly fullName="Machine.Specifications, Version=0.3.0.0, Culture=neutral, PublicKeyToken=5c474de7a495cff1"
codeBase="Machine.Specifications.dll" />
</assemblies>
<components>
<component componentId="Machine.Specifications"
serviceId="Gallio.TestFramework"
componentType="Machine.Specifications.GallioAdapter.MachineSpecificationsFramework, Machine.Specifications.GallioAdapter.3.1">
<traits>
<name>Machine Specifications</name>
<frameworkAssemblies>Machine.Specifications, Version=0.3.0.0</frameworkAssemblies>
<version>0.3.0.0</version>
<fileTypes>Assembly</fileTypes>
</traits>
</component>
</components>
</plugin> | {
"pile_set_name": "Github"
} |
// Copyright 2014 The Prometheus 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 expfmt
import (
"fmt"
"io"
"math"
"strings"
dto "github.com/prometheus/client_model/go"
"github.com/prometheus/common/model"
)
// MetricFamilyToText converts a MetricFamily proto message into text format and
// writes the resulting lines to 'out'. It returns the number of bytes written
// and any error encountered. The output will have the same order as the input,
// no further sorting is performed. Furthermore, this function assumes the input
// is already sanitized and does not perform any sanity checks. If the input
// contains duplicate metrics or invalid metric or label names, the conversion
// will result in invalid text format output.
//
// This method fulfills the type 'prometheus.encoder'.
func MetricFamilyToText(out io.Writer, in *dto.MetricFamily) (int, error) {
var written int
// Fail-fast checks.
if len(in.Metric) == 0 {
return written, fmt.Errorf("MetricFamily has no metrics: %s", in)
}
name := in.GetName()
if name == "" {
return written, fmt.Errorf("MetricFamily has no name: %s", in)
}
// Comments, first HELP, then TYPE.
if in.Help != nil {
n, err := fmt.Fprintf(
out, "# HELP %s %s\n",
name, escapeString(*in.Help, false),
)
written += n
if err != nil {
return written, err
}
}
metricType := in.GetType()
n, err := fmt.Fprintf(
out, "# TYPE %s %s\n",
name, strings.ToLower(metricType.String()),
)
written += n
if err != nil {
return written, err
}
// Finally the samples, one line for each.
for _, metric := range in.Metric {
switch metricType {
case dto.MetricType_COUNTER:
if metric.Counter == nil {
return written, fmt.Errorf(
"expected counter in metric %s %s", name, metric,
)
}
n, err = writeSample(
name, metric, "", "",
metric.Counter.GetValue(),
out,
)
case dto.MetricType_GAUGE:
if metric.Gauge == nil {
return written, fmt.Errorf(
"expected gauge in metric %s %s", name, metric,
)
}
n, err = writeSample(
name, metric, "", "",
metric.Gauge.GetValue(),
out,
)
case dto.MetricType_UNTYPED:
if metric.Untyped == nil {
return written, fmt.Errorf(
"expected untyped in metric %s %s", name, metric,
)
}
n, err = writeSample(
name, metric, "", "",
metric.Untyped.GetValue(),
out,
)
case dto.MetricType_SUMMARY:
if metric.Summary == nil {
return written, fmt.Errorf(
"expected summary in metric %s %s", name, metric,
)
}
for _, q := range metric.Summary.Quantile {
n, err = writeSample(
name, metric,
model.QuantileLabel, fmt.Sprint(q.GetQuantile()),
q.GetValue(),
out,
)
written += n
if err != nil {
return written, err
}
}
n, err = writeSample(
name+"_sum", metric, "", "",
metric.Summary.GetSampleSum(),
out,
)
if err != nil {
return written, err
}
written += n
n, err = writeSample(
name+"_count", metric, "", "",
float64(metric.Summary.GetSampleCount()),
out,
)
case dto.MetricType_HISTOGRAM:
if metric.Histogram == nil {
return written, fmt.Errorf(
"expected histogram in metric %s %s", name, metric,
)
}
infSeen := false
for _, q := range metric.Histogram.Bucket {
n, err = writeSample(
name+"_bucket", metric,
model.BucketLabel, fmt.Sprint(q.GetUpperBound()),
float64(q.GetCumulativeCount()),
out,
)
written += n
if err != nil {
return written, err
}
if math.IsInf(q.GetUpperBound(), +1) {
infSeen = true
}
}
if !infSeen {
n, err = writeSample(
name+"_bucket", metric,
model.BucketLabel, "+Inf",
float64(metric.Histogram.GetSampleCount()),
out,
)
if err != nil {
return written, err
}
written += n
}
n, err = writeSample(
name+"_sum", metric, "", "",
metric.Histogram.GetSampleSum(),
out,
)
if err != nil {
return written, err
}
written += n
n, err = writeSample(
name+"_count", metric, "", "",
float64(metric.Histogram.GetSampleCount()),
out,
)
default:
return written, fmt.Errorf(
"unexpected type in metric %s %s", name, metric,
)
}
written += n
if err != nil {
return written, err
}
}
return written, nil
}
// writeSample writes a single sample in text format to out, given the metric
// name, the metric proto message itself, optionally an additional label name
// and value (use empty strings if not required), and the value. The function
// returns the number of bytes written and any error encountered.
func writeSample(
name string,
metric *dto.Metric,
additionalLabelName, additionalLabelValue string,
value float64,
out io.Writer,
) (int, error) {
var written int
n, err := fmt.Fprint(out, name)
written += n
if err != nil {
return written, err
}
n, err = labelPairsToText(
metric.Label,
additionalLabelName, additionalLabelValue,
out,
)
written += n
if err != nil {
return written, err
}
n, err = fmt.Fprintf(out, " %v", value)
written += n
if err != nil {
return written, err
}
if metric.TimestampMs != nil {
n, err = fmt.Fprintf(out, " %v", *metric.TimestampMs)
written += n
if err != nil {
return written, err
}
}
n, err = out.Write([]byte{'\n'})
written += n
if err != nil {
return written, err
}
return written, nil
}
// labelPairsToText converts a slice of LabelPair proto messages plus the
// explicitly given additional label pair into text formatted as required by the
// text format and writes it to 'out'. An empty slice in combination with an
// empty string 'additionalLabelName' results in nothing being
// written. Otherwise, the label pairs are written, escaped as required by the
// text format, and enclosed in '{...}'. The function returns the number of
// bytes written and any error encountered.
func labelPairsToText(
in []*dto.LabelPair,
additionalLabelName, additionalLabelValue string,
out io.Writer,
) (int, error) {
if len(in) == 0 && additionalLabelName == "" {
return 0, nil
}
var written int
separator := '{'
for _, lp := range in {
n, err := fmt.Fprintf(
out, `%c%s="%s"`,
separator, lp.GetName(), escapeString(lp.GetValue(), true),
)
written += n
if err != nil {
return written, err
}
separator = ','
}
if additionalLabelName != "" {
n, err := fmt.Fprintf(
out, `%c%s="%s"`,
separator, additionalLabelName,
escapeString(additionalLabelValue, true),
)
written += n
if err != nil {
return written, err
}
}
n, err := out.Write([]byte{'}'})
written += n
if err != nil {
return written, err
}
return written, nil
}
var (
escape = strings.NewReplacer("\\", `\\`, "\n", `\n`)
escapeWithDoubleQuote = strings.NewReplacer("\\", `\\`, "\n", `\n`, "\"", `\"`)
)
// escapeString replaces '\' by '\\', new line character by '\n', and - if
// includeDoubleQuote is true - '"' by '\"'.
func escapeString(v string, includeDoubleQuote bool) string {
if includeDoubleQuote {
return escapeWithDoubleQuote.Replace(v)
}
return escape.Replace(v)
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
* (c) Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Exception thrown when a syntax error occurs during lexing or parsing of a template.
*
* @author Fabien Potencier <[email protected]>
*/
class Twig_Error_Syntax extends Twig_Error
{
/**
* Tweaks the error message to include suggestions.
*
* @param string $name The original name of the item that does not exist
* @param array $items An array of possible items
*/
public function addSuggestions($name, array $items)
{
if (!$alternatives = self::computeAlternatives($name, $items)) {
return;
}
$this->appendMessage(sprintf(' Did you mean "%s"?', implode('", "', $alternatives)));
}
/**
* @internal
*
* To be merged with the addSuggestions() method in 2.0.
*/
public static function computeAlternatives($name, $items)
{
$alternatives = array();
foreach ($items as $item) {
$lev = levenshtein($name, $item);
if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
$alternatives[$item] = $lev;
}
}
asort($alternatives);
return array_keys($alternatives);
}
}
class_alias('Twig_Error_Syntax', 'Twig\Error\SyntaxError', false);
| {
"pile_set_name": "Github"
} |
#ifndef __DEBUG_H__
#define __DEBUG_H__
#include <stdint.h>
void dump_binary(const char *prompt, const uint8_t *data, size_t size);
#endif // __DEBUG_H__
| {
"pile_set_name": "Github"
} |
// Copyright (C) 2017. See 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 openssl
import (
"errors"
"net"
)
type listener struct {
net.Listener
ctx *Ctx
}
func (l *listener) Accept() (c net.Conn, err error) {
c, err = l.Listener.Accept()
if err != nil {
return nil, err
}
ssl_c, err := Server(c, l.ctx)
if err != nil {
c.Close()
return nil, err
}
return ssl_c, nil
}
// NewListener wraps an existing net.Listener such that all accepted
// connections are wrapped as OpenSSL server connections using the provided
// context ctx.
func NewListener(inner net.Listener, ctx *Ctx) net.Listener {
return &listener{
Listener: inner,
ctx: ctx}
}
// Listen is a wrapper around net.Listen that wraps incoming connections with
// an OpenSSL server connection using the provided context ctx.
func Listen(network, laddr string, ctx *Ctx) (net.Listener, error) {
if ctx == nil {
return nil, errors.New("no ssl context provided")
}
l, err := net.Listen(network, laddr)
if err != nil {
return nil, err
}
return NewListener(l, ctx), nil
}
type DialFlags int
const (
InsecureSkipHostVerification DialFlags = 1 << iota
DisableSNI
)
// Dial will connect to network/address and then wrap the corresponding
// underlying connection with an OpenSSL client connection using context ctx.
// If flags includes InsecureSkipHostVerification, the server certificate's
// hostname will not be checked to match the hostname in addr. Otherwise, flags
// should be 0.
//
// Dial probably won't work for you unless you set a verify location or add
// some certs to the certificate store of the client context you're using.
// This library is not nice enough to use the system certificate store by
// default for you yet.
func Dial(network, addr string, ctx *Ctx, flags DialFlags) (*Conn, error) {
return DialSession(network, addr, ctx, flags, nil)
}
// DialSession will connect to network/address and then wrap the corresponding
// underlying connection with an OpenSSL client connection using context ctx.
// If flags includes InsecureSkipHostVerification, the server certificate's
// hostname will not be checked to match the hostname in addr. Otherwise, flags
// should be 0.
//
// Dial probably won't work for you unless you set a verify location or add
// some certs to the certificate store of the client context you're using.
// This library is not nice enough to use the system certificate store by
// default for you yet.
//
// If session is not nil it will be used to resume the tls state. The session
// can be retrieved from the GetSession method on the Conn.
func DialSession(network, addr string, ctx *Ctx, flags DialFlags,
session []byte) (*Conn, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, err
}
if ctx == nil {
var err error
ctx, err = NewCtx()
if err != nil {
return nil, err
}
// TODO: use operating system default certificate chain?
}
c, err := net.Dial(network, addr)
if err != nil {
return nil, err
}
conn, err := Client(c, ctx)
if err != nil {
c.Close()
return nil, err
}
if session != nil {
err := conn.setSession(session)
if err != nil {
c.Close()
return nil, err
}
}
if flags&DisableSNI == 0 {
err = conn.SetTlsExtHostName(host)
if err != nil {
conn.Close()
return nil, err
}
}
err = conn.Handshake()
if err != nil {
conn.Close()
return nil, err
}
if flags&InsecureSkipHostVerification == 0 {
err = conn.VerifyHostname(host)
if err != nil {
conn.Close()
return nil, err
}
}
return conn, nil
}
| {
"pile_set_name": "Github"
} |
(module JST_PH_S9B-PH-SM4-TB_1x09-1MP_P2.00mm_Horizontal (layer F.Cu) (tedit 5B78AD87)
(descr "JST PH series connector, S9B-PH-SM4-TB (http://www.jst-mfg.com/product/pdf/eng/ePH.pdf), generated with kicad-footprint-generator")
(tags "connector JST PH top entry")
(attr smd)
(fp_text reference REF** (at 0 -5.8) (layer F.SilkS)
(effects (font (size 1 1) (thickness 0.15)))
)
(fp_text value JST_PH_S9B-PH-SM4-TB_1x09-1MP_P2.00mm_Horizontal (at 0 5.8) (layer F.Fab)
(effects (font (size 1 1) (thickness 0.15)))
)
(fp_line (start -10.95 -3.2) (end -10.15 -3.2) (layer F.Fab) (width 0.1))
(fp_line (start -10.15 -3.2) (end -10.15 -1.6) (layer F.Fab) (width 0.1))
(fp_line (start -10.15 -1.6) (end 10.15 -1.6) (layer F.Fab) (width 0.1))
(fp_line (start 10.15 -1.6) (end 10.15 -3.2) (layer F.Fab) (width 0.1))
(fp_line (start 10.15 -3.2) (end 10.95 -3.2) (layer F.Fab) (width 0.1))
(fp_line (start -11.06 0.94) (end -11.06 -3.31) (layer F.SilkS) (width 0.12))
(fp_line (start -11.06 -3.31) (end -10.04 -3.31) (layer F.SilkS) (width 0.12))
(fp_line (start -10.04 -3.31) (end -10.04 -1.71) (layer F.SilkS) (width 0.12))
(fp_line (start -10.04 -1.71) (end -8.76 -1.71) (layer F.SilkS) (width 0.12))
(fp_line (start -8.76 -1.71) (end -8.76 -4.6) (layer F.SilkS) (width 0.12))
(fp_line (start 11.06 0.94) (end 11.06 -3.31) (layer F.SilkS) (width 0.12))
(fp_line (start 11.06 -3.31) (end 10.04 -3.31) (layer F.SilkS) (width 0.12))
(fp_line (start 10.04 -3.31) (end 10.04 -1.71) (layer F.SilkS) (width 0.12))
(fp_line (start 10.04 -1.71) (end 8.76 -1.71) (layer F.SilkS) (width 0.12))
(fp_line (start -9.34 4.51) (end 9.34 4.51) (layer F.SilkS) (width 0.12))
(fp_line (start -10.95 4.4) (end 10.95 4.4) (layer F.Fab) (width 0.1))
(fp_line (start -10.95 -3.2) (end -10.95 4.4) (layer F.Fab) (width 0.1))
(fp_line (start 10.95 -3.2) (end 10.95 4.4) (layer F.Fab) (width 0.1))
(fp_line (start -11.6 -5.1) (end -11.6 5.1) (layer F.CrtYd) (width 0.05))
(fp_line (start -11.6 5.1) (end 11.6 5.1) (layer F.CrtYd) (width 0.05))
(fp_line (start 11.6 5.1) (end 11.6 -5.1) (layer F.CrtYd) (width 0.05))
(fp_line (start 11.6 -5.1) (end -11.6 -5.1) (layer F.CrtYd) (width 0.05))
(fp_line (start -8.5 -1.6) (end -8 -0.892893) (layer F.Fab) (width 0.1))
(fp_line (start -8 -0.892893) (end -7.5 -1.6) (layer F.Fab) (width 0.1))
(pad 1 smd roundrect (at -8 -2.85) (size 1 3.5) (layers F.Cu F.Mask F.Paste) (roundrect_rratio 0.25))
(pad 2 smd roundrect (at -6 -2.85) (size 1 3.5) (layers F.Cu F.Mask F.Paste) (roundrect_rratio 0.25))
(pad 3 smd roundrect (at -4 -2.85) (size 1 3.5) (layers F.Cu F.Mask F.Paste) (roundrect_rratio 0.25))
(pad 4 smd roundrect (at -2 -2.85) (size 1 3.5) (layers F.Cu F.Mask F.Paste) (roundrect_rratio 0.25))
(pad 5 smd roundrect (at 0 -2.85) (size 1 3.5) (layers F.Cu F.Mask F.Paste) (roundrect_rratio 0.25))
(pad 6 smd roundrect (at 2 -2.85) (size 1 3.5) (layers F.Cu F.Mask F.Paste) (roundrect_rratio 0.25))
(pad 7 smd roundrect (at 4 -2.85) (size 1 3.5) (layers F.Cu F.Mask F.Paste) (roundrect_rratio 0.25))
(pad 8 smd roundrect (at 6 -2.85) (size 1 3.5) (layers F.Cu F.Mask F.Paste) (roundrect_rratio 0.25))
(pad 9 smd roundrect (at 8 -2.85) (size 1 3.5) (layers F.Cu F.Mask F.Paste) (roundrect_rratio 0.25))
(pad MP smd roundrect (at -10.35 2.9) (size 1.5 3.4) (layers F.Cu F.Mask F.Paste) (roundrect_rratio 0.166667))
(pad MP smd roundrect (at 10.35 2.9) (size 1.5 3.4) (layers F.Cu F.Mask F.Paste) (roundrect_rratio 0.166667))
(fp_text user %R (at 0 1.5) (layer F.Fab)
(effects (font (size 1 1) (thickness 0.15)))
)
(model ${KISYS3DMOD}/Connector_JST.3dshapes/JST_PH_S9B-PH-SM4-TB_1x09-1MP_P2.00mm_Horizontal.wrl
(at (xyz 0 0 0))
(scale (xyz 1 1 1))
(rotate (xyz 0 0 0))
)
) | {
"pile_set_name": "Github"
} |
# Interface: ParserOptions
### Properties
* [sourceCodeLocationInfo](#sourcecodelocationinfo)
* [scriptingEnabled](#scriptingenabled)
* [treeAdapter](#treeadapter)
---
## Properties
<a id="sourcecodelocationinfo"></a>
### `<Optional>` sourceCodeLocationInfo
**● sourceCodeLocationInfo**: *`boolean`*
Enables source code location information. When enabled, each node (except the root node) will have a `sourceCodeLocation` property (property name can be different depending on [tree adapter](../tree-adapter/interface.md) that has been used, hereinafter property names for the [DefaultTreeAdapter](../tree-adapter/interface-list.md) will be given). If the node is not an empty element, `sourceCodeLocation` will be a [ElementLocation](../source-code-location/element-location.md) object, otherwise it will be [Location](../source-code-location/location.md). If the element was implicitly created by the parser (as part of [tree correction](https://html.spec.whatwg.org/multipage/syntax.html#an-introduction-to-error-handling-and-strange-cases-in-the-parser)), its `sourceCodeLocation` property will be `undefined`.
**Default:** `false`
___
<a id="scriptingenabled"></a>
### `<Optional>` scriptingEnabled
**● scriptingEnabled**: *`boolean`*
The [scripting flag](https://html.spec.whatwg.org/multipage/parsing.html#scripting-flag). If set to
`true`, `noscript` element content will be parsed as text.
**Default:** `true`
___
<a id="treeadapter"></a>
### `<Optional>` treeAdapter
**● treeAdapter**: *[TreeAdapter](../tree-adapter/interface.md)*
Specifies the resulting tree format.
**Default:** [DefaultTreeAdapter](../tree-adapter/default/interface-list.md)
___
| {
"pile_set_name": "Github"
} |
/* $NetBSD: base64.c,v 1.1 2011/10/23 21:15:02 agc Exp $ */
/*-
* Copyright (c) 2005,2006,2011 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Wasabi Systems, Inc.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 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.
*/
/*
* Adapted for kernel mode use with minimal changes from
* /usr/src/crypto/dist/heimdal/lib/roken/base64.c
*
* Original:
* Copyright (c) 1995-2001 Kungliga Tekniska Högskolan
* (Royal Institute of Technology, Stockholm, Sweden).
* 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 of the Institute 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 INSTITUTE 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 INSTITUTE 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.
*/
#include <string.h>
#include "base64.h"
static char base64_chars[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static int
pos(char c)
{
char *p;
for (p = base64_chars; *p; p++) {
if (*p == c) {
return (int)(p - base64_chars);
}
}
return -1;
}
int
base64_encode(const void *data, int size, uint8_t * buffer)
{
uint8_t *p;
int i;
int c;
const uint8_t *q;
p = buffer;
q = (const uint8_t *) data;
//*p++ = '0';
//*p++ = 'b';
i = 0;
for (i = 0; i < size;) {
c = q[i++];
c *= 256;
if (i < size) {
c += q[i];
}
i++;
c *= 256;
if (i < size) {
c += q[i];
}
i++;
p[0] = base64_chars[(c & 0x00fc0000) >> 18];
p[1] = base64_chars[(c & 0x0003f000) >> 12];
p[2] = base64_chars[(c & 0x00000fc0) >> 6];
p[3] = base64_chars[(c & 0x0000003f) >> 0];
if (i > size) {
p[3] = '=';
}
if (i > size + 1) {
p[2] = '=';
}
p += 4;
}
*p = 0;
return strlen(buffer);
}
#define DECODE_ERROR 0xffffffff
static uint32_t
token_decode(uint8_t * token, int tokenLen)
{
int i;
uint32_t val = 0;
int marker = 0;
if (tokenLen < 4) {
return DECODE_ERROR;
}
for (i = 0; i < 4; i++) {
val *= 64;
if (token[i] == '=') {
marker++;
} else if (marker > 0) {
return DECODE_ERROR;
} else {
val += pos(token[i]);
}
}
if (marker > 2) {
return DECODE_ERROR;
}
return (marker << 24) | val;
}
uint8_t *
base64_decode(const uint8_t * str, void *data, int *datalen)
{
uint8_t *p, *q;
uint32_t marker = 0;
char* strEnd = str + strlen(str);
q = data;
for (p = str; *p; p += 4) {
uint32_t val = token_decode(p, strEnd - p);
marker = (val >> 24) & 0xff;
if (val == DECODE_ERROR) {
return 0;
}
*q++ = (val >> 16) & 0xff;
if (marker < 2) {
*q++ = (val >> 8) & 0xff;
}
if (marker < 1) {
*q++ = val & 0xff;
}
}
*datalen = (int)(q - (uint8_t *) data);
return p - marker + 1;
}
| {
"pile_set_name": "Github"
} |
<!doctype html>
<html class="default no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>MethodBaseScalarsAnnotations | RAML JS Parser 2</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../assets/css/main.css">
<script src="../assets/js/modernizr.js"></script>
</head>
<body>
<header>
<div class="tsd-page-toolbar">
<div class="container">
<div class="table-wrap">
<div class="table-cell" id="tsd-search" data-index="../assets/js/search.js" data-base="..">
<div class="field">
<label for="tsd-search-field" class="tsd-widget search no-caption">Search</label>
<input id="tsd-search-field" type="text" />
</div>
<ul class="results">
<li class="state loading">Preparing search index...</li>
<li class="state failure">The search index is not available</li>
</ul>
<a href="../index.html" class="title">RAML JS Parser 2</a>
</div>
<div class="table-cell" id="tsd-widgets">
<div id="tsd-filter">
<a href="#" class="tsd-widget options no-caption" data-toggle="options">Options</a>
<div class="tsd-filter-group">
<div class="tsd-select" id="tsd-filter-visibility">
<span class="tsd-select-label">All</span>
<ul class="tsd-select-list">
<li data-value="public">Public</li>
<li data-value="protected">Public/Protected</li>
<li data-value="private" class="selected">All</li>
</ul>
</div>
<input type="checkbox" id="tsd-filter-inherited" checked />
<label class="tsd-widget" for="tsd-filter-inherited">Inherited</label>
<input type="checkbox" id="tsd-filter-externals" checked />
<label class="tsd-widget" for="tsd-filter-externals">Externals</label>
<input type="checkbox" id="tsd-filter-only-exported" />
<label class="tsd-widget" for="tsd-filter-only-exported">Only exported</label>
</div>
</div>
<a href="#" class="tsd-widget menu no-caption" data-toggle="menu">Menu</a>
</div>
</div>
</div>
</div>
<div class="tsd-page-title">
<div class="container">
<ul class="tsd-breadcrumb">
<li>
<a href="../globals.html">Globals</a>
</li>
<li>
<a href="../modules/_src_raml1_artifacts_raml10parserapi_.html">"src/raml1/artifacts/raml10parserapi"</a>
</li>
<li>
<a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html">MethodBaseScalarsAnnotations</a>
</li>
</ul>
<h1>Interface MethodBaseScalarsAnnotations</h1>
</div>
</div>
</header>
<div class="container container-main">
<div class="row">
<div class="col-8 col-content">
<section class="tsd-panel tsd-comment">
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>MethodBase scalar properties annotations accessor</p>
</div>
</div>
</section>
<section class="tsd-panel tsd-hierarchy">
<h3>Hierarchy</h3>
<ul class="tsd-hierarchy">
<li>
<a href="_src_raml1_artifacts_raml10parserapi_.annotablescalarsannotations.html" class="tsd-signature-type">AnnotableScalarsAnnotations</a>
<ul class="tsd-hierarchy">
<li>
<span class="target">MethodBaseScalarsAnnotations</span>
<ul class="tsd-hierarchy">
<li>
<a href="_src_raml1_artifacts_raml10parserapi_.methodscalarsannotations.html" class="tsd-signature-type">MethodScalarsAnnotations</a>
</li>
<li>
<a href="_src_raml1_artifacts_raml10parserapi_.traitscalarsannotations.html" class="tsd-signature-type">TraitScalarsAnnotations</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</section>
<section class="tsd-panel-group tsd-index-group">
<h2>Index</h2>
<section class="tsd-panel tsd-index-panel">
<div class="tsd-index-content">
<section class="tsd-index-section tsd-is-external">
<h3>Methods</h3>
<ul class="tsd-index-list">
<li class="tsd-kind-method tsd-parent-kind-interface tsd-is-inherited tsd-is-external"><a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#annotations" class="tsd-kind-icon">annotations</a></li>
<li class="tsd-kind-method tsd-parent-kind-interface tsd-is-external"><a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#description" class="tsd-kind-icon">description</a></li>
<li class="tsd-kind-method tsd-parent-kind-interface tsd-is-external"><a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#displayname" class="tsd-kind-icon">display<wbr>Name</a></li>
<li class="tsd-kind-method tsd-parent-kind-interface tsd-is-external"><a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#is" class="tsd-kind-icon">is</a></li>
<li class="tsd-kind-method tsd-parent-kind-interface tsd-is-external"><a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#protocols" class="tsd-kind-icon">protocols</a></li>
<li class="tsd-kind-method tsd-parent-kind-interface tsd-is-external"><a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#securedby" class="tsd-kind-icon">secured<wbr>By</a></li>
</ul>
</section>
</div>
</section>
</section>
<section class="tsd-panel-group tsd-member-group tsd-is-external">
<h2>Methods</h2>
<section class="tsd-panel tsd-member tsd-kind-method tsd-parent-kind-interface tsd-is-inherited tsd-is-external">
<a name="annotations" class="tsd-anchor"></a>
<h3>annotations</h3>
<ul class="tsd-signatures tsd-kind-method tsd-parent-kind-interface tsd-is-inherited tsd-is-external">
<li class="tsd-signature tsd-kind-icon">annotations<span class="tsd-signature-symbol">(</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<aside class="tsd-sources">
<p>Inherited from <a href="_src_raml1_artifacts_raml10parserapi_.annotablescalarsannotations.html">AnnotableScalarsAnnotations</a>.<a href="_src_raml1_artifacts_raml10parserapi_.annotablescalarsannotations.html#annotations">annotations</a></p>
<ul>
<li>Defined in <a href="https://github.com/raml-org/raml-js-parser-2/blob/develop/src/raml1/artifacts/raml10parserapi.ts#L478">src/raml1/artifacts/raml10parserapi.ts:478</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>Annotable.annotations annotations</p>
</div>
</div>
<h4 class="tsd-returns-title">Returns <a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></h4>
</li>
</ul>
</section>
<section class="tsd-panel tsd-member tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<a name="description" class="tsd-anchor"></a>
<h3>description</h3>
<ul class="tsd-signatures tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<li class="tsd-signature tsd-kind-icon">description<span class="tsd-signature-symbol">(</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/raml-org/raml-js-parser-2/blob/develop/src/raml1/artifacts/raml10parserapi.ts#L1527">src/raml1/artifacts/raml10parserapi.ts:1527</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>MethodBase.description annotations</p>
</div>
</div>
<h4 class="tsd-returns-title">Returns <a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></h4>
</li>
</ul>
</section>
<section class="tsd-panel tsd-member tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<a name="displayname" class="tsd-anchor"></a>
<h3>display<wbr>Name</h3>
<ul class="tsd-signatures tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<li class="tsd-signature tsd-kind-icon">display<wbr>Name<span class="tsd-signature-symbol">(</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/raml-org/raml-js-parser-2/blob/develop/src/raml1/artifacts/raml10parserapi.ts#L1533">src/raml1/artifacts/raml10parserapi.ts:1533</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>MethodBase.displayName annotations</p>
</div>
</div>
<h4 class="tsd-returns-title">Returns <a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></h4>
</li>
</ul>
</section>
<section class="tsd-panel tsd-member tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<a name="is" class="tsd-anchor"></a>
<h3>is</h3>
<ul class="tsd-signatures tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<li class="tsd-signature tsd-kind-icon">is<span class="tsd-signature-symbol">(</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/raml-org/raml-js-parser-2/blob/develop/src/raml1/artifacts/raml10parserapi.ts#L1515">src/raml1/artifacts/raml10parserapi.ts:1515</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>MethodBase.is annotations</p>
</div>
</div>
<h4 class="tsd-returns-title">Returns <a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></h4>
</li>
</ul>
</section>
<section class="tsd-panel tsd-member tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<a name="protocols" class="tsd-anchor"></a>
<h3>protocols</h3>
<ul class="tsd-signatures tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<li class="tsd-signature tsd-kind-icon">protocols<span class="tsd-signature-symbol">(</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/raml-org/raml-js-parser-2/blob/develop/src/raml1/artifacts/raml10parserapi.ts#L1509">src/raml1/artifacts/raml10parserapi.ts:1509</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>MethodBase.protocols annotations</p>
</div>
</div>
<h4 class="tsd-returns-title">Returns <a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></h4>
</li>
</ul>
</section>
<section class="tsd-panel tsd-member tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<a name="securedby" class="tsd-anchor"></a>
<h3>secured<wbr>By</h3>
<ul class="tsd-signatures tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<li class="tsd-signature tsd-kind-icon">secured<wbr>By<span class="tsd-signature-symbol">(</span><span class="tsd-signature-symbol">)</span><span class="tsd-signature-symbol">: </span><a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></li>
</ul>
<ul class="tsd-descriptions">
<li class="tsd-description">
<aside class="tsd-sources">
<ul>
<li>Defined in <a href="https://github.com/raml-org/raml-js-parser-2/blob/develop/src/raml1/artifacts/raml10parserapi.ts#L1521">src/raml1/artifacts/raml10parserapi.ts:1521</a></li>
</ul>
</aside>
<div class="tsd-comment tsd-typography">
<div class="lead">
<p>MethodBase.securedBy annotations</p>
</div>
</div>
<h4 class="tsd-returns-title">Returns <a href="_src_raml1_artifacts_raml10parserapi_.annotationref.html" class="tsd-signature-type">AnnotationRef</a><span class="tsd-signature-symbol">[]</span></h4>
</li>
</ul>
</section>
</section>
</div>
<div class="col-4 col-menu menu-sticky-wrap menu-highlight">
<nav class="tsd-navigation primary">
<ul>
<li class="globals ">
<a href="../globals.html"><em>Globals</em></a>
</li>
<li class="current tsd-kind-external-module tsd-is-external">
<a href="../modules/_src_raml1_artifacts_raml10parserapi_.html">"src/raml1/artifacts/raml10parserapi"</a>
</li>
</ul>
</nav>
<nav class="tsd-navigation secondary menu-sticky">
<ul class="before-current">
</ul>
<ul class="current">
<li class="current tsd-kind-interface tsd-parent-kind-external-module tsd-is-external">
<a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html" class="tsd-kind-icon">Method<wbr>Base<wbr>Scalars<wbr>Annotations</a>
<ul>
<li class=" tsd-kind-method tsd-parent-kind-interface tsd-is-inherited tsd-is-external">
<a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#annotations" class="tsd-kind-icon">annotations</a>
</li>
<li class=" tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#description" class="tsd-kind-icon">description</a>
</li>
<li class=" tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#displayname" class="tsd-kind-icon">display<wbr>Name</a>
</li>
<li class=" tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#is" class="tsd-kind-icon">is</a>
</li>
<li class=" tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#protocols" class="tsd-kind-icon">protocols</a>
</li>
<li class=" tsd-kind-method tsd-parent-kind-interface tsd-is-external">
<a href="_src_raml1_artifacts_raml10parserapi_.methodbasescalarsannotations.html#securedby" class="tsd-kind-icon">secured<wbr>By</a>
</li>
</ul>
</li>
</ul>
<ul class="after-current">
</ul>
</nav>
</div>
</div>
</div>
<footer class="with-border-bottom">
<div class="container">
<h2>Legend</h2>
<div class="tsd-legend-group">
<ul class="tsd-legend">
<li class="tsd-kind-module"><span class="tsd-kind-icon">Module</span></li>
<li class="tsd-kind-object-literal"><span class="tsd-kind-icon">Object literal</span></li>
<li class="tsd-kind-variable"><span class="tsd-kind-icon">Variable</span></li>
<li class="tsd-kind-function"><span class="tsd-kind-icon">Function</span></li>
<li class="tsd-kind-function tsd-has-type-parameter"><span class="tsd-kind-icon">Function with type parameter</span></li>
<li class="tsd-kind-index-signature"><span class="tsd-kind-icon">Index signature</span></li>
<li class="tsd-kind-type-alias"><span class="tsd-kind-icon">Type alias</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-enum"><span class="tsd-kind-icon">Enumeration</span></li>
<li class="tsd-kind-enum-member"><span class="tsd-kind-icon">Enumeration member</span></li>
<li class="tsd-kind-property tsd-parent-kind-enum"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-enum"><span class="tsd-kind-icon">Method</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-interface"><span class="tsd-kind-icon">Interface</span></li>
<li class="tsd-kind-interface tsd-has-type-parameter"><span class="tsd-kind-icon">Interface with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-interface"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-interface"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-interface"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-interface"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-class"><span class="tsd-kind-icon">Class</span></li>
<li class="tsd-kind-class tsd-has-type-parameter"><span class="tsd-kind-icon">Class with type parameter</span></li>
<li class="tsd-kind-constructor tsd-parent-kind-class"><span class="tsd-kind-icon">Constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class"><span class="tsd-kind-icon">Property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class"><span class="tsd-kind-icon">Method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class"><span class="tsd-kind-icon">Accessor</span></li>
<li class="tsd-kind-index-signature tsd-parent-kind-class"><span class="tsd-kind-icon">Index signature</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-constructor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited constructor</span></li>
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-inherited"><span class="tsd-kind-icon">Inherited accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-protected"><span class="tsd-kind-icon">Protected accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private property</span></li>
<li class="tsd-kind-method tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private method</span></li>
<li class="tsd-kind-accessor tsd-parent-kind-class tsd-is-private"><span class="tsd-kind-icon">Private accessor</span></li>
</ul>
<ul class="tsd-legend">
<li class="tsd-kind-property tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static property</span></li>
<li class="tsd-kind-call-signature tsd-parent-kind-class tsd-is-static"><span class="tsd-kind-icon">Static method</span></li>
</ul>
</div>
</div>
</footer>
<div class="container tsd-generator">
<p>Generated using <a href="http://typedoc.io" target="_blank">TypeDoc</a></p>
</div>
<div class="overlay"></div>
<script src="../assets/js/main.js"></script>
<script>if (location.protocol == 'file:') document.write('<script src="../assets/js/search.js"><' + '/script>');</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
/*
* Copyright 2017 Milian Wolff <[email protected]>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
inline void __attribute__((always_inline)) asdf()
{
new char[1234];
}
inline void __attribute__((always_inline)) bar()
{
asdf();
}
inline void __attribute__((always_inline)) foo()
{
bar();
}
int main()
{
foo();
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Registry for retrieving specific URI scheme validator objects.
*/
class HTMLPurifier_URISchemeRegistry
{
/**
* Retrieve sole instance of the registry.
* @param HTMLPurifier_URISchemeRegistry $prototype Optional prototype to overload sole instance with,
* or bool true to reset to default registry.
* @return HTMLPurifier_URISchemeRegistry
* @note Pass a registry object $prototype with a compatible interface and
* the function will copy it and return it all further times.
*/
public static function instance($prototype = null)
{
static $instance = null;
if ($prototype !== null) {
$instance = $prototype;
} elseif ($instance === null || $prototype == true) {
$instance = new HTMLPurifier_URISchemeRegistry();
}
return $instance;
}
/**
* Cache of retrieved schemes.
* @type HTMLPurifier_URIScheme[]
*/
protected $schemes = array();
/**
* Retrieves a scheme validator object
* @param string $scheme String scheme name like http or mailto
* @param HTMLPurifier_Config $config
* @param HTMLPurifier_Context $context
* @return HTMLPurifier_URIScheme
*/
public function getScheme($scheme, $config, $context)
{
if (!$config) {
$config = HTMLPurifier_Config::createDefault();
}
// important, otherwise attacker could include arbitrary file
$allowed_schemes = $config->get('URI.AllowedSchemes');
if (!$config->get('URI.OverrideAllowedSchemes') &&
!isset($allowed_schemes[$scheme])
) {
return;
}
if (isset($this->schemes[$scheme])) {
return $this->schemes[$scheme];
}
if (!isset($allowed_schemes[$scheme])) {
return;
}
$class = 'HTMLPurifier_URIScheme_' . $scheme;
if (!class_exists($class)) {
return;
}
$this->schemes[$scheme] = new $class();
return $this->schemes[$scheme];
}
/**
* Registers a custom scheme to the cache, bypassing reflection.
* @param string $scheme Scheme name
* @param HTMLPurifier_URIScheme $scheme_obj
*/
public function register($scheme, $scheme_obj)
{
$this->schemes[$scheme] = $scheme_obj;
}
}
// vim: et sw=4 sts=4
| {
"pile_set_name": "Github"
} |
#include <glib.h>
#include <gtk/gtk.h>
#include <granite.h>
void granite_widgets_show_about_dialog (GtkWindow *parent,
const gchar *first_property_name,
...); | {
"pile_set_name": "Github"
} |
#include"petsc.h"
PetscErrorCode FormDAEFunction(TS ts, PetscReal t, Vec x, Vec xdot, Vec f, void *ctx){
Solver_ctx *sol_ctx = (Solver_ctx*)ctx;
ASL *asl=(ASL*)(sol_ctx->asl);
PetscErrorCode ierr;
const PetscScalar *xx, *xxdot; /* Variable vector*/
PetscScalar *ff;
int err=0;
int i;
real x_asl[n_var];
/* Take values from petsc vectors and put into ASL vector */
if(sol_ctx->dae_map_t > 0) x_asl[sol_ctx->dae_map_t] = t;
ierr = VecGetArrayRead(x, &xx); CHKERRQ(ierr);
ierr = VecGetArrayRead(xdot, &xxdot); CHKERRQ(ierr);
for(i=0;i<sol_ctx->n_var_state;++i){
x_asl[sol_ctx->dae_map_x[i]] = xx[i];
if(sol_ctx->dae_map_xdot[i] >= 0) x_asl[sol_ctx->dae_map_xdot[i]] = xxdot[i];
}
ierr = VecRestoreArrayRead(x,&xx);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(xdot,&xxdot);CHKERRQ(ierr);
/* Compute */
ierr = VecGetArray(f,&ff);CHKERRQ(ierr);
conval(x_asl, (real*)ff, &err);
for(i=0;i<sol_ctx->n_var_state;++i) ff[i] -= LUrhs[i];
ierr = VecRestoreArray(f,&ff);CHKERRQ(ierr);
return 0;
}
PetscErrorCode FormDAEJacobian(
TS ts, PetscReal t, Vec x, Vec xdot, PetscReal sig, Mat jac, Mat B,void *ctx){
Solver_ctx *sol_ctx = (Solver_ctx*)ctx;
ASL *asl=(ASL*)(sol_ctx->asl);
const PetscScalar *xx, *xxdot; /* Variable vector*/
PetscScalar A[nzc]; /* Temporary storage for Jacobian Calc. */
PetscErrorCode ierr; /* PETSc Error code */
int err; /* ASL Error code */
unsigned long int i, j; /* Constraint index, var */
cgrad *cg; /* Constraint gradient information */
real x_asl[n_var];
/* Compute Jacobian entries */
/* Take values from petsc vectors and put into ASL vector */
if(sol_ctx->dae_map_t > 0) x_asl[sol_ctx->dae_map_t] = t;
ierr = VecGetArrayRead(x, &xx); CHKERRQ(ierr);
ierr = VecGetArrayRead(xdot, &xxdot); CHKERRQ(ierr);
for(i=0;i<sol_ctx->n_var_state;++i){
x_asl[sol_ctx->dae_map_x[i]] = xx[i];
if(sol_ctx->dae_map_xdot[i] >= 0) x_asl[sol_ctx->dae_map_xdot[i]] = xxdot[i];
}
ierr = VecRestoreArrayRead(x,&xx);CHKERRQ(ierr);
ierr = VecRestoreArrayRead(xdot,&xxdot);CHKERRQ(ierr);
jacval((real*)x_asl, (real*)A, &err);
/* The ASL isn't setup for DAEs, but not too hard to make the right Jacobian
From asl we have a Jacobian where t, x, and xdot are all treated the same,
PETSc want J = sigma*F_xdot(t, x, xdot) + F_x(t, x, xdot), so we need to
eliminate the t column and combine the x and xdot columns appropriatly */
ierr = MatZeroEntries(B); CHKERRQ(ierr); //since I'm going to add things
for(i=n_conjac[0];i<n_conjac[1]; ++i){ /*i is constraint index */
cg = Cgrad[i];
while(cg!=NULL){
j = cg->varno;
if(sol_ctx->dae_suffix_var->u.i[j]==2){
MatSetValue(B, i, sol_ctx->dae_map_back[j], sig*A[cg->goff], ADD_VALUES);}
else if(sol_ctx->dae_suffix_var->u.i[j]==3); //drop t
else MatSetValue(B, i, sol_ctx->dae_map_back[j], A[cg->goff], ADD_VALUES);
cg=cg->next;
}
}
/* Assemble matrix */
ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
ierr = MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
return 0;
}
void dae_var_map(Solver_ctx *sol_ctx){
int i=0, j=0, cx;
ASL *asl=(ASL*)(sol_ctx->asl); //need this for ASL macros
/* create a mapping PETSc <-> asl */
sol_ctx->dae_link = (int*)malloc(n_var*sizeof(int));
for(i=0;i<n_var;++i) sol_ctx->dae_link[i] = -1;
for(i=0;i<n_var;++i){
if(sol_ctx->dae_suffix_var->u.i[i]==2){ //a derivative var
for(j=0;j<n_var;++j){
if(i == j) continue;
if(sol_ctx->dae_link_var->u.i[i] == sol_ctx->dae_link_var->u.i[j]){
sol_ctx->dae_link[i] = j;
sol_ctx->dae_link[j] = i;
}
} //end for j
} //end if suffix == 2
} //end for i
sol_ctx->dae_map_x = (int*)malloc(sol_ctx->n_var_state*sizeof(int));
sol_ctx->dae_map_xdot = (int*)malloc(sol_ctx->n_var_state*sizeof(int));
sol_ctx->dae_map_back = (int*)malloc(n_var*sizeof(int));
for(i=0;i<sol_ctx->n_var_state;++i) sol_ctx->dae_map_xdot[i] = -1;
cx = 0;
for(i=0;i<n_var;++i){
if (sol_ctx->dae_suffix_var->u.i[i]==3){ //time variable (0 or 1 of these)
sol_ctx->dae_map_t = i;
}
else if (sol_ctx->dae_suffix_var->u.i[i]==2);
else{ //agebraic and differential variables
sol_ctx->dae_map_x[cx] = i;
sol_ctx->dae_map_back[i] = cx;
++cx;
}
} //end for i
for(i=0;i<n_var;++i){
// there is a derivative in xdot for all state vars, but in a dae some are
// just going to be zero in the function and jacobian calcualtions.
if (sol_ctx->dae_suffix_var->u.i[i] == 1){
j = sol_ctx->dae_link[i]; // index of associated derivative
sol_ctx->dae_map_xdot[sol_ctx->dae_map_back[i]] = j;
sol_ctx->dae_map_back[j] = sol_ctx->dae_map_back[i];
}//end if suffix == 1
}// end for i
}
void get_dae_info(Solver_ctx *sol_ctx){
int i=0;
ASL *asl=(ASL*)(sol_ctx->asl); //need this for ASL macros
sol_ctx->dae_suffix_var = suf_get("dae_suffix", ASL_Sufkind_var);
sol_ctx->dae_link_var = suf_get("dae_link", ASL_Sufkind_var);
for(i=0; i<n_var; ++i){
if(sol_ctx->dae_suffix_var->u.i[i]==1) ++sol_ctx->n_var_diff;
else if(sol_ctx->dae_suffix_var->u.i[i]==2) ++sol_ctx->n_var_deriv;
else if(sol_ctx->dae_suffix_var->u.i[i]==3) ++sol_ctx->explicit_time;
}
sol_ctx->n_var_state = n_var - sol_ctx->n_var_deriv - sol_ctx->explicit_time;
sol_ctx->n_var_alg = sol_ctx->n_var_state - sol_ctx->n_var_diff;
}
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="refresh" content="0;URL=../../../../libc/fn.islower.html">
</head>
<body>
<p>Redirecting to <a href="../../../../libc/fn.islower.html">../../../../libc/fn.islower.html</a>...</p>
<script>location.replace("../../../../libc/fn.islower.html" + location.search + location.hash);</script>
</body>
</html> | {
"pile_set_name": "Github"
} |
{
"jsonSchemaSemanticVersion": "1.0.0",
"imports": [
{
"corpusPath": "cdm:/foundations.1.2.cdm.json"
},
{
"corpusPath": "/core/operationsCommon/Common.1.0.cdm.json",
"moniker": "base_Common"
},
{
"corpusPath": "/core/operationsCommon/DataEntityView.1.0.cdm.json",
"moniker": "base_DataEntityView"
},
{
"corpusPath": "ResRatingModel.1.0.cdm.json"
}
],
"definitions": [
{
"entityName": "ResRatingLevel",
"extendsEntity": "base_Common/Common",
"exhibitsTraits": [
{
"traitReference": "is.CDM.entityVersion",
"arguments": [
{
"name": "versionNumber",
"value": "1.1"
}
]
}
],
"hasAttributes": [
{
"name": "Name",
"dataType": "Name",
"description": ""
},
{
"name": "Description",
"dataType": "Description",
"isNullable": true,
"description": ""
},
{
"name": "RatingModel",
"dataType": "ResRatingModelRecId",
"description": ""
},
{
"entity": {
"entityReference": "ResRatingModel"
},
"name": "Relationship_RatingModelRelationship",
"resolutionGuidance": {
"entityByReference": {
"allowReference": true
}
}
}
],
"displayName": ""
},
{
"dataTypeName": "Name",
"extendsDataType": "string"
},
{
"dataTypeName": "Description",
"extendsDataType": "string"
},
{
"dataTypeName": "ResRatingModelRecId",
"extendsDataType": "bigInteger"
}
]
} | {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:Receiver.xcodeproj">
</FileRef>
</Workspace>
| {
"pile_set_name": "Github"
} |
#if canImport(UIKit)
import UIKit
/// Used to set image onto ImageView
public class ImageViewDisplayer: ImageDisplayer {
private let animationOption: UIView.AnimationOptions
public init(animationOption: UIView.AnimationOptions = .transitionCrossDissolve) {
self.animationOption = animationOption
}
public func display(placeholder: Image, onto view: View) {
guard let imageView = view as? ImageView else {
return
}
imageView.image = placeholder
}
public func display(image: Image, onto view: View) {
guard let imageView = view as? ImageView else {
return
}
UIView.transition(with: imageView, duration: 0.25,
options: [self.animationOption, .allowUserInteraction],
animations: {
imageView.image = image
}, completion: nil)
}
}
#endif
| {
"pile_set_name": "Github"
} |
#"Copyright (c) 2019-present Lenovo
#Licensed under BSD-3, see COPYING.BSD file for details."
# hr630x has 14 fan ports
LABEL_fan1 = "fan1"
LABEL_fan2 = "fan2"
LABEL_fan3 = "fan3"
LABEL_fan4 = "fan4"
LABEL_fan5 = "fan5"
LABEL_fan6 = "fan6"
LABEL_fan7 = "fan7"
LABEL_fan8 = "fan8"
LABEL_fan9 = "fan9"
LABEL_fan10 = "fan10"
LABEL_fan11 = "fan11"
LABEL_fan12 = "fan12"
LABEL_fan13 = "fan13"
LABEL_fan14 = "fan14"
PWM_TARGET_fan1 = "1"
PWM_TARGET_fan2 = "1"
PWM_TARGET_fan3 = "2"
PWM_TARGET_fan4 = "2"
PWM_TARGET_fan5 = "3"
PWM_TARGET_fan6 = "3"
PWM_TARGET_fan7 = "4"
PWM_TARGET_fan8 = "4"
PWM_TARGET_fan9 = "5"
PWM_TARGET_fan10 = "5"
PWM_TARGET_fan11 = "6"
PWM_TARGET_fan12 = "6"
PWM_TARGET_fan13 = "7"
PWM_TARGET_fan14 = "7"
| {
"pile_set_name": "Github"
} |
polygon
1
1.543199E+01 4.972074E+01
1.543198E+01 4.972086E+01
1.543202E+01 4.972105E+01
1.543203E+01 4.972116E+01
1.543197E+01 4.972120E+01
1.543195E+01 4.972129E+01
1.543203E+01 4.972133E+01
1.543202E+01 4.972139E+01
1.543195E+01 4.972144E+01
1.543190E+01 4.972144E+01
1.543167E+01 4.972162E+01
1.543158E+01 4.972166E+01
1.543159E+01 4.972172E+01
1.543149E+01 4.972181E+01
1.543119E+01 4.972215E+01
1.543076E+01 4.972262E+01
1.543089E+01 4.972272E+01
1.543094E+01 4.972279E+01
1.543098E+01 4.972297E+01
1.543091E+01 4.972301E+01
1.543093E+01 4.972315E+01
1.543098E+01 4.972324E+01
1.543097E+01 4.972334E+01
1.543104E+01 4.972346E+01
1.543109E+01 4.972360E+01
1.543111E+01 4.972372E+01
1.543107E+01 4.972378E+01
1.543110E+01 4.972390E+01
1.543130E+01 4.972403E+01
1.543130E+01 4.972411E+01
1.543133E+01 4.972417E+01
1.543155E+01 4.972424E+01
1.543157E+01 4.972429E+01
1.543153E+01 4.972431E+01
1.543171E+01 4.972445E+01
1.543179E+01 4.972444E+01
1.543187E+01 4.972447E+01
1.543188E+01 4.972451E+01
1.543182E+01 4.972466E+01
1.543189E+01 4.972472E+01
1.543196E+01 4.972479E+01
1.543196E+01 4.972490E+01
1.543200E+01 4.972494E+01
1.543207E+01 4.972498E+01
1.543209E+01 4.972503E+01
1.543221E+01 4.972520E+01
1.543228E+01 4.972525E+01
1.543230E+01 4.972531E+01
1.543256E+01 4.972545E+01
1.543264E+01 4.972550E+01
1.543303E+01 4.972560E+01
1.543329E+01 4.972565E+01
1.543356E+01 4.972567E+01
1.543357E+01 4.972580E+01
1.543360E+01 4.972591E+01
1.543364E+01 4.972605E+01
1.543365E+01 4.972619E+01
1.543325E+01 4.972642E+01
1.543275E+01 4.972675E+01
1.543246E+01 4.972693E+01
1.543226E+01 4.972706E+01
1.543214E+01 4.972714E+01
1.543212E+01 4.972721E+01
1.543217E+01 4.972731E+01
1.543227E+01 4.972745E+01
1.543283E+01 4.972754E+01
1.543287E+01 4.972754E+01
1.543316E+01 4.972784E+01
1.543330E+01 4.972794E+01
1.543356E+01 4.972814E+01
1.543373E+01 4.972827E+01
1.543398E+01 4.972852E+01
1.543404E+01 4.972855E+01
1.543408E+01 4.972858E+01
1.543401E+01 4.972876E+01
1.543480E+01 4.972967E+01
1.543482E+01 4.972970E+01
1.543483E+01 4.972972E+01
1.543493E+01 4.972989E+01
1.543496E+01 4.972996E+01
1.543528E+01 4.973034E+01
1.543600E+01 4.973013E+01
1.543651E+01 4.972991E+01
1.543689E+01 4.972979E+01
1.543727E+01 4.972968E+01
1.543744E+01 4.972963E+01
1.543770E+01 4.972948E+01
1.543816E+01 4.972934E+01
1.543838E+01 4.972931E+01
1.543862E+01 4.972931E+01
1.543889E+01 4.972928E+01
1.543913E+01 4.972928E+01
1.543924E+01 4.972949E+01
1.543922E+01 4.972972E+01
1.543936E+01 4.972994E+01
1.543967E+01 4.973000E+01
1.543994E+01 4.973001E+01
1.544009E+01 4.973004E+01
1.544049E+01 4.973002E+01
1.544079E+01 4.973007E+01
1.544103E+01 4.973014E+01
1.544122E+01 4.973016E+01
1.544177E+01 4.973023E+01
1.544232E+01 4.973027E+01
1.544259E+01 4.973027E+01
1.544289E+01 4.973033E+01
1.544334E+01 4.973033E+01
1.544369E+01 4.973029E+01
1.544396E+01 4.973037E+01
1.544408E+01 4.973038E+01
1.544440E+01 4.973046E+01
1.544392E+01 4.973104E+01
1.544353E+01 4.973157E+01
1.544299E+01 4.973228E+01
1.544277E+01 4.973245E+01
1.544273E+01 4.973293E+01
1.544275E+01 4.973318E+01
1.544281E+01 4.973330E+01
1.544300E+01 4.973353E+01
1.544324E+01 4.973372E+01
1.544336E+01 4.973377E+01
1.544348E+01 4.973387E+01
1.544358E+01 4.973396E+01
1.544381E+01 4.973405E+01
1.544399E+01 4.973421E+01
1.544410E+01 4.973429E+01
1.544382E+01 4.973437E+01
1.544365E+01 4.973455E+01
1.544360E+01 4.973467E+01
1.544362E+01 4.973479E+01
1.544358E+01 4.973492E+01
1.544337E+01 4.973514E+01
1.544322E+01 4.973526E+01
1.544315E+01 4.973541E+01
1.544311E+01 4.973554E+01
1.544311E+01 4.973573E+01
1.544316E+01 4.973593E+01
1.544329E+01 4.973605E+01
1.544339E+01 4.973610E+01
1.544360E+01 4.973615E+01
1.544281E+01 4.973656E+01
1.544218E+01 4.973688E+01
1.544158E+01 4.973714E+01
1.544136E+01 4.973727E+01
1.544110E+01 4.973750E+01
1.544050E+01 4.973796E+01
1.543996E+01 4.973829E+01
1.543982E+01 4.973828E+01
1.543850E+01 4.973953E+01
1.543838E+01 4.973960E+01
1.543818E+01 4.973971E+01
1.543813E+01 4.974011E+01
1.543813E+01 4.974077E+01
1.543822E+01 4.974090E+01
1.543837E+01 4.974104E+01
1.543859E+01 4.974117E+01
1.543867E+01 4.974144E+01
1.543865E+01 4.974188E+01
1.543867E+01 4.974211E+01
1.543892E+01 4.974251E+01
1.543928E+01 4.974278E+01
1.543959E+01 4.974287E+01
1.544014E+01 4.974305E+01
1.543994E+01 4.974327E+01
1.544101E+01 4.974373E+01
1.544145E+01 4.974401E+01
1.544152E+01 4.974406E+01
1.544162E+01 4.974417E+01
1.544193E+01 4.974457E+01
1.544193E+01 4.974474E+01
1.544191E+01 4.974493E+01
1.544199E+01 4.974520E+01
1.544203E+01 4.974526E+01
1.544156E+01 4.974583E+01
1.544126E+01 4.974617E+01
1.544122E+01 4.974623E+01
1.544135E+01 4.974668E+01
1.544169E+01 4.974727E+01
1.544184E+01 4.974778E+01
1.544206E+01 4.974797E+01
1.544226E+01 4.974813E+01
1.544225E+01 4.974816E+01
1.544223E+01 4.974827E+01
1.544247E+01 4.974877E+01
1.544281E+01 4.974914E+01
1.544284E+01 4.974918E+01
1.544287E+01 4.974932E+01
1.544289E+01 4.974938E+01
1.544270E+01 4.974945E+01
1.544203E+01 4.974961E+01
1.544227E+01 4.974995E+01
1.544232E+01 4.974993E+01
1.544272E+01 4.974983E+01
1.544291E+01 4.974978E+01
1.544325E+01 4.974971E+01
1.544347E+01 4.974894E+01
1.544346E+01 4.974860E+01
1.544403E+01 4.974855E+01
1.544408E+01 4.974885E+01
1.544448E+01 4.974893E+01
1.544487E+01 4.974903E+01
1.544522E+01 4.974906E+01
1.544577E+01 4.974880E+01
1.544598E+01 4.974868E+01
1.544704E+01 4.974875E+01
1.544692E+01 4.974910E+01
1.544725E+01 4.974908E+01
1.544734E+01 4.974909E+01
1.544734E+01 4.974936E+01
1.544733E+01 4.974941E+01
1.544728E+01 4.974940E+01
1.544731E+01 4.974945E+01
1.544723E+01 4.974965E+01
1.544709E+01 4.974980E+01
1.544671E+01 4.975009E+01
1.544667E+01 4.975012E+01
1.544657E+01 4.975049E+01
1.544649E+01 4.975065E+01
1.544626E+01 4.975093E+01
1.544590E+01 4.975158E+01
1.544568E+01 4.975185E+01
1.544579E+01 4.975280E+01
1.544580E+01 4.975299E+01
1.544614E+01 4.975418E+01
1.544621E+01 4.975429E+01
1.544676E+01 4.975417E+01
1.544715E+01 4.975861E+01
1.545269E+01 4.975841E+01
1.545292E+01 4.975846E+01
1.545370E+01 4.975890E+01
1.545385E+01 4.975907E+01
1.545411E+01 4.976177E+01
1.545339E+01 4.976482E+01
1.545544E+01 4.976627E+01
1.545609E+01 4.976663E+01
1.545668E+01 4.976713E+01
1.545704E+01 4.976744E+01
1.545734E+01 4.976770E+01
1.545772E+01 4.976803E+01
1.545797E+01 4.976823E+01
1.545817E+01 4.976850E+01
1.545838E+01 4.976878E+01
1.545858E+01 4.976903E+01
1.545886E+01 4.976948E+01
1.545896E+01 4.976956E+01
1.545899E+01 4.976962E+01
1.545926E+01 4.976990E+01
1.545928E+01 4.977000E+01
1.545945E+01 4.977013E+01
1.545964E+01 4.977025E+01
1.545972E+01 4.977030E+01
1.545989E+01 4.977053E+01
1.546015E+01 4.977079E+01
1.546064E+01 4.977108E+01
1.546090E+01 4.977133E+01
1.546108E+01 4.977153E+01
1.546178E+01 4.977207E+01
1.546210E+01 4.977228E+01
1.546231E+01 4.977241E+01
1.546262E+01 4.977263E+01
1.546310E+01 4.977302E+01
1.546346E+01 4.977345E+01
1.546364E+01 4.977410E+01
1.546369E+01 4.977417E+01
1.546383E+01 4.977438E+01
1.546412E+01 4.977629E+01
1.546400E+01 4.977730E+01
1.546442E+01 4.977812E+01
1.546445E+01 4.977823E+01
1.546666E+01 4.978119E+01
1.546636E+01 4.978151E+01
1.546575E+01 4.978186E+01
1.546730E+01 4.978294E+01
1.546825E+01 4.978365E+01
1.546878E+01 4.978400E+01
1.546944E+01 4.978444E+01
1.546977E+01 4.978535E+01
1.547004E+01 4.978569E+01
1.547050E+01 4.978611E+01
1.547082E+01 4.978643E+01
1.547124E+01 4.978671E+01
1.547200E+01 4.978700E+01
1.547253E+01 4.978722E+01
1.547297E+01 4.978750E+01
1.547321E+01 4.978760E+01
1.547360E+01 4.978791E+01
1.547349E+01 4.978797E+01
1.547362E+01 4.978823E+01
1.547221E+01 4.978935E+01
1.547177E+01 4.978945E+01
1.547196E+01 4.978951E+01
1.547230E+01 4.978962E+01
1.547252E+01 4.978970E+01
1.547289E+01 4.978970E+01
1.547336E+01 4.978971E+01
1.547326E+01 4.978981E+01
1.547289E+01 4.979035E+01
1.547280E+01 4.979055E+01
1.547275E+01 4.979069E+01
1.547269E+01 4.979102E+01
1.547252E+01 4.979146E+01
1.547230E+01 4.979250E+01
1.547225E+01 4.979269E+01
1.547233E+01 4.979262E+01
1.547245E+01 4.979259E+01
1.547267E+01 4.979258E+01
1.547352E+01 4.979257E+01
1.547359E+01 4.979271E+01
1.547359E+01 4.979276E+01
1.547412E+01 4.979298E+01
1.547476E+01 4.979325E+01
1.547499E+01 4.979335E+01
1.547561E+01 4.979367E+01
1.547626E+01 4.979401E+01
1.547642E+01 4.979409E+01
1.547731E+01 4.979444E+01
1.547766E+01 4.979458E+01
1.547780E+01 4.979463E+01
1.547786E+01 4.979465E+01
1.547795E+01 4.979469E+01
1.547821E+01 4.979479E+01
1.547853E+01 4.979492E+01
1.547910E+01 4.979513E+01
1.547958E+01 4.979530E+01
1.547963E+01 4.979515E+01
1.547966E+01 4.979509E+01
1.547992E+01 4.979519E+01
1.548016E+01 4.979471E+01
1.548042E+01 4.979415E+01
1.548136E+01 4.979446E+01
1.548154E+01 4.979448E+01
1.548165E+01 4.979418E+01
1.548182E+01 4.979396E+01
1.548206E+01 4.979367E+01
1.548215E+01 4.979369E+01
1.548219E+01 4.979362E+01
1.548264E+01 4.979371E+01
1.548282E+01 4.979374E+01
1.548302E+01 4.979375E+01
1.548330E+01 4.979375E+01
1.548520E+01 4.979371E+01
1.548581E+01 4.979370E+01
1.548584E+01 4.979363E+01
1.548589E+01 4.979338E+01
1.548584E+01 4.979327E+01
1.548579E+01 4.979311E+01
1.548587E+01 4.979295E+01
1.548599E+01 4.979275E+01
1.548631E+01 4.979254E+01
1.548641E+01 4.979259E+01
1.548714E+01 4.979285E+01
1.548826E+01 4.979322E+01
1.548847E+01 4.979328E+01
1.548953E+01 4.979301E+01
1.549040E+01 4.979278E+01
1.549032E+01 4.979257E+01
1.549035E+01 4.979233E+01
1.549118E+01 4.979239E+01
1.549141E+01 4.979242E+01
1.549177E+01 4.979205E+01
1.549210E+01 4.979172E+01
1.549218E+01 4.979166E+01
1.549257E+01 4.979171E+01
1.549273E+01 4.979169E+01
1.549288E+01 4.979171E+01
1.549322E+01 4.979177E+01
1.549383E+01 4.979189E+01
1.549415E+01 4.979191E+01
1.549422E+01 4.979171E+01
1.549433E+01 4.979155E+01
1.549428E+01 4.979147E+01
1.549428E+01 4.979137E+01
1.549423E+01 4.979124E+01
1.549410E+01 4.979116E+01
1.549392E+01 4.979081E+01
1.549384E+01 4.979061E+01
1.549359E+01 4.979028E+01
1.549334E+01 4.979002E+01
1.549337E+01 4.978945E+01
1.549346E+01 4.978907E+01
1.549359E+01 4.978882E+01
1.549374E+01 4.978862E+01
1.549401E+01 4.978835E+01
1.549443E+01 4.978794E+01
1.549462E+01 4.978778E+01
1.549467E+01 4.978772E+01
1.549479E+01 4.978754E+01
1.549470E+01 4.978729E+01
1.549519E+01 4.978715E+01
1.549623E+01 4.978676E+01
1.549650E+01 4.978669E+01
1.549683E+01 4.978655E+01
1.549715E+01 4.978634E+01
1.549744E+01 4.978628E+01
1.549781E+01 4.978625E+01
1.549845E+01 4.978638E+01
1.549864E+01 4.978645E+01
1.549886E+01 4.978659E+01
1.549893E+01 4.978639E+01
1.549897E+01 4.978638E+01
1.549873E+01 4.978606E+01
1.549898E+01 4.978576E+01
1.549885E+01 4.978534E+01
1.549880E+01 4.978518E+01
1.549901E+01 4.978494E+01
1.549838E+01 4.978435E+01
1.549854E+01 4.978395E+01
1.549829E+01 4.978357E+01
1.549858E+01 4.978312E+01
1.549885E+01 4.978271E+01
1.549914E+01 4.978257E+01
1.549920E+01 4.978240E+01
1.549915E+01 4.978213E+01
1.549934E+01 4.978192E+01
1.549965E+01 4.978204E+01
1.549978E+01 4.978195E+01
1.549968E+01 4.978171E+01
1.549998E+01 4.978157E+01
1.550005E+01 4.978164E+01
1.550024E+01 4.978160E+01
1.550028E+01 4.978148E+01
1.550059E+01 4.978142E+01
1.550072E+01 4.978123E+01
1.550100E+01 4.978123E+01
1.550113E+01 4.978096E+01
1.550135E+01 4.978073E+01
1.550152E+01 4.978073E+01
1.550193E+01 4.978047E+01
1.550220E+01 4.978030E+01
1.550274E+01 4.978013E+01
1.550278E+01 4.977997E+01
1.550304E+01 4.977993E+01
1.550301E+01 4.977978E+01
1.550352E+01 4.977942E+01
1.550366E+01 4.977915E+01
1.550374E+01 4.977907E+01
1.550384E+01 4.977907E+01
1.550389E+01 4.977889E+01
1.550441E+01 4.977870E+01
1.550461E+01 4.977832E+01
1.550471E+01 4.977810E+01
1.550436E+01 4.977805E+01
1.550371E+01 4.977797E+01
1.550328E+01 4.977767E+01
1.550310E+01 4.977760E+01
1.550285E+01 4.977739E+01
1.550276E+01 4.977729E+01
1.550248E+01 4.977696E+01
1.550238E+01 4.977671E+01
1.550243E+01 4.977660E+01
1.550236E+01 4.977652E+01
1.550242E+01 4.977643E+01
1.550241E+01 4.977637E+01
1.550259E+01 4.977633E+01
1.550263E+01 4.977622E+01
1.550270E+01 4.977615E+01
1.550265E+01 4.977607E+01
1.550280E+01 4.977602E+01
1.550280E+01 4.977593E+01
1.550275E+01 4.977589E+01
1.550280E+01 4.977574E+01
1.550273E+01 4.977559E+01
1.550285E+01 4.977549E+01
1.550294E+01 4.977538E+01
1.550275E+01 4.977530E+01
1.550268E+01 4.977524E+01
1.550245E+01 4.977512E+01
1.550233E+01 4.977509E+01
1.550225E+01 4.977510E+01
1.550208E+01 4.977513E+01
1.550078E+01 4.977546E+01
1.550075E+01 4.977548E+01
1.550047E+01 4.977526E+01
1.550019E+01 4.977511E+01
1.550005E+01 4.977502E+01
1.549986E+01 4.977487E+01
1.549965E+01 4.977470E+01
1.549947E+01 4.977454E+01
1.549933E+01 4.977439E+01
1.549921E+01 4.977405E+01
1.549923E+01 4.977405E+01
1.549920E+01 4.977396E+01
1.549918E+01 4.977396E+01
1.549908E+01 4.977371E+01
1.549897E+01 4.977345E+01
1.549892E+01 4.977335E+01
1.549886E+01 4.977325E+01
1.549853E+01 4.977287E+01
1.549837E+01 4.977272E+01
1.549818E+01 4.977256E+01
1.549782E+01 4.977228E+01
1.549765E+01 4.977216E+01
1.549733E+01 4.977189E+01
1.549717E+01 4.977172E+01
1.549713E+01 4.977167E+01
1.549706E+01 4.977155E+01
1.549697E+01 4.977140E+01
1.549673E+01 4.977089E+01
1.549661E+01 4.977068E+01
1.549656E+01 4.977059E+01
1.549652E+01 4.977048E+01
1.549646E+01 4.977034E+01
1.549644E+01 4.977028E+01
1.549643E+01 4.977017E+01
1.549641E+01 4.977002E+01
1.549640E+01 4.976976E+01
1.549636E+01 4.976954E+01
1.549648E+01 4.976933E+01
1.549640E+01 4.976935E+01
1.549630E+01 4.976921E+01
1.549615E+01 4.976892E+01
1.549606E+01 4.976874E+01
1.549595E+01 4.976853E+01
1.549585E+01 4.976833E+01
1.549576E+01 4.976819E+01
1.549563E+01 4.976800E+01
1.549550E+01 4.976773E+01
1.549527E+01 4.976737E+01
1.549435E+01 4.976601E+01
1.549567E+01 4.976597E+01
1.549588E+01 4.976583E+01
1.549615E+01 4.976563E+01
1.549636E+01 4.976563E+01
1.549662E+01 4.976560E+01
1.549682E+01 4.976551E+01
1.549699E+01 4.976530E+01
1.549701E+01 4.976528E+01
1.549710E+01 4.976500E+01
1.549714E+01 4.976478E+01
1.549712E+01 4.976438E+01
1.549715E+01 4.976410E+01
1.549639E+01 4.976363E+01
1.549623E+01 4.976342E+01
1.549597E+01 4.976311E+01
1.549583E+01 4.976286E+01
1.549555E+01 4.976259E+01
1.549531E+01 4.976216E+01
1.549538E+01 4.976190E+01
1.549556E+01 4.976185E+01
1.549570E+01 4.976188E+01
1.549647E+01 4.976184E+01
1.549676E+01 4.976184E+01
1.549676E+01 4.976191E+01
1.549659E+01 4.976224E+01
1.549660E+01 4.976254E+01
1.549675E+01 4.976276E+01
1.549696E+01 4.976314E+01
1.549737E+01 4.976313E+01
1.549763E+01 4.976306E+01
1.549778E+01 4.976292E+01
1.549806E+01 4.976273E+01
1.549834E+01 4.976263E+01
1.549863E+01 4.976258E+01
1.549884E+01 4.976262E+01
1.549916E+01 4.976266E+01
1.549938E+01 4.976268E+01
1.549956E+01 4.976259E+01
1.549967E+01 4.976260E+01
1.549979E+01 4.976259E+01
1.550027E+01 4.976256E+01
1.550081E+01 4.976264E+01
1.550136E+01 4.976257E+01
1.550146E+01 4.976260E+01
1.550177E+01 4.976261E+01
1.550188E+01 4.976259E+01
1.550219E+01 4.976240E+01
1.550237E+01 4.976233E+01
1.550272E+01 4.976217E+01
1.550295E+01 4.976220E+01
1.550339E+01 4.976219E+01
1.550370E+01 4.976206E+01
1.550385E+01 4.976181E+01
1.550406E+01 4.976169E+01
1.550418E+01 4.976167E+01
1.550431E+01 4.976163E+01
1.550446E+01 4.976155E+01
1.550463E+01 4.976139E+01
1.550474E+01 4.976134E+01
1.550519E+01 4.976115E+01
1.550545E+01 4.976103E+01
1.550577E+01 4.976092E+01
1.550604E+01 4.976083E+01
1.550623E+01 4.976079E+01
1.550639E+01 4.976078E+01
1.550644E+01 4.976082E+01
1.550683E+01 4.976130E+01
1.550708E+01 4.976159E+01
1.550725E+01 4.976181E+01
1.550751E+01 4.976217E+01
1.550763E+01 4.976231E+01
1.550802E+01 4.976278E+01
1.550793E+01 4.976282E+01
1.550820E+01 4.976307E+01
1.550846E+01 4.976337E+01
1.550869E+01 4.976363E+01
1.550888E+01 4.976382E+01
1.550906E+01 4.976402E+01
1.550920E+01 4.976384E+01
1.550960E+01 4.976369E+01
1.551001E+01 4.976351E+01
1.551032E+01 4.976337E+01
1.551053E+01 4.976330E+01
1.551074E+01 4.976333E+01
1.551108E+01 4.976337E+01
1.551124E+01 4.976302E+01
1.551140E+01 4.976265E+01
1.551148E+01 4.976245E+01
1.551160E+01 4.976217E+01
1.551174E+01 4.976197E+01
1.551262E+01 4.976165E+01
1.551292E+01 4.976153E+01
1.551363E+01 4.976114E+01
1.551388E+01 4.976101E+01
1.551418E+01 4.976083E+01
1.551438E+01 4.976063E+01
1.551463E+01 4.976034E+01
1.551485E+01 4.976004E+01
1.551508E+01 4.975975E+01
1.551535E+01 4.975940E+01
1.551572E+01 4.975902E+01
1.551605E+01 4.975867E+01
1.551613E+01 4.975845E+01
1.551632E+01 4.975790E+01
1.551662E+01 4.975704E+01
1.551674E+01 4.975677E+01
1.551692E+01 4.975625E+01
1.551702E+01 4.975599E+01
1.551708E+01 4.975583E+01
1.551718E+01 4.975567E+01
1.551730E+01 4.975539E+01
1.551756E+01 4.975504E+01
1.551767E+01 4.975484E+01
1.551743E+01 4.975455E+01
1.551721E+01 4.975439E+01
1.551699E+01 4.975426E+01
1.551686E+01 4.975417E+01
1.551676E+01 4.975409E+01
1.551658E+01 4.975395E+01
1.551648E+01 4.975379E+01
1.551636E+01 4.975356E+01
1.551626E+01 4.975339E+01
1.551614E+01 4.975324E+01
1.551612E+01 4.975322E+01
1.551574E+01 4.975295E+01
1.551552E+01 4.975283E+01
1.551528E+01 4.975276E+01
1.551508E+01 4.975267E+01
1.551492E+01 4.975263E+01
1.551488E+01 4.975240E+01
1.551486E+01 4.975226E+01
1.551483E+01 4.975211E+01
1.551444E+01 4.975214E+01
1.551424E+01 4.975210E+01
1.551397E+01 4.975205E+01
1.551378E+01 4.975195E+01
1.551317E+01 4.975211E+01
1.551306E+01 4.975196E+01
1.551292E+01 4.975166E+01
1.551313E+01 4.975160E+01
1.551295E+01 4.975129E+01
1.551316E+01 4.975124E+01
1.551303E+01 4.975099E+01
1.551288E+01 4.975104E+01
1.551252E+01 4.975116E+01
1.551248E+01 4.975107E+01
1.551241E+01 4.975097E+01
1.551228E+01 4.975091E+01
1.551207E+01 4.975083E+01
1.551171E+01 4.975082E+01
1.551131E+01 4.975084E+01
1.551116E+01 4.975086E+01
1.551117E+01 4.975083E+01
1.551113E+01 4.975078E+01
1.551104E+01 4.975070E+01
1.551106E+01 4.975061E+01
1.551098E+01 4.975054E+01
1.551093E+01 4.975030E+01
1.551089E+01 4.975019E+01
1.551096E+01 4.975014E+01
1.551088E+01 4.975003E+01
1.551073E+01 4.975000E+01
1.551066E+01 4.974992E+01
1.551071E+01 4.974991E+01
1.551073E+01 4.974985E+01
1.551065E+01 4.974982E+01
1.551059E+01 4.974974E+01
1.551062E+01 4.974970E+01
1.551070E+01 4.974968E+01
1.551066E+01 4.974959E+01
1.551053E+01 4.974960E+01
1.551041E+01 4.974951E+01
1.551033E+01 4.974941E+01
1.551022E+01 4.974930E+01
1.551008E+01 4.974922E+01
1.551003E+01 4.974917E+01
1.550997E+01 4.974909E+01
1.550992E+01 4.974897E+01
1.550985E+01 4.974884E+01
1.550996E+01 4.974874E+01
1.550997E+01 4.974872E+01
1.550995E+01 4.974869E+01
1.550991E+01 4.974865E+01
1.550996E+01 4.974856E+01
1.551035E+01 4.974857E+01
1.551019E+01 4.974843E+01
1.551026E+01 4.974834E+01
1.551023E+01 4.974830E+01
1.551027E+01 4.974827E+01
1.551014E+01 4.974823E+01
1.551015E+01 4.974818E+01
1.551005E+01 4.974809E+01
1.551016E+01 4.974802E+01
1.551012E+01 4.974796E+01
1.551013E+01 4.974794E+01
1.551015E+01 4.974789E+01
1.551015E+01 4.974775E+01
1.551025E+01 4.974770E+01
1.551021E+01 4.974765E+01
1.551022E+01 4.974759E+01
1.551010E+01 4.974736E+01
1.550998E+01 4.974735E+01
1.550998E+01 4.974731E+01
1.550999E+01 4.974725E+01
1.550993E+01 4.974711E+01
1.551008E+01 4.974712E+01
1.551012E+01 4.974716E+01
1.551017E+01 4.974714E+01
1.551009E+01 4.974703E+01
1.551010E+01 4.974702E+01
1.551017E+01 4.974703E+01
1.551023E+01 4.974697E+01
1.551019E+01 4.974694E+01
1.551020E+01 4.974689E+01
1.551025E+01 4.974677E+01
1.551037E+01 4.974663E+01
1.551055E+01 4.974669E+01
1.551056E+01 4.974667E+01
1.551050E+01 4.974656E+01
1.551056E+01 4.974653E+01
1.551074E+01 4.974660E+01
1.551075E+01 4.974658E+01
1.551078E+01 4.974655E+01
1.551074E+01 4.974653E+01
1.551063E+01 4.974652E+01
1.551061E+01 4.974651E+01
1.551066E+01 4.974635E+01
1.551074E+01 4.974632E+01
1.551082E+01 4.974632E+01
1.551095E+01 4.974640E+01
1.551097E+01 4.974645E+01
1.551103E+01 4.974644E+01
1.551111E+01 4.974628E+01
1.551108E+01 4.974622E+01
1.551110E+01 4.974615E+01
1.551113E+01 4.974610E+01
1.551124E+01 4.974604E+01
1.551140E+01 4.974612E+01
1.551132E+01 4.974618E+01
1.551135E+01 4.974622E+01
1.551162E+01 4.974616E+01
1.551171E+01 4.974618E+01
1.551176E+01 4.974627E+01
1.551182E+01 4.974625E+01
1.551188E+01 4.974619E+01
1.551197E+01 4.974624E+01
1.551207E+01 4.974627E+01
1.551211E+01 4.974625E+01
1.551213E+01 4.974622E+01
1.551207E+01 4.974611E+01
1.551213E+01 4.974609E+01
1.551215E+01 4.974608E+01
1.551223E+01 4.974609E+01
1.551232E+01 4.974623E+01
1.551240E+01 4.974624E+01
1.551246E+01 4.974606E+01
1.551244E+01 4.974599E+01
1.551249E+01 4.974599E+01
1.551252E+01 4.974585E+01
1.551259E+01 4.974581E+01
1.551258E+01 4.974572E+01
1.551239E+01 4.974570E+01
1.551225E+01 4.974562E+01
1.551239E+01 4.974547E+01
1.551257E+01 4.974558E+01
1.551260E+01 4.974558E+01
1.551260E+01 4.974544E+01
1.551265E+01 4.974541E+01
1.551270E+01 4.974540E+01
1.551273E+01 4.974535E+01
1.551289E+01 4.974531E+01
1.551295E+01 4.974524E+01
1.551319E+01 4.974524E+01
1.551329E+01 4.974520E+01
1.551336E+01 4.974520E+01
1.551342E+01 4.974512E+01
1.551349E+01 4.974509E+01
1.551348E+01 4.974508E+01
1.551352E+01 4.974476E+01
1.551353E+01 4.974456E+01
1.551349E+01 4.974444E+01
1.551343E+01 4.974439E+01
1.551337E+01 4.974429E+01
1.551336E+01 4.974415E+01
1.551319E+01 4.974401E+01
1.551298E+01 4.974398E+01
1.551260E+01 4.974369E+01
1.551251E+01 4.974352E+01
1.551243E+01 4.974335E+01
1.551248E+01 4.974329E+01
1.551229E+01 4.974322E+01
1.551228E+01 4.974312E+01
1.551222E+01 4.974305E+01
1.551213E+01 4.974301E+01
1.551192E+01 4.974269E+01
1.551188E+01 4.974265E+01
1.551178E+01 4.974268E+01
1.551169E+01 4.974261E+01
1.551164E+01 4.974262E+01
1.551147E+01 4.974249E+01
1.551148E+01 4.974245E+01
1.551157E+01 4.974242E+01
1.551146E+01 4.974230E+01
1.551131E+01 4.974226E+01
1.551109E+01 4.974217E+01
1.551101E+01 4.974209E+01
1.551095E+01 4.974200E+01
1.551075E+01 4.974190E+01
1.551062E+01 4.974192E+01
1.551054E+01 4.974190E+01
1.551004E+01 4.974192E+01
1.550983E+01 4.974180E+01
1.550969E+01 4.974174E+01
1.550962E+01 4.974160E+01
1.550948E+01 4.974157E+01
1.550933E+01 4.974144E+01
1.550926E+01 4.974145E+01
1.550909E+01 4.974129E+01
1.550907E+01 4.974122E+01
1.550899E+01 4.974116E+01
1.550876E+01 4.974110E+01
1.550867E+01 4.974074E+01
1.550857E+01 4.974069E+01
1.550853E+01 4.974060E+01
1.550838E+01 4.974053E+01
1.550836E+01 4.974047E+01
1.550801E+01 4.974021E+01
1.550796E+01 4.974014E+01
1.550780E+01 4.974007E+01
1.550773E+01 4.973992E+01
1.550762E+01 4.973984E+01
1.550740E+01 4.973978E+01
1.550733E+01 4.973973E+01
1.550723E+01 4.973958E+01
1.550712E+01 4.973952E+01
1.550682E+01 4.973924E+01
1.550670E+01 4.973907E+01
1.550672E+01 4.973891E+01
1.550659E+01 4.973873E+01
1.550641E+01 4.973873E+01
1.550610E+01 4.973837E+01
1.550600E+01 4.973817E+01
1.550593E+01 4.973803E+01
1.550559E+01 4.973772E+01
1.550499E+01 4.973717E+01
1.550442E+01 4.973657E+01
1.550403E+01 4.973619E+01
1.550398E+01 4.973611E+01
1.550401E+01 4.973557E+01
1.550404E+01 4.973533E+01
1.550404E+01 4.973517E+01
1.550402E+01 4.973510E+01
1.550337E+01 4.973444E+01
1.550328E+01 4.973434E+01
1.550319E+01 4.973427E+01
1.550279E+01 4.973396E+01
1.550246E+01 4.973374E+01
1.550179E+01 4.973329E+01
1.550095E+01 4.973364E+01
1.550066E+01 4.973367E+01
1.550038E+01 4.973377E+01
1.550025E+01 4.973379E+01
1.549971E+01 4.973402E+01
1.549932E+01 4.973423E+01
1.549913E+01 4.973431E+01
1.549873E+01 4.973451E+01
1.549841E+01 4.973438E+01
1.549790E+01 4.973404E+01
1.549746E+01 4.973375E+01
1.549675E+01 4.973329E+01
1.549720E+01 4.973260E+01
1.549625E+01 4.973262E+01
1.549587E+01 4.973269E+01
1.549556E+01 4.973278E+01
1.549543E+01 4.973278E+01
1.549546E+01 4.973268E+01
1.549545E+01 4.973228E+01
1.549530E+01 4.973227E+01
1.549504E+01 4.973255E+01
1.549479E+01 4.973274E+01
1.549425E+01 4.973310E+01
1.549393E+01 4.973336E+01
1.549310E+01 4.973296E+01
1.549254E+01 4.973266E+01
1.549195E+01 4.973233E+01
1.549131E+01 4.973274E+01
1.549104E+01 4.973293E+01
1.549058E+01 4.973326E+01
1.549020E+01 4.973353E+01
1.548971E+01 4.973388E+01
1.548934E+01 4.973414E+01
1.548933E+01 4.973426E+01
1.548923E+01 4.973437E+01
1.548920E+01 4.973439E+01
1.548907E+01 4.973441E+01
1.548872E+01 4.973435E+01
1.548876E+01 4.973447E+01
1.548859E+01 4.973453E+01
1.548857E+01 4.973463E+01
1.548847E+01 4.973465E+01
1.548837E+01 4.973468E+01
1.548809E+01 4.973481E+01
1.548803E+01 4.973484E+01
1.548784E+01 4.973495E+01
1.548772E+01 4.973513E+01
1.548751E+01 4.973522E+01
1.548750E+01 4.973527E+01
1.548714E+01 4.973549E+01
1.548711E+01 4.973554E+01
1.548703E+01 4.973554E+01
1.548661E+01 4.973591E+01
1.548655E+01 4.973619E+01
1.548661E+01 4.973643E+01
1.548674E+01 4.973649E+01
1.548651E+01 4.973688E+01
1.548658E+01 4.973706E+01
1.548656E+01 4.973714E+01
1.548640E+01 4.973722E+01
1.548627E+01 4.973733E+01
1.548628E+01 4.973743E+01
1.548614E+01 4.973751E+01
1.548608E+01 4.973757E+01
1.548603E+01 4.973796E+01
1.548598E+01 4.973802E+01
1.548596E+01 4.973809E+01
1.548599E+01 4.973821E+01
1.548575E+01 4.973851E+01
1.548581E+01 4.973862E+01
1.548571E+01 4.973867E+01
1.548568E+01 4.973882E+01
1.548575E+01 4.973903E+01
1.548589E+01 4.973910E+01
1.548587E+01 4.973921E+01
1.548594E+01 4.973938E+01
1.548580E+01 4.973945E+01
1.548604E+01 4.973971E+01
1.548592E+01 4.973980E+01
1.548581E+01 4.973996E+01
1.548531E+01 4.973976E+01
1.548472E+01 4.973950E+01
1.548350E+01 4.973892E+01
1.548309E+01 4.973874E+01
1.548225E+01 4.973836E+01
1.548210E+01 4.973833E+01
1.548166E+01 4.973810E+01
1.548111E+01 4.973777E+01
1.548073E+01 4.973796E+01
1.548063E+01 4.973802E+01
1.548040E+01 4.973812E+01
1.548026E+01 4.973817E+01
1.548011E+01 4.973826E+01
1.547996E+01 4.973835E+01
1.547975E+01 4.973845E+01
1.547964E+01 4.973849E+01
1.547942E+01 4.973862E+01
1.547920E+01 4.973887E+01
1.547905E+01 4.973900E+01
1.547880E+01 4.973914E+01
1.547840E+01 4.973944E+01
1.547827E+01 4.973952E+01
1.547804E+01 4.973963E+01
1.547774E+01 4.973981E+01
1.547759E+01 4.973989E+01
1.547731E+01 4.974006E+01
1.547711E+01 4.974023E+01
1.547689E+01 4.974042E+01
1.547656E+01 4.974066E+01
1.547631E+01 4.974087E+01
1.547605E+01 4.974106E+01
1.547586E+01 4.974117E+01
1.547542E+01 4.974152E+01
1.547502E+01 4.974139E+01
1.547451E+01 4.974217E+01
1.547439E+01 4.974241E+01
1.547430E+01 4.974269E+01
1.547428E+01 4.974306E+01
1.547433E+01 4.974334E+01
1.547429E+01 4.974334E+01
1.547351E+01 4.974301E+01
1.547290E+01 4.974270E+01
1.547274E+01 4.974286E+01
1.547255E+01 4.974296E+01
1.547199E+01 4.974311E+01
1.547164E+01 4.974324E+01
1.547127E+01 4.974339E+01
1.547101E+01 4.974348E+01
1.547078E+01 4.974346E+01
1.547076E+01 4.974359E+01
1.547077E+01 4.974371E+01
1.547078E+01 4.974391E+01
1.547108E+01 4.974431E+01
1.547117E+01 4.974445E+01
1.547055E+01 4.974464E+01
1.547031E+01 4.974498E+01
1.547087E+01 4.974514E+01
1.547106E+01 4.974571E+01
1.547140E+01 4.974638E+01
1.547130E+01 4.974646E+01
1.547059E+01 4.974624E+01
1.547043E+01 4.974619E+01
1.546987E+01 4.974598E+01
1.546981E+01 4.974596E+01
1.546946E+01 4.974586E+01
1.546928E+01 4.974632E+01
1.546920E+01 4.974634E+01
1.546923E+01 4.974640E+01
1.546907E+01 4.974639E+01
1.546901E+01 4.974641E+01
1.546883E+01 4.974639E+01
1.546869E+01 4.974642E+01
1.546851E+01 4.974640E+01
1.546840E+01 4.974646E+01
1.546829E+01 4.974650E+01
1.546830E+01 4.974660E+01
1.546824E+01 4.974662E+01
1.546816E+01 4.974659E+01
1.546807E+01 4.974664E+01
1.546801E+01 4.974662E+01
1.546801E+01 4.974651E+01
1.546791E+01 4.974649E+01
1.546780E+01 4.974651E+01
1.546784E+01 4.974663E+01
1.546773E+01 4.974667E+01
1.546757E+01 4.974663E+01
1.546744E+01 4.974666E+01
1.546740E+01 4.974677E+01
1.546729E+01 4.974679E+01
1.546720E+01 4.974686E+01
1.546670E+01 4.974695E+01
1.546668E+01 4.974704E+01
1.546671E+01 4.974712E+01
1.546664E+01 4.974714E+01
1.546652E+01 4.974710E+01
1.546646E+01 4.974708E+01
1.546656E+01 4.974701E+01
1.546652E+01 4.974693E+01
1.546630E+01 4.974699E+01
1.546630E+01 4.974707E+01
1.546638E+01 4.974710E+01
1.546634E+01 4.974714E+01
1.546634E+01 4.974720E+01
1.546622E+01 4.974723E+01
1.546612E+01 4.974729E+01
1.546614E+01 4.974740E+01
1.546592E+01 4.974748E+01
1.546575E+01 4.974751E+01
1.546567E+01 4.974755E+01
1.546552E+01 4.974755E+01
1.546530E+01 4.974772E+01
1.546523E+01 4.974762E+01
1.546513E+01 4.974766E+01
1.546532E+01 4.974790E+01
1.546524E+01 4.974794E+01
1.546525E+01 4.974803E+01
1.546526E+01 4.974811E+01
1.546531E+01 4.974817E+01
1.546547E+01 4.974815E+01
1.546551E+01 4.974831E+01
1.546537E+01 4.974838E+01
1.546530E+01 4.974838E+01
1.546499E+01 4.974820E+01
1.546494E+01 4.974812E+01
1.546465E+01 4.974790E+01
1.546384E+01 4.974822E+01
1.546374E+01 4.974828E+01
1.546347E+01 4.974827E+01
1.546334E+01 4.974827E+01
1.546322E+01 4.974828E+01
1.546320E+01 4.974790E+01
1.546309E+01 4.974702E+01
1.546303E+01 4.974665E+01
1.546287E+01 4.974606E+01
1.546272E+01 4.974552E+01
1.546259E+01 4.974511E+01
1.546257E+01 4.974500E+01
1.546253E+01 4.974478E+01
1.546233E+01 4.974427E+01
1.546230E+01 4.974417E+01
1.546207E+01 4.974359E+01
1.546199E+01 4.974340E+01
1.546146E+01 4.974343E+01
1.546131E+01 4.974347E+01
1.546078E+01 4.974347E+01
1.546050E+01 4.974350E+01
1.545985E+01 4.974352E+01
1.545940E+01 4.974349E+01
1.545895E+01 4.974341E+01
1.545881E+01 4.974336E+01
1.545837E+01 4.974338E+01
1.545800E+01 4.974342E+01
1.545738E+01 4.974305E+01
1.545727E+01 4.974296E+01
1.545702E+01 4.974261E+01
1.545677E+01 4.974221E+01
1.545663E+01 4.974211E+01
1.545649E+01 4.974192E+01
1.545608E+01 4.974159E+01
1.545584E+01 4.974139E+01
1.545522E+01 4.974095E+01
1.545464E+01 4.974047E+01
1.545420E+01 4.973998E+01
1.545409E+01 4.973984E+01
1.545405E+01 4.973976E+01
1.545391E+01 4.973947E+01
1.545369E+01 4.973927E+01
1.545348E+01 4.973907E+01
1.545323E+01 4.973889E+01
1.545298E+01 4.973878E+01
1.545270E+01 4.973872E+01
1.545244E+01 4.973865E+01
1.545217E+01 4.973849E+01
1.545174E+01 4.973831E+01
1.545174E+01 4.973829E+01
1.545125E+01 4.973813E+01
1.545104E+01 4.973805E+01
1.545094E+01 4.973800E+01
1.545104E+01 4.973787E+01
1.545121E+01 4.973779E+01
1.545122E+01 4.973773E+01
1.545126E+01 4.973769E+01
1.545157E+01 4.973753E+01
1.545156E+01 4.973747E+01
1.545179E+01 4.973733E+01
1.545180E+01 4.973724E+01
1.545195E+01 4.973728E+01
1.545200E+01 4.973720E+01
1.545208E+01 4.973718E+01
1.545205E+01 4.973707E+01
1.545218E+01 4.973701E+01
1.545208E+01 4.973689E+01
1.545238E+01 4.973652E+01
1.545237E+01 4.973640E+01
1.545250E+01 4.973630E+01
1.545268E+01 4.973619E+01
1.545274E+01 4.973615E+01
1.545289E+01 4.973604E+01
1.545298E+01 4.973597E+01
1.545315E+01 4.973588E+01
1.545325E+01 4.973577E+01
1.545341E+01 4.973561E+01
1.545356E+01 4.973544E+01
1.545363E+01 4.973532E+01
1.545378E+01 4.973507E+01
1.545394E+01 4.973481E+01
1.545407E+01 4.973461E+01
1.545421E+01 4.973441E+01
1.545430E+01 4.973420E+01
1.545433E+01 4.973400E+01
1.545427E+01 4.973384E+01
1.545429E+01 4.973372E+01
1.545426E+01 4.973364E+01
1.545428E+01 4.973357E+01
1.545422E+01 4.973343E+01
1.545422E+01 4.973318E+01
1.545407E+01 4.973305E+01
1.545407E+01 4.973296E+01
1.545414E+01 4.973290E+01
1.545423E+01 4.973289E+01
1.545428E+01 4.973282E+01
1.545421E+01 4.973273E+01
1.545414E+01 4.973270E+01
1.545425E+01 4.973261E+01
1.545428E+01 4.973251E+01
1.545454E+01 4.973227E+01
1.545485E+01 4.973199E+01
1.545518E+01 4.973170E+01
1.545536E+01 4.973152E+01
1.545538E+01 4.973150E+01
1.545543E+01 4.973146E+01
1.545547E+01 4.973144E+01
1.545516E+01 4.973114E+01
1.545488E+01 4.973087E+01
1.545463E+01 4.973064E+01
1.545433E+01 4.973036E+01
1.545429E+01 4.973033E+01
1.545473E+01 4.973005E+01
1.545513E+01 4.972981E+01
1.545513E+01 4.972980E+01
1.545515E+01 4.972979E+01
1.545558E+01 4.972948E+01
1.545573E+01 4.972937E+01
1.545603E+01 4.972919E+01
1.545628E+01 4.972903E+01
1.545656E+01 4.972890E+01
1.545733E+01 4.972854E+01
1.545758E+01 4.972843E+01
1.545839E+01 4.972823E+01
1.545891E+01 4.972813E+01
1.545945E+01 4.972800E+01
1.545975E+01 4.972795E+01
1.546004E+01 4.972789E+01
1.546098E+01 4.972748E+01
1.546130E+01 4.972730E+01
1.546144E+01 4.972723E+01
1.546369E+01 4.972610E+01
1.546490E+01 4.972549E+01
1.546782E+01 4.972793E+01
1.546826E+01 4.972778E+01
1.546830E+01 4.972781E+01
1.546850E+01 4.972794E+01
1.546907E+01 4.972830E+01
1.546950E+01 4.972855E+01
1.546996E+01 4.972878E+01
1.547043E+01 4.972902E+01
1.547059E+01 4.972892E+01
1.547067E+01 4.972887E+01
1.547098E+01 4.972866E+01
1.547112E+01 4.972855E+01
1.547154E+01 4.972828E+01
1.547190E+01 4.972809E+01
1.547202E+01 4.972802E+01
1.547253E+01 4.972777E+01
1.547310E+01 4.972753E+01
1.547362E+01 4.972734E+01
1.547417E+01 4.972712E+01
1.547464E+01 4.972694E+01
1.547497E+01 4.972681E+01
1.547531E+01 4.972669E+01
1.547546E+01 4.972663E+01
1.547546E+01 4.972663E+01
1.547543E+01 4.972660E+01
1.547602E+01 4.972639E+01
1.547648E+01 4.972622E+01
1.547685E+01 4.972604E+01
1.547718E+01 4.972588E+01
1.547747E+01 4.972576E+01
1.547821E+01 4.972547E+01
1.547911E+01 4.972516E+01
1.547910E+01 4.972499E+01
1.547910E+01 4.972471E+01
1.547895E+01 4.972446E+01
1.547867E+01 4.972415E+01
1.547837E+01 4.972390E+01
1.547803E+01 4.972368E+01
1.547780E+01 4.972345E+01
1.547764E+01 4.972329E+01
1.547758E+01 4.972326E+01
1.547738E+01 4.972315E+01
1.547713E+01 4.972304E+01
1.547676E+01 4.972286E+01
1.547655E+01 4.972275E+01
1.547617E+01 4.972256E+01
1.547592E+01 4.972215E+01
1.547582E+01 4.972200E+01
1.547572E+01 4.972186E+01
1.547565E+01 4.972178E+01
1.547556E+01 4.972170E+01
1.547543E+01 4.972163E+01
1.547525E+01 4.972158E+01
1.547519E+01 4.972155E+01
1.547507E+01 4.972150E+01
1.547504E+01 4.972145E+01
1.547502E+01 4.972142E+01
1.547491E+01 4.972136E+01
1.547489E+01 4.972135E+01
1.547482E+01 4.972124E+01
1.547478E+01 4.972116E+01
1.547470E+01 4.972113E+01
1.547466E+01 4.972108E+01
1.547458E+01 4.972108E+01
1.547454E+01 4.972106E+01
1.547452E+01 4.972100E+01
1.547444E+01 4.972103E+01
1.547443E+01 4.972101E+01
1.547434E+01 4.972103E+01
1.547432E+01 4.972092E+01
1.547427E+01 4.972092E+01
1.547429E+01 4.972084E+01
1.547422E+01 4.972082E+01
1.547396E+01 4.972062E+01
1.547392E+01 4.972055E+01
1.547377E+01 4.972053E+01
1.547359E+01 4.972048E+01
1.547335E+01 4.972046E+01
1.547323E+01 4.972036E+01
1.547314E+01 4.972030E+01
1.547300E+01 4.972021E+01
1.547283E+01 4.972003E+01
1.547268E+01 4.971988E+01
1.547248E+01 4.971969E+01
1.547258E+01 4.971962E+01
1.547275E+01 4.971949E+01
1.547239E+01 4.971945E+01
1.547203E+01 4.971940E+01
1.547185E+01 4.971920E+01
1.547182E+01 4.971922E+01
1.547100E+01 4.971835E+01
1.547095E+01 4.971830E+01
1.547090E+01 4.971823E+01
1.547078E+01 4.971806E+01
1.547027E+01 4.971740E+01
1.547007E+01 4.971722E+01
1.546914E+01 4.971662E+01
1.546886E+01 4.971643E+01
1.546833E+01 4.971609E+01
1.546813E+01 4.971600E+01
1.546802E+01 4.971596E+01
1.546788E+01 4.971590E+01
1.546752E+01 4.971578E+01
1.546644E+01 4.971546E+01
1.546601E+01 4.971534E+01
1.546606E+01 4.971532E+01
1.546594E+01 4.971531E+01
1.546591E+01 4.971527E+01
1.546557E+01 4.971511E+01
1.546560E+01 4.971507E+01
1.546552E+01 4.971503E+01
1.546551E+01 4.971500E+01
1.546544E+01 4.971500E+01
1.546539E+01 4.971483E+01
1.546527E+01 4.971466E+01
1.546504E+01 4.971448E+01
1.546494E+01 4.971440E+01
1.546452E+01 4.971405E+01
1.546430E+01 4.971387E+01
1.546378E+01 4.971382E+01
1.546370E+01 4.971383E+01
1.546359E+01 4.971380E+01
1.546350E+01 4.971379E+01
1.546349E+01 4.971379E+01
1.546278E+01 4.971373E+01
1.546277E+01 4.971357E+01
1.546257E+01 4.971355E+01
1.546262E+01 4.971345E+01
1.546235E+01 4.971346E+01
1.546214E+01 4.971315E+01
1.546184E+01 4.971305E+01
1.546184E+01 4.971293E+01
1.546183E+01 4.971290E+01
1.546155E+01 4.971286E+01
1.546132E+01 4.971286E+01
1.546108E+01 4.971274E+01
1.546100E+01 4.971241E+01
1.546102E+01 4.971211E+01
1.546111E+01 4.971207E+01
1.546119E+01 4.971190E+01
1.546111E+01 4.971183E+01
1.546116E+01 4.971162E+01
1.546116E+01 4.971161E+01
1.546117E+01 4.971159E+01
1.546116E+01 4.971158E+01
1.546103E+01 4.971138E+01
1.546101E+01 4.971125E+01
1.546103E+01 4.971120E+01
1.546092E+01 4.971120E+01
1.546092E+01 4.971096E+01
1.546115E+01 4.971045E+01
1.546117E+01 4.971027E+01
1.546114E+01 4.971008E+01
1.546093E+01 4.970969E+01
1.546066E+01 4.970951E+01
1.546017E+01 4.970919E+01
1.546005E+01 4.970895E+01
1.545990E+01 4.970883E+01
1.545977E+01 4.970876E+01
1.545971E+01 4.970872E+01
1.545928E+01 4.970839E+01
1.545904E+01 4.970815E+01
1.545875E+01 4.970805E+01
1.545859E+01 4.970788E+01
1.545852E+01 4.970776E+01
1.545843E+01 4.970753E+01
1.545830E+01 4.970733E+01
1.545830E+01 4.970712E+01
1.545793E+01 4.970681E+01
1.545767E+01 4.970666E+01
1.545745E+01 4.970646E+01
1.545720E+01 4.970612E+01
1.545673E+01 4.970599E+01
1.545647E+01 4.970585E+01
1.545572E+01 4.970531E+01
1.545560E+01 4.970525E+01
1.545531E+01 4.970512E+01
1.545510E+01 4.970502E+01
1.545509E+01 4.970502E+01
1.545497E+01 4.970498E+01
1.545449E+01 4.970486E+01
1.545413E+01 4.970471E+01
1.545392E+01 4.970456E+01
1.545367E+01 4.970451E+01
1.545334E+01 4.970442E+01
1.545316E+01 4.970431E+01
1.545313E+01 4.970426E+01
1.545297E+01 4.970415E+01
1.545286E+01 4.970406E+01
1.545283E+01 4.970400E+01
1.545280E+01 4.970391E+01
1.545274E+01 4.970383E+01
1.545266E+01 4.970371E+01
1.545237E+01 4.970343E+01
1.545234E+01 4.970340E+01
1.545236E+01 4.970336E+01
1.545227E+01 4.970324E+01
1.545208E+01 4.970324E+01
1.545183E+01 4.970317E+01
1.545169E+01 4.970312E+01
1.545163E+01 4.970302E+01
1.545144E+01 4.970290E+01
1.545135E+01 4.970287E+01
1.545121E+01 4.970286E+01
1.545111E+01 4.970278E+01
1.545089E+01 4.970271E+01
1.545078E+01 4.970266E+01
1.545072E+01 4.970258E+01
1.545065E+01 4.970253E+01
1.545057E+01 4.970248E+01
1.545054E+01 4.970243E+01
1.545055E+01 4.970238E+01
1.545049E+01 4.970235E+01
1.545051E+01 4.970224E+01
1.545046E+01 4.970222E+01
1.545026E+01 4.970225E+01
1.545019E+01 4.970230E+01
1.545014E+01 4.970231E+01
1.545007E+01 4.970229E+01
1.544995E+01 4.970223E+01
1.544992E+01 4.970217E+01
1.544981E+01 4.970213E+01
1.544955E+01 4.970213E+01
1.544929E+01 4.970208E+01
1.544902E+01 4.970189E+01
1.544875E+01 4.970177E+01
1.544862E+01 4.970175E+01
1.544841E+01 4.970174E+01
1.544830E+01 4.970165E+01
1.544823E+01 4.970162E+01
1.544811E+01 4.970162E+01
1.544800E+01 4.970165E+01
1.544792E+01 4.970167E+01
1.544784E+01 4.970165E+01
1.544772E+01 4.970159E+01
1.544750E+01 4.970154E+01
1.544733E+01 4.970147E+01
1.544728E+01 4.970149E+01
1.544721E+01 4.970153E+01
1.544711E+01 4.970160E+01
1.544710E+01 4.970167E+01
1.544709E+01 4.970174E+01
1.544702E+01 4.970176E+01
1.544686E+01 4.970176E+01
1.544670E+01 4.970175E+01
1.544654E+01 4.970169E+01
1.544631E+01 4.970158E+01
1.544625E+01 4.970156E+01
1.544620E+01 4.970151E+01
1.544601E+01 4.970142E+01
1.544597E+01 4.970144E+01
1.544586E+01 4.970151E+01
1.544553E+01 4.970169E+01
1.544543E+01 4.970176E+01
1.544534E+01 4.970188E+01
1.544519E+01 4.970212E+01
1.544512E+01 4.970224E+01
1.544496E+01 4.970255E+01
1.544483E+01 4.970277E+01
1.544474E+01 4.970289E+01
1.544468E+01 4.970302E+01
1.544467E+01 4.970313E+01
1.544473E+01 4.970321E+01
1.544475E+01 4.970331E+01
1.544479E+01 4.970339E+01
1.544477E+01 4.970356E+01
1.544467E+01 4.970363E+01
1.544454E+01 4.970375E+01
1.544452E+01 4.970375E+01
1.544452E+01 4.970376E+01
1.544448E+01 4.970379E+01
1.544451E+01 4.970385E+01
1.544450E+01 4.970387E+01
1.544454E+01 4.970391E+01
1.544459E+01 4.970394E+01
1.544467E+01 4.970398E+01
1.544468E+01 4.970401E+01
1.544472E+01 4.970401E+01
1.544481E+01 4.970398E+01
1.544483E+01 4.970399E+01
1.544483E+01 4.970402E+01
1.544482E+01 4.970404E+01
1.544477E+01 4.970407E+01
1.544469E+01 4.970408E+01
1.544468E+01 4.970409E+01
1.544466E+01 4.970412E+01
1.544466E+01 4.970417E+01
1.544463E+01 4.970421E+01
1.544466E+01 4.970428E+01
1.544460E+01 4.970434E+01
1.544462E+01 4.970438E+01
1.544469E+01 4.970441E+01
1.544474E+01 4.970444E+01
1.544482E+01 4.970444E+01
1.544489E+01 4.970449E+01
1.544489E+01 4.970452E+01
1.544489E+01 4.970456E+01
1.544492E+01 4.970460E+01
1.544500E+01 4.970464E+01
1.544504E+01 4.970466E+01
1.544510E+01 4.970465E+01
1.544512E+01 4.970466E+01
1.544515E+01 4.970469E+01
1.544514E+01 4.970474E+01
1.544515E+01 4.970477E+01
1.544523E+01 4.970483E+01
1.544527E+01 4.970485E+01
1.544536E+01 4.970487E+01
1.544538E+01 4.970489E+01
1.544536E+01 4.970495E+01
1.544536E+01 4.970506E+01
1.544544E+01 4.970510E+01
1.544550E+01 4.970515E+01
1.544552E+01 4.970523E+01
1.544556E+01 4.970530E+01
1.544558E+01 4.970542E+01
1.544564E+01 4.970547E+01
1.544568E+01 4.970549E+01
1.544570E+01 4.970552E+01
1.544567E+01 4.970553E+01
1.544555E+01 4.970552E+01
1.544554E+01 4.970560E+01
1.544550E+01 4.970567E+01
1.544553E+01 4.970573E+01
1.544547E+01 4.970577E+01
1.544546E+01 4.970579E+01
1.544548E+01 4.970580E+01
1.544562E+01 4.970578E+01
1.544571E+01 4.970578E+01
1.544574E+01 4.970583E+01
1.544571E+01 4.970588E+01
1.544570E+01 4.970594E+01
1.544569E+01 4.970598E+01
1.544579E+01 4.970609E+01
1.544587E+01 4.970613E+01
1.544587E+01 4.970619E+01
1.544580E+01 4.970626E+01
1.544579E+01 4.970629E+01
1.544584E+01 4.970634E+01
1.544588E+01 4.970636E+01
1.544593E+01 4.970633E+01
1.544600E+01 4.970634E+01
1.544602E+01 4.970637E+01
1.544599E+01 4.970644E+01
1.544605E+01 4.970654E+01
1.544623E+01 4.970657E+01
1.544625E+01 4.970660E+01
1.544621E+01 4.970672E+01
1.544623E+01 4.970680E+01
1.544631E+01 4.970683E+01
1.544631E+01 4.970686E+01
1.544625E+01 4.970696E+01
1.544627E+01 4.970701E+01
1.544632E+01 4.970702E+01
1.544636E+01 4.970707E+01
1.544636E+01 4.970715E+01
1.544639E+01 4.970725E+01
1.544643E+01 4.970734E+01
1.544649E+01 4.970736E+01
1.544653E+01 4.970747E+01
1.544660E+01 4.970753E+01
1.544673E+01 4.970753E+01
1.544667E+01 4.970760E+01
1.544675E+01 4.970768E+01
1.544690E+01 4.970773E+01
1.544689E+01 4.970779E+01
1.544700E+01 4.970777E+01
1.544703E+01 4.970784E+01
1.544712E+01 4.970788E+01
1.544710E+01 4.970801E+01
1.544719E+01 4.970805E+01
1.544725E+01 4.970810E+01
1.544729E+01 4.970831E+01
1.544733E+01 4.970848E+01
1.544733E+01 4.970856E+01
1.544728E+01 4.970866E+01
1.544729E+01 4.970868E+01
1.544710E+01 4.970894E+01
1.544703E+01 4.970900E+01
1.544681E+01 4.970929E+01
1.544670E+01 4.970949E+01
1.544663E+01 4.970968E+01
1.544662E+01 4.970986E+01
1.544665E+01 4.970998E+01
1.544676E+01 4.971036E+01
1.544683E+01 4.971062E+01
1.544689E+01 4.971116E+01
1.544692E+01 4.971156E+01
1.544695E+01 4.971168E+01
1.544700E+01 4.971180E+01
1.544723E+01 4.971215E+01
1.544728E+01 4.971223E+01
1.544740E+01 4.971243E+01
1.544744E+01 4.971255E+01
1.544744E+01 4.971270E+01
1.544742E+01 4.971283E+01
1.544729E+01 4.971298E+01
1.544705E+01 4.971316E+01
1.544659E+01 4.971335E+01
1.544659E+01 4.971335E+01
1.544648E+01 4.971343E+01
1.544646E+01 4.971344E+01
1.544629E+01 4.971348E+01
1.544548E+01 4.971378E+01
1.544524E+01 4.971372E+01
1.544513E+01 4.971369E+01
1.544482E+01 4.971363E+01
1.544453E+01 4.971358E+01
1.544452E+01 4.971358E+01
1.544444E+01 4.971357E+01
1.544154E+01 4.971363E+01
1.544146E+01 4.971372E+01
1.544121E+01 4.971394E+01
1.544091E+01 4.971420E+01
1.544062E+01 4.971446E+01
1.544056E+01 4.971451E+01
1.544052E+01 4.971454E+01
1.544021E+01 4.971480E+01
1.543992E+01 4.971500E+01
1.543960E+01 4.971521E+01
1.543939E+01 4.971532E+01
1.543919E+01 4.971541E+01
1.543869E+01 4.971553E+01
1.543868E+01 4.971548E+01
1.543866E+01 4.971549E+01
1.543855E+01 4.971555E+01
1.543813E+01 4.971580E+01
1.543785E+01 4.971593E+01
1.543783E+01 4.971595E+01
1.543766E+01 4.971604E+01
1.543752E+01 4.971612E+01
1.543742E+01 4.971616E+01
1.543732E+01 4.971621E+01
1.543716E+01 4.971628E+01
1.543693E+01 4.971637E+01
1.543667E+01 4.971650E+01
1.543660E+01 4.971654E+01
1.543585E+01 4.971675E+01
1.543533E+01 4.971696E+01
1.543469E+01 4.971734E+01
1.543422E+01 4.971761E+01
1.543342E+01 4.971824E+01
1.543332E+01 4.971840E+01
1.543321E+01 4.971865E+01
1.543305E+01 4.971911E+01
1.543292E+01 4.971938E+01
1.543284E+01 4.971961E+01
1.543262E+01 4.972030E+01
1.543250E+01 4.972049E+01
1.543236E+01 4.972065E+01
1.543199E+01 4.972074E+01
END
END
| {
"pile_set_name": "Github"
} |
//
// SectionModel.swift
// RxDataSources
//
// Created by Krunoslav Zaher on 6/16/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
public struct SectionModel<Section, ItemType> {
public var model: Section
public var items: [Item]
public init(model: Section, items: [Item]) {
self.model = model
self.items = items
}
}
extension SectionModel
: SectionModelType {
public typealias Identity = Section
public typealias Item = ItemType
public var identity: Section {
return model
}
}
extension SectionModel
: CustomStringConvertible {
public var description: String {
return "\(self.model) > \(items)"
}
}
extension SectionModel {
public init(original: SectionModel<Section, Item>, items: [Item]) {
self.model = original.model
self.items = items
}
}
| {
"pile_set_name": "Github"
} |
-----BEGIN CERTIFICATE-----
MIICKjCCAZMCCQCDBr594bsJmTANBgkqhkiG9w0BAQUFADB6MQswCQYDVQQGEwJV
UzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQKEwZKb3llbnQxEDAO
BgNVBAsTB05vZGUuanMxDDAKBgNVBAMTA2NhMjEgMB4GCSqGSIb3DQEJARYRcnlA
dGlueWNsb3Vkcy5vcmcwHhcNMTEwMzE0MTgyOTEyWhcNMzgwNzI5MTgyOTEyWjB9
MQswCQYDVQQGEwJVUzELMAkGA1UECBMCQ0ExCzAJBgNVBAcTAlNGMQ8wDQYDVQQK
EwZKb3llbnQxEDAOBgNVBAsTB05vZGUuanMxDzANBgNVBAMTBmFnZW50MzEgMB4G
CSqGSIb3DQEJARYRcnlAdGlueWNsb3Vkcy5vcmcwXDANBgkqhkiG9w0BAQEFAANL
ADBIAkEAtlNDZ+bHeBI0B2gD/IWqA7Aq1hwsnS4+XpnLesjTQcL2JwFFpkR0oWrw
yjrYhCogi7c5gjKrLZF1d2JD5JgHgQIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAJoK
bXwsImk7vJz9649yrmsXwnuGbEKVYMvqcGyjaZNP9lYEG41y5CeRzxhWy2rlYdhE
f2nqE2lg75oJP7LQqfQY7aCqwahM3q/GQbsfKVCGjF7TVyq9TQzd8iW+FEJIQzSE
3aN85hR67+3VAXeSzmkGSVBO2m1SJIug4qftIkc2
-----END CERTIFICATE-----
| {
"pile_set_name": "Github"
} |
/**
* Returns whether the provided value is a promise
*
* @param {object} value Potential promise
* @return {Boolean}
*/
export default function isPromise(value) {
return !!value &&
typeof value.promise === 'object' &&
typeof value.promise.then === 'function';
}
| {
"pile_set_name": "Github"
} |
///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net)
/// 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.
///
/// Restrictions:
/// By making use of the Software for military purposes, you choose to make
/// a Bunny unhappy.
///
/// 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.
///
/// @ref core
/// @file glm/matrix.hpp
/// @date 2013-12-24 / 2013-12-24
/// @author Christophe Riccio
///////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "detail/func_matrix.hpp"
| {
"pile_set_name": "Github"
} |
{% from "macros/loadComponentTemplate.njk" import loadComponentTemplate %}
<h4 class="govuk-heading-s">Markup</h4>
{% set componentHtml %}{{ loadComponentTemplate(componentSlug, example.data) }}{% endset %}
<pre><code class="govuk-!-font-size-16">{{- componentHtml | e -}}</code></pre>
<h4 class="govuk-heading-s">Macro</h4>
<pre class="govuk-!-margin-bottom-0 govuk-!-font-size-16"><code>{% raw %}{%{% endraw %} from "{{ componentSlug }}/macro.njk" import {{ componentSlug | componentNameToMacroName }} {% raw %}%}{% endraw %}
{% raw %}{{ {% endraw %}{{ componentSlug | componentNameToMacroName }}(
{{- example.data | dump(2) -}}
){% raw %} }}{% endraw %}</code></pre>
| {
"pile_set_name": "Github"
} |
<?php
namespace app\models;
use app\libraries\Core;
use app\libraries\DiffViewer;
use app\libraries\Utils;
/**
* Class GradeableAutocheck
*
* Contains information pertaining to the autocheck element that's contained within a
* GradeableTestcase. There is 0+ autochecks per GradeableTestcase.
*
* @method string getIndex()
* @method DiffViewer getDiffViewer()
* @method string getDescription()
* @method array[] getMessages()
* @method boolean getPublic()
*/
class GradeableAutocheck extends AbstractModel {
/** @prop @var string */
protected $index;
/** @var DiffViewer DiffViewer instance to hold the student, instructor, and differences */
protected $diff_viewer;
/** @prop @var string Description to show for displaying the diff */
protected $description = "";
/** @prop @var array[] Message to show underneath the description for a diff */
protected $messages = [];
/** @prop @var boolean If this check's file is in results_public */
protected $public;
/** @prop @var boolean If this check's file should be displayed as a sequence diagram */
protected $display_as_sequence_diagram;
/**
* GradeableAutocheck constructor.
*
* @param Core $core
* @param $details
* @param $course_path
* @param $results_path
* @param $results_public_path
* @param $idx
*/
public function __construct(Core $core, $details, $course_path, $results_path, $results_public_path, $idx) {
parent::__construct($core);
$this->index = $idx;
if (isset($details['description'])) {
$this->description = Utils::prepareHtmlString($details['description']);
}
if (isset($details['messages'])) {
foreach ($details['messages'] as $message) {
$this->messages[] = ['message' => $message['message'],
'type' => Utils::prepareHtmlString($message['type'])];
}
}
if (isset($details["display_as_sequence_diagram"])) {
$this->display_as_sequence_diagram = $details["display_as_sequence_diagram"];
}
else {
$this->display_as_sequence_diagram = false;
}
$actual_file = $expected_file = $difference_file = $image_difference = "";
if (isset($details["actual_file"])) {
$this->public = (isset($details["results_public"]) && $details["results_public"]);
$path = ($this->public ? $results_public_path : $results_path) . "/details/" . $details["actual_file"];
if (file_exists($path)) {
$actual_file = $path;
}
}
if (isset($details["expected_file"])) {
if (substr($details["expected_file"], 0, 11) == "test_output") {
if (file_exists($course_path . "/" . $details["expected_file"])) {
$expected_file = $course_path . "/" . $details["expected_file"];
}
else {
$this->core->addErrorMessage("Expected file not found.");
}
}
elseif (substr($details["expected_file"], 0, 16) == "generated_output") {
$result_path_array = array_reverse(explode("/", $results_path));
$path_array = explode("/", $details["expected_file"]);
$inserted_array = [$result_path_array[2],"random_output"];
array_splice($path_array, 1, 0, $inserted_array);
if (file_exists($course_path . "/" . implode('/', $path_array))) {
$expected_file = $course_path . "/" . implode('/', $path_array);
}
else {
$expected_file = $course_path . "/" . implode('/', $path_array);
$this->core->addErrorMessage($expected_file);
}
}
elseif (substr($details["expected_file"], 0, 13) == "random_output") {
if (file_exists($results_path . "/" . $details["expected_file"])) {
$expected_file = $results_path . "/" . $details["expected_file"];
}
else {
$this->core->addErrorMessage("Expected file not found.");
}
// Try to find the file in the details directory. Do not print an error,
// as the file is likely student generated.
}
else {
if (file_exists($results_path . "/details/" . $details["expected_file"])) {
$expected_file = $results_path . "/details/" . $details["expected_file"];
}
}
}
if (isset($details["difference_file"]) && file_exists($results_path . "/details/" . $details["difference_file"])) {
$difference_file = $results_path . "/details/" . $details["difference_file"];
}
if (
isset($details["image_difference_file"])
&& file_exists($results_path . "/details/" . $details["image_difference_file"])
) {
$this->index = $idx;
$image_difference = $results_path . "/details/" . $details["image_difference_file"];
}
$this->diff_viewer = new DiffViewer($actual_file, $expected_file, $difference_file, $image_difference, $this->index);
}
}
| {
"pile_set_name": "Github"
} |
// Copyright 2013 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 ssa
// This file implements the BUILD phase of SSA construction.
//
// SSA construction has two phases, CREATE and BUILD. In the CREATE phase
// (create.go), all packages are constructed and type-checked and
// definitions of all package members are created, method-sets are
// computed, and wrapper methods are synthesized.
// ssa.Packages are created in arbitrary order.
//
// In the BUILD phase (builder.go), the builder traverses the AST of
// each Go source function and generates SSA instructions for the
// function body. Initializer expressions for package-level variables
// are emitted to the package's init() function in the order specified
// by go/types.Info.InitOrder, then code for each function in the
// package is generated in lexical order.
// The BUILD phases for distinct packages are independent and are
// executed in parallel.
//
// TODO(adonovan): indeed, building functions is now embarrassingly parallel.
// Audit for concurrency then benchmark using more goroutines.
//
// The builder's and Program's indices (maps) are populated and
// mutated during the CREATE phase, but during the BUILD phase they
// remain constant. The sole exception is Prog.methodSets and its
// related maps, which are protected by a dedicated mutex.
import (
"fmt"
"go/ast"
"go/constant"
"go/token"
"go/types"
"os"
"sync"
)
type opaqueType struct {
types.Type
name string
}
func (t *opaqueType) String() string { return t.name }
var (
varOk = newVar("ok", tBool)
varIndex = newVar("index", tInt)
// Type constants.
tBool = types.Typ[types.Bool]
tByte = types.Typ[types.Byte]
tInt = types.Typ[types.Int]
tInvalid = types.Typ[types.Invalid]
tString = types.Typ[types.String]
tUntypedNil = types.Typ[types.UntypedNil]
tRangeIter = &opaqueType{nil, "iter"} // the type of all "range" iterators
tEface = types.NewInterfaceType(nil, nil).Complete()
// SSA Value constants.
vZero = intConst(0)
vOne = intConst(1)
vTrue = NewConst(constant.MakeBool(true), tBool)
)
// builder holds state associated with the package currently being built.
// Its methods contain all the logic for AST-to-SSA conversion.
type builder struct{}
// cond emits to fn code to evaluate boolean condition e and jump
// to t or f depending on its value, performing various simplifications.
//
// Postcondition: fn.currentBlock is nil.
//
func (b *builder) cond(fn *Function, e ast.Expr, t, f *BasicBlock) {
switch e := e.(type) {
case *ast.ParenExpr:
b.cond(fn, e.X, t, f)
return
case *ast.BinaryExpr:
switch e.Op {
case token.LAND:
ltrue := fn.newBasicBlock("cond.true")
b.cond(fn, e.X, ltrue, f)
fn.currentBlock = ltrue
b.cond(fn, e.Y, t, f)
return
case token.LOR:
lfalse := fn.newBasicBlock("cond.false")
b.cond(fn, e.X, t, lfalse)
fn.currentBlock = lfalse
b.cond(fn, e.Y, t, f)
return
}
case *ast.UnaryExpr:
if e.Op == token.NOT {
b.cond(fn, e.X, f, t)
return
}
}
// A traditional compiler would simplify "if false" (etc) here
// but we do not, for better fidelity to the source code.
//
// The value of a constant condition may be platform-specific,
// and may cause blocks that are reachable in some configuration
// to be hidden from subsequent analyses such as bug-finding tools.
emitIf(fn, b.expr(fn, e), t, f)
}
// logicalBinop emits code to fn to evaluate e, a &&- or
// ||-expression whose reified boolean value is wanted.
// The value is returned.
//
func (b *builder) logicalBinop(fn *Function, e *ast.BinaryExpr) Value {
rhs := fn.newBasicBlock("binop.rhs")
done := fn.newBasicBlock("binop.done")
// T(e) = T(e.X) = T(e.Y) after untyped constants have been
// eliminated.
// TODO(adonovan): not true; MyBool==MyBool yields UntypedBool.
t := fn.Pkg.typeOf(e)
var short Value // value of the short-circuit path
switch e.Op {
case token.LAND:
b.cond(fn, e.X, rhs, done)
short = NewConst(constant.MakeBool(false), t)
case token.LOR:
b.cond(fn, e.X, done, rhs)
short = NewConst(constant.MakeBool(true), t)
}
// Is rhs unreachable?
if rhs.Preds == nil {
// Simplify false&&y to false, true||y to true.
fn.currentBlock = done
return short
}
// Is done unreachable?
if done.Preds == nil {
// Simplify true&&y (or false||y) to y.
fn.currentBlock = rhs
return b.expr(fn, e.Y)
}
// All edges from e.X to done carry the short-circuit value.
var edges []Value
for range done.Preds {
edges = append(edges, short)
}
// The edge from e.Y to done carries the value of e.Y.
fn.currentBlock = rhs
edges = append(edges, b.expr(fn, e.Y))
emitJump(fn, done)
fn.currentBlock = done
phi := &Phi{Edges: edges, Comment: e.Op.String()}
phi.pos = e.OpPos
phi.typ = t
return done.emit(phi)
}
// exprN lowers a multi-result expression e to SSA form, emitting code
// to fn and returning a single Value whose type is a *types.Tuple.
// The caller must access the components via Extract.
//
// Multi-result expressions include CallExprs in a multi-value
// assignment or return statement, and "value,ok" uses of
// TypeAssertExpr, IndexExpr (when X is a map), and UnaryExpr (when Op
// is token.ARROW).
//
func (b *builder) exprN(fn *Function, e ast.Expr) Value {
typ := fn.Pkg.typeOf(e).(*types.Tuple)
switch e := e.(type) {
case *ast.ParenExpr:
return b.exprN(fn, e.X)
case *ast.CallExpr:
// Currently, no built-in function nor type conversion
// has multiple results, so we can avoid some of the
// cases for single-valued CallExpr.
var c Call
b.setCall(fn, e, &c.Call)
c.typ = typ
return fn.emit(&c)
case *ast.IndexExpr:
mapt := fn.Pkg.typeOf(e.X).Underlying().(*types.Map)
lookup := &Lookup{
X: b.expr(fn, e.X),
Index: emitConv(fn, b.expr(fn, e.Index), mapt.Key()),
CommaOk: true,
}
lookup.setType(typ)
lookup.setPos(e.Lbrack)
return fn.emit(lookup)
case *ast.TypeAssertExpr:
return emitTypeTest(fn, b.expr(fn, e.X), typ.At(0).Type(), e.Lparen)
case *ast.UnaryExpr: // must be receive <-
unop := &UnOp{
Op: token.ARROW,
X: b.expr(fn, e.X),
CommaOk: true,
}
unop.setType(typ)
unop.setPos(e.OpPos)
return fn.emit(unop)
}
panic(fmt.Sprintf("exprN(%T) in %s", e, fn))
}
// builtin emits to fn SSA instructions to implement a call to the
// built-in function obj with the specified arguments
// and return type. It returns the value defined by the result.
//
// The result is nil if no special handling was required; in this case
// the caller should treat this like an ordinary library function
// call.
//
func (b *builder) builtin(fn *Function, obj *types.Builtin, args []ast.Expr, typ types.Type, pos token.Pos) Value {
switch obj.Name() {
case "make":
switch typ.Underlying().(type) {
case *types.Slice:
n := b.expr(fn, args[1])
m := n
if len(args) == 3 {
m = b.expr(fn, args[2])
}
if m, ok := m.(*Const); ok {
// treat make([]T, n, m) as new([m]T)[:n]
cap := m.Int64()
at := types.NewArray(typ.Underlying().(*types.Slice).Elem(), cap)
alloc := emitNew(fn, at, pos)
alloc.Comment = "makeslice"
v := &Slice{
X: alloc,
High: n,
}
v.setPos(pos)
v.setType(typ)
return fn.emit(v)
}
v := &MakeSlice{
Len: n,
Cap: m,
}
v.setPos(pos)
v.setType(typ)
return fn.emit(v)
case *types.Map:
var res Value
if len(args) == 2 {
res = b.expr(fn, args[1])
}
v := &MakeMap{Reserve: res}
v.setPos(pos)
v.setType(typ)
return fn.emit(v)
case *types.Chan:
var sz Value = vZero
if len(args) == 2 {
sz = b.expr(fn, args[1])
}
v := &MakeChan{Size: sz}
v.setPos(pos)
v.setType(typ)
return fn.emit(v)
}
case "new":
alloc := emitNew(fn, deref(typ), pos)
alloc.Comment = "new"
return alloc
case "len", "cap":
// Special case: len or cap of an array or *array is
// based on the type, not the value which may be nil.
// We must still evaluate the value, though. (If it
// was side-effect free, the whole call would have
// been constant-folded.)
t := deref(fn.Pkg.typeOf(args[0])).Underlying()
if at, ok := t.(*types.Array); ok {
b.expr(fn, args[0]) // for effects only
return intConst(at.Len())
}
// Otherwise treat as normal.
case "panic":
fn.emit(&Panic{
X: emitConv(fn, b.expr(fn, args[0]), tEface),
pos: pos,
})
fn.currentBlock = fn.newBasicBlock("unreachable")
return vTrue // any non-nil Value will do
}
return nil // treat all others as a regular function call
}
// addr lowers a single-result addressable expression e to SSA form,
// emitting code to fn and returning the location (an lvalue) defined
// by the expression.
//
// If escaping is true, addr marks the base variable of the
// addressable expression e as being a potentially escaping pointer
// value. For example, in this code:
//
// a := A{
// b: [1]B{B{c: 1}}
// }
// return &a.b[0].c
//
// the application of & causes a.b[0].c to have its address taken,
// which means that ultimately the local variable a must be
// heap-allocated. This is a simple but very conservative escape
// analysis.
//
// Operations forming potentially escaping pointers include:
// - &x, including when implicit in method call or composite literals.
// - a[:] iff a is an array (not *array)
// - references to variables in lexically enclosing functions.
//
func (b *builder) addr(fn *Function, e ast.Expr, escaping bool) lvalue {
switch e := e.(type) {
case *ast.Ident:
if isBlankIdent(e) {
return blank{}
}
obj := fn.Pkg.objectOf(e)
v := fn.Prog.packageLevelValue(obj) // var (address)
if v == nil {
v = fn.lookup(obj, escaping)
}
return &address{addr: v, pos: e.Pos(), expr: e}
case *ast.CompositeLit:
t := deref(fn.Pkg.typeOf(e))
var v *Alloc
if escaping {
v = emitNew(fn, t, e.Lbrace)
} else {
v = fn.addLocal(t, e.Lbrace)
}
v.Comment = "complit"
var sb storebuf
b.compLit(fn, v, e, true, &sb)
sb.emit(fn)
return &address{addr: v, pos: e.Lbrace, expr: e}
case *ast.ParenExpr:
return b.addr(fn, e.X, escaping)
case *ast.SelectorExpr:
sel, ok := fn.Pkg.info.Selections[e]
if !ok {
// qualified identifier
return b.addr(fn, e.Sel, escaping)
}
if sel.Kind() != types.FieldVal {
panic(sel)
}
wantAddr := true
v := b.receiver(fn, e.X, wantAddr, escaping, sel)
last := len(sel.Index()) - 1
return &address{
addr: emitFieldSelection(fn, v, sel.Index()[last], true, e.Sel),
pos: e.Sel.Pos(),
expr: e.Sel,
}
case *ast.IndexExpr:
var x Value
var et types.Type
switch t := fn.Pkg.typeOf(e.X).Underlying().(type) {
case *types.Array:
x = b.addr(fn, e.X, escaping).address(fn)
et = types.NewPointer(t.Elem())
case *types.Pointer: // *array
x = b.expr(fn, e.X)
et = types.NewPointer(t.Elem().Underlying().(*types.Array).Elem())
case *types.Slice:
x = b.expr(fn, e.X)
et = types.NewPointer(t.Elem())
case *types.Map:
return &element{
m: b.expr(fn, e.X),
k: emitConv(fn, b.expr(fn, e.Index), t.Key()),
t: t.Elem(),
pos: e.Lbrack,
}
default:
panic("unexpected container type in IndexExpr: " + t.String())
}
v := &IndexAddr{
X: x,
Index: emitConv(fn, b.expr(fn, e.Index), tInt),
}
v.setPos(e.Lbrack)
v.setType(et)
return &address{addr: fn.emit(v), pos: e.Lbrack, expr: e}
case *ast.StarExpr:
return &address{addr: b.expr(fn, e.X), pos: e.Star, expr: e}
}
panic(fmt.Sprintf("unexpected address expression: %T", e))
}
type store struct {
lhs lvalue
rhs Value
}
type storebuf struct{ stores []store }
func (sb *storebuf) store(lhs lvalue, rhs Value) {
sb.stores = append(sb.stores, store{lhs, rhs})
}
func (sb *storebuf) emit(fn *Function) {
for _, s := range sb.stores {
s.lhs.store(fn, s.rhs)
}
}
// assign emits to fn code to initialize the lvalue loc with the value
// of expression e. If isZero is true, assign assumes that loc holds
// the zero value for its type.
//
// This is equivalent to loc.store(fn, b.expr(fn, e)), but may generate
// better code in some cases, e.g., for composite literals in an
// addressable location.
//
// If sb is not nil, assign generates code to evaluate expression e, but
// not to update loc. Instead, the necessary stores are appended to the
// storebuf sb so that they can be executed later. This allows correct
// in-place update of existing variables when the RHS is a composite
// literal that may reference parts of the LHS.
//
func (b *builder) assign(fn *Function, loc lvalue, e ast.Expr, isZero bool, sb *storebuf) {
// Can we initialize it in place?
if e, ok := unparen(e).(*ast.CompositeLit); ok {
// A CompositeLit never evaluates to a pointer,
// so if the type of the location is a pointer,
// an &-operation is implied.
if _, ok := loc.(blank); !ok { // avoid calling blank.typ()
if isPointer(loc.typ()) {
ptr := b.addr(fn, e, true).address(fn)
// copy address
if sb != nil {
sb.store(loc, ptr)
} else {
loc.store(fn, ptr)
}
return
}
}
if _, ok := loc.(*address); ok {
if isInterface(loc.typ()) {
// e.g. var x interface{} = T{...}
// Can't in-place initialize an interface value.
// Fall back to copying.
} else {
// x = T{...} or x := T{...}
addr := loc.address(fn)
if sb != nil {
b.compLit(fn, addr, e, isZero, sb)
} else {
var sb storebuf
b.compLit(fn, addr, e, isZero, &sb)
sb.emit(fn)
}
// Subtle: emit debug ref for aggregate types only;
// slice and map are handled by store ops in compLit.
switch loc.typ().Underlying().(type) {
case *types.Struct, *types.Array:
emitDebugRef(fn, e, addr, true)
}
return
}
}
}
// simple case: just copy
rhs := b.expr(fn, e)
if sb != nil {
sb.store(loc, rhs)
} else {
loc.store(fn, rhs)
}
}
// expr lowers a single-result expression e to SSA form, emitting code
// to fn and returning the Value defined by the expression.
//
func (b *builder) expr(fn *Function, e ast.Expr) Value {
e = unparen(e)
tv := fn.Pkg.info.Types[e]
// Is expression a constant?
if tv.Value != nil {
return NewConst(tv.Value, tv.Type)
}
var v Value
if tv.Addressable() {
// Prefer pointer arithmetic ({Index,Field}Addr) followed
// by Load over subelement extraction (e.g. Index, Field),
// to avoid large copies.
v = b.addr(fn, e, false).load(fn)
} else {
v = b.expr0(fn, e, tv)
}
if fn.debugInfo() {
emitDebugRef(fn, e, v, false)
}
return v
}
func (b *builder) expr0(fn *Function, e ast.Expr, tv types.TypeAndValue) Value {
switch e := e.(type) {
case *ast.BasicLit:
panic("non-constant BasicLit") // unreachable
case *ast.FuncLit:
fn2 := &Function{
name: fmt.Sprintf("%s$%d", fn.Name(), 1+len(fn.AnonFuncs)),
Signature: fn.Pkg.typeOf(e.Type).Underlying().(*types.Signature),
pos: e.Type.Func,
parent: fn,
Pkg: fn.Pkg,
Prog: fn.Prog,
syntax: e,
}
fn.AnonFuncs = append(fn.AnonFuncs, fn2)
b.buildFunction(fn2)
if fn2.FreeVars == nil {
return fn2
}
v := &MakeClosure{Fn: fn2}
v.setType(tv.Type)
for _, fv := range fn2.FreeVars {
v.Bindings = append(v.Bindings, fv.outer)
fv.outer = nil
}
return fn.emit(v)
case *ast.TypeAssertExpr: // single-result form only
return emitTypeAssert(fn, b.expr(fn, e.X), tv.Type, e.Lparen)
case *ast.CallExpr:
if fn.Pkg.info.Types[e.Fun].IsType() {
// Explicit type conversion, e.g. string(x) or big.Int(x)
x := b.expr(fn, e.Args[0])
y := emitConv(fn, x, tv.Type)
if y != x {
switch y := y.(type) {
case *Convert:
y.pos = e.Lparen
case *ChangeType:
y.pos = e.Lparen
case *MakeInterface:
y.pos = e.Lparen
}
}
return y
}
// Call to "intrinsic" built-ins, e.g. new, make, panic.
if id, ok := unparen(e.Fun).(*ast.Ident); ok {
if obj, ok := fn.Pkg.info.Uses[id].(*types.Builtin); ok {
if v := b.builtin(fn, obj, e.Args, tv.Type, e.Lparen); v != nil {
return v
}
}
}
// Regular function call.
var v Call
b.setCall(fn, e, &v.Call)
v.setType(tv.Type)
return fn.emit(&v)
case *ast.UnaryExpr:
switch e.Op {
case token.AND: // &X --- potentially escaping.
addr := b.addr(fn, e.X, true)
if _, ok := unparen(e.X).(*ast.StarExpr); ok {
// &*p must panic if p is nil (http://golang.org/s/go12nil).
// For simplicity, we'll just (suboptimally) rely
// on the side effects of a load.
// TODO(adonovan): emit dedicated nilcheck.
addr.load(fn)
}
return addr.address(fn)
case token.ADD:
return b.expr(fn, e.X)
case token.NOT, token.ARROW, token.SUB, token.XOR: // ! <- - ^
v := &UnOp{
Op: e.Op,
X: b.expr(fn, e.X),
}
v.setPos(e.OpPos)
v.setType(tv.Type)
return fn.emit(v)
default:
panic(e.Op)
}
case *ast.BinaryExpr:
switch e.Op {
case token.LAND, token.LOR:
return b.logicalBinop(fn, e)
case token.SHL, token.SHR:
fallthrough
case token.ADD, token.SUB, token.MUL, token.QUO, token.REM, token.AND, token.OR, token.XOR, token.AND_NOT:
return emitArith(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), tv.Type, e.OpPos)
case token.EQL, token.NEQ, token.GTR, token.LSS, token.LEQ, token.GEQ:
cmp := emitCompare(fn, e.Op, b.expr(fn, e.X), b.expr(fn, e.Y), e.OpPos)
// The type of x==y may be UntypedBool.
return emitConv(fn, cmp, DefaultType(tv.Type))
default:
panic("illegal op in BinaryExpr: " + e.Op.String())
}
case *ast.SliceExpr:
var low, high, max Value
var x Value
switch fn.Pkg.typeOf(e.X).Underlying().(type) {
case *types.Array:
// Potentially escaping.
x = b.addr(fn, e.X, true).address(fn)
case *types.Basic, *types.Slice, *types.Pointer: // *array
x = b.expr(fn, e.X)
default:
panic("unreachable")
}
if e.High != nil {
high = b.expr(fn, e.High)
}
if e.Low != nil {
low = b.expr(fn, e.Low)
}
if e.Slice3 {
max = b.expr(fn, e.Max)
}
v := &Slice{
X: x,
Low: low,
High: high,
Max: max,
}
v.setPos(e.Lbrack)
v.setType(tv.Type)
return fn.emit(v)
case *ast.Ident:
obj := fn.Pkg.info.Uses[e]
// Universal built-in or nil?
switch obj := obj.(type) {
case *types.Builtin:
return &Builtin{name: obj.Name(), sig: tv.Type.(*types.Signature)}
case *types.Nil:
return nilConst(tv.Type)
}
// Package-level func or var?
if v := fn.Prog.packageLevelValue(obj); v != nil {
if _, ok := obj.(*types.Var); ok {
return emitLoad(fn, v) // var (address)
}
return v // (func)
}
// Local var.
return emitLoad(fn, fn.lookup(obj, false)) // var (address)
case *ast.SelectorExpr:
sel, ok := fn.Pkg.info.Selections[e]
if !ok {
// qualified identifier
return b.expr(fn, e.Sel)
}
switch sel.Kind() {
case types.MethodExpr:
// (*T).f or T.f, the method f from the method-set of type T.
// The result is a "thunk".
return emitConv(fn, makeThunk(fn.Prog, sel), tv.Type)
case types.MethodVal:
// e.f where e is an expression and f is a method.
// The result is a "bound".
obj := sel.Obj().(*types.Func)
rt := recvType(obj)
wantAddr := isPointer(rt)
escaping := true
v := b.receiver(fn, e.X, wantAddr, escaping, sel)
if isInterface(rt) {
// If v has interface type I,
// we must emit a check that v is non-nil.
// We use: typeassert v.(I).
emitTypeAssert(fn, v, rt, token.NoPos)
}
c := &MakeClosure{
Fn: makeBound(fn.Prog, obj),
Bindings: []Value{v},
}
c.setPos(e.Sel.Pos())
c.setType(tv.Type)
return fn.emit(c)
case types.FieldVal:
indices := sel.Index()
last := len(indices) - 1
v := b.expr(fn, e.X)
v = emitImplicitSelections(fn, v, indices[:last])
v = emitFieldSelection(fn, v, indices[last], false, e.Sel)
return v
}
panic("unexpected expression-relative selector")
case *ast.IndexExpr:
switch t := fn.Pkg.typeOf(e.X).Underlying().(type) {
case *types.Array:
// Non-addressable array (in a register).
v := &Index{
X: b.expr(fn, e.X),
Index: emitConv(fn, b.expr(fn, e.Index), tInt),
}
v.setPos(e.Lbrack)
v.setType(t.Elem())
return fn.emit(v)
case *types.Map:
// Maps are not addressable.
mapt := fn.Pkg.typeOf(e.X).Underlying().(*types.Map)
v := &Lookup{
X: b.expr(fn, e.X),
Index: emitConv(fn, b.expr(fn, e.Index), mapt.Key()),
}
v.setPos(e.Lbrack)
v.setType(mapt.Elem())
return fn.emit(v)
case *types.Basic: // => string
// Strings are not addressable.
v := &Lookup{
X: b.expr(fn, e.X),
Index: b.expr(fn, e.Index),
}
v.setPos(e.Lbrack)
v.setType(tByte)
return fn.emit(v)
case *types.Slice, *types.Pointer: // *array
// Addressable slice/array; use IndexAddr and Load.
return b.addr(fn, e, false).load(fn)
default:
panic("unexpected container type in IndexExpr: " + t.String())
}
case *ast.CompositeLit, *ast.StarExpr:
// Addressable types (lvalues)
return b.addr(fn, e, false).load(fn)
}
panic(fmt.Sprintf("unexpected expr: %T", e))
}
// stmtList emits to fn code for all statements in list.
func (b *builder) stmtList(fn *Function, list []ast.Stmt) {
for _, s := range list {
b.stmt(fn, s)
}
}
// receiver emits to fn code for expression e in the "receiver"
// position of selection e.f (where f may be a field or a method) and
// returns the effective receiver after applying the implicit field
// selections of sel.
//
// wantAddr requests that the result is an an address. If
// !sel.Indirect(), this may require that e be built in addr() mode; it
// must thus be addressable.
//
// escaping is defined as per builder.addr().
//
func (b *builder) receiver(fn *Function, e ast.Expr, wantAddr, escaping bool, sel *types.Selection) Value {
var v Value
if wantAddr && !sel.Indirect() && !isPointer(fn.Pkg.typeOf(e)) {
v = b.addr(fn, e, escaping).address(fn)
} else {
v = b.expr(fn, e)
}
last := len(sel.Index()) - 1
v = emitImplicitSelections(fn, v, sel.Index()[:last])
if !wantAddr && isPointer(v.Type()) {
v = emitLoad(fn, v)
}
return v
}
// setCallFunc populates the function parts of a CallCommon structure
// (Func, Method, Recv, Args[0]) based on the kind of invocation
// occurring in e.
//
func (b *builder) setCallFunc(fn *Function, e *ast.CallExpr, c *CallCommon) {
c.pos = e.Lparen
// Is this a method call?
if selector, ok := unparen(e.Fun).(*ast.SelectorExpr); ok {
sel, ok := fn.Pkg.info.Selections[selector]
if ok && sel.Kind() == types.MethodVal {
obj := sel.Obj().(*types.Func)
recv := recvType(obj)
wantAddr := isPointer(recv)
escaping := true
v := b.receiver(fn, selector.X, wantAddr, escaping, sel)
if isInterface(recv) {
// Invoke-mode call.
c.Value = v
c.Method = obj
} else {
// "Call"-mode call.
c.Value = fn.Prog.declaredFunc(obj)
c.Args = append(c.Args, v)
}
return
}
// sel.Kind()==MethodExpr indicates T.f() or (*T).f():
// a statically dispatched call to the method f in the
// method-set of T or *T. T may be an interface.
//
// e.Fun would evaluate to a concrete method, interface
// wrapper function, or promotion wrapper.
//
// For now, we evaluate it in the usual way.
//
// TODO(adonovan): opt: inline expr() here, to make the
// call static and to avoid generation of wrappers.
// It's somewhat tricky as it may consume the first
// actual parameter if the call is "invoke" mode.
//
// Examples:
// type T struct{}; func (T) f() {} // "call" mode
// type T interface { f() } // "invoke" mode
//
// type S struct{ T }
//
// var s S
// S.f(s)
// (*S).f(&s)
//
// Suggested approach:
// - consume the first actual parameter expression
// and build it with b.expr().
// - apply implicit field selections.
// - use MethodVal logic to populate fields of c.
}
// Evaluate the function operand in the usual way.
c.Value = b.expr(fn, e.Fun)
}
// emitCallArgs emits to f code for the actual parameters of call e to
// a (possibly built-in) function of effective type sig.
// The argument values are appended to args, which is then returned.
//
func (b *builder) emitCallArgs(fn *Function, sig *types.Signature, e *ast.CallExpr, args []Value) []Value {
// f(x, y, z...): pass slice z straight through.
if e.Ellipsis != 0 {
for i, arg := range e.Args {
v := emitConv(fn, b.expr(fn, arg), sig.Params().At(i).Type())
args = append(args, v)
}
return args
}
offset := len(args) // 1 if call has receiver, 0 otherwise
// Evaluate actual parameter expressions.
//
// If this is a chained call of the form f(g()) where g has
// multiple return values (MRV), they are flattened out into
// args; a suffix of them may end up in a varargs slice.
for _, arg := range e.Args {
v := b.expr(fn, arg)
if ttuple, ok := v.Type().(*types.Tuple); ok { // MRV chain
for i, n := 0, ttuple.Len(); i < n; i++ {
args = append(args, emitExtract(fn, v, i))
}
} else {
args = append(args, v)
}
}
// Actual->formal assignability conversions for normal parameters.
np := sig.Params().Len() // number of normal parameters
if sig.Variadic() {
np--
}
for i := 0; i < np; i++ {
args[offset+i] = emitConv(fn, args[offset+i], sig.Params().At(i).Type())
}
// Actual->formal assignability conversions for variadic parameter,
// and construction of slice.
if sig.Variadic() {
varargs := args[offset+np:]
st := sig.Params().At(np).Type().(*types.Slice)
vt := st.Elem()
if len(varargs) == 0 {
args = append(args, nilConst(st))
} else {
// Replace a suffix of args with a slice containing it.
at := types.NewArray(vt, int64(len(varargs)))
a := emitNew(fn, at, token.NoPos)
a.setPos(e.Rparen)
a.Comment = "varargs"
for i, arg := range varargs {
iaddr := &IndexAddr{
X: a,
Index: intConst(int64(i)),
}
iaddr.setType(types.NewPointer(vt))
fn.emit(iaddr)
emitStore(fn, iaddr, arg, arg.Pos())
}
s := &Slice{X: a}
s.setType(st)
args[offset+np] = fn.emit(s)
args = args[:offset+np+1]
}
}
return args
}
// setCall emits to fn code to evaluate all the parameters of a function
// call e, and populates *c with those values.
//
func (b *builder) setCall(fn *Function, e *ast.CallExpr, c *CallCommon) {
// First deal with the f(...) part and optional receiver.
b.setCallFunc(fn, e, c)
// Then append the other actual parameters.
sig, _ := fn.Pkg.typeOf(e.Fun).Underlying().(*types.Signature)
if sig == nil {
panic(fmt.Sprintf("no signature for call of %s", e.Fun))
}
c.Args = b.emitCallArgs(fn, sig, e, c.Args)
}
// assignOp emits to fn code to perform loc <op>= val.
func (b *builder) assignOp(fn *Function, loc lvalue, val Value, op token.Token, pos token.Pos) {
oldv := loc.load(fn)
loc.store(fn, emitArith(fn, op, oldv, emitConv(fn, val, oldv.Type()), loc.typ(), pos))
}
// localValueSpec emits to fn code to define all of the vars in the
// function-local ValueSpec, spec.
//
func (b *builder) localValueSpec(fn *Function, spec *ast.ValueSpec) {
switch {
case len(spec.Values) == len(spec.Names):
// e.g. var x, y = 0, 1
// 1:1 assignment
for i, id := range spec.Names {
if !isBlankIdent(id) {
fn.addLocalForIdent(id)
}
lval := b.addr(fn, id, false) // non-escaping
b.assign(fn, lval, spec.Values[i], true, nil)
}
case len(spec.Values) == 0:
// e.g. var x, y int
// Locals are implicitly zero-initialized.
for _, id := range spec.Names {
if !isBlankIdent(id) {
lhs := fn.addLocalForIdent(id)
if fn.debugInfo() {
emitDebugRef(fn, id, lhs, true)
}
}
}
default:
// e.g. var x, y = pos()
tuple := b.exprN(fn, spec.Values[0])
for i, id := range spec.Names {
if !isBlankIdent(id) {
fn.addLocalForIdent(id)
lhs := b.addr(fn, id, false) // non-escaping
lhs.store(fn, emitExtract(fn, tuple, i))
}
}
}
}
// assignStmt emits code to fn for a parallel assignment of rhss to lhss.
// isDef is true if this is a short variable declaration (:=).
//
// Note the similarity with localValueSpec.
//
func (b *builder) assignStmt(fn *Function, lhss, rhss []ast.Expr, isDef bool) {
// Side effects of all LHSs and RHSs must occur in left-to-right order.
lvals := make([]lvalue, len(lhss))
isZero := make([]bool, len(lhss))
for i, lhs := range lhss {
var lval lvalue = blank{}
if !isBlankIdent(lhs) {
if isDef {
if obj := fn.Pkg.info.Defs[lhs.(*ast.Ident)]; obj != nil {
fn.addNamedLocal(obj)
isZero[i] = true
}
}
lval = b.addr(fn, lhs, false) // non-escaping
}
lvals[i] = lval
}
if len(lhss) == len(rhss) {
// Simple assignment: x = f() (!isDef)
// Parallel assignment: x, y = f(), g() (!isDef)
// or short var decl: x, y := f(), g() (isDef)
//
// In all cases, the RHSs may refer to the LHSs,
// so we need a storebuf.
var sb storebuf
for i := range rhss {
b.assign(fn, lvals[i], rhss[i], isZero[i], &sb)
}
sb.emit(fn)
} else {
// e.g. x, y = pos()
tuple := b.exprN(fn, rhss[0])
emitDebugRef(fn, rhss[0], tuple, false)
for i, lval := range lvals {
lval.store(fn, emitExtract(fn, tuple, i))
}
}
}
// arrayLen returns the length of the array whose composite literal elements are elts.
func (b *builder) arrayLen(fn *Function, elts []ast.Expr) int64 {
var max int64 = -1
var i int64 = -1
for _, e := range elts {
if kv, ok := e.(*ast.KeyValueExpr); ok {
i = b.expr(fn, kv.Key).(*Const).Int64()
} else {
i++
}
if i > max {
max = i
}
}
return max + 1
}
// compLit emits to fn code to initialize a composite literal e at
// address addr with type typ.
//
// Nested composite literals are recursively initialized in place
// where possible. If isZero is true, compLit assumes that addr
// holds the zero value for typ.
//
// Because the elements of a composite literal may refer to the
// variables being updated, as in the second line below,
// x := T{a: 1}
// x = T{a: x.a}
// all the reads must occur before all the writes. Thus all stores to
// loc are emitted to the storebuf sb for later execution.
//
// A CompositeLit may have pointer type only in the recursive (nested)
// case when the type name is implicit. e.g. in []*T{{}}, the inner
// literal has type *T behaves like &T{}.
// In that case, addr must hold a T, not a *T.
//
func (b *builder) compLit(fn *Function, addr Value, e *ast.CompositeLit, isZero bool, sb *storebuf) {
typ := deref(fn.Pkg.typeOf(e))
switch t := typ.Underlying().(type) {
case *types.Struct:
if !isZero && len(e.Elts) != t.NumFields() {
// memclear
sb.store(&address{addr, e.Lbrace, nil},
zeroValue(fn, deref(addr.Type())))
isZero = true
}
for i, e := range e.Elts {
fieldIndex := i
pos := e.Pos()
if kv, ok := e.(*ast.KeyValueExpr); ok {
fname := kv.Key.(*ast.Ident).Name
for i, n := 0, t.NumFields(); i < n; i++ {
sf := t.Field(i)
if sf.Name() == fname {
fieldIndex = i
pos = kv.Colon
e = kv.Value
break
}
}
}
sf := t.Field(fieldIndex)
faddr := &FieldAddr{
X: addr,
Field: fieldIndex,
}
faddr.setType(types.NewPointer(sf.Type()))
fn.emit(faddr)
b.assign(fn, &address{addr: faddr, pos: pos, expr: e}, e, isZero, sb)
}
case *types.Array, *types.Slice:
var at *types.Array
var array Value
switch t := t.(type) {
case *types.Slice:
at = types.NewArray(t.Elem(), b.arrayLen(fn, e.Elts))
alloc := emitNew(fn, at, e.Lbrace)
alloc.Comment = "slicelit"
array = alloc
case *types.Array:
at = t
array = addr
if !isZero && int64(len(e.Elts)) != at.Len() {
// memclear
sb.store(&address{array, e.Lbrace, nil},
zeroValue(fn, deref(array.Type())))
}
}
var idx *Const
for _, e := range e.Elts {
pos := e.Pos()
if kv, ok := e.(*ast.KeyValueExpr); ok {
idx = b.expr(fn, kv.Key).(*Const)
pos = kv.Colon
e = kv.Value
} else {
var idxval int64
if idx != nil {
idxval = idx.Int64() + 1
}
idx = intConst(idxval)
}
iaddr := &IndexAddr{
X: array,
Index: idx,
}
iaddr.setType(types.NewPointer(at.Elem()))
fn.emit(iaddr)
if t != at { // slice
// backing array is unaliased => storebuf not needed.
b.assign(fn, &address{addr: iaddr, pos: pos, expr: e}, e, true, nil)
} else {
b.assign(fn, &address{addr: iaddr, pos: pos, expr: e}, e, true, sb)
}
}
if t != at { // slice
s := &Slice{X: array}
s.setPos(e.Lbrace)
s.setType(typ)
sb.store(&address{addr: addr, pos: e.Lbrace, expr: e}, fn.emit(s))
}
case *types.Map:
m := &MakeMap{Reserve: intConst(int64(len(e.Elts)))}
m.setPos(e.Lbrace)
m.setType(typ)
fn.emit(m)
for _, e := range e.Elts {
e := e.(*ast.KeyValueExpr)
// If a key expression in a map literal is itself a
// composite literal, the type may be omitted.
// For example:
// map[*struct{}]bool{{}: true}
// An &-operation may be implied:
// map[*struct{}]bool{&struct{}{}: true}
var key Value
if _, ok := unparen(e.Key).(*ast.CompositeLit); ok && isPointer(t.Key()) {
// A CompositeLit never evaluates to a pointer,
// so if the type of the location is a pointer,
// an &-operation is implied.
key = b.addr(fn, e.Key, true).address(fn)
} else {
key = b.expr(fn, e.Key)
}
loc := element{
m: m,
k: emitConv(fn, key, t.Key()),
t: t.Elem(),
pos: e.Colon,
}
// We call assign() only because it takes care
// of any &-operation required in the recursive
// case, e.g.,
// map[int]*struct{}{0: {}} implies &struct{}{}.
// In-place update is of course impossible,
// and no storebuf is needed.
b.assign(fn, &loc, e.Value, true, nil)
}
sb.store(&address{addr: addr, pos: e.Lbrace, expr: e}, m)
default:
panic("unexpected CompositeLit type: " + t.String())
}
}
// switchStmt emits to fn code for the switch statement s, optionally
// labelled by label.
//
func (b *builder) switchStmt(fn *Function, s *ast.SwitchStmt, label *lblock) {
// We treat SwitchStmt like a sequential if-else chain.
// Multiway dispatch can be recovered later by ssautil.Switches()
// to those cases that are free of side effects.
if s.Init != nil {
b.stmt(fn, s.Init)
}
var tag Value = vTrue
if s.Tag != nil {
tag = b.expr(fn, s.Tag)
}
done := fn.newBasicBlock("switch.done")
if label != nil {
label._break = done
}
// We pull the default case (if present) down to the end.
// But each fallthrough label must point to the next
// body block in source order, so we preallocate a
// body block (fallthru) for the next case.
// Unfortunately this makes for a confusing block order.
var dfltBody *[]ast.Stmt
var dfltFallthrough *BasicBlock
var fallthru, dfltBlock *BasicBlock
ncases := len(s.Body.List)
for i, clause := range s.Body.List {
body := fallthru
if body == nil {
body = fn.newBasicBlock("switch.body") // first case only
}
// Preallocate body block for the next case.
fallthru = done
if i+1 < ncases {
fallthru = fn.newBasicBlock("switch.body")
}
cc := clause.(*ast.CaseClause)
if cc.List == nil {
// Default case.
dfltBody = &cc.Body
dfltFallthrough = fallthru
dfltBlock = body
continue
}
var nextCond *BasicBlock
for _, cond := range cc.List {
nextCond = fn.newBasicBlock("switch.next")
// TODO(adonovan): opt: when tag==vTrue, we'd
// get better code if we use b.cond(cond)
// instead of BinOp(EQL, tag, b.expr(cond))
// followed by If. Don't forget conversions
// though.
cond := emitCompare(fn, token.EQL, tag, b.expr(fn, cond), cond.Pos())
emitIf(fn, cond, body, nextCond)
fn.currentBlock = nextCond
}
fn.currentBlock = body
fn.targets = &targets{
tail: fn.targets,
_break: done,
_fallthrough: fallthru,
}
b.stmtList(fn, cc.Body)
fn.targets = fn.targets.tail
emitJump(fn, done)
fn.currentBlock = nextCond
}
if dfltBlock != nil {
emitJump(fn, dfltBlock)
fn.currentBlock = dfltBlock
fn.targets = &targets{
tail: fn.targets,
_break: done,
_fallthrough: dfltFallthrough,
}
b.stmtList(fn, *dfltBody)
fn.targets = fn.targets.tail
}
emitJump(fn, done)
fn.currentBlock = done
}
// typeSwitchStmt emits to fn code for the type switch statement s, optionally
// labelled by label.
//
func (b *builder) typeSwitchStmt(fn *Function, s *ast.TypeSwitchStmt, label *lblock) {
// We treat TypeSwitchStmt like a sequential if-else chain.
// Multiway dispatch can be recovered later by ssautil.Switches().
// Typeswitch lowering:
//
// var x X
// switch y := x.(type) {
// case T1, T2: S1 // >1 (y := x)
// case nil: SN // nil (y := x)
// default: SD // 0 types (y := x)
// case T3: S3 // 1 type (y := x.(T3))
// }
//
// ...s.Init...
// x := eval x
// .caseT1:
// t1, ok1 := typeswitch,ok x <T1>
// if ok1 then goto S1 else goto .caseT2
// .caseT2:
// t2, ok2 := typeswitch,ok x <T2>
// if ok2 then goto S1 else goto .caseNil
// .S1:
// y := x
// ...S1...
// goto done
// .caseNil:
// if t2, ok2 := typeswitch,ok x <T2>
// if x == nil then goto SN else goto .caseT3
// .SN:
// y := x
// ...SN...
// goto done
// .caseT3:
// t3, ok3 := typeswitch,ok x <T3>
// if ok3 then goto S3 else goto default
// .S3:
// y := t3
// ...S3...
// goto done
// .default:
// y := x
// ...SD...
// goto done
// .done:
if s.Init != nil {
b.stmt(fn, s.Init)
}
var x Value
switch ass := s.Assign.(type) {
case *ast.ExprStmt: // x.(type)
x = b.expr(fn, unparen(ass.X).(*ast.TypeAssertExpr).X)
case *ast.AssignStmt: // y := x.(type)
x = b.expr(fn, unparen(ass.Rhs[0]).(*ast.TypeAssertExpr).X)
}
done := fn.newBasicBlock("typeswitch.done")
if label != nil {
label._break = done
}
var default_ *ast.CaseClause
for _, clause := range s.Body.List {
cc := clause.(*ast.CaseClause)
if cc.List == nil {
default_ = cc
continue
}
body := fn.newBasicBlock("typeswitch.body")
var next *BasicBlock
var casetype types.Type
var ti Value // ti, ok := typeassert,ok x <Ti>
for _, cond := range cc.List {
next = fn.newBasicBlock("typeswitch.next")
casetype = fn.Pkg.typeOf(cond)
var condv Value
if casetype == tUntypedNil {
condv = emitCompare(fn, token.EQL, x, nilConst(x.Type()), token.NoPos)
ti = x
} else {
yok := emitTypeTest(fn, x, casetype, cc.Case)
ti = emitExtract(fn, yok, 0)
condv = emitExtract(fn, yok, 1)
}
emitIf(fn, condv, body, next)
fn.currentBlock = next
}
if len(cc.List) != 1 {
ti = x
}
fn.currentBlock = body
b.typeCaseBody(fn, cc, ti, done)
fn.currentBlock = next
}
if default_ != nil {
b.typeCaseBody(fn, default_, x, done)
} else {
emitJump(fn, done)
}
fn.currentBlock = done
}
func (b *builder) typeCaseBody(fn *Function, cc *ast.CaseClause, x Value, done *BasicBlock) {
if obj := fn.Pkg.info.Implicits[cc]; obj != nil {
// In a switch y := x.(type), each case clause
// implicitly declares a distinct object y.
// In a single-type case, y has that type.
// In multi-type cases, 'case nil' and default,
// y has the same type as the interface operand.
emitStore(fn, fn.addNamedLocal(obj), x, obj.Pos())
}
fn.targets = &targets{
tail: fn.targets,
_break: done,
}
b.stmtList(fn, cc.Body)
fn.targets = fn.targets.tail
emitJump(fn, done)
}
// selectStmt emits to fn code for the select statement s, optionally
// labelled by label.
//
func (b *builder) selectStmt(fn *Function, s *ast.SelectStmt, label *lblock) {
// A blocking select of a single case degenerates to a
// simple send or receive.
// TODO(adonovan): opt: is this optimization worth its weight?
if len(s.Body.List) == 1 {
clause := s.Body.List[0].(*ast.CommClause)
if clause.Comm != nil {
b.stmt(fn, clause.Comm)
done := fn.newBasicBlock("select.done")
if label != nil {
label._break = done
}
fn.targets = &targets{
tail: fn.targets,
_break: done,
}
b.stmtList(fn, clause.Body)
fn.targets = fn.targets.tail
emitJump(fn, done)
fn.currentBlock = done
return
}
}
// First evaluate all channels in all cases, and find
// the directions of each state.
var states []*SelectState
blocking := true
debugInfo := fn.debugInfo()
for _, clause := range s.Body.List {
var st *SelectState
switch comm := clause.(*ast.CommClause).Comm.(type) {
case nil: // default case
blocking = false
continue
case *ast.SendStmt: // ch<- i
ch := b.expr(fn, comm.Chan)
st = &SelectState{
Dir: types.SendOnly,
Chan: ch,
Send: emitConv(fn, b.expr(fn, comm.Value),
ch.Type().Underlying().(*types.Chan).Elem()),
Pos: comm.Arrow,
}
if debugInfo {
st.DebugNode = comm
}
case *ast.AssignStmt: // x := <-ch
recv := unparen(comm.Rhs[0]).(*ast.UnaryExpr)
st = &SelectState{
Dir: types.RecvOnly,
Chan: b.expr(fn, recv.X),
Pos: recv.OpPos,
}
if debugInfo {
st.DebugNode = recv
}
case *ast.ExprStmt: // <-ch
recv := unparen(comm.X).(*ast.UnaryExpr)
st = &SelectState{
Dir: types.RecvOnly,
Chan: b.expr(fn, recv.X),
Pos: recv.OpPos,
}
if debugInfo {
st.DebugNode = recv
}
}
states = append(states, st)
}
// We dispatch on the (fair) result of Select using a
// sequential if-else chain, in effect:
//
// idx, recvOk, r0...r_n-1 := select(...)
// if idx == 0 { // receive on channel 0 (first receive => r0)
// x, ok := r0, recvOk
// ...state0...
// } else if v == 1 { // send on channel 1
// ...state1...
// } else {
// ...default...
// }
sel := &Select{
States: states,
Blocking: blocking,
}
sel.setPos(s.Select)
var vars []*types.Var
vars = append(vars, varIndex, varOk)
for _, st := range states {
if st.Dir == types.RecvOnly {
tElem := st.Chan.Type().Underlying().(*types.Chan).Elem()
vars = append(vars, anonVar(tElem))
}
}
sel.setType(types.NewTuple(vars...))
fn.emit(sel)
idx := emitExtract(fn, sel, 0)
done := fn.newBasicBlock("select.done")
if label != nil {
label._break = done
}
var defaultBody *[]ast.Stmt
state := 0
r := 2 // index in 'sel' tuple of value; increments if st.Dir==RECV
for _, cc := range s.Body.List {
clause := cc.(*ast.CommClause)
if clause.Comm == nil {
defaultBody = &clause.Body
continue
}
body := fn.newBasicBlock("select.body")
next := fn.newBasicBlock("select.next")
emitIf(fn, emitCompare(fn, token.EQL, idx, intConst(int64(state)), token.NoPos), body, next)
fn.currentBlock = body
fn.targets = &targets{
tail: fn.targets,
_break: done,
}
switch comm := clause.Comm.(type) {
case *ast.ExprStmt: // <-ch
if debugInfo {
v := emitExtract(fn, sel, r)
emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false)
}
r++
case *ast.AssignStmt: // x := <-states[state].Chan
if comm.Tok == token.DEFINE {
fn.addLocalForIdent(comm.Lhs[0].(*ast.Ident))
}
x := b.addr(fn, comm.Lhs[0], false) // non-escaping
v := emitExtract(fn, sel, r)
if debugInfo {
emitDebugRef(fn, states[state].DebugNode.(ast.Expr), v, false)
}
x.store(fn, v)
if len(comm.Lhs) == 2 { // x, ok := ...
if comm.Tok == token.DEFINE {
fn.addLocalForIdent(comm.Lhs[1].(*ast.Ident))
}
ok := b.addr(fn, comm.Lhs[1], false) // non-escaping
ok.store(fn, emitExtract(fn, sel, 1))
}
r++
}
b.stmtList(fn, clause.Body)
fn.targets = fn.targets.tail
emitJump(fn, done)
fn.currentBlock = next
state++
}
if defaultBody != nil {
fn.targets = &targets{
tail: fn.targets,
_break: done,
}
b.stmtList(fn, *defaultBody)
fn.targets = fn.targets.tail
} else {
// A blocking select must match some case.
// (This should really be a runtime.errorString, not a string.)
fn.emit(&Panic{
X: emitConv(fn, stringConst("blocking select matched no case"), tEface),
})
fn.currentBlock = fn.newBasicBlock("unreachable")
}
emitJump(fn, done)
fn.currentBlock = done
}
// forStmt emits to fn code for the for statement s, optionally
// labelled by label.
//
func (b *builder) forStmt(fn *Function, s *ast.ForStmt, label *lblock) {
// ...init...
// jump loop
// loop:
// if cond goto body else done
// body:
// ...body...
// jump post
// post: (target of continue)
// ...post...
// jump loop
// done: (target of break)
if s.Init != nil {
b.stmt(fn, s.Init)
}
body := fn.newBasicBlock("for.body")
done := fn.newBasicBlock("for.done") // target of 'break'
loop := body // target of back-edge
if s.Cond != nil {
loop = fn.newBasicBlock("for.loop")
}
cont := loop // target of 'continue'
if s.Post != nil {
cont = fn.newBasicBlock("for.post")
}
if label != nil {
label._break = done
label._continue = cont
}
emitJump(fn, loop)
fn.currentBlock = loop
if loop != body {
b.cond(fn, s.Cond, body, done)
fn.currentBlock = body
}
fn.targets = &targets{
tail: fn.targets,
_break: done,
_continue: cont,
}
b.stmt(fn, s.Body)
fn.targets = fn.targets.tail
emitJump(fn, cont)
if s.Post != nil {
fn.currentBlock = cont
b.stmt(fn, s.Post)
emitJump(fn, loop) // back-edge
}
fn.currentBlock = done
}
// rangeIndexed emits to fn the header for an integer-indexed loop
// over array, *array or slice value x.
// The v result is defined only if tv is non-nil.
// forPos is the position of the "for" token.
//
func (b *builder) rangeIndexed(fn *Function, x Value, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) {
//
// length = len(x)
// index = -1
// loop: (target of continue)
// index++
// if index < length goto body else done
// body:
// k = index
// v = x[index]
// ...body...
// jump loop
// done: (target of break)
// Determine number of iterations.
var length Value
if arr, ok := deref(x.Type()).Underlying().(*types.Array); ok {
// For array or *array, the number of iterations is
// known statically thanks to the type. We avoid a
// data dependence upon x, permitting later dead-code
// elimination if x is pure, static unrolling, etc.
// Ranging over a nil *array may have >0 iterations.
// We still generate code for x, in case it has effects.
length = intConst(arr.Len())
} else {
// length = len(x).
var c Call
c.Call.Value = makeLen(x.Type())
c.Call.Args = []Value{x}
c.setType(tInt)
length = fn.emit(&c)
}
index := fn.addLocal(tInt, token.NoPos)
emitStore(fn, index, intConst(-1), pos)
loop = fn.newBasicBlock("rangeindex.loop")
emitJump(fn, loop)
fn.currentBlock = loop
incr := &BinOp{
Op: token.ADD,
X: emitLoad(fn, index),
Y: vOne,
}
incr.setType(tInt)
emitStore(fn, index, fn.emit(incr), pos)
body := fn.newBasicBlock("rangeindex.body")
done = fn.newBasicBlock("rangeindex.done")
emitIf(fn, emitCompare(fn, token.LSS, incr, length, token.NoPos), body, done)
fn.currentBlock = body
k = emitLoad(fn, index)
if tv != nil {
switch t := x.Type().Underlying().(type) {
case *types.Array:
instr := &Index{
X: x,
Index: k,
}
instr.setType(t.Elem())
v = fn.emit(instr)
case *types.Pointer: // *array
instr := &IndexAddr{
X: x,
Index: k,
}
instr.setType(types.NewPointer(t.Elem().Underlying().(*types.Array).Elem()))
v = emitLoad(fn, fn.emit(instr))
case *types.Slice:
instr := &IndexAddr{
X: x,
Index: k,
}
instr.setType(types.NewPointer(t.Elem()))
v = emitLoad(fn, fn.emit(instr))
default:
panic("rangeIndexed x:" + t.String())
}
}
return
}
// rangeIter emits to fn the header for a loop using
// Range/Next/Extract to iterate over map or string value x.
// tk and tv are the types of the key/value results k and v, or nil
// if the respective component is not wanted.
//
func (b *builder) rangeIter(fn *Function, x Value, tk, tv types.Type, pos token.Pos) (k, v Value, loop, done *BasicBlock) {
//
// it = range x
// loop: (target of continue)
// okv = next it (ok, key, value)
// ok = extract okv #0
// if ok goto body else done
// body:
// k = extract okv #1
// v = extract okv #2
// ...body...
// jump loop
// done: (target of break)
//
if tk == nil {
tk = tInvalid
}
if tv == nil {
tv = tInvalid
}
rng := &Range{X: x}
rng.setPos(pos)
rng.setType(tRangeIter)
it := fn.emit(rng)
loop = fn.newBasicBlock("rangeiter.loop")
emitJump(fn, loop)
fn.currentBlock = loop
_, isString := x.Type().Underlying().(*types.Basic)
okv := &Next{
Iter: it,
IsString: isString,
}
okv.setType(types.NewTuple(
varOk,
newVar("k", tk),
newVar("v", tv),
))
fn.emit(okv)
body := fn.newBasicBlock("rangeiter.body")
done = fn.newBasicBlock("rangeiter.done")
emitIf(fn, emitExtract(fn, okv, 0), body, done)
fn.currentBlock = body
if tk != tInvalid {
k = emitExtract(fn, okv, 1)
}
if tv != tInvalid {
v = emitExtract(fn, okv, 2)
}
return
}
// rangeChan emits to fn the header for a loop that receives from
// channel x until it fails.
// tk is the channel's element type, or nil if the k result is
// not wanted
// pos is the position of the '=' or ':=' token.
//
func (b *builder) rangeChan(fn *Function, x Value, tk types.Type, pos token.Pos) (k Value, loop, done *BasicBlock) {
//
// loop: (target of continue)
// ko = <-x (key, ok)
// ok = extract ko #1
// if ok goto body else done
// body:
// k = extract ko #0
// ...
// goto loop
// done: (target of break)
loop = fn.newBasicBlock("rangechan.loop")
emitJump(fn, loop)
fn.currentBlock = loop
recv := &UnOp{
Op: token.ARROW,
X: x,
CommaOk: true,
}
recv.setPos(pos)
recv.setType(types.NewTuple(
newVar("k", x.Type().Underlying().(*types.Chan).Elem()),
varOk,
))
ko := fn.emit(recv)
body := fn.newBasicBlock("rangechan.body")
done = fn.newBasicBlock("rangechan.done")
emitIf(fn, emitExtract(fn, ko, 1), body, done)
fn.currentBlock = body
if tk != nil {
k = emitExtract(fn, ko, 0)
}
return
}
// rangeStmt emits to fn code for the range statement s, optionally
// labelled by label.
//
func (b *builder) rangeStmt(fn *Function, s *ast.RangeStmt, label *lblock) {
var tk, tv types.Type
if s.Key != nil && !isBlankIdent(s.Key) {
tk = fn.Pkg.typeOf(s.Key)
}
if s.Value != nil && !isBlankIdent(s.Value) {
tv = fn.Pkg.typeOf(s.Value)
}
// If iteration variables are defined (:=), this
// occurs once outside the loop.
//
// Unlike a short variable declaration, a RangeStmt
// using := never redeclares an existing variable; it
// always creates a new one.
if s.Tok == token.DEFINE {
if tk != nil {
fn.addLocalForIdent(s.Key.(*ast.Ident))
}
if tv != nil {
fn.addLocalForIdent(s.Value.(*ast.Ident))
}
}
x := b.expr(fn, s.X)
var k, v Value
var loop, done *BasicBlock
switch rt := x.Type().Underlying().(type) {
case *types.Slice, *types.Array, *types.Pointer: // *array
k, v, loop, done = b.rangeIndexed(fn, x, tv, s.For)
case *types.Chan:
k, loop, done = b.rangeChan(fn, x, tk, s.For)
case *types.Map, *types.Basic: // string
k, v, loop, done = b.rangeIter(fn, x, tk, tv, s.For)
default:
panic("Cannot range over: " + rt.String())
}
// Evaluate both LHS expressions before we update either.
var kl, vl lvalue
if tk != nil {
kl = b.addr(fn, s.Key, false) // non-escaping
}
if tv != nil {
vl = b.addr(fn, s.Value, false) // non-escaping
}
if tk != nil {
kl.store(fn, k)
}
if tv != nil {
vl.store(fn, v)
}
if label != nil {
label._break = done
label._continue = loop
}
fn.targets = &targets{
tail: fn.targets,
_break: done,
_continue: loop,
}
b.stmt(fn, s.Body)
fn.targets = fn.targets.tail
emitJump(fn, loop) // back-edge
fn.currentBlock = done
}
// stmt lowers statement s to SSA form, emitting code to fn.
func (b *builder) stmt(fn *Function, _s ast.Stmt) {
// The label of the current statement. If non-nil, its _goto
// target is always set; its _break and _continue are set only
// within the body of switch/typeswitch/select/for/range.
// It is effectively an additional default-nil parameter of stmt().
var label *lblock
start:
switch s := _s.(type) {
case *ast.EmptyStmt:
// ignore. (Usually removed by gofmt.)
case *ast.DeclStmt: // Con, Var or Typ
d := s.Decl.(*ast.GenDecl)
if d.Tok == token.VAR {
for _, spec := range d.Specs {
if vs, ok := spec.(*ast.ValueSpec); ok {
b.localValueSpec(fn, vs)
}
}
}
case *ast.LabeledStmt:
label = fn.labelledBlock(s.Label)
emitJump(fn, label._goto)
fn.currentBlock = label._goto
_s = s.Stmt
goto start // effectively: tailcall stmt(fn, s.Stmt, label)
case *ast.ExprStmt:
b.expr(fn, s.X)
case *ast.SendStmt:
fn.emit(&Send{
Chan: b.expr(fn, s.Chan),
X: emitConv(fn, b.expr(fn, s.Value),
fn.Pkg.typeOf(s.Chan).Underlying().(*types.Chan).Elem()),
pos: s.Arrow,
})
case *ast.IncDecStmt:
op := token.ADD
if s.Tok == token.DEC {
op = token.SUB
}
loc := b.addr(fn, s.X, false)
b.assignOp(fn, loc, NewConst(constant.MakeInt64(1), loc.typ()), op, s.Pos())
case *ast.AssignStmt:
switch s.Tok {
case token.ASSIGN, token.DEFINE:
b.assignStmt(fn, s.Lhs, s.Rhs, s.Tok == token.DEFINE)
default: // +=, etc.
op := s.Tok + token.ADD - token.ADD_ASSIGN
b.assignOp(fn, b.addr(fn, s.Lhs[0], false), b.expr(fn, s.Rhs[0]), op, s.Pos())
}
case *ast.GoStmt:
// The "intrinsics" new/make/len/cap are forbidden here.
// panic is treated like an ordinary function call.
v := Go{pos: s.Go}
b.setCall(fn, s.Call, &v.Call)
fn.emit(&v)
case *ast.DeferStmt:
// The "intrinsics" new/make/len/cap are forbidden here.
// panic is treated like an ordinary function call.
v := Defer{pos: s.Defer}
b.setCall(fn, s.Call, &v.Call)
fn.emit(&v)
// A deferred call can cause recovery from panic,
// and control resumes at the Recover block.
createRecoverBlock(fn)
case *ast.ReturnStmt:
var results []Value
if len(s.Results) == 1 && fn.Signature.Results().Len() > 1 {
// Return of one expression in a multi-valued function.
tuple := b.exprN(fn, s.Results[0])
ttuple := tuple.Type().(*types.Tuple)
for i, n := 0, ttuple.Len(); i < n; i++ {
results = append(results,
emitConv(fn, emitExtract(fn, tuple, i),
fn.Signature.Results().At(i).Type()))
}
} else {
// 1:1 return, or no-arg return in non-void function.
for i, r := range s.Results {
v := emitConv(fn, b.expr(fn, r), fn.Signature.Results().At(i).Type())
results = append(results, v)
}
}
if fn.namedResults != nil {
// Function has named result parameters (NRPs).
// Perform parallel assignment of return operands to NRPs.
for i, r := range results {
emitStore(fn, fn.namedResults[i], r, s.Return)
}
}
// Run function calls deferred in this
// function when explicitly returning from it.
fn.emit(new(RunDefers))
if fn.namedResults != nil {
// Reload NRPs to form the result tuple.
results = results[:0]
for _, r := range fn.namedResults {
results = append(results, emitLoad(fn, r))
}
}
fn.emit(&Return{Results: results, pos: s.Return})
fn.currentBlock = fn.newBasicBlock("unreachable")
case *ast.BranchStmt:
var block *BasicBlock
switch s.Tok {
case token.BREAK:
if s.Label != nil {
block = fn.labelledBlock(s.Label)._break
} else {
for t := fn.targets; t != nil && block == nil; t = t.tail {
block = t._break
}
}
case token.CONTINUE:
if s.Label != nil {
block = fn.labelledBlock(s.Label)._continue
} else {
for t := fn.targets; t != nil && block == nil; t = t.tail {
block = t._continue
}
}
case token.FALLTHROUGH:
for t := fn.targets; t != nil && block == nil; t = t.tail {
block = t._fallthrough
}
case token.GOTO:
block = fn.labelledBlock(s.Label)._goto
}
emitJump(fn, block)
fn.currentBlock = fn.newBasicBlock("unreachable")
case *ast.BlockStmt:
b.stmtList(fn, s.List)
case *ast.IfStmt:
if s.Init != nil {
b.stmt(fn, s.Init)
}
then := fn.newBasicBlock("if.then")
done := fn.newBasicBlock("if.done")
els := done
if s.Else != nil {
els = fn.newBasicBlock("if.else")
}
b.cond(fn, s.Cond, then, els)
fn.currentBlock = then
b.stmt(fn, s.Body)
emitJump(fn, done)
if s.Else != nil {
fn.currentBlock = els
b.stmt(fn, s.Else)
emitJump(fn, done)
}
fn.currentBlock = done
case *ast.SwitchStmt:
b.switchStmt(fn, s, label)
case *ast.TypeSwitchStmt:
b.typeSwitchStmt(fn, s, label)
case *ast.SelectStmt:
b.selectStmt(fn, s, label)
case *ast.ForStmt:
b.forStmt(fn, s, label)
case *ast.RangeStmt:
b.rangeStmt(fn, s, label)
default:
panic(fmt.Sprintf("unexpected statement kind: %T", s))
}
}
// buildFunction builds SSA code for the body of function fn. Idempotent.
func (b *builder) buildFunction(fn *Function) {
if fn.Blocks != nil {
return // building already started
}
var recvField *ast.FieldList
var body *ast.BlockStmt
var functype *ast.FuncType
switch n := fn.syntax.(type) {
case nil:
return // not a Go source function. (Synthetic, or from object file.)
case *ast.FuncDecl:
functype = n.Type
recvField = n.Recv
body = n.Body
case *ast.FuncLit:
functype = n.Type
body = n.Body
default:
panic(n)
}
if body == nil {
// External function.
if fn.Params == nil {
// This condition ensures we add a non-empty
// params list once only, but we may attempt
// the degenerate empty case repeatedly.
// TODO(adonovan): opt: don't do that.
// We set Function.Params even though there is no body
// code to reference them. This simplifies clients.
if recv := fn.Signature.Recv(); recv != nil {
fn.addParamObj(recv)
}
params := fn.Signature.Params()
for i, n := 0, params.Len(); i < n; i++ {
fn.addParamObj(params.At(i))
}
}
return
}
if fn.Prog.mode&LogSource != 0 {
defer logStack("build function %s @ %s", fn, fn.Prog.Fset.Position(fn.pos))()
}
fn.startBody()
fn.createSyntacticParams(recvField, functype)
b.stmt(fn, body)
if cb := fn.currentBlock; cb != nil && (cb == fn.Blocks[0] || cb == fn.Recover || cb.Preds != nil) {
// Control fell off the end of the function's body block.
//
// Block optimizations eliminate the current block, if
// unreachable. It is a builder invariant that
// if this no-arg return is ill-typed for
// fn.Signature.Results, this block must be
// unreachable. The sanity checker checks this.
fn.emit(new(RunDefers))
fn.emit(new(Return))
}
fn.finishBody()
}
// buildFuncDecl builds SSA code for the function or method declared
// by decl in package pkg.
//
func (b *builder) buildFuncDecl(pkg *Package, decl *ast.FuncDecl) {
id := decl.Name
if isBlankIdent(id) {
return // discard
}
fn := pkg.values[pkg.info.Defs[id]].(*Function)
if decl.Recv == nil && id.Name == "init" {
var v Call
v.Call.Value = fn
v.setType(types.NewTuple())
pkg.init.emit(&v)
}
b.buildFunction(fn)
}
// Build calls Package.Build for each package in prog.
// Building occurs in parallel unless the BuildSerially mode flag was set.
//
// Build is intended for whole-program analysis; a typical compiler
// need only build a single package.
//
// Build is idempotent and thread-safe.
//
func (prog *Program) Build() {
var wg sync.WaitGroup
for _, p := range prog.packages {
if prog.mode&BuildSerially != 0 {
p.Build()
} else {
wg.Add(1)
go func(p *Package) {
p.Build()
wg.Done()
}(p)
}
}
wg.Wait()
}
// Build builds SSA code for all functions and vars in package p.
//
// Precondition: CreatePackage must have been called for all of p's
// direct imports (and hence its direct imports must have been
// error-free).
//
// Build is idempotent and thread-safe.
//
func (p *Package) Build() { p.buildOnce.Do(p.build) }
func (p *Package) build() {
if p.info == nil {
return // synthetic package, e.g. "testmain"
}
// Ensure we have runtime type info for all exported members.
// TODO(adonovan): ideally belongs in memberFromObject, but
// that would require package creation in topological order.
for name, mem := range p.Members {
if ast.IsExported(name) {
p.Prog.needMethodsOf(mem.Type())
}
}
if p.Prog.mode&LogSource != 0 {
defer logStack("build %s", p)()
}
init := p.init
init.startBody()
var done *BasicBlock
if p.Prog.mode&BareInits == 0 {
// Make init() skip if package is already initialized.
initguard := p.Var("init$guard")
doinit := init.newBasicBlock("init.start")
done = init.newBasicBlock("init.done")
emitIf(init, emitLoad(init, initguard), done, doinit)
init.currentBlock = doinit
emitStore(init, initguard, vTrue, token.NoPos)
// Call the init() function of each package we import.
for _, pkg := range p.Pkg.Imports() {
prereq := p.Prog.packages[pkg]
if prereq == nil {
panic(fmt.Sprintf("Package(%q).Build(): unsatisfied import: Program.CreatePackage(%q) was not called", p.Pkg.Path(), pkg.Path()))
}
var v Call
v.Call.Value = prereq.init
v.Call.pos = init.pos
v.setType(types.NewTuple())
init.emit(&v)
}
}
var b builder
// Initialize package-level vars in correct order.
for _, varinit := range p.info.InitOrder {
if init.Prog.mode&LogSource != 0 {
fmt.Fprintf(os.Stderr, "build global initializer %v @ %s\n",
varinit.Lhs, p.Prog.Fset.Position(varinit.Rhs.Pos()))
}
if len(varinit.Lhs) == 1 {
// 1:1 initialization: var x, y = a(), b()
var lval lvalue
if v := varinit.Lhs[0]; v.Name() != "_" {
lval = &address{addr: p.values[v].(*Global), pos: v.Pos()}
} else {
lval = blank{}
}
b.assign(init, lval, varinit.Rhs, true, nil)
} else {
// n:1 initialization: var x, y := f()
tuple := b.exprN(init, varinit.Rhs)
for i, v := range varinit.Lhs {
if v.Name() == "_" {
continue
}
emitStore(init, p.values[v].(*Global), emitExtract(init, tuple, i), v.Pos())
}
}
}
// Build all package-level functions, init functions
// and methods, including unreachable/blank ones.
// We build them in source order, but it's not significant.
for _, file := range p.files {
for _, decl := range file.Decls {
if decl, ok := decl.(*ast.FuncDecl); ok {
b.buildFuncDecl(p, decl)
}
}
}
// Finish up init().
if p.Prog.mode&BareInits == 0 {
emitJump(init, done)
init.currentBlock = done
}
init.emit(new(Return))
init.finishBody()
p.info = nil // We no longer need ASTs or go/types deductions.
if p.Prog.mode&SanityCheckFunctions != 0 {
sanityCheckPackage(p)
}
}
// Like ObjectOf, but panics instead of returning nil.
// Only valid during p's create and build phases.
func (p *Package) objectOf(id *ast.Ident) types.Object {
if o := p.info.ObjectOf(id); o != nil {
return o
}
panic(fmt.Sprintf("no types.Object for ast.Ident %s @ %s",
id.Name, p.Prog.Fset.Position(id.Pos())))
}
// Like TypeOf, but panics instead of returning nil.
// Only valid during p's create and build phases.
func (p *Package) typeOf(e ast.Expr) types.Type {
if T := p.info.TypeOf(e); T != nil {
return T
}
panic(fmt.Sprintf("no type for %T @ %s",
e, p.Prog.Fset.Position(e.Pos())))
}
| {
"pile_set_name": "Github"
} |
var mathSymbols = [];
var mathSymbolCategories = ['All'];
const grid = document.querySelector('#Symbols .grid');
var vscode;
(function() {
vscode = acquireVsCodeApi();
tikzInitialise();
})();
window.addEventListener('message', event => {
const data = event.data;
if (data.type === 'mathSymbols') {
data.mathSymbols.forEach(symbol => {
processMathSymbol(symbol);
})
}
});
function processMathSymbol(mathSymbol) {
mathSymbol.searchText = getSearchText(mathSymbol);
mathSymbol.category = mathSymbol.category.replace(/^-/, '');
mathSymbols.push(mathSymbol);
if (mathSymbolCategories.indexOf(mathSymbol.category) === -1) {
mathSymbolCategories.push(mathSymbol.category);
document.querySelector('#Symbols .header select').innerHTML = mathSymbolCategories
.map(category => `<option>${category}</option>`)
.join('\n');
}
const symbolDiv = document.createElement('div');
symbolDiv.className = 'snippet';
symbolDiv.setAttribute('data-snippet', mathSymbol.snippet);
symbolDiv.innerHTML = mathSymbol.svg;
symbolDiv.addEventListener('click', _evt => {
vscode.postMessage({
type: 'insertSnippet',
snippet: symbolDiv.getAttribute('data-snippet') + ' '
});
});
mathSymbol.div = symbolDiv;
grid.appendChild(symbolDiv);
}
let lastSymbol;
function mathSymbolSearch() {
const searchStr = document.querySelector('#Symbols .header input').value;
let category = document.querySelector('#Symbols .header select').value;
category = category === 'All' ? '' : category;
if (lastSymbol) {
lastSymbol.div.style = '';
lastSymbol = undefined;
}
mathSymbols.forEach(mathSymbol => {
if (category && mathSymbol.category !== category) {
mathSymbol.div.style.display = 'none';
return;
}
if (mathSymbol.searchText.toLowerCase().indexOf(searchStr.toLowerCase()) === -1) {
mathSymbol.div.style.display = 'none';
} else {
mathSymbol.div.style.display = '';
lastSymbol = mathSymbol;
}
});
if (lastSymbol) {
lastSymbol.div.style = 'margin-right: auto;';
}
}
function getSearchText(symbol) {
let searchText = symbol.name + symbol.keywords;
if (!symbol.category.match(/^-/)) {
searchText += symbol.category;
}
return searchText;
}
function tikzInitialise() {
document.querySelectorAll('#TikZ a.cmd').forEach(elem => {
elem.addEventListener('click', _evt => {
vscode.postMessage({
type: 'insertSnippet',
snippet: elem.getAttribute('data-snippet').replace(/\\n/g, '\n')
});
});
});
}
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName('tabcontent');
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = 'none';
}
tablinks = document.getElementsByClassName('tablinks');
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(' active', '');
}
document.getElementById(tabName).style.display = 'block';
evt.currentTarget.className += ' active';
}
document.querySelector('.tablinks.active').click();
| {
"pile_set_name": "Github"
} |
// 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.
// +build !go1.12
package impl
import "reflect"
type mapIter struct {
v reflect.Value
keys []reflect.Value
}
// mapRange provides a less-efficient equivalent to
// the Go 1.12 reflect.Value.MapRange method.
func mapRange(v reflect.Value) *mapIter {
return &mapIter{v: v}
}
func (i *mapIter) Next() bool {
if i.keys == nil {
i.keys = i.v.MapKeys()
} else {
i.keys = i.keys[1:]
}
return len(i.keys) > 0
}
func (i *mapIter) Key() reflect.Value {
return i.keys[0]
}
func (i *mapIter) Value() reflect.Value {
return i.v.MapIndex(i.keys[0])
}
| {
"pile_set_name": "Github"
} |
# exception classes
class TrelbyError(Exception):
def __init__(self, msg):
Exception.__init__(self, msg)
self.msg = msg
def __str__(self):
return str(self.msg)
class ConfigError(TrelbyError):
def __init__(self, msg):
TrelbyError.__init__(self, msg)
class MiscError(TrelbyError):
def __init__(self, msg):
TrelbyError.__init__(self, msg)
| {
"pile_set_name": "Github"
} |
#!/usr/bin/env php
<?php include 'phpdoc.php'; | {
"pile_set_name": "Github"
} |
"""myshop URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.9/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url, include
from django.contrib import admin
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^', include('shop.urls', namespace='shop')),
]
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Google Analytics + OutboundLink + Google Adsense -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-79254642-1"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-79254642-1');
</script>
<script>
var getOutboundLink = function(url) {
gtag('event', 'click', {
'event_category': 'outbound',
'event_label': url,
'transport_type': 'beacon',
'event_callback': function(){document.location = url;}
});
}
</script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<script>
(adsbygoogle = window.adsbygoogle || []).push({
google_ad_client: "ca-pub-3523953066677938",
enable_page_level_ads: true
});
</script>
<!-- Google Analytics + OutboundLink + Google Adsense -->
<meta charset="utf-8">
<title>Hexbin chart and scatterplot with ggplot2 – the R Graph Gallery</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="This post explains how to build a hexbin chart with a scatterplot on top using R and ggplot2. Code and reproducible code provided.">
<meta name="keywords" content="R,ggplot2,tidyverse,Example,Data,Dataviz,Datavisualization,Plot,Chart,Graph,Learning,Caveat,Pitfall,Mistake">
<meta name="author" content="Yan Holtz">
<link rel="icon" href="img/logo/R_single_small.png">
<!-- Control appearance when shared by social media -->
<meta property="og:title" content="Hexbin chart and scatterplot with ggplot2" />
<meta property="og:image" content="img/overview_RGG.png" />
<meta property="og:description" content="This post explains how to build a hexbin chart with a scatterplot on top using R and ggplot2. Code and reproducible code provided." />
<meta property='og:url' content="https://www.r-graph-gallery.com/198-scatter-and-density-plot-ggplot2.html" />
<meta property="og:type" content="website" />
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom fonts for this template -->
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- Custom styles for this template -->
<link href="css/agency.css" rel="stylesheet">
<!-- JQUERY -->
<script src="vendor/jquery/jquery.min.js"></script>
</head>
<body data-spy="scroll" data-target="#myScrollspy" data-offset="1">
<!-- THIS ALLOWS TO INSERT THE MENU THAT IS STORED IN A MENU.HTML FILE-->
<nav class="navbar navbar-expand-lg fixed-top" id="mainNav"></nav>
<script>
$(function(){
$("#mainNav").load("html_chunk/menu.html");
});
</script>
<!-- THIS ALLOWS TO INSERT THE MODAL OF THE MENU THAT IS STORED IN A MENU_MODAL.HTML FILE-->
<div id="modal_menu_insertion"> </div>
<script>
$(function(){
$("#modal_menu_insertion").load("html_chunk/menu_modal.html");
});
</script>
<!-- Header = Title in big + social media Icon + quick description -->
<header class="masthead" style="padding-bottom: 30px;">
<div class="textlanding">
<center><h1>Hexbin chart and scatterplot with ggplot2</h1></center>
<hr class="short_hr">
<br>
<ul class="list-inline social-buttons">
<li class="list-inline-item">
<a href="https://twitter.com/R_Graph_Gallery">
<i class="fa fa-twitter"></i>
</a>
</li>
<li class="list-inline-item social-buttons">
<a href="https://github.com/holtzy">
<i class="fa fa-github" style="color: white"></i>
</a>
</li>
<li class="list-inline-item social-buttons">
<a href="https://www.linkedin.com/in/yan-holtz-2477534a/">
<i class="fa fa-linkedin"></i>
</a>
</li>
<li class="list-inline-item social-buttons">
<a href="https://www.yan-holtz.com">
<i class="fa fa-home"></i>
</a>
</li>
</ul>
<center><p style="max-width: 600px; margin-top: 40px">This post explains how to build a hexbin chart with a <a href="scatterplot.html">scatterplot</a> on top using <code>R</code> and <a href="ggplot2-package.html">ggplot2</a>. It is an addition to the page about <a href="2d-density-plot-with-ggplot2.html">2d density plot with ggplot2</a>.</p></center>
<div style="text-align:center">
<a class="btn btn-secondary btn-xl text-uppercase js-scroll-trigger" href='2d-density-chart.html'>2d density section</a>
<a class="btn btn-secondary btn-xl text-uppercase js-scroll-trigger" href='https://www.data-to-viz.com/graph/density2d.html'>Data to Viz</a>
</div>
</div>
</header>
<!-- THIS ALLOWS TO INSERT THE ADVERTISEMENT BANNER THAT IS STORED IN A BANNER.HTML FILE-->
<div id="position_for_images"></div>
<script>
$(function(){
$("#position_for_images").load("html_chunk/images.html");
});
</script>
<!-- STYLE for chart pages but not the rest of tthe website -->
<style>
img {
margin-top: 20px;
}
</style>
<div class="container" style="padding-top: 100px">
<div class="row">
<div class="col-md-6 col-sm-12 align-self-center">
<p>This plot extends the concepts described in the <a href="2d-density-plot-with-ggplot2.html">2d density chart with ggplot2</a> document. It simply illustrates that a <a href="scatterplot.html">scatterplot</a> can be added on top of the 2d density chart.</p>
<p>Thanks <a href="http://chrisk91.me/">Christian Jacob</a> for this submission.</p>
</div>
<div class="col-md-6 col-sm-12">
<p><img src="198-scatter-and-density-plot-ggplot2_files/figure-html/thecode-1.png" width="100%" /></p>
</div>
</div>
<div class="sourceCode" id="cb1"><pre class="sourceCode r"><code class="sourceCode r"><a class="sourceLine" id="cb1-1" data-line-number="1"><span class="co"># library</span></a>
<a class="sourceLine" id="cb1-2" data-line-number="2"><span class="kw">library</span>(ggplot2) </a>
<a class="sourceLine" id="cb1-3" data-line-number="3"></a>
<a class="sourceLine" id="cb1-4" data-line-number="4"><span class="co"># data</span></a>
<a class="sourceLine" id="cb1-5" data-line-number="5">sample_data <-<span class="st"> </span><span class="kw">data.frame</span>(<span class="dt">x_values =</span> <span class="dv">1</span><span class="op">:</span><span class="dv">100</span> <span class="op">+</span><span class="st"> </span><span class="kw">rnorm</span>(<span class="dv">100</span>,<span class="dt">sd=</span><span class="dv">20</span>), <span class="dt">y_values =</span> <span class="dv">1</span><span class="op">:</span><span class="dv">100</span> <span class="op">+</span><span class="st"> </span><span class="kw">rnorm</span>(<span class="dv">100</span>,<span class="dt">sd=</span><span class="dv">27</span>)) </a>
<a class="sourceLine" id="cb1-6" data-line-number="6"></a>
<a class="sourceLine" id="cb1-7" data-line-number="7"><span class="co">#plot</span></a>
<a class="sourceLine" id="cb1-8" data-line-number="8"><span class="kw">ggplot</span>(sample_data, <span class="kw">aes</span>(x_values, y_values)) <span class="op">+</span></a>
<a class="sourceLine" id="cb1-9" data-line-number="9"><span class="st"> </span><span class="kw">stat_density2d</span>(<span class="dt">geom=</span><span class="st">"tile"</span>, <span class="kw">aes</span>(<span class="dt">fill =</span> ..density..), <span class="dt">contour =</span> <span class="ot">FALSE</span>) <span class="op">+</span><span class="st"> </span></a>
<a class="sourceLine" id="cb1-10" data-line-number="10"><span class="st"> </span><span class="kw">geom_point</span>(<span class="dt">colour =</span> <span class="st">"white"</span>)</a></code></pre></div>
<!-- Close container -->
</div>
<!-- ============================ RELATED SECTION ============================ -->
<section class="bg-light" id="portfolio_landing" style="padding-top: 30px; padding-bottom: 30px; margin-top: 100px;">
<div class="container">
<p class="mySeryTitle">Related chart types</p>
<hr>
<div class="row">
<div class="col-md-2 col-sm-4 portfolio-item ">
<a class="portfolio-link" href="scatterplot.html">
<div class="portfolio-hover">
<div class="portfolio-hover-content">
<i class="fa fa-plus fa-3x"></i>
</div>
</div>
<img class="img-fluid" src="img/section/ScatterPlot150.png" alt="">
</a>
<div class="captionPortfolio">Scatter</div>
</div>
<div class="col-md-2 col-sm-4 portfolio-item">
<a class="portfolio-link" href="heatmap.html">
<div class="portfolio-hover">
<div class="portfolio-hover-content">
<i class="fa fa-plus fa-3x"></i>
</div>
</div>
<img class="img-fluid" src="img/section/Heatmap150.png" alt="">
</a>
<div class="captionPortfolio">Heatmap</div>
</div>
<div class="col-md-2 col-sm-4 portfolio-item">
<a class="portfolio-link" href="correlogram.html">
<div class="portfolio-hover">
<div class="portfolio-hover-content">
<i class="fa fa-plus fa-3x"></i>
</div>
</div>
<img class="img-fluid" src="img/section/Correlogram150.png" alt="">
</a>
<div class="captionPortfolio">Correlogram</div>
</div>
<div class="col-md-2 col-sm-4 portfolio-item">
<a class="portfolio-link" href="bubble-chart.html">
<div class="portfolio-hover">
<div class="portfolio-hover-content">
<i class="fa fa-plus fa-3x"></i>
</div>
</div>
<img class="img-fluid" src="img/section/BubblePlot150.png" alt="">
</a>
<div class="captionPortfolio">Bubble</div>
</div>
<div class="col-md-2 col-sm-4 portfolio-item ">
<a class="portfolio-link" href="connected-scatterplot.html">
<div class="portfolio-hover">
<div class="portfolio-hover-content">
<i class="fa fa-plus fa-3x"></i>
</div>
</div>
<img class="img-fluid" src="img/section/ScatterConnected150.png" alt="">
</a>
<div class="captionPortfolio">Connected scatter</div>
</div>
<div class="col-md-2 col-sm-4 portfolio-item show column correlation numonly bigdata">
<a class="portfolio-link" href="2d-density-chart.html">
<div class="portfolio-hover">
<div class="portfolio-hover-content">
<i class="fa fa-plus fa-3x"></i>
</div>
</div>
<img class="img-fluid" src="img/section/2dDensity150.png" alt="">
</a>
<div class="captionPortfolio">Density 2d</div>
</div>
</div>
</div>
</section>
<!-- ============================ CONTACT SECTION ============================ -->
<section id="contact" class="bg" style="background-color: white; padding-top: 60px">
<div class="container">
<div class="row">
<div class="col-lg-2 text-center"></div>
<div class="col-lg-8 text-center">
<br><br><br>
<h2 class="section-heading text-uppercase" style="color: black">Contact</h2>
<p>This document is a work by <a href="https://www.yan-holtz.com">Yan Holtz</a>. Any feedback is highly encouraged. You can fill an issue on <a href="https://github.com/holtzy/D3-graph-gallery/issues">Github</a>, drop me a message on <a href="https://twitter.com/R_Graph_Gallery">Twitter</a>, or send an email pasting <a href="">yan.holtz.data</a> with <a href="">gmail.com</a>.</p>
<div style="text-align:center">
<a class="btn btn-primary btn-xl text-uppercase js-scroll-trigger" href="https://github.com/holtzy">Github</a>
<a class="btn btn-primary btn-xl text-uppercase js-scroll-trigger" href="https://twitter.com/R_Graph_Gallery">Twitter</a>
</div>
</div>
</div>
</div>
</section>
<!-- ============================ FOOTER SECTION ============================ -->
<footer class="bg-light" id="myFooter">
<div class="container" >
<div class="row">
<div class="col-md-4">
<span class="copyright">Copyright © the R graph gallery 2018</span>
</div>
<div class="col-md-4">
<ul class="list-inline social-buttons">
<li class="list-inline-item">
<a href="https://twitter.com/R_Graph_Gallery">
<i class="fa fa-twitter"></i>
</a>
</li>
<li class="list-inline-item">
<a href="https://github.com/holtzy">
<i class="fa fa-github"></i>
</a>
</li>
<li class="list-inline-item">
<a href="https://www.linkedin.com/in/yan-holtz-2477534a/">
<i class="fa fa-linkedin"></i>
</a>
</li>
</ul>
</div>
<div class="col-md-4">
<ul class="list-inline quicklinks">
<li class="list-inline-item">
<a href="#">Privacy Policy</a>
</li>
<li class="list-inline-item">
<a href="#">Terms of Use</a>
</li>
</ul>
</div>
</div>
</div>
</footer>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- ============================ JAVASCRIPT SECTION ============================ -->
<!-- Bootstrap core JavaScript -->
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<!-- Custom scripts for this template -->
<script src="js/agency.min.js"></script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
<h2>DESCRIPTION</h2>
<em>v.to.db</em> loads vector map features or metrics into a database
table, or prints them (or the SQL queries used to obtain them) in a
form of a human-readable report. For uploaded/printed category values
'-1' is used for 'no category' and 'null'/'-' if category cannot be
found or multiple categories were found. For line azimuths '-1' is used
for closed lines (start equals end).
<h2>NOTES</h2>
Measures of lengths and areas are always reported in meters, unless the
<em>unit</em> parameter is set.
The units <em>miles</em>, <em>feet</em>, <em>meters</em> and
<em>kilometers</em> are square for <em>option=area</em>.
<p>Feet and acre units are always reported in their common versions
(i.e. the International Foot, exactly 5280 feet in a mile), even
when the location's standard map unit is the US Survey foot.
<p>When calculating perimeters in Latitude-Longitude locations, the geodesic
distance between the vertices is used.
<p>When using <em>option=coor</em> on a vector area map,
only coordinates of centroids with unique category will be reported.
<p>When using <em>option=bbox</em> on a vector area map with more than one
feature per category value, the results corresponds to the bounding box of
all features of same category taken together.
<p>Line azimuth is calculated as angle from the North direction to the line endnode
direction at the line statnode. By default it's reported in decimal degrees (0-360, CW) but
it also may be repored in radians with <em>unit=radians</em>. Azimuth value
<b>-1</b> is used to report closed line with it's startnode and endnode being in
same place. Azimuth values make sense only if every vector line has only one
entry in database (unique CAT value).
<p>If the module is apparently slow <em>and</em> the map attributes are
stored in an external DBMS such as PostgreSQL, it is highly recommended
to create an index on the key (category) column.
<p>Uploading the vector map attributes to a database requires a table attached to
a given input vector <em>layer</em>. The <b>print only</b> (<b>-p</b>) mode
doesn't require a table. Use <em><a href="db.execute.html">db.execute</a></em>
or <em><a href="v.db.addtable.html">v.db.addtable</a></em> to create a table if
needed.
<p>Updating the table has to be done column-wise. The <em>column</em> will be
created in the table if it doesn't already exist, except when using the
<b>print only</b> (<b>-p</b>) mode. If the <em>column</em> exists, the
<b>--overwrite</b> flag is required to overwrite it.
<h2>EXAMPLES</h2>
<h3>Updating attribute tables</h3>
Upload category numbers to attribute table (used for new map):<br>
<div class="code"><pre>
v.to.db map=soils type=centroid option=cat
</pre></div>
<p>Upload polygon areas to corresponding centroid record in the attribute table:<br>
<div class="code"><pre>
v.to.db map=soils type=centroid option=area columns=area_size unit=h
</pre></div>
<p>Upload line lengths (in meters) of each vector line to attribute table
(use <em>v.category</em> in case of missing categories):<br>
<div class="code"><pre>
v.to.db map=roads option=length type=line columns=linelength units=me
</pre></div>
<p>Upload x and y coordinates from vector geometry to attribute table:<br>
<div class="code"><pre>
v.to.db map=pointsmap option=coor columns=x,y
</pre></div>
<p>Upload x, y and z coordinates from vector geometry to attribute table:<br>
<div class="code"><pre>
v.to.db map=pointsmap option=coor columns=x,y,z
</pre></div>
<p>Transfer attributes from a character column (with numeric contents) to a new
integer column:<br>
<div class="code"><pre>
v.db.addcolumn usa_income_employment2002 col="FIPS_NUM integer"
v.to.db usa_income_employment2002 option=query columns=FIPS_NUM query_column=STATE_FIPS
</pre></div>
<p>Upload category numbers of left and right area, to an attribute table of
boundaries common for the areas:<br>
<div class="code"><pre>
# add categories for boundaries of the input vector map, in layer 2:
v.category soils out=mysoils layer=2 type=boundary option=add
# add a table with columns named "left" and "right" to layer 2 of the input
# vector map:
v.db.addtable mysoils layer=2 columns="left integer,right integer"
# upload categories of left and right areas:
v.to.db mysoils option=sides columns=left,right layer=2
# display the result:
v.db.select mysoils layer=2
</pre></div>
<p>Compute D<sub>L</sub>, the Fractal Dimension (Mandelbrot, 1982), of the
boundary defining a polygon based on the formula:
<br><tt>
D = 2 * (log perimeter) / (log area):<br>
</tt>
<div class="code"><pre>
g.copy vect=soils,mysoils
v.db.addcolumn mysoils col="d double precision"
v.to.db mysoils option=fd column="d"
g.region vector=mysoils res=50
v.to.rast input=mysoils output=soils_fd type=area use=attr attribute_column=d
r.colors map=soils_fd color=gyr
d.mon wx0
d.rast.leg soils_fd
d.vect mysoils type=boundary
</pre></div>
<h3>Printing reports</h3>
Report x,y,z coordinates of points in the input vector map:<br>
<div class="code"><pre>
v.to.db -p bugsites option=coor type=point
</pre></div>
Report all area sizes of the input vector map:<br>
<div class="code"><pre>
v.to.db -p soils option=area type=boundary units=h
</pre></div>
<p>Report all area sizes of the input vector map, in hectares, sorted by category
number (requires GNU <em>sort</em> utility installed):<br>
<div class="code"><pre>
v.to.db -p soils option=area type=boundary units=h | sort -n
</pre></div>
<p>Report all line lengths of the input vector map, in kilometers:<br>
<div class="code"><pre>
v.to.db -p roads option=length type=line units=k
</pre></div>
<p>Report number of features for each category in the input vector map:<br>
<div class="code"><pre>
v.to.db -p roads option=count type=line
</pre></div>
<h2>SEE ALSO</h2>
<em>
<a href="d.what.vect.html">d.what.vect</a>,
<a href="db.execute.html">db.execute</a>,
<a href="v.category.html">v.category</a>,
<a href="v.db.addtable.html">v.db.addtable</a>,
<a href="v.db.addcolumn.html">v.db.addcolumn</a>,
<a href="v.db.connect.html">v.db.connect</a>,
<a href="v.distance.html">v.distance</a>,
<a href="v.report.html">v.report</a>,
<a href="v.univar.html">v.univar</a>,
<a href="v.what.html">v.what</a>
</em>
<h2>REFERENCES</h2>
<ul>
<li>Mandelbrot, B. B. (1982). The fractal geometry of nature. New York: W. H. Freeman.</li>
<li>Xu, Y. F. & Sun, D. A. (2005). Geotechnique 55, No. 9, 691-695</li>
</ul>
<h2>AUTHOR</h2>
Radim Blazek, ITC-irst, Trento, Italy<br>
Line sinuousity implemented by Wolf Bergenheim
<!--
<p>
<i>Last changed: $Date$</i>
-->
| {
"pile_set_name": "Github"
} |
/*
* Copyright © 2014 Intel Corporation
*
* 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 (including the next
* paragraph) 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.
*
* Author: Shobhit Kumar <[email protected]>
*
*/
#include <linux/gpio/consumer.h>
#include <linux/gpio/machine.h>
#include <linux/mfd/intel_soc_pmic.h>
#include <linux/pinctrl/consumer.h>
#include <linux/pinctrl/machine.h>
#include <linux/slab.h>
#include <asm/intel-mid.h>
#include <asm/unaligned.h>
#include <drm/drm_crtc.h>
#include <drm/drm_edid.h>
#include <video/mipi_display.h>
#include "i915_drv.h"
#include "intel_display_types.h"
#include "intel_dsi.h"
#include "intel_sideband.h"
#define MIPI_TRANSFER_MODE_SHIFT 0
#define MIPI_VIRTUAL_CHANNEL_SHIFT 1
#define MIPI_PORT_SHIFT 3
/* base offsets for gpio pads */
#define VLV_GPIO_NC_0_HV_DDI0_HPD 0x4130
#define VLV_GPIO_NC_1_HV_DDI0_DDC_SDA 0x4120
#define VLV_GPIO_NC_2_HV_DDI0_DDC_SCL 0x4110
#define VLV_GPIO_NC_3_PANEL0_VDDEN 0x4140
#define VLV_GPIO_NC_4_PANEL0_BKLTEN 0x4150
#define VLV_GPIO_NC_5_PANEL0_BKLTCTL 0x4160
#define VLV_GPIO_NC_6_HV_DDI1_HPD 0x4180
#define VLV_GPIO_NC_7_HV_DDI1_DDC_SDA 0x4190
#define VLV_GPIO_NC_8_HV_DDI1_DDC_SCL 0x4170
#define VLV_GPIO_NC_9_PANEL1_VDDEN 0x4100
#define VLV_GPIO_NC_10_PANEL1_BKLTEN 0x40E0
#define VLV_GPIO_NC_11_PANEL1_BKLTCTL 0x40F0
#define VLV_GPIO_PCONF0(base_offset) (base_offset)
#define VLV_GPIO_PAD_VAL(base_offset) ((base_offset) + 8)
struct gpio_map {
u16 base_offset;
bool init;
};
static struct gpio_map vlv_gpio_table[] = {
{ VLV_GPIO_NC_0_HV_DDI0_HPD },
{ VLV_GPIO_NC_1_HV_DDI0_DDC_SDA },
{ VLV_GPIO_NC_2_HV_DDI0_DDC_SCL },
{ VLV_GPIO_NC_3_PANEL0_VDDEN },
{ VLV_GPIO_NC_4_PANEL0_BKLTEN },
{ VLV_GPIO_NC_5_PANEL0_BKLTCTL },
{ VLV_GPIO_NC_6_HV_DDI1_HPD },
{ VLV_GPIO_NC_7_HV_DDI1_DDC_SDA },
{ VLV_GPIO_NC_8_HV_DDI1_DDC_SCL },
{ VLV_GPIO_NC_9_PANEL1_VDDEN },
{ VLV_GPIO_NC_10_PANEL1_BKLTEN },
{ VLV_GPIO_NC_11_PANEL1_BKLTCTL },
};
struct i2c_adapter_lookup {
u16 slave_addr;
struct intel_dsi *intel_dsi;
acpi_handle dev_handle;
};
#define CHV_GPIO_IDX_START_N 0
#define CHV_GPIO_IDX_START_E 73
#define CHV_GPIO_IDX_START_SW 100
#define CHV_GPIO_IDX_START_SE 198
#define CHV_VBT_MAX_PINS_PER_FMLY 15
#define CHV_GPIO_PAD_CFG0(f, i) (0x4400 + (f) * 0x400 + (i) * 8)
#define CHV_GPIO_GPIOEN (1 << 15)
#define CHV_GPIO_GPIOCFG_GPIO (0 << 8)
#define CHV_GPIO_GPIOCFG_GPO (1 << 8)
#define CHV_GPIO_GPIOCFG_GPI (2 << 8)
#define CHV_GPIO_GPIOCFG_HIZ (3 << 8)
#define CHV_GPIO_GPIOTXSTATE(state) ((!!(state)) << 1)
#define CHV_GPIO_PAD_CFG1(f, i) (0x4400 + (f) * 0x400 + (i) * 8 + 4)
#define CHV_GPIO_CFGLOCK (1 << 31)
/* ICL DSI Display GPIO Pins */
#define ICL_GPIO_DDSP_HPD_A 0
#define ICL_GPIO_L_VDDEN_1 1
#define ICL_GPIO_L_BKLTEN_1 2
#define ICL_GPIO_DDPA_CTRLCLK_1 3
#define ICL_GPIO_DDPA_CTRLDATA_1 4
#define ICL_GPIO_DDSP_HPD_B 5
#define ICL_GPIO_L_VDDEN_2 6
#define ICL_GPIO_L_BKLTEN_2 7
#define ICL_GPIO_DDPA_CTRLCLK_2 8
#define ICL_GPIO_DDPA_CTRLDATA_2 9
static enum port intel_dsi_seq_port_to_port(u8 port)
{
return port ? PORT_C : PORT_A;
}
static const u8 *mipi_exec_send_packet(struct intel_dsi *intel_dsi,
const u8 *data)
{
struct drm_i915_private *dev_priv = to_i915(intel_dsi->base.base.dev);
struct mipi_dsi_device *dsi_device;
u8 type, flags, seq_port;
u16 len;
enum port port;
drm_dbg_kms(&dev_priv->drm, "\n");
flags = *data++;
type = *data++;
len = *((u16 *) data);
data += 2;
seq_port = (flags >> MIPI_PORT_SHIFT) & 3;
/* For DSI single link on Port A & C, the seq_port value which is
* parsed from Sequence Block#53 of VBT has been set to 0
* Now, read/write of packets for the DSI single link on Port A and
* Port C will based on the DVO port from VBT block 2.
*/
if (intel_dsi->ports == (1 << PORT_C))
port = PORT_C;
else
port = intel_dsi_seq_port_to_port(seq_port);
dsi_device = intel_dsi->dsi_hosts[port]->device;
if (!dsi_device) {
drm_dbg_kms(&dev_priv->drm, "no dsi device for port %c\n",
port_name(port));
goto out;
}
if ((flags >> MIPI_TRANSFER_MODE_SHIFT) & 1)
dsi_device->mode_flags &= ~MIPI_DSI_MODE_LPM;
else
dsi_device->mode_flags |= MIPI_DSI_MODE_LPM;
dsi_device->channel = (flags >> MIPI_VIRTUAL_CHANNEL_SHIFT) & 3;
switch (type) {
case MIPI_DSI_GENERIC_SHORT_WRITE_0_PARAM:
mipi_dsi_generic_write(dsi_device, NULL, 0);
break;
case MIPI_DSI_GENERIC_SHORT_WRITE_1_PARAM:
mipi_dsi_generic_write(dsi_device, data, 1);
break;
case MIPI_DSI_GENERIC_SHORT_WRITE_2_PARAM:
mipi_dsi_generic_write(dsi_device, data, 2);
break;
case MIPI_DSI_GENERIC_READ_REQUEST_0_PARAM:
case MIPI_DSI_GENERIC_READ_REQUEST_1_PARAM:
case MIPI_DSI_GENERIC_READ_REQUEST_2_PARAM:
drm_dbg(&dev_priv->drm,
"Generic Read not yet implemented or used\n");
break;
case MIPI_DSI_GENERIC_LONG_WRITE:
mipi_dsi_generic_write(dsi_device, data, len);
break;
case MIPI_DSI_DCS_SHORT_WRITE:
mipi_dsi_dcs_write_buffer(dsi_device, data, 1);
break;
case MIPI_DSI_DCS_SHORT_WRITE_PARAM:
mipi_dsi_dcs_write_buffer(dsi_device, data, 2);
break;
case MIPI_DSI_DCS_READ:
drm_dbg(&dev_priv->drm,
"DCS Read not yet implemented or used\n");
break;
case MIPI_DSI_DCS_LONG_WRITE:
mipi_dsi_dcs_write_buffer(dsi_device, data, len);
break;
}
if (INTEL_GEN(dev_priv) < 11)
vlv_dsi_wait_for_fifo_empty(intel_dsi, port);
out:
data += len;
return data;
}
static const u8 *mipi_exec_delay(struct intel_dsi *intel_dsi, const u8 *data)
{
struct drm_i915_private *i915 = to_i915(intel_dsi->base.base.dev);
u32 delay = *((const u32 *) data);
drm_dbg_kms(&i915->drm, "\n");
usleep_range(delay, delay + 10);
data += 4;
return data;
}
static void vlv_exec_gpio(struct drm_i915_private *dev_priv,
u8 gpio_source, u8 gpio_index, bool value)
{
struct gpio_map *map;
u16 pconf0, padval;
u32 tmp;
u8 port;
if (gpio_index >= ARRAY_SIZE(vlv_gpio_table)) {
drm_dbg_kms(&dev_priv->drm, "unknown gpio index %u\n",
gpio_index);
return;
}
map = &vlv_gpio_table[gpio_index];
if (dev_priv->vbt.dsi.seq_version >= 3) {
/* XXX: this assumes vlv_gpio_table only has NC GPIOs. */
port = IOSF_PORT_GPIO_NC;
} else {
if (gpio_source == 0) {
port = IOSF_PORT_GPIO_NC;
} else if (gpio_source == 1) {
drm_dbg_kms(&dev_priv->drm, "SC gpio not supported\n");
return;
} else {
drm_dbg_kms(&dev_priv->drm,
"unknown gpio source %u\n", gpio_source);
return;
}
}
pconf0 = VLV_GPIO_PCONF0(map->base_offset);
padval = VLV_GPIO_PAD_VAL(map->base_offset);
vlv_iosf_sb_get(dev_priv, BIT(VLV_IOSF_SB_GPIO));
if (!map->init) {
/* FIXME: remove constant below */
vlv_iosf_sb_write(dev_priv, port, pconf0, 0x2000CC00);
map->init = true;
}
tmp = 0x4 | value;
vlv_iosf_sb_write(dev_priv, port, padval, tmp);
vlv_iosf_sb_put(dev_priv, BIT(VLV_IOSF_SB_GPIO));
}
static void chv_exec_gpio(struct drm_i915_private *dev_priv,
u8 gpio_source, u8 gpio_index, bool value)
{
u16 cfg0, cfg1;
u16 family_num;
u8 port;
if (dev_priv->vbt.dsi.seq_version >= 3) {
if (gpio_index >= CHV_GPIO_IDX_START_SE) {
/* XXX: it's unclear whether 255->57 is part of SE. */
gpio_index -= CHV_GPIO_IDX_START_SE;
port = CHV_IOSF_PORT_GPIO_SE;
} else if (gpio_index >= CHV_GPIO_IDX_START_SW) {
gpio_index -= CHV_GPIO_IDX_START_SW;
port = CHV_IOSF_PORT_GPIO_SW;
} else if (gpio_index >= CHV_GPIO_IDX_START_E) {
gpio_index -= CHV_GPIO_IDX_START_E;
port = CHV_IOSF_PORT_GPIO_E;
} else {
port = CHV_IOSF_PORT_GPIO_N;
}
} else {
/* XXX: The spec is unclear about CHV GPIO on seq v2 */
if (gpio_source != 0) {
drm_dbg_kms(&dev_priv->drm,
"unknown gpio source %u\n", gpio_source);
return;
}
if (gpio_index >= CHV_GPIO_IDX_START_E) {
drm_dbg_kms(&dev_priv->drm,
"invalid gpio index %u for GPIO N\n",
gpio_index);
return;
}
port = CHV_IOSF_PORT_GPIO_N;
}
family_num = gpio_index / CHV_VBT_MAX_PINS_PER_FMLY;
gpio_index = gpio_index % CHV_VBT_MAX_PINS_PER_FMLY;
cfg0 = CHV_GPIO_PAD_CFG0(family_num, gpio_index);
cfg1 = CHV_GPIO_PAD_CFG1(family_num, gpio_index);
vlv_iosf_sb_get(dev_priv, BIT(VLV_IOSF_SB_GPIO));
vlv_iosf_sb_write(dev_priv, port, cfg1, 0);
vlv_iosf_sb_write(dev_priv, port, cfg0,
CHV_GPIO_GPIOEN | CHV_GPIO_GPIOCFG_GPO |
CHV_GPIO_GPIOTXSTATE(value));
vlv_iosf_sb_put(dev_priv, BIT(VLV_IOSF_SB_GPIO));
}
static void bxt_exec_gpio(struct drm_i915_private *dev_priv,
u8 gpio_source, u8 gpio_index, bool value)
{
/* XXX: this table is a quick ugly hack. */
static struct gpio_desc *bxt_gpio_table[U8_MAX + 1];
struct gpio_desc *gpio_desc = bxt_gpio_table[gpio_index];
if (!gpio_desc) {
gpio_desc = devm_gpiod_get_index(dev_priv->drm.dev,
NULL, gpio_index,
value ? GPIOD_OUT_LOW :
GPIOD_OUT_HIGH);
if (IS_ERR_OR_NULL(gpio_desc)) {
drm_err(&dev_priv->drm,
"GPIO index %u request failed (%ld)\n",
gpio_index, PTR_ERR(gpio_desc));
return;
}
bxt_gpio_table[gpio_index] = gpio_desc;
}
gpiod_set_value(gpio_desc, value);
}
static void icl_exec_gpio(struct drm_i915_private *dev_priv,
u8 gpio_source, u8 gpio_index, bool value)
{
drm_dbg_kms(&dev_priv->drm, "Skipping ICL GPIO element execution\n");
}
static const u8 *mipi_exec_gpio(struct intel_dsi *intel_dsi, const u8 *data)
{
struct drm_device *dev = intel_dsi->base.base.dev;
struct drm_i915_private *dev_priv = to_i915(dev);
u8 gpio_source, gpio_index = 0, gpio_number;
bool value;
drm_dbg_kms(&dev_priv->drm, "\n");
if (dev_priv->vbt.dsi.seq_version >= 3)
gpio_index = *data++;
gpio_number = *data++;
/* gpio source in sequence v2 only */
if (dev_priv->vbt.dsi.seq_version == 2)
gpio_source = (*data >> 1) & 3;
else
gpio_source = 0;
/* pull up/down */
value = *data++ & 1;
if (INTEL_GEN(dev_priv) >= 11)
icl_exec_gpio(dev_priv, gpio_source, gpio_index, value);
else if (IS_VALLEYVIEW(dev_priv))
vlv_exec_gpio(dev_priv, gpio_source, gpio_number, value);
else if (IS_CHERRYVIEW(dev_priv))
chv_exec_gpio(dev_priv, gpio_source, gpio_number, value);
else
bxt_exec_gpio(dev_priv, gpio_source, gpio_index, value);
return data;
}
#ifdef CONFIG_ACPI
static int i2c_adapter_lookup(struct acpi_resource *ares, void *data)
{
struct i2c_adapter_lookup *lookup = data;
struct intel_dsi *intel_dsi = lookup->intel_dsi;
struct acpi_resource_i2c_serialbus *sb;
struct i2c_adapter *adapter;
acpi_handle adapter_handle;
acpi_status status;
if (!i2c_acpi_get_i2c_resource(ares, &sb))
return 1;
if (lookup->slave_addr != sb->slave_address)
return 1;
status = acpi_get_handle(lookup->dev_handle,
sb->resource_source.string_ptr,
&adapter_handle);
if (ACPI_FAILURE(status))
return 1;
adapter = i2c_acpi_find_adapter_by_handle(adapter_handle);
if (adapter)
intel_dsi->i2c_bus_num = adapter->nr;
return 1;
}
static void i2c_acpi_find_adapter(struct intel_dsi *intel_dsi,
const u16 slave_addr)
{
struct drm_device *drm_dev = intel_dsi->base.base.dev;
struct device *dev = &drm_dev->pdev->dev;
struct acpi_device *acpi_dev;
struct list_head resource_list;
struct i2c_adapter_lookup lookup;
acpi_dev = ACPI_COMPANION(dev);
if (acpi_dev) {
memset(&lookup, 0, sizeof(lookup));
lookup.slave_addr = slave_addr;
lookup.intel_dsi = intel_dsi;
lookup.dev_handle = acpi_device_handle(acpi_dev);
INIT_LIST_HEAD(&resource_list);
acpi_dev_get_resources(acpi_dev, &resource_list,
i2c_adapter_lookup,
&lookup);
acpi_dev_free_resource_list(&resource_list);
}
}
#else
static inline void i2c_acpi_find_adapter(struct intel_dsi *intel_dsi,
const u16 slave_addr)
{
}
#endif
static const u8 *mipi_exec_i2c(struct intel_dsi *intel_dsi, const u8 *data)
{
struct drm_i915_private *i915 = to_i915(intel_dsi->base.base.dev);
struct i2c_adapter *adapter;
struct i2c_msg msg;
int ret;
u8 vbt_i2c_bus_num = *(data + 2);
u16 slave_addr = *(u16 *)(data + 3);
u8 reg_offset = *(data + 5);
u8 payload_size = *(data + 6);
u8 *payload_data;
if (intel_dsi->i2c_bus_num < 0) {
intel_dsi->i2c_bus_num = vbt_i2c_bus_num;
i2c_acpi_find_adapter(intel_dsi, slave_addr);
}
adapter = i2c_get_adapter(intel_dsi->i2c_bus_num);
if (!adapter) {
drm_err(&i915->drm, "Cannot find a valid i2c bus for xfer\n");
goto err_bus;
}
payload_data = kzalloc(payload_size + 1, GFP_KERNEL);
if (!payload_data)
goto err_alloc;
payload_data[0] = reg_offset;
memcpy(&payload_data[1], (data + 7), payload_size);
msg.addr = slave_addr;
msg.flags = 0;
msg.len = payload_size + 1;
msg.buf = payload_data;
ret = i2c_transfer(adapter, &msg, 1);
if (ret < 0)
drm_err(&i915->drm,
"Failed to xfer payload of size (%u) to reg (%u)\n",
payload_size, reg_offset);
kfree(payload_data);
err_alloc:
i2c_put_adapter(adapter);
err_bus:
return data + payload_size + 7;
}
static const u8 *mipi_exec_spi(struct intel_dsi *intel_dsi, const u8 *data)
{
struct drm_i915_private *i915 = to_i915(intel_dsi->base.base.dev);
drm_dbg_kms(&i915->drm, "Skipping SPI element execution\n");
return data + *(data + 5) + 6;
}
static const u8 *mipi_exec_pmic(struct intel_dsi *intel_dsi, const u8 *data)
{
struct drm_i915_private *i915 = to_i915(intel_dsi->base.base.dev);
#ifdef CONFIG_PMIC_OPREGION
u32 value, mask, reg_address;
u16 i2c_address;
int ret;
/* byte 0 aka PMIC Flag is reserved */
i2c_address = get_unaligned_le16(data + 1);
reg_address = get_unaligned_le32(data + 3);
value = get_unaligned_le32(data + 7);
mask = get_unaligned_le32(data + 11);
ret = intel_soc_pmic_exec_mipi_pmic_seq_element(i2c_address,
reg_address,
value, mask);
if (ret)
drm_err(&i915->drm, "%s failed, error: %d\n", __func__, ret);
#else
drm_err(&i915->drm,
"Your hardware requires CONFIG_PMIC_OPREGION and it is not set\n");
#endif
return data + 15;
}
typedef const u8 * (*fn_mipi_elem_exec)(struct intel_dsi *intel_dsi,
const u8 *data);
static const fn_mipi_elem_exec exec_elem[] = {
[MIPI_SEQ_ELEM_SEND_PKT] = mipi_exec_send_packet,
[MIPI_SEQ_ELEM_DELAY] = mipi_exec_delay,
[MIPI_SEQ_ELEM_GPIO] = mipi_exec_gpio,
[MIPI_SEQ_ELEM_I2C] = mipi_exec_i2c,
[MIPI_SEQ_ELEM_SPI] = mipi_exec_spi,
[MIPI_SEQ_ELEM_PMIC] = mipi_exec_pmic,
};
/*
* MIPI Sequence from VBT #53 parsing logic
* We have already separated each seqence during bios parsing
* Following is generic execution function for any sequence
*/
static const char * const seq_name[] = {
[MIPI_SEQ_DEASSERT_RESET] = "MIPI_SEQ_DEASSERT_RESET",
[MIPI_SEQ_INIT_OTP] = "MIPI_SEQ_INIT_OTP",
[MIPI_SEQ_DISPLAY_ON] = "MIPI_SEQ_DISPLAY_ON",
[MIPI_SEQ_DISPLAY_OFF] = "MIPI_SEQ_DISPLAY_OFF",
[MIPI_SEQ_ASSERT_RESET] = "MIPI_SEQ_ASSERT_RESET",
[MIPI_SEQ_BACKLIGHT_ON] = "MIPI_SEQ_BACKLIGHT_ON",
[MIPI_SEQ_BACKLIGHT_OFF] = "MIPI_SEQ_BACKLIGHT_OFF",
[MIPI_SEQ_TEAR_ON] = "MIPI_SEQ_TEAR_ON",
[MIPI_SEQ_TEAR_OFF] = "MIPI_SEQ_TEAR_OFF",
[MIPI_SEQ_POWER_ON] = "MIPI_SEQ_POWER_ON",
[MIPI_SEQ_POWER_OFF] = "MIPI_SEQ_POWER_OFF",
};
static const char *sequence_name(enum mipi_seq seq_id)
{
if (seq_id < ARRAY_SIZE(seq_name) && seq_name[seq_id])
return seq_name[seq_id];
else
return "(unknown)";
}
static void intel_dsi_vbt_exec(struct intel_dsi *intel_dsi,
enum mipi_seq seq_id)
{
struct drm_i915_private *dev_priv = to_i915(intel_dsi->base.base.dev);
const u8 *data;
fn_mipi_elem_exec mipi_elem_exec;
if (drm_WARN_ON(&dev_priv->drm,
seq_id >= ARRAY_SIZE(dev_priv->vbt.dsi.sequence)))
return;
data = dev_priv->vbt.dsi.sequence[seq_id];
if (!data)
return;
drm_WARN_ON(&dev_priv->drm, *data != seq_id);
drm_dbg_kms(&dev_priv->drm, "Starting MIPI sequence %d - %s\n",
seq_id, sequence_name(seq_id));
/* Skip Sequence Byte. */
data++;
/* Skip Size of Sequence. */
if (dev_priv->vbt.dsi.seq_version >= 3)
data += 4;
while (1) {
u8 operation_byte = *data++;
u8 operation_size = 0;
if (operation_byte == MIPI_SEQ_ELEM_END)
break;
if (operation_byte < ARRAY_SIZE(exec_elem))
mipi_elem_exec = exec_elem[operation_byte];
else
mipi_elem_exec = NULL;
/* Size of Operation. */
if (dev_priv->vbt.dsi.seq_version >= 3)
operation_size = *data++;
if (mipi_elem_exec) {
const u8 *next = data + operation_size;
data = mipi_elem_exec(intel_dsi, data);
/* Consistency check if we have size. */
if (operation_size && data != next) {
drm_err(&dev_priv->drm,
"Inconsistent operation size\n");
return;
}
} else if (operation_size) {
/* We have size, skip. */
drm_dbg_kms(&dev_priv->drm,
"Unsupported MIPI operation byte %u\n",
operation_byte);
data += operation_size;
} else {
/* No size, can't skip without parsing. */
drm_err(&dev_priv->drm,
"Unsupported MIPI operation byte %u\n",
operation_byte);
return;
}
}
}
void intel_dsi_vbt_exec_sequence(struct intel_dsi *intel_dsi,
enum mipi_seq seq_id)
{
if (seq_id == MIPI_SEQ_POWER_ON && intel_dsi->gpio_panel)
gpiod_set_value_cansleep(intel_dsi->gpio_panel, 1);
if (seq_id == MIPI_SEQ_BACKLIGHT_ON && intel_dsi->gpio_backlight)
gpiod_set_value_cansleep(intel_dsi->gpio_backlight, 1);
intel_dsi_vbt_exec(intel_dsi, seq_id);
if (seq_id == MIPI_SEQ_POWER_OFF && intel_dsi->gpio_panel)
gpiod_set_value_cansleep(intel_dsi->gpio_panel, 0);
if (seq_id == MIPI_SEQ_BACKLIGHT_OFF && intel_dsi->gpio_backlight)
gpiod_set_value_cansleep(intel_dsi->gpio_backlight, 0);
}
void intel_dsi_msleep(struct intel_dsi *intel_dsi, int msec)
{
struct drm_i915_private *dev_priv = to_i915(intel_dsi->base.base.dev);
/* For v3 VBTs in vid-mode the delays are part of the VBT sequences */
if (is_vid_mode(intel_dsi) && dev_priv->vbt.dsi.seq_version >= 3)
return;
msleep(msec);
}
void intel_dsi_log_params(struct intel_dsi *intel_dsi)
{
struct drm_i915_private *i915 = to_i915(intel_dsi->base.base.dev);
drm_dbg_kms(&i915->drm, "Pclk %d\n", intel_dsi->pclk);
drm_dbg_kms(&i915->drm, "Pixel overlap %d\n",
intel_dsi->pixel_overlap);
drm_dbg_kms(&i915->drm, "Lane count %d\n", intel_dsi->lane_count);
drm_dbg_kms(&i915->drm, "DPHY param reg 0x%x\n", intel_dsi->dphy_reg);
drm_dbg_kms(&i915->drm, "Video mode format %s\n",
intel_dsi->video_mode_format == VIDEO_MODE_NON_BURST_WITH_SYNC_PULSE ?
"non-burst with sync pulse" :
intel_dsi->video_mode_format == VIDEO_MODE_NON_BURST_WITH_SYNC_EVENTS ?
"non-burst with sync events" :
intel_dsi->video_mode_format == VIDEO_MODE_BURST ?
"burst" : "<unknown>");
drm_dbg_kms(&i915->drm, "Burst mode ratio %d\n",
intel_dsi->burst_mode_ratio);
drm_dbg_kms(&i915->drm, "Reset timer %d\n", intel_dsi->rst_timer_val);
drm_dbg_kms(&i915->drm, "Eot %s\n",
enableddisabled(intel_dsi->eotp_pkt));
drm_dbg_kms(&i915->drm, "Clockstop %s\n",
enableddisabled(!intel_dsi->clock_stop));
drm_dbg_kms(&i915->drm, "Mode %s\n",
intel_dsi->operation_mode ? "command" : "video");
if (intel_dsi->dual_link == DSI_DUAL_LINK_FRONT_BACK)
drm_dbg_kms(&i915->drm,
"Dual link: DSI_DUAL_LINK_FRONT_BACK\n");
else if (intel_dsi->dual_link == DSI_DUAL_LINK_PIXEL_ALT)
drm_dbg_kms(&i915->drm,
"Dual link: DSI_DUAL_LINK_PIXEL_ALT\n");
else
drm_dbg_kms(&i915->drm, "Dual link: NONE\n");
drm_dbg_kms(&i915->drm, "Pixel Format %d\n", intel_dsi->pixel_format);
drm_dbg_kms(&i915->drm, "TLPX %d\n", intel_dsi->escape_clk_div);
drm_dbg_kms(&i915->drm, "LP RX Timeout 0x%x\n",
intel_dsi->lp_rx_timeout);
drm_dbg_kms(&i915->drm, "Turnaround Timeout 0x%x\n",
intel_dsi->turn_arnd_val);
drm_dbg_kms(&i915->drm, "Init Count 0x%x\n", intel_dsi->init_count);
drm_dbg_kms(&i915->drm, "HS to LP Count 0x%x\n",
intel_dsi->hs_to_lp_count);
drm_dbg_kms(&i915->drm, "LP Byte Clock %d\n", intel_dsi->lp_byte_clk);
drm_dbg_kms(&i915->drm, "DBI BW Timer 0x%x\n", intel_dsi->bw_timer);
drm_dbg_kms(&i915->drm, "LP to HS Clock Count 0x%x\n",
intel_dsi->clk_lp_to_hs_count);
drm_dbg_kms(&i915->drm, "HS to LP Clock Count 0x%x\n",
intel_dsi->clk_hs_to_lp_count);
drm_dbg_kms(&i915->drm, "BTA %s\n",
enableddisabled(!(intel_dsi->video_frmt_cfg_bits & DISABLE_VIDEO_BTA)));
}
bool intel_dsi_vbt_init(struct intel_dsi *intel_dsi, u16 panel_id)
{
struct drm_device *dev = intel_dsi->base.base.dev;
struct drm_i915_private *dev_priv = to_i915(dev);
struct mipi_config *mipi_config = dev_priv->vbt.dsi.config;
struct mipi_pps_data *pps = dev_priv->vbt.dsi.pps;
struct drm_display_mode *mode = dev_priv->vbt.lfp_lvds_vbt_mode;
u16 burst_mode_ratio;
enum port port;
drm_dbg_kms(&dev_priv->drm, "\n");
intel_dsi->eotp_pkt = mipi_config->eot_pkt_disabled ? 0 : 1;
intel_dsi->clock_stop = mipi_config->enable_clk_stop ? 1 : 0;
intel_dsi->lane_count = mipi_config->lane_cnt + 1;
intel_dsi->pixel_format =
pixel_format_from_register_bits(
mipi_config->videomode_color_format << 7);
intel_dsi->dual_link = mipi_config->dual_link;
intel_dsi->pixel_overlap = mipi_config->pixel_overlap;
intel_dsi->operation_mode = mipi_config->is_cmd_mode;
intel_dsi->video_mode_format = mipi_config->video_transfer_mode;
intel_dsi->escape_clk_div = mipi_config->byte_clk_sel;
intel_dsi->lp_rx_timeout = mipi_config->lp_rx_timeout;
intel_dsi->hs_tx_timeout = mipi_config->hs_tx_timeout;
intel_dsi->turn_arnd_val = mipi_config->turn_around_timeout;
intel_dsi->rst_timer_val = mipi_config->device_reset_timer;
intel_dsi->init_count = mipi_config->master_init_timer;
intel_dsi->bw_timer = mipi_config->dbi_bw_timer;
intel_dsi->video_frmt_cfg_bits =
mipi_config->bta_enabled ? DISABLE_VIDEO_BTA : 0;
intel_dsi->bgr_enabled = mipi_config->rgb_flip;
/* Starting point, adjusted depending on dual link and burst mode */
intel_dsi->pclk = mode->clock;
/* In dual link mode each port needs half of pixel clock */
if (intel_dsi->dual_link) {
intel_dsi->pclk /= 2;
/* we can enable pixel_overlap if needed by panel. In this
* case we need to increase the pixelclock for extra pixels
*/
if (intel_dsi->dual_link == DSI_DUAL_LINK_FRONT_BACK) {
intel_dsi->pclk += DIV_ROUND_UP(mode->vtotal * intel_dsi->pixel_overlap * 60, 1000);
}
}
/* Burst Mode Ratio
* Target ddr frequency from VBT / non burst ddr freq
* multiply by 100 to preserve remainder
*/
if (intel_dsi->video_mode_format == VIDEO_MODE_BURST) {
if (mipi_config->target_burst_mode_freq) {
u32 bitrate = intel_dsi_bitrate(intel_dsi);
/*
* Sometimes the VBT contains a slightly lower clock,
* then the bitrate we have calculated, in this case
* just replace it with the calculated bitrate.
*/
if (mipi_config->target_burst_mode_freq < bitrate &&
intel_fuzzy_clock_check(
mipi_config->target_burst_mode_freq,
bitrate))
mipi_config->target_burst_mode_freq = bitrate;
if (mipi_config->target_burst_mode_freq < bitrate) {
drm_err(&dev_priv->drm,
"Burst mode freq is less than computed\n");
return false;
}
burst_mode_ratio = DIV_ROUND_UP(
mipi_config->target_burst_mode_freq * 100,
bitrate);
intel_dsi->pclk = DIV_ROUND_UP(intel_dsi->pclk * burst_mode_ratio, 100);
} else {
drm_err(&dev_priv->drm,
"Burst mode target is not set\n");
return false;
}
} else
burst_mode_ratio = 100;
intel_dsi->burst_mode_ratio = burst_mode_ratio;
/* delays in VBT are in unit of 100us, so need to convert
* here in ms
* Delay (100us) * 100 /1000 = Delay / 10 (ms) */
intel_dsi->backlight_off_delay = pps->bl_disable_delay / 10;
intel_dsi->backlight_on_delay = pps->bl_enable_delay / 10;
intel_dsi->panel_on_delay = pps->panel_on_delay / 10;
intel_dsi->panel_off_delay = pps->panel_off_delay / 10;
intel_dsi->panel_pwr_cycle_delay = pps->panel_power_cycle_delay / 10;
intel_dsi->i2c_bus_num = -1;
/* a regular driver would get the device in probe */
for_each_dsi_port(port, intel_dsi->ports) {
mipi_dsi_attach(intel_dsi->dsi_hosts[port]->device);
}
return true;
}
/*
* On some BYT/CHT devs some sequences are incomplete and we need to manually
* control some GPIOs. We need to add a GPIO lookup table before we get these.
* If the GOP did not initialize the panel (HDMI inserted) we may need to also
* change the pinmux for the SoC's PWM0 pin from GPIO to PWM.
*/
static struct gpiod_lookup_table pmic_panel_gpio_table = {
/* Intel GFX is consumer */
.dev_id = "0000:00:02.0",
.table = {
/* Panel EN/DISABLE */
GPIO_LOOKUP("gpio_crystalcove", 94, "panel", GPIO_ACTIVE_HIGH),
{ }
},
};
static struct gpiod_lookup_table soc_panel_gpio_table = {
.dev_id = "0000:00:02.0",
.table = {
GPIO_LOOKUP("INT33FC:01", 10, "backlight", GPIO_ACTIVE_HIGH),
GPIO_LOOKUP("INT33FC:01", 11, "panel", GPIO_ACTIVE_HIGH),
{ }
},
};
static const struct pinctrl_map soc_pwm_pinctrl_map[] = {
PIN_MAP_MUX_GROUP("0000:00:02.0", "soc_pwm0", "INT33FC:00",
"pwm0_grp", "pwm"),
};
void intel_dsi_vbt_gpio_init(struct intel_dsi *intel_dsi, bool panel_is_on)
{
struct drm_device *dev = intel_dsi->base.base.dev;
struct drm_i915_private *dev_priv = to_i915(dev);
struct mipi_config *mipi_config = dev_priv->vbt.dsi.config;
enum gpiod_flags flags = panel_is_on ? GPIOD_OUT_HIGH : GPIOD_OUT_LOW;
bool want_backlight_gpio = false;
bool want_panel_gpio = false;
struct pinctrl *pinctrl;
int ret;
if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
mipi_config->pwm_blc == PPS_BLC_PMIC) {
gpiod_add_lookup_table(&pmic_panel_gpio_table);
want_panel_gpio = true;
}
if (IS_VALLEYVIEW(dev_priv) && mipi_config->pwm_blc == PPS_BLC_SOC) {
gpiod_add_lookup_table(&soc_panel_gpio_table);
want_panel_gpio = true;
want_backlight_gpio = true;
/* Ensure PWM0 pin is muxed as PWM instead of GPIO */
ret = pinctrl_register_mappings(soc_pwm_pinctrl_map,
ARRAY_SIZE(soc_pwm_pinctrl_map));
if (ret)
drm_err(&dev_priv->drm,
"Failed to register pwm0 pinmux mapping\n");
pinctrl = devm_pinctrl_get_select(dev->dev, "soc_pwm0");
if (IS_ERR(pinctrl))
drm_err(&dev_priv->drm,
"Failed to set pinmux to PWM\n");
}
if (want_panel_gpio) {
intel_dsi->gpio_panel = gpiod_get(dev->dev, "panel", flags);
if (IS_ERR(intel_dsi->gpio_panel)) {
drm_err(&dev_priv->drm,
"Failed to own gpio for panel control\n");
intel_dsi->gpio_panel = NULL;
}
}
if (want_backlight_gpio) {
intel_dsi->gpio_backlight =
gpiod_get(dev->dev, "backlight", flags);
if (IS_ERR(intel_dsi->gpio_backlight)) {
drm_err(&dev_priv->drm,
"Failed to own gpio for backlight control\n");
intel_dsi->gpio_backlight = NULL;
}
}
}
void intel_dsi_vbt_gpio_cleanup(struct intel_dsi *intel_dsi)
{
struct drm_device *dev = intel_dsi->base.base.dev;
struct drm_i915_private *dev_priv = to_i915(dev);
struct mipi_config *mipi_config = dev_priv->vbt.dsi.config;
if (intel_dsi->gpio_panel) {
gpiod_put(intel_dsi->gpio_panel);
intel_dsi->gpio_panel = NULL;
}
if (intel_dsi->gpio_backlight) {
gpiod_put(intel_dsi->gpio_backlight);
intel_dsi->gpio_backlight = NULL;
}
if ((IS_VALLEYVIEW(dev_priv) || IS_CHERRYVIEW(dev_priv)) &&
mipi_config->pwm_blc == PPS_BLC_PMIC)
gpiod_remove_lookup_table(&pmic_panel_gpio_table);
if (IS_VALLEYVIEW(dev_priv) && mipi_config->pwm_blc == PPS_BLC_SOC) {
pinctrl_unregister_mappings(soc_pwm_pinctrl_map);
gpiod_remove_lookup_table(&soc_panel_gpio_table);
}
}
| {
"pile_set_name": "Github"
} |
import * as PropTypes from 'prop-types';
import * as React from 'react';
export const SomeShape = PropTypes.shape({});
/**
* A repro props interface
*/
export interface ExportsPropTypesProps {
/** foo description */
foo: any;
}
/**
* ExportsPropTypes description
*/
export class ExportsPropTypes extends React.Component<
ExportsPropTypesProps,
{}
> {
render() {
return <div />;
}
}
| {
"pile_set_name": "Github"
} |
/* Luxembourgish initialisation for the jQuery UI date picker plugin. */
/* Written by Michel Weimerskirch <[email protected]> */
jQuery(function($){
$.datepicker.regional['lb'] = {
closeText: 'Fäerdeg',
prevText: 'Zréck',
nextText: 'Weider',
currentText: 'Haut',
monthNames: ['Januar','Februar','Mäerz','Abrëll','Mee','Juni',
'Juli','August','September','Oktober','November','Dezember'],
monthNamesShort: ['Jan', 'Feb', 'Mäe', 'Abr', 'Mee', 'Jun',
'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Dez'],
dayNames: ['Sonndeg', 'Méindeg', 'Dënschdeg', 'Mëttwoch', 'Donneschdeg', 'Freideg', 'Samschdeg'],
dayNamesShort: ['Son', 'Méi', 'Dën', 'Mët', 'Don', 'Fre', 'Sam'],
dayNamesMin: ['So','Mé','Dë','Më','Do','Fr','Sa'],
weekHeader: 'W',
dateFormat: 'dd.mm.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''};
$.datepicker.setDefaults($.datepicker.regional['lb']);
});
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2016 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker 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.
*
* Loop Habit Tracker 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/>.
*/
package org.isoron.uhabits.widgets;
import android.app.*;
import android.content.*;
import android.graphics.*;
import android.view.*;
import android.widget.*;
import androidx.annotation.NonNull;
import org.isoron.uhabits.*;
import org.isoron.uhabits.core.preferences.*;
import org.isoron.uhabits.intents.*;
import static android.view.View.MeasureSpec.makeMeasureSpec;
public abstract class BaseWidget
{
private final int id;
@NonNull
protected final WidgetPreferences widgetPrefs;
@NonNull
protected final Preferences prefs;
@NonNull
protected final PendingIntentFactory pendingIntentFactory;
@NonNull
private final Context context;
@NonNull
private WidgetDimensions dimensions;
public BaseWidget(@NonNull Context context, int id)
{
this.id = id;
this.context = context;
HabitsApplication app =
(HabitsApplication) context.getApplicationContext();
widgetPrefs = app.getComponent().getWidgetPreferences();
prefs = app.getComponent().getPreferences();
pendingIntentFactory = app.getComponent().getPendingIntentFactory();
dimensions = new WidgetDimensions(getDefaultWidth(), getDefaultHeight(),
getDefaultWidth(), getDefaultHeight());
}
public void delete()
{
widgetPrefs.removeWidget(id);
}
@NonNull
public Context getContext()
{
return context;
}
public int getId()
{
return id;
}
@NonNull
public RemoteViews getLandscapeRemoteViews()
{
return getRemoteViews(dimensions.getLandscapeWidth(),
dimensions.getLandscapeHeight());
}
public abstract PendingIntent getOnClickPendingIntent(Context context);
@NonNull
public RemoteViews getPortraitRemoteViews()
{
return getRemoteViews(dimensions.getPortraitWidth(),
dimensions.getPortraitHeight());
}
public abstract void refreshData(View widgetView);
public void setDimensions(@NonNull WidgetDimensions dimensions)
{
this.dimensions = dimensions;
}
protected abstract View buildView();
protected abstract int getDefaultHeight();
protected abstract int getDefaultWidth();
private void adjustRemoteViewsPadding(RemoteViews remoteViews,
View view,
int width,
int height)
{
int imageWidth = view.getMeasuredWidth();
int imageHeight = view.getMeasuredHeight();
int p[] = calculatePadding(width, height, imageWidth, imageHeight);
remoteViews.setViewPadding(R.id.buttonOverlay, p[0], p[1], p[2], p[3]);
}
private void buildRemoteViews(View view,
RemoteViews remoteViews,
int width,
int height)
{
Bitmap bitmap = getBitmapFromView(view);
remoteViews.setImageViewBitmap(R.id.imageView, bitmap);
adjustRemoteViewsPadding(remoteViews, view, width, height);
PendingIntent onClickIntent = getOnClickPendingIntent(context);
if (onClickIntent != null)
remoteViews.setOnClickPendingIntent(R.id.button, onClickIntent);
}
private int[] calculatePadding(int entireWidth,
int entireHeight,
int imageWidth,
int imageHeight)
{
int w = (int) (((float) entireWidth - imageWidth) / 2);
int h = (int) (((float) entireHeight - imageHeight) / 2);
return new int[]{w, h, w, h};
}
@NonNull
private Bitmap getBitmapFromView(View view)
{
view.invalidate();
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
view.draw(canvas);
return bitmap;
}
@NonNull
protected RemoteViews getRemoteViews(int width, int height)
{
View view = buildView();
measureView(view, width, height);
refreshData(view);
if (view.isLayoutRequested()) measureView(view, width, height);
RemoteViews remoteViews =
new RemoteViews(context.getPackageName(), R.layout.widget_wrapper);
buildRemoteViews(view, remoteViews, width, height);
return remoteViews;
}
private void measureView(View view, int width, int height)
{
LayoutInflater inflater = LayoutInflater.from(context);
View entireView = inflater.inflate(R.layout.widget_wrapper, null);
int specWidth = makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int specHeight = makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
entireView.measure(specWidth, specHeight);
entireView.layout(0, 0, entireView.getMeasuredWidth(),
entireView.getMeasuredHeight());
View imageView = entireView.findViewById(R.id.imageView);
width = imageView.getMeasuredWidth();
height = imageView.getMeasuredHeight();
specWidth = makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
specHeight = makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
view.measure(specWidth, specHeight);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
}
protected int getPreferedBackgroundAlpha() {
return prefs.getWidgetOpacity();
}
}
| {
"pile_set_name": "Github"
} |
<div>{{> abc/def/ghi/test}}</div>
| {
"pile_set_name": "Github"
} |
# Use the latest 2.1 version of CircleCI pipeline processing engine, see https://circleci.com/docs/2.0/configuration-reference/
version: 2.1
# Use a package of configuration called an orb, see https://circleci.com/docs/2.0/orb-intro/
orbs:
# Declare a dependency on the welcome-orb
welcome: circleci/[email protected]
# Orchestrate or schedule a set of jobs, see https://circleci.com/docs/2.0/workflows/
workflows:
# Name the workflow "Welcome"
Welcome:
# Run the welcome/run job in its own container
jobs:
- welcome/run
| {
"pile_set_name": "Github"
} |
<?php
namespace Drupal\layout_builder\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\layout_builder\Plugin\SectionStorage\SectionStorageLocalTaskProviderInterface;
use Drupal\layout_builder\SectionStorage\SectionStorageManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides local task definitions for the layout builder user interface.
*
* @todo Remove this in https://www.drupal.org/project/drupal/issues/2936655.
*
* @internal
* Plugin derivers are internal.
*/
class LayoutBuilderLocalTaskDeriver extends DeriverBase implements ContainerDeriverInterface {
use StringTranslationTrait;
/**
* The entity type manager.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The section storage manager.
*
* @var \Drupal\layout_builder\SectionStorage\SectionStorageManagerInterface
*/
protected $sectionStorageManager;
/**
* Constructs a new LayoutBuilderLocalTaskDeriver.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\layout_builder\SectionStorage\SectionStorageManagerInterface $section_storage_manager
* The section storage manager.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, SectionStorageManagerInterface $section_storage_manager) {
$this->entityTypeManager = $entity_type_manager;
$this->sectionStorageManager = $section_storage_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static(
$container->get('entity_type.manager'),
$container->get('plugin.manager.layout_builder.section_storage')
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
foreach ($this->sectionStorageManager->getDefinitions() as $plugin_id => $definition) {
$section_storage = $this->sectionStorageManager->loadEmpty($plugin_id);
if ($section_storage instanceof SectionStorageLocalTaskProviderInterface) {
$this->derivatives += $section_storage->buildLocalTasks($base_plugin_definition);
}
}
return $this->derivatives;
}
}
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the Prophecy.
* (c) Konstantin Kudryashov <[email protected]>
* Marcello Duarte <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Prophecy\Argument\Token;
use Prophecy\Util\StringUtil;
/**
* Identical value token.
*
* @author Florian Voutzinos <[email protected]>
*/
class IdenticalValueToken implements TokenInterface
{
private $value;
private $string;
private $util;
/**
* Initializes token.
*
* @param mixed $value
* @param StringUtil $util
*/
public function __construct($value, StringUtil $util = null)
{
$this->value = $value;
$this->util = $util ?: new StringUtil();
}
/**
* Scores 11 if argument matches preset value.
*
* @param $argument
*
* @return bool|int
*/
public function scoreArgument($argument)
{
return $argument === $this->value ? 11 : false;
}
/**
* Returns false.
*
* @return bool
*/
public function isLast()
{
return false;
}
/**
* Returns string representation for token.
*
* @return string
*/
public function __toString()
{
if (null === $this->string) {
$this->string = sprintf('identical(%s)', $this->util->stringify($this->value));
}
return $this->string;
}
}
| {
"pile_set_name": "Github"
} |
package com.mg.axechen.wanandroid.javabean
import com.chad.library.adapter.base.entity.MultiItemEntity
/**
* Created by AxeChen on 2018/4/10.
*/
class SearchViewType(private var itemType: Int, var item: Any?) : MultiItemEntity {
fun setItemType(itemType: Int) {
this.itemType = itemType
}
override fun getItemType(): Int {
return itemType
}
companion object {
val VIEW_TYPE_SELECTION = 0
val VIEW_TYPE_HISTORY = 1
val VIEW_TYPE_RECOMMEND = 2
val VIEW_TYPE_RESULT = 3
val VIEW_TYPE_HISTORY_SELECTION = 4
}
}
| {
"pile_set_name": "Github"
} |
## 解析动态内容
根据权威机构发布的全球互联网可访问性审计报告,全球约有四分之三的网站其内容或部分内容是通过JavaScript动态生成的,这就意味着在浏览器窗口中“查看网页源代码”时无法在HTML代码中找到这些内容,也就是说我们之前用的抓取数据的方式无法正常运转了。解决这样的问题基本上有两种方案,一是JavaScript逆向工程;另一种是渲染JavaScript获得渲染后的内容。
### JavaScript逆向工程
下面我们以“360图片”网站为例,说明什么是JavaScript逆向工程。其实所谓的JavaScript逆向工程就是找到通过Ajax技术动态获取数据的接口。在浏览器中输入<http://image.so.com/z?ch=beauty>就可以打开“360图片”的“美女”版块,如下图所示。

但是当我们在浏览器中通过右键菜单“显示网页源代码”的时候,居然惊奇的发现页面的HTML代码中连一个`<img>`标签都没有,那么我们看到的图片是怎么显示出来的呢?原来所有的图片都是通过JavaScript动态加载的,而在浏览器的“开发人员工具”的“网络”中可以找到获取这些图片数据的网络API接口,如下图所示。

那么结论就很简单了,只要我们找到了这些网络API接口,那么就能通过这些接口获取到数据,当然实际开发的时候可能还要对这些接口的参数以及接口返回的数据进行分析,了解每个参数的意义以及返回的JSON数据的格式,这样才能在我们的爬虫中使用这些数据。
### 使用Selenium
尽管很多网站对自己的网络API接口进行了保护,增加了获取数据的难度,但是只要经过足够的努力,绝大多数还是可以被逆向工程的,但是在实际开发中,我们可以通过浏览器渲染引擎来避免这些繁琐的工作,WebKit就是一个利用的渲染引擎。
WebKit的代码始于1998年的KHTML项目,当时它是Konqueror浏览器的渲染引擎。2001年,苹果公司从这个项目的代码中衍生出了WebKit并应用于Safari浏览器,早期的Chrome浏览器也使用了该内核。在Python中,我们可以通过Qt框架获得WebKit引擎并使用它来渲染页面获得动态内容,关于这个内容请大家自行阅读[《爬虫技术:动态页面抓取超级指南》](http://python.jobbole.com/84600/)一文。
如果没有打算用上面所说的方式来渲染页面并获得动态内容,其实还有一种替代方案就是使用自动化测试工具Selenium,它提供了浏览器自动化的API接口,这样就可以通过操控浏览器来获取动态内容。首先可以使用pip来安装Selenium。
```Shell
pip3 install selenium
```
下面以“阿里V任务”的“直播服务”为例,来演示如何使用Selenium获取到动态内容并抓取主播图片。
```Python
import requests
from bs4 import BeautifulSoup
def main():
resp = requests.get('https://v.taobao.com/v/content/live?catetype=704&from=taonvlang')
soup = BeautifulSoup(resp.text, 'lxml')
for img_tag in soup.select('img[src]'):
print(img_tag.attrs['src'])
if __name__ == '__main__':
main()
```
运行上面的程序会发现没有任何的输出,因为页面的HTML代码上根本找不到`<img>`标签。接下来我们使用Selenium来获取到页面上的动态内容,再提取主播图片。
```Python
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
def main():
driver = webdriver.Chrome()
driver.get('https://v.taobao.com/v/content/live?catetype=704&from=taonvlang')
soup = BeautifulSoup(driver.page_source, 'lxml')
for img_tag in soup.body.select('img[src]'):
print(img_tag.attrs['src'])
if __name__ == '__main__':
main()
```
在上面的程序中,我们通过Selenium实现对Chrome浏览器的操控,如果要操控其他的浏览器,可以创对应的浏览器对象,例如Firefox、IE等。运行上面的程序,如果看到如下所示的错误提示,那是说明我们还没有将Chrome浏览器的驱动添加到PATH环境变量中,也没有在程序中指定Chrome浏览器驱动所在的位置。
```Shell
selenium.common.exceptions.WebDriverException: Message: 'chromedriver' executable needs to be in PATH. Please see https://sites.google.com/a/chromium.org/chromedriver/home
```
为了解决上面的问题,可以到Selenium的[官方网站](https://www.seleniumhq.org)找到浏览器驱动的下载链接并下载需要的驱动,在Linux或macOS系统下可以通过下面的命令来设置PATH环境变量,Windows下配置环境变量也非常简单,不清楚的可以自行了解。
```Shell
export PATH=$PATH:/Users/Hao/Downloads/Tools/chromedriver/
```
其中`/Users/Hao/Downloads/Tools/chromedriver/ `就是chromedriver所在的路径。当然,更为简单的办法是把chromedriver直接放在虚拟环境中,跟Python解释器位于同一个路径下就可以了。
### WebDriver用法详解
表1. 定位页面元素的方法
表2. WebDriver的常用属性
| 属性 | 描述 |
| --------------------- | ----------------------------- |
| current_url | 当前页面的URL |
| current_window_handle | 当前窗口的句柄(引用) |
| name | WebDriver实例底层浏览器的名称 |
| orientation | 当前设备的方向(横屏、竖屏) |
| page_source | 当前页面的源代码(动态内容) |
| title | 当前页面的标题 |
| window_handles | WebDriver打开的所有窗口的句柄 |
表3. WebDriver的常用方法
| 方法 | 描述 |
| ----------------------------------- | -------------------------------------- |
| back() / forward() | 在浏览历史记录中后退/前进 |
| close() / quit() | 关闭当前浏览器窗口 / 退出WebDriver实例 |
| get(url) | 加载指定URL的页面到浏览器中 |
| maximize_window() | 将浏览器窗口最大化 |
| refresh() | 刷新当前页面 |
| switch_to_active_element() | 获得页面上得到焦点的元素 |
| switch_to_alert() | 把焦点切换至弹出的警告框 |
| set_page_load_timeout(time_to_wait) | 设置页面加载超时时间 |
| set_script_timeout(time_to_wait) | 设置JavaScript执行超时时间 |
| implicit_wait(time_to_wait) | 设置等待元素被找到或目标指令完成 |
### WebElement用法
表1. WebElement常用属性
| | |
| ---- | ---- |
| | |
| | |
| | |
表2. WebElement常用方法
| | |
| ---- | ---- |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
| | |
### Select用法
### Alert用法
### 元素等待机制
#### 隐式等待
#### 显示等待
### 高级特性
#### 鼠标和键盘事件
#### 调用JavaScript
#### 屏幕截图和录制
#### 操作Cookie
| {
"pile_set_name": "Github"
} |
import Argo
import Curry
import Runes
public struct Backing {
public let addOns: [Reward]?
public let amount: Double
public let backer: User?
public let backerId: Int
public let backerCompleted: Bool?
public let bonusAmount: Double
public let cancelable: Bool
public let id: Int
public let locationId: Int?
public let locationName: String?
public let paymentSource: PaymentSource?
public let pledgedAt: TimeInterval
public let projectCountry: String
public let projectId: Int
public let reward: Reward?
public let rewardId: Int?
public let sequence: Int
public let shippingAmount: Int?
public let status: Status
public struct PaymentSource {
public var expirationDate: String?
public var id: String?
public var lastFour: String?
public var paymentType: PaymentType
public var state: String
public var type: CreditCardType?
}
public enum Status: String, CaseIterable {
case canceled
case collected
case dropped
case errored
case pledged
case preauth
}
}
extension Backing: Equatable {}
public func == (lhs: Backing, rhs: Backing) -> Bool {
return lhs.id == rhs.id
}
extension Backing: Argo.Decodable {
public static func decode(_ json: JSON) -> Decoded<Backing> {
let tmp1 = curry(Backing.init)
<^> json <||? "add_ons"
<*> json <| "amount"
<*> json <|? "backer"
<*> json <| "backer_id"
<*> json <|? "backer_completed_at"
<*> (json <| "bonus_amount" <|> .success(0.0))
<*> json <| "cancelable"
let tmp2 = tmp1
<*> json <| "id"
<*> json <|? "location_id"
<*> json <|? "location_name"
<*> (json <|? "payment_source" >>- tryDecodePaymentSource)
<*> json <| "pledged_at"
<*> json <| "project_country"
return tmp2
<*> json <| "project_id"
<*> json <|? "reward"
<*> json <|? "reward_id"
<*> json <| "sequence"
<*> json <|? "shipping_amount"
<*> json <| "status"
}
}
#warning("Function tryDecodePaymentSource(_:) should be deleted once the data is being returned normally.")
/*
Since staging is not returning all the values for Payment Source, the Backing deserialization is failing
on that environment. This is a workaround to allow us to test on Staging and should be deleted once the
data is being returned normally.
*/
private func tryDecodePaymentSource(_ json: JSON?) -> Decoded<Backing.PaymentSource?> {
guard let json = json else {
return .success(nil)
}
let value = Backing.PaymentSource.decode(json)
switch value {
case let .success(value):
return .success(value)
case .failure:
return .success(nil)
}
}
extension Backing: EncodableType {
public func encode() -> [String: Any] {
var result: [String: Any] = [:]
result["backer_completed_at"] = self.backerCompleted
return result
}
}
extension Backing.PaymentSource: Argo.Decodable {
public static func decode(_ json: JSON) -> Decoded<Backing.PaymentSource?> {
return curry(Backing.PaymentSource.init)
<^> json <|? "expiration_date"
<*> json <|? "id"
<*> json <|? "last_four"
<*> json <| "payment_type"
<*> json <| "state"
<*> json <|? "type"
}
}
extension Backing.Status: Argo.Decodable {}
extension Backing.PaymentSource: Equatable {}
public func == (lhs: Backing.PaymentSource, rhs: Backing.PaymentSource) -> Bool {
return lhs.id == rhs.id
}
extension Backing: GraphIDBridging {
public static var modelName: String {
return "Backing"
}
}
| {
"pile_set_name": "Github"
} |
{
"start_time": 1569910014242,
"end_time": 1569910319313,
"observation_time": 305,
"database_type": "postgres",
"database_version": "9.6",
"workload_name": "tpcc"
}
| {
"pile_set_name": "Github"
} |
/* Webcamoid, webcam capture application.
* Copyright (C) 2016 Gonzalo Exequiel Pedone
*
* Webcamoid 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.
*
* Webcamoid 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 Webcamoid. If not, see <http://www.gnu.org/licenses/>.
*
* Web-Site: http://webcamoid.github.io/
*/
#ifndef PLUGIN_H
#define PLUGIN_H
#include <akplugin.h>
class Plugin: public QObject, public AkPlugin
{
Q_OBJECT
Q_INTERFACES(AkPlugin)
Q_PLUGIN_METADATA(IID "org.avkys.plugin" FILE "pspec.json")
public:
QObject *create(const QString &key, const QString &specification);
QStringList keys() const;
};
#endif // PLUGIN_H
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf8">
<title>Test for the network actor (GET request)</title>
<script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
<script type="text/javascript;version=1.8" src="common.js"></script>
<!-- Any copyright is dedicated to the Public Domain.
- http://creativecommons.org/publicdomain/zero/1.0/ -->
</head>
<body>
<p>Test for the network actor (GET request)</p>
<iframe src="http://example.com/chrome/toolkit/devtools/webconsole/test/network_requests_iframe.html"></iframe>
<script class="testbody" type="text/javascript;version=1.8">
SimpleTest.waitForExplicitFinish();
function startTest()
{
removeEventListener("load", startTest);
attachConsole(["NetworkActivity"], onAttach, true);
}
function onAttach(aState, aResponse)
{
info("test network GET request");
onNetworkEvent = onNetworkEvent.bind(null, aState);
aState.dbgClient.addListener("networkEvent", onNetworkEvent);
onNetworkEventUpdate = onNetworkEventUpdate.bind(null, aState);
aState.dbgClient.addListener("networkEventUpdate", onNetworkEventUpdate);
let iframe = document.querySelector("iframe").contentWindow;
iframe.wrappedJSObject.testXhrGet();
}
function onNetworkEvent(aState, aType, aPacket)
{
is(aPacket.from, aState.actor, "network event actor");
info("checking the network event packet");
let netActor = aPacket.eventActor;
checkObject(netActor, {
actor: /[a-z]/,
startedDateTime: /^\d+\-\d+\-\d+T.+$/,
url: /data\.json/,
method: "GET",
});
aState.netActor = netActor.actor;
aState.dbgClient.removeListener("networkEvent", onNetworkEvent);
}
let updates = [];
function onNetworkEventUpdate(aState, aType, aPacket)
{
info("received networkEventUpdate " + aPacket.updateType);
is(aPacket.from, aState.netActor, "networkEventUpdate actor");
updates.push(aPacket.updateType);
let expectedPacket = null;
switch (aPacket.updateType) {
case "requestHeaders":
case "responseHeaders":
ok(aPacket.headers > 0, "headers > 0");
ok(aPacket.headersSize > 0, "headersSize > 0");
break;
case "requestCookies":
expectedPacket = {
cookies: 3,
};
break;
case "requestPostData":
ok(false, "got unexpected requestPostData");
break;
case "responseStart":
expectedPacket = {
response: {
httpVersion: /^HTTP\/\d\.\d$/,
status: 200,
statusText: "OK",
headersSize: /^\d+$/,
discardResponseBody: true,
},
};
break;
case "responseCookies":
expectedPacket = {
cookies: 0,
};
break;
case "responseContent":
expectedPacket = {
mimeType: "application/json",
contentSize: 0,
discardResponseBody: true,
};
break;
case "eventTimings":
expectedPacket = {
totalTime: /^\d+$/,
};
break;
default:
ok(false, "unknown network event update type: " +
aPacket.updateType);
return;
}
if (expectedPacket) {
info("checking the packet content");
checkObject(aPacket, expectedPacket);
}
if (updates.indexOf("responseContent") > -1 &&
updates.indexOf("eventTimings") > -1) {
aState.dbgClient.removeListener("networkEventUpdate",
onNetworkEvent);
onRequestHeaders = onRequestHeaders.bind(null, aState);
aState.client.getRequestHeaders(aState.netActor,
onRequestHeaders);
}
}
function onRequestHeaders(aState, aResponse)
{
info("checking request headers");
ok(aResponse.headers.length > 0, "request headers > 0");
ok(aResponse.headersSize > 0, "request headersSize > 0");
checkHeadersOrCookies(aResponse.headers, {
Referer: /network_requests_iframe\.html/,
Cookie: /bug768096/,
});
onRequestCookies = onRequestCookies.bind(null, aState);
aState.client.getRequestCookies(aState.netActor,
onRequestCookies);
}
function onRequestCookies(aState, aResponse)
{
info("checking request cookies");
is(aResponse.cookies.length, 3, "request cookies length");
checkHeadersOrCookies(aResponse.cookies, {
foobar: "fooval",
omgfoo: "bug768096",
badcookie: "bug826798=st3fan",
});
onRequestPostData = onRequestPostData.bind(null, aState);
aState.client.getRequestPostData(aState.netActor,
onRequestPostData);
}
function onRequestPostData(aState, aResponse)
{
info("checking request POST data");
ok(!aResponse.postData.text, "no request POST data");
ok(aResponse.postDataDiscarded, "request POST data was discarded");
onResponseHeaders = onResponseHeaders.bind(null, aState);
aState.client.getResponseHeaders(aState.netActor,
onResponseHeaders);
}
function onResponseHeaders(aState, aResponse)
{
info("checking response headers");
ok(aResponse.headers.length > 0, "response headers > 0");
ok(aResponse.headersSize > 0, "response headersSize > 0");
checkHeadersOrCookies(aResponse.headers, {
"Content-Type": /^application\/(json|octet-stream)$/,
"Content-Length": /^\d+$/,
});
onResponseCookies = onResponseCookies.bind(null, aState);
aState.client.getResponseCookies(aState.netActor,
onResponseCookies);
}
function onResponseCookies(aState, aResponse)
{
info("checking response cookies");
is(aResponse.cookies.length, 0, "response cookies length");
onResponseContent = onResponseContent.bind(null, aState);
aState.client.getResponseContent(aState.netActor,
onResponseContent);
}
function onResponseContent(aState, aResponse)
{
info("checking response content");
ok(!aResponse.content.text, "no response content");
ok(aResponse.contentDiscarded, "response content was discarded");
onEventTimings = onEventTimings.bind(null, aState);
aState.client.getEventTimings(aState.netActor,
onEventTimings);
}
function onEventTimings(aState, aResponse)
{
info("checking event timings");
checkObject(aResponse, {
timings: {
blocked: /^-1|\d+$/,
dns: /^-1|\d+$/,
connect: /^-1|\d+$/,
send: /^-1|\d+$/,
wait: /^-1|\d+$/,
receive: /^-1|\d+$/,
},
totalTime: /^\d+$/,
});
closeDebugger(aState, function() {
SimpleTest.finish();
});
}
addEventListener("load", startTest);
</script>
</body>
</html>
| {
"pile_set_name": "Github"
} |
using UnityEngine;
/// <summary>
/// Dummy subtype of PropertyAttribute for custom inspector to use.
/// </summary>
public class OVRLayerAttribute : PropertyAttribute {
}
| {
"pile_set_name": "Github"
} |
== 体系结构
[[architecture]]
本章从高层次的角度简要介绍了CMMN引擎的内部结构。当然,由于CMMN引擎代码是开源的,因此可以通过深入了解源代码来找到实际的实现细节。
如下图所示,CMMN引擎是Flowable引擎生态系统的一部分,其设计方式与其他引擎类似。CMMN引擎基于CMMN特定服务和共享服务构建:任务,变量,身份和作业服务,它们独立于引擎。 在较低级别,实体和数据管理器层负责低级别持久性,相当于其他引擎。
image::images/cmmn.architecture.png[align="center"]
通过使用共享服务,这也意味着例如来自BPMN和CMMN引擎的任务将最终结合在一起,并且可以通过相同的API查询和管理。类似地,对于异步执行器:定时器和异步作业使用相同的逻辑,甚至可以由中央执行器管理。
共享服务架构有第二个好处。通常情况下,当引擎一起使用时,引擎将尽可能共享资源,数据库事务将跨越多个引擎操作的调用,查找缓存是常见的,并且持久性是独立于引擎本身处理的。
CMMN引擎的设计原理与Flowable项目的其他引擎相同。下图给出了使用CMMN引擎时涉及的不同组件的高级概述:
image::images/cmmn.api-call-flow.png[align="center"]
从高层次来看:
一个**CmmnEngine**实例是从**CmmnEngineConfiguration**创建的。可以从配置文件或以编程方式创建配置实例。
__CmmnEngine__以服务的形式提供对Flowable CMMN API的访问:**CmmnRepositoryService**、**CmmnRuntimeService**、**CmmnTaskService**、**CmmnHistoryService**、**CmmnManagementService**。服务的命名及其职责与其他引擎类似。
每个API方法都转换为**Command**实例,此__Command__实例传递给**CommandExecutor**,其中包括使一些**CommandInterceptors**。这些拦截器具有各种职责,包括处理事务。
最终,__Command__通常(除非是纯数据修改__Command__)在**CmmnEngineAgenda**上计划**CmmnOperation**。
操作将从__CmmnEngineAgenda__中获取,直到不再进行操作为止。通常,操作将计划新操作作为其逻辑的一部分。
操作中的逻辑将调用较低级别的服务和/或实体管理器。
BPMN和CMMN引擎之间的一个很大区别是BPMN引擎通常是“本地的”:引擎查看当前状态,检查进程中的前面的信息并继续(当然这是一个简化,这有很多不适用的操作,但从概念上做出区分,这是正确的)。CMMN引擎的工作方式不同:在CMMN中,数据起着重要作用,数据的更改可以在案例定义中的各个位置触发很多事情。因此,只要发生更改,就会经常计划和执行**EvaluateCriteriaOperation**。当检测到重复或无用的评估时,引擎会对这些评估进行优化。
CMMN引擎工作的核心是计划项目实例的概念,表示当前在案例中存在哪些**计划实例项**以及它们具有哪种状态。与BPMN完全不同,CMMN为__计划项__定义了严格的状态__生命周期__。这在__CmmnRuntimeService__方法,查询API和**PlanItemInstance**对象的数据字段部分中表示。
可以通过将日志记录设置为议程包的调试来检查议程的工作,操作以及如何处理计划项实例。例如,使用log4j时:
```
log4j.logger.org.flowable.cmmn.engine.impl.agenda=DEBUG
```
这样记录的信息如下:
```
Planned [Init Plan Model] initializing plan model for case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122
Planned [Change PlanItem state] Task A (id: planItemTaskA), new state: [available] with transition [create]
Planned [Change PlanItem state] PlanItem Milestone One (id: planItemMileStoneOne), new state: [available] with transition [create]
Planned [Change PlanItem state] Task B (id: planItemTaskB), new state: [available] with transition [create]
Planned [Change PlanItem state] PlanItem Milestone Two (id: planItemMileStoneTwo), new state: [available] with transition [create]
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'create' having fired for plan item planItemTaskA (Task A)
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'create' having fired for plan item planItemMileStoneOne (PlanItem Milestone One)
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'create' having fired for plan item planItemTaskB (Task B)
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'create' having fired for plan item planItemMileStoneTwo (PlanItem Milestone Two)
Planned [Activate PlanItem] Task A (planItemTaskA)
Planned [Change PlanItem state] Task A (id: planItemTaskA), new state: [active] with transition [start]
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'start' having fired for plan item planItemTaskA (Task A)
Planned [Change PlanItem state] Task A (id: planItemTaskA), new state: [completed] with transition [complete]
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'complete' having fired for plan item planItemTaskA (Task A)
Planned [Activate PlanItem] PlanItem Milestone One (planItemMileStoneOne)
Planned [Change PlanItem state] PlanItem Milestone One (id: planItemMileStoneOne), new state: [active] with transition [start]
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'start' having fired for plan item planItemMileStoneOne (PlanItem Milestone One)
Planned [Change PlanItem state] PlanItem Milestone One (id: planItemMileStoneOne), new state: [completed] with transition [occur]
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'occur' having fired for plan item planItemMileStoneOne (PlanItem Milestone One)
Planned [Activate PlanItem] Task B (planItemTaskB)
Planned [Change PlanItem state] Task B (id: planItemTaskB), new state: [active] with transition [start]
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'start' having fired for plan item planItemTaskB (Task B)
Planned [Change PlanItem state] Task B (id: planItemTaskB), new state: [completed] with transition [complete]
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'complete' having fired for plan item planItemTaskB (Task B)
Planned [Activate PlanItem] PlanItem Milestone Two (planItemMileStoneTwo)
Planned [Change PlanItem state] PlanItem Milestone Two (id: planItemMileStoneTwo), new state: [active] with transition [start]
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'start' having fired for plan item planItemMileStoneTwo (PlanItem Milestone Two)
Planned [Change PlanItem state] PlanItem Milestone Two (id: planItemMileStoneTwo), new state: [completed] with transition [occur]
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122 with transition 'occur' having fired for plan item planItemMileStoneTwo (PlanItem Milestone Two)
Planned [Evaluate Criteria] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122
No active plan items found for plan model, completing case instance
Planned [Complete case instance] case instance bfaf0e64-eaf4-11e7-b9d0-acde48001122
```
| {
"pile_set_name": "Github"
} |
// 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
// RUN: not %target-swift-frontend %s -typecheck
{extension{let:{
let n=[V
class a{class
case,
| {
"pile_set_name": "Github"
} |
//==- SystemZInstrDFP.td - Floating-point SystemZ instructions -*- tblgen-*-==//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// The instructions in this file implement SystemZ decimal floating-point
// arithmetic. These instructions are inot currently used for code generation,
// are provided for use with the assembler and disassembler only. If LLVM
// ever supports decimal floating-point types (_Decimal64 etc.), they can
// also be used for code generation for those types.
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// Move instructions
//===----------------------------------------------------------------------===//
// Load and test.
let Uses = [FPC], Defs = [CC] in {
def LTDTR : UnaryRRE<"ltdtr", 0xB3D6, null_frag, FP64, FP64>;
def LTXTR : UnaryRRE<"ltxtr", 0xB3DE, null_frag, FP128, FP128>;
}
//===----------------------------------------------------------------------===//
// Conversion instructions
//===----------------------------------------------------------------------===//
// Convert floating-point values to narrower representations. The destination
// of LDXTR is a 128-bit value, but only the first register of the pair is used.
let Uses = [FPC] in {
def LEDTR : TernaryRRFe<"ledtr", 0xB3D5, FP32, FP64>;
def LDXTR : TernaryRRFe<"ldxtr", 0xB3DD, FP128, FP128>;
}
// Extend floating-point values to wider representations.
let Uses = [FPC] in {
def LDETR : BinaryRRFd<"ldetr", 0xB3D4, FP64, FP32>;
def LXDTR : BinaryRRFd<"lxdtr", 0xB3DC, FP128, FP64>;
}
// Convert a signed integer value to a floating-point one.
let Uses = [FPC] in {
def CDGTR : UnaryRRE<"cdgtr", 0xB3F1, null_frag, FP64, GR64>;
def CXGTR : UnaryRRE<"cxgtr", 0xB3F9, null_frag, FP128, GR64>;
let Predicates = [FeatureFPExtension] in {
def CDGTRA : TernaryRRFe<"cdgtra", 0xB3F1, FP64, GR64>;
def CXGTRA : TernaryRRFe<"cxgtra", 0xB3F9, FP128, GR64>;
def CDFTR : TernaryRRFe<"cdftr", 0xB951, FP64, GR32>;
def CXFTR : TernaryRRFe<"cxftr", 0xB959, FP128, GR32>;
}
}
// Convert an unsigned integer value to a floating-point one.
let Uses = [FPC], Predicates = [FeatureFPExtension] in {
def CDLGTR : TernaryRRFe<"cdlgtr", 0xB952, FP64, GR64>;
def CXLGTR : TernaryRRFe<"cxlgtr", 0xB95A, FP128, GR64>;
def CDLFTR : TernaryRRFe<"cdlftr", 0xB953, FP64, GR32>;
def CXLFTR : TernaryRRFe<"cxlftr", 0xB95B, FP128, GR32>;
}
// Convert a floating-point value to a signed integer value.
let Uses = [FPC], Defs = [CC] in {
def CGDTR : BinaryRRFe<"cgdtr", 0xB3E1, GR64, FP64>;
def CGXTR : BinaryRRFe<"cgxtr", 0xB3E9, GR64, FP128>;
let Predicates = [FeatureFPExtension] in {
def CGDTRA : TernaryRRFe<"cgdtra", 0xB3E1, GR64, FP64>;
def CGXTRA : TernaryRRFe<"cgxtra", 0xB3E9, GR64, FP128>;
def CFDTR : TernaryRRFe<"cfdtr", 0xB941, GR32, FP64>;
def CFXTR : TernaryRRFe<"cfxtr", 0xB949, GR32, FP128>;
}
}
// Convert a floating-point value to an unsigned integer value.
let Uses = [FPC], Defs = [CC] in {
let Predicates = [FeatureFPExtension] in {
def CLGDTR : TernaryRRFe<"clgdtr", 0xB942, GR64, FP64>;
def CLGXTR : TernaryRRFe<"clgxtr", 0xB94A, GR64, FP128>;
def CLFDTR : TernaryRRFe<"clfdtr", 0xB943, GR32, FP64>;
def CLFXTR : TernaryRRFe<"clfxtr", 0xB94B, GR32, FP128>;
}
}
// Convert a packed value to a floating-point one.
def CDSTR : UnaryRRE<"cdstr", 0xB3F3, null_frag, FP64, GR64>;
def CXSTR : UnaryRRE<"cxstr", 0xB3FB, null_frag, FP128, GR128>;
def CDUTR : UnaryRRE<"cdutr", 0xB3F2, null_frag, FP64, GR64>;
def CXUTR : UnaryRRE<"cxutr", 0xB3FA, null_frag, FP128, GR128>;
// Convert a floating-point value to a packed value.
def CSDTR : BinaryRRFd<"csdtr", 0xB3E3, GR64, FP64>;
def CSXTR : BinaryRRFd<"csxtr", 0xB3EB, GR128, FP128>;
def CUDTR : UnaryRRE<"cudtr", 0xB3E2, null_frag, GR64, FP64>;
def CUXTR : UnaryRRE<"cuxtr", 0xB3EA, null_frag, GR128, FP128>;
// Convert from/to memory values in the zoned format.
let Predicates = [FeatureDFPZonedConversion] in {
def CDZT : BinaryRSL<"cdzt", 0xEDAA, FP64>;
def CXZT : BinaryRSL<"cxzt", 0xEDAB, FP128>;
def CZDT : StoreBinaryRSL<"czdt", 0xEDA8, FP64>;
def CZXT : StoreBinaryRSL<"czxt", 0xEDA9, FP128>;
}
// Convert from/to memory values in the packed format.
let Predicates = [FeatureDFPPackedConversion] in {
def CDPT : BinaryRSL<"cdpt", 0xEDAE, FP64>;
def CXPT : BinaryRSL<"cxpt", 0xEDAF, FP128>;
def CPDT : StoreBinaryRSL<"cpdt", 0xEDAC, FP64>;
def CPXT : StoreBinaryRSL<"cpxt", 0xEDAD, FP128>;
}
// Perform floating-point operation.
let Defs = [CC, R1L, F0Q], Uses = [FPC, R0L, F4Q] in
def PFPO : SideEffectInherentE<"pfpo", 0x010A>;
//===----------------------------------------------------------------------===//
// Unary arithmetic
//===----------------------------------------------------------------------===//
// Round to an integer, with the second operand (M3) specifying the rounding
// mode. M4 can be set to 4 to suppress detection of inexact conditions.
let Uses = [FPC] in {
def FIDTR : TernaryRRFe<"fidtr", 0xB3D7, FP64, FP64>;
def FIXTR : TernaryRRFe<"fixtr", 0xB3DF, FP128, FP128>;
}
// Extract biased exponent.
def EEDTR : UnaryRRE<"eedtr", 0xB3E5, null_frag, FP64, FP64>;
def EEXTR : UnaryRRE<"eextr", 0xB3ED, null_frag, FP128, FP128>;
// Extract significance.
def ESDTR : UnaryRRE<"esdtr", 0xB3E7, null_frag, FP64, FP64>;
def ESXTR : UnaryRRE<"esxtr", 0xB3EF, null_frag, FP128, FP128>;
//===----------------------------------------------------------------------===//
// Binary arithmetic
//===----------------------------------------------------------------------===//
// Addition.
let Uses = [FPC], Defs = [CC] in {
let isCommutable = 1 in {
def ADTR : BinaryRRFa<"adtr", 0xB3D2, null_frag, FP64, FP64, FP64>;
def AXTR : BinaryRRFa<"axtr", 0xB3DA, null_frag, FP128, FP128, FP128>;
}
let Predicates = [FeatureFPExtension] in {
def ADTRA : TernaryRRFa<"adtra", 0xB3D2, FP64, FP64, FP64>;
def AXTRA : TernaryRRFa<"axtra", 0xB3DA, FP128, FP128, FP128>;
}
}
// Subtraction.
let Uses = [FPC], Defs = [CC] in {
def SDTR : BinaryRRFa<"sdtr", 0xB3D3, null_frag, FP64, FP64, FP64>;
def SXTR : BinaryRRFa<"sxtr", 0xB3DB, null_frag, FP128, FP128, FP128>;
let Predicates = [FeatureFPExtension] in {
def SDTRA : TernaryRRFa<"sdtra", 0xB3D3, FP64, FP64, FP64>;
def SXTRA : TernaryRRFa<"sxtra", 0xB3DB, FP128, FP128, FP128>;
}
}
// Multiplication.
let Uses = [FPC] in {
let isCommutable = 1 in {
def MDTR : BinaryRRFa<"mdtr", 0xB3D0, null_frag, FP64, FP64, FP64>;
def MXTR : BinaryRRFa<"mxtr", 0xB3D8, null_frag, FP128, FP128, FP128>;
}
let Predicates = [FeatureFPExtension] in {
def MDTRA : TernaryRRFa<"mdtra", 0xB3D0, FP64, FP64, FP64>;
def MXTRA : TernaryRRFa<"mxtra", 0xB3D8, FP128, FP128, FP128>;
}
}
// Division.
let Uses = [FPC] in {
def DDTR : BinaryRRFa<"ddtr", 0xB3D1, null_frag, FP64, FP64, FP64>;
def DXTR : BinaryRRFa<"dxtr", 0xB3D9, null_frag, FP128, FP128, FP128>;
let Predicates = [FeatureFPExtension] in {
def DDTRA : TernaryRRFa<"ddtra", 0xB3D1, FP64, FP64, FP64>;
def DXTRA : TernaryRRFa<"dxtra", 0xB3D9, FP128, FP128, FP128>;
}
}
// Quantize.
let Uses = [FPC] in {
def QADTR : TernaryRRFb<"qadtr", 0xB3F5, FP64, FP64, FP64>;
def QAXTR : TernaryRRFb<"qaxtr", 0xB3FD, FP128, FP128, FP128>;
}
// Reround.
let Uses = [FPC] in {
def RRDTR : TernaryRRFb<"rrdtr", 0xB3F7, FP64, FP64, FP64>;
def RRXTR : TernaryRRFb<"rrxtr", 0xB3FF, FP128, FP128, FP128>;
}
// Shift significand left/right.
def SLDT : BinaryRXF<"sldt", 0xED40, null_frag, FP64, FP64, null_frag, 0>;
def SLXT : BinaryRXF<"slxt", 0xED48, null_frag, FP128, FP128, null_frag, 0>;
def SRDT : BinaryRXF<"srdt", 0xED41, null_frag, FP64, FP64, null_frag, 0>;
def SRXT : BinaryRXF<"srxt", 0xED49, null_frag, FP128, FP128, null_frag, 0>;
// Insert biased exponent.
def IEDTR : BinaryRRFb<"iedtr", 0xB3F6, null_frag, FP64, FP64, FP64>;
def IEXTR : BinaryRRFb<"iextr", 0xB3FE, null_frag, FP128, FP128, FP128>;
//===----------------------------------------------------------------------===//
// Comparisons
//===----------------------------------------------------------------------===//
// Compare.
let Uses = [FPC], Defs = [CC] in {
def CDTR : CompareRRE<"cdtr", 0xB3E4, null_frag, FP64, FP64>;
def CXTR : CompareRRE<"cxtr", 0xB3EC, null_frag, FP128, FP128>;
}
// Compare and signal.
let Uses = [FPC], Defs = [CC] in {
def KDTR : CompareRRE<"kdtr", 0xB3E0, null_frag, FP64, FP64>;
def KXTR : CompareRRE<"kxtr", 0xB3E8, null_frag, FP128, FP128>;
}
// Compare biased exponent.
let Defs = [CC] in {
def CEDTR : CompareRRE<"cedtr", 0xB3F4, null_frag, FP64, FP64>;
def CEXTR : CompareRRE<"cextr", 0xB3FC, null_frag, FP128, FP128>;
}
// Test Data Class.
let Defs = [CC] in {
def TDCET : TestRXE<"tdcet", 0xED50, null_frag, FP32>;
def TDCDT : TestRXE<"tdcdt", 0xED54, null_frag, FP64>;
def TDCXT : TestRXE<"tdcxt", 0xED58, null_frag, FP128>;
}
// Test Data Group.
let Defs = [CC] in {
def TDGET : TestRXE<"tdget", 0xED51, null_frag, FP32>;
def TDGDT : TestRXE<"tdgdt", 0xED55, null_frag, FP64>;
def TDGXT : TestRXE<"tdgxt", 0xED59, null_frag, FP128>;
}
| {
"pile_set_name": "Github"
} |
# from http://mail.python.org/pipermail/python-dev/2001-June/015239.html
# if you keep changing a dictionary while looking up a key, you can
# provoke an infinite recursion in C
# At the time neither Tim nor Michael could be bothered to think of a
# way to fix it.
class Yuck:
def __init__(self):
self.i = 0
def make_dangerous(self):
self.i = 1
def __hash__(self):
# direct to slot 4 in table of size 8; slot 12 when size 16
return 4 + 8
def __eq__(self, other):
if self.i == 0:
# leave dict alone
pass
elif self.i == 1:
# fiddle to 16 slots
self.__fill_dict(6)
self.i = 2
else:
# fiddle to 8 slots
self.__fill_dict(4)
self.i = 1
return 1
def __fill_dict(self, n):
self.i = 0
dict.clear()
for i in range(n):
dict[i] = i
dict[self] = "OK!"
y = Yuck()
dict = {y: "OK!"}
z = Yuck()
y.make_dangerous()
print dict[z]
| {
"pile_set_name": "Github"
} |
// RUN: %clang_cc1 -DCHECK -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefix CHECK --check-prefix CHECK-64
// RUN: %clang_cc1 -DCHECK -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -DCHECK -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefix CHECK --check-prefix CHECK-64
// RUN: %clang_cc1 -DCHECK -verify -fopenmp -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefix CHECK --check-prefix CHECK-32
// RUN: %clang_cc1 -DCHECK -fopenmp -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -DCHECK -fopenmp -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefix CHECK --check-prefix CHECK-32
// RUN: %clang_cc1 -DCHECK -verify -fopenmp-simd -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -DCHECK -fopenmp-simd -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -DCHECK -fopenmp-simd -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -DCHECK -verify -fopenmp-simd -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -DCHECK -fopenmp-simd -x c++ -std=c++11 -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -DCHECK -fopenmp-simd -x c++ -triple i386-unknown-unknown -fopenmp-targets=i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY0 %s
// SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
// RUN: %clang_cc1 -DLAMBDA -verify -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefix LAMBDA --check-prefix LAMBDA-64
// RUN: %clang_cc1 -DLAMBDA -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -DLAMBDA -fopenmp -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap %s --check-prefix LAMBDA --check-prefix LAMBDA-64
// RUN: %clang_cc1 -DLAMBDA -verify -fopenmp-simd -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-llvm %s -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY1 %s
// RUN: %clang_cc1 -DLAMBDA -fopenmp-simd -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -DLAMBDA -fopenmp-simd -x c++ -std=c++11 -triple powerpc64le-unknown-unknown -fopenmp-targets=powerpc64le-ibm-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck -allow-deprecated-dag-overlap --check-prefix SIMD-ONLY1 %s
// SIMD-ONLY1-NOT: {{__kmpc|__tgt}}
// expected-no-diagnostics
#ifndef HEADER
#define HEADER
struct St {
int a, b;
St() : a(0), b(0) {}
St(const St &st) : a(st.a + st.b), b(0) {}
~St() {}
};
volatile int g = 1212;
volatile int &g1 = g;
template <class T>
struct S {
T f;
S(T a) : f(a + g) {}
S() : f(g) {}
S(const S &s, St t = St()) : f(s.f + t.a) {}
operator T() { return T(); }
~S() {}
};
// CHECK-DAG: [[S_FLOAT_TY:%.+]] = type { float }
// CHECK-DAG: [[S_INT_TY:%.+]] = type { i{{[0-9]+}} }
// CHECK-DAG: [[ST_TY:%.+]] = type { i{{[0-9]+}}, i{{[0-9]+}} }
template <typename T>
T tmain() {
S<T> test;
T t_var = T();
T vec[] = {1, 2};
S<T> s_arr[] = {1, 2};
S<T> &var = test;
#pragma omp target teams distribute simd firstprivate(t_var, vec, s_arr, var)
for (int i = 0; i < 2; ++i) {
vec[i] = t_var;
s_arr[i] = var;
}
return T();
}
// CHECK-DAG: [[TEST:@.+]] = global [[S_FLOAT_TY]] zeroinitializer,
S<float> test;
// CHECK-DAG: [[T_VAR:@.+]] = global i{{[0-9]+}} 333,
int t_var = 333;
// CHECK-DAG: [[VEC:@.+]] = global [2 x i{{[0-9]+}}] [i{{[0-9]+}} 1, i{{[0-9]+}} 2],
int vec[] = {1, 2};
// CHECK-DAG: [[S_ARR:@.+]] = global [2 x [[S_FLOAT_TY]]] zeroinitializer,
S<float> s_arr[] = {1, 2};
// CHECK-DAG: [[VAR:@.+]] = global [[S_FLOAT_TY]] zeroinitializer,
S<float> var(3);
// CHECK-DAG: [[SIVAR:@.+]] = internal global i{{[0-9]+}} 0,
int main() {
static int sivar;
#ifdef LAMBDA
// LAMBDA: [[G:@.+]] = global i{{[0-9]+}} 1212,
// LAMBDA-LABEL: @main
// LAMBDA: call void [[OUTER_LAMBDA:@.+]](
[&]() {
// LAMBDA: define{{.*}} internal{{.*}} void [[OUTER_LAMBDA]](
// LAMBDA: call i32 @__tgt_target_teams(i64 -1, i8* @{{[^,]+}}, i32 3, i8** %{{[^,]+}}, i8** %{{[^,]+}}, i{{64|32}}* {{.+}}@{{[^,]+}}, i32 0, i32 0), i64* {{.+}}@{{[^,]+}}, i32 0, i32 0), i32 0, i32 1)
// LAMBDA: call void @[[LOFFL1:.+]](i{{64|32}} %{{.+}})
// LAMBDA: ret
#pragma omp target teams distribute simd firstprivate(g, g1, sivar)
for (int i = 0; i < 2; ++i) {
// LAMBDA: define{{.*}} internal{{.*}} void @[[LOFFL1]](i{{64|32}} {{%.+}}, i{{64|32}} {{%.+}})
// LAMBDA: {{%.+}} = alloca i{{[0-9]+}},
// LAMBDA: {{%.+}} = alloca i{{[0-9]+}},
// LAMBDA: {{%.+}} = alloca i{{[0-9]+}},
// LAMBDA: [[G_CAST:%.+]] = alloca i{{[0-9]+}},
// LAMBDA: [[G1_CAST:%.+]] = alloca i{{[0-9]+}},
// LAMBDA: [[SIVAR_CAST:%.+]] = alloca i{{[0-9]+}},
// LAMBDA-DAG: [[G_CAST_VAL:%.+]] = load{{.+}} [[G_CAST]],
// LAMBDA-DAG: [[G1_CAST_VAL:%.+]] = load{{.+}} [[G1_CAST]],
// LAMBDA-DAG: [[SIVAR_CAST_VAL:%.+]] = load{{.+}} [[SIVAR_CAST]],
// LAMBDA: call void {{.+}} @__kmpc_fork_teams({{.+}}, i32 3, {{.+}} @[[LOUTL1:.+]] to {{.+}}, {{.+}} [[G_CAST_VAL]], {{.+}} [[G1_CAST_VAL]], {{.+}} [[SIVAR_CAST_VAL]])
// LAMBDA: ret void
// LAMBDA: define internal void @[[LOUTL1]]({{.+}})
// Skip global and bound tid vars
// LAMBDA: {{.+}} = alloca i32*,
// LAMBDA: {{.+}} = alloca i32*,
// LAMBDA: [[G_ADDR:%.+]] = alloca i{{[0-9]+}},
// LAMBDA: [[G1_ADDR:%.+]] = alloca i{{[0-9]+}},
// LAMBDA: [[SIVAR_ADDR:%.+]] = alloca i{{[0-9]+}},
// LAMBDA: [[G1_TMP:%.+]] = alloca i32*,
// skip loop vars
// LAMBDA-DAG: store {{.+}}, {{.+}} [[G_ADDR]],
// LAMBDA-DAG: store {{.+}}, {{.+}} [[G1_ADDR]],
// LAMBDA-DAG: store {{.+}}, {{.+}} [[SIVAR_ADDR]],
// LAMBDA-DAG: [[G_CONV:%.+]] = bitcast {{.+}} [[G_ADDR]] to
// LAMBDA-DAG: [[G1_CONV:%.+]] = bitcast {{.+}} [[G1_ADDR]] to
// LAMBDA-DAG: [[SIVAR_CONV:%.+]] = bitcast {{.+}} [[SIVAR_ADDR]] to
// LAMBDA-DAG: store{{.+}} [[G1_CONV]], {{.+}} [[G1_TMP]],
g = 1;
g1 = 1;
sivar = 2;
// LAMBDA: call void @__kmpc_for_static_init_4(
// LAMBDA-DAG: store{{.+}} 1, {{.+}} [[G_CONV]],
// LAMBDA-DAG: [[G1:%.+]] = load{{.+}}, {{.+}}* [[G1_TMP]]
// LAMBDA-DAG: store{{.+}} 1, {{.+}} [[G1]],
// LAMBDA-DAG: store{{.+}} 2, {{.+}} [[SIVAR_CONV]],
// LAMBDA-DAG: [[G1_REF:%.+]] = load{{.+}}, {{.+}} [[G1_TMP]],
// LAMBDA-DAG: store{{.+}} 1, {{.+}} [[G1_REF]],
// LAMBDA: call void [[INNER_LAMBDA:@.+]](
// LAMBDA: call void @__kmpc_for_static_fini(
[&]() {
// LAMBDA: define {{.+}} void [[INNER_LAMBDA]](%{{.+}}* [[ARG_PTR:%.+]])
// LAMBDA: store %{{.+}}* [[ARG_PTR]], %{{.+}}** [[ARG_PTR_REF:%.+]],
g = 2;
g1 = 2;
sivar = 4;
// LAMBDA: [[ARG_PTR:%.+]] = load %{{.+}}*, %{{.+}}** [[ARG_PTR_REF]]
// LAMBDA: [[G_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
// LAMBDA: [[G_REF:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[G_PTR_REF]]
// LAMBDA: store i{{[0-9]+}} 2, i{{[0-9]+}}* [[G_REF]]
// LAMBDA: [[G1_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 1
// LAMBDA: [[G1_REF:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[G1_PTR_REF]]
// LAMBDA: store i{{[0-9]+}} 2, i{{[0-9]+}}* [[G1_REF]]
// LAMBDA: [[SIVAR_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 2
// LAMBDA: [[SIVAR_REF:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[SIVAR_PTR_REF]]
// LAMBDA: store i{{[0-9]+}} 4, i{{[0-9]+}}* [[SIVAR_REF]]
}();
}
}();
return 0;
#else
#pragma omp target teams distribute simd firstprivate(t_var, vec, s_arr, var, sivar)
for (int i = 0; i < 2; ++i) {
vec[i] = t_var;
s_arr[i] = var;
sivar += i;
}
return tmain<int>();
#endif
}
// CHECK: define {{.*}}i{{[0-9]+}} @main()
// CHECK: call i32 @__tgt_target_teams(i64 -1, i8* @{{[^,]+}}, i32 5, i8** %{{[^,]+}}, i8** %{{[^,]+}}, i{{64|32}}* {{.+}}@{{[^,]+}}, i32 0, i32 0), i64* {{.+}}@{{[^,]+}}, i32 0, i32 0), i32 0, i32 1)
// CHECK: call void @[[OFFL1:.+]]({{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}})
// CHECK: {{%.+}} = call{{.*}} i32 @[[TMAIN_INT:.+]]()
// CHECK: ret
// CHECK: define{{.*}} void @[[OFFL1]]({{.+}})
// CHECK: [[VEC_PRIV:%.+]] = alloca [2 x i{{[0-9]+}}]*,
// CHECK: [[T_VAR_PRIV:%.+]] = alloca i{{[0-9]+}},
// CHECK: [[S_ARR_PRIV:%.+]] = alloca [2 x [[S_FLOAT_TY]]]*,
// CHECK: [[VAR_PRIV:%.+]] = alloca [[S_FLOAT_TY]]*,
// CHECK: [[SIVAR_PRIV:%.+]] = alloca i{{[0-9]+}},
// CHECK: [[T_VAR_CAST:%.+]] = alloca i{{[0-9]+}},
// CHECK: [[SIVAR_CAST:%.+]] = alloca i{{[0-9]+}},
// CHECK-DAG: [[VEC_TE_PAR:%.+]] = load [2 x i{{[0-9]+}}]*, [2 x i{{[0-9]+}}]** [[VEC_PRIV]],
// CHECK-DAG: [[T_VAR_TE_PAR:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[T_VAR_CAST]],
// CHECK-DAG: [[S_ARR_TE_PAR:%.+]] = load [2 x [[S_FLOAT_TY]]]*, [2 x [[S_FLOAT_TY]]]** [[S_ARR_PRIV]],
// CHECK-DAG: [[VAR_TE_PAR:%.+]] = load [[S_FLOAT_TY]]*, [[S_FLOAT_TY]]** [[VAR_PRIV]],
// CHECK-DAG: [[SIVAR_TE_PAR:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[SIVAR_CAST]],
// CHECK: call void {{.+}} @__kmpc_fork_teams({{.+}}, i32 5, {{.+}} @[[OUTL1:.+]] to {{.+}}, [2 x i{{[0-9]+}}]* [[VEC_TE_PAR]], i{{[0-9]+}} [[T_VAR_TE_PAR]], [2 x [[S_FLOAT_TY]]]* [[S_ARR_TE_PAR]], [[S_FLOAT_TY]]* [[VAR_TE_PAR]], i{{[0-9]+}} [[SIVAR_TE_PAR]])
// CHECK: ret void
// CHECK: define internal void @[[OUTL1]]({{.+}})
// Skip global and bound tid vars
// CHECK: {{.+}} = alloca i32*,
// CHECK: {{.+}} = alloca i32*,
// CHECK: [[VEC_ADDR:%.+]] = alloca [2 x i{{[0-9]+}}]*,
// CHECK: [[T_VAR_ADDR:%.+]] = alloca i{{[0-9]+}},
// CHECK: [[S_ARR_ADDR:%.+]] = alloca [2 x [[S_FLOAT_TY]]]*,
// CHECK: [[VAR_ADDR:%.+]] = alloca [[S_FLOAT_TY]]*,
// CHECK: [[SIVAR_ADDR:%.+]] = alloca i{{[0-9]+}},
// Skip temp vars for loop
// CHECK: alloca i{{[0-9]+}},
// CHECK: alloca i{{[0-9]+}},
// CHECK: alloca i{{[0-9]+}},
// CHECK: alloca i{{[0-9]+}},
// CHECK: alloca i{{[0-9]+}},
// CHECK: [[VEC_PRIV:%.+]] = alloca [2 x i{{[0-9]+}}],
// CHECK: [[S_ARR_PRIV:%.+]] = alloca [2 x [[S_FLOAT_TY]]],
// CHECK: [[AGG_TMP1:%.+]] = alloca [[ST_TY]],
// CHECK: [[VAR_PRIV:%.+]] = alloca [[S_FLOAT_TY]],
// CHECK: [[AGG_TMP2:%.+]] = alloca [[ST_TY]],
// param copy
// CHECK: store [2 x i{{[0-9]+}}]* {{.+}}, [2 x i{{[0-9]+}}]** [[VEC_ADDR]],
// CHECK: store i{{[0-9]+}} {{.+}}, i{{[0-9]+}}* [[T_VAR_ADDR]],
// CHECK: store [2 x [[S_FLOAT_TY]]]* {{.+}}, [2 x [[S_FLOAT_TY]]]** [[S_ARR_ADDR]],
// CHECK: store [[S_FLOAT_TY]]* {{.+}}, [[S_FLOAT_TY]]** [[VAR_ADDR]],
// CHECK: store i{{[0-9]+}} {{.+}}, i{{[0-9]+}}* [[SIVAR_ADDR]],
// T_VAR and SIVAR
// CHECK-64-DAG: [[CONV_TVAR:%.+]] = bitcast i64* [[T_VAR_ADDR]] to i32*
// CHECK-64-DAG: [[CONV_SIVAR:%.+]] = bitcast i64* [[SIVAR_ADDR]] to i32*
// preparation vars
// CHECK-DAG: [[VEC_ADDR_VAL:%.+]] = load [2 x i{{[0-9]+}}]*, [2 x i{{[0-9]+}}]** [[VEC_ADDR]],
// CHECK-DAG: [[S_ARR_ADDR_REF:%.+]] = load [2 x [[S_FLOAT_TY]]]*, [2 x [[S_FLOAT_TY]]]** [[S_ARR_ADDR]],
// CHECK-DAG: [[VAR_ADDR_REF:%.+]] = load{{.+}} [[VAR_ADDR]],
// firstprivate vec(vec): copy from *_addr into priv1 and then from priv1 into priv2
// CHECK-DAG: [[VEC_DEST_PRIV:%.+]] = bitcast [2 x i{{[0-9]+}}]* [[VEC_PRIV]] to i8*
// CHECK-DAG: [[VEC_SRC:%.+]] = bitcast [2 x i{{[0-9]+}}]* [[VEC_ADDR_VAL]] to i8*
// CHECK: call void @llvm.memcpy.{{.+}}(i8* align {{[0-9]+}} [[VEC_DEST_PRIV]], i8* align {{[0-9]+}} [[VEC_SRC]], {{.+}})
// firstprivate(s_arr)
// CHECK-DAG: [[S_ARR_PRIV_BGN:%.+]] = getelementptr{{.*}} [2 x [[S_FLOAT_TY]]], [2 x [[S_FLOAT_TY]]]* [[S_ARR_PRIV]],
// CHECK-DAG: [[S_ARR_ADDR_BGN:%.+]] = bitcast [2 x [[S_FLOAT_TY]]]* [[S_ARR_ADDR_REF]] to
// CHECK-DAG: [[S_ARR_FIN:%.+]] = icmp{{.+}} [[S_ARR_PRIV_BGN]],
// CHECK-DAG: [[S_ARR_SRC_COPY:%.+]] = phi{{.+}} [ [[S_ARR_ADDR_BGN]], {{.+}} ], [ [[S_ARR_SRC:%.+]], {{.+}} ]
// CHECK-DAG: [[S_ARR_DST_COPY:%.+]] = phi{{.+}} [ [[S_ARR_PRIV_BGN]], {{.+}}], [ [[S_ARR_DST:%.+]], {{.+}} ]
// CHECK-DAG: call void @{{.+}}({{.+}} [[AGG_TMP1]])
// CHECK-DAG: call void @{{.+}}({{.+}} [[S_ARR_DST_COPY]], {{.+}} [[S_ARR_SRC_COPY]], {{.+}} [[AGG_TMP1]])
// CHECK-DAG: call void @{{.+}}({{.+}} [[AGG_TMP1]])
// CHECK-DAG: [[S_ARR_DST]] = getelementptr {{.+}} [[S_ARR_DST_COPY]],
// CHECK-DAG: [[S_ARR_SRC]] = getelementptr {{.+}} [[S_ARR_SRC_COPY]],
// firstprivate(var)
// CHECK-DAG: call void @{{.+}}({{.+}} [[AGG_TMP2]])
// CHECK-DAG: call void @{{.+}}({{.+}} [[VAR_PRIV]], {{.+}} [[VAR_ADDR_REF]], {{.+}} [[AGG_TMP2]])
// CHECK-DAG: call void @{{.+}}({{.+}} [[AGG_TMP2]])
// CHECK: call void @__kmpc_for_static_init_4(
// CHECK-32-DAG: {{.+}} = {{.+}} [[T_VAR_ADDR]]
// CHECK-64-DAG: {{.+}} = {{.+}} [[CONV_TVAR]]
// CHECK-DAG: {{.+}} = {{.+}} [[VEC_PRIV]]
// CHECK-DAG: {{.+}} = {{.+}} [[S_ARR_PRIV]]
// CHECK-DAG: {{.+}} = {{.+}} [[VAR_PRIV]]
// CHECK-32-DAG: {{.+}} = {{.+}} [[SIVAR_ADDR]]
// CHECK-64-DAG: {{.+}} = {{.+}} [[CONV_SIVAR]]
// CHECK: call void @__kmpc_for_static_fini(
// CHECK: ret void
// CHECK: define{{.*}} i{{[0-9]+}} @[[TMAIN_INT]]()
// CHECK: call i32 @__tgt_target_teams(i64 -1, i8* @{{[^,]+}}, i32 4, i8** %{{[^,]+}}, i8** %{{[^,]+}}, i{{64|32}}* {{.+}}@{{[^,]+}}, i32 0, i32 0), i64* {{.+}}@{{[^,]+}}, i32 0, i32 0), i32 0, i32 1)
// CHECK: call void @[[TOFFL1:.+]]({{[^,]+}}, {{[^,]+}}, {{[^,]+}}, {{[^,]+}})
// CHECK: ret
// CHECK: define {{.*}}void @[[TOFFL1]]({{.+}})
// CHECK: [[TVEC_PRIV:%.+]] = alloca [2 x i{{[0-9]+}}]*,
// CHECK: [[TT_VAR_PRIV:%.+]] = alloca i{{[0-9]+}},
// CHECK: [[TS_ARR_PRIV:%.+]] = alloca [2 x [[S_INT_TY]]]*,
// CHECK: [[TVAR_PRIV:%.+]] = alloca [[S_INT_TY]]*,
// CHECK: [[TT_VAR_CAST:%.+]] = alloca i{{[0-9]+}},
// CHECK-DAG: [[TVEC_TE_PAR:%.+]] = load [2 x i{{[0-9]+}}]*, [2 x i{{[0-9]+}}]** [[TVEC_PRIV]],
// CHECK-DAG: [[TT_VAR_TE_PAR:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[TT_VAR_CAST]],
// CHECK-DAG: [[TS_ARR_TE_PAR:%.+]] = load [2 x [[S_INT_TY]]]*, [2 x [[S_INT_TY]]]** [[TS_ARR_PRIV]],
// CHECK-DAG: [[TVAR_TE_PAR:%.+]] = load [[S_INT_TY]]*, [[S_INT_TY]]** [[TVAR_PRIV]],
// CHECK: [[TVAR_TE_PAR:%.+]] = load [[S_INT_TY]]*, [[S_INT_TY]]** %
// CHECK: call void {{.+}} @__kmpc_fork_teams({{.+}}, i32 4, {{.+}} @[[TOUTL1:.+]] to {{.+}}, [2 x i{{[0-9]+}}]* [[TVEC_TE_PAR]], i{{[0-9]+}} [[TT_VAR_TE_PAR]], [2 x [[S_INT_TY]]]* [[TS_ARR_TE_PAR]], [[S_INT_TY]]* [[TVAR_TE_PAR]])
// CHECK: ret void
// CHECK: define internal void @[[TOUTL1]]({{.+}})
// Skip global and bound tid vars
// CHECK: {{.+}} = alloca i32*,
// CHECK: {{.+}} = alloca i32*,
// CHECK: [[VEC_ADDR:%.+]] = alloca [2 x i{{[0-9]+}}]*,
// CHECK: [[T_VAR_ADDR:%.+]] = alloca i{{[0-9]+}},
// CHECK: [[S_ARR_ADDR:%.+]] = alloca [2 x [[S_INT_TY]]]*,
// CHECK: [[VAR_ADDR:%.+]] = alloca [[S_INT_TY]]*,
// CHECK: [[TMP_VAR_ADDR:%.+]] = alloca [[S_INT_TY]]*,
// Skip temp vars for loop
// CHECK: alloca i{{[0-9]+}},
// CHECK: alloca i{{[0-9]+}},
// CHECK: alloca i{{[0-9]+}},
// CHECK: alloca i{{[0-9]+}},
// CHECK: alloca i{{[0-9]+}},
// CHECK: [[VEC_PRIV:%.+]] = alloca [2 x i{{[0-9]+}}],
// CHECK: [[S_ARR_PRIV:%.+]] = alloca [2 x [[S_INT_TY]]],
// CHECK: [[AGG_TMP1:%.+]] = alloca [[ST_TY]],
// CHECK: [[VAR_PRIV:%.+]] = alloca [[S_INT_TY]],
// CHECK: [[AGG_TMP2:%.+]] = alloca [[ST_TY]],
// CHECK: [[TMP:%.+]] = alloca [[S_INT_TY]]*,
// param copy
// CHECK: store [2 x i{{[0-9]+}}]* {{.+}}, [2 x i{{[0-9]+}}]** [[VEC_ADDR]],
// CHECK: store i{{[0-9]+}} {{.+}}, i{{[0-9]+}}* [[T_VAR_ADDR]],
// CHECK: store [2 x [[S_INT_TY]]]* {{.+}}, [2 x [[S_INT_TY]]]** [[S_ARR_ADDR]],
// CHECK: store [[S_INT_TY]]* {{.+}}, [[S_INT_TY]]** [[VAR_ADDR]],
// T_VAR and preparation variables
// CHECK: [[VEC_ADDR_VAL:%.+]] = load [2 x i{{[0-9]+}}]*, [2 x i{{[0-9]+}}]** [[VEC_ADDR]],
// CHECK-64: [[CONV_TVAR:%.+]] = bitcast i64* [[T_VAR_ADDR]] to i32*
// CHECK: [[S_ARR_ADDR_REF:%.+]] = load [2 x [[S_INT_TY]]]*, [2 x [[S_INT_TY]]]** [[S_ARR_ADDR]],
// firstprivate vec(vec): copy from *_addr into priv1 and then from priv1 into priv2
// CHECK-DAG: [[VEC_DEST_PRIV:%.+]] = bitcast [2 x i{{[0-9]+}}]* [[VEC_PRIV]] to i8*
// CHECK-DAG: [[VEC_SRC:%.+]] = bitcast [2 x i{{[0-9]+}}]* [[VEC_ADDR_VAL]] to i8*
// CHECK: call void @llvm.memcpy.{{.+}}(i8* align {{[0-9]+}} [[VEC_DEST_PRIV]], i8* align {{[0-9]+}} [[VEC_SRC]], {{.+}})
// firstprivate(s_arr)
// CHECK-DAG: [[S_ARR_PRIV_BGN:%.+]] = getelementptr{{.*}} [2 x [[S_INT_TY]]], [2 x [[S_INT_TY]]]* [[S_ARR_PRIV]],
// CHECK-DAG: [[S_ARR_ADDR_BGN:%.+]] = bitcast [2 x [[S_INT_TY]]]* [[S_ARR_ADDR_REF]] to
// CHECK-DAG: [[S_ARR_FIN:%.+]] = icmp{{.+}} [[S_ARR_PRIV_BGN]],
// CHECK-DAG: [[S_ARR_SRC_COPY:%.+]] = phi{{.+}} [ [[S_ARR_ADDR_BGN]], {{.+}} ], [ [[S_ARR_SRC:%.+]], {{.+}} ]
// CHECK-DAG: [[S_ARR_DST_COPY:%.+]] = phi{{.+}} [ [[S_ARR_PRIV_BGN]], {{.+}} ], [ [[S_ARR_DST:%.+]], {{.+}} ]
// CHECK-DAG: call void @{{.+}}({{.+}} [[AGG_TMP1]])
// CHECK-DAG: call void @{{.+}}({{.+}} [[S_ARR_DST_COPY]], {{.+}} [[S_ARR_SRC_COPY]], {{.+}} [[AGG_TMP1]])
// CHECK-DAG: call void @{{.+}}({{.+}} [[AGG_TMP1]])
// CHECK-DAG: [[S_ARR_DST]] = getelementptr {{.+}} [[S_ARR_DST_COPY]],
// CHECK-DAG: [[S_ARR_SRC]] = getelementptr {{.+}} [[S_ARR_SRC_COPY]],
// firstprivate(var)
// CHECK-DAG: [[VAR_ADDR_REF:%.+]] = load{{.+}} [[TMP_VAR_ADDR]],
// CHECK-DAG: call void @{{.+}}({{.+}} [[AGG_TMP2]])
// CHECK-DAG: call void @{{.+}}({{.+}} [[VAR_PRIV]], {{.+}} [[VAR_ADDR_REF]], {{.+}} [[AGG_TMP2]])
// CHECK-DAG: call void @{{.+}}({{.+}} [[AGG_TMP2]])
// CHECK-DAG: store [[S_INT_TY]]* [[VAR_PRIV]], [[S_INT_TY]]** [[TMP]],
// CHECK: call void @__kmpc_for_static_init_4(
// CHECK-32-DAG: {{.+}} = {{.+}} [[T_VAR_ADDR]]
// CHECK-64-DAG: {{.+}} = {{.+}} [[CONV_TVAR]]
// CHECK-DAG: {{.+}} = {{.+}} [[VEC_PRIV]]
// CHECK-DAG: {{.+}} = {{.+}} [[TMP]]
// CHECK-DAG: {{.+}} = {{.+}} [[S_ARR_PRIV]]
// CHECK: call void @__kmpc_for_static_fini(
// CHECK: ret void
#endif
| {
"pile_set_name": "Github"
} |
require 'test_helper'
class RacersControllerTest < ActionController::TestCase
setup do
@racer = racers(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:racers)
end
test "should get new" do
get :new
assert_response :success
end
test "should create racer" do
assert_difference('Racer.count') do
post :create, racer: { first_name: @racer.first_name, gender: @racer.gender, group: @racer.group, last_name: @racer.last_name, number: @racer.number, secs: @racer.secs }
end
assert_redirected_to racer_path(assigns(:racer))
end
test "should show racer" do
get :show, id: @racer
assert_response :success
end
test "should get edit" do
get :edit, id: @racer
assert_response :success
end
test "should update racer" do
patch :update, id: @racer, racer: { first_name: @racer.first_name, gender: @racer.gender, group: @racer.group, last_name: @racer.last_name, number: @racer.number, secs: @racer.secs }
assert_redirected_to racer_path(assigns(:racer))
end
test "should destroy racer" do
assert_difference('Racer.count', -1) do
delete :destroy, id: @racer
end
assert_redirected_to racers_path
end
end
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<EmguTFLiteMacLinkTarget>MacOS_x64</EmguTFLiteMacLinkTarget>
<EmguTFLiteMacBuildX64 Condition="'$(Platform)'=='AnyCPU' OR '$(Platform)'=='x64'">True</EmguTFLiteMacBuildX64>
<EmguTFLiteMacNativeFileX64>$(MSBuildThisFileDirectory)libtfliteextern.dylib</EmguTFLiteMacNativeFileX64>
<EmguTFLiteMacErrorMessage Condition="'$(EmguTFLiteMacBuildX64)'=='True' AND !Exists('$(EmguTFLiteMacNativeFileX64)')">This package do not contain necessary binary for $(EmguTFLiteMacLinkTarget). File $(EmguTFLiteMacNativeFileX64) is missing.</EmguTFLiteMacErrorMessage>
<EmguTFLiteMacDeployMessage Condition="'$(EmguTFLiteMacBuildX64)'=='True' AND Exists('$(EmguTFLiteMacNativeFileX64)')">$(EmguTFLiteMacDeployMessage)x64 </EmguTFLiteMacDeployMessage >
</PropertyGroup>
<ItemGroup Condition="'$(EmguTFLiteMacBuildX64)'=='True' AND Exists('$(EmguTFLiteMacNativeFileX64)')">
<None Include="$(MSBuildThisFileDirectory)\*.dylib">
<Link>%(RecursiveDir)%(Filename)%(Extension)</Link>
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<Target Name="EmguTFLiteMacPackageBuildImports" BeforeTargets="PrepareForBuild">
<!-- <Message Condition="'$(EmguTFLiteMacLinkTarget)'!=''" Text="Emgu TF nuget package compiling against $(EmguTFLiteMacLinkTarget)" Importance="High" /> -->
<Warning Text="'$(EmguTFLiteMacErrorMessage)'" Condition="'$(EmguTFLiteMacErrorMessage)'!=''" />
<Message Text="Emgu TF Lite Compiling with $(EmguTFLiteMacDeployMessage)binary" Condition="'$(EmguTFLiteMacDeployMessage)'!=''" Importance="High" />
<Message Text="No native binary is deployed by the runtime.macos.Emgu.TF.Lite nuget package." Condition="'$(EmguTFLiteMacDeployMessage)'==''" Importance="High" />
</Target>
</Project> | {
"pile_set_name": "Github"
} |
# frozen_string_literal: true
# Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC 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.
require File.expand_path('../spec_helper', __dir__)
module Selenium
module WebDriver
module IE
describe Driver do
let(:service) { instance_double(Service, launch: service_manager) }
let(:service_manager) { instance_double(ServiceManager, uri: 'http://example.com') }
let(:valid_response) do
{status: 200,
body: {value: {sessionId: 0, capabilities: Remote::Capabilities.ie}}.to_json,
headers: {"content_type": "application/json"}}
end
def expect_request(body: nil, endpoint: nil)
body = (body || {capabilities: {firstMatch: [browserName: "internet explorer",
platformName: 'windows']}}).to_json
endpoint ||= "#{service_manager.uri}/session"
stub_request(:post, endpoint).with(body: body).to_return(valid_response)
end
before do
allow(Service).to receive_messages(new: service)
end
it 'does not require any parameters' do
expect_request
expect { Driver.new }.not_to raise_exception
end
context 'with :desired capabilities' do
it 'accepts value as a Symbol' do
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
platformName: 'windows']}})
expect {
expect { Driver.new(desired_capabilities: :ie) }.to have_deprecated(:desired_capabilities)
}.not_to raise_exception
end
it 'accepts Capabilities.ie' do
capabilities = Remote::Capabilities.ie(invalid: 'foobar')
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
platformName: 'windows',
invalid: 'foobar']}})
expect {
expect { Driver.new(desired_capabilities: capabilities) }.to have_deprecated(:desired_capabilities)
}.not_to raise_exception
end
it 'accepts constructed Capabilities with Snake Case as Symbols' do
capabilities = Remote::Capabilities.new(browser_name: 'internet explorer', invalid: 'foobar')
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
invalid: 'foobar']}})
expect {
expect { Driver.new(desired_capabilities: capabilities) }.to have_deprecated(:desired_capabilities)
}.not_to raise_exception
end
it 'accepts constructed Capabilities with Camel Case as Symbols' do
capabilities = Remote::Capabilities.new(browserName: 'internet explorer', invalid: 'foobar')
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
invalid: 'foobar']}})
expect {
expect { Driver.new(desired_capabilities: capabilities) }.to have_deprecated(:desired_capabilities)
}.not_to raise_exception
end
it 'accepts constructed Capabilities with Camel Case as Strings' do
capabilities = Remote::Capabilities.new('browserName' => 'internet explorer', 'invalid' => 'foobar')
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
invalid: 'foobar']}})
expect {
expect { Driver.new(desired_capabilities: capabilities) }.to have_deprecated(:desired_capabilities)
}.not_to raise_exception
end
it 'accepts Hash with Camel Case keys as Symbols' do
capabilities = {browserName: 'internet explorer', invalid: 'foobar'}
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
invalid: 'foobar']}})
expect {
expect { Driver.new(desired_capabilities: capabilities) }.to have_deprecated(:desired_capabilities)
}.not_to raise_exception
end
it 'accepts Hash with Camel Case keys as Strings' do
capabilities = {"browserName" => 'internet explorer', "invalid" => 'foobar'}
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
invalid: 'foobar']}})
expect {
expect { Driver.new(desired_capabilities: capabilities) }.to have_deprecated(:desired_capabilities)
}.not_to raise_exception
end
end
it 'accepts provided Options as sole parameter' do
opts = {invalid: 'foobar', args: ['-f']}
expect_request(body: {capabilities: {firstMatch: ["browserName": "internet explorer",
"se:ieOptions": {"invalid": "foobar",
"nativeEvents": true,
"ie.browserCommandLineSwitches": "-f"}]}})
expect {
expect { Driver.new(options: Options.new(**opts)) }.to have_deprecated(:browser_options)
}.not_to raise_exception
end
it 'accepts combination of Options and Capabilities' do
caps = Remote::Capabilities.ie(invalid: 'foobar')
browser_opts = {args: ['-f']}
expect_request(body: {capabilities: {firstMatch: ["browserName": "internet explorer",
"platformName": "windows",
"invalid": "foobar",
"se:ieOptions": {"nativeEvents": true,
"ie.browserCommandLineSwitches": "-f"}]}})
expect {
expect {
Driver.new(options: Options.new(**browser_opts), desired_capabilities: caps)
}.to have_deprecated(%i[browser_options desired_capabilities])
}.not_to raise_exception
end
it 'raises an ArgumentError if parameter is not recognized' do
msg = 'Unable to create a driver with parameters: {:invalid=>"foo"}'
expect { Driver.new(invalid: 'foo') }.to raise_error(ArgumentError, msg)
end
context 'with :capabilities' do
it 'accepts value as a Symbol' do
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
platformName: 'windows']}})
expect { Driver.new(capabilities: :ie) }.not_to raise_exception
end
it 'accepts Capabilities.ie' do
capabilities = Remote::Capabilities.ie(invalid: 'foobar')
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
platformName: 'windows',
invalid: 'foobar']}})
expect { Driver.new(capabilities: capabilities) }.not_to raise_exception
end
it 'accepts constructed Capabilities with Snake Case as Symbols' do
capabilities = Remote::Capabilities.new(browser_name: 'internet explorer', invalid: 'foobar')
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer", invalid: 'foobar']}})
expect { Driver.new(capabilities: capabilities) }.not_to raise_exception
end
it 'accepts constructed Capabilities with Camel Case as Symbols' do
capabilities = Remote::Capabilities.new(browserName: 'internet explorer', invalid: 'foobar')
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer", invalid: 'foobar']}})
expect { Driver.new(capabilities: capabilities) }.not_to raise_exception
end
it 'accepts constructed Capabilities with Camel Case as Strings' do
capabilities = Remote::Capabilities.new('browserName' => 'internet explorer', 'invalid' => 'foobar')
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer", invalid: 'foobar']}})
expect { Driver.new(capabilities: capabilities) }.not_to raise_exception
end
it 'accepts Hash with Camel Case keys as Symbols but is deprecated' do
capabilities = {browserName: 'internet explorer', invalid: 'foobar'}
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer", invalid: 'foobar']}})
expect {
expect { Driver.new(capabilities: capabilities) }.to have_deprecated(:capabilities_hash)
}.not_to raise_exception
end
it 'accepts Hash with Camel Case keys as Strings but is deprecated' do
capabilities = {"browserName" => 'internet explorer', "invalid" => 'foobar'}
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer", invalid: 'foobar']}})
expect {
expect { Driver.new(capabilities: capabilities) }.to have_deprecated(:capabilities_hash)
}.not_to raise_exception
end
context 'when value is an Array' do
let(:as_json_object) do
Class.new do
def as_json(*)
{'company:key': 'value'}
end
end
end
it 'with Options instance' do
browser_opts = {start_page: 'http://selenium.dev'}
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
'se:ieOptions': {"startPage": 'http://selenium.dev',
'nativeEvents': true}]}})
expect { Driver.new(capabilities: [Options.new(**browser_opts)]) }.not_to raise_exception
end
it 'with Capabilities instance' do
capabilities = Remote::Capabilities.new(browser_name: 'internet explorer', invalid: 'foobar')
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer", invalid: 'foobar']}})
expect { Driver.new(capabilities: [capabilities]) }.not_to raise_exception
end
it 'with Options instance and an instance of a custom object responding to #as_json' do
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
'se:ieOptions': {"nativeEvents": true},
'company:key': 'value']}})
expect { Driver.new(capabilities: [Options.new, as_json_object.new]) }.not_to raise_exception
end
it 'with Options instance, Capabilities instance and instance of a custom object responding to #as_json' do
capabilities = Remote::Capabilities.new(browser_name: 'internet explorer', invalid: 'foobar')
options = Options.new(start_page: 'http://selenium.dev')
expect_request(body: {capabilities: {firstMatch: [browserName: "internet explorer",
invalid: 'foobar',
'se:ieOptions': {"startPage": 'http://selenium.dev',
'nativeEvents': true},
'company:key': 'value']}})
expect { Driver.new(capabilities: [capabilities, options, as_json_object.new]) }.not_to raise_exception
end
end
end
end
end # IE
end # WebDriver
end # Selenium
| {
"pile_set_name": "Github"
} |
package cn.mldn.microboot;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
@SpringBootTest(classes = StartSpringBootMain.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class AppTest {
@Test
public void testStart() throws Exception {
Thread.sleep(Long.MAX_VALUE);
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2014-2015 The Notify Authors. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
package notify
import (
"errors"
"os"
"path/filepath"
"strings"
)
const all = ^Event(0)
const sep = string(os.PathSeparator)
var errDepth = errors.New("exceeded allowed iteration count (circular symlink?)")
func min(i, j int) int {
if i > j {
return j
}
return i
}
func max(i, j int) int {
if i < j {
return j
}
return i
}
// must panics if err is non-nil.
func must(err error) {
if err != nil {
panic(err)
}
}
// nonil gives first non-nil error from the given arguments.
func nonil(err ...error) error {
for _, err := range err {
if err != nil {
return err
}
}
return nil
}
func cleanpath(path string) (realpath string, isrec bool, err error) {
if strings.HasSuffix(path, "...") {
isrec = true
path = path[:len(path)-3]
}
if path, err = filepath.Abs(path); err != nil {
return "", false, err
}
if path, err = canonical(path); err != nil {
return "", false, err
}
return path, isrec, nil
}
// canonical resolves any symlink in the given path and returns it in a clean form.
// It expects the path to be absolute. It fails to resolve circular symlinks by
// maintaining a simple iteration limit.
func canonical(p string) (string, error) {
p, err := filepath.Abs(p)
if err != nil {
return "", err
}
for i, j, depth := 1, 0, 1; i < len(p); i, depth = i+1, depth+1 {
if depth > 128 {
return "", &os.PathError{Op: "canonical", Path: p, Err: errDepth}
}
if j = strings.IndexRune(p[i:], '/'); j == -1 {
j, i = i, len(p)
} else {
j, i = i, i+j
}
fi, err := os.Lstat(p[:i])
if err != nil {
return "", err
}
if fi.Mode()&os.ModeSymlink == os.ModeSymlink {
s, err := os.Readlink(p[:i])
if err != nil {
return "", err
}
if filepath.IsAbs(s) {
p = "/" + s + p[i:]
} else {
p = p[:j] + s + p[i:]
}
i = 1 // no guarantee s is canonical, start all over
}
}
return filepath.Clean(p), nil
}
func joinevents(events []Event) (e Event) {
if len(events) == 0 {
e = All
} else {
for _, event := range events {
e |= event
}
}
return
}
func split(s string) (string, string) {
if i := lastIndexSep(s); i != -1 {
return s[:i], s[i+1:]
}
return "", s
}
func base(s string) string {
if i := lastIndexSep(s); i != -1 {
return s[i+1:]
}
return s
}
func indexbase(root, name string) int {
if n, m := len(root), len(name); m >= n && name[:n] == root &&
(n == m || name[n] == os.PathSeparator) {
return min(n+1, m)
}
return -1
}
func indexSep(s string) int {
for i := 0; i < len(s); i++ {
if s[i] == os.PathSeparator {
return i
}
}
return -1
}
func lastIndexSep(s string) int {
for i := len(s) - 1; i >= 0; i-- {
if s[i] == os.PathSeparator {
return i
}
}
return -1
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* Pi Engine (http://piengine.org)
*
* @link http://code.piengine.org for the Pi Engine source repository
* @copyright Copyright (c) Pi Engine http://piengine.org
* @license http://piengine.org/license.txt BSD 3-Clause License
* @package Registry
*/
namespace Module\Page\Registry;
use Pi;
use Pi\Application\Registry\AbstractRegistry;
/**
* Page navigation menu
*
* @author Taiwen Jiang <[email protected]>
*/
class Nav extends AbstractRegistry
{
/** @var string Module name */
protected $module = 'page';
/**
* {@inheritDoc}
*/
protected function loadDynamic($options = [])
{
$list = [];
$model = Pi::model('page', $this->module);
$select = $model->select();
$select->where(['active' => 1, 'nav_order > ?' => 0]);
$select->order('nav_order ASC');
$select->columns(['id', 'title', 'name', 'slug']);
$rowset = $model->selectWith($select);
foreach ($rowset as $row) {
$id = (int)$row['id'];
$name = $row['slug'] ?: $row['name'];
$url = Pi::service('url')->assemble('page', [
'module' => $this->module,
'name' => $name,
]);
$item = [
'id' => $id,
'title' => $row['title'],
'url' => $url,
];
$list[$id] = $item;
}
return $list;
}
/**
* {@inheritDoc}
* @param array
*/
public function read()
{
$options = [];
$result = $this->loadData($options);
return $result;
}
/**
* {@inheritDoc}
* @param bool $name
*/
public function create()
{
$this->clear('');
$this->read();
return true;
}
/**
* {@inheritDoc}
*/
public function setNamespace($meta = '')
{
return parent::setNamespace('');
}
/**
* {@inheritDoc}
*/
public function flush()
{
return $this->clear('');
}
}
| {
"pile_set_name": "Github"
} |
#version 430 core
layout (local_size_x = 16, local_size_y = 16) in;
layout (binding = 0, rgba32f) uniform writeonly image2D normalmap;
uniform sampler2D heightmap;
uniform int N;
uniform float normalStrength;
void main(void)
{
// z0 -- z1 -- z2
// | | |
// z3 -- h -- z4
// | | |
// z5 -- z6 -- z7
ivec2 x = ivec2(gl_GlobalInvocationID.xy);
vec2 texCoord = gl_GlobalInvocationID.xy/float(N);
float texelSize = 1.0/N;
float z0 = texture(heightmap, texCoord + vec2(-texelSize,-texelSize)).r;
float z1 = texture(heightmap, texCoord + vec2(0,-texelSize)).r;
float z2 = texture(heightmap, texCoord + vec2(texelSize,-texelSize)).r;
float z3 = texture(heightmap, texCoord + vec2(-texelSize,0)).r;
float z4 = texture(heightmap, texCoord + vec2(texelSize,0)).r;
float z5 = texture(heightmap, texCoord + vec2(-texelSize,texelSize)).r;
float z6 = texture(heightmap, texCoord + vec2(0,texelSize)).r;
float z7 = texture(heightmap, texCoord + vec2(texelSize,texelSize)).r;
vec3 normal;
// Sobel Filter
normal.z = 1.0/normalStrength;
normal.x = z0 + 2*z3 + z5 - z2 - 2*z4 - z7;
normal.y = z0 + 2*z1 + z2 -z5 - 2*z6 - z7;
imageStore(normalmap, x, vec4(normalize(normal),1));
} | {
"pile_set_name": "Github"
} |
S : "a" ;
: "b" ;
: "c" ;
: "a" A "a" ;
: "b" A "b" ;
: "c" A "c" ;
A : "a" A "a" ;
: "b" A "b" ;
: "c" A "c" ;
| {
"pile_set_name": "Github"
} |
/*
* This file is part of wl12xx
*
* Copyright (C) 2012 Texas Instruments. All rights reserved.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include "event.h"
#include "scan.h"
#include "../wlcore/cmd.h"
#include "../wlcore/debug.h"
int wl12xx_wait_for_event(struct wl1271 *wl, enum wlcore_wait_event event,
bool *timeout)
{
u32 local_event;
switch (event) {
case WLCORE_EVENT_ROLE_STOP_COMPLETE:
local_event = ROLE_STOP_COMPLETE_EVENT_ID;
break;
case WLCORE_EVENT_PEER_REMOVE_COMPLETE:
local_event = PEER_REMOVE_COMPLETE_EVENT_ID;
break;
default:
/* event not implemented */
return 0;
}
return wlcore_cmd_wait_for_event_or_timeout(wl, local_event, timeout);
}
int wl12xx_process_mailbox_events(struct wl1271 *wl)
{
struct wl12xx_event_mailbox *mbox = wl->mbox;
u32 vector;
vector = le32_to_cpu(mbox->events_vector);
vector &= ~(le32_to_cpu(mbox->events_mask));
wl1271_debug(DEBUG_EVENT, "MBOX vector: 0x%x", vector);
if (vector & SCAN_COMPLETE_EVENT_ID) {
wl1271_debug(DEBUG_EVENT, "status: 0x%x",
mbox->scheduled_scan_status);
if (wl->scan_wlvif)
wl12xx_scan_completed(wl, wl->scan_wlvif);
}
if (vector & PERIODIC_SCAN_REPORT_EVENT_ID) {
wl1271_debug(DEBUG_EVENT,
"PERIODIC_SCAN_REPORT_EVENT (status 0x%0x)",
mbox->scheduled_scan_status);
wlcore_scan_sched_scan_results(wl);
}
if (vector & PERIODIC_SCAN_COMPLETE_EVENT_ID)
wlcore_event_sched_scan_completed(wl,
mbox->scheduled_scan_status);
if (vector & SOFT_GEMINI_SENSE_EVENT_ID)
wlcore_event_soft_gemini_sense(wl,
mbox->soft_gemini_sense_info);
if (vector & BSS_LOSE_EVENT_ID)
wlcore_event_beacon_loss(wl, 0xff);
if (vector & RSSI_SNR_TRIGGER_0_EVENT_ID)
wlcore_event_rssi_trigger(wl, mbox->rssi_snr_trigger_metric);
if (vector & BA_SESSION_RX_CONSTRAINT_EVENT_ID)
wlcore_event_ba_rx_constraint(wl,
BIT(mbox->role_id),
mbox->rx_ba_allowed);
if (vector & CHANNEL_SWITCH_COMPLETE_EVENT_ID)
wlcore_event_channel_switch(wl, 0xff,
mbox->channel_switch_status);
if (vector & DUMMY_PACKET_EVENT_ID)
wlcore_event_dummy_packet(wl);
/*
* "TX retries exceeded" has a different meaning according to mode.
* In AP mode the offending station is disconnected.
*/
if (vector & MAX_TX_RETRY_EVENT_ID)
wlcore_event_max_tx_failure(wl,
le16_to_cpu(mbox->sta_tx_retry_exceeded));
if (vector & INACTIVE_STA_EVENT_ID)
wlcore_event_inactive_sta(wl,
le16_to_cpu(mbox->sta_aging_status));
if (vector & REMAIN_ON_CHANNEL_COMPLETE_EVENT_ID)
wlcore_event_roc_complete(wl);
return 0;
}
| {
"pile_set_name": "Github"
} |
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
<string>${app.name}</string>
<key>CFBundleExecutable</key>
<string>${app.executable}</string>
<key>CFBundleIdentifier</key>
<string>${app.id}</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>${app.name}</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>${app.version}</string>
<key>CFBundleSignature</key>
<string>????</string>
<key>CFBundleVersion</key>
<string>${app.build}</string>
<key>LSRequiresIPhoneOS</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>
<key>UIStatusBarHidden</key>
<false/>
<key>UIDeviceFamily</key>
<array>
<integer>1</integer>
<integer>2</integer>
</array>
<key>UIRequiredDeviceCapabilities</key>
<array>
<string>armv7</string>
<string>opengles-2</string>
</array>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
</array>
</dict>
</plist>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1996, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
* (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
*
* The original version of this source code and documentation is copyrighted
* and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These
* materials are provided under terms of a License Agreement between Taligent
* and Sun. This technology is protected by multiple US and International
* patents. This notice and attribution to Taligent may not be removed.
* Taligent is a registered trademark of Taligent, Inc.
*
*/
package java.text;
import java.io.InvalidObjectException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
/**
* <code>MessageFormat</code> provides a means to produce concatenated
* messages in a language-neutral way. Use this to construct messages
* displayed for end users.
*
* <p>
* <code>MessageFormat</code> takes a set of objects, formats them, then
* inserts the formatted strings into the pattern at the appropriate places.
*
* <p>
* <strong>Note:</strong>
* <code>MessageFormat</code> differs from the other <code>Format</code>
* classes in that you create a <code>MessageFormat</code> object with one
* of its constructors (not with a <code>getInstance</code> style factory
* method). The factory methods aren't necessary because <code>MessageFormat</code>
* itself doesn't implement locale specific behavior. Any locale specific
* behavior is defined by the pattern that you provide as well as the
* subformats used for inserted arguments.
*
* <h3><a id="patterns">Patterns and Their Interpretation</a></h3>
*
* <code>MessageFormat</code> uses patterns of the following form:
* <blockquote><pre>
* <i>MessageFormatPattern:</i>
* <i>String</i>
* <i>MessageFormatPattern</i> <i>FormatElement</i> <i>String</i>
*
* <i>FormatElement:</i>
* { <i>ArgumentIndex</i> }
* { <i>ArgumentIndex</i> , <i>FormatType</i> }
* { <i>ArgumentIndex</i> , <i>FormatType</i> , <i>FormatStyle</i> }
*
* <i>FormatType: one of </i>
* number date time choice
*
* <i>FormatStyle:</i>
* short
* medium
* long
* full
* integer
* currency
* percent
* <i>SubformatPattern</i>
* </pre></blockquote>
*
* <p>Within a <i>String</i>, a pair of single quotes can be used to
* quote any arbitrary characters except single quotes. For example,
* pattern string <code>"'{0}'"</code> represents string
* <code>"{0}"</code>, not a <i>FormatElement</i>. A single quote itself
* must be represented by doubled single quotes {@code ''} throughout a
* <i>String</i>. For example, pattern string <code>"'{''}'"</code> is
* interpreted as a sequence of <code>'{</code> (start of quoting and a
* left curly brace), <code>''</code> (a single quote), and
* <code>}'</code> (a right curly brace and end of quoting),
* <em>not</em> <code>'{'</code> and <code>'}'</code> (quoted left and
* right curly braces): representing string <code>"{'}"</code>,
* <em>not</em> <code>"{}"</code>.
*
* <p>A <i>SubformatPattern</i> is interpreted by its corresponding
* subformat, and subformat-dependent pattern rules apply. For example,
* pattern string <code>"{1,number,<u>$'#',##</u>}"</code>
* (<i>SubformatPattern</i> with underline) will produce a number format
* with the pound-sign quoted, with a result such as: {@code
* "$#31,45"}. Refer to each {@code Format} subclass documentation for
* details.
*
* <p>Any unmatched quote is treated as closed at the end of the given
* pattern. For example, pattern string {@code "'{0}"} is treated as
* pattern {@code "'{0}'"}.
*
* <p>Any curly braces within an unquoted pattern must be balanced. For
* example, <code>"ab {0} de"</code> and <code>"ab '}' de"</code> are
* valid patterns, but <code>"ab {0'}' de"</code>, <code>"ab } de"</code>
* and <code>"''{''"</code> are not.
*
* <dl><dt><b>Warning:</b><dd>The rules for using quotes within message
* format patterns unfortunately have shown to be somewhat confusing.
* In particular, it isn't always obvious to localizers whether single
* quotes need to be doubled or not. Make sure to inform localizers about
* the rules, and tell them (for example, by using comments in resource
* bundle source files) which strings will be processed by {@code MessageFormat}.
* Note that localizers may need to use single quotes in translated
* strings where the original version doesn't have them.
* </dl>
* <p>
* The <i>ArgumentIndex</i> value is a non-negative integer written
* using the digits {@code '0'} through {@code '9'}, and represents an index into the
* {@code arguments} array passed to the {@code format} methods
* or the result array returned by the {@code parse} methods.
* <p>
* The <i>FormatType</i> and <i>FormatStyle</i> values are used to create
* a {@code Format} instance for the format element. The following
* table shows how the values map to {@code Format} instances. Combinations not
* shown in the table are illegal. A <i>SubformatPattern</i> must
* be a valid pattern string for the {@code Format} subclass used.
*
* <table class="plain">
* <caption style="display:none">Shows how FormatType and FormatStyle values map to Format instances</caption>
* <thead>
* <tr>
* <th scope="col" class="TableHeadingColor">FormatType
* <th scope="col" class="TableHeadingColor">FormatStyle
* <th scope="col" class="TableHeadingColor">Subformat Created
* </thead>
* <tbody>
* <tr>
* <th scope="row" style="text-weight: normal"><i>(none)</i>
* <th scope="row" style="text-weight: normal"><i>(none)</i>
* <td>{@code null}
* <tr>
* <th scope="row" style="text-weight: normal" rowspan=5>{@code number}
* <th scope="row" style="text-weight: normal"><i>(none)</i>
* <td>{@link NumberFormat#getInstance(Locale) NumberFormat.getInstance}{@code (getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code integer}
* <td>{@link NumberFormat#getIntegerInstance(Locale) NumberFormat.getIntegerInstance}{@code (getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code currency}
* <td>{@link NumberFormat#getCurrencyInstance(Locale) NumberFormat.getCurrencyInstance}{@code (getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code percent}
* <td>{@link NumberFormat#getPercentInstance(Locale) NumberFormat.getPercentInstance}{@code (getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal"><i>SubformatPattern</i>
* <td>{@code new} {@link DecimalFormat#DecimalFormat(String,DecimalFormatSymbols) DecimalFormat}{@code (subformatPattern,} {@link DecimalFormatSymbols#getInstance(Locale) DecimalFormatSymbols.getInstance}{@code (getLocale()))}
* <tr>
* <th scope="row" style="text-weight: normal" rowspan=6>{@code date}
* <th scope="row" style="text-weight: normal"><i>(none)</i>
* <td>{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code short}
* <td>{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#SHORT}{@code , getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code medium}
* <td>{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code long}
* <td>{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#LONG}{@code , getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code full}
* <td>{@link DateFormat#getDateInstance(int,Locale) DateFormat.getDateInstance}{@code (}{@link DateFormat#FULL}{@code , getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal"><i>SubformatPattern</i>
* <td>{@code new} {@link SimpleDateFormat#SimpleDateFormat(String,Locale) SimpleDateFormat}{@code (subformatPattern, getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal" rowspan=6>{@code time}
* <th scope="row" style="text-weight: normal"><i>(none)</i>
* <td>{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code short}
* <td>{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#SHORT}{@code , getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code medium}
* <td>{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#DEFAULT}{@code , getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code long}
* <td>{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#LONG}{@code , getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code full}
* <td>{@link DateFormat#getTimeInstance(int,Locale) DateFormat.getTimeInstance}{@code (}{@link DateFormat#FULL}{@code , getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal"><i>SubformatPattern</i>
* <td>{@code new} {@link SimpleDateFormat#SimpleDateFormat(String,Locale) SimpleDateFormat}{@code (subformatPattern, getLocale())}
* <tr>
* <th scope="row" style="text-weight: normal">{@code choice}
* <th scope="row" style="text-weight: normal"><i>SubformatPattern</i>
* <td>{@code new} {@link ChoiceFormat#ChoiceFormat(String) ChoiceFormat}{@code (subformatPattern)}
* </tbody>
* </table>
*
* <h4>Usage Information</h4>
*
* <p>
* Here are some examples of usage.
* In real internationalized programs, the message format pattern and other
* static strings will, of course, be obtained from resource bundles.
* Other parameters will be dynamically determined at runtime.
* <p>
* The first example uses the static method <code>MessageFormat.format</code>,
* which internally creates a <code>MessageFormat</code> for one-time use:
* <blockquote><pre>
* int planet = 7;
* String event = "a disturbance in the Force";
*
* String result = MessageFormat.format(
* "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
* planet, new Date(), event);
* </pre></blockquote>
* The output is:
* <blockquote><pre>
* At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
* </pre></blockquote>
*
* <p>
* The following example creates a <code>MessageFormat</code> instance that
* can be used repeatedly:
* <blockquote><pre>
* int fileCount = 1273;
* String diskName = "MyDisk";
* Object[] testArgs = {new Long(fileCount), diskName};
*
* MessageFormat form = new MessageFormat(
* "The disk \"{1}\" contains {0} file(s).");
*
* System.out.println(form.format(testArgs));
* </pre></blockquote>
* The output with different values for <code>fileCount</code>:
* <blockquote><pre>
* The disk "MyDisk" contains 0 file(s).
* The disk "MyDisk" contains 1 file(s).
* The disk "MyDisk" contains 1,273 file(s).
* </pre></blockquote>
*
* <p>
* For more sophisticated patterns, you can use a <code>ChoiceFormat</code>
* to produce correct forms for singular and plural:
* <blockquote><pre>
* MessageFormat form = new MessageFormat("The disk \"{1}\" contains {0}.");
* double[] filelimits = {0,1,2};
* String[] filepart = {"no files","one file","{0,number} files"};
* ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
* form.setFormatByArgumentIndex(0, fileform);
*
* int fileCount = 1273;
* String diskName = "MyDisk";
* Object[] testArgs = {new Long(fileCount), diskName};
*
* System.out.println(form.format(testArgs));
* </pre></blockquote>
* The output with different values for <code>fileCount</code>:
* <blockquote><pre>
* The disk "MyDisk" contains no files.
* The disk "MyDisk" contains one file.
* The disk "MyDisk" contains 1,273 files.
* </pre></blockquote>
*
* <p>
* You can create the <code>ChoiceFormat</code> programmatically, as in the
* above example, or by using a pattern. See {@link ChoiceFormat}
* for more information.
* <blockquote><pre>{@code
* form.applyPattern(
* "There {0,choice,0#are no files|1#is one file|1<are {0,number,integer} files}.");
* }</pre></blockquote>
*
* <p>
* <strong>Note:</strong> As we see above, the string produced
* by a <code>ChoiceFormat</code> in <code>MessageFormat</code> is treated as special;
* occurrences of '{' are used to indicate subformats, and cause recursion.
* If you create both a <code>MessageFormat</code> and <code>ChoiceFormat</code>
* programmatically (instead of using the string patterns), then be careful not to
* produce a format that recurses on itself, which will cause an infinite loop.
* <p>
* When a single argument is parsed more than once in the string, the last match
* will be the final result of the parsing. For example,
* <blockquote><pre>
* MessageFormat mf = new MessageFormat("{0,number,#.##}, {0,number,#.#}");
* Object[] objs = {new Double(3.1415)};
* String result = mf.format( objs );
* // result now equals "3.14, 3.1"
* objs = null;
* objs = mf.parse(result, new ParsePosition(0));
* // objs now equals {new Double(3.1)}
* </pre></blockquote>
*
* <p>
* Likewise, parsing with a {@code MessageFormat} object using patterns containing
* multiple occurrences of the same argument would return the last match. For
* example,
* <blockquote><pre>
* MessageFormat mf = new MessageFormat("{0}, {0}, {0}");
* String forParsing = "x, y, z";
* Object[] objs = mf.parse(forParsing, new ParsePosition(0));
* // result now equals {new String("z")}
* </pre></blockquote>
*
* <h4><a id="synchronization">Synchronization</a></h4>
*
* <p>
* Message formats are not synchronized.
* It is recommended to create separate format instances for each thread.
* If multiple threads access a format concurrently, it must be synchronized
* externally.
*
* @see java.util.Locale
* @see Format
* @see NumberFormat
* @see DecimalFormat
* @see DecimalFormatSymbols
* @see ChoiceFormat
* @see DateFormat
* @see SimpleDateFormat
*
* @author Mark Davis
* @since 1.1
*/
public class MessageFormat extends Format {
private static final long serialVersionUID = 6479157306784022952L;
/**
* Constructs a MessageFormat for the default
* {@link java.util.Locale.Category#FORMAT FORMAT} locale and the
* specified pattern.
* The constructor first sets the locale, then parses the pattern and
* creates a list of subformats for the format elements contained in it.
* Patterns and their interpretation are specified in the
* <a href="#patterns">class description</a>.
*
* @param pattern the pattern for this message format
* @exception IllegalArgumentException if the pattern is invalid
* @exception NullPointerException if {@code pattern} is
* {@code null}
*/
public MessageFormat(String pattern) {
this.locale = Locale.getDefault(Locale.Category.FORMAT);
applyPattern(pattern);
}
/**
* Constructs a MessageFormat for the specified locale and
* pattern.
* The constructor first sets the locale, then parses the pattern and
* creates a list of subformats for the format elements contained in it.
* Patterns and their interpretation are specified in the
* <a href="#patterns">class description</a>.
*
* @param pattern the pattern for this message format
* @param locale the locale for this message format
* @exception IllegalArgumentException if the pattern is invalid
* @exception NullPointerException if {@code pattern} is
* {@code null}
* @since 1.4
*/
public MessageFormat(String pattern, Locale locale) {
this.locale = locale;
applyPattern(pattern);
}
/**
* Sets the locale to be used when creating or comparing subformats.
* This affects subsequent calls
* <ul>
* <li>to the {@link #applyPattern applyPattern}
* and {@link #toPattern toPattern} methods if format elements specify
* a format type and therefore have the subformats created in the
* <code>applyPattern</code> method, as well as
* <li>to the <code>format</code> and
* {@link #formatToCharacterIterator formatToCharacterIterator} methods
* if format elements do not specify a format type and therefore have
* the subformats created in the formatting methods.
* </ul>
* Subformats that have already been created are not affected.
*
* @param locale the locale to be used when creating or comparing subformats
*/
public void setLocale(Locale locale) {
this.locale = locale;
}
/**
* Gets the locale that's used when creating or comparing subformats.
*
* @return the locale used when creating or comparing subformats
*/
public Locale getLocale() {
return locale;
}
/**
* Sets the pattern used by this message format.
* The method parses the pattern and creates a list of subformats
* for the format elements contained in it.
* Patterns and their interpretation are specified in the
* <a href="#patterns">class description</a>.
*
* @param pattern the pattern for this message format
* @exception IllegalArgumentException if the pattern is invalid
* @exception NullPointerException if {@code pattern} is
* {@code null}
*/
@SuppressWarnings("fallthrough") // fallthrough in switch is expected, suppress it
public void applyPattern(String pattern) {
StringBuilder[] segments = new StringBuilder[4];
// Allocate only segments[SEG_RAW] here. The rest are
// allocated on demand.
segments[SEG_RAW] = new StringBuilder();
int part = SEG_RAW;
int formatNumber = 0;
boolean inQuote = false;
int braceStack = 0;
maxOffset = -1;
for (int i = 0; i < pattern.length(); ++i) {
char ch = pattern.charAt(i);
if (part == SEG_RAW) {
if (ch == '\'') {
if (i + 1 < pattern.length()
&& pattern.charAt(i+1) == '\'') {
segments[part].append(ch); // handle doubles
++i;
} else {
inQuote = !inQuote;
}
} else if (ch == '{' && !inQuote) {
part = SEG_INDEX;
if (segments[SEG_INDEX] == null) {
segments[SEG_INDEX] = new StringBuilder();
}
} else {
segments[part].append(ch);
}
} else {
if (inQuote) { // just copy quotes in parts
segments[part].append(ch);
if (ch == '\'') {
inQuote = false;
}
} else {
switch (ch) {
case ',':
if (part < SEG_MODIFIER) {
if (segments[++part] == null) {
segments[part] = new StringBuilder();
}
} else {
segments[part].append(ch);
}
break;
case '{':
++braceStack;
segments[part].append(ch);
break;
case '}':
if (braceStack == 0) {
part = SEG_RAW;
makeFormat(i, formatNumber, segments);
formatNumber++;
// throw away other segments
segments[SEG_INDEX] = null;
segments[SEG_TYPE] = null;
segments[SEG_MODIFIER] = null;
} else {
--braceStack;
segments[part].append(ch);
}
break;
case ' ':
// Skip any leading space chars for SEG_TYPE.
if (part != SEG_TYPE || segments[SEG_TYPE].length() > 0) {
segments[part].append(ch);
}
break;
case '\'':
inQuote = true;
// fall through, so we keep quotes in other parts
default:
segments[part].append(ch);
break;
}
}
}
}
if (braceStack == 0 && part != 0) {
maxOffset = -1;
throw new IllegalArgumentException("Unmatched braces in the pattern.");
}
this.pattern = segments[0].toString();
}
/**
* Returns a pattern representing the current state of the message format.
* The string is constructed from internal information and therefore
* does not necessarily equal the previously applied pattern.
*
* @return a pattern representing the current state of the message format
*/
public String toPattern() {
// later, make this more extensible
int lastOffset = 0;
StringBuilder result = new StringBuilder();
for (int i = 0; i <= maxOffset; ++i) {
copyAndFixQuotes(pattern, lastOffset, offsets[i], result);
lastOffset = offsets[i];
result.append('{').append(argumentNumbers[i]);
Format fmt = formats[i];
if (fmt == null) {
// do nothing, string format
} else if (fmt instanceof NumberFormat) {
if (fmt.equals(NumberFormat.getInstance(locale))) {
result.append(",number");
} else if (fmt.equals(NumberFormat.getCurrencyInstance(locale))) {
result.append(",number,currency");
} else if (fmt.equals(NumberFormat.getPercentInstance(locale))) {
result.append(",number,percent");
} else if (fmt.equals(NumberFormat.getIntegerInstance(locale))) {
result.append(",number,integer");
} else {
if (fmt instanceof DecimalFormat) {
result.append(",number,").append(((DecimalFormat)fmt).toPattern());
} else if (fmt instanceof ChoiceFormat) {
result.append(",choice,").append(((ChoiceFormat)fmt).toPattern());
} else {
// UNKNOWN
}
}
} else if (fmt instanceof DateFormat) {
int index;
for (index = MODIFIER_DEFAULT; index < DATE_TIME_MODIFIERS.length; index++) {
DateFormat df = DateFormat.getDateInstance(DATE_TIME_MODIFIERS[index],
locale);
if (fmt.equals(df)) {
result.append(",date");
break;
}
df = DateFormat.getTimeInstance(DATE_TIME_MODIFIERS[index],
locale);
if (fmt.equals(df)) {
result.append(",time");
break;
}
}
if (index >= DATE_TIME_MODIFIERS.length) {
if (fmt instanceof SimpleDateFormat) {
result.append(",date,").append(((SimpleDateFormat)fmt).toPattern());
} else {
// UNKNOWN
}
} else if (index != MODIFIER_DEFAULT) {
result.append(',').append(DATE_TIME_MODIFIER_KEYWORDS[index]);
}
} else {
//result.append(", unknown");
}
result.append('}');
}
copyAndFixQuotes(pattern, lastOffset, pattern.length(), result);
return result.toString();
}
/**
* Sets the formats to use for the values passed into
* <code>format</code> methods or returned from <code>parse</code>
* methods. The indices of elements in <code>newFormats</code>
* correspond to the argument indices used in the previously set
* pattern string.
* The order of formats in <code>newFormats</code> thus corresponds to
* the order of elements in the <code>arguments</code> array passed
* to the <code>format</code> methods or the result array returned
* by the <code>parse</code> methods.
* <p>
* If an argument index is used for more than one format element
* in the pattern string, then the corresponding new format is used
* for all such format elements. If an argument index is not used
* for any format element in the pattern string, then the
* corresponding new format is ignored. If fewer formats are provided
* than needed, then only the formats for argument indices less
* than <code>newFormats.length</code> are replaced.
*
* @param newFormats the new formats to use
* @exception NullPointerException if <code>newFormats</code> is null
* @since 1.4
*/
public void setFormatsByArgumentIndex(Format[] newFormats) {
for (int i = 0; i <= maxOffset; i++) {
int j = argumentNumbers[i];
if (j < newFormats.length) {
formats[i] = newFormats[j];
}
}
}
/**
* Sets the formats to use for the format elements in the
* previously set pattern string.
* The order of formats in <code>newFormats</code> corresponds to
* the order of format elements in the pattern string.
* <p>
* If more formats are provided than needed by the pattern string,
* the remaining ones are ignored. If fewer formats are provided
* than needed, then only the first <code>newFormats.length</code>
* formats are replaced.
* <p>
* Since the order of format elements in a pattern string often
* changes during localization, it is generally better to use the
* {@link #setFormatsByArgumentIndex setFormatsByArgumentIndex}
* method, which assumes an order of formats corresponding to the
* order of elements in the <code>arguments</code> array passed to
* the <code>format</code> methods or the result array returned by
* the <code>parse</code> methods.
*
* @param newFormats the new formats to use
* @exception NullPointerException if <code>newFormats</code> is null
*/
public void setFormats(Format[] newFormats) {
int runsToCopy = newFormats.length;
if (runsToCopy > maxOffset + 1) {
runsToCopy = maxOffset + 1;
}
for (int i = 0; i < runsToCopy; i++) {
formats[i] = newFormats[i];
}
}
/**
* Sets the format to use for the format elements within the
* previously set pattern string that use the given argument
* index.
* The argument index is part of the format element definition and
* represents an index into the <code>arguments</code> array passed
* to the <code>format</code> methods or the result array returned
* by the <code>parse</code> methods.
* <p>
* If the argument index is used for more than one format element
* in the pattern string, then the new format is used for all such
* format elements. If the argument index is not used for any format
* element in the pattern string, then the new format is ignored.
*
* @param argumentIndex the argument index for which to use the new format
* @param newFormat the new format to use
* @since 1.4
*/
public void setFormatByArgumentIndex(int argumentIndex, Format newFormat) {
for (int j = 0; j <= maxOffset; j++) {
if (argumentNumbers[j] == argumentIndex) {
formats[j] = newFormat;
}
}
}
/**
* Sets the format to use for the format element with the given
* format element index within the previously set pattern string.
* The format element index is the zero-based number of the format
* element counting from the start of the pattern string.
* <p>
* Since the order of format elements in a pattern string often
* changes during localization, it is generally better to use the
* {@link #setFormatByArgumentIndex setFormatByArgumentIndex}
* method, which accesses format elements based on the argument
* index they specify.
*
* @param formatElementIndex the index of a format element within the pattern
* @param newFormat the format to use for the specified format element
* @exception ArrayIndexOutOfBoundsException if {@code formatElementIndex} is equal to or
* larger than the number of format elements in the pattern string
*/
public void setFormat(int formatElementIndex, Format newFormat) {
if (formatElementIndex > maxOffset) {
throw new ArrayIndexOutOfBoundsException(formatElementIndex);
}
formats[formatElementIndex] = newFormat;
}
/**
* Gets the formats used for the values passed into
* <code>format</code> methods or returned from <code>parse</code>
* methods. The indices of elements in the returned array
* correspond to the argument indices used in the previously set
* pattern string.
* The order of formats in the returned array thus corresponds to
* the order of elements in the <code>arguments</code> array passed
* to the <code>format</code> methods or the result array returned
* by the <code>parse</code> methods.
* <p>
* If an argument index is used for more than one format element
* in the pattern string, then the format used for the last such
* format element is returned in the array. If an argument index
* is not used for any format element in the pattern string, then
* null is returned in the array.
*
* @return the formats used for the arguments within the pattern
* @since 1.4
*/
public Format[] getFormatsByArgumentIndex() {
int maximumArgumentNumber = -1;
for (int i = 0; i <= maxOffset; i++) {
if (argumentNumbers[i] > maximumArgumentNumber) {
maximumArgumentNumber = argumentNumbers[i];
}
}
Format[] resultArray = new Format[maximumArgumentNumber + 1];
for (int i = 0; i <= maxOffset; i++) {
resultArray[argumentNumbers[i]] = formats[i];
}
return resultArray;
}
/**
* Gets the formats used for the format elements in the
* previously set pattern string.
* The order of formats in the returned array corresponds to
* the order of format elements in the pattern string.
* <p>
* Since the order of format elements in a pattern string often
* changes during localization, it's generally better to use the
* {@link #getFormatsByArgumentIndex getFormatsByArgumentIndex}
* method, which assumes an order of formats corresponding to the
* order of elements in the <code>arguments</code> array passed to
* the <code>format</code> methods or the result array returned by
* the <code>parse</code> methods.
*
* @return the formats used for the format elements in the pattern
*/
public Format[] getFormats() {
Format[] resultArray = new Format[maxOffset + 1];
System.arraycopy(formats, 0, resultArray, 0, maxOffset + 1);
return resultArray;
}
/**
* Formats an array of objects and appends the <code>MessageFormat</code>'s
* pattern, with format elements replaced by the formatted objects, to the
* provided <code>StringBuffer</code>.
* <p>
* The text substituted for the individual format elements is derived from
* the current subformat of the format element and the
* <code>arguments</code> element at the format element's argument index
* as indicated by the first matching line of the following table. An
* argument is <i>unavailable</i> if <code>arguments</code> is
* <code>null</code> or has fewer than argumentIndex+1 elements.
*
* <table class="plain">
* <caption style="display:none">Examples of subformat,argument,and formatted text</caption>
* <thead>
* <tr>
* <th scope="col">Subformat
* <th scope="col">Argument
* <th scope="col">Formatted Text
* </thead>
* <tbody>
* <tr>
* <th scope="row" style="text-weight-normal" rowspan=2><i>any</i>
* <th scope="row" style="text-weight-normal"><i>unavailable</i>
* <td><code>"{" + argumentIndex + "}"</code>
* <tr>
* <th scope="row" style="text-weight-normal"><code>null</code>
* <td><code>"null"</code>
* <tr>
* <th scope="row" style="text-weight-normal"><code>instanceof ChoiceFormat</code>
* <th scope="row" style="text-weight-normal"><i>any</i>
* <td><code>subformat.format(argument).indexOf('{') >= 0 ?<br>
* (new MessageFormat(subformat.format(argument), getLocale())).format(argument) :
* subformat.format(argument)</code>
* <tr>
* <th scope="row" style="text-weight-normal"><code>!= null</code>
* <th scope="row" style="text-weight-normal"><i>any</i>
* <td><code>subformat.format(argument)</code>
* <tr>
* <th scope="row" style="text-weight-normal" rowspan=4><code>null</code>
* <th scope="row" style="text-weight-normal"><code>instanceof Number</code>
* <td><code>NumberFormat.getInstance(getLocale()).format(argument)</code>
* <tr>
* <th scope="row" style="text-weight-normal"><code>instanceof Date</code>
* <td><code>DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, getLocale()).format(argument)</code>
* <tr>
* <th scope="row" style="text-weight-normal"><code>instanceof String</code>
* <td><code>argument</code>
* <tr>
* <th scope="row" style="text-weight-normal"><i>any</i>
* <td><code>argument.toString()</code>
* </tbody>
* </table>
* <p>
* If <code>pos</code> is non-null, and refers to
* <code>Field.ARGUMENT</code>, the location of the first formatted
* string will be returned.
*
* @param arguments an array of objects to be formatted and substituted.
* @param result where text is appended.
* @param pos keeps track on the position of the first replaced argument
in the output string.
* @return the string buffer passed in as {@code result}, with formatted
* text appended
* @exception IllegalArgumentException if an argument in the
* <code>arguments</code> array is not of the type
* expected by the format element(s) that use it.
* @exception NullPointerException if {@code result} is {@code null}
*/
public final StringBuffer format(Object[] arguments, StringBuffer result,
FieldPosition pos)
{
return subformat(arguments, result, pos, null);
}
/**
* Creates a MessageFormat with the given pattern and uses it
* to format the given arguments. This is equivalent to
* <blockquote>
* <code>(new {@link #MessageFormat(String) MessageFormat}(pattern)).{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
* </blockquote>
*
* @param pattern the pattern string
* @param arguments object(s) to format
* @return the formatted string
* @exception IllegalArgumentException if the pattern is invalid,
* or if an argument in the <code>arguments</code> array
* is not of the type expected by the format element(s)
* that use it.
* @exception NullPointerException if {@code pattern} is {@code null}
*/
public static String format(String pattern, Object ... arguments) {
MessageFormat temp = new MessageFormat(pattern);
return temp.format(arguments);
}
// Overrides
/**
* Formats an array of objects and appends the <code>MessageFormat</code>'s
* pattern, with format elements replaced by the formatted objects, to the
* provided <code>StringBuffer</code>.
* This is equivalent to
* <blockquote>
* <code>{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}((Object[]) arguments, result, pos)</code>
* </blockquote>
*
* @param arguments an array of objects to be formatted and substituted.
* @param result where text is appended.
* @param pos keeps track on the position of the first replaced argument
* in the output string.
* @exception IllegalArgumentException if an argument in the
* <code>arguments</code> array is not of the type
* expected by the format element(s) that use it.
* @exception NullPointerException if {@code result} is {@code null}
*/
public final StringBuffer format(Object arguments, StringBuffer result,
FieldPosition pos)
{
return subformat((Object[]) arguments, result, pos, null);
}
/**
* Formats an array of objects and inserts them into the
* <code>MessageFormat</code>'s pattern, producing an
* <code>AttributedCharacterIterator</code>.
* You can use the returned <code>AttributedCharacterIterator</code>
* to build the resulting String, as well as to determine information
* about the resulting String.
* <p>
* The text of the returned <code>AttributedCharacterIterator</code> is
* the same that would be returned by
* <blockquote>
* <code>{@link #format(java.lang.Object[], java.lang.StringBuffer, java.text.FieldPosition) format}(arguments, new StringBuffer(), null).toString()</code>
* </blockquote>
* <p>
* In addition, the <code>AttributedCharacterIterator</code> contains at
* least attributes indicating where text was generated from an
* argument in the <code>arguments</code> array. The keys of these attributes are of
* type <code>MessageFormat.Field</code>, their values are
* <code>Integer</code> objects indicating the index in the <code>arguments</code>
* array of the argument from which the text was generated.
* <p>
* The attributes/value from the underlying <code>Format</code>
* instances that <code>MessageFormat</code> uses will also be
* placed in the resulting <code>AttributedCharacterIterator</code>.
* This allows you to not only find where an argument is placed in the
* resulting String, but also which fields it contains in turn.
*
* @param arguments an array of objects to be formatted and substituted.
* @return AttributedCharacterIterator describing the formatted value.
* @exception NullPointerException if <code>arguments</code> is null.
* @exception IllegalArgumentException if an argument in the
* <code>arguments</code> array is not of the type
* expected by the format element(s) that use it.
* @since 1.4
*/
public AttributedCharacterIterator formatToCharacterIterator(Object arguments) {
StringBuffer result = new StringBuffer();
ArrayList<AttributedCharacterIterator> iterators = new ArrayList<>();
if (arguments == null) {
throw new NullPointerException(
"formatToCharacterIterator must be passed non-null object");
}
subformat((Object[]) arguments, result, null, iterators);
if (iterators.size() == 0) {
return createAttributedCharacterIterator("");
}
return createAttributedCharacterIterator(
iterators.toArray(
new AttributedCharacterIterator[iterators.size()]));
}
/**
* Parses the string.
*
* <p>Caveats: The parse may fail in a number of circumstances.
* For example:
* <ul>
* <li>If one of the arguments does not occur in the pattern.
* <li>If the format of an argument loses information, such as
* with a choice format where a large number formats to "many".
* <li>Does not yet handle recursion (where
* the substituted strings contain {n} references.)
* <li>Will not always find a match (or the correct match)
* if some part of the parse is ambiguous.
* For example, if the pattern "{1},{2}" is used with the
* string arguments {"a,b", "c"}, it will format as "a,b,c".
* When the result is parsed, it will return {"a", "b,c"}.
* <li>If a single argument is parsed more than once in the string,
* then the later parse wins.
* </ul>
* When the parse fails, use ParsePosition.getErrorIndex() to find out
* where in the string the parsing failed. The returned error
* index is the starting offset of the sub-patterns that the string
* is comparing with. For example, if the parsing string "AAA {0} BBB"
* is comparing against the pattern "AAD {0} BBB", the error index is
* 0. When an error occurs, the call to this method will return null.
* If the source is null, return an empty array.
*
* @param source the string to parse
* @param pos the parse position
* @return an array of parsed objects
* @exception NullPointerException if {@code pos} is {@code null}
* for a non-null {@code source} string.
*/
public Object[] parse(String source, ParsePosition pos) {
if (source == null) {
Object[] empty = {};
return empty;
}
int maximumArgumentNumber = -1;
for (int i = 0; i <= maxOffset; i++) {
if (argumentNumbers[i] > maximumArgumentNumber) {
maximumArgumentNumber = argumentNumbers[i];
}
}
Object[] resultArray = new Object[maximumArgumentNumber + 1];
int patternOffset = 0;
int sourceOffset = pos.index;
ParsePosition tempStatus = new ParsePosition(0);
for (int i = 0; i <= maxOffset; ++i) {
// match up to format
int len = offsets[i] - patternOffset;
if (len == 0 || pattern.regionMatches(patternOffset,
source, sourceOffset, len)) {
sourceOffset += len;
patternOffset += len;
} else {
pos.errorIndex = sourceOffset;
return null; // leave index as is to signal error
}
// now use format
if (formats[i] == null) { // string format
// if at end, use longest possible match
// otherwise uses first match to intervening string
// does NOT recursively try all possibilities
int tempLength = (i != maxOffset) ? offsets[i+1] : pattern.length();
int next;
if (patternOffset >= tempLength) {
next = source.length();
}else{
next = source.indexOf(pattern.substring(patternOffset, tempLength),
sourceOffset);
}
if (next < 0) {
pos.errorIndex = sourceOffset;
return null; // leave index as is to signal error
} else {
String strValue= source.substring(sourceOffset,next);
if (!strValue.equals("{"+argumentNumbers[i]+"}"))
resultArray[argumentNumbers[i]]
= source.substring(sourceOffset,next);
sourceOffset = next;
}
} else {
tempStatus.index = sourceOffset;
resultArray[argumentNumbers[i]]
= formats[i].parseObject(source,tempStatus);
if (tempStatus.index == sourceOffset) {
pos.errorIndex = sourceOffset;
return null; // leave index as is to signal error
}
sourceOffset = tempStatus.index; // update
}
}
int len = pattern.length() - patternOffset;
if (len == 0 || pattern.regionMatches(patternOffset,
source, sourceOffset, len)) {
pos.index = sourceOffset + len;
} else {
pos.errorIndex = sourceOffset;
return null; // leave index as is to signal error
}
return resultArray;
}
/**
* Parses text from the beginning of the given string to produce an object
* array.
* The method may not use the entire text of the given string.
* <p>
* See the {@link #parse(String, ParsePosition)} method for more information
* on message parsing.
*
* @param source A <code>String</code> whose beginning should be parsed.
* @return An <code>Object</code> array parsed from the string.
* @exception ParseException if the beginning of the specified string
* cannot be parsed.
*/
public Object[] parse(String source) throws ParseException {
ParsePosition pos = new ParsePosition(0);
Object[] result = parse(source, pos);
if (pos.index == 0) // unchanged, returned object is null
throw new ParseException("MessageFormat parse error!", pos.errorIndex);
return result;
}
/**
* Parses text from a string to produce an object array.
* <p>
* The method attempts to parse text starting at the index given by
* <code>pos</code>.
* If parsing succeeds, then the index of <code>pos</code> is updated
* to the index after the last character used (parsing does not necessarily
* use all characters up to the end of the string), and the parsed
* object array is returned. The updated <code>pos</code> can be used to
* indicate the starting point for the next call to this method.
* If an error occurs, then the index of <code>pos</code> is not
* changed, the error index of <code>pos</code> is set to the index of
* the character where the error occurred, and null is returned.
* <p>
* See the {@link #parse(String, ParsePosition)} method for more information
* on message parsing.
*
* @param source A <code>String</code>, part of which should be parsed.
* @param pos A <code>ParsePosition</code> object with index and error
* index information as described above.
* @return An <code>Object</code> array parsed from the string. In case of
* error, returns null.
* @throws NullPointerException if {@code pos} is null.
*/
public Object parseObject(String source, ParsePosition pos) {
return parse(source, pos);
}
/**
* Creates and returns a copy of this object.
*
* @return a clone of this instance.
*/
public Object clone() {
MessageFormat other = (MessageFormat) super.clone();
// clone arrays. Can't do with utility because of bug in Cloneable
other.formats = formats.clone(); // shallow clone
for (int i = 0; i < formats.length; ++i) {
if (formats[i] != null)
other.formats[i] = (Format)formats[i].clone();
}
// for primitives or immutables, shallow clone is enough
other.offsets = offsets.clone();
other.argumentNumbers = argumentNumbers.clone();
return other;
}
/**
* Equality comparison between two message format objects
*/
public boolean equals(Object obj) {
if (this == obj) // quick check
return true;
if (obj == null || getClass() != obj.getClass())
return false;
MessageFormat other = (MessageFormat) obj;
return (maxOffset == other.maxOffset
&& pattern.equals(other.pattern)
&& ((locale != null && locale.equals(other.locale))
|| (locale == null && other.locale == null))
&& Arrays.equals(offsets,other.offsets)
&& Arrays.equals(argumentNumbers,other.argumentNumbers)
&& Arrays.equals(formats,other.formats));
}
/**
* Generates a hash code for the message format object.
*/
public int hashCode() {
return pattern.hashCode(); // enough for reasonable distribution
}
/**
* Defines constants that are used as attribute keys in the
* <code>AttributedCharacterIterator</code> returned
* from <code>MessageFormat.formatToCharacterIterator</code>.
*
* @since 1.4
*/
public static class Field extends Format.Field {
// Proclaim serial compatibility with 1.4 FCS
private static final long serialVersionUID = 7899943957617360810L;
/**
* Creates a Field with the specified name.
*
* @param name Name of the attribute
*/
protected Field(String name) {
super(name);
}
/**
* Resolves instances being deserialized to the predefined constants.
*
* @throws InvalidObjectException if the constant could not be
* resolved.
* @return resolved MessageFormat.Field constant
*/
protected Object readResolve() throws InvalidObjectException {
if (this.getClass() != MessageFormat.Field.class) {
throw new InvalidObjectException("subclass didn't correctly implement readResolve");
}
return ARGUMENT;
}
//
// The constants
//
/**
* Constant identifying a portion of a message that was generated
* from an argument passed into <code>formatToCharacterIterator</code>.
* The value associated with the key will be an <code>Integer</code>
* indicating the index in the <code>arguments</code> array of the
* argument from which the text was generated.
*/
public static final Field ARGUMENT =
new Field("message argument field");
}
// ===========================privates============================
/**
* The locale to use for formatting numbers and dates.
* @serial
*/
private Locale locale;
/**
* The string that the formatted values are to be plugged into. In other words, this
* is the pattern supplied on construction with all of the {} expressions taken out.
* @serial
*/
private String pattern = "";
/** The initially expected number of subformats in the format */
private static final int INITIAL_FORMATS = 10;
/**
* An array of formatters, which are used to format the arguments.
* @serial
*/
private Format[] formats = new Format[INITIAL_FORMATS];
/**
* The positions where the results of formatting each argument are to be inserted
* into the pattern.
* @serial
*/
private int[] offsets = new int[INITIAL_FORMATS];
/**
* The argument numbers corresponding to each formatter. (The formatters are stored
* in the order they occur in the pattern, not in the order in which the arguments
* are specified.)
* @serial
*/
private int[] argumentNumbers = new int[INITIAL_FORMATS];
/**
* One less than the number of entries in <code>offsets</code>. Can also be thought of
* as the index of the highest-numbered element in <code>offsets</code> that is being used.
* All of these arrays should have the same number of elements being used as <code>offsets</code>
* does, and so this variable suffices to tell us how many entries are in all of them.
* @serial
*/
private int maxOffset = -1;
/**
* Internal routine used by format. If {@code characterIterators} is
* {@code non-null}, AttributedCharacterIterator will be created from the
* subformats as necessary. If {@code characterIterators} is {@code null}
* and {@code fp} is {@code non-null} and identifies
* {@code Field.ARGUMENT} as the field attribute, the location of
* the first replaced argument will be set in it.
*
* @exception IllegalArgumentException if an argument in the
* <code>arguments</code> array is not of the type
* expected by the format element(s) that use it.
*/
private StringBuffer subformat(Object[] arguments, StringBuffer result,
FieldPosition fp, List<AttributedCharacterIterator> characterIterators) {
// note: this implementation assumes a fast substring & index.
// if this is not true, would be better to append chars one by one.
int lastOffset = 0;
int last = result.length();
for (int i = 0; i <= maxOffset; ++i) {
result.append(pattern, lastOffset, offsets[i]);
lastOffset = offsets[i];
int argumentNumber = argumentNumbers[i];
if (arguments == null || argumentNumber >= arguments.length) {
result.append('{').append(argumentNumber).append('}');
continue;
}
// int argRecursion = ((recursionProtection >> (argumentNumber*2)) & 0x3);
if (false) { // if (argRecursion == 3){
// prevent loop!!!
result.append('\uFFFD');
} else {
Object obj = arguments[argumentNumber];
String arg = null;
Format subFormatter = null;
if (obj == null) {
arg = "null";
} else if (formats[i] != null) {
subFormatter = formats[i];
if (subFormatter instanceof ChoiceFormat) {
arg = formats[i].format(obj);
if (arg.indexOf('{') >= 0) {
subFormatter = new MessageFormat(arg, locale);
obj = arguments;
arg = null;
}
}
} else if (obj instanceof Number) {
// format number if can
subFormatter = NumberFormat.getInstance(locale);
} else if (obj instanceof Date) {
// format a Date if can
subFormatter = DateFormat.getDateTimeInstance(
DateFormat.SHORT, DateFormat.SHORT, locale);//fix
} else if (obj instanceof String) {
arg = (String) obj;
} else {
arg = obj.toString();
if (arg == null) arg = "null";
}
// At this point we are in two states, either subFormatter
// is non-null indicating we should format obj using it,
// or arg is non-null and we should use it as the value.
if (characterIterators != null) {
// If characterIterators is non-null, it indicates we need
// to get the CharacterIterator from the child formatter.
if (last != result.length()) {
characterIterators.add(
createAttributedCharacterIterator(result.substring
(last)));
last = result.length();
}
if (subFormatter != null) {
AttributedCharacterIterator subIterator =
subFormatter.formatToCharacterIterator(obj);
append(result, subIterator);
if (last != result.length()) {
characterIterators.add(
createAttributedCharacterIterator(
subIterator, Field.ARGUMENT,
Integer.valueOf(argumentNumber)));
last = result.length();
}
arg = null;
}
if (arg != null && !arg.isEmpty()) {
result.append(arg);
characterIterators.add(
createAttributedCharacterIterator(
arg, Field.ARGUMENT,
Integer.valueOf(argumentNumber)));
last = result.length();
}
}
else {
if (subFormatter != null) {
arg = subFormatter.format(obj);
}
last = result.length();
result.append(arg);
if (i == 0 && fp != null && Field.ARGUMENT.equals(
fp.getFieldAttribute())) {
fp.setBeginIndex(last);
fp.setEndIndex(result.length());
}
last = result.length();
}
}
}
result.append(pattern, lastOffset, pattern.length());
if (characterIterators != null && last != result.length()) {
characterIterators.add(createAttributedCharacterIterator(
result.substring(last)));
}
return result;
}
/**
* Convenience method to append all the characters in
* <code>iterator</code> to the StringBuffer <code>result</code>.
*/
private void append(StringBuffer result, CharacterIterator iterator) {
if (iterator.first() != CharacterIterator.DONE) {
char aChar;
result.append(iterator.first());
while ((aChar = iterator.next()) != CharacterIterator.DONE) {
result.append(aChar);
}
}
}
// Indices for segments
private static final int SEG_RAW = 0;
private static final int SEG_INDEX = 1;
private static final int SEG_TYPE = 2;
private static final int SEG_MODIFIER = 3; // modifier or subformat
// Indices for type keywords
private static final int TYPE_NULL = 0;
private static final int TYPE_NUMBER = 1;
private static final int TYPE_DATE = 2;
private static final int TYPE_TIME = 3;
private static final int TYPE_CHOICE = 4;
private static final String[] TYPE_KEYWORDS = {
"",
"number",
"date",
"time",
"choice"
};
// Indices for number modifiers
private static final int MODIFIER_DEFAULT = 0; // common in number and date-time
private static final int MODIFIER_CURRENCY = 1;
private static final int MODIFIER_PERCENT = 2;
private static final int MODIFIER_INTEGER = 3;
private static final String[] NUMBER_MODIFIER_KEYWORDS = {
"",
"currency",
"percent",
"integer"
};
// Indices for date-time modifiers
private static final int MODIFIER_SHORT = 1;
private static final int MODIFIER_MEDIUM = 2;
private static final int MODIFIER_LONG = 3;
private static final int MODIFIER_FULL = 4;
private static final String[] DATE_TIME_MODIFIER_KEYWORDS = {
"",
"short",
"medium",
"long",
"full"
};
// Date-time style values corresponding to the date-time modifiers.
private static final int[] DATE_TIME_MODIFIERS = {
DateFormat.DEFAULT,
DateFormat.SHORT,
DateFormat.MEDIUM,
DateFormat.LONG,
DateFormat.FULL,
};
private void makeFormat(int position, int offsetNumber,
StringBuilder[] textSegments)
{
String[] segments = new String[textSegments.length];
for (int i = 0; i < textSegments.length; i++) {
StringBuilder oneseg = textSegments[i];
segments[i] = (oneseg != null) ? oneseg.toString() : "";
}
// get the argument number
int argumentNumber;
try {
argumentNumber = Integer.parseInt(segments[SEG_INDEX]); // always unlocalized!
} catch (NumberFormatException e) {
throw new IllegalArgumentException("can't parse argument number: "
+ segments[SEG_INDEX], e);
}
if (argumentNumber < 0) {
throw new IllegalArgumentException("negative argument number: "
+ argumentNumber);
}
// resize format information arrays if necessary
if (offsetNumber >= formats.length) {
int newLength = formats.length * 2;
Format[] newFormats = new Format[newLength];
int[] newOffsets = new int[newLength];
int[] newArgumentNumbers = new int[newLength];
System.arraycopy(formats, 0, newFormats, 0, maxOffset + 1);
System.arraycopy(offsets, 0, newOffsets, 0, maxOffset + 1);
System.arraycopy(argumentNumbers, 0, newArgumentNumbers, 0, maxOffset + 1);
formats = newFormats;
offsets = newOffsets;
argumentNumbers = newArgumentNumbers;
}
int oldMaxOffset = maxOffset;
maxOffset = offsetNumber;
offsets[offsetNumber] = segments[SEG_RAW].length();
argumentNumbers[offsetNumber] = argumentNumber;
// now get the format
Format newFormat = null;
if (!segments[SEG_TYPE].isEmpty()) {
int type = findKeyword(segments[SEG_TYPE], TYPE_KEYWORDS);
switch (type) {
case TYPE_NULL:
// Type "" is allowed. e.g., "{0,}", "{0,,}", and "{0,,#}"
// are treated as "{0}".
break;
case TYPE_NUMBER:
switch (findKeyword(segments[SEG_MODIFIER], NUMBER_MODIFIER_KEYWORDS)) {
case MODIFIER_DEFAULT:
newFormat = NumberFormat.getInstance(locale);
break;
case MODIFIER_CURRENCY:
newFormat = NumberFormat.getCurrencyInstance(locale);
break;
case MODIFIER_PERCENT:
newFormat = NumberFormat.getPercentInstance(locale);
break;
case MODIFIER_INTEGER:
newFormat = NumberFormat.getIntegerInstance(locale);
break;
default: // DecimalFormat pattern
try {
newFormat = new DecimalFormat(segments[SEG_MODIFIER],
DecimalFormatSymbols.getInstance(locale));
} catch (IllegalArgumentException e) {
maxOffset = oldMaxOffset;
throw e;
}
break;
}
break;
case TYPE_DATE:
case TYPE_TIME:
int mod = findKeyword(segments[SEG_MODIFIER], DATE_TIME_MODIFIER_KEYWORDS);
if (mod >= 0 && mod < DATE_TIME_MODIFIER_KEYWORDS.length) {
if (type == TYPE_DATE) {
newFormat = DateFormat.getDateInstance(DATE_TIME_MODIFIERS[mod],
locale);
} else {
newFormat = DateFormat.getTimeInstance(DATE_TIME_MODIFIERS[mod],
locale);
}
} else {
// SimpleDateFormat pattern
try {
newFormat = new SimpleDateFormat(segments[SEG_MODIFIER], locale);
} catch (IllegalArgumentException e) {
maxOffset = oldMaxOffset;
throw e;
}
}
break;
case TYPE_CHOICE:
try {
// ChoiceFormat pattern
newFormat = new ChoiceFormat(segments[SEG_MODIFIER]);
} catch (Exception e) {
maxOffset = oldMaxOffset;
throw new IllegalArgumentException("Choice Pattern incorrect: "
+ segments[SEG_MODIFIER], e);
}
break;
default:
maxOffset = oldMaxOffset;
throw new IllegalArgumentException("unknown format type: " +
segments[SEG_TYPE]);
}
}
formats[offsetNumber] = newFormat;
}
private static final int findKeyword(String s, String[] list) {
for (int i = 0; i < list.length; ++i) {
if (s.equals(list[i]))
return i;
}
// Try trimmed lowercase.
String ls = s.trim().toLowerCase(Locale.ROOT);
if (ls != s) {
for (int i = 0; i < list.length; ++i) {
if (ls.equals(list[i]))
return i;
}
}
return -1;
}
private static final void copyAndFixQuotes(String source, int start, int end,
StringBuilder target) {
boolean quoted = false;
for (int i = start; i < end; ++i) {
char ch = source.charAt(i);
if (ch == '{') {
if (!quoted) {
target.append('\'');
quoted = true;
}
target.append(ch);
} else if (ch == '\'') {
target.append("''");
} else {
if (quoted) {
target.append('\'');
quoted = false;
}
target.append(ch);
}
}
if (quoted) {
target.append('\'');
}
}
/**
* After reading an object from the input stream, do a simple verification
* to maintain class invariants.
* @throws InvalidObjectException if the objects read from the stream is invalid.
*/
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
boolean isValid = maxOffset >= -1
&& formats.length > maxOffset
&& offsets.length > maxOffset
&& argumentNumbers.length > maxOffset;
if (isValid) {
int lastOffset = pattern.length() + 1;
for (int i = maxOffset; i >= 0; --i) {
if ((offsets[i] < 0) || (offsets[i] > lastOffset)) {
isValid = false;
break;
} else {
lastOffset = offsets[i];
}
}
}
if (!isValid) {
throw new InvalidObjectException("Could not reconstruct MessageFormat from corrupt stream.");
}
}
}
| {
"pile_set_name": "Github"
} |
// array.h -- Thatcher Ulrich <[email protected]> 2003, Vitaly Alexeev <[email protected]> 2007
// This source code has been donated to the Public Domain. Do
// whatever you want with it.
// Action Script Array implementation code for the gameswf SWF player library.
#ifndef GAMESWF_AS_ARRAY_H
#define GAMESWF_AS_ARRAY_H
#include "gameswf/gameswf_action.h" // for as_object
#include "gameswf/gameswf_function.h"
namespace gameswf
{
// constructor of an Array object
void as_global_array_ctor(const fn_call& fn);
// this is an Array object
struct as_array : public as_object
{
// Unique id of a gameswf resource
enum { m_class_id = AS_ARRAY };
virtual bool is(int class_id) const
{
if (m_class_id == class_id) return true;
else return as_object::is(class_id);
}
exported_module virtual bool get_member(const tu_stringi& name, as_value* val);
exported_module virtual bool set_member(const tu_stringi& name, const as_value& val);
virtual void clear_refs(hash<as_object*, bool>* visited_objects, as_object* this_ptr);
exported_module as_array(player* player);
exported_module virtual const char* to_string();
exported_module void push(const as_value& val) { m_array.push_back(val); }
exported_module void remove(int index) { m_array.remove(index); }
exported_module void insert(int index, const as_value& val) { m_array.insert(index, val); }
exported_module void sort(int options, as_function* compare_function);
exported_module int size() const { return m_array.size(); }
exported_module void resize(int size) { m_array.resize(size); }
tu_string m_string_value;
array<as_value> m_array;
};
// this is "_global.Array" object
struct as_global_array : public as_c_function
{
enum option
{
CASEINSENSITIVE = 1,
DESCENDING = 2,
UNIQUESORT = 4,
RETURNINDEXEDARRAY = 8,
NUMERIC = 16
};
as_global_array(player* player);
};
} // end namespace gameswf
#endif // GAMESWF_AS_ARRAY_H
// Local Variables:
// mode: C++
// c-basic-offset: 8
// tab-width: 8
// indent-tabs-mode: t
// End:
| {
"pile_set_name": "Github"
} |
# 集群的使用方法
> **注释**:本文描述了如何使用 Akka 集群。
有关 Akka 集群概念的介绍,请参阅「[集群规范](https://github.com/guobinhit/akka-guide/blob/master/articles/cluster-specification.md)」。
Akka 集群的核心是集群成员(`cluster membership`),以跟踪哪些节点是集群的一部分以及它们的健康状况。
## 依赖
为了使用 Akka 集群,你必须在你的项目中添加如下依赖:
```xml
<!-- Maven -->
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-cluster_2.11</artifactId>
<version>2.5.19</version>
</dependency>
<!-- Gradle -->
dependencies {
compile group: 'com.typesafe.akka', name: 'akka-cluster_2.11', version: '2.5.19'
}
<!-- sbt -->
libraryDependencies += "com.typesafe.akka" %% "akka-cluster" % "2.5.19"
```
## 示例项目
你可以查看「[集群示例](https://developer.lightbend.com/start/?group=akka&project=akka-samples-cluster-java)」项目,以了解 Akka 集群的实际使用情况。
## 何时何地使用 Akka 集群?
如果你打算使用微服务架构或传统的分布式应用程序,则必须进行架构的选择。这个选择将影响你应该如何使用 Akka 集群。
### 微服务
微服务(`Microservices`)具有许多吸引人的特性,例如,微服务的独立性允许多个更小、更专注的团队能够更频繁地提供新功能,并且能够更快地响应业务机会。响应式微服务(`Reactive Microservices`)应该是独立的、自主的,并且有一个单一的责任,正如 Jonas Bonér 在「[Reactive Microsystems: The Evolution of Microservices at Scale](https://info.lightbend.com/ebook-reactive-microservices-the-evolution-of-microservices-at-scale-register.html)」一书中所指出的那样。
在微服务架构中,你应该考虑服务内部和服务之间的通信。
一般来说,我们建议不要在不同的服务之间使用 Akka 集群和 Actor 消息传递,因为这会导致服务之间的代码耦合过紧,并且难以独立地部署这些服务,这是使用微服务架构的主要原因之一。有关这方面的一些背景,请参见「[Lagom Framework](https://www.lagomframework.com/)」中关于「[Internal and External Communication](https://www.lagomframework.com/documentation/current/java/InternalAndExternalCommunication.html)」的讨论,其中每个微服务都是一个 Akka 集群。
单个服务的节点需要较少的去耦。它们共享相同的代码,由单个团队或个人作为一个集合部署在一起。在滚动部署(`rolling deployment`)期间,可能有两个版本同时运行,但整个集合的部署只有一个控制点。因此,业务内通信可以利用 Akka 集群的故障管理和 Actor 消息传递使用方便和性能优异的优点。
在不同的服务之间,「[Akka HTTP](https://doc.akka.io/docs/akka-http/current/)」或「[Akka gRPC](https://developer.lightbend.com/docs/akka-grpc/current/)」可用于同步(但不阻塞)通信,而「[Akka Streams Kafka](https://doc.akka.io/docs/akka-stream-kafka/current/home.html)」或其他「[Alpakka](https://doc.akka.io/docs/alpakka/current/)」连接器可用于集成异步通信。所有这些通信机制都可以很好地与端到端的反向压力(`end-to-end back-pressure`)的消息流配合使用,同步通信工具也可以用于单个请求-响应(`request response`)交互。同样重要的是要注意,当使用这些工具时,通信的双方不必使用 Akka 实现,编程语言也不重要。
## 传统的分布式应用
我们承认微服务也带来了许多新的挑战,它不是构建应用程序的唯一方法。传统的分布式应用程序可能不那么复杂,在许多情况下也工作得很好。例如,对于一个小的初创企业,只有一个团队,在那里构建一个应用程序,上市时间就是一切。Akka 集群可以有效地用于构建这种分布式应用程序。
在这种情况下,你只有一个部署单元,从单个代码库构建(或使用传统的二进制依赖性管理模块化),但使用单个集群跨多个节点部署。更紧密的耦合是可以的,因为有一个部署和控制的中心点。在某些情况下,节点可能具有专门的运行时角色,这意味着集群不是完全相同的(例如,“前端”和“后端”节点,或专用的`master/worker`节点),但如果这些节点是从相同的构建构件运行的,则这只是一种运行时行为,不会造成与紧耦合中可能出现的问题相同的问题。
紧耦合的分布式应用程序多年来为行业和许多 Akka 用户提供了良好的服务,仍然是一个有效的选择。
## 分布式整体
还有一种反模式(`anti-pattern`),有时被称为“分布式整体(`distributed monolith`)”。你有多个彼此独立地构建和部署的服务,但是它们之间的紧密耦合使得这非常危险,例如共享集群、共享代码和服务 API 调用的依赖项,或者共享数据库模式。由于代码和部署单元的物理分离,有一种错误的自主权感,但是由于一个服务的实现中的更改泄漏到其他服务的行为中,你很可能会遇到问题。参见 Ben Christensen 的「[Don’t Build a Distributed Monolith](https://www.microservices.com/talks/dont-build-a-distributed-monolith/)」。
在这种情况下,发现自己处于这种状态的组织通常会通过集中协调多个服务的部署来作出反应,此时,在承担成本的同时,你已经失去了微服务的主要好处。你正处于一个中间状态,以一种单独的方式构建和部署那些并不真正可分离的东西。有些人这样做,有些人设法使它工作,但这不是我们推荐的,它需要小心管理。
## 一个简单的集群示例
以下配置允许使用`Cluster`扩展。它加入集群,Actor 订阅集群成员事件并记录它们。
`application.conf`配置如下:
```java
akka {
actor {
provider = "cluster"
}
remote {
log-remote-lifecycle-events = off
netty.tcp {
hostname = "127.0.0.1"
port = 0
}
}
cluster {
seed-nodes = [
"akka.tcp://[email protected]:2551",
"akka.tcp://[email protected]:2552"]
# auto downing is NOT safe for production deployments.
# you may want to use it during development, read more about it in the docs.
#
# auto-down-unreachable-after = 10s
}
}
# Enable metrics extension in akka-cluster-metrics.
akka.extensions=["akka.cluster.metrics.ClusterMetricsExtension"]
# Sigar native library extract location during tests.
# Note: use per-jvm-instance folder when running multiple jvm on one host.
akka.cluster.metrics.native-library-extract-folder=${user.dir}/target/native
```
要在 Akka 项目中启用集群功能,你至少应该添加「[Remoting](https://doc.akka.io/docs/akka/current/remoting.html)」设置,但使用集群。`akka.cluster.seed-nodes`通常也应该添加到`application.conf`文件中。
- **注释**:如果你在 Docker 容器中运行 Akka,或者由于其他原因,节点具有单独的内部和外部 IP 地址,则必须根据 NAT 或 Docker 容器中的 Akka 配置远程处理。
种子节点是为集群的初始、自动、连接配置的接触点。
请注意,如果要在不同的计算机上启动节点,则需要在`application.conf`中指定计算机的 IP 地址或主机名,而不是`127.0.0.1`。
使用集群扩展的 Actor 可能如下所示:
```java
/*
* Copyright (C) 2018 Lightbend Inc. <https://www.lightbend.com>
*/
package jdocs.cluster;
import akka.actor.AbstractActor;
import akka.cluster.Cluster;
import akka.cluster.ClusterEvent;
import akka.cluster.ClusterEvent.MemberEvent;
import akka.cluster.ClusterEvent.MemberUp;
import akka.cluster.ClusterEvent.MemberRemoved;
import akka.cluster.ClusterEvent.UnreachableMember;
import akka.event.Logging;
import akka.event.LoggingAdapter;
public class SimpleClusterListener extends AbstractActor {
LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);
Cluster cluster = Cluster.get(getContext().getSystem());
//subscribe to cluster changes
@Override
public void preStart() {
cluster.subscribe(getSelf(), ClusterEvent.initialStateAsEvents(),
MemberEvent.class, UnreachableMember.class);
}
//re-subscribe when restart
@Override
public void postStop() {
cluster.unsubscribe(getSelf());
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(MemberUp.class, mUp -> {
log.info("Member is Up: {}", mUp.member());
})
.match(UnreachableMember.class, mUnreachable -> {
log.info("Member detected as unreachable: {}", mUnreachable.member());
})
.match(MemberRemoved.class, mRemoved -> {
log.info("Member is Removed: {}", mRemoved.member());
})
.match(MemberEvent.class, message -> {
// ignore
})
.build();
}
}
```
Actor 将自己注册为某些集群事件的订阅者。它在订阅开始时接收与集群当前状态对应的事件,然后接收集群中发生更改的事件。
你自己运行这个例子最简单的方法是下载准备好的「[Akka Cluster Sample with Java](https://example.lightbend.com/v1/download/akka-samples-cluster-java)」和教程。它包含有关如何运行`SimpleClusterApp`的说明。此示例的源代码可以在「[Akka Samples Repository](https://developer.lightbend.com/start/?group=akka&project=akka-sample-cluster-java)」中找到。
## 联接到种子节点
- **注释**:当在云系统上启动集群时,如 Kubernetes、AWS、Google Cloud、Azure、Mesos 或其他维护 DNS 或其他发现节点的方式,你可能希望使用开源「[Akka Cluster Bootstrap](https://developer.lightbend.com/docs/akka-management/current/bootstrap/index.html)」模块实现的自动加入过程。
### 联接已配置的种子节点
你可以决定是手动加入集群,还是自动加入到配置的初始接触点,即所谓的种子节点。在连接过程之后,种子节点并不特殊,它们以与其他节点完全相同的方式参与集群。
当一个新节点启动时,它会向所有种子节点发送一条消息,然后向首先应答的节点发送`join`命令。如果没有任何种子节点响应(可能尚未启动),则会重试此过程,直到成功或关闭。
你在`application.conf`配置文件中定义种子节点:
```java
akka.cluster.seed-nodes = [
"akka.tcp://ClusterSystem@host1:2552",
"akka.tcp://ClusterSystem@host2:2552"]
```
当 JVM 启动时,也可以将其定义 Java 系统属性:
```java
-Dakka.cluster.seed-nodes.0=akka.tcp://ClusterSystem@host1:2552
-Dakka.cluster.seed-nodes.1=akka.tcp://ClusterSystem@host2:2552
```
种子节点可以任意顺序启动,不需要运行所有的种子节点,但是在初始启动集群时必须启动配置列表`seed-nodes`中第一个元素的节点,否则其他种子节点将不会初始化,其他节点也不能加入集群。第一个种子节点之所以特殊,其原因是避免从空集群开始时形成分离的岛(`islands`)。同时启动所有配置的种子节点是最快的(顺序无关紧要),否则它可以占用配置的`seed-node-timeout`,直到节点可以加入。
一旦启动了两个以上的种子节点,就可以关闭第一个种子节点。如果第一个种子节点重新启动,它将首先尝试加入现有集群中的其他种子节点。**请注意,如果同时停止所有种子节点,并使用相同的`seed-nodes`配置重新启动它们,它们将自己加入并形成新的集群,而不是加入现有集群的其余节点**。这可能是不需要的,应该通过将几个节点列为种子节点来避免冗余,并且不要同时停止所有节点。
### 使用 Cluster Bootstrap 自动联接种子节点
与手动配置种子节点(这在开发或静态分配的节点 IP 中很有用)不同,你可能希望使用云提供者(`cloud providers`)或集群协调者(`cluster orchestrator`)或其他某种形式的服务发现(如托管 DNS)来自动发现种子节点。开源的 Akka 管理库包括「[Cluster Bootstrap](https://developer.lightbend.com/docs/akka-management/current/bootstrap/index.html)」模块,它就专注于处理这个问题。有关更多详细信息,请参阅其文档。
### 使用 joinSeedNodes 编程联接到种子节点
你还可以使用`Cluster.get(system).joinSeedNodes`以编程方式连接种子节点,这在启动时使用一些外部工具或 API 动态发现其他节点时很有吸引力。当使用`joinSeedNodes`时,除了应该是第一个种子节点的节点之外,不应该包括节点本身,并且应该将其放在`joinSeedNodes`的参数中的第一个节点中。
```java
import akka.actor.Address;
import akka.cluster.Cluster;
final Cluster cluster = Cluster.get(system);
List<Address> list = new LinkedList<>(); //replace this with your method to dynamically get seed nodes
cluster.joinSeedNodes(list);
```
在配置属性`seed-node-timeout`中定义的时间段之后,将自动重试联系种子节点失败的尝试。在尝试联接失败之后,经过`retry-unsuccessful-join-after`配置的时间,将自动重试加入特定种子节点失败的尝试。重试意味着它尝试联系所有种子节点,然后连接首先应答的节点。如果种子节点列表中的第一个节点在配置的`seed-node-timeout`时间内无法联系任何其他种子节点,那么它将连接自身。
默认情况下,给定种子节点的联接将无限期重试,直到成功联接为止。如果配置超时失败,则可以中止该进程。当中止时,它将运行「[Coordinated Shutdown](https://doc.akka.io/docs/akka/current/actors.html#coordinated-shutdown)」,默认情况下将终止`ActorSystem`。也可以将 Coordinated Shutdown 配置为退出 JVM。如果`seed-nodes`是动态组装的,并且在尝试失败后使用新`seed-nodes`重新启动,则定义此超时非常有用。
```java
akka.cluster.shutdown-after-unsuccessful-join-seed-nodes = 20s
akka.coordinated-shutdown.terminate-actor-system = on
```
如果不配置种子节点或使用`joinSeedNodes`,则需要手动加入集群,可以使用「[JMX](https://doc.akka.io/docs/akka/current/cluster-usage.html#cluster-jmx)」或「[HTTP](https://doc.akka.io/docs/akka/current/cluster-usage.html#cluster-http)」执行。
你可以加入集群中的任何节点。它不必配置为种子节点。请注意,你只能联接到现有的集群成员,这意味着对于`bootstrapping`,某些节点必须联接到自己,然后以下节点可以联接它们以组成集群。
Actor 系统只能加入一次集群。其他尝试将被忽略。当它成功加入时,必须重新启动才能加入另一个集群或再次加入同一个集群。重新启动后可以使用相同的主机名和端口,当它成为集群中现有成员的新化身(`incarnation`),尝试加入时,将从集群中删除现有成员,然后允许它加入。
- **注释**:对于集群中的所有成员,`ActorSystem`的名称必须相同。当你启动`ActorSystem`时,将给出`ActorSystem`的名称。
## Downing
当故障检测器(`failure detector`)认为某个成员`unreachable`时,不允许`leader`履行其职责,例如将新加入成员的状态更改为`Up`。节点必须首先再次`reachable`,或者`unreachable`的成员的状态必须更改为`Down`。将状态更改为`Down`可以自动或手动执行。默认情况下,必须使用「[JMX](https://doc.akka.io/docs/akka/current/cluster-usage.html#cluster-jmx)」或「[HTTP](https://doc.akka.io/docs/akka/current/cluster-usage.html#cluster-http)」手动完成。
它也可以用`Cluster.get(system).down(address)`以编程方式执行。
如果一个节点仍在运行,并且将其自身视为`Down`,那么它将关闭。如果在运行时将`run-coordinated-shutdown-when-down`设置为`on`(默认值),则 Coordinated Shutdown 将自动运行,但是节点不会尝试优雅地离开集群,因此不会发生分片和单例迁移。
「[Split Brain Resolver](https://developer.lightbend.com/docs/akka-commercial-addons/current/split-brain-resolver.html)」是「[Lightbend Reactive Platform](https://www.lightbend.com/lightbend-platform)」的一部分,它提供了一种针对`downing`问题的预打包(`pre-packaged`)解决方案。如果你不使用 RP,你无论如何都应该仔细阅读 Split Brain Resolver 的文档,并确保你使用的解决方案能够处理此处描述的问题。
### Auto-downing (DO NOT USE)
有一个自动`downing`的功能,但你不应该在生产中使用。出于测试目的,你可以通过配置启用它:
```java
akka.cluster.auto-down-unreachable-after = 120s
```
这意味着在配置时间内没联接成功的话,集群的`leader`将自动改变`unreachable`节点的状态为`down`。
这是一种从集群成员中删除`unreachable`节点的天真方法。它在开发过程中是有用的,但在生产环境中,它最终会破坏集群。当发生网络分裂时,分裂的两侧将看到另一侧`unreachable`,并将其从集群中移除。这导致了两个分开的、断开的簇的形成,称为 Split Brain。
此行为不限于网络分裂(`network partitions`)。如果集群中的节点过载,或者经历长 GC 暂停,也可能发生这种情况。
- **警告**:
- 我们建议不要在生产中使用 Akka 集群的`auto-down`功能。它对生产系统有多种不良后果。
- 如果你使用的是 Cluster Singleton 或 Cluster Sharding,那么它可能会破坏这些特性提供的契约。两者都保证了一个 Actor 在集群中是唯一的。启用`auto-down`功能后,可能形成多个独立集群。当这种情况发生时,保证的唯一性将不再是真的,从而导致系统中的不良行为。
- 当 Akka Persistence 与 Cluster Sharding 结合使用时,这种情况更为严重。在这种情况下,缺少唯一性的 Actor 会导致多个 Actor 写入同一个日志。Akka Persistence 的工作是单一写入原则(`single writer principle`)。拥有多个写入者会损坏日志并使其无法使用。
- 最后,即使你不使用 Persistence、Sharding 或 Singletons 等特性,`auto-downing`也会导致系统形成多个小集群。这些小集群将彼此独立。它们将无法通信,因此你可能会遇到性能下降。一旦出现这种情况,就需要人工干预来修正集群。
- 由于这些问题,`auto-downing`不应该在生产环境中使用。
## Leaving
从集群中删除成员有两种方法。
你可以停止 Actor 系统(或 JVM 进程)。它将被检测为`unreachable`,并在自动或手动`downing`后移除,如上文所述。
如果你告诉集群一个节点应该离开,那么可以执行更优雅的退出。这可以使用「[JMX](https://doc.akka.io/docs/akka/current/cluster-usage.html#cluster-jmx)」或「[HTTP](https://doc.akka.io/docs/akka/current/cluster-usage.html#cluster-http)」执行。也可以通过以下方式以编程方式执行:
```java
final Cluster cluster = Cluster.get(system);
cluster.leave(cluster.selfAddress());
```
注意,这个命令可以发送给集群中的任何成员,不一定是要离开的成员。
当集群节点将自己视为`Exiting`时,Coordinated Shutdown 将自动运行,即从另一个节点退出将触发`leaving`节点上的关闭过程。当使用 Akka 集群时,会自动添加集群的优雅离开任务,包括 Cluster Singletons 的优雅关闭和 Cluster Sharding,即运行关闭过程也会触发尚未进行的优雅离开。
通常情况下,这是自动处理的,但在此过程中,如果出现网络故障,可能仍然需要将节点的状态设置为`Down`,以便完成删除。
## WeaklyUp 成员
如果一个节点是`unreachable`的,那么消息聚合是不可能的,因此`leader`的任何行为也是不可能的。但是,在这个场景中,我们仍然可能希望新节点加入集群。
如果不能达到聚合,加入成员将被提升为`WeaklyUp`,并成为集群的一部分。一旦达到消息聚合,`leader`就会把`WeaklyUp`的成员调为`Up`。
默认情况下启用此功能,但可以使用配置选项禁用此功能:
```java
akka.cluster.allow-weakly-up-members = off
```
你可以订阅`WeaklyUp`的成员事件,以使用处于此状态的成员,但你应该注意,网络分裂另一端的成员不知道新成员的存在。例如,在`quorum decisions`时,你不应该把`WeaklyUp`的成员计算在内。
## 订阅集群事件
可以使用`Cluster.get(system).subscribe`订阅集群成员的更改通知。
```java
cluster.subscribe(getSelf(), MemberEvent.class, UnreachableMember.class);
```
完整状态的快照`akka.cluster.ClusterEvent.CurrentClusterState`将作为第一条消息发送给订阅者,随后是在有更新事件时,再发送消息。
请注意,如果在完成初始联接过程之前启动订阅,则可能会收到一个空的`CurrentClusterState`,其中不包含成员,后面是已联接的其他节点的`MemberUp`事件。例如,当你在`cluster.join()`之后立即启动订阅时,可能会发生这种情况,如下所示。这是预期行为。当节点在集群中被接受后,你将收到该节点和其他节点的`MemberUp`。
```java
Cluster cluster = Cluster.get(getContext().getSystem());
cluster.join(cluster.selfAddress());
cluster.subscribe(getSelf(), MemberEvent.class, UnreachableMember.class);
```
为了避免在开始时接收空的`CurrentClusterState`,你可以像下例所示这样使用它,将订阅推迟到接收到自己节点的`MemberUp`事件为止:
```java
Cluster cluster = Cluster.get(getContext().getSystem());
cluster.join(cluster.selfAddress());
cluster.registerOnMemberUp(
() -> cluster.subscribe(getSelf(), MemberEvent.class, UnreachableMember.class)
);
```
如果你发现处理`CurrentClusterState`不方便,可以使用`ClusterEvent.initialStateAsEvents()`作为参数进行订阅。这意味着,你将收到与当前状态相对应的事件,以模拟在过去发生事件时,如果正在监听这些事件,你将看到的情况,而不是作为第一条消息接收`CurrentClusterState`。请注意,这些初始事件只对应于当前状态,而不是集群中实际发生的所有更改的完整历史记录。
```java
cluster.subscribe(getSelf(), ClusterEvent.initialStateAsEvents(),
MemberEvent.class, UnreachableMember.class);
```
跟踪成员生命周期的事件有:
- `ClusterEvent.MemberJoined`,新成员已加入集群,其状态已更改为`Joining`。
- `ClusterEvent.MemberUp`,新成员已加入集群,其状态已更改为`Up`。
- `ClusterEvent.MemberExited`,某个成员正在离开集群,其状态已更改为`Exiting`。请注意,在另一个节点上发布此事件时,该节点可能已关闭。
- `ClusterEvent.MemberRemoved`,成员已从集群中完全删除。
- `ClusterEvent.UnreachableMember`,一个成员被认为是`unreachable`,由至少一个其他节点的故障检测器检测到。
- `ClusterEvent.ReachableMember`,在`unreachable`之后,成员被认为是`reachable`的。以前检测到它不可访问的所有节点都再次检测到它是可访问的。
有更多类型的变更事件,请参阅扩展`akka.cluster.ClusterEvent.ClusterDomainEvent`类的 API 文档,以了解有关事件的详细信息。
有时,不订阅集群事件,只使用`Cluster.get(system).state()`获取完整成员状态是很方便的。请注意,此状态不一定与发布到集群订阅的事件同步。
### Worker Dial-in Example
让我们来看一个示例,该示例演示了名为`backend`的工作者如何检测并注册到名为`frontend`的新主节点。
示例应用程序提供了一个转换文本的服务。当一些文本发送到其中一个`frontend`服务时,它将被委托给一个`backend`,后者执行转换作业,并将结果发送回原始客户机。新的`backend`节点以及新的`frontend`节点可以在集群中动态地添加或删除。
消息:
```java
public interface TransformationMessages {
public static class TransformationJob implements Serializable {
private final String text;
public TransformationJob(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
public static class TransformationResult implements Serializable {
private final String text;
public TransformationResult(String text) {
this.text = text;
}
public String getText() {
return text;
}
@Override
public String toString() {
return "TransformationResult(" + text + ")";
}
}
public static class JobFailed implements Serializable {
private final String reason;
private final TransformationJob job;
public JobFailed(String reason, TransformationJob job) {
this.reason = reason;
this.job = job;
}
public String getReason() {
return reason;
}
public TransformationJob getJob() {
return job;
}
@Override
public String toString() {
return "JobFailed(" + reason + ")";
}
}
public static final String BACKEND_REGISTRATION = "BackendRegistration";
}
```
`backend`执行文件转换工作:
```java
public class TransformationBackend extends AbstractActor {
Cluster cluster = Cluster.get(getContext().getSystem());
//subscribe to cluster changes, MemberUp
@Override
public void preStart() {
cluster.subscribe(getSelf(), MemberUp.class);
}
//re-subscribe when restart
@Override
public void postStop() {
cluster.unsubscribe(getSelf());
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(TransformationJob.class, job -> {
getSender().tell(new TransformationResult(job.getText().toUpperCase()),
getSelf());
})
.match(CurrentClusterState.class, state -> {
for (Member member : state.getMembers()) {
if (member.status().equals(MemberStatus.up())) {
register(member);
}
}
})
.match(MemberUp.class, mUp -> {
register(mUp.member());
})
.build();
}
void register(Member member) {
if (member.hasRole("frontend"))
getContext().actorSelection(member.address() + "/user/frontend").tell(
BACKEND_REGISTRATION, getSelf());
}
}
```
请注意,`TransformationBackend` Actor 订阅集群事件以检测新的、潜在的`frontend`节点,并向它们发送注册消息,以便它们知道可以使用`backend`工作者。
接收用户作业并委托给已注册的`backend`的`frontend`节点:
```java
public class TransformationFrontend extends AbstractActor {
List<ActorRef> backends = new ArrayList<ActorRef>();
int jobCounter = 0;
@Override
public Receive createReceive() {
return receiveBuilder()
.match(TransformationJob.class, job -> backends.isEmpty(), job -> {
getSender().tell(
new JobFailed("Service unavailable, try again later", job),
getSender());
})
.match(TransformationJob.class, job -> {
jobCounter++;
backends.get(jobCounter % backends.size())
.forward(job, getContext());
})
.matchEquals(BACKEND_REGISTRATION, x -> {
getContext().watch(getSender());
backends.add(getSender());
})
.match(Terminated.class, terminated -> {
backends.remove(terminated.getActor());
})
.build();
}
}
```
请注意,`TransformationFrontend` Actor 监视已注册的`backend`,以便能够将其从可用`backend`列表中删除。Death Watch 对集群中的节点使用集群故障检测器,例如检测网络故障和 JVM 崩溃,并优雅地终止被监视的 Actor。当`unreachable`的集群节点被关闭和删除时,Death Watch 将向监视 Actor 生成`Terminated`消息。
在示例中运行`Worker Dial-in Example`最简单的方法是下载准备好的「[Akka Cluster Sample with Java](https://example.lightbend.com/v1/download/akka-samples-cluster-java)」和教程。它包含有关如何运行`Worker Dial-in Example`示例的说明。此示例的源代码可以在「[Akka Samples Repository](https://developer.lightbend.com/start/?group=akka&project=akka-sample-cluster-java)」中找到。
## 节点角色
并非集群的所有节点都需要执行相同的功能:可能有一个子集运行 Web 前端,一个子集运行数据访问层,一个子集用于数字处理。例如,通过集群感知路由器(`cluster-aware routers`)部署 Actor,可以考虑节点角色(`node roles`)以实现这种职责分配。
节点的角色在名为`akka.cluster.roles`的配置属性中定义,通常在启动脚本中将其定义为系统属性或环境变量。
节点的角色是可以订阅的`MemberEvent`中成员信息的一部分。
## 如何在达到群集大小时启动
一个常见的用例是在集群已经初始化、成员已经加入并且集群已经达到一定的大小之后启动 Actor。
通过配置选项,你可以在`leader`将`Joining`成员的状态更改为`Up`之前定义所需的成员数:
```java
akka.cluster.min-nr-of-members = 3
```
以类似的方式,你可以在`leader`将`Joining`成员的状态更改为`Up`之前,定义特定角色所需的成员数:
```java
akka.cluster.role {
frontend.min-nr-of-members = 1
backend.min-nr-of-members = 2
}
```
可以在`registerOnMemberUp`回调中启动 Actor,当当前成员状态更改为`Up`时,将调用该回调,例如集群至少具有已定义的成员数。
```java
Cluster.get(system).registerOnMemberUp(new Runnable() {
@Override
public void run() {
system.actorOf(Props.create(FactorialFrontend.class, upToN, true),
"factorialFrontend");
}
});
```
这个回调可以用于启动 Actor 以外的其他事情。
## 如何清理 Removed 状态的成员
你可以在`registerOnMemberRemoved`回调中进行一些清理,当当前成员状态更改为`Removed`或群集已关闭时,将调用该回调。
另一种方法是将任务注册到 Coordinated Shutdown 中。
- **注释**:在已关闭的群集上注册`OnMemberRemoved`回调,该回调将立即在调用方线程上调用,否则稍后当当前成员状态更改为`Removed`时将调用该回调。你可能希望在群集启动后安装一些清理处理,但在安装时群集可能已经关闭,这取决于竞争是否正常。
## 更高级别的群集工具
### Cluster Singleton
对于某些用例,确保集群中某个类型的某个 Actor 恰好运行在某个位置是方便的,有时也是强制的。
这可以通过订阅成员事件来实现,但有几个情况需要考虑。因此,这个特定的用例由「[Cluster Singleton](https://doc.akka.io/docs/akka/current/cluster-singleton.html)」覆盖。
### Cluster Sharding
将 Actor 分布在集群中的多个节点上,并支持使用其逻辑标识符与 Actor 进行交互,但不必关心它们在集群中的物理位置。
详见「[Cluster Sharding](https://doc.akka.io/docs/akka/current/cluster-sharding.html)」。
### Distributed Publish Subscribe
在集群中的 Actor 之间发布订阅消息,并使用 Actor 的逻辑路径发布点对点(`point-to-point `)消息,即发送方不必知道目标 Actor 正在哪个节点上运行。
详见「[Distributed Publish Subscribe](https://doc.akka.io/docs/akka/current/distributed-pub-sub.html)」。
### Cluster Client
从不是集群一部分的 Actor 系统到集群中某个地方运行的 Actor 的通信。客户端不必知道目标 Actor 正在哪个节点上运行。
详见「[Cluster Client](https://doc.akka.io/docs/akka/current/cluster-client.html)」。
### Distributed Data
当需要在 Akka 集群中的节点之间共享数据时,Akka 分布式数据(`Distributed Data`)非常有用。通过提供类似 API 的键值(`key-value`)存储的 Actor 访问数据。
详见「[Distributed Data](https://doc.akka.io/docs/akka/current/distributed-data.html)」。
### Cluster Aware Routers
所有路由(`routers`)都可以知道集群中的成员节点,即部署新的`routees`或在集群中的节点上查找`routees`。当一个节点无法访问或离开集群时,该节点的`routees`将自动从「[路由](https://doc.akka.io/docs/akka/current/routing.html)」中注销。当新节点加入集群时,会根据配置向路由添加额外的`routees`。
详见「[Cluster Aware Routers](https://doc.akka.io/docs/akka/current/cluster-routing.html)」。
### Cluster Metrics
集群的成员节点可以收集系统健康度量(`health metrics`),并将其发布到其他集群节点和系统事件总线(`system event bus`)上注册的订阅者。
详见「[Cluster Metrics](https://doc.akka.io/docs/akka/current/cluster-metrics.html)」。
## 故障检测器
在集群中,每个节点都由几个(默认最多 5 个)其他节点监控,当其中任何一个节点检测到`unreachable`该节点时,信息将通过`gossip`传播到集群的其余部分。换句话说,只要有一个节点将一个节点标记为`unreachable`,则集群的其余部分也将该节点标记为`unreachable`。
故障检测器(`failure detector`)还将检测节点是否可以再次`reachable`。当监视`unreachable`节点的所有节点再次检测到它是`reachable`时,在消息传播之后,集群将认为它是`reachable`的。
如果系统消息无法传递到节点,那么它将被隔离,然后它将无法从`unreachable`的状态返回。如果有太多未确认的系统消息(例如监视、终止、远程 Actor 部署、远程父级监控的 Actor 失败),则可能发生这种情况。然后需要将节点移动到`down`或`removed`状态,并且必须重新启动隔离节点的 Actor 系统,然后才能再次加入集群。
集群中的节点通过发送心跳来相互监控,以检测是否可以从集群的其余部分访问节点。心跳到达时间由「[The Phi Accrual Failure Detector](https://www.coord.c.titech.ac.jp/)」的实现来解释。
故障的等级由一个称为`phi`的值给出。`phi`故障检测器的基本思想是用动态调整的尺度来表示`phi`的值,以反映当前的网络状况。
`phi`值计算如下:
```
phi = -log10(1 - F(timeSinceLastHeartbeat))
```
式中,`F`是正态分布的累积分布函数,平均值和标准偏差根据历史心跳到达时间估计。
在配置中,你可以调整`akka.cluster.failure-detector.threshold`来定义什么时候将`phi`值视为故障。
低阈值容易产生许多误报,但可以确保在发生真正的崩溃时快速检测。相反,高阈值产生的错误更少,但需要更多的时间来检测实际的崩溃。默认阈值为`8`,适用于大多数情况。然而,在云环境中,例如 Amazon EC2,为了解决此类平台上有时出现的网络问题,其值可以增加到`12`。
下图说明了自上一次心跳以来,`phi`是如何随着时间的增加而增加的:

根据历史到达时间的平均值和标准偏差计算`phi`。前面的图表是`200ms`标准偏差的一个例子。如果心跳到达时的偏差较小,曲线会变陡,即可以更快地确定故障。对于`100ms`的标准偏差,曲线看起来是这样的:

为了能够承受突发的异常情况,例如垃圾收集暂停和短暂的网络故障,故障检测器可以通过`akka.cluster.failure-detector.acceptable-heartbeat-pause`配置一个边界值。你可能需要根据你的环境调整此配置。这就是配置`acceptable-heartbeat-pause`为`3s`的可接受心跳暂停的曲线:

Death Watch 对集群中的节点使用集群故障检测器,即它检测网络故障和 JVM 崩溃,并优雅地终止被监视的 Actor。当无法访问的群集节点被关闭和删除时,Death Watch 将向监视 Actor 生成`Terminated`消息。
如果在系统加载时遇到可疑的误报,你应该为集群 Actor 定义一个单独的调度程序,如「[Cluster Dispatcher](https://doc.akka.io/docs/akka/current/cluster-usage.html#cluster-dispatcher)」中所述的。
## 如何测试?
目前,使用`sbt multi-jvm`插件进行的测试只记录在 Scala 中。有关详细信息,请转到此页对应的 Scala 版本查看。
## 管理
### HTTP
HTTP API 提供了集群的信息和管理。详见「[Akka Management](https://developer.lightbend.com/docs/akka-management/current/?_ga=2.247638279.1425355925.1547861917-52773400.1547780943)」。
### JMX
集群的信息和管理以根名称`akka.Cluster`的 JMX MBeans 提供。JMX 信息可以用普通的 JMX 控制台,如 JConsole 或 JVisualVM 显示。
在 JMX 中,你可以:
- 查看属于集群的哪些成员
- 查看此节点的状态
- 查看每个成员的角色
- 将此节点连接到群集中的另一个节点
- 将群集中的任何节点标记为`down`
- 告诉群集中的任何节点离开
成员节点由格式为` akka.://@:`的地址标识。
### 命令行
- **警告**:`Deprecation warning`,命令行脚本已被否决,并计划在下一个主要版本中删除。使用带有`curl`或类似代码的 HTTP 管理 API。
可以使用「[Akka GitHub](https://github.com/akka/akka/tree/v2.5.19/akka-cluster/jmx-client)」中提供的脚本`akka-cluster`管理集群。将脚本和`jmxsh-R5.jar`放在同一个目录中。
不带参数运行它,可以查看有关如何使用脚本的说明:
```
Usage: ./akka-cluster <node-hostname> <jmx-port> <command> ...
Supported commands are:
join <node-url> - Sends request a JOIN node with the specified URL
leave <node-url> - Sends a request for node with URL to LEAVE the cluster
down <node-url> - Sends a request for marking node with URL as DOWN
member-status - Asks the member node for its current status
members - Asks the cluster for addresses of current members
unreachable - Asks the cluster for addresses of unreachable members
cluster-status - Asks the cluster for its current status (member ring,
unavailable nodes, meta data etc.)
leader - Asks the cluster who the current leader is
is-singleton - Checks if the cluster is a singleton cluster (single
node cluster)
is-available - Checks if the member node is available
Where the <node-url> should be on the format of
'akka.<protocol>://<actor-system-name>@<hostname>:<port>'
Examples: ./akka-cluster localhost 9999 is-available
./akka-cluster localhost 9999 join akka.tcp://MySystem@darkstar:2552
./akka-cluster localhost 9999 cluster-status
```
## 配置
集群有几个配置属性。有关更多信息,请见「[参考配置](https://doc.akka.io/docs/akka/current/general/configuration.html#config-akka-cluster)」。
### Cluster Info Logging
你可以使用以下配置属性在`info`级别停止群集事件的日志记录:
```
akka.cluster.log-info = off
```
你可以在`info`级别启用群集事件的详细日志记录,例如用于临时故障排除,配置属性为:
```
akka.cluster.log-info-verbose = on
```
### Cluster Dispatcher
集群扩展是由 Actor 实现的,可能需要为这些 Actor 创建一个隔离墙,以避免来自其他 Actor 的干扰。尤其是那些用于故障检测的心跳 Actor,如果不给他们定期运行的机会,他们可能会产生误报。为此,你可以定义一个单独的调度程序(`dispatcher`),用于集群 Actor:
```java
akka.cluster.use-dispatcher = cluster-dispatcher
cluster-dispatcher {
type = "Dispatcher"
executor = "fork-join-executor"
fork-join-executor {
parallelism-min = 2
parallelism-max = 4
}
}
```
- **注释**:通常不需要为集群配置单独的调度程序。默认调度程序应该足以执行集群任务,即不应更改`akka.cluster.use-dispatcher `。如果在使用默认调度器时出现与集群相关的问题,这通常表示你正在默认调度器上运行阻塞或 CPU 密集型参与者/任务(`actors/tasks`)。为这些参与者/任务使用专用的调度器,而不是在默认调度器上运行它们,因为这样可能会使系统内部任务匮乏。相关配置属性:`akka.cluster.use-dispatcher = akka.cluster.cluster-dispatcher`。对应的默认值:`akka.cluster.use-dispatcher =`。
### 配置兼容性检查
创建集群是指部署两个或多个节点,然后使它们的行为像一个应用程序一样。因此,配置集群中所有节点的兼容设置非常重要。
配置兼容性检查(`Configuration Compatibility Check`)功能确保集群中的所有节点都具有兼容的配置。每当一个新节点加入一个现有的集群时,它的配置设置的一个子集(只有那些需要检查的)被发送到集群中的节点以进行验证。一旦在集群端检查了配置,集群就会发送回自己的一组必需的配置设置。然后,加入节点将验证它是否符合集群配置。只有在两侧的所有检查都通过时,新加入的节点才会继续。
通过扩展`akka.cluster.JoinConfigCompatChecker`并将其包含在配置中,可以添加新的自定义检查程序。每个检查器必须与唯一键关联:
```java
akka.cluster.configuration-compatibility-check.checkers {
my-custom-config = "com.company.MyCustomJoinConfigCompatChecker"
}
```
- **注释**:
- 配置兼容性检查默认启用,但可以通过设置`akka.cluster.configuration-compatibility-check.enforce-on-join = off`来禁用。这在执行滚动更新时特别有用。显然,只有当完全关闭集群不是一个选项时,才应该这样做。具有不同配置设置的节点的集群可能会导致数据丢失或数据损坏。
- 仅应在联接节点上禁用此设置。始终在两侧执行检查,并记录警告。在不兼容的情况下,连接节点负责决定是否中断进程。
- 如果使用 Akka 2.5.9 或更高版本对集群执行滚动更新(不支持此功能),则不会执行检查,因为正在运行的集群无法验证加入节点发送的配置,也无法发送回自己的配置。
----------
**英文原文链接**:[Cluster Usage](https://doc.akka.io/docs/akka/current/cluster-usage.html).
----------
———— ☆☆☆ —— [返回 -> Akka 中文指南 <- 目录](https://github.com/guobinhit/akka-guide/blob/master/README.md) —— ☆☆☆ ———— | {
"pile_set_name": "Github"
} |
/* Sticky footer */
/**
* Basic idea: https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/
* Details: https://github.com/philipwalton/solved-by-flexbox/blob/master/assets/css/components/site.css
*
* .Site -> body > .container
* .Site-content -> body > .container .row
* .footer -> footer
*
* Key idea seems to be to ensure that .container and __all its parents__
* have height set to 100%
*
*/
html, body {
height: 100%;
}
body > .container {
display: flex;
height: 100%;
flex-direction: column;
}
body > .container .row {
flex: 1 0 auto;
}
footer {
margin-top: 45px;
padding: 35px 0 36px;
border-top: 1px solid #e5e5e5;
color: #666;
display: flex;
flex-shrink: 0;
}
footer p {
margin-bottom: 0;
}
footer div {
flex: 1;
}
footer .pkgdown {
text-align: right;
}
footer p {
margin-bottom: 0;
}
img.icon {
float: right;
}
img {
max-width: 100%;
}
/* Fix bug in bootstrap (only seen in firefox) */
summary {
display: list-item;
}
/* Typographic tweaking ---------------------------------*/
.contents .page-header {
margin-top: calc(-60px + 1em);
}
/* Section anchors ---------------------------------*/
a.anchor {
margin-left: -30px;
display:inline-block;
width: 30px;
height: 30px;
visibility: hidden;
background-image: url(./link.svg);
background-repeat: no-repeat;
background-size: 20px 20px;
background-position: center center;
}
.hasAnchor:hover a.anchor {
visibility: visible;
}
@media (max-width: 767px) {
.hasAnchor:hover a.anchor {
visibility: hidden;
}
}
/* Fixes for fixed navbar --------------------------*/
.contents h1, .contents h2, .contents h3, .contents h4 {
padding-top: 60px;
margin-top: -40px;
}
/* Sidebar --------------------------*/
#sidebar {
margin-top: 30px;
position: -webkit-sticky;
position: sticky;
top: 70px;
}
#sidebar h2 {
font-size: 1.5em;
margin-top: 1em;
}
#sidebar h2:first-child {
margin-top: 0;
}
#sidebar .list-unstyled li {
margin-bottom: 0.5em;
}
.orcid {
height: 16px;
/* margins are required by official ORCID trademark and display guidelines */
margin-left:4px;
margin-right:4px;
vertical-align: middle;
}
/* Reference index & topics ----------------------------------------------- */
.ref-index th {font-weight: normal;}
.ref-index td {vertical-align: top;}
.ref-index .icon {width: 40px;}
.ref-index .alias {width: 40%;}
.ref-index-icons .alias {width: calc(40% - 40px);}
.ref-index .title {width: 60%;}
.ref-arguments th {text-align: right; padding-right: 10px;}
.ref-arguments th, .ref-arguments td {vertical-align: top;}
.ref-arguments .name {width: 20%;}
.ref-arguments .desc {width: 80%;}
/* Nice scrolling for wide elements --------------------------------------- */
table {
display: block;
overflow: auto;
}
/* Syntax highlighting ---------------------------------------------------- */
pre {
word-wrap: normal;
word-break: normal;
border: 1px solid #eee;
}
pre, code {
background-color: #f8f8f8;
color: #333;
}
pre code {
overflow: auto;
word-wrap: normal;
white-space: pre;
}
pre .img {
margin: 5px 0;
}
pre .img img {
background-color: #fff;
display: block;
height: auto;
}
code a, pre a {
color: #375f84;
}
a.sourceLine:hover {
text-decoration: none;
}
.fl {color: #1514b5;}
.fu {color: #000000;} /* function */
.ch,.st {color: #036a07;} /* string */
.kw {color: #264D66;} /* keyword */
.co {color: #888888;} /* comment */
.message { color: black; font-weight: bolder;}
.error { color: orange; font-weight: bolder;}
.warning { color: #6A0366; font-weight: bolder;}
/* Clipboard --------------------------*/
.hasCopyButton {
position: relative;
}
.btn-copy-ex {
position: absolute;
right: 0;
top: 0;
visibility: hidden;
}
.hasCopyButton:hover button.btn-copy-ex {
visibility: visible;
}
/* headroom.js ------------------------ */
.headroom {
will-change: transform;
transition: transform 200ms linear;
}
.headroom--pinned {
transform: translateY(0%);
}
.headroom--unpinned {
transform: translateY(-100%);
}
/* mark.js ----------------------------*/
mark {
background-color: rgba(255, 255, 51, 0.5);
border-bottom: 2px solid rgba(255, 153, 51, 0.3);
padding: 1px;
}
/* vertical spacing after htmlwidgets */
.html-widget {
margin-bottom: 10px;
}
/* fontawesome ------------------------ */
.fab {
font-family: "Font Awesome 5 Brands" !important;
}
/* don't display links in code chunks when printing */
/* source: https://stackoverflow.com/a/10781533 */
@media print {
code a:link:after, code a:visited:after {
content: "";
}
}
| {
"pile_set_name": "Github"
} |
#begin document (nw/wsj/02/wsj_0265); part 000
nw/wsj/02/wsj_0265 0 0 [WORD] NNP (TOP(S(NP* - - - - (ORG* * * * -
nw/wsj/02/wsj_0265 0 1 [WORD] NNP * - - - - * * * * -
nw/wsj/02/wsj_0265 0 2 [WORD] NNP *) - - - - *) * * * -
nw/wsj/02/wsj_0265 0 3 [WORD] VBD (VP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 4 [WORD] PRP (SBAR(S(NP*) - - - - * (ARG0*) * * -
nw/wsj/02/wsj_0265 0 5 [WORD] VBD (VP* reach 01 - - * (V*) * * -
nw/wsj/02/wsj_0265 0 6 [WORD] DT (NP(NP* - - - - * (ARG1* (ARG0* * -
nw/wsj/02/wsj_0265 0 7 [WORD] CD (NML* - - - - (DATE* * * * -
nw/wsj/02/wsj_0265 0 8 [WORD] HYPH * - - - - * * * * -
nw/wsj/02/wsj_0265 0 9 [WORD] NN *) - - - - *) * * * -
nw/wsj/02/wsj_0265 0 10 [WORD] NN * - - - - * * * * -
nw/wsj/02/wsj_0265 0 11 [WORD] NN *)) - - - - * *) *) * -
nw/wsj/02/wsj_0265 0 12 [WORD] IN (PP* - - - - * (ARGM-COM* (ARGM-PRD* * -
nw/wsj/02/wsj_0265 0 13 [WORD] PRP$ (NP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 14 [WORD] NNP * - - - - (ORG) * * * -
nw/wsj/02/wsj_0265 0 15 [WORD] NN *)) - - - - * *) *) * -
nw/wsj/02/wsj_0265 0 16 [WORD] VBG (VP* call 03 - - * (C-ARG1* (V*) * -
nw/wsj/02/wsj_0265 0 17 [WORD] IN (SBAR* - - - - * * (ARG1* * -
nw/wsj/02/wsj_0265 0 18 [WORD] NNP (S(NP*) - - - - (ORG) * * (ARG0*) -
nw/wsj/02/wsj_0265 0 19 [WORD] TO (VP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 20 [WORD] VB (VP(VP* pay 01 - - * * * (V*) -
nw/wsj/02/wsj_0265 0 21 [WORD] NNP (NP*) - - - - (ORG) * * (ARG2*) -
nw/wsj/02/wsj_0265 0 22 [WORD] $ (NP(QP* - - - - (MONEY* * * (ARG1* -
nw/wsj/02/wsj_0265 0 23 [WORD] CD * - - - - * * * * -
nw/wsj/02/wsj_0265 0 24 [WORD] CD *)) - - - - *) * * *) -
nw/wsj/02/wsj_0265 0 25 [WORD] RB (ADVP* - - - - * * * (ARGM-TMP* -
nw/wsj/02/wsj_0265 0 26 [WORD] RB *)) - - - - * * * *) -
nw/wsj/02/wsj_0265 0 27 [WORD] CC * - - - - * * * * -
nw/wsj/02/wsj_0265 0 28 [WORD] JJ (VP(NP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 29 [WORD] NNS *) - - - - * * * * -
nw/wsj/02/wsj_0265 0 30 [WORD] IN (PP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 31 [WORD] DT (NP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 32 [WORD] NN *)))))))))))) - - - - * *) *) * -
nw/wsj/02/wsj_0265 0 33 [WORD] . *)) - - - - * * * * -
nw/wsj/02/wsj_0265 0 0 [WORD] IN (TOP(S(PP* - - - - * (ARGM-LOC* * * * -
nw/wsj/02/wsj_0265 0 1 [WORD] DT (NP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 2 [WORD] NN *)) - - - - * *) * * * -
nw/wsj/02/wsj_0265 0 3 [WORD] , * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 4 [WORD] NNP (NP(NP*) - - - - (ORG) (ARG0* * * * -
nw/wsj/02/wsj_0265 0 5 [WORD] , * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 6 [WORD] DT (NP(NP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 7 [WORD] NN *) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 8 [WORD] IN (PP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 9 [WORD] NN (NP(NML* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 10 [WORD] HYPH * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 11 [WORD] NN *) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 12 [WORD] NNS *))) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 13 [WORD] , *) - - - - * *) * * * -
nw/wsj/02/wsj_0265 0 14 [WORD] VBD (VP* say 01 - - * (V*) * * * -
nw/wsj/02/wsj_0265 0 15 [WORD] PRP (SBAR(S(NP*) - - - - * (ARG1* (ARG0*) (ARG0*) * -
nw/wsj/02/wsj_0265 0 16 [WORD] MD (VP* - - - - * * (ARGM-MOD*) (ARGM-MOD*) * -
nw/wsj/02/wsj_0265 0 17 [WORD] VB (VP(VP* pay 01 - - * * (V*) * * -
nw/wsj/02/wsj_0265 0 18 [WORD] NNP (NP*) - - - - (ORG) * (ARG2*) * * -
nw/wsj/02/wsj_0265 0 19 [WORD] $ (NP(NP(QP* - - - - (MONEY* * (ARG1* * * -
nw/wsj/02/wsj_0265 0 20 [WORD] CD * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 21 [WORD] CD *)) - - - - *) * * * * -
nw/wsj/02/wsj_0265 0 22 [WORD] IN (PP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 23 [WORD] JJ (NP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 24 [WORD] NN (NML* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 25 [WORD] CC * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 26 [WORD] NN *) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 27 [WORD] NNS *)))) - - - - * * *) * * -
nw/wsj/02/wsj_0265 0 28 [WORD] CC * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 29 [WORD] VB (VP* repay 01 1 - * * * (V*) * -
nw/wsj/02/wsj_0265 0 30 [WORD] $ (NP(NP(QP* - - - - (MONEY* * * (ARG3* * -
nw/wsj/02/wsj_0265 0 31 [WORD] CD * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 32 [WORD] CD *)) - - - - *) * * * * -
nw/wsj/02/wsj_0265 0 33 [WORD] IN (PP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 34 [WORD] NNS (NP(NP*) - - - - * * * * (ARG1*) -
nw/wsj/02/wsj_0265 0 35 [WORD] WDT (SBAR(WHNP*) - - - - * * * * (R-ARG1*) -
nw/wsj/02/wsj_0265 0 36 [WORD] NNP (S(NP*) - - - - (ORG) * * * (ARG0*) -
nw/wsj/02/wsj_0265 0 37 [WORD] VBD (VP* advance 01 5 - * * * * (V*) -
nw/wsj/02/wsj_0265 0 38 [WORD] IN (PP* - - - - * * * * (ARGM-PRP* -
nw/wsj/02/wsj_0265 0 39 [WORD] NN (NP(NP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 40 [WORD] NN *) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 41 [WORD] IN (PP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 42 [WORD] NNS (NP*)))))))))))))))) - - - - * *) * *) *) -
nw/wsj/02/wsj_0265 0 43 [WORD] . *)) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 0 [WORD] IN (TOP(S(PP* - - - - * (ARGM-DIR* * -
nw/wsj/02/wsj_0265 0 1 [WORD] NN (NP*)) - - - - * *) * -
nw/wsj/02/wsj_0265 0 2 [WORD] , * - - - - * * * -
nw/wsj/02/wsj_0265 0 3 [WORD] NNP (NP*) - - - - (ORG) (ARG0*) * -
nw/wsj/02/wsj_0265 0 4 [WORD] VBD (VP* agree 01 - - * (V*) * -
nw/wsj/02/wsj_0265 0 5 [WORD] IN (SBAR* - - - - * (ARG1* * -
nw/wsj/02/wsj_0265 0 6 [WORD] PRP (S(NP*) - - - - * * (ARG0*) -
nw/wsj/02/wsj_0265 0 7 [WORD] MD (VP* - - - - * * (ARGM-MOD*) -
nw/wsj/02/wsj_0265 0 8 [WORD] RB * - - - - * * (ARGM-NEG*) -
nw/wsj/02/wsj_0265 0 9 [WORD] VB (VP* exercise 01 1 - * * (V*) -
nw/wsj/02/wsj_0265 0 10 [WORD] PRP$ (NP* - - - - * * (ARG1* -
nw/wsj/02/wsj_0265 0 11 [WORD] NNS * - - - - * * * -
nw/wsj/02/wsj_0265 0 12 [WORD] CC * - - - - * * * -
nw/wsj/02/wsj_0265 0 13 [WORD] NNS *) - - - - * * *) -
nw/wsj/02/wsj_0265 0 14 [WORD] IN (PP* - - - - * * (ARGM-GOL* -
nw/wsj/02/wsj_0265 0 15 [WORD] NNP (NP*)) - - - - (ORG) * *) -
nw/wsj/02/wsj_0265 0 16 [WORD] IN (PP* - - - - * * (ARGM-TMP* -
nw/wsj/02/wsj_0265 0 17 [WORD] DT (NP* - - - - * * * -
nw/wsj/02/wsj_0265 0 18 [WORD] CD (NML* - - - - (DATE* * * -
nw/wsj/02/wsj_0265 0 19 [WORD] HYPH * - - - - * * * -
nw/wsj/02/wsj_0265 0 20 [WORD] NN *) - - - - *) * * -
nw/wsj/02/wsj_0265 0 21 [WORD] NN *))))))) - - - - * *) *) -
nw/wsj/02/wsj_0265 0 22 [WORD] . *)) - - - - * * * -
nw/wsj/02/wsj_0265 0 0 [WORD] IN (TOP(S(PP* - - - - * (ARGM-TMP* * * -
nw/wsj/02/wsj_0265 0 1 [WORD] DT (NP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 2 [WORD] NN *)) - - - - * *) * * -
nw/wsj/02/wsj_0265 0 3 [WORD] , * - - - - * * * * -
nw/wsj/02/wsj_0265 0 4 [WORD] NNP (NP*) - - - - (ORG) (ARG1*) * * -
nw/wsj/02/wsj_0265 0 5 [WORD] RB (ADVP*) - - - - * (ARGM-TMP*) * * -
nw/wsj/02/wsj_0265 0 6 [WORD] MD (VP* - - - - * (ARGM-MOD*) * * -
nw/wsj/02/wsj_0265 0 7 [WORD] VB (VP* be 01 - - * (V*) * * -
nw/wsj/02/wsj_0265 0 8 [WORD] $ (PP(NP(QP* - - - - (MONEY* (ARG2* * * -
nw/wsj/02/wsj_0265 0 9 [WORD] CD * - - - - * * * * -
nw/wsj/02/wsj_0265 0 10 [WORD] CD *)) - - - - *) * * * -
nw/wsj/02/wsj_0265 0 11 [WORD] IN * - - - - * * * * -
nw/wsj/02/wsj_0265 0 12 [WORD] NNS (NP(NP*) - - - - * * * * -
nw/wsj/02/wsj_0265 0 13 [WORD] IN (PP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 14 [WORD] NN (NP(NP(NML* - - - - * * * * -
nw/wsj/02/wsj_0265 0 15 [WORD] CC * - - - - * * * * -
nw/wsj/02/wsj_0265 0 16 [WORD] NN *) - - - - * * * * -
nw/wsj/02/wsj_0265 0 17 [WORD] NNS *) - - - - * * * * -
nw/wsj/02/wsj_0265 0 18 [WORD] IN (PP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 19 [WORD] NNP (NP(NP*) - - - - (ORG) * * * -
nw/wsj/02/wsj_0265 0 20 [WORD] , * - - - - * * * * -
nw/wsj/02/wsj_0265 0 21 [WORD] DT (NP(NP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 22 [WORD] JJ (NML(NML* - - - - * * * * -
nw/wsj/02/wsj_0265 0 23 [WORD] NN *) - - - - * * * * -
nw/wsj/02/wsj_0265 0 24 [WORD] NN *) - - - - * * * * -
nw/wsj/02/wsj_0265 0 25 [WORD] NN *) - - - - * * * * -
nw/wsj/02/wsj_0265 0 26 [WORD] WP$ (SBAR(WHNP* - - - - * * (ARG1* * -
nw/wsj/02/wsj_0265 0 27 [WORD] NN *) - - - - * * *) * -
nw/wsj/02/wsj_0265 0 28 [WORD] VBZ (S(VP* consist 01 2 - * * (V*) * -
nw/wsj/02/wsj_0265 0 29 [WORD] RB (ADVP*) - - - - * * (ARGM-ADV*) * -
nw/wsj/02/wsj_0265 0 30 [WORD] IN (PP* - - - - * * (ARG2* * -
nw/wsj/02/wsj_0265 0 31 [WORD] NNS (NP(NP*) - - - - * * * (ARG1*) -
nw/wsj/02/wsj_0265 0 32 [WORD] VBN (VP* operate 01 - - * * * (V*) -
nw/wsj/02/wsj_0265 0 33 [WORD] IN (PP* - - - - * * * (ARG0* -
nw/wsj/02/wsj_0265 0 34 [WORD] NNP (NP*))))))))))))))))) - - - - (ORG) *) *) *) -
nw/wsj/02/wsj_0265 0 35 [WORD] . *)) - - - - * * * * -
nw/wsj/02/wsj_0265 0 0 [WORD] NNP (TOP(S(NP*) - - - - (ORG) (ARG0*) * -
nw/wsj/02/wsj_0265 0 1 [WORD] VBZ (VP* - - - - * * * -
nw/wsj/02/wsj_0265 0 2 [WORD] VBN (VP* give 01 - - * (V*) * -
nw/wsj/02/wsj_0265 0 3 [WORD] NNP (NP*) - - - - (ORG) (ARG2*) * -
nw/wsj/02/wsj_0265 0 4 [WORD] DT (NP(NP(NP* - - - - * (ARG1* (ARG1* -
nw/wsj/02/wsj_0265 0 5 [WORD] CD (NML* - - - - (PERCENT* * * -
nw/wsj/02/wsj_0265 0 6 [WORD] NN *) - - - - *) * * -
nw/wsj/02/wsj_0265 0 7 [WORD] NN *) - - - - * * * -
nw/wsj/02/wsj_0265 0 8 [WORD] IN (PP* - - - - * * * -
nw/wsj/02/wsj_0265 0 9 [WORD] DT (NP* - - - - * * * -
nw/wsj/02/wsj_0265 0 10 [WORD] JJ * - - - - * * * -
nw/wsj/02/wsj_0265 0 11 [WORD] NN *))) - - - - * * *) -
nw/wsj/02/wsj_0265 0 12 [WORD] , * - - - - * * * -
nw/wsj/02/wsj_0265 0 13 [WORD] TO (SBAR(S(VP* - - - - * * * -
nw/wsj/02/wsj_0265 0 14 [WORD] VB (VP* - - - - * * * -
nw/wsj/02/wsj_0265 0 15 [WORD] VBN (VP* repay 01 - - * * (V*) -
nw/wsj/02/wsj_0265 0 16 [WORD] IN (PP* - - - - * * (ARGM-TMP* -
nw/wsj/02/wsj_0265 0 17 [WORD] CD (NP* - - - - (DATE* * * -
nw/wsj/02/wsj_0265 0 18 [WORD] NNS *)))))))))) - - - - *) *) *) -
nw/wsj/02/wsj_0265 0 19 [WORD] . *)) - - - - * * * -
nw/wsj/02/wsj_0265 0 0 [WORD] IN (TOP(S(PP* - - - - * * -
nw/wsj/02/wsj_0265 0 1 [WORD] NN (NP*)) - - - - * * -
nw/wsj/02/wsj_0265 0 2 [WORD] , * - - - - * * -
nw/wsj/02/wsj_0265 0 3 [WORD] NNP (NP*) - - - - (ORG) * -
nw/wsj/02/wsj_0265 0 4 [WORD] VBD (VP* - - - - * * -
nw/wsj/02/wsj_0265 0 5 [WORD] TO (S(VP* - - - - * * -
nw/wsj/02/wsj_0265 0 6 [WORD] VB (VP* - - - - * * -
nw/wsj/02/wsj_0265 0 7 [WORD] JJ (NP(NP(NP* - - - - (DATE) * -
nw/wsj/02/wsj_0265 0 8 [WORD] NN (NML* - - - - * * -
nw/wsj/02/wsj_0265 0 9 [WORD] CC * - - - - * * -
nw/wsj/02/wsj_0265 0 10 [WORD] NN *) - - - - * * -
nw/wsj/02/wsj_0265 0 11 [WORD] NNS *) - - - - * * -
nw/wsj/02/wsj_0265 0 12 [WORD] IN (PP* - - - - * * -
nw/wsj/02/wsj_0265 0 13 [WORD] $ (NP(QP* - - - - (MONEY* * -
nw/wsj/02/wsj_0265 0 14 [WORD] CD * - - - - * * -
nw/wsj/02/wsj_0265 0 15 [WORD] CD * - - - - * * -
nw/wsj/02/wsj_0265 0 16 [WORD] TO * - - - - * * -
nw/wsj/02/wsj_0265 0 17 [WORD] $ * - - - - * * -
nw/wsj/02/wsj_0265 0 18 [WORD] CD * - - - - * * -
nw/wsj/02/wsj_0265 0 19 [WORD] CD *))) - - - - *) * -
nw/wsj/02/wsj_0265 0 20 [WORD] IN (PP* - - - - * * -
nw/wsj/02/wsj_0265 0 21 [WORD] NNP (NP*)))) - - - - (ORG) * -
nw/wsj/02/wsj_0265 0 22 [WORD] IN (PP* - - - - * * -
nw/wsj/02/wsj_0265 0 23 [WORD] DT (NP* - - - - * * -
nw/wsj/02/wsj_0265 0 24 [WORD] JJ * - - - - * * -
nw/wsj/02/wsj_0265 0 25 [WORD] NN *)) - - - - (DATE) * -
nw/wsj/02/wsj_0265 0 26 [WORD] , * - - - - * * -
nw/wsj/02/wsj_0265 0 27 [WORD] TO (SBAR(S(VP* - - - - * * -
nw/wsj/02/wsj_0265 0 28 [WORD] VB (VP* - - - - * * -
nw/wsj/02/wsj_0265 0 29 [WORD] VBN (VP* - - - - * * -
nw/wsj/02/wsj_0265 0 30 [WORD] WRB (SBAR(WHADVP*) - - - - * (ARGM-TMP*) -
nw/wsj/02/wsj_0265 0 31 [WORD] NNP (S(NP*) - - - - (ORG) (ARG0*) -
nw/wsj/02/wsj_0265 0 32 [WORD] RB (ADVP*) - - - - * (ARGM-MNR*) -
nw/wsj/02/wsj_0265 0 33 [WORD] VBZ (VP* complete 01 - - * (V*) -
nw/wsj/02/wsj_0265 0 34 [WORD] NN (NP* - - - - * (ARG1* -
nw/wsj/02/wsj_0265 0 35 [WORD] NNS *))))))))))))) - - - - * *) -
nw/wsj/02/wsj_0265 0 36 [WORD] . *)) - - - - * * -
nw/wsj/02/wsj_0265 0 0 [WORD] IN (TOP(S(SBAR* - - - - * * * (ARGM-CAU* -
nw/wsj/02/wsj_0265 0 1 [WORD] NNP (S(NP*) - - - - (ORG) (ARG0*) * * -
nw/wsj/02/wsj_0265 0 2 [WORD] RB (ADVP*) - - - - * (ARGM-ADV*) * * -
nw/wsj/02/wsj_0265 0 3 [WORD] VBZ (VP* owe 01 1 - * (V*) * * -
nw/wsj/02/wsj_0265 0 4 [WORD] NNP (NP*) - - - - (ORG) (ARG2*) * * -
nw/wsj/02/wsj_0265 0 5 [WORD] $ (NP(NP(QP* - - - - (MONEY* (ARG1* * * -
nw/wsj/02/wsj_0265 0 6 [WORD] CD * - - - - * * * * -
nw/wsj/02/wsj_0265 0 7 [WORD] CD *)) - - - - *) * * * -
nw/wsj/02/wsj_0265 0 8 [WORD] IN (PP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 9 [WORD] NN (NP(NML* - - - - * * * * -
nw/wsj/02/wsj_0265 0 10 [WORD] CC * - - - - * * * * -
nw/wsj/02/wsj_0265 0 11 [WORD] NN *) - - - - * * * * -
nw/wsj/02/wsj_0265 0 12 [WORD] NNS *))) - - - - * *) * * -
nw/wsj/02/wsj_0265 0 13 [WORD] DT (NP* - - - - * (ARGM-TMP* * * -
nw/wsj/02/wsj_0265 0 14 [WORD] NN *)))) - - - - (DATE) *) * *) -
nw/wsj/02/wsj_0265 0 15 [WORD] , * - - - - * * * * -
nw/wsj/02/wsj_0265 0 16 [WORD] DT (NP(NP(NP* - - - - * * * (ARG1* -
nw/wsj/02/wsj_0265 0 17 [WORD] NN *) - - - - * * * * -
nw/wsj/02/wsj_0265 0 18 [WORD] JJ (ADJP*)) - - - - * * * * -
nw/wsj/02/wsj_0265 0 19 [WORD] IN (PP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 20 [WORD] DT (NP(NP* - - - - * * (ARG1* * -
nw/wsj/02/wsj_0265 0 21 [WORD] NN *) - - - - * * *) * -
nw/wsj/02/wsj_0265 0 22 [WORD] VBN (VP*)))) pay 01 - - * * (V*) *) -
nw/wsj/02/wsj_0265 0 23 [WORD] MD (VP* - - - - * * * (ARGM-MOD*) -
nw/wsj/02/wsj_0265 0 24 [WORD] VB (VP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 25 [WORD] VBN (VP* add 02 - - * * * (V*) -
nw/wsj/02/wsj_0265 0 26 [WORD] IN (PP* - - - - * * * (ARG2* -
nw/wsj/02/wsj_0265 0 27 [WORD] DT (NP* - - - - * * * * -
nw/wsj/02/wsj_0265 0 28 [WORD] CD (NML* - - - - (DATE* * * * -
nw/wsj/02/wsj_0265 0 29 [WORD] HYPH * - - - - * * * * -
nw/wsj/02/wsj_0265 0 30 [WORD] NN *) - - - - *) * * * -
nw/wsj/02/wsj_0265 0 31 [WORD] NN *))))) - - - - * * * *) -
nw/wsj/02/wsj_0265 0 32 [WORD] . *)) - - - - * * * * -
nw/wsj/02/wsj_0265 0 0 [WORD] DT (TOP(S(NP* - - - - * (ARG0* (ARG0* * * -
nw/wsj/02/wsj_0265 0 1 [WORD] NNS *) - - - - * *) *) * * -
nw/wsj/02/wsj_0265 0 2 [WORD] MD (VP* - - - - * (ARGM-MOD*) * * * -
nw/wsj/02/wsj_0265 0 3 [WORD] VB (VP* help 01 - - * (V*) * * * -
nw/wsj/02/wsj_0265 0 4 [WORD] VB (S(VP* ease 02 - - * (ARG1* (V*) * * -
nw/wsj/02/wsj_0265 0 5 [WORD] DT (NP(NP* - - - - * * (ARG1* * * -
nw/wsj/02/wsj_0265 0 6 [WORD] NN * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 7 [WORD] NN *) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 8 [WORD] IN (PP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 9 [WORD] NNP (NP(NP*) - - - - (ORG) * * (ARG1*) * -
nw/wsj/02/wsj_0265 0 10 [WORD] , * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 11 [WORD] WDT (SBAR(WHNP*) - - - - * * * (R-ARG1*) (ARG0*) -
nw/wsj/02/wsj_0265 0 12 [WORD] VBZ (S(VP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 13 [WORD] VBN (VP* be 01 - - * * * (V*) * -
nw/wsj/02/wsj_0265 0 14 [WORD] JJ (ADJP* - - - - * * * (ARG2* * -
nw/wsj/02/wsj_0265 0 15 [WORD] TO (S(VP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 16 [WORD] VB (VP* pay 01 - - * * * * (V*) -
nw/wsj/02/wsj_0265 0 17 [WORD] PRP$ (NP* - - - - * * * * (ARG3* -
nw/wsj/02/wsj_0265 0 18 [WORD] NNS *))))) - - - - * * * *) *) -
nw/wsj/02/wsj_0265 0 19 [WORD] IN (SBAR* - - - - * * * (ARGM-CAU* * -
nw/wsj/02/wsj_0265 0 20 [WORD] NNP (S(NP*) - - - - (ORG) * * * * -
nw/wsj/02/wsj_0265 0 21 [WORD] VBZ (VP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 22 [WORD] RB * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 23 [WORD] VBD (VP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 24 [WORD] JJ (NP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 25 [WORD] NN (NML* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 26 [WORD] CC * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 27 [WORD] NN *) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 28 [WORD] NNS *) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 29 [WORD] IN (PP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 30 [WORD] NNP (NP*))))))))))))))))) - - - - (DATE) *) *) *) * -
nw/wsj/02/wsj_0265 0 31 [WORD] . *)) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 0 [WORD] DT (TOP(S(NP* - - - - * (ARG0* * * * -
nw/wsj/02/wsj_0265 0 1 [WORD] NN *) - - - - * *) * * * -
nw/wsj/02/wsj_0265 0 2 [WORD] VBD (VP* say 01 - - * (V*) * * * -
nw/wsj/02/wsj_0265 0 3 [WORD] NNP (SBAR(S(NP*) - - - - (ORG) (ARG1* (ARG0*) * (ARG1*) -
nw/wsj/02/wsj_0265 0 4 [WORD] VBZ (VP(VP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 5 [WORD] VBN (VP* pay 01 - - * * (V*) * * -
nw/wsj/02/wsj_0265 0 6 [WORD] CD (NP(NP*) - - - - (CARDINAL) * (ARG2* * * -
nw/wsj/02/wsj_0265 0 7 [WORD] IN (PP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 8 [WORD] DT (NP(NP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 9 [WORD] CD * - - - - (CARDINAL) * * * * -
nw/wsj/02/wsj_0265 0 10 [WORD] NNS *) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 11 [WORD] PRP (SBAR(S(NP*) - - - - * * * (ARG0*) * -
nw/wsj/02/wsj_0265 0 12 [WORD] VBD (VP* owe 01 1 - * * * (V*) * -
nw/wsj/02/wsj_0265 0 13 [WORD] NN (NP*) - - - - * * * (ARG1*) * -
nw/wsj/02/wsj_0265 0 14 [WORD] IN (PP*) - - - - * * * (ARG2*) * -
nw/wsj/02/wsj_0265 0 15 [WORD] IN (PP* - - - - * * * (ARGM-TMP* * -
nw/wsj/02/wsj_0265 0 16 [WORD] NNP (NP*)))))))))) - - - - (DATE) * *) *) * -
nw/wsj/02/wsj_0265 0 17 [WORD] CC * - - - - * * * * * -
nw/wsj/02/wsj_0265 0 18 [WORD] VBZ (VP* be 01 - - * * * * (V*) -
nw/wsj/02/wsj_0265 0 19 [WORD] IN (PP* - - - - * * * * (ARG2* -
nw/wsj/02/wsj_0265 0 20 [WORD] NNS (NP(NP*) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 21 [WORD] IN (PP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 22 [WORD] DT (NP* - - - - * * * * * -
nw/wsj/02/wsj_0265 0 23 [WORD] JJ * - - - - (ORDINAL) * * * * -
nw/wsj/02/wsj_0265 0 24 [WORD] NN *))))))))) - - - - * *) * * *) -
nw/wsj/02/wsj_0265 0 25 [WORD] . *)) - - - - * * * * * -
nw/wsj/02/wsj_0265 0 0 [WORD] NNP (TOP(S(NP(NP*) - - - - (ORG) (ARG1*) (ARG0* * * * * -
nw/wsj/02/wsj_0265 0 1 [WORD] , * - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 2 [WORD] WDT (SBAR(WHNP*) - - - - * (R-ARG1*) * * * * * -
nw/wsj/02/wsj_0265 0 3 [WORD] VBZ (S(VP* - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 4 [WORD] VBN (VP* be 01 - - * (V*) * * * * * -
nw/wsj/02/wsj_0265 0 5 [WORD] IN (PP* - - - - * (ARG2* * * * * * -
nw/wsj/02/wsj_0265 0 6 [WORD] DT (NP* - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 7 [WORD] JJ * - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 8 [WORD] NN * - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 9 [WORD] NN *)))))) - - - - * *) * * * * * -
nw/wsj/02/wsj_0265 0 10 [WORD] , *) - - - - * * *) * * * * -
nw/wsj/02/wsj_0265 0 11 [WORD] VBD (VP* say 01 - - * * (V*) * * * * -
nw/wsj/02/wsj_0265 0 12 [WORD] PRP (SBAR(S(NP*) - - - - * * (ARG1* (ARG1*) * * * -
nw/wsj/02/wsj_0265 0 13 [WORD] VBZ (VP* be 01 - - * * * (V*) * * * -
nw/wsj/02/wsj_0265 0 14 [WORD] JJ (ADJP* - - - - * * * (ARG2* * * * -
nw/wsj/02/wsj_0265 0 15 [WORD] TO (S(VP* - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 16 [WORD] VB (VP* - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 17 [WORD] DT (NP* - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 18 [WORD] NNS *))))) - - - - * * * *) * * * -
nw/wsj/02/wsj_0265 0 19 [WORD] IN (SBAR* - - - - * * * (ARGM-CAU* * * * -
nw/wsj/02/wsj_0265 0 20 [WORD] PRP (S(NP*) - - - - * * * * (ARG0*) * * -
nw/wsj/02/wsj_0265 0 21 [WORD] VBD (VP* complete 01 - - * * * * (V*) * * -
nw/wsj/02/wsj_0265 0 22 [WORD] DT (NP(NP(NP* - - - - * * * * (ARG1* (ARGM-LOC* (ARGM-LOC* -
nw/wsj/02/wsj_0265 0 23 [WORD] NN *) - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 24 [WORD] IN (PP* - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 25 [WORD] NNP (NP* - - - - (ORG* * * * * * * -
nw/wsj/02/wsj_0265 0 26 [WORD] NNP * - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 27 [WORD] NNP * - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 28 [WORD] NNP *))) - - - - *) * * * * *) *) -
nw/wsj/02/wsj_0265 0 29 [WORD] IN (SBAR(WHPP* - - - - * * * * * (R-ARGM-LOC* (R-ARGM-LOC* -
nw/wsj/02/wsj_0265 0 30 [WORD] WDT (WHNP*)) - - - - * * * * * *) *) -
nw/wsj/02/wsj_0265 0 31 [WORD] NNP (S(NP*) - - - - (ORG) * * * * (ARG0*) (ARG0*) -
nw/wsj/02/wsj_0265 0 32 [WORD] VBD (VP(VP* purchase 01 1 - * * * * * (V*) * -
nw/wsj/02/wsj_0265 0 33 [WORD] NN (NP* - - - - * * * * * (ARG1* * -
nw/wsj/02/wsj_0265 0 34 [WORD] CC * - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 35 [WORD] NNS *) - - - - * * * * * *) * -
nw/wsj/02/wsj_0265 0 36 [WORD] IN (PP* - - - - * * * * * (ARG3* * -
nw/wsj/02/wsj_0265 0 37 [WORD] $ (NP(QP* - - - - (MONEY* * * * * * * -
nw/wsj/02/wsj_0265 0 38 [WORD] CD *)))) - - - - *) * * * * *) * -
nw/wsj/02/wsj_0265 0 39 [WORD] CC * - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 40 [WORD] VBD (VP* loan 01 - - * * * * * * (V*) -
nw/wsj/02/wsj_0265 0 41 [WORD] NNP (NP*) - - - - (ORG) * * * * * (ARG2*) -
nw/wsj/02/wsj_0265 0 42 [WORD] $ (NP(QP* - - - - (MONEY* * * * * * (ARG1* -
nw/wsj/02/wsj_0265 0 43 [WORD] CD * - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 44 [WORD] CD *)))))))))))))) - - - - *) * *) *) *) * *) -
nw/wsj/02/wsj_0265 0 45 [WORD] . *)) - - - - * * * * * * * -
nw/wsj/02/wsj_0265 0 0 [WORD] DT (TOP(S(NP* - - - - * (ARG1* -
nw/wsj/02/wsj_0265 0 1 [WORD] NN *) - - - - * *) -
nw/wsj/02/wsj_0265 0 2 [WORD] VBZ (VP* - - - - * * -
nw/wsj/02/wsj_0265 0 3 [WORD] VBN (VP* back 01 - - * (V*) -
nw/wsj/02/wsj_0265 0 4 [WORD] IN (PP* - - - - * (ARG0* -
nw/wsj/02/wsj_0265 0 5 [WORD] NNP (NP(NP(NP(NP* - - - - (ORG) * -
nw/wsj/02/wsj_0265 0 6 [WORD] POS *) - - - - * * -
nw/wsj/02/wsj_0265 0 7 [WORD] CD (NML* - - - - (PERCENT* * -
nw/wsj/02/wsj_0265 0 8 [WORD] NN *) - - - - *) * -
nw/wsj/02/wsj_0265 0 9 [WORD] NN *) - - - - * * -
nw/wsj/02/wsj_0265 0 10 [WORD] IN (PP* - - - - * * -
nw/wsj/02/wsj_0265 0 11 [WORD] NNP (NP*))) - - - - (ORG) * -
nw/wsj/02/wsj_0265 0 12 [WORD] CC * - - - - * * -
nw/wsj/02/wsj_0265 0 13 [WORD] NN (NP(NP*) - - - - * * -
nw/wsj/02/wsj_0265 0 14 [WORD] IN (PP* - - - - * * -
nw/wsj/02/wsj_0265 0 15 [WORD] JJ (NP* - - - - * * -
nw/wsj/02/wsj_0265 0 16 [WORD] NNS *))))))) - - - - * *) -
nw/wsj/02/wsj_0265 0 17 [WORD] . *)) - - - - * * -
#end document
| {
"pile_set_name": "Github"
} |
`dexp` command
==============
SJK's dump format may include arbutrary data records besides thread sampling information.
This ablity could be exposed via API.
`dexp` command can be used to export arbitrary data from binary dump format into text or csv format.
Usage
-----
> java -jar sjk.jar --help dexp
[Dump Export] Extract metrics from compressed dump into tabular format
Usage: dexp [options]
Options:
-cl, --columns
List of columns (tags) to be exported
Default: []
--commands
Default: false
--explain
Include additional information into std out
Default: false
--export-all
Export all columns
Default: false
* -f, --file
Input files
Default: []
--help
Default: false
-o, --outfile
Out data into a file instead of std out
--parsers-info
Print parsers available in classpath
Default: false
--tags
Output statistics for tags
Default: false
-tr, --time-range
Time range filter
-tz, --timezone
Set time zone to be used for date formating
-X, --verbose
Enable detailed diagnostics
Default: false
-csv
Format output as CSV
Default: false
| {
"pile_set_name": "Github"
} |
package com.baiyi.opscloud.service.cloud;
import com.baiyi.opscloud.domain.generator.opscloud.OcCloudDbAccount;
import java.util.List;
/**
* @Author baiyi
* @Date 2020/3/3 10:15 上午
* @Version 1.0
*/
public interface OcCloudDBAccountService {
List<OcCloudDbAccount> queryOcCloudDbAccountByCloudDbId(int cloudDbId);
OcCloudDbAccount queryOcCloudDbAccountByUniqueKey(OcCloudDbAccount ocCloudDbAccount);
void addOcCloudDbAccount(OcCloudDbAccount ocCloudDbAccount);
void delOcCloudDbAccountById(int id);
}
| {
"pile_set_name": "Github"
} |
/*-
* This file is in the public domain.
*/
/* $FreeBSD: release/9.1.0/sys/i386/include/bus.h 216592 2010-12-20 16:39:43Z tijl $ */
#include <x86/bus.h>
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* 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 com.android.example.simpletransition;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import androidx.appcompat.app.AppCompatActivity;
import androidx.transition.ChangeBounds;
import androidx.transition.Transition;
import androidx.transition.TransitionManager;
import androidx.transition.TransitionSet;
import static android.widget.RelativeLayout.ABOVE;
import static android.widget.RelativeLayout.ALIGN_PARENT_BOTTOM;
import static android.widget.RelativeLayout.ALIGN_PARENT_LEFT;
import static android.widget.RelativeLayout.ALIGN_PARENT_RIGHT;
import static android.widget.RelativeLayout.BELOW;
import static android.widget.RelativeLayout.LayoutParams;
public class MainActivity extends AppCompatActivity {
CheckBox mStaggerCB;
Button mFirstButton, mSecondButton, mThirdButton, mFourthButton;
ViewGroup mSceneRoot;
TransitionSet mStaggeredTransition;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStaggerCB = (CheckBox) findViewById(R.id.staggerCB);
mFirstButton = (Button) findViewById(R.id.firstButton);
mSecondButton = (Button) findViewById(R.id.secondButton);
mThirdButton = (Button) findViewById(R.id.thirdButton);
mFourthButton = (Button) findViewById(R.id.fourthButton);
mSceneRoot = (ViewGroup) findViewById(R.id.activity_main);
// Create custom transition that 'staggers' the animations by offsetting
// the individual start times
mStaggeredTransition = new TransitionSet();
Transition first = new ChangeBounds();
Transition second = new ChangeBounds();
Transition third = new ChangeBounds();
Transition fourth = new ChangeBounds();
first.addTarget(mFirstButton);
second.setStartDelay(50).addTarget(mSecondButton);
third.setStartDelay(100).addTarget(mThirdButton);
fourth.setStartDelay(150).addTarget(mFourthButton);
mStaggeredTransition.addTransition(first).addTransition(second).addTransition(third).
addTransition(fourth);
}
private void alignButtons(boolean left, boolean top) {
LayoutParams params;
// Trigger a transition to run after the next layout pass
if (mStaggerCB.isChecked()) {
TransitionManager.beginDelayedTransition(mSceneRoot, mStaggeredTransition);
} else {
TransitionManager.beginDelayedTransition(mSceneRoot);
}
// Change layout parameters of the button stack
int oldAlignmentLR = left ? ALIGN_PARENT_RIGHT : ALIGN_PARENT_LEFT;
int newAlignmentLR = left ? ALIGN_PARENT_LEFT : ALIGN_PARENT_RIGHT;
int oldAlignmentTB = top ? ABOVE : BELOW;
int newAlignmentTB = top ? BELOW : ABOVE;
params = (LayoutParams) mFirstButton.getLayoutParams();
params.addRule(top ? ALIGN_PARENT_BOTTOM : BELOW, 0);
params.addRule(oldAlignmentLR, 0);
params.addRule(top ? BELOW : ALIGN_PARENT_BOTTOM, top ? R.id.staggerCB : 1);
params.addRule(newAlignmentLR);
mFirstButton.setLayoutParams(params);
params = (LayoutParams) mSecondButton.getLayoutParams();
params.addRule(oldAlignmentLR, 0);
params.addRule(oldAlignmentTB, 0);
params.addRule(newAlignmentLR);
params.addRule(newAlignmentTB, R.id.firstButton);
mSecondButton.setLayoutParams(params);
params = (LayoutParams) mThirdButton.getLayoutParams();
params.addRule(oldAlignmentLR, 0);
params.addRule(oldAlignmentTB, 0);
params.addRule(newAlignmentLR);
params.addRule(newAlignmentTB, R.id.secondButton);
mThirdButton.setLayoutParams(params);
params = (LayoutParams) mFourthButton.getLayoutParams();
params.addRule(oldAlignmentLR, 0);
params.addRule(oldAlignmentTB, 0);
params.addRule(newAlignmentLR);
params.addRule(newAlignmentTB, R.id.thirdButton);
mFourthButton.setLayoutParams(params);
}
public void onClick(View view) {
switch (((Button) view).getText().toString()) {
case "Top Left":
alignButtons(true, true);
break;
case "Top Right":
alignButtons(false, true);
break;
case "Bottom Left":
alignButtons(true, false);
break;
case "Bottom Right":
alignButtons(false, false);
break;
}
}
}
| {
"pile_set_name": "Github"
} |
/**
* This file is part of Graylog.
*
* Graylog 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.
*
* Graylog 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 Graylog. If not, see <http://www.gnu.org/licenses/>.
*/
package org.graylog2.events;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.BasicDBObjectBuilder;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import org.graylog.testing.mongodb.MongoDBInstance;
import org.graylog2.bindings.providers.MongoJackObjectMapperProvider;
import org.graylog2.database.MongoConnection;
import org.graylog2.shared.bindings.providers.ObjectMapperProvider;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
import org.joda.time.DateTimeZone;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
public class ClusterEventCleanupPeriodicalTest {
@Rule
public final MongoDBInstance mongodb = MongoDBInstance.createForClass();
private static final DateTime TIME = new DateTime(2015, 4, 1, 0, 0, DateTimeZone.UTC);
@Rule
public final MockitoRule mockitoRule = MockitoJUnit.rule();
private final ObjectMapper objectMapper = new ObjectMapperProvider().get();
private MongoConnection mongoConnection;
private ClusterEventCleanupPeriodical clusterEventCleanupPeriodical;
@Before
public void setUpService() throws Exception {
DateTimeUtils.setCurrentMillisFixed(TIME.getMillis());
this.mongoConnection = mongodb.mongoConnection();
MongoJackObjectMapperProvider provider = new MongoJackObjectMapperProvider(objectMapper);
this.clusterEventCleanupPeriodical = new ClusterEventCleanupPeriodical(provider, mongodb.mongoConnection());
}
@After
public void tearDown() {
DateTimeUtils.setCurrentMillisSystem();
mongoConnection.getMongoDatabase().drop();
}
@Test
public void testDoRun() throws Exception {
final DBCollection collection = mongoConnection.getDatabase().getCollection(ClusterEventPeriodical.COLLECTION_NAME);
assertThat(insertEvent(collection, 0L)).isTrue();
assertThat(insertEvent(collection, TIME.getMillis())).isTrue();
assertThat(insertEvent(collection, TIME.minus(ClusterEventCleanupPeriodical.DEFAULT_MAX_EVENT_AGE).getMillis())).isTrue();
assertThat(insertEvent(collection, TIME.minus(2 * ClusterEventCleanupPeriodical.DEFAULT_MAX_EVENT_AGE).getMillis())).isTrue();
assertThat(collection.count()).isEqualTo(4L);
clusterEventCleanupPeriodical.run();
assertThat(collection.count()).isEqualTo(2L);
}
private boolean insertEvent(DBCollection collection, long timestamp) {
DBObject event = new BasicDBObjectBuilder()
.add("timestamp", timestamp)
.add("producer", "TEST-PRODUCER")
.add("consumers", Collections.emptyList())
.add("event_class", String.class.getCanonicalName())
.add("payload", "Test" + timestamp)
.get();
return collection.save(event).wasAcknowledged();
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2017 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.
*/
// This file was collated from types used in:
// https://github.com/coreos/etcd-operator/tree/e7f18696bbdc127fa028a99ca8166a8519749328/pkg/apis/etcd/v1beta2.
// When kubeadm moves to its own repo and controls its own dependencies,
// this file will be no longer be needed.
package spec
import (
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
)
const (
// CRDResourceKind is the CRD resource kind
CRDResourceKind = "EtcdCluster"
// CRDResourcePlural is the CRD resource plural
CRDResourcePlural = "etcdclusters"
groupName = "etcd.database.coreos.com"
)
var (
// SchemeBuilder is a scheme builder
SchemeBuilder = runtime.NewSchemeBuilder(AddKnownTypes)
// AddToScheme adds to the scheme
AddToScheme = SchemeBuilder.AddToScheme
// SchemeGroupVersion is the scheme version
SchemeGroupVersion = schema.GroupVersion{Group: groupName, Version: "v1beta2"}
// CRDName is the name of the CRD
CRDName = CRDResourcePlural + "." + groupName
)
// Resource gets an EtcdCluster GroupResource for a specified resource
func Resource(resource string) schema.GroupResource {
return SchemeGroupVersion.WithResource(resource).GroupResource()
}
// AddKnownTypes adds the set of types defined in this package to the supplied scheme.
func AddKnownTypes(s *runtime.Scheme) error {
s.AddKnownTypes(SchemeGroupVersion,
&EtcdCluster{},
&EtcdClusterList{},
)
metav1.AddToGroupVersion(s, SchemeGroupVersion)
return nil
}
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// EtcdClusterList is a list of etcd clusters.
type EtcdClusterList struct {
metav1.TypeMeta `json:",inline"`
// Standard list metadata
// More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
metav1.ListMeta `json:"metadata,omitempty"`
Items []EtcdCluster `json:"items"`
}
// +genclient
// +k8s:deepcopy-gen:interfaces=k8s.io/apimachinery/pkg/runtime.Object
// EtcdCluster represents an etcd cluster
type EtcdCluster struct {
metav1.TypeMeta `json:",inline"`
metav1.ObjectMeta `json:"metadata,omitempty"`
Spec ClusterSpec `json:"spec"`
}
// ClusterSpec represents a cluster spec
type ClusterSpec struct {
// Size is the expected size of the etcd cluster.
// The etcd-operator will eventually make the size of the running
// cluster equal to the expected size.
// The vaild range of the size is from 1 to 7.
Size int `json:"size"`
// BaseImage is the base etcd image name that will be used to launch
// etcd clusters. This is useful for private registries, etc.
//
// If image is not set, default is quay.io/coreos/etcd
BaseImage string `json:"baseImage"`
// Version is the expected version of the etcd cluster.
// The etcd-operator will eventually make the etcd cluster version
// equal to the expected version.
//
// The version must follow the [semver]( http://semver.org) format, for example "3.1.8".
// Only etcd released versions are supported: https://github.com/coreos/etcd/releases
//
// If version is not set, default is "3.1.8".
Version string `json:"version,omitempty"`
// Paused is to pause the control of the operator for the etcd cluster.
Paused bool `json:"paused,omitempty"`
// Pod defines the policy to create pod for the etcd pod.
//
// Updating Pod does not take effect on any existing etcd pods.
Pod *PodPolicy `json:"pod,omitempty"`
// SelfHosted determines if the etcd cluster is used for a self-hosted
// Kubernetes cluster.
//
// SelfHosted is a cluster initialization configuration. It cannot be updated.
SelfHosted *SelfHostedPolicy `json:"selfHosted,omitempty"`
// etcd cluster TLS configuration
TLS *TLSPolicy `json:"TLS,omitempty"`
}
// PodPolicy defines the policy to create pod for the etcd container.
type PodPolicy struct {
// Labels specifies the labels to attach to pods the operator creates for the
// etcd cluster.
// "app" and "etcd_*" labels are reserved for the internal use of the etcd operator.
// Do not overwrite them.
Labels map[string]string `json:"labels,omitempty"`
// NodeSelector specifies a map of key-value pairs. For the pod to be eligible
// to run on a node, the node must have each of the indicated key-value pairs as
// labels.
NodeSelector map[string]string `json:"nodeSelector,omitempty"`
// AntiAffinity determines if the etcd-operator tries to avoid putting
// the etcd members in the same cluster onto the same node.
AntiAffinity bool `json:"antiAffinity,omitempty"`
// Resources is the resource requirements for the etcd container.
// This field cannot be updated once the cluster is created.
Resources v1.ResourceRequirements `json:"resources,omitempty"`
// Tolerations specifies the pod's tolerations.
Tolerations []v1.Toleration `json:"tolerations,omitempty"`
// List of environment variables to set in the etcd container.
// This is used to configure etcd process. etcd cluster cannot be created, when
// bad environement variables are provided. Do not overwrite any flags used to
// bootstrap the cluster (for example `--initial-cluster` flag).
// This field cannot be updated.
EtcdEnv []v1.EnvVar `json:"etcdEnv,omitempty"`
// By default, kubernetes will mount a service account token into the etcd pods.
// AutomountServiceAccountToken indicates whether pods running with the service account should have an API token automatically mounted.
AutomountServiceAccountToken *bool `json:"automountServiceAccountToken,omitempty"`
}
// TLSPolicy defines the TLS policy of an etcd cluster
type TLSPolicy struct {
// StaticTLS enables user to generate static x509 certificates and keys,
// put them into Kubernetes secrets, and specify them into here.
Static *StaticTLS `json:"static,omitempty"`
}
// StaticTLS represents static TLS
type StaticTLS struct {
// Member contains secrets containing TLS certs used by each etcd member pod.
Member *MemberSecret `json:"member,omitempty"`
// OperatorSecret is the secret containing TLS certs used by operator to
// talk securely to this cluster.
OperatorSecret string `json:"operatorSecret,omitempty"`
}
// MemberSecret represents a member secret
type MemberSecret struct {
// PeerSecret is the secret containing TLS certs used by each etcd member pod
// for the communication between etcd peers.
PeerSecret string `json:"peerSecret,omitempty"`
// ServerSecret is the secret containing TLS certs used by each etcd member pod
// for the communication between etcd server and its clients.
ServerSecret string `json:"serverSecret,omitempty"`
}
// SelfHostedPolicy represents a self-hosted policy
type SelfHostedPolicy struct {
// BootMemberClientEndpoint specifies a bootstrap member for the cluster.
// If there is no bootstrap member, a completely new cluster will be created.
// The boot member will be removed from the cluster once the self-hosted cluster
// setup successfully.
BootMemberClientEndpoint string `json:"bootMemberClientEndpoint,omitempty"`
// SkipBootMemberRemoval specifies whether the removal of the bootstrap member
// should be skipped. By default the operator will automatically remove the
// bootstrap member from the new cluster - this happens during the pivot
// procedure and is the first step of decommissioning the bootstrap member.
// If unspecified, the default is `false`. If set to `true`, you are
// expected to remove the boot member yourself from the etcd cluster.
SkipBootMemberRemoval bool `json:"skipBootMemberRemoval,omitempty"`
}
| {
"pile_set_name": "Github"
} |
.theme-flatwhite {
.king-table tr {
border-bottom: 1px solid #eee;
}
.pagination-bar {
.oi {
color: #666;
}
}
.king-table-head {
background-color: #FFF;
}
.king-table a {
color: #000;
}
.king-table-body tr {
&:hover {
background-color: #F7F7F7;
}
}
}
| {
"pile_set_name": "Github"
} |
<vector xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
android:width="72dp"
android:height="100dp"
android:viewportWidth="72"
android:viewportHeight="100">
<path
android:pathData="M45,1l27,26.7V99H0V1h45z">
<aapt:attr name="android:fillColor">
<gradient
android:startY="99"
android:startX="36"
android:endY="1"
android:endX="36"
android:type="linear">
<item android:offset="0" android:color="#FFC8D4DB"/>
<item android:offset="0.139" android:color="#FFD8E1E6"/>
<item android:offset="0.359" android:color="#FFEBF0F3"/>
<item android:offset="0.617" android:color="#FFF9FAFB"/>
<item android:offset="1" android:color="#FFFFFFFF"/>
</gradient>
</aapt:attr>
</path>
<path
android:pathData="M45,1l27,26.7V99H0V1h45z"
android:strokeWidth="2"
android:fillColor="#00000000"
android:strokeColor="#7191a1"/>
<path
android:pathData="M14.4,44.1v-4.9c1,-0.1 1.8,-0.2 2.3,-0.5 0.5,-0.2 0.9,-0.7 1.3,-1.2 0.4,-0.6 0.6,-1.3 0.8,-2.2 0.1,-0.7 0.2,-1.8 0.2,-3.4 0,-2.7 0.1,-4.5 0.4,-5.6 0.2,-1 0.7,-1.9 1.3,-2.5s1.6,-1.1 2.8,-1.5c0.8,-0.2 2.1,-0.4 3.9,-0.4h1.1v4.9c-1.5,0 -2.5,0.1 -2.9,0.3 -0.4,0.2 -0.7,0.4 -1,0.8 -0.2,0.3 -0.3,0.9 -0.3,1.8s-0.1,2.5 -0.2,4.9c-0.1,1.4 -0.2,2.5 -0.5,3.4 -0.3,0.8 -0.7,1.5 -1.1,2.1 -0.4,0.5 -1.1,1.1 -2,1.7 0.8,0.5 1.5,1 2,1.6s0.9,1.4 1.2,2.3 0.5,2.1 0.5,3.6c0.1,2.3 0.1,3.7 0.1,4.4 0,0.9 0.1,1.5 0.3,1.9 0.2,0.4 0.6,0.6 1,0.8 0.4,0.2 1.4,0.3 2.9,0.3v4.9h-1.1c-1.8,0 -3.3,-0.1 -4.2,-0.4 -1,-0.3 -1.8,-0.8 -2.5,-1.5s-1.1,-1.5 -1.4,-2.5c-0.2,-1 -0.3,-2.6 -0.3,-4.8 0,-2.5 -0.1,-4.2 -0.3,-4.9 -0.3,-1.1 -0.8,-1.9 -1.4,-2.4 -0.7,-0.6 -1.6,-1 -2.9,-1z"
android:strokeAlpha="0.95"
android:fillAlpha="0.95">
<aapt:attr name="android:fillColor">
<gradient
android:startY="61.55"
android:startX="21.45"
android:endY="21.95"
android:endX="21.45"
android:type="linear">
<item android:offset="0" android:color="#FFADCCDC"/>
<item android:offset="1" android:color="#FF4C6C7B"/>
</gradient>
</aapt:attr>
</path>
<path
android:pathData="M58.7,44.1c-1,0.1 -1.8,0.2 -2.3,0.5 -0.5,0.2 -0.9,0.7 -1.3,1.2 -0.4,0.6 -0.6,1.3 -0.8,2.2 -0.1,0.7 -0.2,1.8 -0.2,3.4 0,2.7 -0.1,4.5 -0.4,5.6 -0.2,1.1 -0.7,1.9 -1.3,2.5 -0.6,0.6 -1.6,1.1 -2.8,1.5 -0.8,0.2 -2.1,0.4 -3.9,0.4h-1.1v-4.9c1.5,0 2.4,-0.1 2.9,-0.3s0.8,-0.5 1,-0.8c0.2,-0.3 0.3,-0.9 0.3,-1.8 0,-0.8 0.1,-2.4 0.2,-4.8 0.1,-1.4 0.3,-2.6 0.6,-3.4 0.3,-0.9 0.7,-1.6 1.2,-2.2s1.1,-1.1 1.9,-1.6c-1,-0.7 -1.8,-1.3 -2.2,-1.9 -0.6,-0.9 -1.1,-2.1 -1.3,-3.4 -0.2,-1 -0.3,-3.1 -0.3,-6.3 0,-1 -0.1,-1.7 -0.3,-2.1 -0.2,-0.3 -0.5,-0.6 -0.9,-0.8 -0.4,-0.2 -1.4,-0.3 -3,-0.3V22h1.1c1.8,0 3.3,0.1 4.2,0.4 1,0.3 1.8,0.8 2.5,1.5s1.1,1.5 1.4,2.5c0.2,1 0.4,2.6 0.4,4.8 0,2.5 0.1,4.1 0.3,4.9 0.3,1.1 0.8,1.9 1.4,2.3 0.6,0.5 1.6,0.7 2.8,0.8l-0.1,4.9z"
android:strokeAlpha="0.95"
android:fillAlpha="0.95">
<aapt:attr name="android:fillColor">
<gradient
android:startY="61.45"
android:startX="51.7"
android:endY="21.95"
android:endX="51.7"
android:type="linear">
<item android:offset="0" android:color="#FFADCCDC"/>
<item android:offset="1" android:color="#FF4C6C7B"/>
</gradient>
</aapt:attr>
</path>
<path
android:pathData="M45,1l27,26.7H45V1z">
<aapt:attr name="android:fillColor">
<gradient
android:startY="27.813"
android:startX="45.037"
android:endY="14.313"
android:endX="58.537"
android:type="linear">
<item android:offset="0" android:color="#FFFFFFFF"/>
<item android:offset="0.35" android:color="#FFFAFBFB"/>
<item android:offset="0.532" android:color="#FFEDF1F4"/>
<item android:offset="0.675" android:color="#FFDDE5E9"/>
<item android:offset="0.799" android:color="#FFC7D3DA"/>
<item android:offset="0.908" android:color="#FFADBDC7"/>
<item android:offset="1" android:color="#FF92A5B0"/>
</gradient>
</aapt:attr>
</path>
<path
android:pathData="M45,1l27,26.7H45V1z"
android:strokeLineJoin="bevel"
android:strokeWidth="2"
android:fillColor="#00000000"
android:strokeColor="#7191a1"/>
<path
android:pathData="M22.1,84.2l3.9,1.2c-0.6,2.2 -1.6,3.8 -3,4.9 -1.4,1.1 -3.2,1.6 -5.3,1.6 -2.7,0 -4.8,-0.9 -6.6,-2.7 -1.7,-1.8 -2.6,-4.3 -2.6,-7.5 0,-3.3 0.9,-5.9 2.6,-7.8s4,-2.8 6.8,-2.8c2.5,0 4.4,0.7 6,2.2 0.9,0.9 1.6,2.1 2.1,3.7l-4,1c-0.2,-1 -0.7,-1.9 -1.5,-2.5s-1.7,-0.9 -2.7,-0.9c-1.5,0 -2.7,0.5 -3.6,1.6 -0.9,1.1 -1.4,2.8 -1.4,5.2 0,2.5 0.5,4.3 1.4,5.4 0.9,1.1 2.1,1.6 3.6,1.6 1.1,0 2,-0.3 2.8,-1 0.6,-0.7 1.1,-1.8 1.5,-3.2zM28.4,85l3.9,-0.4c0.2,1.3 0.7,2.3 1.4,2.9s1.7,0.9 2.9,0.9c1.3,0 2.3,-0.3 2.9,-0.8 0.7,-0.6 1,-1.2 1,-1.9 0,-0.5 -0.1,-0.9 -0.4,-1.2 -0.3,-0.3 -0.8,-0.6 -1.5,-0.9 -0.5,-0.2 -1.6,-0.5 -3.2,-0.9 -2.2,-0.5 -3.7,-1.2 -4.6,-2 -1.2,-1.1 -1.8,-2.4 -1.8,-4 0,-1 0.3,-2 0.9,-2.9 0.6,-0.9 1.4,-1.6 2.5,-2 1.1,-0.5 2.4,-0.7 3.9,-0.7 2.5,0 4.4,0.6 5.7,1.7s1.9,2.6 2,4.4l-4,0.2c-0.2,-1 -0.5,-1.8 -1.1,-2.2 -0.6,-0.5 -1.4,-0.7 -2.6,-0.7 -1.2,0 -2.1,0.2 -2.8,0.7 -0.2,0.3 -0.5,0.8 -0.5,1.3s0.2,0.9 0.6,1.2c0.5,0.4 1.8,0.9 3.7,1.3s3.4,0.9 4.4,1.4 1.7,1.2 2.2,2 0.8,1.9 0.8,3.2c0,1.1 -0.3,2.2 -1,3.2 -0.6,1 -1.5,1.7 -2.7,2.2 -1.2,0.5 -2.6,0.7 -4.4,0.7 -2.5,0 -4.5,-0.6 -5.8,-1.8 -1.3,-0.9 -2.1,-2.6 -2.4,-4.9zM47.1,85l3.9,-0.4c0.2,1.3 0.7,2.3 1.4,2.9s1.7,0.9 2.9,0.9c1.3,0 2.3,-0.3 2.9,-0.8 0.7,-0.6 1,-1.2 1,-1.9 0,-0.5 -0.1,-0.9 -0.4,-1.2 -0.3,-0.3 -0.8,-0.6 -1.5,-0.9 -0.5,-0.2 -1.6,-0.5 -3.2,-0.9 -2.2,-0.5 -3.7,-1.2 -4.6,-2 -1.2,-1.1 -1.8,-2.4 -1.8,-4 0,-1 0.3,-2 0.9,-2.9 0.6,-0.9 1.4,-1.6 2.5,-2 1.1,-0.5 2.4,-0.7 3.9,-0.7 2.5,0 4.4,0.6 5.7,1.7s1.9,2.6 2,4.4l-4,0.2c-0.2,-1 -0.5,-1.8 -1.1,-2.2 -0.6,-0.5 -1.4,-0.7 -2.6,-0.7 -1.2,0 -2.1,0.2 -2.8,0.7 -0.4,0.3 -0.6,0.7 -0.6,1.2s0.2,0.9 0.6,1.2c0.5,0.4 1.8,0.9 3.7,1.3s3.4,0.9 4.4,1.4 1.7,1.2 2.2,2 0.8,1.9 0.8,3.2c0,1.1 -0.3,2.2 -1,3.2 -0.6,1 -1.5,1.7 -2.7,2.2 -1.2,0.5 -2.6,0.7 -4.4,0.7 -2.5,0 -4.5,-0.6 -5.8,-1.8 -1.2,-0.8 -2,-2.5 -2.3,-4.8z"
android:fillColor="#4c6c7b"/>
</vector>
| {
"pile_set_name": "Github"
} |
{
"__comment__": [
"Rename this file from composer.local.json.dist to composer.local.json to"
"manage your local dependencies without changing the core composer.json."
"See https://github.com/wikimedia/composer-merge-plugin for more details."
],
"require": {
"example/dependency": "1.0.0"
}
}
| {
"pile_set_name": "Github"
} |
package service.impl;
import java.util.Set;
import javax.annotation.Resource;
import dao.UserDao;
import entity.User;
import service.UserService;
import org.springframework.stereotype.Service;
@Service("userService")
public class UserServiceImpl implements UserService {
@Resource
private UserDao userDao;
public User getByUserName(String userName) {
return userDao.getByUserName(userName);
}
public Set<String> getRoles(String userName) {
return userDao.getRoles(userName);
}
public Set<String> getPermissions(String userName) {
return userDao.getPermissions(userName);
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2020 LINE Corporation
*
* LINE Corporation licenses this file to you under the Apache License,
* version 2.0 (the "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.linecorp.bot.client;
import java.io.IOException;
import java.util.Collections;
import org.junit.Before;
import org.junit.Test;
import com.linecorp.bot.model.Narrowcast;
import com.linecorp.bot.model.message.TextMessage;
import com.linecorp.bot.model.narrowcast.Filter;
import com.linecorp.bot.model.narrowcast.filter.GenderDemographicFilter;
import com.linecorp.bot.model.narrowcast.filter.GenderDemographicFilter.Gender;
import com.linecorp.bot.model.response.BotApiResponse;
import com.linecorp.bot.model.response.GetMessageEventResponse;
import com.linecorp.bot.model.response.NarrowcastProgressResponse;
import com.linecorp.bot.model.response.NarrowcastProgressResponse.Phase;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class InsightIntegrationTest {
private LineMessagingClient target;
@Before
public void setUp() throws IOException {
IntegrationTestSettings settings = IntegrationTestSettingsLoader.load();
target = LineMessagingClientFactory.create(settings);
}
@Test
public void testGetMessageEvent() throws Exception {
// Send narrowcast message.
BotApiResponse response = target.narrowcast(
new Narrowcast(new TextMessage("Narrowcast test(gender=male)"),
Filter.builder()
.demographic(
GenderDemographicFilter
.builder()
.oneOf(Collections.singletonList(Gender.MALE))
.build()
).build())).get();
log.info("Narrowcast response={}", response);
// Waiting sending process
for (int i = 0; i < 10; i++) {
NarrowcastProgressResponse progressResponse = target.getNarrowcastProgress(
response.getRequestId()).get();
log.info("Progress={}", progressResponse);
log.info("Progress response={}", progressResponse);
if (progressResponse.getPhase() == Phase.SUCCEEDED
|| progressResponse.getPhase() == Phase.FAILED) {
break;
}
Thread.sleep(1000);
}
GetMessageEventResponse messageEvent = target.getMessageEvent(
response.getRequestId()).get();
log.info("messageEvent={}", messageEvent);
}
}
| {
"pile_set_name": "Github"
} |
{
"test_desc" : "varchar data type, maximum size",
"server" : {
"version" : {
"min" : "9.2.0",
"max" : ""
}
}
}
| {
"pile_set_name": "Github"
} |
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5
org.eclipse.jdt.core.compiler.compliance=1.5
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.5
| {
"pile_set_name": "Github"
} |
{
"typedDefinition": {
"UnionMember1": {
"x": 1
}
},
"omitted": "OMITTED"
}
| {
"pile_set_name": "Github"
} |
/* Copyright 2016-2017 Joaquin M Lopez Munoz.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* See http://www.boost.org/libs/poly_collection for library home page.
*/
#include "test_erasure.hpp"
#include <boost/core/lightweight_test.hpp>
#include <iterator>
#include "any_types.hpp"
#include "base_types.hpp"
#include "function_types.hpp"
#include "test_utilities.hpp"
using namespace test_utilities;
template<typename Type,typename PolyCollection>
void test_local_erase(const PolyCollection& p2)
{
using size_type=typename PolyCollection::size_type;
for(size_type i=0;i<p2.template size<Type>();++i){
PolyCollection p=p2;
auto it=p.erase(p.template cbegin<Type>()+i);
BOOST_TEST(it-p.template begin<Type>()==(std::ptrdiff_t)i);
BOOST_TEST(p.template size<Type>()==p2.template size<Type>()-1);
}
}
template<typename Type,typename PolyCollection>
void test_local_range_erase(const PolyCollection& p2)
{
using size_type=typename PolyCollection::size_type;
for(size_type i=0;i<=p2.template size<Type>();++i){
for(size_type j=i;j<=p2.template size<Type>();++j){
PolyCollection p=p2;
auto first=p.template cbegin<Type>()+i,
last=p.template cbegin<Type>()+j;
auto it=p.erase(first,last);
BOOST_TEST(it-p.template begin<Type>()==(std::ptrdiff_t)i);
BOOST_TEST(p.template size<Type>()==p2.template size<Type>()-(j-i));
}
}
}
template<typename Type,typename PolyCollection>
void test_local_clear(const PolyCollection& p2)
{
PolyCollection p=p2;
p.template clear<Type>();
BOOST_TEST(p.template empty<Type>());
BOOST_TEST(p.size()==p2.size()-p2.template size<Type>());
}
template<typename PolyCollection,typename ValueFactory,typename... Types>
void test_erasure()
{
using size_type=typename PolyCollection::size_type;
PolyCollection p,p2;
ValueFactory v;
fill<constraints<is_copy_constructible>,Types...>(p2,v,5);
auto sit=p2.segment_traversal().begin();
p2.clear(sit->type_info());
++sit;++sit;
p2.clear(sit->type_info());
for(size_type i=0;i<p2.size();++i){
p=p2;
auto it=p.erase(std::next(p.cbegin(),i));
BOOST_TEST(std::distance(p.begin(),it)==(std::ptrdiff_t)i);
BOOST_TEST(p.size()==p2.size()-1);
}
for(auto s:p2.segment_traversal()){
auto& info=s.type_info();
for(size_type i=0;i<p2.size(info);++i){
p=p2;
auto it=p.erase(p.cbegin(info)+i);
BOOST_TEST(it-p.begin(info)==(std::ptrdiff_t)i);
BOOST_TEST(p.size(info)==p2.size(info)-1);
}
}
do_((
p2.template is_registered<Types>()?test_local_erase<Types>(p2),0:0)...);
for(size_type i=0;i<=p2.size();++i){
for(size_type j=i;j<=p2.size();++j){
p=p2;
auto first=std::next(p.cbegin(),i),
last=std::next(p.cbegin(),j);
auto it=p.erase(first,last);
BOOST_TEST(std::distance(p.begin(),it)==(std::ptrdiff_t)i);
BOOST_TEST(p.size()==p2.size()-(j-i));
}
}
for(auto s:p2.segment_traversal()){
auto& info=s.type_info();
for(size_type i=0;i<=p2.size(info);++i){
for(size_type j=i;j<=p2.size(info);++j){
p=p2;
auto first=p.cbegin(info)+i,
last=p.cbegin(info)+j;
auto it=p.erase(first,last);
BOOST_TEST(it-p.begin(info)==(std::ptrdiff_t)i);
BOOST_TEST(p.size(info)==p2.size(info)-(j-i));
}
}
}
do_((p2.template is_registered<Types>()?
test_local_range_erase<Types>(p2),0:0)...);
p=p2;
p.clear();
BOOST_TEST(p.empty());
for(auto s:p2.segment_traversal()){
auto& info=s.type_info();
p=p2;
p.clear(info);
BOOST_TEST(p.empty(info));
BOOST_TEST(p.size()==p2.size()-p2.size(info));
}
do_((p2.template is_registered<Types>()?
test_local_clear<Types>(p2),0:0)...);
}
void test_erasure()
{
test_erasure<
any_types::collection,auto_increment,
any_types::t1,any_types::t2,any_types::t3,
any_types::t4,any_types::t5>();
test_erasure<
base_types::collection,auto_increment,
base_types::t1,base_types::t2,base_types::t3,
base_types::t4,base_types::t5>();
test_erasure<
function_types::collection,auto_increment,
function_types::t1,function_types::t2,function_types::t3,
function_types::t4,function_types::t5>();
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.ec2.model.transform;
import javax.xml.stream.events.XMLEvent;
import javax.annotation.Generated;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* DeprovisionByoipCidrResult StAX Unmarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeprovisionByoipCidrResultStaxUnmarshaller implements Unmarshaller<DeprovisionByoipCidrResult, StaxUnmarshallerContext> {
public DeprovisionByoipCidrResult unmarshall(StaxUnmarshallerContext context) throws Exception {
DeprovisionByoipCidrResult deprovisionByoipCidrResult = new DeprovisionByoipCidrResult();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return deprovisionByoipCidrResult;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("byoipCidr", targetDepth)) {
deprovisionByoipCidrResult.setByoipCidr(ByoipCidrStaxUnmarshaller.getInstance().unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return deprovisionByoipCidrResult;
}
}
}
}
private static DeprovisionByoipCidrResultStaxUnmarshaller instance;
public static DeprovisionByoipCidrResultStaxUnmarshaller getInstance() {
if (instance == null)
instance = new DeprovisionByoipCidrResultStaxUnmarshaller();
return instance;
}
}
| {
"pile_set_name": "Github"
} |
#ifndef OCCA_TOOLS_HASH_HEADER
#define OCCA_TOOLS_HASH_HEADER
#include <iostream>
#include <occa/defines.hpp>
#include <occa/io/output.hpp>
#include <occa/types.hpp>
namespace occa {
// Uses FNV hashing
class hash_t {
public:
bool initialized;
int h[8];
mutable std::string h_string;
mutable int sh[8];
hash_t();
hash_t(const int *h_);
hash_t(const hash_t &hash);
hash_t& operator = (const hash_t &hash);
void clear();
inline bool isInitialized() const { return initialized; }
bool operator < (const hash_t &fo) const;
bool operator == (const hash_t &fo) const;
bool operator != (const hash_t &fo) const;
hash_t& operator ^= (const hash_t hash);
template <class TM>
hash_t operator ^ (const TM &t) const;
std::string getFullString() const;
std::string getString() const;
operator std::string () const;
static hash_t fromString(const std::string &s);
friend std::ostream& operator << (std::ostream &out,
const hash_t &hash);
};
std::ostream& operator << (std::ostream &out,
const hash_t &hash);
hash_t hash(const void *ptr, udim_t bytes);
template <class TM>
inline hash_t hash(const TM &t) {
return hash(&t, sizeof(TM));
}
template <class TM>
inline hash_t hash_t::operator ^ (const TM &t) const {
return (*this ^ hash(t));
}
template <>
hash_t hash_t::operator ^ (const hash_t &hash) const;
hash_t hash(const char *c);
hash_t hash(const std::string &str);
hash_t hashFile(const std::string &filename);
}
#endif
| {
"pile_set_name": "Github"
} |
@charset "UTF-8";
/*!
*
* bttn.css - https://ganapativs.github.io/bttn.css
* Version - 0.2.4
* Demo: https://bttn.surge.sh
*
* Licensed under the MIT license - http://opensource.org/licenses/MIT
*
* Copyright (c) 2016 Ganapati V S (@ganapativs)
*
*/
/* standalone - .bttn-stretch */
.bttn-default {
color: #fff;
}
.bttn-primary,
.bttn,
.bttn-lg,
.bttn-md,
.bttn-sm,
.bttn-xs {
color: #1d89ff;
}
.bttn-warning {
color: #feab3a;
}
.bttn-danger {
color: #ff5964;
}
.bttn-success {
color: #28b78d;
}
.bttn-royal {
color: #bd2df5;
}
.bttn,
.bttn-lg,
.bttn-md,
.bttn-sm,
.bttn-xs {
margin: 0;
padding: 0;
border-width: 0;
border-color: transparent;
background: transparent;
font-weight: 400;
cursor: pointer;
position: relative;
}
.bttn-lg {
padding: 8px 15px;
font-size: 24px;
font-family: inherit;
}
.bttn-md {
font-size: 20px;
font-family: inherit;
padding: 5px 12px;
}
.bttn-sm {
padding: 4px 10px;
font-size: 16px;
font-family: inherit;
}
.bttn-xs {
padding: 3px 8px;
font-size: 12px;
font-family: inherit;
}
.bttn-stretch {
margin: 0;
padding: 0;
border-width: 0;
border-color: transparent;
background: transparent;
font-weight: 400;
cursor: pointer;
position: relative;
font-size: 20px;
font-family: inherit;
padding: 5px 12px;
overflow: hidden;
border-width: 0;
border-radius: 0;
background: transparent;
color: #fff;
letter-spacing: 0;
-webkit-transition: all 0.2s cubic-bezier(0.02, 0.01, 0.47, 1);
transition: all 0.2s cubic-bezier(0.02, 0.01, 0.47, 1);
}
.bttn-stretch:after,
.bttn-stretch:before {
position: absolute;
left: 0;
width: 100%;
height: 1px;
background: currentColor;
content: '';
opacity: 0.65;
-webkit-transition: all 0.2s cubic-bezier(0.02, 0.01, 0.47, 1);
transition: all 0.2s cubic-bezier(0.02, 0.01, 0.47, 1);
-webkit-transform: scaleX(0);
transform: scaleX(0);
}
.bttn-stretch:after {
top: 0;
}
.bttn-stretch:before {
bottom: 0;
}
.bttn-stretch:hover,
.bttn-stretch:focus {
letter-spacing: 2px;
opacity: 0.9;
-webkit-transition: all 0.3s cubic-bezier(0.02, 0.01, 0.47, 1);
transition: all 0.3s cubic-bezier(0.02, 0.01, 0.47, 1);
}
.bttn-stretch:hover:after,
.bttn-stretch:focus:after {
opacity: 1;
-webkit-transition: all 0.3s cubic-bezier(0.02, 0.01, 0.47, 1);
transition: all 0.3s cubic-bezier(0.02, 0.01, 0.47, 1);
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
.bttn-stretch:hover:before,
.bttn-stretch:focus:before {
opacity: 1;
-webkit-transition: all 0.3s cubic-bezier(0.02, 0.01, 0.47, 1);
transition: all 0.3s cubic-bezier(0.02, 0.01, 0.47, 1);
-webkit-transform: scaleX(1);
transform: scaleX(1);
}
.bttn-stretch.bttn-xs {
padding: 3px 8px;
font-size: 12px;
font-family: inherit;
}
.bttn-stretch.bttn-sm {
padding: 4px 10px;
font-size: 16px;
font-family: inherit;
}
.bttn-stretch.bttn-md {
font-size: 20px;
font-family: inherit;
padding: 5px 12px;
}
.bttn-stretch.bttn-lg {
padding: 8px 15px;
font-size: 24px;
font-family: inherit;
}
.bttn-stretch.bttn-default {
color: #fff;
}
.bttn-stretch.bttn-primary {
color: #1d89ff;
}
.bttn-stretch.bttn-warning {
color: #feab3a;
}
.bttn-stretch.bttn-danger {
color: #ff5964;
}
.bttn-stretch.bttn-success {
color: #28b78d;
}
.bttn-stretch.bttn-royal {
color: #bd2df5;
}
| {
"pile_set_name": "Github"
} |
{
"network": [
[
"probeNetwork - default - end",
2,
283480
],
[
"probeNetwork - default - start",
0,
0
]
],
"gfx": [
[
"probeGFX - default - end",
3,
7,
7,
1,
[
1089568,
1089568
],
[
82,
82
],
[
144,
144
]
]
]
} | {
"pile_set_name": "Github"
} |
import scala.tools.partest._
// Simple sanity test for -Yshow-member-pos.
object Test extends DirectTest {
override def extraSettings: String = "-usejavacp -Ystop-after:parser -Yshow-member-pos \"\" -d " + testOutput.path
override def show() = compile()
override def code = """
class A(val a: Int = 1) {
}
object A {
def bippy = {
def hello = 55
"" + hello
}
class Dingo {
def foooooz = /****
****/ {
val a = 1
a
}
}
}
class B { def f = 1 }
"""
}
| {
"pile_set_name": "Github"
} |
diff -r C:\Program Files (x86)\Embarcadero\Studio\20.0\source\rtl\common\System.iOS.Sensors.pas Z:\Source\DelphiWorlds\Patches\Delphi\10.3.3\System.iOS.Sensors.pas
36c36,38
< iOSapi.CocoaTypes, iOSapi.CoreLocation, iOSapi.CoreMotion, Macapi.Helpers, Macapi.Consts;
---
> iOSapi.CocoaTypes, iOSapi.CoreLocation, iOSapi.CoreMotion, Macapi.Helpers, Macapi.Consts,
> // DW - helper units
> DW.iOSapi.Helpers, DW.iOS.Sensors;
81a84,85
> // DW
> LCircularRegion: CLCircularRegion;
84,85c88,91
< UniqueID := TNSString.Wrap(TNSString.OCClass.stringWithUTF8String(MarshaledAString(UTF8Encode(Region.ID))));
<
---
> // DW - commenting out unnecessary code
> UniqueID := StrToNSStr(Region.ID); // TNSString.Wrap(TNSString.OCClass.stringWithUTF8String(MarshaledAString(UTF8Encode(Region.ID))));
>
> // DW - commenting out deprecated code, adding current code
87,90c93,99
< CLRegionPtr := objc_msgSend(objc_getClass('CLRegion'), sel_getUid('alloc'));
< Result := TCLRegion.Wrap(
< objc_msgSendPD3(CLRegionPtr, sel_getUid('initCircularRegionWithCenter:radius:identifier:'),
< Center, Region.Radius, NSStringToID(UniqueID)) );
---
> // CLRegionPtr := objc_msgSend(objc_getClass('CLRegion'), sel_getUid('alloc'));
> // Result := TCLRegion.Wrap(
> // objc_msgSendPD3(CLRegionPtr, sel_getUid('initCircularRegionWithCenter:radius:identifier:'),
> // Center, Region.Radius, NSStringToID(UniqueID)) );
> LCircularRegion := TCLCircularRegion.Create;
> LCircularRegion.initWithCenter(Center, Region.Radius, (UniqueID as ILocalObject).GetObjectID);
> Result := LCircularRegion;
513a523,524
> // DW
> TiOSLocationSensorHelper.Locater := FLocater;
518a530,531
> // DW
> TiOSLocationSensorHelper.Locater := nil;
579a593,595
> // DW - explicitly set allowance for background updates since iOS requires it on iOS >= 9.0
> if TOSVersion.Check(9) and (FLocater <> nil) and TiOSHelperEx.HasBackgroundMode('location') then
> FLocater.setAllowsBackgroundLocationUpdates(True);
1006c1022,1023
< kCLAuthorizationStatusAuthorized:
---
> // DW - add missing case value
> kCLAuthorizationStatusAuthorized, kCLAuthorizationStatusAuthorizedWhenInUse:
| {
"pile_set_name": "Github"
} |
#include "test.h"
#include <stdio.h>
int main(int argc, char** argv)
{
int s = TestClass::someFunction("foobar");
printf("jadda %d\n", s);
return 0;
}
| {
"pile_set_name": "Github"
} |
{
"errors": [
{
"message": "Variable \"$v1\" got invalid value. Expected type \"String!\" found null.",
"locations": [
{
"line": 1,
"column": 27
}
]
}
]
} | {
"pile_set_name": "Github"
} |
#! /bin/sh
# set -x
# Demos shell for sugoupillaud
# Albena Mateeva, Jan 29, 2001
#---------------------------------------------------------------
# An example reflectivity series in rdemo.asc
#
# 2048 samples corresponding to:
#
# a surface reflection coeficient
# ( r[0]=-1.0 for this example, i.e., free surface )
#
# and 2047 subsurface interfaces (equally spaced in time).
#
#---------------------------------------------------------------
#-------- show example reflectivity ---------------
# in this example the two-way time thickness of the subsurface layers is 2ms
a2b n1=1 < rdemo.asc | suaddhead ns=2048 | sushw key=dt a=2000 > rdemo.su
suxgraph < rdemo.su label1="Time (s)" label2="Displacement Reflection \
Coeficient" title="REFLECTIVITY SERIES" x2beg=-1 x2end=1 height=600 width=300 &
# COMPUTE AND GRAPH DISPLACEMENT SEISMOGRAMS FOR A SURFACE SOURCE:
#------ surface seismogram --------------------------------------------
sugoupillaud < rdemo.su | suresamp | \
suxgraph label1="Time (s)" label2="Displacement" \
title="SURFACE SEISMOGRAM" x2beg=-1 x2end=1 height=600 width=300 &
#------ receiver burried at 250 ms (250 layers) below the surface -----
sugoupillaud <rdemo.su k=251 | suresamp | \
suxgraph label1="Time (s)" label2="Displacement" \
title="RECEIVER DEPTH 250 ms" x2beg=-1 x2end=1 height=563 width=300 &
#------ receiver burried at 500 ms (500 layers) below the surface -----
sugoupillaud < rdemo.su k=501 | suresamp | \
suxgraph label1="Time (s)" label2="Displacement" \
title="RECEIVER DEPTH 500 ms" x2beg=-1 x2end=1 height=527 width=300 &
# REMARK: The length of these seismograms is defined by the default value
# of tmax. It coinsides with the arrival of the primary reflection from the
# deepest interface. This choice (and any smaller tmax) neutralizes the
# consequences of modelling the earth below the deepest interface as a
# homogeneous half-space.
# SUGGESTED EXERCISE: Change the surface reflection coeficient
# (the first entry in the rdemo.asc file) from -1.0 (free surface)
# to zero (no surface-related multiples) and see what happens to
# the seismograms.
exit 0
| {
"pile_set_name": "Github"
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_111) on Mon Oct 31 20:20:43 PDT 2016 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.guacamole.net.auth.permission.SystemPermission (guacamole-ext 0.9.10-incubating API)</title>
<meta name="date" content="2016-10-31">
<link rel="stylesheet" type="text/css" href="../../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.guacamole.net.auth.permission.SystemPermission (guacamole-ext 0.9.10-incubating API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/guacamole/net/auth/permission/class-use/SystemPermission.html" target="_top">Frames</a></li>
<li><a href="SystemPermission.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.guacamole.net.auth.permission.SystemPermission" class="title">Uses of Class<br>org.apache.guacamole.net.auth.permission.SystemPermission</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.guacamole.net.auth.permission">org.apache.guacamole.net.auth.permission</a></td>
<td class="colLast">
<div class="block">Provides classes which describe the various permissions a Guacamole user
can be granted.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#org.apache.guacamole.net.auth.simple">org.apache.guacamole.net.auth.simple</a></td>
<td class="colLast">
<div class="block">Provides a basic AuthenticationProvider base class that can be used to create
simple AuthenticationProviders in the same way allowed by the old
authentication API.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.guacamole.net.auth.permission">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a> in <a href="../../../../../../../org/apache/guacamole/net/auth/permission/package-summary.html">org.apache.guacamole.net.auth.permission</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/apache/guacamole/net/auth/permission/package-summary.html">org.apache.guacamole.net.auth.permission</a> that return types with arguments of type <a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><<a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a>></code></td>
<td class="colLast"><span class="typeNameLabel">SystemPermissionSet.</span><code><span class="memberNameLink"><a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermissionSet.html#getPermissions--">getPermissions</a></span>()</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Method parameters in <a href="../../../../../../../org/apache/guacamole/net/auth/permission/package-summary.html">org.apache.guacamole.net.auth.permission</a> with type arguments of type <a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">SystemPermissionSet.</span><code><span class="memberNameLink"><a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermissionSet.html#addPermissions-java.util.Set-">addPermissions</a></span>(<a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><<a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a>> permissions)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">SystemPermissionSet.</span><code><span class="memberNameLink"><a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermissionSet.html#removePermissions-java.util.Set-">removePermissions</a></span>(<a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><<a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a>> permissions)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="org.apache.guacamole.net.auth.simple">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a> in <a href="../../../../../../../org/apache/guacamole/net/auth/simple/package-summary.html">org.apache.guacamole.net.auth.simple</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../../org/apache/guacamole/net/auth/simple/package-summary.html">org.apache.guacamole.net.auth.simple</a> that return types with arguments of type <a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><<a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a>></code></td>
<td class="colLast"><span class="typeNameLabel">SimpleSystemPermissionSet.</span><code><span class="memberNameLink"><a href="../../../../../../../org/apache/guacamole/net/auth/simple/SimpleSystemPermissionSet.html#getPermissions--">getPermissions</a></span>()</code> </td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Method parameters in <a href="../../../../../../../org/apache/guacamole/net/auth/simple/package-summary.html">org.apache.guacamole.net.auth.simple</a> with type arguments of type <a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">SimpleSystemPermissionSet.</span><code><span class="memberNameLink"><a href="../../../../../../../org/apache/guacamole/net/auth/simple/SimpleSystemPermissionSet.html#addPermissions-java.util.Set-">addPermissions</a></span>(<a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><<a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a>> permissions)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">SimpleSystemPermissionSet.</span><code><span class="memberNameLink"><a href="../../../../../../../org/apache/guacamole/net/auth/simple/SimpleSystemPermissionSet.html#removePermissions-java.util.Set-">removePermissions</a></span>(<a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><<a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a>> permissions)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected void</code></td>
<td class="colLast"><span class="typeNameLabel">SimpleSystemPermissionSet.</span><code><span class="memberNameLink"><a href="../../../../../../../org/apache/guacamole/net/auth/simple/SimpleSystemPermissionSet.html#setPermissions-java.util.Set-">setPermissions</a></span>(<a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><<a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a>> permissions)</code>
<div class="block">Sets the Set which backs this SimpleSystemPermissionSet.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructor parameters in <a href="../../../../../../../org/apache/guacamole/net/auth/simple/package-summary.html">org.apache.guacamole.net.auth.simple</a> with type arguments of type <a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../../org/apache/guacamole/net/auth/simple/SimpleSystemPermissionSet.html#SimpleSystemPermissionSet-java.util.Set-">SimpleSystemPermissionSet</a></span>(<a href="http://docs.oracle.com/javase/6/docs/api/java/util/Set.html?is-external=true" title="class or interface in java.util">Set</a><<a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">SystemPermission</a>> permissions)</code>
<div class="block">Creates a new SimpleSystemPermissionSet which contains the permissions
within the given Set.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../org/apache/guacamole/net/auth/permission/SystemPermission.html" title="class in org.apache.guacamole.net.auth.permission">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../index.html?org/apache/guacamole/net/auth/permission/class-use/SystemPermission.html" target="_top">Frames</a></li>
<li><a href="SystemPermission.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2016. All rights reserved.</small></p>
</body>
</html>
| {
"pile_set_name": "Github"
} |
package Paws::RDS::DescribeDBInstances;
use Moose;
has DBInstanceIdentifier => (is => 'ro', isa => 'Str');
has Filters => (is => 'ro', isa => 'ArrayRef[Paws::RDS::Filter]');
has Marker => (is => 'ro', isa => 'Str');
has MaxRecords => (is => 'ro', isa => 'Int');
use MooseX::ClassAttribute;
class_has _api_call => (isa => 'Str', is => 'ro', default => 'DescribeDBInstances');
class_has _returns => (isa => 'Str', is => 'ro', default => 'Paws::RDS::DBInstanceMessage');
class_has _result_key => (isa => 'Str', is => 'ro', default => 'DescribeDBInstancesResult');
1;
### main pod documentation begin ###
=head1 NAME
Paws::RDS::DescribeDBInstances - Arguments for method DescribeDBInstances on L<Paws::RDS>
=head1 DESCRIPTION
This class represents the parameters used for calling the method DescribeDBInstances on the
L<Amazon Relational Database Service|Paws::RDS> service. Use the attributes of this class
as arguments to method DescribeDBInstances.
You shouldn't make instances of this class. Each attribute should be used as a named argument in the call to DescribeDBInstances.
=head1 SYNOPSIS
my $rds = Paws->service('RDS');
# To list DB instance settings
# This example lists settings for the specified DB instance.
my $DBInstanceMessage =
$rds->DescribeDBInstances( 'DBInstanceIdentifier' => 'mymysqlinstance' );
Values for attributes that are native types (Int, String, Float, etc) can passed as-is (scalar values). Values for complex Types (objects) can be passed as a HashRef. The keys and values of the hashref will be used to instance the underlying object.
For the AWS API documentation, see L<https://docs.aws.amazon.com/goto/WebAPI/rds/DescribeDBInstances>
=head1 ATTRIBUTES
=head2 DBInstanceIdentifier => Str
The user-supplied instance identifier. If this parameter is specified,
information from only the specific DB instance is returned. This
parameter isn't case-sensitive.
Constraints:
=over
=item *
If supplied, must match the identifier of an existing DBInstance.
=back
=head2 Filters => ArrayRef[L<Paws::RDS::Filter>]
A filter that specifies one or more DB instances to describe.
Supported filters:
=over
=item *
C<db-cluster-id> - Accepts DB cluster identifiers and DB cluster Amazon
Resource Names (ARNs). The results list will only include information
about the DB instances associated with the DB clusters identified by
these ARNs.
=item *
C<db-instance-id> - Accepts DB instance identifiers and DB instance
Amazon Resource Names (ARNs). The results list will only include
information about the DB instances identified by these ARNs.
=item *
C<dbi-resource-id> - Accepts DB instance resource identifiers. The
results list will only include information about the DB instances
identified by these DB instance resource identifiers.
=item *
C<domain> - Accepts Active Directory directory IDs. The results list
will only include information about the DB instances associated with
these domains.
=item *
C<engine> - Accepts engine names. The results list will only include
information about the DB instances for these engines.
=back
=head2 Marker => Str
An optional pagination token provided by a previous
C<DescribeDBInstances> request. If this parameter is specified, the
response includes only records beyond the marker, up to the value
specified by C<MaxRecords>.
=head2 MaxRecords => Int
The maximum number of records to include in the response. If more
records exist than the specified C<MaxRecords> value, a pagination
token called a marker is included in the response so that you can
retrieve the remaining results.
Default: 100
Constraints: Minimum 20, maximum 100.
=head1 SEE ALSO
This class forms part of L<Paws>, documenting arguments for method DescribeDBInstances in L<Paws::RDS>
=head1 BUGS and CONTRIBUTIONS
The source code is located here: L<https://github.com/pplu/aws-sdk-perl>
Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues>
=cut
| {
"pile_set_name": "Github"
} |
export default {
skip_if_ssr: true,
props: {
indeterminate: true
},
html: `
<input type="checkbox">
<p>checked? false</p>
<p>indeterminate? true</p>
`,
async test({ assert, component, target, window }) {
const input = target.querySelector('input');
assert.equal(input.checked, false);
assert.equal(input.indeterminate, true);
const event = new window.Event('change');
input.checked = true;
input.indeterminate = false;
await input.dispatchEvent(event);
assert.equal(component.indeterminate, false);
assert.equal(component.checked, true);
assert.htmlEqual(target.innerHTML, `
<input type="checkbox">
<p>checked? true</p>
<p>indeterminate? false</p>
`);
component.indeterminate = true;
assert.equal(input.indeterminate, true);
assert.equal(input.checked, true);
assert.htmlEqual(target.innerHTML, `
<input type="checkbox">
<p>checked? true</p>
<p>indeterminate? true</p>
`);
}
};
| {
"pile_set_name": "Github"
} |
# accepts
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][downloads-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][travis-image]][travis-url]
[![Test Coverage][coveralls-image]][coveralls-url]
Higher level content negotiation based on [negotiator](https://www.npmjs.com/package/negotiator). Extracted from [koa](https://www.npmjs.com/package/koa) for general use.
In addition to negotiator, it allows:
- Allows types as an array or arguments list, ie `(['text/html', 'application/json'])` as well as `('text/html', 'application/json')`.
- Allows type shorthands such as `json`.
- Returns `false` when no types match
- Treats non-existent headers as `*`
## Installation
```sh
npm install accepts
```
## API
```js
var accepts = require('accepts')
```
### accepts(req)
Create a new `Accepts` object for the given `req`.
#### .charset(charsets)
Return the first accepted charset. If nothing in `charsets` is accepted,
then `false` is returned.
#### .charsets()
Return the charsets that the request accepts, in the order of the client's
preference (most preferred first).
#### .encoding(encodings)
Return the first accepted encoding. If nothing in `encodings` is accepted,
then `false` is returned.
#### .encodings()
Return the encodings that the request accepts, in the order of the client's
preference (most preferred first).
#### .language(languages)
Return the first accepted language. If nothing in `languages` is accepted,
then `false` is returned.
#### .languages()
Return the languages that the request accepts, in the order of the client's
preference (most preferred first).
#### .type(types)
Return the first accepted type (and it is returned as the same text as what
appears in the `types` array). If nothing in `types` is accepted, then `false`
is returned.
The `types` array can contain full MIME types or file extensions. Any value
that is not a full MIME types is passed to `require('mime-types').lookup`.
#### .types()
Return the types that the request accepts, in the order of the client's
preference (most preferred first).
## Examples
### Simple type negotiation
This simple example shows how to use `accepts` to return a different typed
respond body based on what the client wants to accept. The server lists it's
preferences in order and will get back the best match between the client and
server.
```js
var accepts = require('accepts')
var http = require('http')
function app(req, res) {
var accept = accepts(req)
// the order of this list is significant; should be server preferred order
switch(accept.type(['json', 'html'])) {
case 'json':
res.setHeader('Content-Type', 'application/json')
res.write('{"hello":"world!"}')
break
case 'html':
res.setHeader('Content-Type', 'text/html')
res.write('<b>hello, world!</b>')
break
default:
// the fallback is text/plain, so no need to specify it above
res.setHeader('Content-Type', 'text/plain')
res.write('hello, world!')
break
}
res.end()
}
http.createServer(app).listen(3000)
```
You can test this out with the cURL program:
```sh
curl -I -H'Accept: text/html' http://localhost:3000/
```
## License
[MIT](LICENSE)
[npm-image]: https://img.shields.io/npm/v/accepts.svg
[npm-url]: https://npmjs.org/package/accepts
[node-version-image]: https://img.shields.io/node/v/accepts.svg
[node-version-url]: http://nodejs.org/download/
[travis-image]: https://img.shields.io/travis/jshttp/accepts/master.svg
[travis-url]: https://travis-ci.org/jshttp/accepts
[coveralls-image]: https://img.shields.io/coveralls/jshttp/accepts/master.svg
[coveralls-url]: https://coveralls.io/r/jshttp/accepts
[downloads-image]: https://img.shields.io/npm/dm/accepts.svg
[downloads-url]: https://npmjs.org/package/accepts
| {
"pile_set_name": "Github"
} |
/*
* linux/fs/locks.c
*
* Provide support for fcntl()'s F_GETLK, F_SETLK, and F_SETLKW calls.
* Doug Evans ([email protected]), August 07, 1992
*
* Deadlock detection added.
* FIXME: one thing isn't handled yet:
* - mandatory locks (requires lots of changes elsewhere)
* Kelly Carmichael (kelly@[142.24.8.65]), September 17, 1994.
*
* Miscellaneous edits, and a total rewrite of posix_lock_file() code.
* Kai Petzke ([email protected]), 1994
*
* Converted file_lock_table to a linked list from an array, which eliminates
* the limits on how many active file locks are open.
* Chad Page ([email protected]), November 27, 1994
*
* Removed dependency on file descriptors. dup()'ed file descriptors now
* get the same locks as the original file descriptors, and a close() on
* any file descriptor removes ALL the locks on the file for the current
* process. Since locks still depend on the process id, locks are inherited
* after an exec() but not after a fork(). This agrees with POSIX, and both
* BSD and SVR4 practice.
* Andy Walker ([email protected]), February 14, 1995
*
* Scrapped free list which is redundant now that we allocate locks
* dynamically with kmalloc()/kfree().
* Andy Walker ([email protected]), February 21, 1995
*
* Implemented two lock personalities - FL_FLOCK and FL_POSIX.
*
* FL_POSIX locks are created with calls to fcntl() and lockf() through the
* fcntl() system call. They have the semantics described above.
*
* FL_FLOCK locks are created with calls to flock(), through the flock()
* system call, which is new. Old C libraries implement flock() via fcntl()
* and will continue to use the old, broken implementation.
*
* FL_FLOCK locks follow the 4.4 BSD flock() semantics. They are associated
* with a file pointer (filp). As a result they can be shared by a parent
* process and its children after a fork(). They are removed when the last
* file descriptor referring to the file pointer is closed (unless explicitly
* unlocked).
*
* FL_FLOCK locks never deadlock, an existing lock is always removed before
* upgrading from shared to exclusive (or vice versa). When this happens
* any processes blocked by the current lock are woken up and allowed to
* run before the new lock is applied.
* Andy Walker ([email protected]), June 09, 1995
*
* Removed some race conditions in flock_lock_file(), marked other possible
* races. Just grep for FIXME to see them.
* Dmitry Gorodchanin ([email protected]), February 09, 1996.
*
* Addressed Dmitry's concerns. Deadlock checking no longer recursive.
* Lock allocation changed to GFP_ATOMIC as we can't afford to sleep
* once we've checked for blocking and deadlocking.
* Andy Walker ([email protected]), April 03, 1996.
*
* Initial implementation of mandatory locks. SunOS turned out to be
* a rotten model, so I implemented the "obvious" semantics.
* See 'Documentation/filesystems/mandatory-locking.txt' for details.
* Andy Walker ([email protected]), April 06, 1996.
*
* Don't allow mandatory locks on mmap()'ed files. Added simple functions to
* check if a file has mandatory locks, used by mmap(), open() and creat() to
* see if system call should be rejected. Ref. HP-UX/SunOS/Solaris Reference
* Manual, Section 2.
* Andy Walker ([email protected]), April 09, 1996.
*
* Tidied up block list handling. Added '/proc/locks' interface.
* Andy Walker ([email protected]), April 24, 1996.
*
* Fixed deadlock condition for pathological code that mixes calls to
* flock() and fcntl().
* Andy Walker ([email protected]), April 29, 1996.
*
* Allow only one type of locking scheme (FL_POSIX or FL_FLOCK) to be in use
* for a given file at a time. Changed the CONFIG_LOCK_MANDATORY scheme to
* guarantee sensible behaviour in the case where file system modules might
* be compiled with different options than the kernel itself.
* Andy Walker ([email protected]), May 15, 1996.
*
* Added a couple of missing wake_up() calls. Thanks to Thomas Meckel
* ([email protected]) for spotting this.
* Andy Walker ([email protected]), May 15, 1996.
*
* Changed FL_POSIX locks to use the block list in the same way as FL_FLOCK
* locks. Changed process synchronisation to avoid dereferencing locks that
* have already been freed.
* Andy Walker ([email protected]), Sep 21, 1996.
*
* Made the block list a circular list to minimise searching in the list.
* Andy Walker ([email protected]), Sep 25, 1996.
*
* Made mandatory locking a mount option. Default is not to allow mandatory
* locking.
* Andy Walker ([email protected]), Oct 04, 1996.
*
* Some adaptations for NFS support.
* Olaf Kirch ([email protected]), Dec 1996,
*
* Fixed /proc/locks interface so that we can't overrun the buffer we are handed.
* Andy Walker ([email protected]), May 12, 1997.
*
* Use slab allocator instead of kmalloc/kfree.
* Use generic list implementation from <linux/list.h>.
* Sped up posix_locks_deadlock by only considering blocked locks.
* Matthew Wilcox <[email protected]>, March, 2000.
*
* Leases and LOCK_MAND
* Matthew Wilcox <[email protected]>, June, 2000.
* Stephen Rothwell <[email protected]>, June, 2000.
*/
#include <linux/capability.h>
#include <linux/file.h>
#include <linux/fdtable.h>
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/security.h>
#include <linux/slab.h>
#include <linux/syscalls.h>
#include <linux/time.h>
#include <linux/rcupdate.h>
#include <linux/pid_namespace.h>
#include <linux/hashtable.h>
#include <linux/percpu.h>
#include <linux/lglock.h>
#define CREATE_TRACE_POINTS
#include <trace/events/filelock.h>
#include <asm/uaccess.h>
#define IS_POSIX(fl) (fl->fl_flags & FL_POSIX)
#define IS_FLOCK(fl) (fl->fl_flags & FL_FLOCK)
#define IS_LEASE(fl) (fl->fl_flags & (FL_LEASE|FL_DELEG|FL_LAYOUT))
#define IS_OFDLCK(fl) (fl->fl_flags & FL_OFDLCK)
static bool lease_breaking(struct file_lock *fl)
{
return fl->fl_flags & (FL_UNLOCK_PENDING | FL_DOWNGRADE_PENDING);
}
static int target_leasetype(struct file_lock *fl)
{
if (fl->fl_flags & FL_UNLOCK_PENDING)
return F_UNLCK;
if (fl->fl_flags & FL_DOWNGRADE_PENDING)
return F_RDLCK;
return fl->fl_type;
}
int leases_enable = 1;
int lease_break_time = 45;
/*
* The global file_lock_list is only used for displaying /proc/locks, so we
* keep a list on each CPU, with each list protected by its own spinlock via
* the file_lock_lglock. Note that alterations to the list also require that
* the relevant flc_lock is held.
*/
DEFINE_STATIC_LGLOCK(file_lock_lglock);
static DEFINE_PER_CPU(struct hlist_head, file_lock_list);
/*
* The blocked_hash is used to find POSIX lock loops for deadlock detection.
* It is protected by blocked_lock_lock.
*
* We hash locks by lockowner in order to optimize searching for the lock a
* particular lockowner is waiting on.
*
* FIXME: make this value scale via some heuristic? We generally will want more
* buckets when we have more lockowners holding locks, but that's a little
* difficult to determine without knowing what the workload will look like.
*/
#define BLOCKED_HASH_BITS 7
static DEFINE_HASHTABLE(blocked_hash, BLOCKED_HASH_BITS);
/*
* This lock protects the blocked_hash. Generally, if you're accessing it, you
* want to be holding this lock.
*
* In addition, it also protects the fl->fl_block list, and the fl->fl_next
* pointer for file_lock structures that are acting as lock requests (in
* contrast to those that are acting as records of acquired locks).
*
* Note that when we acquire this lock in order to change the above fields,
* we often hold the flc_lock as well. In certain cases, when reading the fields
* protected by this lock, we can skip acquiring it iff we already hold the
* flc_lock.
*
* In particular, adding an entry to the fl_block list requires that you hold
* both the flc_lock and the blocked_lock_lock (acquired in that order).
* Deleting an entry from the list however only requires the file_lock_lock.
*/
static DEFINE_SPINLOCK(blocked_lock_lock);
static struct kmem_cache *flctx_cache __read_mostly;
static struct kmem_cache *filelock_cache __read_mostly;
static struct file_lock_context *
locks_get_lock_context(struct inode *inode, int type)
{
struct file_lock_context *ctx;
/* paired with cmpxchg() below */
ctx = smp_load_acquire(&inode->i_flctx);
if (likely(ctx) || type == F_UNLCK)
goto out;
ctx = kmem_cache_alloc(flctx_cache, GFP_KERNEL);
if (!ctx)
goto out;
spin_lock_init(&ctx->flc_lock);
INIT_LIST_HEAD(&ctx->flc_flock);
INIT_LIST_HEAD(&ctx->flc_posix);
INIT_LIST_HEAD(&ctx->flc_lease);
/*
* Assign the pointer if it's not already assigned. If it is, then
* free the context we just allocated.
*/
if (cmpxchg(&inode->i_flctx, NULL, ctx)) {
kmem_cache_free(flctx_cache, ctx);
ctx = smp_load_acquire(&inode->i_flctx);
}
out:
return ctx;
}
void
locks_free_lock_context(struct file_lock_context *ctx)
{
if (ctx) {
WARN_ON_ONCE(!list_empty(&ctx->flc_flock));
WARN_ON_ONCE(!list_empty(&ctx->flc_posix));
WARN_ON_ONCE(!list_empty(&ctx->flc_lease));
kmem_cache_free(flctx_cache, ctx);
}
}
static void locks_init_lock_heads(struct file_lock *fl)
{
INIT_HLIST_NODE(&fl->fl_link);
INIT_LIST_HEAD(&fl->fl_list);
INIT_LIST_HEAD(&fl->fl_block);
init_waitqueue_head(&fl->fl_wait);
}
/* Allocate an empty lock structure. */
struct file_lock *locks_alloc_lock(void)
{
struct file_lock *fl = kmem_cache_zalloc(filelock_cache, GFP_KERNEL);
if (fl)
locks_init_lock_heads(fl);
return fl;
}
EXPORT_SYMBOL_GPL(locks_alloc_lock);
void locks_release_private(struct file_lock *fl)
{
if (fl->fl_ops) {
if (fl->fl_ops->fl_release_private)
fl->fl_ops->fl_release_private(fl);
fl->fl_ops = NULL;
}
if (fl->fl_lmops) {
if (fl->fl_lmops->lm_put_owner) {
fl->fl_lmops->lm_put_owner(fl->fl_owner);
fl->fl_owner = NULL;
}
fl->fl_lmops = NULL;
}
}
EXPORT_SYMBOL_GPL(locks_release_private);
/* Free a lock which is not in use. */
void locks_free_lock(struct file_lock *fl)
{
BUG_ON(waitqueue_active(&fl->fl_wait));
BUG_ON(!list_empty(&fl->fl_list));
BUG_ON(!list_empty(&fl->fl_block));
BUG_ON(!hlist_unhashed(&fl->fl_link));
locks_release_private(fl);
kmem_cache_free(filelock_cache, fl);
}
EXPORT_SYMBOL(locks_free_lock);
static void
locks_dispose_list(struct list_head *dispose)
{
struct file_lock *fl;
while (!list_empty(dispose)) {
fl = list_first_entry(dispose, struct file_lock, fl_list);
list_del_init(&fl->fl_list);
locks_free_lock(fl);
}
}
void locks_init_lock(struct file_lock *fl)
{
memset(fl, 0, sizeof(struct file_lock));
locks_init_lock_heads(fl);
}
EXPORT_SYMBOL(locks_init_lock);
/*
* Initialize a new lock from an existing file_lock structure.
*/
void locks_copy_conflock(struct file_lock *new, struct file_lock *fl)
{
new->fl_owner = fl->fl_owner;
new->fl_pid = fl->fl_pid;
new->fl_file = NULL;
new->fl_flags = fl->fl_flags;
new->fl_type = fl->fl_type;
new->fl_start = fl->fl_start;
new->fl_end = fl->fl_end;
new->fl_lmops = fl->fl_lmops;
new->fl_ops = NULL;
if (fl->fl_lmops) {
if (fl->fl_lmops->lm_get_owner)
fl->fl_lmops->lm_get_owner(fl->fl_owner);
}
}
EXPORT_SYMBOL(locks_copy_conflock);
void locks_copy_lock(struct file_lock *new, struct file_lock *fl)
{
/* "new" must be a freshly-initialized lock */
WARN_ON_ONCE(new->fl_ops);
locks_copy_conflock(new, fl);
new->fl_file = fl->fl_file;
new->fl_ops = fl->fl_ops;
if (fl->fl_ops) {
if (fl->fl_ops->fl_copy_lock)
fl->fl_ops->fl_copy_lock(new, fl);
}
}
EXPORT_SYMBOL(locks_copy_lock);
static inline int flock_translate_cmd(int cmd) {
if (cmd & LOCK_MAND)
return cmd & (LOCK_MAND | LOCK_RW);
switch (cmd) {
case LOCK_SH:
return F_RDLCK;
case LOCK_EX:
return F_WRLCK;
case LOCK_UN:
return F_UNLCK;
}
return -EINVAL;
}
/* Fill in a file_lock structure with an appropriate FLOCK lock. */
static struct file_lock *
flock_make_lock(struct file *filp, unsigned int cmd)
{
struct file_lock *fl;
int type = flock_translate_cmd(cmd);
if (type < 0)
return ERR_PTR(type);
fl = locks_alloc_lock();
if (fl == NULL)
return ERR_PTR(-ENOMEM);
fl->fl_file = filp;
fl->fl_owner = filp;
fl->fl_pid = current->tgid;
fl->fl_flags = FL_FLOCK;
fl->fl_type = type;
fl->fl_end = OFFSET_MAX;
return fl;
}
static int assign_type(struct file_lock *fl, long type)
{
switch (type) {
case F_RDLCK:
case F_WRLCK:
case F_UNLCK:
fl->fl_type = type;
break;
default:
return -EINVAL;
}
return 0;
}
static int flock64_to_posix_lock(struct file *filp, struct file_lock *fl,
struct flock64 *l)
{
switch (l->l_whence) {
case SEEK_SET:
fl->fl_start = 0;
break;
case SEEK_CUR:
fl->fl_start = filp->f_pos;
break;
case SEEK_END:
fl->fl_start = i_size_read(file_inode(filp));
break;
default:
return -EINVAL;
}
if (l->l_start > OFFSET_MAX - fl->fl_start)
return -EOVERFLOW;
fl->fl_start += l->l_start;
if (fl->fl_start < 0)
return -EINVAL;
/* POSIX-1996 leaves the case l->l_len < 0 undefined;
POSIX-2001 defines it. */
if (l->l_len > 0) {
if (l->l_len - 1 > OFFSET_MAX - fl->fl_start)
return -EOVERFLOW;
fl->fl_end = fl->fl_start + l->l_len - 1;
} else if (l->l_len < 0) {
if (fl->fl_start + l->l_len < 0)
return -EINVAL;
fl->fl_end = fl->fl_start - 1;
fl->fl_start += l->l_len;
} else
fl->fl_end = OFFSET_MAX;
fl->fl_owner = current->files;
fl->fl_pid = current->tgid;
fl->fl_file = filp;
fl->fl_flags = FL_POSIX;
fl->fl_ops = NULL;
fl->fl_lmops = NULL;
return assign_type(fl, l->l_type);
}
/* Verify a "struct flock" and copy it to a "struct file_lock" as a POSIX
* style lock.
*/
static int flock_to_posix_lock(struct file *filp, struct file_lock *fl,
struct flock *l)
{
struct flock64 ll = {
.l_type = l->l_type,
.l_whence = l->l_whence,
.l_start = l->l_start,
.l_len = l->l_len,
};
return flock64_to_posix_lock(filp, fl, &ll);
}
/* default lease lock manager operations */
static bool
lease_break_callback(struct file_lock *fl)
{
kill_fasync(&fl->fl_fasync, SIGIO, POLL_MSG);
return false;
}
static void
lease_setup(struct file_lock *fl, void **priv)
{
struct file *filp = fl->fl_file;
struct fasync_struct *fa = *priv;
/*
* fasync_insert_entry() returns the old entry if any. If there was no
* old entry, then it used "priv" and inserted it into the fasync list.
* Clear the pointer to indicate that it shouldn't be freed.
*/
if (!fasync_insert_entry(fa->fa_fd, filp, &fl->fl_fasync, fa))
*priv = NULL;
__f_setown(filp, task_pid(current), PIDTYPE_PID, 0);
}
static const struct lock_manager_operations lease_manager_ops = {
.lm_break = lease_break_callback,
.lm_change = lease_modify,
.lm_setup = lease_setup,
};
/*
* Initialize a lease, use the default lock manager operations
*/
static int lease_init(struct file *filp, long type, struct file_lock *fl)
{
if (assign_type(fl, type) != 0)
return -EINVAL;
fl->fl_owner = filp;
fl->fl_pid = current->tgid;
fl->fl_file = filp;
fl->fl_flags = FL_LEASE;
fl->fl_start = 0;
fl->fl_end = OFFSET_MAX;
fl->fl_ops = NULL;
fl->fl_lmops = &lease_manager_ops;
return 0;
}
/* Allocate a file_lock initialised to this type of lease */
static struct file_lock *lease_alloc(struct file *filp, long type)
{
struct file_lock *fl = locks_alloc_lock();
int error = -ENOMEM;
if (fl == NULL)
return ERR_PTR(error);
error = lease_init(filp, type, fl);
if (error) {
locks_free_lock(fl);
return ERR_PTR(error);
}
return fl;
}
/* Check if two locks overlap each other.
*/
static inline int locks_overlap(struct file_lock *fl1, struct file_lock *fl2)
{
return ((fl1->fl_end >= fl2->fl_start) &&
(fl2->fl_end >= fl1->fl_start));
}
/*
* Check whether two locks have the same owner.
*/
static int posix_same_owner(struct file_lock *fl1, struct file_lock *fl2)
{
if (fl1->fl_lmops && fl1->fl_lmops->lm_compare_owner)
return fl2->fl_lmops == fl1->fl_lmops &&
fl1->fl_lmops->lm_compare_owner(fl1, fl2);
return fl1->fl_owner == fl2->fl_owner;
}
/* Must be called with the flc_lock held! */
static void locks_insert_global_locks(struct file_lock *fl)
{
lg_local_lock(&file_lock_lglock);
fl->fl_link_cpu = smp_processor_id();
hlist_add_head(&fl->fl_link, this_cpu_ptr(&file_lock_list));
lg_local_unlock(&file_lock_lglock);
}
/* Must be called with the flc_lock held! */
static void locks_delete_global_locks(struct file_lock *fl)
{
/*
* Avoid taking lock if already unhashed. This is safe since this check
* is done while holding the flc_lock, and new insertions into the list
* also require that it be held.
*/
if (hlist_unhashed(&fl->fl_link))
return;
lg_local_lock_cpu(&file_lock_lglock, fl->fl_link_cpu);
hlist_del_init(&fl->fl_link);
lg_local_unlock_cpu(&file_lock_lglock, fl->fl_link_cpu);
}
static unsigned long
posix_owner_key(struct file_lock *fl)
{
if (fl->fl_lmops && fl->fl_lmops->lm_owner_key)
return fl->fl_lmops->lm_owner_key(fl);
return (unsigned long)fl->fl_owner;
}
static void locks_insert_global_blocked(struct file_lock *waiter)
{
lockdep_assert_held(&blocked_lock_lock);
hash_add(blocked_hash, &waiter->fl_link, posix_owner_key(waiter));
}
static void locks_delete_global_blocked(struct file_lock *waiter)
{
lockdep_assert_held(&blocked_lock_lock);
hash_del(&waiter->fl_link);
}
/* Remove waiter from blocker's block list.
* When blocker ends up pointing to itself then the list is empty.
*
* Must be called with blocked_lock_lock held.
*/
static void __locks_delete_block(struct file_lock *waiter)
{
locks_delete_global_blocked(waiter);
list_del_init(&waiter->fl_block);
waiter->fl_next = NULL;
}
static void locks_delete_block(struct file_lock *waiter)
{
spin_lock(&blocked_lock_lock);
__locks_delete_block(waiter);
spin_unlock(&blocked_lock_lock);
}
/* Insert waiter into blocker's block list.
* We use a circular list so that processes can be easily woken up in
* the order they blocked. The documentation doesn't require this but
* it seems like the reasonable thing to do.
*
* Must be called with both the flc_lock and blocked_lock_lock held. The
* fl_block list itself is protected by the blocked_lock_lock, but by ensuring
* that the flc_lock is also held on insertions we can avoid taking the
* blocked_lock_lock in some cases when we see that the fl_block list is empty.
*/
static void __locks_insert_block(struct file_lock *blocker,
struct file_lock *waiter)
{
BUG_ON(!list_empty(&waiter->fl_block));
waiter->fl_next = blocker;
list_add_tail(&waiter->fl_block, &blocker->fl_block);
if (IS_POSIX(blocker) && !IS_OFDLCK(blocker))
locks_insert_global_blocked(waiter);
}
/* Must be called with flc_lock held. */
static void locks_insert_block(struct file_lock *blocker,
struct file_lock *waiter)
{
spin_lock(&blocked_lock_lock);
__locks_insert_block(blocker, waiter);
spin_unlock(&blocked_lock_lock);
}
/*
* Wake up processes blocked waiting for blocker.
*
* Must be called with the inode->flc_lock held!
*/
static void locks_wake_up_blocks(struct file_lock *blocker)
{
/*
* Avoid taking global lock if list is empty. This is safe since new
* blocked requests are only added to the list under the flc_lock, and
* the flc_lock is always held here. Note that removal from the fl_block
* list does not require the flc_lock, so we must recheck list_empty()
* after acquiring the blocked_lock_lock.
*/
if (list_empty(&blocker->fl_block))
return;
spin_lock(&blocked_lock_lock);
while (!list_empty(&blocker->fl_block)) {
struct file_lock *waiter;
waiter = list_first_entry(&blocker->fl_block,
struct file_lock, fl_block);
__locks_delete_block(waiter);
if (waiter->fl_lmops && waiter->fl_lmops->lm_notify)
waiter->fl_lmops->lm_notify(waiter);
else
wake_up(&waiter->fl_wait);
}
spin_unlock(&blocked_lock_lock);
}
static void
locks_insert_lock_ctx(struct file_lock *fl, struct list_head *before)
{
fl->fl_nspid = get_pid(task_tgid(current));
list_add_tail(&fl->fl_list, before);
locks_insert_global_locks(fl);
}
static void
locks_unlink_lock_ctx(struct file_lock *fl)
{
locks_delete_global_locks(fl);
list_del_init(&fl->fl_list);
if (fl->fl_nspid) {
put_pid(fl->fl_nspid);
fl->fl_nspid = NULL;
}
locks_wake_up_blocks(fl);
}
static void
locks_delete_lock_ctx(struct file_lock *fl, struct list_head *dispose)
{
locks_unlink_lock_ctx(fl);
if (dispose)
list_add(&fl->fl_list, dispose);
else
locks_free_lock(fl);
}
/* Determine if lock sys_fl blocks lock caller_fl. Common functionality
* checks for shared/exclusive status of overlapping locks.
*/
static int locks_conflict(struct file_lock *caller_fl, struct file_lock *sys_fl)
{
if (sys_fl->fl_type == F_WRLCK)
return 1;
if (caller_fl->fl_type == F_WRLCK)
return 1;
return 0;
}
/* Determine if lock sys_fl blocks lock caller_fl. POSIX specific
* checking before calling the locks_conflict().
*/
static int posix_locks_conflict(struct file_lock *caller_fl, struct file_lock *sys_fl)
{
/* POSIX locks owned by the same process do not conflict with
* each other.
*/
if (posix_same_owner(caller_fl, sys_fl))
return (0);
/* Check whether they overlap */
if (!locks_overlap(caller_fl, sys_fl))
return 0;
return (locks_conflict(caller_fl, sys_fl));
}
/* Determine if lock sys_fl blocks lock caller_fl. FLOCK specific
* checking before calling the locks_conflict().
*/
static int flock_locks_conflict(struct file_lock *caller_fl, struct file_lock *sys_fl)
{
/* FLOCK locks referring to the same filp do not conflict with
* each other.
*/
if (caller_fl->fl_file == sys_fl->fl_file)
return (0);
if ((caller_fl->fl_type & LOCK_MAND) || (sys_fl->fl_type & LOCK_MAND))
return 0;
return (locks_conflict(caller_fl, sys_fl));
}
void
posix_test_lock(struct file *filp, struct file_lock *fl)
{
struct file_lock *cfl;
struct file_lock_context *ctx;
struct inode *inode = file_inode(filp);
ctx = smp_load_acquire(&inode->i_flctx);
if (!ctx || list_empty_careful(&ctx->flc_posix)) {
fl->fl_type = F_UNLCK;
return;
}
spin_lock(&ctx->flc_lock);
list_for_each_entry(cfl, &ctx->flc_posix, fl_list) {
if (posix_locks_conflict(fl, cfl)) {
locks_copy_conflock(fl, cfl);
if (cfl->fl_nspid)
fl->fl_pid = pid_vnr(cfl->fl_nspid);
goto out;
}
}
fl->fl_type = F_UNLCK;
out:
spin_unlock(&ctx->flc_lock);
return;
}
EXPORT_SYMBOL(posix_test_lock);
/*
* Deadlock detection:
*
* We attempt to detect deadlocks that are due purely to posix file
* locks.
*
* We assume that a task can be waiting for at most one lock at a time.
* So for any acquired lock, the process holding that lock may be
* waiting on at most one other lock. That lock in turns may be held by
* someone waiting for at most one other lock. Given a requested lock
* caller_fl which is about to wait for a conflicting lock block_fl, we
* follow this chain of waiters to ensure we are not about to create a
* cycle.
*
* Since we do this before we ever put a process to sleep on a lock, we
* are ensured that there is never a cycle; that is what guarantees that
* the while() loop in posix_locks_deadlock() eventually completes.
*
* Note: the above assumption may not be true when handling lock
* requests from a broken NFS client. It may also fail in the presence
* of tasks (such as posix threads) sharing the same open file table.
* To handle those cases, we just bail out after a few iterations.
*
* For FL_OFDLCK locks, the owner is the filp, not the files_struct.
* Because the owner is not even nominally tied to a thread of
* execution, the deadlock detection below can't reasonably work well. Just
* skip it for those.
*
* In principle, we could do a more limited deadlock detection on FL_OFDLCK
* locks that just checks for the case where two tasks are attempting to
* upgrade from read to write locks on the same inode.
*/
#define MAX_DEADLK_ITERATIONS 10
/* Find a lock that the owner of the given block_fl is blocking on. */
static struct file_lock *what_owner_is_waiting_for(struct file_lock *block_fl)
{
struct file_lock *fl;
hash_for_each_possible(blocked_hash, fl, fl_link, posix_owner_key(block_fl)) {
if (posix_same_owner(fl, block_fl))
return fl->fl_next;
}
return NULL;
}
/* Must be called with the blocked_lock_lock held! */
static int posix_locks_deadlock(struct file_lock *caller_fl,
struct file_lock *block_fl)
{
int i = 0;
lockdep_assert_held(&blocked_lock_lock);
/*
* This deadlock detector can't reasonably detect deadlocks with
* FL_OFDLCK locks, since they aren't owned by a process, per-se.
*/
if (IS_OFDLCK(caller_fl))
return 0;
while ((block_fl = what_owner_is_waiting_for(block_fl))) {
if (i++ > MAX_DEADLK_ITERATIONS)
return 0;
if (posix_same_owner(caller_fl, block_fl))
return 1;
}
return 0;
}
/* Try to create a FLOCK lock on filp. We always insert new FLOCK locks
* after any leases, but before any posix locks.
*
* Note that if called with an FL_EXISTS argument, the caller may determine
* whether or not a lock was successfully freed by testing the return
* value for -ENOENT.
*/
static int flock_lock_inode(struct inode *inode, struct file_lock *request)
{
struct file_lock *new_fl = NULL;
struct file_lock *fl;
struct file_lock_context *ctx;
int error = 0;
bool found = false;
LIST_HEAD(dispose);
ctx = locks_get_lock_context(inode, request->fl_type);
if (!ctx) {
if (request->fl_type != F_UNLCK)
return -ENOMEM;
return (request->fl_flags & FL_EXISTS) ? -ENOENT : 0;
}
if (!(request->fl_flags & FL_ACCESS) && (request->fl_type != F_UNLCK)) {
new_fl = locks_alloc_lock();
if (!new_fl)
return -ENOMEM;
}
spin_lock(&ctx->flc_lock);
if (request->fl_flags & FL_ACCESS)
goto find_conflict;
list_for_each_entry(fl, &ctx->flc_flock, fl_list) {
if (request->fl_file != fl->fl_file)
continue;
if (request->fl_type == fl->fl_type)
goto out;
found = true;
locks_delete_lock_ctx(fl, &dispose);
break;
}
if (request->fl_type == F_UNLCK) {
if ((request->fl_flags & FL_EXISTS) && !found)
error = -ENOENT;
goto out;
}
find_conflict:
list_for_each_entry(fl, &ctx->flc_flock, fl_list) {
if (!flock_locks_conflict(request, fl))
continue;
error = -EAGAIN;
if (!(request->fl_flags & FL_SLEEP))
goto out;
error = FILE_LOCK_DEFERRED;
locks_insert_block(fl, request);
goto out;
}
if (request->fl_flags & FL_ACCESS)
goto out;
locks_copy_lock(new_fl, request);
locks_insert_lock_ctx(new_fl, &ctx->flc_flock);
new_fl = NULL;
error = 0;
out:
spin_unlock(&ctx->flc_lock);
if (new_fl)
locks_free_lock(new_fl);
locks_dispose_list(&dispose);
return error;
}
static int __posix_lock_file(struct inode *inode, struct file_lock *request, struct file_lock *conflock)
{
struct file_lock *fl, *tmp;
struct file_lock *new_fl = NULL;
struct file_lock *new_fl2 = NULL;
struct file_lock *left = NULL;
struct file_lock *right = NULL;
struct file_lock_context *ctx;
int error;
bool added = false;
LIST_HEAD(dispose);
ctx = locks_get_lock_context(inode, request->fl_type);
if (!ctx)
return (request->fl_type == F_UNLCK) ? 0 : -ENOMEM;
/*
* We may need two file_lock structures for this operation,
* so we get them in advance to avoid races.
*
* In some cases we can be sure, that no new locks will be needed
*/
if (!(request->fl_flags & FL_ACCESS) &&
(request->fl_type != F_UNLCK ||
request->fl_start != 0 || request->fl_end != OFFSET_MAX)) {
new_fl = locks_alloc_lock();
new_fl2 = locks_alloc_lock();
}
spin_lock(&ctx->flc_lock);
/*
* New lock request. Walk all POSIX locks and look for conflicts. If
* there are any, either return error or put the request on the
* blocker's list of waiters and the global blocked_hash.
*/
if (request->fl_type != F_UNLCK) {
list_for_each_entry(fl, &ctx->flc_posix, fl_list) {
if (!posix_locks_conflict(request, fl))
continue;
if (conflock)
locks_copy_conflock(conflock, fl);
error = -EAGAIN;
if (!(request->fl_flags & FL_SLEEP))
goto out;
/*
* Deadlock detection and insertion into the blocked
* locks list must be done while holding the same lock!
*/
error = -EDEADLK;
spin_lock(&blocked_lock_lock);
if (likely(!posix_locks_deadlock(request, fl))) {
error = FILE_LOCK_DEFERRED;
__locks_insert_block(fl, request);
}
spin_unlock(&blocked_lock_lock);
goto out;
}
}
/* If we're just looking for a conflict, we're done. */
error = 0;
if (request->fl_flags & FL_ACCESS)
goto out;
/* Find the first old lock with the same owner as the new lock */
list_for_each_entry(fl, &ctx->flc_posix, fl_list) {
if (posix_same_owner(request, fl))
break;
}
/* Process locks with this owner. */
list_for_each_entry_safe_from(fl, tmp, &ctx->flc_posix, fl_list) {
if (!posix_same_owner(request, fl))
break;
/* Detect adjacent or overlapping regions (if same lock type) */
if (request->fl_type == fl->fl_type) {
/* In all comparisons of start vs end, use
* "start - 1" rather than "end + 1". If end
* is OFFSET_MAX, end + 1 will become negative.
*/
if (fl->fl_end < request->fl_start - 1)
continue;
/* If the next lock in the list has entirely bigger
* addresses than the new one, insert the lock here.
*/
if (fl->fl_start - 1 > request->fl_end)
break;
/* If we come here, the new and old lock are of the
* same type and adjacent or overlapping. Make one
* lock yielding from the lower start address of both
* locks to the higher end address.
*/
if (fl->fl_start > request->fl_start)
fl->fl_start = request->fl_start;
else
request->fl_start = fl->fl_start;
if (fl->fl_end < request->fl_end)
fl->fl_end = request->fl_end;
else
request->fl_end = fl->fl_end;
if (added) {
locks_delete_lock_ctx(fl, &dispose);
continue;
}
request = fl;
added = true;
} else {
/* Processing for different lock types is a bit
* more complex.
*/
if (fl->fl_end < request->fl_start)
continue;
if (fl->fl_start > request->fl_end)
break;
if (request->fl_type == F_UNLCK)
added = true;
if (fl->fl_start < request->fl_start)
left = fl;
/* If the next lock in the list has a higher end
* address than the new one, insert the new one here.
*/
if (fl->fl_end > request->fl_end) {
right = fl;
break;
}
if (fl->fl_start >= request->fl_start) {
/* The new lock completely replaces an old
* one (This may happen several times).
*/
if (added) {
locks_delete_lock_ctx(fl, &dispose);
continue;
}
/*
* Replace the old lock with new_fl, and
* remove the old one. It's safe to do the
* insert here since we know that we won't be
* using new_fl later, and that the lock is
* just replacing an existing lock.
*/
error = -ENOLCK;
if (!new_fl)
goto out;
locks_copy_lock(new_fl, request);
request = new_fl;
new_fl = NULL;
locks_insert_lock_ctx(request, &fl->fl_list);
locks_delete_lock_ctx(fl, &dispose);
added = true;
}
}
}
/*
* The above code only modifies existing locks in case of merging or
* replacing. If new lock(s) need to be inserted all modifications are
* done below this, so it's safe yet to bail out.
*/
error = -ENOLCK; /* "no luck" */
if (right && left == right && !new_fl2)
goto out;
error = 0;
if (!added) {
if (request->fl_type == F_UNLCK) {
if (request->fl_flags & FL_EXISTS)
error = -ENOENT;
goto out;
}
if (!new_fl) {
error = -ENOLCK;
goto out;
}
locks_copy_lock(new_fl, request);
locks_insert_lock_ctx(new_fl, &fl->fl_list);
fl = new_fl;
new_fl = NULL;
}
if (right) {
if (left == right) {
/* The new lock breaks the old one in two pieces,
* so we have to use the second new lock.
*/
left = new_fl2;
new_fl2 = NULL;
locks_copy_lock(left, right);
locks_insert_lock_ctx(left, &fl->fl_list);
}
right->fl_start = request->fl_end + 1;
locks_wake_up_blocks(right);
}
if (left) {
left->fl_end = request->fl_start - 1;
locks_wake_up_blocks(left);
}
out:
spin_unlock(&ctx->flc_lock);
/*
* Free any unused locks.
*/
if (new_fl)
locks_free_lock(new_fl);
if (new_fl2)
locks_free_lock(new_fl2);
locks_dispose_list(&dispose);
return error;
}
/**
* posix_lock_file - Apply a POSIX-style lock to a file
* @filp: The file to apply the lock to
* @fl: The lock to be applied
* @conflock: Place to return a copy of the conflicting lock, if found.
*
* Add a POSIX style lock to a file.
* We merge adjacent & overlapping locks whenever possible.
* POSIX locks are sorted by owner task, then by starting address
*
* Note that if called with an FL_EXISTS argument, the caller may determine
* whether or not a lock was successfully freed by testing the return
* value for -ENOENT.
*/
int posix_lock_file(struct file *filp, struct file_lock *fl,
struct file_lock *conflock)
{
return __posix_lock_file(file_inode(filp), fl, conflock);
}
EXPORT_SYMBOL(posix_lock_file);
/**
* posix_lock_inode_wait - Apply a POSIX-style lock to a file
* @inode: inode of file to which lock request should be applied
* @fl: The lock to be applied
*
* Apply a POSIX style lock request to an inode.
*/
static int posix_lock_inode_wait(struct inode *inode, struct file_lock *fl)
{
int error;
might_sleep ();
for (;;) {
error = __posix_lock_file(inode, fl, NULL);
if (error != FILE_LOCK_DEFERRED)
break;
error = wait_event_interruptible(fl->fl_wait, !fl->fl_next);
if (!error)
continue;
locks_delete_block(fl);
break;
}
return error;
}
/**
* locks_mandatory_locked - Check for an active lock
* @file: the file to check
*
* Searches the inode's list of locks to find any POSIX locks which conflict.
* This function is called from locks_verify_locked() only.
*/
int locks_mandatory_locked(struct file *file)
{
int ret;
struct inode *inode = file_inode(file);
struct file_lock_context *ctx;
struct file_lock *fl;
ctx = smp_load_acquire(&inode->i_flctx);
if (!ctx || list_empty_careful(&ctx->flc_posix))
return 0;
/*
* Search the lock list for this inode for any POSIX locks.
*/
spin_lock(&ctx->flc_lock);
ret = 0;
list_for_each_entry(fl, &ctx->flc_posix, fl_list) {
if (fl->fl_owner != current->files &&
fl->fl_owner != file) {
ret = -EAGAIN;
break;
}
}
spin_unlock(&ctx->flc_lock);
return ret;
}
/**
* locks_mandatory_area - Check for a conflicting lock
* @read_write: %FLOCK_VERIFY_WRITE for exclusive access, %FLOCK_VERIFY_READ
* for shared
* @inode: the file to check
* @filp: how the file was opened (if it was)
* @offset: start of area to check
* @count: length of area to check
*
* Searches the inode's list of locks to find any POSIX locks which conflict.
* This function is called from rw_verify_area() and
* locks_verify_truncate().
*/
int locks_mandatory_area(int read_write, struct inode *inode,
struct file *filp, loff_t offset,
size_t count)
{
struct file_lock fl;
int error;
bool sleep = false;
locks_init_lock(&fl);
fl.fl_pid = current->tgid;
fl.fl_file = filp;
fl.fl_flags = FL_POSIX | FL_ACCESS;
if (filp && !(filp->f_flags & O_NONBLOCK))
sleep = true;
fl.fl_type = (read_write == FLOCK_VERIFY_WRITE) ? F_WRLCK : F_RDLCK;
fl.fl_start = offset;
fl.fl_end = offset + count - 1;
for (;;) {
if (filp) {
fl.fl_owner = filp;
fl.fl_flags &= ~FL_SLEEP;
error = __posix_lock_file(inode, &fl, NULL);
if (!error)
break;
}
if (sleep)
fl.fl_flags |= FL_SLEEP;
fl.fl_owner = current->files;
error = __posix_lock_file(inode, &fl, NULL);
if (error != FILE_LOCK_DEFERRED)
break;
error = wait_event_interruptible(fl.fl_wait, !fl.fl_next);
if (!error) {
/*
* If we've been sleeping someone might have
* changed the permissions behind our back.
*/
if (__mandatory_lock(inode))
continue;
}
locks_delete_block(&fl);
break;
}
return error;
}
EXPORT_SYMBOL(locks_mandatory_area);
static void lease_clear_pending(struct file_lock *fl, int arg)
{
switch (arg) {
case F_UNLCK:
fl->fl_flags &= ~FL_UNLOCK_PENDING;
/* fall through: */
case F_RDLCK:
fl->fl_flags &= ~FL_DOWNGRADE_PENDING;
}
}
/* We already had a lease on this file; just change its type */
int lease_modify(struct file_lock *fl, int arg, struct list_head *dispose)
{
int error = assign_type(fl, arg);
if (error)
return error;
lease_clear_pending(fl, arg);
locks_wake_up_blocks(fl);
if (arg == F_UNLCK) {
struct file *filp = fl->fl_file;
f_delown(filp);
filp->f_owner.signum = 0;
fasync_helper(0, fl->fl_file, 0, &fl->fl_fasync);
if (fl->fl_fasync != NULL) {
printk(KERN_ERR "locks_delete_lock: fasync == %p\n", fl->fl_fasync);
fl->fl_fasync = NULL;
}
locks_delete_lock_ctx(fl, dispose);
}
return 0;
}
EXPORT_SYMBOL(lease_modify);
static bool past_time(unsigned long then)
{
if (!then)
/* 0 is a special value meaning "this never expires": */
return false;
return time_after(jiffies, then);
}
static void time_out_leases(struct inode *inode, struct list_head *dispose)
{
struct file_lock_context *ctx = inode->i_flctx;
struct file_lock *fl, *tmp;
lockdep_assert_held(&ctx->flc_lock);
list_for_each_entry_safe(fl, tmp, &ctx->flc_lease, fl_list) {
trace_time_out_leases(inode, fl);
if (past_time(fl->fl_downgrade_time))
lease_modify(fl, F_RDLCK, dispose);
if (past_time(fl->fl_break_time))
lease_modify(fl, F_UNLCK, dispose);
}
}
static bool leases_conflict(struct file_lock *lease, struct file_lock *breaker)
{
if ((breaker->fl_flags & FL_LAYOUT) != (lease->fl_flags & FL_LAYOUT))
return false;
if ((breaker->fl_flags & FL_DELEG) && (lease->fl_flags & FL_LEASE))
return false;
return locks_conflict(breaker, lease);
}
static bool
any_leases_conflict(struct inode *inode, struct file_lock *breaker)
{
struct file_lock_context *ctx = inode->i_flctx;
struct file_lock *fl;
lockdep_assert_held(&ctx->flc_lock);
list_for_each_entry(fl, &ctx->flc_lease, fl_list) {
if (leases_conflict(fl, breaker))
return true;
}
return false;
}
/**
* __break_lease - revoke all outstanding leases on file
* @inode: the inode of the file to return
* @mode: O_RDONLY: break only write leases; O_WRONLY or O_RDWR:
* break all leases
* @type: FL_LEASE: break leases and delegations; FL_DELEG: break
* only delegations
*
* break_lease (inlined for speed) has checked there already is at least
* some kind of lock (maybe a lease) on this file. Leases are broken on
* a call to open() or truncate(). This function can sleep unless you
* specified %O_NONBLOCK to your open().
*/
int __break_lease(struct inode *inode, unsigned int mode, unsigned int type)
{
int error = 0;
struct file_lock_context *ctx;
struct file_lock *new_fl, *fl, *tmp;
unsigned long break_time;
int want_write = (mode & O_ACCMODE) != O_RDONLY;
LIST_HEAD(dispose);
new_fl = lease_alloc(NULL, want_write ? F_WRLCK : F_RDLCK);
if (IS_ERR(new_fl))
return PTR_ERR(new_fl);
new_fl->fl_flags = type;
/* typically we will check that ctx is non-NULL before calling */
ctx = smp_load_acquire(&inode->i_flctx);
if (!ctx) {
WARN_ON_ONCE(1);
return error;
}
spin_lock(&ctx->flc_lock);
time_out_leases(inode, &dispose);
if (!any_leases_conflict(inode, new_fl))
goto out;
break_time = 0;
if (lease_break_time > 0) {
break_time = jiffies + lease_break_time * HZ;
if (break_time == 0)
break_time++; /* so that 0 means no break time */
}
list_for_each_entry_safe(fl, tmp, &ctx->flc_lease, fl_list) {
if (!leases_conflict(fl, new_fl))
continue;
if (want_write) {
if (fl->fl_flags & FL_UNLOCK_PENDING)
continue;
fl->fl_flags |= FL_UNLOCK_PENDING;
fl->fl_break_time = break_time;
} else {
if (lease_breaking(fl))
continue;
fl->fl_flags |= FL_DOWNGRADE_PENDING;
fl->fl_downgrade_time = break_time;
}
if (fl->fl_lmops->lm_break(fl))
locks_delete_lock_ctx(fl, &dispose);
}
if (list_empty(&ctx->flc_lease))
goto out;
if (mode & O_NONBLOCK) {
trace_break_lease_noblock(inode, new_fl);
error = -EWOULDBLOCK;
goto out;
}
restart:
fl = list_first_entry(&ctx->flc_lease, struct file_lock, fl_list);
break_time = fl->fl_break_time;
if (break_time != 0)
break_time -= jiffies;
if (break_time == 0)
break_time++;
locks_insert_block(fl, new_fl);
trace_break_lease_block(inode, new_fl);
spin_unlock(&ctx->flc_lock);
locks_dispose_list(&dispose);
error = wait_event_interruptible_timeout(new_fl->fl_wait,
!new_fl->fl_next, break_time);
spin_lock(&ctx->flc_lock);
trace_break_lease_unblock(inode, new_fl);
locks_delete_block(new_fl);
if (error >= 0) {
/*
* Wait for the next conflicting lease that has not been
* broken yet
*/
if (error == 0)
time_out_leases(inode, &dispose);
if (any_leases_conflict(inode, new_fl))
goto restart;
error = 0;
}
out:
spin_unlock(&ctx->flc_lock);
locks_dispose_list(&dispose);
locks_free_lock(new_fl);
return error;
}
EXPORT_SYMBOL(__break_lease);
/**
* lease_get_mtime - get the last modified time of an inode
* @inode: the inode
* @time: pointer to a timespec which will contain the last modified time
*
* This is to force NFS clients to flush their caches for files with
* exclusive leases. The justification is that if someone has an
* exclusive lease, then they could be modifying it.
*/
void lease_get_mtime(struct inode *inode, struct timespec *time)
{
bool has_lease = false;
struct file_lock_context *ctx;
struct file_lock *fl;
ctx = smp_load_acquire(&inode->i_flctx);
if (ctx && !list_empty_careful(&ctx->flc_lease)) {
spin_lock(&ctx->flc_lock);
if (!list_empty(&ctx->flc_lease)) {
fl = list_first_entry(&ctx->flc_lease,
struct file_lock, fl_list);
if (fl->fl_type == F_WRLCK)
has_lease = true;
}
spin_unlock(&ctx->flc_lock);
}
if (has_lease)
*time = current_fs_time(inode->i_sb);
else
*time = inode->i_mtime;
}
EXPORT_SYMBOL(lease_get_mtime);
/**
* fcntl_getlease - Enquire what lease is currently active
* @filp: the file
*
* The value returned by this function will be one of
* (if no lease break is pending):
*
* %F_RDLCK to indicate a shared lease is held.
*
* %F_WRLCK to indicate an exclusive lease is held.
*
* %F_UNLCK to indicate no lease is held.
*
* (if a lease break is pending):
*
* %F_RDLCK to indicate an exclusive lease needs to be
* changed to a shared lease (or removed).
*
* %F_UNLCK to indicate the lease needs to be removed.
*
* XXX: sfr & willy disagree over whether F_INPROGRESS
* should be returned to userspace.
*/
int fcntl_getlease(struct file *filp)
{
struct file_lock *fl;
struct inode *inode = file_inode(filp);
struct file_lock_context *ctx;
int type = F_UNLCK;
LIST_HEAD(dispose);
ctx = smp_load_acquire(&inode->i_flctx);
if (ctx && !list_empty_careful(&ctx->flc_lease)) {
spin_lock(&ctx->flc_lock);
time_out_leases(file_inode(filp), &dispose);
list_for_each_entry(fl, &ctx->flc_lease, fl_list) {
if (fl->fl_file != filp)
continue;
type = target_leasetype(fl);
break;
}
spin_unlock(&ctx->flc_lock);
locks_dispose_list(&dispose);
}
return type;
}
/**
* check_conflicting_open - see if the given dentry points to a file that has
* an existing open that would conflict with the
* desired lease.
* @dentry: dentry to check
* @arg: type of lease that we're trying to acquire
* @flags: current lock flags
*
* Check to see if there's an existing open fd on this file that would
* conflict with the lease we're trying to set.
*/
static int
check_conflicting_open(const struct dentry *dentry, const long arg, int flags)
{
int ret = 0;
struct inode *inode = dentry->d_inode;
if (flags & FL_LAYOUT)
return 0;
if ((arg == F_RDLCK) && (atomic_read(&inode->i_writecount) > 0))
return -EAGAIN;
if ((arg == F_WRLCK) && ((d_count(dentry) > 1) ||
(atomic_read(&inode->i_count) > 1)))
ret = -EAGAIN;
return ret;
}
static int
generic_add_lease(struct file *filp, long arg, struct file_lock **flp, void **priv)
{
struct file_lock *fl, *my_fl = NULL, *lease;
struct dentry *dentry = filp->f_path.dentry;
struct inode *inode = file_inode(filp);
struct file_lock_context *ctx;
bool is_deleg = (*flp)->fl_flags & FL_DELEG;
int error;
LIST_HEAD(dispose);
lease = *flp;
trace_generic_add_lease(inode, lease);
/* Note that arg is never F_UNLCK here */
ctx = locks_get_lock_context(inode, arg);
if (!ctx)
return -ENOMEM;
/*
* In the delegation case we need mutual exclusion with
* a number of operations that take the i_mutex. We trylock
* because delegations are an optional optimization, and if
* there's some chance of a conflict--we'd rather not
* bother, maybe that's a sign this just isn't a good file to
* hand out a delegation on.
*/
if (is_deleg && !mutex_trylock(&inode->i_mutex))
return -EAGAIN;
if (is_deleg && arg == F_WRLCK) {
/* Write delegations are not currently supported: */
mutex_unlock(&inode->i_mutex);
WARN_ON_ONCE(1);
return -EINVAL;
}
spin_lock(&ctx->flc_lock);
time_out_leases(inode, &dispose);
error = check_conflicting_open(dentry, arg, lease->fl_flags);
if (error)
goto out;
/*
* At this point, we know that if there is an exclusive
* lease on this file, then we hold it on this filp
* (otherwise our open of this file would have blocked).
* And if we are trying to acquire an exclusive lease,
* then the file is not open by anyone (including us)
* except for this filp.
*/
error = -EAGAIN;
list_for_each_entry(fl, &ctx->flc_lease, fl_list) {
if (fl->fl_file == filp &&
fl->fl_owner == lease->fl_owner) {
my_fl = fl;
continue;
}
/*
* No exclusive leases if someone else has a lease on
* this file:
*/
if (arg == F_WRLCK)
goto out;
/*
* Modifying our existing lease is OK, but no getting a
* new lease if someone else is opening for write:
*/
if (fl->fl_flags & FL_UNLOCK_PENDING)
goto out;
}
if (my_fl != NULL) {
lease = my_fl;
error = lease->fl_lmops->lm_change(lease, arg, &dispose);
if (error)
goto out;
goto out_setup;
}
error = -EINVAL;
if (!leases_enable)
goto out;
locks_insert_lock_ctx(lease, &ctx->flc_lease);
/*
* The check in break_lease() is lockless. It's possible for another
* open to race in after we did the earlier check for a conflicting
* open but before the lease was inserted. Check again for a
* conflicting open and cancel the lease if there is one.
*
* We also add a barrier here to ensure that the insertion of the lock
* precedes these checks.
*/
smp_mb();
error = check_conflicting_open(dentry, arg, lease->fl_flags);
if (error) {
locks_unlink_lock_ctx(lease);
goto out;
}
out_setup:
if (lease->fl_lmops->lm_setup)
lease->fl_lmops->lm_setup(lease, priv);
out:
spin_unlock(&ctx->flc_lock);
locks_dispose_list(&dispose);
if (is_deleg)
mutex_unlock(&inode->i_mutex);
if (!error && !my_fl)
*flp = NULL;
return error;
}
static int generic_delete_lease(struct file *filp, void *owner)
{
int error = -EAGAIN;
struct file_lock *fl, *victim = NULL;
struct inode *inode = file_inode(filp);
struct file_lock_context *ctx;
LIST_HEAD(dispose);
ctx = smp_load_acquire(&inode->i_flctx);
if (!ctx) {
trace_generic_delete_lease(inode, NULL);
return error;
}
spin_lock(&ctx->flc_lock);
list_for_each_entry(fl, &ctx->flc_lease, fl_list) {
if (fl->fl_file == filp &&
fl->fl_owner == owner) {
victim = fl;
break;
}
}
trace_generic_delete_lease(inode, victim);
if (victim)
error = fl->fl_lmops->lm_change(victim, F_UNLCK, &dispose);
spin_unlock(&ctx->flc_lock);
locks_dispose_list(&dispose);
return error;
}
/**
* generic_setlease - sets a lease on an open file
* @filp: file pointer
* @arg: type of lease to obtain
* @flp: input - file_lock to use, output - file_lock inserted
* @priv: private data for lm_setup (may be NULL if lm_setup
* doesn't require it)
*
* The (input) flp->fl_lmops->lm_break function is required
* by break_lease().
*/
int generic_setlease(struct file *filp, long arg, struct file_lock **flp,
void **priv)
{
struct inode *inode = file_inode(filp);
int error;
if ((!uid_eq(current_fsuid(), inode->i_uid)) && !capable(CAP_LEASE))
return -EACCES;
if (!S_ISREG(inode->i_mode))
return -EINVAL;
error = security_file_lock(filp, arg);
if (error)
return error;
switch (arg) {
case F_UNLCK:
return generic_delete_lease(filp, *priv);
case F_RDLCK:
case F_WRLCK:
if (!(*flp)->fl_lmops->lm_break) {
WARN_ON_ONCE(1);
return -ENOLCK;
}
return generic_add_lease(filp, arg, flp, priv);
default:
return -EINVAL;
}
}
EXPORT_SYMBOL(generic_setlease);
/**
* vfs_setlease - sets a lease on an open file
* @filp: file pointer
* @arg: type of lease to obtain
* @lease: file_lock to use when adding a lease
* @priv: private info for lm_setup when adding a lease (may be
* NULL if lm_setup doesn't require it)
*
* Call this to establish a lease on the file. The "lease" argument is not
* used for F_UNLCK requests and may be NULL. For commands that set or alter
* an existing lease, the (*lease)->fl_lmops->lm_break operation must be set;
* if not, this function will return -ENOLCK (and generate a scary-looking
* stack trace).
*
* The "priv" pointer is passed directly to the lm_setup function as-is. It
* may be NULL if the lm_setup operation doesn't require it.
*/
int
vfs_setlease(struct file *filp, long arg, struct file_lock **lease, void **priv)
{
if (filp->f_op->setlease)
return filp->f_op->setlease(filp, arg, lease, priv);
else
return generic_setlease(filp, arg, lease, priv);
}
EXPORT_SYMBOL_GPL(vfs_setlease);
static int do_fcntl_add_lease(unsigned int fd, struct file *filp, long arg)
{
struct file_lock *fl;
struct fasync_struct *new;
int error;
fl = lease_alloc(filp, arg);
if (IS_ERR(fl))
return PTR_ERR(fl);
new = fasync_alloc();
if (!new) {
locks_free_lock(fl);
return -ENOMEM;
}
new->fa_fd = fd;
error = vfs_setlease(filp, arg, &fl, (void **)&new);
if (fl)
locks_free_lock(fl);
if (new)
fasync_free(new);
return error;
}
/**
* fcntl_setlease - sets a lease on an open file
* @fd: open file descriptor
* @filp: file pointer
* @arg: type of lease to obtain
*
* Call this fcntl to establish a lease on the file.
* Note that you also need to call %F_SETSIG to
* receive a signal when the lease is broken.
*/
int fcntl_setlease(unsigned int fd, struct file *filp, long arg)
{
if (arg == F_UNLCK)
return vfs_setlease(filp, F_UNLCK, NULL, (void **)&filp);
return do_fcntl_add_lease(fd, filp, arg);
}
/**
* flock_lock_inode_wait - Apply a FLOCK-style lock to a file
* @inode: inode of the file to apply to
* @fl: The lock to be applied
*
* Apply a FLOCK style lock request to an inode.
*/
static int flock_lock_inode_wait(struct inode *inode, struct file_lock *fl)
{
int error;
might_sleep();
for (;;) {
error = flock_lock_inode(inode, fl);
if (error != FILE_LOCK_DEFERRED)
break;
error = wait_event_interruptible(fl->fl_wait, !fl->fl_next);
if (!error)
continue;
locks_delete_block(fl);
break;
}
return error;
}
/**
* locks_lock_inode_wait - Apply a lock to an inode
* @inode: inode of the file to apply to
* @fl: The lock to be applied
*
* Apply a POSIX or FLOCK style lock request to an inode.
*/
int locks_lock_inode_wait(struct inode *inode, struct file_lock *fl)
{
int res = 0;
switch (fl->fl_flags & (FL_POSIX|FL_FLOCK)) {
case FL_POSIX:
res = posix_lock_inode_wait(inode, fl);
break;
case FL_FLOCK:
res = flock_lock_inode_wait(inode, fl);
break;
default:
BUG();
}
return res;
}
EXPORT_SYMBOL(locks_lock_inode_wait);
/**
* sys_flock: - flock() system call.
* @fd: the file descriptor to lock.
* @cmd: the type of lock to apply.
*
* Apply a %FL_FLOCK style lock to an open file descriptor.
* The @cmd can be one of
*
* %LOCK_SH -- a shared lock.
*
* %LOCK_EX -- an exclusive lock.
*
* %LOCK_UN -- remove an existing lock.
*
* %LOCK_MAND -- a `mandatory' flock. This exists to emulate Windows Share Modes.
*
* %LOCK_MAND can be combined with %LOCK_READ or %LOCK_WRITE to allow other
* processes read and write access respectively.
*/
SYSCALL_DEFINE2(flock, unsigned int, fd, unsigned int, cmd)
{
struct fd f = fdget(fd);
struct file_lock *lock;
int can_sleep, unlock;
int error;
error = -EBADF;
if (!f.file)
goto out;
can_sleep = !(cmd & LOCK_NB);
cmd &= ~LOCK_NB;
unlock = (cmd == LOCK_UN);
if (!unlock && !(cmd & LOCK_MAND) &&
!(f.file->f_mode & (FMODE_READ|FMODE_WRITE)))
goto out_putf;
lock = flock_make_lock(f.file, cmd);
if (IS_ERR(lock)) {
error = PTR_ERR(lock);
goto out_putf;
}
if (can_sleep)
lock->fl_flags |= FL_SLEEP;
error = security_file_lock(f.file, lock->fl_type);
if (error)
goto out_free;
if (f.file->f_op->flock)
error = f.file->f_op->flock(f.file,
(can_sleep) ? F_SETLKW : F_SETLK,
lock);
else
error = locks_lock_file_wait(f.file, lock);
out_free:
locks_free_lock(lock);
out_putf:
fdput(f);
out:
return error;
}
/**
* vfs_test_lock - test file byte range lock
* @filp: The file to test lock for
* @fl: The lock to test; also used to hold result
*
* Returns -ERRNO on failure. Indicates presence of conflicting lock by
* setting conf->fl_type to something other than F_UNLCK.
*/
int vfs_test_lock(struct file *filp, struct file_lock *fl)
{
if (filp->f_op->lock)
return filp->f_op->lock(filp, F_GETLK, fl);
posix_test_lock(filp, fl);
return 0;
}
EXPORT_SYMBOL_GPL(vfs_test_lock);
static int posix_lock_to_flock(struct flock *flock, struct file_lock *fl)
{
flock->l_pid = IS_OFDLCK(fl) ? -1 : fl->fl_pid;
#if BITS_PER_LONG == 32
/*
* Make sure we can represent the posix lock via
* legacy 32bit flock.
*/
if (fl->fl_start > OFFT_OFFSET_MAX)
return -EOVERFLOW;
if (fl->fl_end != OFFSET_MAX && fl->fl_end > OFFT_OFFSET_MAX)
return -EOVERFLOW;
#endif
flock->l_start = fl->fl_start;
flock->l_len = fl->fl_end == OFFSET_MAX ? 0 :
fl->fl_end - fl->fl_start + 1;
flock->l_whence = 0;
flock->l_type = fl->fl_type;
return 0;
}
#if BITS_PER_LONG == 32
static void posix_lock_to_flock64(struct flock64 *flock, struct file_lock *fl)
{
flock->l_pid = IS_OFDLCK(fl) ? -1 : fl->fl_pid;
flock->l_start = fl->fl_start;
flock->l_len = fl->fl_end == OFFSET_MAX ? 0 :
fl->fl_end - fl->fl_start + 1;
flock->l_whence = 0;
flock->l_type = fl->fl_type;
}
#endif
/* Report the first existing lock that would conflict with l.
* This implements the F_GETLK command of fcntl().
*/
int fcntl_getlk(struct file *filp, unsigned int cmd, struct flock __user *l)
{
struct file_lock file_lock;
struct flock flock;
int error;
error = -EFAULT;
if (copy_from_user(&flock, l, sizeof(flock)))
goto out;
error = -EINVAL;
if ((flock.l_type != F_RDLCK) && (flock.l_type != F_WRLCK))
goto out;
error = flock_to_posix_lock(filp, &file_lock, &flock);
if (error)
goto out;
if (cmd == F_OFD_GETLK) {
error = -EINVAL;
if (flock.l_pid != 0)
goto out;
cmd = F_GETLK;
file_lock.fl_flags |= FL_OFDLCK;
file_lock.fl_owner = filp;
}
error = vfs_test_lock(filp, &file_lock);
if (error)
goto out;
flock.l_type = file_lock.fl_type;
if (file_lock.fl_type != F_UNLCK) {
error = posix_lock_to_flock(&flock, &file_lock);
if (error)
goto rel_priv;
}
error = -EFAULT;
if (!copy_to_user(l, &flock, sizeof(flock)))
error = 0;
rel_priv:
locks_release_private(&file_lock);
out:
return error;
}
/**
* vfs_lock_file - file byte range lock
* @filp: The file to apply the lock to
* @cmd: type of locking operation (F_SETLK, F_GETLK, etc.)
* @fl: The lock to be applied
* @conf: Place to return a copy of the conflicting lock, if found.
*
* A caller that doesn't care about the conflicting lock may pass NULL
* as the final argument.
*
* If the filesystem defines a private ->lock() method, then @conf will
* be left unchanged; so a caller that cares should initialize it to
* some acceptable default.
*
* To avoid blocking kernel daemons, such as lockd, that need to acquire POSIX
* locks, the ->lock() interface may return asynchronously, before the lock has
* been granted or denied by the underlying filesystem, if (and only if)
* lm_grant is set. Callers expecting ->lock() to return asynchronously
* will only use F_SETLK, not F_SETLKW; they will set FL_SLEEP if (and only if)
* the request is for a blocking lock. When ->lock() does return asynchronously,
* it must return FILE_LOCK_DEFERRED, and call ->lm_grant() when the lock
* request completes.
* If the request is for non-blocking lock the file system should return
* FILE_LOCK_DEFERRED then try to get the lock and call the callback routine
* with the result. If the request timed out the callback routine will return a
* nonzero return code and the file system should release the lock. The file
* system is also responsible to keep a corresponding posix lock when it
* grants a lock so the VFS can find out which locks are locally held and do
* the correct lock cleanup when required.
* The underlying filesystem must not drop the kernel lock or call
* ->lm_grant() before returning to the caller with a FILE_LOCK_DEFERRED
* return code.
*/
int vfs_lock_file(struct file *filp, unsigned int cmd, struct file_lock *fl, struct file_lock *conf)
{
if (filp->f_op->lock)
return filp->f_op->lock(filp, cmd, fl);
else
return posix_lock_file(filp, fl, conf);
}
EXPORT_SYMBOL_GPL(vfs_lock_file);
static int do_lock_file_wait(struct file *filp, unsigned int cmd,
struct file_lock *fl)
{
int error;
error = security_file_lock(filp, fl->fl_type);
if (error)
return error;
for (;;) {
error = vfs_lock_file(filp, cmd, fl, NULL);
if (error != FILE_LOCK_DEFERRED)
break;
error = wait_event_interruptible(fl->fl_wait, !fl->fl_next);
if (!error)
continue;
locks_delete_block(fl);
break;
}
return error;
}
/* Ensure that fl->fl_file has compatible f_mode for F_SETLK calls */
static int
check_fmode_for_setlk(struct file_lock *fl)
{
switch (fl->fl_type) {
case F_RDLCK:
if (!(fl->fl_file->f_mode & FMODE_READ))
return -EBADF;
break;
case F_WRLCK:
if (!(fl->fl_file->f_mode & FMODE_WRITE))
return -EBADF;
}
return 0;
}
/* Apply the lock described by l to an open file descriptor.
* This implements both the F_SETLK and F_SETLKW commands of fcntl().
*/
int fcntl_setlk(unsigned int fd, struct file *filp, unsigned int cmd,
struct flock __user *l)
{
struct file_lock *file_lock = locks_alloc_lock();
struct flock flock;
struct inode *inode;
struct file *f;
int error;
if (file_lock == NULL)
return -ENOLCK;
/*
* This might block, so we do it before checking the inode.
*/
error = -EFAULT;
if (copy_from_user(&flock, l, sizeof(flock)))
goto out;
inode = file_inode(filp);
/* Don't allow mandatory locks on files that may be memory mapped
* and shared.
*/
if (mandatory_lock(inode) && mapping_writably_mapped(filp->f_mapping)) {
error = -EAGAIN;
goto out;
}
error = flock_to_posix_lock(filp, file_lock, &flock);
if (error)
goto out;
error = check_fmode_for_setlk(file_lock);
if (error)
goto out;
/*
* If the cmd is requesting file-private locks, then set the
* FL_OFDLCK flag and override the owner.
*/
switch (cmd) {
case F_OFD_SETLK:
error = -EINVAL;
if (flock.l_pid != 0)
goto out;
cmd = F_SETLK;
file_lock->fl_flags |= FL_OFDLCK;
file_lock->fl_owner = filp;
break;
case F_OFD_SETLKW:
error = -EINVAL;
if (flock.l_pid != 0)
goto out;
cmd = F_SETLKW;
file_lock->fl_flags |= FL_OFDLCK;
file_lock->fl_owner = filp;
/* Fallthrough */
case F_SETLKW:
file_lock->fl_flags |= FL_SLEEP;
}
error = do_lock_file_wait(filp, cmd, file_lock);
/*
* Attempt to detect a close/fcntl race and recover by
* releasing the lock that was just acquired.
*/
if (!error && file_lock->fl_type != F_UNLCK) {
/*
* We need that spin_lock here - it prevents reordering between
* update of i_flctx->flc_posix and check for it done in
* close(). rcu_read_lock() wouldn't do.
*/
spin_lock(¤t->files->file_lock);
f = fcheck(fd);
spin_unlock(¤t->files->file_lock);
if (f != filp) {
file_lock->fl_type = F_UNLCK;
error = do_lock_file_wait(filp, cmd, file_lock);
WARN_ON_ONCE(error);
error = -EBADF;
}
}
out:
locks_free_lock(file_lock);
return error;
}
#if BITS_PER_LONG == 32
/* Report the first existing lock that would conflict with l.
* This implements the F_GETLK command of fcntl().
*/
int fcntl_getlk64(struct file *filp, unsigned int cmd, struct flock64 __user *l)
{
struct file_lock file_lock;
struct flock64 flock;
int error;
error = -EFAULT;
if (copy_from_user(&flock, l, sizeof(flock)))
goto out;
error = -EINVAL;
if ((flock.l_type != F_RDLCK) && (flock.l_type != F_WRLCK))
goto out;
error = flock64_to_posix_lock(filp, &file_lock, &flock);
if (error)
goto out;
if (cmd == F_OFD_GETLK) {
error = -EINVAL;
if (flock.l_pid != 0)
goto out;
cmd = F_GETLK64;
file_lock.fl_flags |= FL_OFDLCK;
file_lock.fl_owner = filp;
}
error = vfs_test_lock(filp, &file_lock);
if (error)
goto out;
flock.l_type = file_lock.fl_type;
if (file_lock.fl_type != F_UNLCK)
posix_lock_to_flock64(&flock, &file_lock);
error = -EFAULT;
if (!copy_to_user(l, &flock, sizeof(flock)))
error = 0;
locks_release_private(&file_lock);
out:
return error;
}
/* Apply the lock described by l to an open file descriptor.
* This implements both the F_SETLK and F_SETLKW commands of fcntl().
*/
int fcntl_setlk64(unsigned int fd, struct file *filp, unsigned int cmd,
struct flock64 __user *l)
{
struct file_lock *file_lock = locks_alloc_lock();
struct flock64 flock;
struct inode *inode;
struct file *f;
int error;
if (file_lock == NULL)
return -ENOLCK;
/*
* This might block, so we do it before checking the inode.
*/
error = -EFAULT;
if (copy_from_user(&flock, l, sizeof(flock)))
goto out;
inode = file_inode(filp);
/* Don't allow mandatory locks on files that may be memory mapped
* and shared.
*/
if (mandatory_lock(inode) && mapping_writably_mapped(filp->f_mapping)) {
error = -EAGAIN;
goto out;
}
error = flock64_to_posix_lock(filp, file_lock, &flock);
if (error)
goto out;
error = check_fmode_for_setlk(file_lock);
if (error)
goto out;
/*
* If the cmd is requesting file-private locks, then set the
* FL_OFDLCK flag and override the owner.
*/
switch (cmd) {
case F_OFD_SETLK:
error = -EINVAL;
if (flock.l_pid != 0)
goto out;
cmd = F_SETLK64;
file_lock->fl_flags |= FL_OFDLCK;
file_lock->fl_owner = filp;
break;
case F_OFD_SETLKW:
error = -EINVAL;
if (flock.l_pid != 0)
goto out;
cmd = F_SETLKW64;
file_lock->fl_flags |= FL_OFDLCK;
file_lock->fl_owner = filp;
/* Fallthrough */
case F_SETLKW64:
file_lock->fl_flags |= FL_SLEEP;
}
error = do_lock_file_wait(filp, cmd, file_lock);
/*
* Attempt to detect a close/fcntl race and recover by
* releasing the lock that was just acquired.
*/
if (!error && file_lock->fl_type != F_UNLCK) {
/*
* We need that spin_lock here - it prevents reordering between
* update of i_flctx->flc_posix and check for it done in
* close(). rcu_read_lock() wouldn't do.
*/
spin_lock(¤t->files->file_lock);
f = fcheck(fd);
spin_unlock(¤t->files->file_lock);
if (f != filp) {
file_lock->fl_type = F_UNLCK;
error = do_lock_file_wait(filp, cmd, file_lock);
WARN_ON_ONCE(error);
error = -EBADF;
}
}
out:
locks_free_lock(file_lock);
return error;
}
#endif /* BITS_PER_LONG == 32 */
/*
* This function is called when the file is being removed
* from the task's fd array. POSIX locks belonging to this task
* are deleted at this time.
*/
void locks_remove_posix(struct file *filp, fl_owner_t owner)
{
struct file_lock lock;
struct file_lock_context *ctx;
/*
* If there are no locks held on this file, we don't need to call
* posix_lock_file(). Another process could be setting a lock on this
* file at the same time, but we wouldn't remove that lock anyway.
*/
ctx = smp_load_acquire(&file_inode(filp)->i_flctx);
if (!ctx || list_empty(&ctx->flc_posix))
return;
lock.fl_type = F_UNLCK;
lock.fl_flags = FL_POSIX | FL_CLOSE;
lock.fl_start = 0;
lock.fl_end = OFFSET_MAX;
lock.fl_owner = owner;
lock.fl_pid = current->tgid;
lock.fl_file = filp;
lock.fl_ops = NULL;
lock.fl_lmops = NULL;
vfs_lock_file(filp, F_SETLK, &lock, NULL);
if (lock.fl_ops && lock.fl_ops->fl_release_private)
lock.fl_ops->fl_release_private(&lock);
}
EXPORT_SYMBOL(locks_remove_posix);
/* The i_flctx must be valid when calling into here */
static void
locks_remove_flock(struct file *filp, struct file_lock_context *flctx)
{
struct file_lock fl = {
.fl_owner = filp,
.fl_pid = current->tgid,
.fl_file = filp,
.fl_flags = FL_FLOCK,
.fl_type = F_UNLCK,
.fl_end = OFFSET_MAX,
};
struct inode *inode = file_inode(filp);
if (list_empty(&flctx->flc_flock))
return;
if (filp->f_op->flock)
filp->f_op->flock(filp, F_SETLKW, &fl);
else
flock_lock_inode(inode, &fl);
if (fl.fl_ops && fl.fl_ops->fl_release_private)
fl.fl_ops->fl_release_private(&fl);
}
/* The i_flctx must be valid when calling into here */
static void
locks_remove_lease(struct file *filp, struct file_lock_context *ctx)
{
struct file_lock *fl, *tmp;
LIST_HEAD(dispose);
if (list_empty(&ctx->flc_lease))
return;
spin_lock(&ctx->flc_lock);
list_for_each_entry_safe(fl, tmp, &ctx->flc_lease, fl_list)
if (filp == fl->fl_file)
lease_modify(fl, F_UNLCK, &dispose);
spin_unlock(&ctx->flc_lock);
locks_dispose_list(&dispose);
}
/*
* This function is called on the last close of an open file.
*/
void locks_remove_file(struct file *filp)
{
struct file_lock_context *ctx;
ctx = smp_load_acquire(&file_inode(filp)->i_flctx);
if (!ctx)
return;
/* remove any OFD locks */
locks_remove_posix(filp, filp);
/* remove flock locks */
locks_remove_flock(filp, ctx);
/* remove any leases */
locks_remove_lease(filp, ctx);
}
/**
* posix_unblock_lock - stop waiting for a file lock
* @waiter: the lock which was waiting
*
* lockd needs to block waiting for locks.
*/
int
posix_unblock_lock(struct file_lock *waiter)
{
int status = 0;
spin_lock(&blocked_lock_lock);
if (waiter->fl_next)
__locks_delete_block(waiter);
else
status = -ENOENT;
spin_unlock(&blocked_lock_lock);
return status;
}
EXPORT_SYMBOL(posix_unblock_lock);
/**
* vfs_cancel_lock - file byte range unblock lock
* @filp: The file to apply the unblock to
* @fl: The lock to be unblocked
*
* Used by lock managers to cancel blocked requests
*/
int vfs_cancel_lock(struct file *filp, struct file_lock *fl)
{
if (filp->f_op->lock)
return filp->f_op->lock(filp, F_CANCELLK, fl);
return 0;
}
EXPORT_SYMBOL_GPL(vfs_cancel_lock);
#ifdef CONFIG_PROC_FS
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
struct locks_iterator {
int li_cpu;
loff_t li_pos;
};
static void lock_get_status(struct seq_file *f, struct file_lock *fl,
loff_t id, char *pfx)
{
struct inode *inode = NULL;
unsigned int fl_pid;
if (fl->fl_nspid)
fl_pid = pid_vnr(fl->fl_nspid);
else
fl_pid = fl->fl_pid;
if (fl->fl_file != NULL)
inode = file_inode(fl->fl_file);
seq_printf(f, "%lld:%s ", id, pfx);
if (IS_POSIX(fl)) {
if (fl->fl_flags & FL_ACCESS)
seq_puts(f, "ACCESS");
else if (IS_OFDLCK(fl))
seq_puts(f, "OFDLCK");
else
seq_puts(f, "POSIX ");
seq_printf(f, " %s ",
(inode == NULL) ? "*NOINODE*" :
mandatory_lock(inode) ? "MANDATORY" : "ADVISORY ");
} else if (IS_FLOCK(fl)) {
if (fl->fl_type & LOCK_MAND) {
seq_puts(f, "FLOCK MSNFS ");
} else {
seq_puts(f, "FLOCK ADVISORY ");
}
} else if (IS_LEASE(fl)) {
if (fl->fl_flags & FL_DELEG)
seq_puts(f, "DELEG ");
else
seq_puts(f, "LEASE ");
if (lease_breaking(fl))
seq_puts(f, "BREAKING ");
else if (fl->fl_file)
seq_puts(f, "ACTIVE ");
else
seq_puts(f, "BREAKER ");
} else {
seq_puts(f, "UNKNOWN UNKNOWN ");
}
if (fl->fl_type & LOCK_MAND) {
seq_printf(f, "%s ",
(fl->fl_type & LOCK_READ)
? (fl->fl_type & LOCK_WRITE) ? "RW " : "READ "
: (fl->fl_type & LOCK_WRITE) ? "WRITE" : "NONE ");
} else {
seq_printf(f, "%s ",
(lease_breaking(fl))
? (fl->fl_type == F_UNLCK) ? "UNLCK" : "READ "
: (fl->fl_type == F_WRLCK) ? "WRITE" : "READ ");
}
if (inode) {
/* userspace relies on this representation of dev_t */
seq_printf(f, "%d %02x:%02x:%ld ", fl_pid,
MAJOR(inode->i_sb->s_dev),
MINOR(inode->i_sb->s_dev), inode->i_ino);
} else {
seq_printf(f, "%d <none>:0 ", fl_pid);
}
if (IS_POSIX(fl)) {
if (fl->fl_end == OFFSET_MAX)
seq_printf(f, "%Ld EOF\n", fl->fl_start);
else
seq_printf(f, "%Ld %Ld\n", fl->fl_start, fl->fl_end);
} else {
seq_puts(f, "0 EOF\n");
}
}
static int locks_show(struct seq_file *f, void *v)
{
struct locks_iterator *iter = f->private;
struct file_lock *fl, *bfl;
fl = hlist_entry(v, struct file_lock, fl_link);
lock_get_status(f, fl, iter->li_pos, "");
list_for_each_entry(bfl, &fl->fl_block, fl_block)
lock_get_status(f, bfl, iter->li_pos, " ->");
return 0;
}
static void __show_fd_locks(struct seq_file *f,
struct list_head *head, int *id,
struct file *filp, struct files_struct *files)
{
struct file_lock *fl;
list_for_each_entry(fl, head, fl_list) {
if (filp != fl->fl_file)
continue;
if (fl->fl_owner != files &&
fl->fl_owner != filp)
continue;
(*id)++;
seq_puts(f, "lock:\t");
lock_get_status(f, fl, *id, "");
}
}
void show_fd_locks(struct seq_file *f,
struct file *filp, struct files_struct *files)
{
struct inode *inode = file_inode(filp);
struct file_lock_context *ctx;
int id = 0;
ctx = smp_load_acquire(&inode->i_flctx);
if (!ctx)
return;
spin_lock(&ctx->flc_lock);
__show_fd_locks(f, &ctx->flc_flock, &id, filp, files);
__show_fd_locks(f, &ctx->flc_posix, &id, filp, files);
__show_fd_locks(f, &ctx->flc_lease, &id, filp, files);
spin_unlock(&ctx->flc_lock);
}
static void *locks_start(struct seq_file *f, loff_t *pos)
__acquires(&blocked_lock_lock)
{
struct locks_iterator *iter = f->private;
iter->li_pos = *pos + 1;
lg_global_lock(&file_lock_lglock);
spin_lock(&blocked_lock_lock);
return seq_hlist_start_percpu(&file_lock_list, &iter->li_cpu, *pos);
}
static void *locks_next(struct seq_file *f, void *v, loff_t *pos)
{
struct locks_iterator *iter = f->private;
++iter->li_pos;
return seq_hlist_next_percpu(v, &file_lock_list, &iter->li_cpu, pos);
}
static void locks_stop(struct seq_file *f, void *v)
__releases(&blocked_lock_lock)
{
spin_unlock(&blocked_lock_lock);
lg_global_unlock(&file_lock_lglock);
}
static const struct seq_operations locks_seq_operations = {
.start = locks_start,
.next = locks_next,
.stop = locks_stop,
.show = locks_show,
};
static int locks_open(struct inode *inode, struct file *filp)
{
return seq_open_private(filp, &locks_seq_operations,
sizeof(struct locks_iterator));
}
static const struct file_operations proc_locks_operations = {
.open = locks_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release_private,
};
static int __init proc_locks_init(void)
{
proc_create("locks", 0, NULL, &proc_locks_operations);
return 0;
}
module_init(proc_locks_init);
#endif
static int __init filelock_init(void)
{
int i;
flctx_cache = kmem_cache_create("file_lock_ctx",
sizeof(struct file_lock_context), 0, SLAB_PANIC, NULL);
filelock_cache = kmem_cache_create("file_lock_cache",
sizeof(struct file_lock), 0, SLAB_PANIC, NULL);
lg_lock_init(&file_lock_lglock, "file_lock_lglock");
for_each_possible_cpu(i)
INIT_HLIST_HEAD(per_cpu_ptr(&file_lock_list, i));
return 0;
}
core_initcall(filelock_init);
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.