text
stringlengths 2
100k
| meta
dict |
---|---|
# What is ci_edit
ci_edit is a text editor. It can help you view or edit text files.
ci_edit runs in the command line (also called the terminal). To start using
ci_edit, download ci_edit and open (execute) `ci.py`.
## What ci_edit can do for you
Many other command line text editors require learning a different set of mouse
and keyboard commands. Many of us use a graphical editor (GUI) that supports
a common set of commands like `ctrl+q` to quit (that is, hold the control key and
press Q). Here are a few common commands:
- ctrl+q to quit the program
- ctrl+s to save the file
- ctrl+z undo
- ctrl+x cut
- ctrl+c copy
- ctrl+v paste
There are more, but you probably get the idea. These common controls are not
common in command line editors.
So, what if you'd like to edit a file in the terminal window but don't want to
recall how to save or quit in an unfamiliar editor? This is where ci_edit
shines, because ci_edit does support those familiar key sequences. You already
know how to save in ci_edit, it's `ctrl+s`. Simple.
This version of ci_edit still doesn't have all the intended features, but it's
a start. It's has the necessary features of a basic text editor and a few fancy
extras. Those fancy extras stay out of your way until you want them.
## How to stay in touch
To get news about new features, please join
- [ci_edit-announce](https://groups.google.com/forum/#!forum/ci_edit-announce)
If you have a question (i.e. "how do I..."), please post it here
- [ci_edit-users](https://groups.google.com/forum/#!forum/ci_edit-users)
Have you found a case where ci_edit misbehaves, please let us know by describing
what happened here
- [Report bug in ci_edit](https://github.com/google/ci_edit/issues/new)
For those interested in contributing new features or steering the future
direction of ci_edit, join us on
- [ci_edit-dev](https://groups.google.com/forum/#!forum/ci_edit-dev)
### Installation (Linux / Mac OS)
* Execute the install script with root privileges. Either change directory
`cd` to the downloaded directory (or local repository): `ci_edit`, or use
the path to the installation file (i.e. `./[PATH_TO_FILE]/install.sh`).
```
$ sudo ./install.sh
```
* **Note:** This script creates a copy of the repository in the directory
`/opt/ci_edit/`; the **update**, overwrites that copy. Then a symbolic
link is created in the directory `/usr/local/bin/`, which is generally
designated for user programs not managed by the distribution package manager
### Usage
* This command opens the text editor from any directory. The execution command
for the editor can be specified by user choice during installation or
manually.
```
$ we
```
* To edit a file (such as `README.md`) by name:
```
$ we README.md
```
## What you can do for ci_edit
The help we now need is finding out what puts users off; what causes someone who
tries the editor to stop using it. We intend to address those issues so that
more users are happy users for a longer time.
# Features of ci_edit
## Stand out features
- nested grammars
- A source file being edited may start in one grammar such as HTML and
contain nested JavaScript or CSS. ci_edit will highlight each grammar for
each separate language.
- terminal mouse support and GUI shortcuts by default (enabled out-of-the-box).
- open the file you meant
- If a given path doesn't exist, ci_edit will try to estimate "what you
meant". This allows for opening a file path by copy/pasting output from
other tools without needing to touch up the path.
- This is disabled by passing a line number parameter, such as +1 (which
opens the file to the first line).
- A path such as `a/foo/bar.cc` can open `foo/bar.cc`.
- Why: `git diff` may add `a/` or `b/` prefixes to files in diff output.
- A path such as `foo/bar.cc:421` can open `foo/bar.cc` to line number 421
- Why: some compiler or log output us a <file>:<line number> notation to
refer to specific lines.
## Uncommon features
Some other editors provide these features, but not all of them.
- file path tab-completion
- i.e. when opening files
- written in Python
- No Python experience is required. Being written in Python means that many
users will be able to review the code.
- Python 3.7+ and Python 2.7+ are supported.
- Python 2 support may be phased out in favor of focusing on Python 3
features. If you'd prefer that Python 2 support continue, please comment on
https://github.com/google/ci_edit/issues/205
- saved undo/redo
- Open a file and undo prior edits of that document
- runs on nCurses
- This means that it can use used in the terminal window just like vim,
emacs, and pine.
- sensible save and quit
- Using GUI editor keyboard short-cuts: `ctrl+s` and `ctrl+q` respectively.
## Common features
We should expect these features from a text editor.
- cut/copy/paste
- Using common GUI editor keyboard short-cuts: `ctrl+x`, `ctrl+c`, and
`ctrl+v`!
- syntax highlighting
- keywords an such are displayed in different colors.
- find within text
- Regular expression search forward and backward.
- line numbers
- Shown on the left side.
- go to line with `ctrl+g`
- Jump to a line number or the top, bottom, or middle of the document
- unlimited undo/redo
- Or at least within the limits of disk space to page to
- selection modes
- select by line, word, character, select all, or rectangle (block) selection
- brace matching
- Place the cursor on a brace, bracket, or parenthesis and the pair of
characters are highlighted.
- mouse support
- Yes, in the terminal
- click to place the cursor
- double click to select by word
- triple click to select by line
- shift+click to extend selection
- alt+click for rectangular (block) selection
- pipe to editor
- Send the output from another program directly into the editor without the
need for a temporary file
- strips/trims trailing white-space on each line
- Each time the file is saved
- resume at last edit position
- The cursor location is stored within `~/.ci_edit/`
- search and replace
- Control the scope of the replacement with the current selection
- execute sub-processes
- Either with or without a sub-shell; including piping between to, from, and
between sub-processes
- filter text through other tools
- Send selected text through a sub-process and capture the output into the
current document.
- spell check
- ultra-fast spell checking. English and coding word dictionaries included.
- built-in filters
- Sort selected lines
- regex text substitution, such as s/dogs/cats/ replaces the text "dogs" with
the text "cats".
## Future features (the to do list)
- bookmarks
- find in files
- Not just the current file, but search through files in a directory.
- user customizable keywords
- user customizable color scheme
- build/error tracking
- Capture the output from make and similar tools and integrate the results.
- auto reload of modified files
- Tell you when a file has changed on disk and offer to re-open it.
- trace file
- Monitor a file and continuously read in the new lines
- jump to opposing brace
- Move the cursor from here to there.
- a lot more...
- There are so many dreams for the future.
# Obligatory
## Origins
The world does need another text editor. (Or at least I think so).
There are other fine curses based editors. I found that I was often trying to
tweak them to get just what I wanted. Almost as often, some aspect of those
editors prevented that last little bit of customization. So writing a text
editor should allow all the customization I like, right?
Writing a text editor is an interesting project. Give it a try sometime.
## Note
This is not an official Google product.
Copyright 2016 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the [License](LICENSE) for the specific language governing permissions and
limitations under the License.
| {
"pile_set_name": "Github"
} |
// Copyright 2017 The Draco 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.
//
#include "draco/attributes/attribute_octahedron_transform.h"
#include "draco/attributes/attribute_transform_type.h"
#include "draco/compression/attributes/normal_compression_utils.h"
namespace draco {
bool AttributeOctahedronTransform::InitFromAttribute(
const PointAttribute &attribute) {
const AttributeTransformData *const transform_data =
attribute.GetAttributeTransformData();
if (!transform_data ||
transform_data->transform_type() != ATTRIBUTE_OCTAHEDRON_TRANSFORM)
return false; // Wrong transform type.
quantization_bits_ = transform_data->GetParameterValue<int32_t>(0);
return true;
}
void AttributeOctahedronTransform::CopyToAttributeTransformData(
AttributeTransformData *out_data) const {
out_data->set_transform_type(ATTRIBUTE_OCTAHEDRON_TRANSFORM);
out_data->AppendParameterValue(quantization_bits_);
}
void AttributeOctahedronTransform::SetParameters(int quantization_bits) {
quantization_bits_ = quantization_bits;
}
bool AttributeOctahedronTransform::EncodeParameters(
EncoderBuffer *encoder_buffer) const {
if (is_initialized()) {
encoder_buffer->Encode(static_cast<uint8_t>(quantization_bits_));
return true;
}
return false;
}
std::unique_ptr<PointAttribute>
AttributeOctahedronTransform::GeneratePortableAttribute(
const PointAttribute &attribute, const std::vector<PointIndex> &point_ids,
int num_points) const {
DRACO_DCHECK(is_initialized());
// Allocate portable attribute.
const int num_entries = static_cast<int>(point_ids.size());
std::unique_ptr<PointAttribute> portable_attribute =
InitPortableAttribute(num_entries, 2, num_points, attribute, true);
// Quantize all values in the order given by point_ids into portable
// attribute.
int32_t *const portable_attribute_data = reinterpret_cast<int32_t *>(
portable_attribute->GetAddress(AttributeValueIndex(0)));
float att_val[3];
int32_t dst_index = 0;
OctahedronToolBox converter;
if (!converter.SetQuantizationBits(quantization_bits_))
return nullptr;
for (uint32_t i = 0; i < point_ids.size(); ++i) {
const AttributeValueIndex att_val_id = attribute.mapped_index(point_ids[i]);
attribute.GetValue(att_val_id, att_val);
// Encode the vector into a s and t octahedral coordinates.
int32_t s, t;
converter.FloatVectorToQuantizedOctahedralCoords(att_val, &s, &t);
portable_attribute_data[dst_index++] = s;
portable_attribute_data[dst_index++] = t;
}
return portable_attribute;
}
} // namespace draco
| {
"pile_set_name": "Github"
} |
/// @ref gtx_color_space
/// @file glm/gtx/color_space.hpp
///
/// @see core (dependence)
///
/// @defgroup gtx_color_space GLM_GTX_color_space
/// @ingroup gtx
///
/// @brief Related to RGB to HSV conversions and operations.
///
/// <glm/gtx/color_space.hpp> need to be included to use these functionalities.
#pragma once
// Dependency:
#include "../glm.hpp"
#ifndef GLM_ENABLE_EXPERIMENTAL
# error "GLM: GLM_GTX_color_space is an experimental extension and may change in the future. Use #define GLM_ENABLE_EXPERIMENTAL before including it, if you really want to use it."
#endif
#if GLM_MESSAGES == GLM_MESSAGES_ENABLED && !defined(GLM_EXT_INCLUDED)
# pragma message("GLM: GLM_GTX_color_space extension included")
#endif
namespace glm
{
/// @addtogroup gtx_color_space
/// @{
/// Converts a color from HSV color space to its color in RGB color space.
/// @see gtx_color_space
template<typename T, precision P>
GLM_FUNC_DECL vec<3, T, P> rgbColor(
vec<3, T, P> const & hsvValue);
/// Converts a color from RGB color space to its color in HSV color space.
/// @see gtx_color_space
template<typename T, precision P>
GLM_FUNC_DECL vec<3, T, P> hsvColor(
vec<3, T, P> const & rgbValue);
/// Build a saturation matrix.
/// @see gtx_color_space
template<typename T>
GLM_FUNC_DECL mat<4, 4, T, defaultp> saturation(
T const s);
/// Modify the saturation of a color.
/// @see gtx_color_space
template<typename T, precision P>
GLM_FUNC_DECL vec<3, T, P> saturation(
T const s,
vec<3, T, P> const & color);
/// Modify the saturation of a color.
/// @see gtx_color_space
template<typename T, precision P>
GLM_FUNC_DECL vec<4, T, P> saturation(
T const s,
vec<4, T, P> const & color);
/// Compute color luminosity associating ratios (0.33, 0.59, 0.11) to RGB canals.
/// @see gtx_color_space
template<typename T, precision P>
GLM_FUNC_DECL T luminosity(
vec<3, T, P> const & color);
/// @}
}//namespace glm
#include "color_space.inl"
| {
"pile_set_name": "Github"
} |
ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES
FRAMEWORK_SEARCH_PATHS = $(inherited) "${PODS_CONFIGURATION_BUILD_DIR}/NXDrawKit" "${PODS_CONFIGURATION_BUILD_DIR}/RSKImageCropper"
GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1
LD_RUNPATH_SEARCH_PATHS = $(inherited) '@executable_path/Frameworks' '@loader_path/Frameworks'
OTHER_CFLAGS = $(inherited) -iquote "${PODS_CONFIGURATION_BUILD_DIR}/NXDrawKit/NXDrawKit.framework/Headers" -iquote "${PODS_CONFIGURATION_BUILD_DIR}/RSKImageCropper/RSKImageCropper.framework/Headers"
OTHER_LDFLAGS = $(inherited) -framework "NXDrawKit" -framework "RSKImageCropper"
OTHER_SWIFT_FLAGS = $(inherited) "-D" "COCOAPODS"
PODS_BUILD_DIR = ${BUILD_DIR}
PODS_CONFIGURATION_BUILD_DIR = ${PODS_BUILD_DIR}/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)
PODS_PODFILE_DIR_PATH = ${SRCROOT}/.
PODS_ROOT = ${SRCROOT}/Pods
| {
"pile_set_name": "Github"
} |
/**
* Copyright (c) 2006-2015, JGraph Ltd
* Copyright (c) 2006-2015, Gaudenz Alder
*/
/**
* Class: mxStylesheet
*
* Defines the appearance of the cells in a graph. See <putCellStyle> for an
* example of creating a new cell style. It is recommended to use objects, not
* arrays for holding cell styles. Existing styles can be cloned using
* <mxUtils.clone> and turned into a string for debugging using
* <mxUtils.toString>.
*
* Default Styles:
*
* The stylesheet contains two built-in styles, which are used if no style is
* defined for a cell:
*
* defaultVertex - Default style for vertices
* defaultEdge - Default style for edges
*
* Example:
*
* (code)
* var vertexStyle = stylesheet.getDefaultVertexStyle();
* vertexStyle[mxConstants.STYLE_ROUNDED] = true;
* var edgeStyle = stylesheet.getDefaultEdgeStyle();
* edgeStyle[mxConstants.STYLE_EDGE] = mxEdgeStyle.EntityRelation;
* (end)
*
* Modifies the built-in default styles.
*
* To avoid the default style for a cell, add a leading semicolon
* to the style definition, eg.
*
* (code)
* ;shadow=1
* (end)
*
* Removing keys:
*
* For removing a key in a cell style of the form [stylename;|key=value;] the
* special value none can be used, eg. highlight;fillColor=none
*
* See also the helper methods in mxUtils to modify strings of this format,
* namely <mxUtils.setStyle>, <mxUtils.indexOfStylename>,
* <mxUtils.addStylename>, <mxUtils.removeStylename>,
* <mxUtils.removeAllStylenames> and <mxUtils.setStyleFlag>.
*
* Constructor: mxStylesheet
*
* Constructs a new stylesheet and assigns default styles.
*/
function mxStylesheet()
{
this.styles = new Object();
this.putDefaultVertexStyle(this.createDefaultVertexStyle());
this.putDefaultEdgeStyle(this.createDefaultEdgeStyle());
};
/**
* Function: styles
*
* Maps from names to cell styles. Each cell style is a map of key,
* value pairs.
*/
mxStylesheet.prototype.styles;
/**
* Function: createDefaultVertexStyle
*
* Creates and returns the default vertex style.
*/
mxStylesheet.prototype.createDefaultVertexStyle = function()
{
var style = new Object();
style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_RECTANGLE;
style[mxConstants.STYLE_PERIMETER] = mxPerimeter.RectanglePerimeter;
style[mxConstants.STYLE_VERTICAL_ALIGN] = mxConstants.ALIGN_MIDDLE;
style[mxConstants.STYLE_ALIGN] = mxConstants.ALIGN_CENTER;
style[mxConstants.STYLE_FILLCOLOR] = '#C3D9FF';
style[mxConstants.STYLE_STROKECOLOR] = '#6482B9';
style[mxConstants.STYLE_FONTCOLOR] = '#774400';
return style;
};
/**
* Function: createDefaultEdgeStyle
*
* Creates and returns the default edge style.
*/
mxStylesheet.prototype.createDefaultEdgeStyle = function()
{
var style = new Object();
style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_CONNECTOR;
style[mxConstants.STYLE_ENDARROW] = mxConstants.ARROW_CLASSIC;
style[mxConstants.STYLE_VERTICAL_ALIGN] = mxConstants.ALIGN_MIDDLE;
style[mxConstants.STYLE_ALIGN] = mxConstants.ALIGN_CENTER;
style[mxConstants.STYLE_STROKECOLOR] = '#6482B9';
style[mxConstants.STYLE_FONTCOLOR] = '#446299';
return style;
};
/**
* Function: putDefaultVertexStyle
*
* Sets the default style for vertices using defaultVertex as the
* stylename.
*
* Parameters:
* style - Key, value pairs that define the style.
*/
mxStylesheet.prototype.putDefaultVertexStyle = function(style)
{
this.putCellStyle('defaultVertex', style);
};
/**
* Function: putDefaultEdgeStyle
*
* Sets the default style for edges using defaultEdge as the stylename.
*/
mxStylesheet.prototype.putDefaultEdgeStyle = function(style)
{
this.putCellStyle('defaultEdge', style);
};
/**
* Function: getDefaultVertexStyle
*
* Returns the default style for vertices.
*/
mxStylesheet.prototype.getDefaultVertexStyle = function()
{
return this.styles['defaultVertex'];
};
/**
* Function: getDefaultEdgeStyle
*
* Sets the default style for edges.
*/
mxStylesheet.prototype.getDefaultEdgeStyle = function()
{
return this.styles['defaultEdge'];
};
/**
* Function: putCellStyle
*
* Stores the given map of key, value pairs under the given name in
* <styles>.
*
* Example:
*
* The following example adds a new style called 'rounded' into an
* existing stylesheet:
*
* (code)
* var style = new Object();
* style[mxConstants.STYLE_SHAPE] = mxConstants.SHAPE_RECTANGLE;
* style[mxConstants.STYLE_PERIMETER] = mxPerimeter.RectanglePerimeter;
* style[mxConstants.STYLE_ROUNDED] = true;
* graph.getStylesheet().putCellStyle('rounded', style);
* (end)
*
* In the above example, the new style is an object. The possible keys of
* the object are all the constants in <mxConstants> that start with STYLE
* and the values are either JavaScript objects, such as
* <mxPerimeter.RightAngleRectanglePerimeter> (which is in fact a function)
* or expressions, such as true. Note that not all keys will be
* interpreted by all shapes (eg. the line shape ignores the fill color).
* The final call to this method associates the style with a name in the
* stylesheet. The style is used in a cell with the following code:
*
* (code)
* model.setStyle(cell, 'rounded');
* (end)
*
* Parameters:
*
* name - Name for the style to be stored.
* style - Key, value pairs that define the style.
*/
mxStylesheet.prototype.putCellStyle = function(name, style)
{
this.styles[name] = style;
};
/**
* Function: getCellStyle
*
* Returns the cell style for the specified stylename or the given
* defaultStyle if no style can be found for the given stylename.
*
* Parameters:
*
* name - String of the form [(stylename|key=value);] that represents the
* style.
* defaultStyle - Default style to be returned if no style can be found.
*/
mxStylesheet.prototype.getCellStyle = function(name, defaultStyle)
{
var style = defaultStyle;
if (name != null && name.length > 0)
{
var pairs = name.split(';');
if (style != null &&
name.charAt(0) != ';')
{
style = mxUtils.clone(style);
}
else
{
style = new Object();
}
// Parses each key, value pair into the existing style
for (var i = 0; i < pairs.length; i++)
{
var tmp = pairs[i];
var pos = tmp.indexOf('=');
if (pos >= 0)
{
var key = tmp.substring(0, pos);
var value = tmp.substring(pos + 1);
if (value == mxConstants.NONE)
{
delete style[key];
}
else if (mxUtils.isNumeric(value))
{
style[key] = parseFloat(value);
}
else
{
style[key] = value;
}
}
else
{
// Merges the entries from a named style
var tmpStyle = this.styles[tmp];
if (tmpStyle != null)
{
for (var key in tmpStyle)
{
style[key] = tmpStyle[key];
}
}
}
}
}
return style;
};
| {
"pile_set_name": "Github"
} |
p( {
"nodes": [
{
"level": 0,
"id": "0",
"label": "0"
},
{
"level": 1,
"id": "1",
"label": "1"
},
{
"level": 2,
"id": "2",
"label": "2"
},
{
"level": 3,
"id": "3",
"label": "3"
},
{
"level": 4,
"id": "4",
"label": "4"
},
{
"level": 5,
"id": "5",
"label": "5"
},
{
"level": 6,
"id": "6",
"label": "6"
},
{
"level": 7,
"id": "7",
"label": "7"
},
{
"level": 8,
"id": "8",
"label": "8"
},
{
"level": 0,
"id": "9",
"label": "9"
},
{
"level": 9,
"id": "10",
"label": "10"
},
{
"level": 10,
"id": "11",
"label": "11"
},
{
"level": 11,
"id": "12",
"label": "12"
},
{
"level": 12,
"id": "13",
"label": "13"
},
{
"level": 13,
"id": "14",
"label": "14"
},
{
"level": 13,
"id": "15",
"label": "15"
},
{
"level": 14,
"id": "16",
"label": "16"
},
{
"level": 15,
"id": "17",
"label": "17"
},
{
"level": 16,
"id": "18",
"label": "18"
},
{
"level": 17,
"id": "19",
"label": "19"
},
{
"level": 18,
"id": "20",
"label": "20"
},
{
"level": 19,
"id": "21",
"label": "21"
},
{
"level": 20,
"id": "22",
"label": "22"
},
{
"level": 21,
"id": "23",
"label": "23"
},
{
"level": 22,
"id": "24",
"label": "24"
},
{
"level": 23,
"id": "25",
"label": "25"
},
{
"level": 24,
"id": "26",
"label": "26"
},
{
"level": 25,
"id": "27",
"label": "27"
},
{
"level": 26,
"id": "28",
"label": "28"
},
{
"level": 27,
"id": "29",
"label": "29"
},
{
"level": 28,
"id": "30",
"label": "30"
},
{
"level": 29,
"id": "31",
"label": "31"
},
{
"level": 30,
"id": "32",
"label": "32"
},
{
"level": 31,
"id": "33",
"label": "33"
},
{
"level": 32,
"id": "34",
"label": "34"
},
{
"level": 32,
"id": "35",
"label": "35"
},
{
"level": 33,
"id": "36",
"label": "36"
},
{
"level": 32,
"id": "37",
"label": "37"
},
{
"level": 34,
"id": "38",
"label": "38"
},
{
"level": 35,
"id": "39",
"label": "39"
},
{
"level": 36,
"id": "40",
"label": "40"
},
{
"level": 37,
"id": "41",
"label": "41"
},
{
"level": 38,
"id": "42",
"label": "42"
},
{
"level": 33,
"id": "43",
"label": "43"
},
{
"level": 39,
"id": "44",
"label": "44"
},
{
"level": 40,
"id": "45",
"label": "45"
},
{
"level": 41,
"id": "46",
"label": "46"
},
{
"level": 42,
"id": "47",
"label": "47"
},
{
"level": 43,
"id": "48",
"label": "48"
},
{
"level": 44,
"id": "49",
"label": "49"
},
{
"level": 45,
"id": "50",
"label": "50"
},
{
"level": 46,
"id": "51",
"label": "51"
},
{
"level": 47,
"id": "52",
"label": "52"
},
{
"level": 48,
"id": "53",
"label": "53"
},
{
"level": 49,
"id": "54",
"label": "54"
},
{
"level": 50,
"id": "55",
"label": "55"
},
{
"level": 51,
"id": "56",
"label": "56"
},
{
"level": 52,
"id": "57",
"label": "57"
},
{
"level": 53,
"id": "58",
"label": "58"
},
{
"level": 54,
"id": "59",
"label": "59"
},
{
"level": 55,
"id": "60",
"label": "60"
},
{
"level": 56,
"id": "61",
"label": "61"
},
{
"level": 57,
"id": "62",
"label": "62"
},
{
"level": 58,
"id": "63",
"label": "63"
},
{
"level": 59,
"id": "64",
"label": "64"
},
{
"level": 55,
"id": "65",
"label": "65"
},
{
"level": 60,
"id": "66",
"label": "66"
},
{
"level": 61,
"id": "67",
"label": "67"
},
{
"level": 62,
"id": "68",
"label": "68"
},
{
"level": 63,
"id": "69",
"label": "69"
},
{
"level": 64,
"id": "70",
"label": "70"
},
{
"level": 65,
"id": "71",
"label": "71"
},
{
"level": 66,
"id": "72",
"label": "72"
},
{
"level": 67,
"id": "73",
"label": "73"
},
{
"level": 68,
"id": "74",
"label": "74"
},
{
"level": 69,
"id": "75",
"label": "75"
},
{
"level": 70,
"id": "76",
"label": "76"
},
{
"level": 71,
"id": "77",
"label": "77"
},
{
"level": 72,
"id": "78",
"label": "78"
},
{
"level": 73,
"id": "79",
"label": "79"
},
{
"level": 74,
"id": "80",
"label": "80"
},
{
"level": 75,
"id": "81",
"label": "81"
},
{
"level": 76,
"id": "82",
"label": "82"
},
{
"level": 77,
"id": "83",
"label": "83"
},
{
"level": 78,
"id": "84",
"label": "84"
},
{
"level": 79,
"id": "85",
"label": "85"
},
{
"level": 80,
"id": "86",
"label": "86"
},
{
"level": 81,
"id": "87",
"label": "87"
},
{
"level": 82,
"id": "88",
"label": "88"
},
{
"level": 83,
"id": "89",
"label": "89"
},
{
"level": 84,
"id": "90",
"label": "90"
},
{
"level": 80,
"id": "91",
"label": "91"
},
{
"level": 85,
"id": "92",
"label": "92"
},
{
"level": 86,
"id": "93",
"label": "93"
},
{
"level": 87,
"id": "94",
"label": "94"
},
{
"level": 88,
"id": "95",
"label": "95"
},
{
"level": 89,
"id": "96",
"label": "96"
},
{
"level": 90,
"id": "97",
"label": "97"
},
{
"level": 91,
"id": "98",
"label": "98"
},
{
"level": 92,
"id": "99",
"label": "99"
},
{
"level": 93,
"id": "100",
"label": "100"
},
{
"level": 94,
"id": "101",
"label": "101"
},
{
"level": 95,
"id": "102",
"label": "102"
},
{
"level": 96,
"id": "103",
"label": "103"
},
{
"level": 97,
"id": "104",
"label": "104"
},
{
"level": 98,
"id": "105",
"label": "105"
},
{
"level": 99,
"id": "106",
"label": "106"
},
{
"level": 100,
"id": "107",
"label": "107"
},
{
"level": 101,
"id": "108",
"label": "108"
},
{
"level": 102,
"id": "109",
"label": "109"
},
{
"level": 103,
"id": "110",
"label": "110"
},
{
"level": 104,
"id": "111",
"label": "111"
},
{
"level": 105,
"id": "112",
"label": "112"
},
{
"level": 106,
"id": "113",
"label": "113"
},
{
"level": 107,
"id": "114",
"label": "114"
},
{
"level": 108,
"id": "115",
"label": "115"
},
{
"level": 109,
"id": "116",
"label": "116"
},
{
"level": 110,
"id": "117",
"label": "117"
},
{
"level": 111,
"id": "118",
"label": "118"
},
{
"level": 112,
"id": "119",
"label": "119"
},
{
"level": 113,
"id": "120",
"label": "120"
},
{
"level": 114,
"id": "121",
"label": "121"
},
{
"level": 115,
"id": "122",
"label": "122"
},
{
"level": 116,
"id": "123",
"label": "123"
},
{
"level": 117,
"id": "124",
"label": "124"
},
{
"level": 118,
"id": "125",
"label": "125"
},
{
"level": 119,
"id": "126",
"label": "126"
},
{
"level": 120,
"id": "127",
"label": "127"
},
{
"level": 121,
"id": "128",
"label": "128"
},
{
"level": 122,
"id": "129",
"label": "129"
},
{
"level": 123,
"id": "130",
"label": "130"
},
{
"level": 124,
"id": "131",
"label": "131"
},
{
"level": 125,
"id": "132",
"label": "132"
},
{
"level": 126,
"id": "133",
"label": "133"
},
{
"level": 126,
"id": "134",
"label": "134"
},
{
"level": 127,
"id": "135",
"label": "135"
},
{
"level": 128,
"id": "136",
"label": "136"
},
{
"level": 129,
"id": "137",
"label": "137"
},
{
"level": 130,
"id": "138",
"label": "138"
},
{
"level": 131,
"id": "139",
"label": "139"
},
{
"level": 131,
"id": "140",
"label": "140"
},
{
"level": 132,
"id": "141",
"label": "141"
},
{
"level": 133,
"id": "142",
"label": "142"
},
{
"level": 134,
"id": "143",
"label": "143"
},
{
"level": 135,
"id": "144",
"label": "144"
},
{
"level": 136,
"id": "145",
"label": "145"
},
{
"level": 137,
"id": "146",
"label": "146"
},
{
"level": 138,
"id": "147",
"label": "147"
},
{
"level": 139,
"id": "148",
"label": "148"
},
{
"level": 140,
"id": "149",
"label": "149"
},
{
"level": 141,
"id": "150",
"label": "150"
},
{
"level": 142,
"id": "151",
"label": "151"
},
{
"level": 143,
"id": "152",
"label": "152"
},
{
"level": 144,
"id": "153",
"label": "153"
},
{
"level": 145,
"id": "154",
"label": "154"
},
{
"level": 146,
"id": "155",
"label": "155"
},
{
"level": 147,
"id": "156",
"label": "156"
},
{
"level": 147,
"id": "157",
"label": "157"
},
{
"level": 148,
"id": "158",
"label": "158"
},
{
"level": 149,
"id": "159",
"label": "159"
},
{
"level": 150,
"id": "160",
"label": "160"
},
{
"level": 151,
"id": "161",
"label": "161"
},
{
"level": 150,
"id": "162",
"label": "162"
},
{
"level": 152,
"id": "163",
"label": "163"
},
{
"level": 151,
"id": "164",
"label": "164"
},
{
"level": 153,
"id": "165",
"label": "165"
},
{
"level": 154,
"id": "166",
"label": "166"
},
{
"level": 155,
"id": "167",
"label": "167"
},
{
"level": 156,
"id": "168",
"label": "168"
},
{
"level": 157,
"id": "169",
"label": "169"
},
{
"level": 157,
"id": "170",
"label": "170"
},
{
"level": 158,
"id": "171",
"label": "171"
},
{
"level": 159,
"id": "172",
"label": "172"
},
{
"level": 160,
"id": "173",
"label": "173"
},
{
"level": 161,
"id": "174",
"label": "174"
},
{
"level": 162,
"id": "175",
"label": "175"
},
{
"level": 163,
"id": "176",
"label": "176"
},
{
"level": 164,
"id": "177",
"label": "177"
},
{
"level": 165,
"id": "178",
"label": "178"
},
{
"level": 166,
"id": "179",
"label": "179"
},
{
"level": 166,
"id": "180",
"label": "180"
},
{
"level": 167,
"id": "181",
"label": "181"
},
{
"level": 168,
"id": "182",
"label": "182"
},
{
"level": 168,
"id": "183",
"label": "183"
},
{
"level": 169,
"id": "184",
"label": "184"
},
{
"level": 170,
"id": "185",
"label": "185"
},
{
"level": 170,
"id": "186",
"label": "186"
},
{
"level": 171,
"id": "187",
"label": "187"
},
{
"level": 172,
"id": "188",
"label": "188"
},
{
"level": 172,
"id": "189",
"label": "189"
},
{
"level": 173,
"id": "190",
"label": "190"
},
{
"level": 174,
"id": "191",
"label": "191"
},
{
"level": 175,
"id": "192",
"label": "192"
},
{
"level": 176,
"id": "193",
"label": "193"
},
{
"level": 177,
"id": "194",
"label": "194"
},
{
"level": 178,
"id": "195",
"label": "195"
},
{
"level": 179,
"id": "196",
"label": "196"
},
{
"level": 179,
"id": "197",
"label": "197"
},
{
"level": 180,
"id": "198",
"label": "198"
},
{
"level": 181,
"id": "199",
"label": "199"
},
{
"level": 182,
"id": "200",
"label": "200"
},
{
"level": 183,
"id": "201",
"label": "201"
},
{
"level": 184,
"id": "202",
"label": "202"
},
{
"level": 185,
"id": "203",
"label": "203"
},
{
"level": 186,
"id": "204",
"label": "204"
},
{
"level": 187,
"id": "205",
"label": "205"
},
{
"level": 188,
"id": "206",
"label": "206"
},
{
"level": 189,
"id": "207",
"label": "207"
},
{
"level": 190,
"id": "208",
"label": "208"
},
{
"level": 191,
"id": "209",
"label": "209"
},
{
"level": 192,
"id": "210",
"label": "210"
},
{
"level": 193,
"id": "211",
"label": "211"
},
{
"level": 194,
"id": "212",
"label": "212"
},
{
"level": 195,
"id": "213",
"label": "213"
},
{
"level": 196,
"id": "214",
"label": "214"
},
{
"level": 197,
"id": "215",
"label": "215"
},
{
"level": 198,
"id": "216",
"label": "216"
},
{
"level": 199,
"id": "217",
"label": "217"
},
{
"level": 200,
"id": "218",
"label": "218"
},
{
"level": 201,
"id": "219",
"label": "219"
},
{
"level": 202,
"id": "220",
"label": "220"
},
{
"level": 203,
"id": "221",
"label": "221"
},
{
"level": 204,
"id": "222",
"label": "222"
},
{
"level": 205,
"id": "223",
"label": "223"
},
{
"level": 206,
"id": "224",
"label": "224"
},
{
"level": 207,
"id": "225",
"label": "225"
},
{
"level": 208,
"id": "226",
"label": "226"
},
{
"level": 209,
"id": "227",
"label": "227"
},
{
"level": 210,
"id": "228",
"label": "228"
},
{
"level": 211,
"id": "229",
"label": "229"
},
{
"level": 212,
"id": "230",
"label": "230"
},
{
"level": 213,
"id": "231",
"label": "231"
},
{
"level": 214,
"id": "232",
"label": "232"
},
{
"level": 215,
"id": "233",
"label": "233"
},
{
"level": 216,
"id": "234",
"label": "234"
},
{
"level": 217,
"id": "235",
"label": "235"
},
{
"level": 218,
"id": "236",
"label": "236"
},
{
"level": 219,
"id": "237",
"label": "237"
},
{
"level": 220,
"id": "238",
"label": "238"
},
{
"level": 221,
"id": "239",
"label": "239"
},
{
"level": 222,
"id": "240",
"label": "240"
},
{
"level": 223,
"id": "241",
"label": "241"
},
{
"level": 212,
"id": "242",
"label": "242"
},
{
"level": 213,
"id": "243",
"label": "243"
},
{
"level": 214,
"id": "244",
"label": "244"
},
{
"level": 215,
"id": "245",
"label": "245"
},
{
"level": 215,
"id": "246",
"label": "246"
},
{
"level": 216,
"id": "247",
"label": "247"
},
{
"level": 217,
"id": "248",
"label": "248"
},
{
"level": 218,
"id": "249",
"label": "249"
},
{
"level": 219,
"id": "250",
"label": "250"
},
{
"level": 220,
"id": "251",
"label": "251"
},
{
"level": 221,
"id": "252",
"label": "252"
},
{
"level": 222,
"id": "253",
"label": "253"
},
{
"level": 223,
"id": "254",
"label": "254"
},
{
"level": 223,
"id": "255",
"label": "255"
},
{
"level": 224,
"id": "256",
"label": "256"
},
{
"level": 225,
"id": "257",
"label": "257"
},
{
"level": 226,
"id": "258",
"label": "258"
},
{
"level": 227,
"id": "259",
"label": "259"
},
{
"level": 228,
"id": "260",
"label": "260"
},
{
"level": 229,
"id": "261",
"label": "261"
},
{
"level": 230,
"id": "262",
"label": "262"
},
{
"level": 231,
"id": "263",
"label": "263"
},
{
"level": 232,
"id": "264",
"label": "264"
},
{
"level": 233,
"id": "265",
"label": "265"
},
{
"level": 234,
"id": "266",
"label": "266"
},
{
"level": 235,
"id": "267",
"label": "267"
},
{
"level": 234,
"id": "268",
"label": "268"
},
{
"level": 236,
"id": "269",
"label": "269"
},
{
"level": 237,
"id": "270",
"label": "270"
},
{
"level": 238,
"id": "271",
"label": "271"
},
{
"level": 239,
"id": "272",
"label": "272"
},
{
"level": 240,
"id": "273",
"label": "273"
},
{
"level": 241,
"id": "274",
"label": "274"
},
{
"level": 242,
"id": "275",
"label": "275"
},
{
"level": 243,
"id": "276",
"label": "276"
},
{
"level": 244,
"id": "277",
"label": "277"
},
{
"level": 245,
"id": "278",
"label": "278"
},
{
"level": 246,
"id": "279",
"label": "279"
},
{
"level": 246,
"id": "280",
"label": "280"
},
{
"level": 247,
"id": "281",
"label": "281"
},
{
"level": 247,
"id": "282",
"label": "282"
},
{
"level": 248,
"id": "283",
"label": "283"
},
{
"level": 248,
"id": "284",
"label": "284"
},
{
"level": 249,
"id": "285",
"label": "285"
},
{
"level": 249,
"id": "286",
"label": "286"
},
{
"level": 250,
"id": "287",
"label": "287"
},
{
"level": 251,
"id": "288",
"label": "288"
},
{
"level": 252,
"id": "289",
"label": "289"
},
{
"level": 253,
"id": "290",
"label": "290"
},
{
"level": 254,
"id": "291",
"label": "291"
},
{
"level": 255,
"id": "292",
"label": "292"
},
{
"level": 256,
"id": "293",
"label": "293"
},
{
"level": 257,
"id": "294",
"label": "294"
},
{
"level": 258,
"id": "295",
"label": "295"
},
{
"level": 259,
"id": "296",
"label": "296"
},
{
"level": 260,
"id": "297",
"label": "297"
},
{
"level": 261,
"id": "298",
"label": "298"
},
{
"level": 262,
"id": "299",
"label": "299"
},
{
"level": 263,
"id": "300",
"label": "300"
},
{
"level": 264,
"id": "301",
"label": "301"
},
{
"level": 265,
"id": "302",
"label": "302"
},
{
"level": 266,
"id": "303",
"label": "303"
},
{
"level": 267,
"id": "304",
"label": "304"
},
{
"level": 268,
"id": "305",
"label": "305"
},
{
"level": 269,
"id": "306",
"label": "306"
},
{
"level": 270,
"id": "307",
"label": "307"
},
{
"level": 271,
"id": "308",
"label": "308"
},
{
"level": 272,
"id": "309",
"label": "309"
},
{
"level": 273,
"id": "310",
"label": "310"
},
{
"level": 274,
"id": "311",
"label": "311"
},
{
"level": 275,
"id": "312",
"label": "312"
},
{
"level": 276,
"id": "313",
"label": "313"
},
{
"level": 277,
"id": "314",
"label": "314"
},
{
"level": 278,
"id": "315",
"label": "315"
},
{
"level": 279,
"id": "316",
"label": "316"
},
{
"level": 280,
"id": "317",
"label": "317"
},
{
"level": 280,
"id": "318",
"label": "318"
},
{
"level": 281,
"id": "319",
"label": "319"
},
{
"level": 282,
"id": "320",
"label": "320"
},
{
"level": 283,
"id": "321",
"label": "321"
},
{
"level": 284,
"id": "322",
"label": "322"
},
{
"level": 285,
"id": "323",
"label": "323"
},
{
"level": 286,
"id": "324",
"label": "324"
},
{
"level": 287,
"id": "325",
"label": "325"
},
{
"level": 288,
"id": "326",
"label": "326"
},
{
"level": 289,
"id": "327",
"label": "327"
},
{
"level": 290,
"id": "328",
"label": "328"
},
{
"level": 291,
"id": "329",
"label": "329"
},
{
"level": 292,
"id": "330",
"label": "330"
},
{
"level": 293,
"id": "331",
"label": "331"
},
{
"level": 281,
"id": "332",
"label": "332"
},
{
"level": 282,
"id": "333",
"label": "333"
},
{
"level": 283,
"id": "334",
"label": "334"
},
{
"level": 284,
"id": "335",
"label": "335"
},
{
"level": 285,
"id": "336",
"label": "336"
},
{
"level": 286,
"id": "337",
"label": "337"
},
{
"level": 287,
"id": "338",
"label": "338"
},
{
"level": 288,
"id": "339",
"label": "339"
},
{
"level": 289,
"id": "340",
"label": "340"
},
{
"level": 290,
"id": "341",
"label": "341"
},
{
"level": 291,
"id": "342",
"label": "342"
},
{
"level": 292,
"id": "343",
"label": "343"
},
{
"level": 293,
"id": "344",
"label": "344"
},
{
"level": 294,
"id": "345",
"label": "345"
},
{
"level": 295,
"id": "346",
"label": "346"
},
{
"level": 296,
"id": "347",
"label": "347"
},
{
"level": 297,
"id": "348",
"label": "348"
},
{
"level": 298,
"id": "349",
"label": "349"
},
{
"level": 299,
"id": "350",
"label": "350"
},
{
"level": 300,
"id": "351",
"label": "351"
},
{
"level": 301,
"id": "352",
"label": "352"
},
{
"level": 302,
"id": "353",
"label": "353"
},
{
"level": 303,
"id": "354",
"label": "354"
},
{
"level": 304,
"id": "355",
"label": "355"
},
{
"level": 305,
"id": "356",
"label": "356"
},
{
"level": 306,
"id": "357",
"label": "357"
},
{
"level": 307,
"id": "358",
"label": "358"
},
{
"level": 308,
"id": "359",
"label": "359"
},
{
"level": 309,
"id": "360",
"label": "360"
},
{
"level": 310,
"id": "361",
"label": "361"
},
{
"level": 311,
"id": "362",
"label": "362"
},
{
"level": 312,
"id": "363",
"label": "363"
},
{
"level": 313,
"id": "364",
"label": "364"
},
{
"level": 314,
"id": "365",
"label": "365"
},
{
"level": 315,
"id": "366",
"label": "366"
},
{
"level": 316,
"id": "367",
"label": "367"
},
{
"level": 317,
"id": "368",
"label": "368"
},
{
"level": 318,
"id": "369",
"label": "369"
},
{
"level": 319,
"id": "370",
"label": "370"
},
{
"level": 320,
"id": "371",
"label": "371"
},
{
"level": 321,
"id": "372",
"label": "372"
},
{
"level": 322,
"id": "373",
"label": "373"
},
{
"level": 323,
"id": "374",
"label": "374"
},
{
"level": 324,
"id": "375",
"label": "375"
},
{
"level": 325,
"id": "376",
"label": "376"
},
{
"level": 326,
"id": "377",
"label": "377"
},
{
"level": 327,
"id": "378",
"label": "378"
},
{
"level": 328,
"id": "379",
"label": "379"
},
{
"level": 329,
"id": "380",
"label": "380"
},
{
"level": 330,
"id": "381",
"label": "381"
},
{
"level": 331,
"id": "382",
"label": "382"
},
{
"level": 332,
"id": "383",
"label": "383"
},
{
"level": 333,
"id": "384",
"label": "384"
},
{
"level": 334,
"id": "385",
"label": "385"
},
{
"level": 14,
"id": "386",
"label": "386"
},
{
"level": 335,
"id": "387",
"label": "387"
},
{
"level": 15,
"id": "388",
"label": "388"
},
{
"level": 336,
"id": "389",
"label": "389"
},
{
"level": 337,
"id": "390",
"label": "390"
},
{
"level": 338,
"id": "391",
"label": "391"
},
{
"level": 339,
"id": "392",
"label": "392"
},
{
"level": 340,
"id": "393",
"label": "393"
},
{
"level": 341,
"id": "394",
"label": "394"
},
{
"level": 342,
"id": "395",
"label": "395"
},
{
"level": 343,
"id": "396",
"label": "396"
},
{
"level": 344,
"id": "397",
"label": "397"
},
{
"level": 345,
"id": "398",
"label": "398"
},
{
"level": 346,
"id": "399",
"label": "399"
}
],
"edges": [
{
"to": "0",
"from": "1"
},
{
"to": "1",
"from": "2"
},
{
"to": "2",
"from": "3"
},
{
"to": "3",
"from": "4"
},
{
"to": "4",
"from": "5"
},
{
"to": "5",
"from": "6"
},
{
"to": "6",
"from": "7"
},
{
"to": "7",
"from": "8"
},
{
"to": "8",
"from": "10"
},
{
"to": "9",
"from": "11"
},
{
"to": "10",
"from": "11"
},
{
"to": "11",
"from": "12"
},
{
"to": "12",
"from": "13"
},
{
"to": "13",
"from": "15"
},
{
"to": "13",
"from": "14"
},
{
"to": "14",
"from": "386"
},
{
"to": "14",
"from": "16"
},
{
"to": "15",
"from": "386"
},
{
"to": "15",
"from": "16"
},
{
"to": "16",
"from": "17"
},
{
"to": "17",
"from": "18"
},
{
"to": "18",
"from": "19"
},
{
"to": "19",
"from": "20"
},
{
"to": "20",
"from": "21"
},
{
"to": "21",
"from": "22"
},
{
"to": "22",
"from": "23"
},
{
"to": "23",
"from": "24"
},
{
"to": "24",
"from": "25"
},
{
"to": "25",
"from": "26"
},
{
"to": "26",
"from": "27"
},
{
"to": "27",
"from": "28"
},
{
"to": "28",
"from": "29"
},
{
"to": "29",
"from": "30"
},
{
"to": "30",
"from": "31"
},
{
"to": "31",
"from": "32"
},
{
"to": "32",
"from": "33"
},
{
"to": "33",
"from": "34"
},
{
"to": "33",
"from": "35"
},
{
"to": "33",
"from": "37"
},
{
"to": "34",
"from": "36"
},
{
"to": "34",
"from": "43"
},
{
"to": "35",
"from": "36"
},
{
"to": "35",
"from": "43"
},
{
"to": "36",
"from": "38"
},
{
"to": "37",
"from": "39"
},
{
"to": "37",
"from": "43"
},
{
"to": "38",
"from": "39"
},
{
"to": "39",
"from": "40"
},
{
"to": "40",
"from": "41"
},
{
"to": "41",
"from": "42"
},
{
"to": "42",
"from": "44"
},
{
"to": "43",
"from": "45"
},
{
"to": "44",
"from": "45"
},
{
"to": "45",
"from": "46"
},
{
"to": "46",
"from": "47"
},
{
"to": "47",
"from": "48"
},
{
"to": "48",
"from": "49"
},
{
"to": "49",
"from": "50"
},
{
"to": "50",
"from": "51"
},
{
"to": "51",
"from": "52"
},
{
"to": "52",
"from": "53"
},
{
"to": "53",
"from": "54"
},
{
"to": "54",
"from": "55"
},
{
"to": "55",
"from": "56"
},
{
"to": "56",
"from": "57"
},
{
"to": "57",
"from": "58"
},
{
"to": "58",
"from": "59"
},
{
"to": "59",
"from": "60"
},
{
"to": "59",
"from": "65"
},
{
"to": "60",
"from": "61"
},
{
"to": "61",
"from": "62"
},
{
"to": "62",
"from": "63"
},
{
"to": "63",
"from": "64"
},
{
"to": "64",
"from": "66"
},
{
"to": "65",
"from": "67"
},
{
"to": "65",
"from": "124"
},
{
"to": "65",
"from": "229"
},
{
"to": "65",
"from": "322"
},
{
"to": "65",
"from": "363"
},
{
"to": "66",
"from": "67"
},
{
"to": "67",
"from": "68"
},
{
"to": "68",
"from": "69"
},
{
"to": "69",
"from": "70"
},
{
"to": "70",
"from": "71"
},
{
"to": "71",
"from": "72"
},
{
"to": "72",
"from": "73"
},
{
"to": "73",
"from": "74"
},
{
"to": "74",
"from": "75"
},
{
"to": "75",
"from": "76"
},
{
"to": "76",
"from": "77"
},
{
"to": "77",
"from": "78"
},
{
"to": "78",
"from": "79"
},
{
"to": "79",
"from": "80"
},
{
"to": "80",
"from": "81"
},
{
"to": "81",
"from": "82"
},
{
"to": "82",
"from": "83"
},
{
"to": "83",
"from": "84"
},
{
"to": "84",
"from": "85"
},
{
"to": "85",
"from": "91"
},
{
"to": "85",
"from": "86"
},
{
"to": "86",
"from": "87"
},
{
"to": "87",
"from": "88"
},
{
"to": "88",
"from": "89"
},
{
"to": "89",
"from": "90"
},
{
"to": "90",
"from": "92"
},
{
"to": "91",
"from": "195"
},
{
"to": "91",
"from": "93"
},
{
"to": "91",
"from": "397"
},
{
"to": "91",
"from": "233"
},
{
"to": "91",
"from": "125"
},
{
"to": "92",
"from": "93"
},
{
"to": "93",
"from": "94"
},
{
"to": "94",
"from": "95"
},
{
"to": "95",
"from": "96"
},
{
"to": "96",
"from": "97"
},
{
"to": "97",
"from": "98"
},
{
"to": "98",
"from": "99"
},
{
"to": "99",
"from": "100"
},
{
"to": "100",
"from": "101"
},
{
"to": "101",
"from": "102"
},
{
"to": "102",
"from": "103"
},
{
"to": "103",
"from": "104"
},
{
"to": "104",
"from": "105"
},
{
"to": "105",
"from": "106"
},
{
"to": "106",
"from": "107"
},
{
"to": "107",
"from": "108"
},
{
"to": "108",
"from": "109"
},
{
"to": "109",
"from": "110"
},
{
"to": "110",
"from": "111"
},
{
"to": "111",
"from": "112"
},
{
"to": "112",
"from": "113"
},
{
"to": "113",
"from": "114"
},
{
"to": "114",
"from": "115"
},
{
"to": "115",
"from": "116"
},
{
"to": "116",
"from": "117"
},
{
"to": "117",
"from": "118"
},
{
"to": "118",
"from": "119"
},
{
"to": "119",
"from": "120"
},
{
"to": "120",
"from": "121"
},
{
"to": "121",
"from": "122"
},
{
"to": "122",
"from": "123"
},
{
"to": "123",
"from": "124"
},
{
"to": "124",
"from": "125"
},
{
"to": "125",
"from": "126"
},
{
"to": "126",
"from": "127"
},
{
"to": "127",
"from": "128"
},
{
"to": "128",
"from": "129"
},
{
"to": "129",
"from": "130"
},
{
"to": "130",
"from": "131"
},
{
"to": "131",
"from": "132"
},
{
"to": "132",
"from": "134"
},
{
"to": "132",
"from": "133"
},
{
"to": "133",
"from": "135"
},
{
"to": "134",
"from": "135"
},
{
"to": "135",
"from": "136"
},
{
"to": "136",
"from": "137"
},
{
"to": "137",
"from": "138"
},
{
"to": "138",
"from": "139"
},
{
"to": "138",
"from": "140"
},
{
"to": "139",
"from": "141"
},
{
"to": "140",
"from": "141"
},
{
"to": "141",
"from": "142"
},
{
"to": "142",
"from": "143"
},
{
"to": "143",
"from": "144"
},
{
"to": "144",
"from": "145"
},
{
"to": "145",
"from": "146"
},
{
"to": "146",
"from": "147"
},
{
"to": "147",
"from": "148"
},
{
"to": "148",
"from": "149"
},
{
"to": "149",
"from": "150"
},
{
"to": "150",
"from": "151"
},
{
"to": "151",
"from": "152"
},
{
"to": "152",
"from": "153"
},
{
"to": "153",
"from": "154"
},
{
"to": "154",
"from": "155"
},
{
"to": "155",
"from": "157"
},
{
"to": "155",
"from": "156"
},
{
"to": "156",
"from": "158"
},
{
"to": "157",
"from": "158"
},
{
"to": "158",
"from": "159"
},
{
"to": "159",
"from": "162"
},
{
"to": "159",
"from": "160"
},
{
"to": "160",
"from": "164"
},
{
"to": "160",
"from": "161"
},
{
"to": "161",
"from": "163"
},
{
"to": "162",
"from": "164"
},
{
"to": "163",
"from": "165"
},
{
"to": "164",
"from": "166"
},
{
"to": "165",
"from": "166"
},
{
"to": "166",
"from": "167"
},
{
"to": "167",
"from": "168"
},
{
"to": "168",
"from": "170"
},
{
"to": "168",
"from": "169"
},
{
"to": "169",
"from": "171"
},
{
"to": "170",
"from": "171"
},
{
"to": "171",
"from": "172"
},
{
"to": "172",
"from": "173"
},
{
"to": "173",
"from": "174"
},
{
"to": "174",
"from": "175"
},
{
"to": "175",
"from": "176"
},
{
"to": "176",
"from": "177"
},
{
"to": "177",
"from": "178"
},
{
"to": "178",
"from": "180"
},
{
"to": "178",
"from": "179"
},
{
"to": "179",
"from": "181"
},
{
"to": "180",
"from": "181"
},
{
"to": "181",
"from": "183"
},
{
"to": "181",
"from": "182"
},
{
"to": "182",
"from": "184"
},
{
"to": "183",
"from": "184"
},
{
"to": "184",
"from": "186"
},
{
"to": "184",
"from": "185"
},
{
"to": "185",
"from": "187"
},
{
"to": "186",
"from": "189"
},
{
"to": "186",
"from": "188"
},
{
"to": "187",
"from": "188"
},
{
"to": "187",
"from": "189"
},
{
"to": "188",
"from": "190"
},
{
"to": "189",
"from": "191"
},
{
"to": "190",
"from": "191"
},
{
"to": "191",
"from": "192"
},
{
"to": "192",
"from": "193"
},
{
"to": "193",
"from": "194"
},
{
"to": "194",
"from": "195"
},
{
"to": "195",
"from": "197"
},
{
"to": "195",
"from": "196"
},
{
"to": "196",
"from": "198"
},
{
"to": "197",
"from": "198"
},
{
"to": "198",
"from": "199"
},
{
"to": "199",
"from": "200"
},
{
"to": "200",
"from": "201"
},
{
"to": "201",
"from": "202"
},
{
"to": "202",
"from": "203"
},
{
"to": "203",
"from": "204"
},
{
"to": "204",
"from": "205"
},
{
"to": "205",
"from": "206"
},
{
"to": "206",
"from": "207"
},
{
"to": "207",
"from": "208"
},
{
"to": "208",
"from": "209"
},
{
"to": "209",
"from": "210"
},
{
"to": "210",
"from": "211"
},
{
"to": "211",
"from": "212"
},
{
"to": "212",
"from": "213"
},
{
"to": "213",
"from": "214"
},
{
"to": "214",
"from": "215"
},
{
"to": "215",
"from": "216"
},
{
"to": "216",
"from": "217"
},
{
"to": "217",
"from": "218"
},
{
"to": "218",
"from": "219"
},
{
"to": "219",
"from": "220"
},
{
"to": "220",
"from": "221"
},
{
"to": "221",
"from": "222"
},
{
"to": "222",
"from": "223"
},
{
"to": "223",
"from": "224"
},
{
"to": "224",
"from": "225"
},
{
"to": "225",
"from": "226"
},
{
"to": "226",
"from": "227"
},
{
"to": "227",
"from": "228"
},
{
"to": "228",
"from": "229"
},
{
"to": "229",
"from": "230"
},
{
"to": "229",
"from": "242"
},
{
"to": "230",
"from": "231"
},
{
"to": "231",
"from": "232"
},
{
"to": "232",
"from": "233"
},
{
"to": "233",
"from": "234"
},
{
"to": "234",
"from": "235"
},
{
"to": "235",
"from": "236"
},
{
"to": "236",
"from": "237"
},
{
"to": "237",
"from": "238"
},
{
"to": "238",
"from": "239"
},
{
"to": "239",
"from": "240"
},
{
"to": "240",
"from": "241"
},
{
"to": "242",
"from": "243"
},
{
"to": "243",
"from": "244"
},
{
"to": "244",
"from": "246"
},
{
"to": "244",
"from": "245"
},
{
"to": "245",
"from": "247"
},
{
"to": "246",
"from": "247"
},
{
"to": "247",
"from": "248"
},
{
"to": "248",
"from": "249"
},
{
"to": "249",
"from": "250"
},
{
"to": "250",
"from": "251"
},
{
"to": "251",
"from": "252"
},
{
"to": "252",
"from": "253"
},
{
"to": "253",
"from": "254"
},
{
"to": "253",
"from": "255"
},
{
"to": "254",
"from": "256"
},
{
"to": "255",
"from": "256"
},
{
"to": "256",
"from": "257"
},
{
"to": "257",
"from": "258"
},
{
"to": "258",
"from": "259"
},
{
"to": "259",
"from": "260"
},
{
"to": "260",
"from": "261"
},
{
"to": "261",
"from": "262"
},
{
"to": "262",
"from": "263"
},
{
"to": "263",
"from": "264"
},
{
"to": "264",
"from": "265"
},
{
"to": "265",
"from": "268"
},
{
"to": "265",
"from": "266"
},
{
"to": "266",
"from": "267"
},
{
"to": "267",
"from": "269"
},
{
"to": "268",
"from": "269"
},
{
"to": "269",
"from": "270"
},
{
"to": "270",
"from": "271"
},
{
"to": "271",
"from": "272"
},
{
"to": "272",
"from": "273"
},
{
"to": "273",
"from": "274"
},
{
"to": "274",
"from": "275"
},
{
"to": "275",
"from": "276"
},
{
"to": "276",
"from": "277"
},
{
"to": "277",
"from": "278"
},
{
"to": "278",
"from": "280"
},
{
"to": "278",
"from": "279"
},
{
"to": "279",
"from": "282"
},
{
"to": "280",
"from": "281"
},
{
"to": "280",
"from": "282"
},
{
"to": "281",
"from": "284"
},
{
"to": "281",
"from": "283"
},
{
"to": "282",
"from": "284"
},
{
"to": "282",
"from": "283"
},
{
"to": "283",
"from": "286"
},
{
"to": "283",
"from": "285"
},
{
"to": "284",
"from": "286"
},
{
"to": "284",
"from": "285"
},
{
"to": "285",
"from": "287"
},
{
"to": "286",
"from": "287"
},
{
"to": "287",
"from": "288"
},
{
"to": "288",
"from": "289"
},
{
"to": "289",
"from": "290"
},
{
"to": "290",
"from": "291"
},
{
"to": "291",
"from": "292"
},
{
"to": "292",
"from": "293"
},
{
"to": "293",
"from": "294"
},
{
"to": "294",
"from": "295"
},
{
"to": "295",
"from": "296"
},
{
"to": "296",
"from": "297"
},
{
"to": "297",
"from": "298"
},
{
"to": "298",
"from": "299"
},
{
"to": "299",
"from": "300"
},
{
"to": "300",
"from": "301"
},
{
"to": "301",
"from": "302"
},
{
"to": "302",
"from": "303"
},
{
"to": "303",
"from": "304"
},
{
"to": "304",
"from": "305"
},
{
"to": "305",
"from": "306"
},
{
"to": "306",
"from": "307"
},
{
"to": "307",
"from": "308"
},
{
"to": "308",
"from": "309"
},
{
"to": "309",
"from": "310"
},
{
"to": "310",
"from": "311"
},
{
"to": "311",
"from": "312"
},
{
"to": "312",
"from": "313"
},
{
"to": "313",
"from": "314"
},
{
"to": "314",
"from": "315"
},
{
"to": "315",
"from": "316"
},
{
"to": "316",
"from": "317"
},
{
"to": "316",
"from": "318"
},
{
"to": "317",
"from": "332"
},
{
"to": "317",
"from": "319"
},
{
"to": "318",
"from": "319"
},
{
"to": "319",
"from": "320"
},
{
"to": "320",
"from": "321"
},
{
"to": "321",
"from": "322"
},
{
"to": "322",
"from": "323"
},
{
"to": "323",
"from": "324"
},
{
"to": "324",
"from": "325"
},
{
"to": "325",
"from": "326"
},
{
"to": "326",
"from": "327"
},
{
"to": "327",
"from": "328"
},
{
"to": "328",
"from": "329"
},
{
"to": "329",
"from": "330"
},
{
"to": "330",
"from": "331"
},
{
"to": "332",
"from": "333"
},
{
"to": "333",
"from": "334"
},
{
"to": "334",
"from": "335"
},
{
"to": "335",
"from": "336"
},
{
"to": "336",
"from": "337"
},
{
"to": "337",
"from": "338"
},
{
"to": "338",
"from": "339"
},
{
"to": "339",
"from": "340"
},
{
"to": "340",
"from": "341"
},
{
"to": "341",
"from": "342"
},
{
"to": "342",
"from": "343"
},
{
"to": "343",
"from": "344"
},
{
"to": "344",
"from": "345"
},
{
"to": "345",
"from": "346"
},
{
"to": "346",
"from": "347"
},
{
"to": "347",
"from": "348"
},
{
"to": "348",
"from": "349"
},
{
"to": "349",
"from": "350"
},
{
"to": "350",
"from": "351"
},
{
"to": "351",
"from": "352"
},
{
"to": "352",
"from": "353"
},
{
"to": "353",
"from": "354"
},
{
"to": "354",
"from": "355"
},
{
"to": "355",
"from": "356"
},
{
"to": "356",
"from": "357"
},
{
"to": "357",
"from": "358"
},
{
"to": "358",
"from": "359"
},
{
"to": "359",
"from": "360"
},
{
"to": "360",
"from": "361"
},
{
"to": "361",
"from": "362"
},
{
"to": "362",
"from": "363"
},
{
"to": "363",
"from": "364"
},
{
"to": "364",
"from": "365"
},
{
"to": "365",
"from": "366"
},
{
"to": "366",
"from": "367"
},
{
"to": "367",
"from": "368"
},
{
"to": "368",
"from": "369"
},
{
"to": "369",
"from": "370"
},
{
"to": "370",
"from": "371"
},
{
"to": "371",
"from": "372"
},
{
"to": "372",
"from": "373"
},
{
"to": "373",
"from": "374"
},
{
"to": "374",
"from": "375"
},
{
"to": "375",
"from": "376"
},
{
"to": "376",
"from": "377"
},
{
"to": "377",
"from": "378"
},
{
"to": "378",
"from": "379"
},
{
"to": "379",
"from": "380"
},
{
"to": "380",
"from": "381"
},
{
"to": "381",
"from": "382"
},
{
"to": "382",
"from": "383"
},
{
"to": "383",
"from": "384"
},
{
"to": "384",
"from": "385"
},
{
"to": "385",
"from": "387"
},
{
"to": "386",
"from": "388"
},
{
"to": "387",
"from": "389"
},
{
"to": "388",
"from": "390"
},
{
"to": "389",
"from": "390"
},
{
"to": "390",
"from": "391"
},
{
"to": "391",
"from": "392"
},
{
"to": "392",
"from": "393"
},
{
"to": "393",
"from": "394"
},
{
"to": "394",
"from": "395"
},
{
"to": "395",
"from": "396"
},
{
"to": "396",
"from": "397"
},
{
"to": "397",
"from": "398"
},
{
"to": "398",
"from": "399"
}
]
} );
| {
"pile_set_name": "Github"
} |
/*
* SGI FREE SOFTWARE LICENSE B (Version 2.0, Sept. 18, 2008)
* Copyright (C) 1991-2000 Silicon Graphics, Inc. All Rights Reserved.
*
* 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 including the dates of first publication and
* either this permission notice or a reference to
* http://oss.sgi.com/projects/FreeB/
* 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
* SILICON GRAPHICS, INC. 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.
*
* Except as contained in this notice, the name of Silicon Graphics, Inc.
* shall not be used in advertising or otherwise to promote the sale, use or
* other dealings in this Software without prior written authorization from
* Silicon Graphics, Inc.
*/
/*
** Author: Eric Veach, July 1994.
**
*/
#ifndef __tessmono_h_
#define __tessmono_h_
/* __gl_meshTessellateMonoRegion( face ) tessellates a monotone region
* (what else would it do??) The region must consist of a single
* loop of half-edges (see mesh.h) oriented CCW. "Monotone" in this
* case means that any vertical line intersects the interior of the
* region in a single interval.
*
* Tessellation consists of adding interior edges (actually pairs of
* half-edges), to split the region into non-overlapping triangles.
*
* __gl_meshTessellateInterior( mesh ) tessellates each region of
* the mesh which is marked "inside" the polygon. Each such region
* must be monotone.
*
* __gl_meshDiscardExterior( mesh ) zaps (ie. sets to NULL) all faces
* which are not marked "inside" the polygon. Since further mesh operations
* on NULL faces are not allowed, the main purpose is to clean up the
* mesh so that exterior loops are not represented in the data structure.
*
* __gl_meshSetWindingNumber( mesh, value, keepOnlyBoundary ) resets the
* winding numbers on all edges so that regions marked "inside" the
* polygon have a winding number of "value", and regions outside
* have a winding number of 0.
*
* If keepOnlyBoundary is TRUE, it also deletes all edges which do not
* separate an interior region from an exterior one.
*/
int __gl_meshTessellateMonoRegion( GLUface *face );
int __gl_meshTessellateInterior( GLUmesh *mesh );
void __gl_meshDiscardExterior( GLUmesh *mesh );
int __gl_meshSetWindingNumber( GLUmesh *mesh, int value,
GLboolean keepOnlyBoundary );
#endif
| {
"pile_set_name": "Github"
} |
#
# Copyright (C) 2010-2015 Marvell International Ltd.
# Copyright (C) 2002-2010 Kinoma, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
binary(SOURCE ${MC_DIR}/application.js)
binary(SOURCE ${MC_DIR}/extensions/coap.js)
binary(SOURCE ${MC_DIR}/extensions/crypt/arith.js)
binary(SOURCE ${MC_DIR}/extensions/crypt/arith_ec.js MODULE ec SUBDIR arith)
binary(SOURCE ${MC_DIR}/extensions/crypt/arith_ecp.js MODULE ecp SUBDIR arith)
binary(SOURCE ${MC_DIR}/extensions/crypt/arith_ed.js MODULE ed SUBDIR arith)
binary(SOURCE ${MC_DIR}/extensions/crypt/arith_int.js MODULE int SUBDIR arith)
binary(SOURCE ${MC_DIR}/extensions/crypt/arith_mod.js MODULE mod SUBDIR arith)
binary(SOURCE ${MC_DIR}/extensions/crypt/arith_mont.js MODULE mont SUBDIR arith)
binary(SOURCE ${MC_DIR}/extensions/crypt/arith_z.js MODULE z SUBDIR arith)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt.js)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_aead.js MODULE aead SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_aes.js MODULE aes SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_ber.js MODULE ber SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_cbc.js MODULE cbc SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_chacha.js MODULE chacha SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_cipher.js MODULE cipher SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_ctr.js MODULE ctr SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_curve25519.js MODULE curve25519 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_des.js MODULE des SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_digest.js MODULE digest SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_dsa.js MODULE dsa SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_ecb.js MODULE ecb SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_ecdsa.js MODULE ecdsa SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_ed25519.js MODULE ed25519 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_ed25519_c.js MODULE ed25519_c SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_hkdf.js MODULE hkdf SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_hmac.js MODULE hmac SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_md5.js MODULE md5 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_mode.js MODULE mode SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_oaep.js MODULE oaep SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_pkcs1.js MODULE pkcs1 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_pkcs1_5.js MODULE pkcs1_5 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_pkcs8.js MODULE pkcs8 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_poly1305.js MODULE poly1305 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_rc4.js MODULE rc4 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_rng.js MODULE rng SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_rsa.js MODULE rsa SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_sha1.js MODULE sha1 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_sha256.js MODULE sha256 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_sha512.js MODULE sha512 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_srp.js MODULE srp SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_stream.js MODULE stream SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_tdes.js MODULE tdes SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/crypt/crypt_x509.js MODULE x509 SUBDIR crypt)
binary(SOURCE ${MC_DIR}/extensions/dial.js)
binary(SOURCE ${MC_DIR}/extensions/dial/pinexplorer/pinexplorer.js SUBDIR dial/pinexplorer)
binary(SOURCE ${MC_DIR}/extensions/dial/pinexplorer/simulator/Analog.js SUBDIR dial/pinexplorer)
binary(SOURCE ${MC_DIR}/extensions/dial/pinexplorer/simulator/Digital.js SUBDIR dial/pinexplorer)
binary(SOURCE ${MC_DIR}/extensions/dial/pinexplorer/simulator/Ground.js SUBDIR dial/pinexplorer)
binary(SOURCE ${MC_DIR}/extensions/dial/pinexplorer/simulator/I2C.js SUBDIR dial/pinexplorer)
binary(SOURCE ${MC_DIR}/extensions/dial/pinexplorer/simulator/Power.js SUBDIR dial/pinexplorer)
binary(SOURCE ${MC_DIR}/extensions/dial/pinexplorer/simulator/Serial.js SUBDIR dial/pinexplorer)
binary(SOURCE ${MC_DIR}/extensions/ext_bin.js MODULE bin)
binary(SOURCE ${MC_DIR}/extensions/ext_dhcpd.js MODULE dhcpd)
binary(SOURCE ${MC_DIR}/extensions/ext_http.xs MODULE http)
binary(SOURCE ${MC_DIR}/extensions/ext_http_client.xs MODULE HTTPClient)
binary(SOURCE ${MC_DIR}/extensions/ext_http_server.xs MODULE HTTPServer)
binary(SOURCE ${MC_DIR}/extensions/ext_json.xs MODULE json)
binary(SOURCE ${MC_DIR}/extensions/ext_mdns.js MODULE mdns)
binary(SOURCE ${MC_DIR}/extensions/ext_secure_socket.js MODULE SecureSocket)
binary(SOURCE ${MC_DIR}/extensions/ext_ssdp.xs MODULE SSDPMessage)
binary(SOURCE ${MC_DIR}/extensions/ext_ssdp_control.xs MODULE SSDPControl)
binary(SOURCE ${MC_DIR}/extensions/ext_ssdp_device.xs MODULE SSDPDevice)
binary(SOURCE ${MC_DIR}/extensions/ext_uuid.xs MODULE uuid)
binary(SOURCE ${MC_DIR}/extensions/hap/hap.js)
binary(SOURCE ${MC_DIR}/extensions/hap/hap_constants.js MODULE constants SUBDIR hap)
binary(SOURCE ${MC_DIR}/extensions/hap/hap_hkdf_sha512.js MODULE hkdf_sha512 SUBDIR hap)
binary(SOURCE ${MC_DIR}/extensions/hap/hap_ie.js MODULE ie SUBDIR hap)
binary(SOURCE ${MC_DIR}/extensions/hap/hap_mfi.js MODULE mfi SUBDIR hap)
binary(SOURCE ${MC_DIR}/extensions/hap/hap_pairing.js MODULE pairing SUBDIR hap)
binary(SOURCE ${MC_DIR}/extensions/hap/hap_setup.js MODULE setup SUBDIR hap)
binary(SOURCE ${MC_DIR}/extensions/hap/hap_socket.js MODULE socket SUBDIR hap)
binary(SOURCE ${MC_DIR}/extensions/hap/hap_tlv.js MODULE tlv SUBDIR hap)
binary(SOURCE ${MC_DIR}/extensions/hap/hap_verify.js MODULE verify SUBDIR hap)
binary(SOURCE ${MC_DIR}/extensions/hap/wac.js)
binary(SOURCE ${MC_DIR}/extensions/inetd_studio.js MODULE StudioHTTPServer)
binary(SOURCE ${MC_DIR}/extensions/inetd_telnetd.js MODULE telnetd)
binary(SOURCE ${MC_DIR}/extensions/inetd_tftpd.js MODULE tftpd)
binary(SOURCE ${MC_DIR}/extensions/io/io_a2d.js MODULE A2D SUBDIR io)
binary(SOURCE ${MC_DIR}/extensions/io/io_i2c.js MODULE I2C SUBDIR io)
binary(SOURCE ${MC_DIR}/extensions/io/io_uart.js MODULE Serial SUBDIR io)
binary(SOURCE ${MC_DIR}/extensions/kunit.js)
binary(SOURCE ${MC_DIR}/extensions/logging.js)
binary(SOURCE ${MC_DIR}/extensions/mqtt.js)
binary(SOURCE ${MC_DIR}/extensions/net.js)
binary(SOURCE ${MC_DIR}/extensions/pinmux.js)
binary(SOURCE ${MC_DIR}/extensions/pins/bll_Analog.js MODULE Analog)
binary(SOURCE ${MC_DIR}/extensions/pins/bll_Digital.js MODULE Digital)
binary(SOURCE ${MC_DIR}/extensions/pins/bll_Ground.js MODULE Ground)
binary(SOURCE ${MC_DIR}/extensions/pins/bll_I2C.js MODULE I2C)
binary(SOURCE ${MC_DIR}/extensions/pins/bll_Power.js MODULE Power)
binary(SOURCE ${MC_DIR}/extensions/pins/bll_Serial.js MODULE Serial)
binary(SOURCE ${MC_DIR}/extensions/pins/pins.js)
binary(SOURCE ${MC_DIR}/extensions/pins/pins_Analog.js MODULE Analog SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/pins/pins_Digital.js MODULE Digital SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/pins/pins_GPIO.js MODULE GPIO SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/pins/pins_Ground.js MODULE Ground SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/pins/pins_I2C.js MODULE I2C SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/pins/pins_K5PinMux.js MODULE K5PinMux SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/pins/pins_Power.js MODULE Power SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/pins/pins_PowerGround.js MODULE PowerGround SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/pins/pins_Serial.js MODULE Serial SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/pins/pins__hap.js MODULE _hap SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/pins/pins__http.js MODULE _http SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/pins/pins_map.js MODULE map SUBDIR pins)
binary(SOURCE ${MC_DIR}/extensions/setup/config.js SUBDIR setup)
binary(SOURCE ${MC_DIR}/extensions/setup/connect.js SUBDIR setup)
binary(SOURCE ${MC_DIR}/extensions/setup/description.js SUBDIR setup)
binary(SOURCE ${MC_DIR}/extensions/setup/download.js SUBDIR setup)
binary(SOURCE ${MC_DIR}/extensions/setup/rssi.js SUBDIR setup)
binary(SOURCE ${MC_DIR}/extensions/setup/scan.js SUBDIR setup)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl.js)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_alert.js MODULE alert SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_cache.js MODULE cache SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_cert_mc.js MODULE cert_mc SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_changecipher.js MODULE changecipher SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_ciphersuites.js MODULE ciphersuites SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_handshake.js MODULE handshake SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_prf.js MODULE prf SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_protocol.js MODULE protocol SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_record.js MODULE record SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_session.js MODULE session SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_setup.js MODULE setup SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/ssl/ssl_stream.js MODULE stream SUBDIR ssl)
binary(SOURCE ${MC_DIR}/extensions/utils.js)
binary(SOURCE ${MC_DIR}/extensions/websocket.js)
binary(SOURCE ${MC_DIR}/inetd.js)
binary(SOURCE ${MC_DIR}/launcher.js)
binary(SOURCE ${MC_DIR}/modules/xm_cli.js MODULE CLI)
binary(SOURCE ${MC_DIR}/modules/xm_console.js MODULE console)
binary(SOURCE ${MC_DIR}/modules/xm_debug.js MODULE debug)
binary(SOURCE ${MC_DIR}/modules/xm_env.js MODULE env)
binary(SOURCE ${MC_DIR}/modules/xm_files.js MODULE files)
binary(SOURCE ${MC_DIR}/modules/xm_socket.js MODULE socket)
binary(SOURCE ${MC_DIR}/modules/xm_stringview.js MODULE stringview)
binary(SOURCE ${MC_DIR}/modules/xm_system.js MODULE system)
binary(SOURCE ${MC_DIR}/modules/xm_timeinterval.js MODULE timeinterval)
binary(SOURCE ${MC_DIR}/modules/xm_timer.js MODULE timer)
binary(SOURCE ${MC_DIR}/modules/xm_watchdogtimer.js MODULE watchdogtimer)
binary(SOURCE ${MC_DIR}/modules/xm_wifi.js MODULE wifi)
binary(SOURCE ${MC_DIR}/tools/print_ski.js)
binary(SOURCE ${MC_DIR}/tools/xssign.js)
add_custom_target(
host_fs
COMMAND ${CMAKE_COMMAND} -E make_directory $ENV{HOME}/tmp/mc
COMMAND ${CMAKE_COMMAND} -E copy_directory ${XS6}/sources/mc/data $ENV{HOME}/tmp/mc
)
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/mc.xsa ${DEST_DIR}/mc.xs.c ${DEST_DIR}/mc.xs.h
COMMAND ${XSL} -a mc -o ${CMAKE_CURRENT_BINARY_DIR} -b ${DEST_DIR} -r 97 ${MC_DEPS}
COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_BINARY_DIR}/mc.xsa ${XS6_MODULES_DIR}/mc.xsa
DEPENDS ${MC_DEPS}
)
add_custom_target(mc.xsa DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/mc.xsa)
list(APPEND SOURCES ${DEST_DIR}/mc.xs.c ${DEST_DIR}/mc.xs.h)
| {
"pile_set_name": "Github"
} |
-- Copyright : (C) Keera Studios Ltd, 2013
-- License : All Rights Reserved
-- Maintainer : [email protected]
--
cabal-version: >=1.10
build-type: Simple
name: keera-hails-demos-gtk
author: Ivan Perez
maintainer: [email protected]
homepage: http://github.com/keera-studios/keera-hails
license: BSD3
license-file: LICENSE
category: Graphics
version: 0.7.0
synopsis: A collection of demos demonstrating reactive Gtk
source-repository head
type: git
location: git://github.com/keera-studios/keera-hails
subdir: keera-hails-demos-gtk
-- You can disable the hlint test suite with -f-test-hlint
flag test-hlint
default: False
manual: True
-- You can disable the haddock coverage test suite with -f-test-doc-coverage
flag test-doc-coverage
default: False
manual: True
executable keera-hails-demos-gtk
main-is:
HelloWorld.hs
build-depends:
base >=4.6 && <5
, gtk3
, keera-hails-reactivevalues
, keera-hails-reactive-gtk3
hs-source-dirs: src
default-language: Haskell2010
test-suite hlint
type:
exitcode-stdio-1.0
main-is:
HLintMain.hs
hs-source-dirs:
tests
if !flag(test-hlint)
buildable: False
else
build-depends:
base
, hlint >= 1.7
default-language:
Haskell2010
-- Verify that the code is thoroughly documented
test-suite haddock-coverage
type:
exitcode-stdio-1.0
main-is:
HaddockCoverage.hs
ghc-options:
-Wall
hs-source-dirs:
tests
if !flag(test-doc-coverage)
buildable: False
else
build-depends:
base >= 4 && < 5
, directory
, filepath
, process
, regex-posix
default-language:
Haskell2010
| {
"pile_set_name": "Github"
} |
/*
* Sonatype Nexus (TM) Open Source Version
* Copyright (c) 2008-present Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions.
*
* This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0,
* which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html.
*
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks
* of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the
* Eclipse Foundation. All other trademarks are the property of their respective owners.
*/
package org.sonatype.nexus.coreui.internal;
import java.util.List;
import javax.annotation.Nullable;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;
import org.sonatype.nexus.ui.UiPluginDescriptor;
import org.sonatype.nexus.ui.UiUtil;
import org.eclipse.sisu.Priority;
import org.eclipse.sisu.space.ClassSpace;
import static java.util.Arrays.asList;
/**
* {@link UiPluginDescriptor} for {@code nexus-coreui-plugin} react code.
*
* @since 3.22
*/
@Named
@Singleton
@Priority(Integer.MAX_VALUE - 100) // after nexus-rapture
public class CoreUiReactPluginDescriptorImpl
implements UiPluginDescriptor
{
private final List<String> scripts;
private final List<String> debugScripts;
private final List<String> styles;
@Inject
public CoreUiReactPluginDescriptorImpl(final ClassSpace space) {
scripts = asList(UiUtil.getPathForFile("nexus-coreui-bundle.js", space));
debugScripts = asList(UiUtil.getPathForFile("nexus-coreui-bundle.debug.js", space));
styles = asList(UiUtil.getPathForFile("nexus-coreui-bundle.css", space));
}
@Override
public String getName() {
return "nexus-coreui-plugin";
}
@Nullable
@Override
public List<String> getScripts(final boolean isDebug) {
return isDebug ? debugScripts : scripts;
}
@Nullable
@Override
public List<String> getStyles() {
return styles;
}
}
| {
"pile_set_name": "Github"
} |
// Copyright (c) 2020 .NET Foundation and Contributors. All rights reserved.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using ReactiveUI.Tests.Xaml;
namespace ReactiveUI.Tests.Wpf
{
public class CommandBindingView : ReactiveObject, IViewFor<CommandBindingViewModel>
{
private CommandBindingViewModel? _viewModel;
public CommandBindingView()
{
Command1 = new CustomClickButton();
Command2 = new Image();
}
object? IViewFor.ViewModel
{
get => ViewModel;
set => ViewModel = (CommandBindingViewModel?)value;
}
public CommandBindingViewModel? ViewModel
{
get => _viewModel;
set => this.RaiseAndSetIfChanged(ref _viewModel, value);
}
public CustomClickButton Command1 { get; protected set; }
public Image Command2 { get; protected set; }
}
}
| {
"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 -emit-ir
func<let{class C{func t(UInt=1 + 1 + 1 + 1 as?Int){(UInt=nil?)a{b{{c
| {
"pile_set_name": "Github"
} |
import resolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import sourceMaps from 'rollup-plugin-sourcemaps';
const pkg = require('./package.json');
const camelCase = require('lodash.camelcase');
const libraryName = 'codesandbox';
export default {
entry: `compiled/${libraryName}.js`,
targets: [
{ dest: pkg.main, moduleName: camelCase(libraryName), format: 'umd' },
{ dest: pkg.module, format: 'es' },
],
sourceMap: true,
// Indicate here external modules you don't wanna include in your bundle (i.e.: 'lodash')
external: [],
plugins: [
// Allow bundling cjs modules (unlike webpack, rollup doesn't understand cjs)
commonjs(),
// Allow node_modules resolution, so you can use 'external' to control
// which external modules to include in the bundle
// https://github.com/rollup/rollup-plugin-node-resolve#usage
resolve(),
// Resolve source maps to the original source
sourceMaps(),
],
onwarn: function(warning) {
if (warning.code !== 'THIS_IS_UNDEFINED') {
console.warn(warning);
}
},
};
| {
"pile_set_name": "Github"
} |
import { GrafanaDatasource } from '../datasource';
// @ts-ignore
import q from 'q';
import { dateTime } from '@grafana/data';
describe('grafana data source', () => {
describe('when executing an annotations query', () => {
let calledBackendSrvParams: any;
const backendSrvStub = {
get: (url: string, options: any) => {
calledBackendSrvParams = options;
return q.resolve([]);
},
};
const templateSrvStub = {
replace: (val: string) => {
return val.replace('$var2', 'replaced__delimiter__replaced2').replace('$var', 'replaced');
},
};
const ds = new GrafanaDatasource(backendSrvStub as any, templateSrvStub as any);
describe('with tags that have template variables', () => {
const options = setupAnnotationQueryOptions({ tags: ['tag1:$var'] });
beforeEach(() => {
return ds.annotationQuery(options);
});
it('should interpolate template variables in tags in query options', () => {
expect(calledBackendSrvParams.tags[0]).toBe('tag1:replaced');
});
});
describe('with tags that have multi value template variables', () => {
const options = setupAnnotationQueryOptions({ tags: ['$var2'] });
beforeEach(() => {
return ds.annotationQuery(options);
});
it('should interpolate template variables in tags in query options', () => {
expect(calledBackendSrvParams.tags[0]).toBe('replaced');
expect(calledBackendSrvParams.tags[1]).toBe('replaced2');
});
});
describe('with type dashboard', () => {
const options = setupAnnotationQueryOptions(
{
type: 'dashboard',
tags: ['tag1'],
},
{ id: 1 }
);
beforeEach(() => {
return ds.annotationQuery(options);
});
it('should remove tags from query options', () => {
expect(calledBackendSrvParams.tags).toBe(undefined);
});
});
});
});
function setupAnnotationQueryOptions(annotation: { tags: string[]; type?: string }, dashboard?: { id: number }) {
return {
annotation,
dashboard,
range: {
from: dateTime(1432288354),
to: dateTime(1432288401),
},
rangeRaw: { from: 'now-24h', to: 'now' },
};
}
| {
"pile_set_name": "Github"
} |
#include "node.h"
#include "env-inl.h"
namespace node {
using v8::Function;
using v8::Isolate;
using v8::Local;
using v8::MaybeLocal;
using v8::Object;
using v8::String;
using v8::Value;
AsyncResource::AsyncResource(Isolate* isolate,
Local<Object> resource,
const char* name,
async_id trigger_async_id)
: env_(Environment::GetCurrent(isolate)),
resource_(isolate, resource) {
CHECK_NOT_NULL(env_);
async_context_ = EmitAsyncInit(isolate, resource, name,
trigger_async_id);
}
AsyncResource::~AsyncResource() {
EmitAsyncDestroy(env_, async_context_);
}
MaybeLocal<Value> AsyncResource::MakeCallback(Local<Function> callback,
int argc,
Local<Value>* argv) {
return node::MakeCallback(env_->isolate(), get_resource(),
callback, argc, argv,
async_context_);
}
MaybeLocal<Value> AsyncResource::MakeCallback(const char* method,
int argc,
Local<Value>* argv) {
return node::MakeCallback(env_->isolate(), get_resource(),
method, argc, argv,
async_context_);
}
MaybeLocal<Value> AsyncResource::MakeCallback(Local<String> symbol,
int argc,
Local<Value>* argv) {
return node::MakeCallback(env_->isolate(), get_resource(),
symbol, argc, argv,
async_context_);
}
Local<Object> AsyncResource::get_resource() {
return resource_.Get(env_->isolate());
}
async_id AsyncResource::get_async_id() const {
return async_context_.async_id;
}
async_id AsyncResource::get_trigger_async_id() const {
return async_context_.trigger_async_id;
}
// TODO(addaleax): We shouldn’t need to use env_->isolate() if we’re just going
// to end up using the Isolate* to figure out the Environment* again.
AsyncResource::CallbackScope::CallbackScope(AsyncResource* res)
: node::CallbackScope(res->env_->isolate(),
res->resource_.Get(res->env_->isolate()),
res->async_context_) {}
} // namespace node
| {
"pile_set_name": "Github"
} |
#!/bin/bash
# Usage:
# - Place the XWiki Solr configuration jar into the same directory as this script
# - ex. wget https://maven.xwiki.org/releases/org/xwiki/platform/xwiki-platform-search-solr-server-data/10.1/xwiki-platform-search-solr-server-data-10.1.jar
# - ensure that this directory, and it's contents, are owned by the solr user and group, 8983:8983
# - ex. chown -R 8983:8983 $PARENT_DIRECTORY
# - mount the partent directory of this script to /docker-entrypoint-initdb.d/ when you run the Solr container
# - ex. add the following to docker run command ... -v $PWD/$PARENT_DIRECTORY:/docker-entrypoint-initdb.d ...
# - At run time, before starting Solr, the container will execute scripts in the /docker-entrypoint-initdb.d/ directory.
cd /docker-entrypoint-initdb.d/
location='/opt/solr/server/solr/'
# Verify the existence of a singular XWiki Solr configuration jar
jars=$(find . -type f -name *.jar | wc -l)
if [ $jars -lt 1 ]; then
echo 'No XWiki Solr configuration jar found'
exit 1
elif [ $jars -gt 1 ]; then
echo 'Too many XWiki Solr configuration jars found, please include only one jar'
exit 1
fi
# Get the name of the XWiki Solr configuration jar
jar=$(find . -type f -name *.jar)
# Ensure that the Solr directory exists
mkdir -p $location
# Add the XWiki Solr plugin
plugin=$(unzip -Z1 $jar | grep lib.*jar)
unzip -o $jar \
$plugin \
-d $location
# Add the XWiki core
core='xwiki/*'
unzip -o $jar \
$core \
-d $location
| {
"pile_set_name": "Github"
} |
<#
Environment
===========
- techsnips.local forest
- PROD-DC
- Enterprise Admin accounts (abertram)
- On a Windows 10 workgroup computer using PowerShell Remoting to connect to DC
Our Mission
===========
- Create, install, enumerate, test, install and uninstall managed service accounts (MSAs)
- Install the gMSA on a domain-joined computer called CLIENT-PROD
Prereqs
=========
CredSSP configured on Windows 10 computer
RSAT installed on the computer associated with the gMSA
#>
#region Setup work
$dcIp = 'x.x.x.x'
$domainCred = Get-Credential -UserName 'techsnips.local\abertram' -Message 'Domain Controller'
Enter-PSSession -Computer $dcIp -Credential $domainCred
#endregion
#region KDS root key
## Check for an existing KDS root key
Get-KdsRootKey
# quick way to get this done instead of waiting up to 10 hours
Add-KdsRootKey -EffectiveTime ((Get-Date).AddHours(-10))
## Command for production
# Add-KdsRootKey -EffectiveImmediately
## Test to ensure it's working
Test-KdsRootKey -KeyId (Get-KdsRootKey).KeyId
#endregion
#region Creating gMSAs
## Check for any existing gMSAs
Get-ADServiceAccount -Filter *
## Find the computer account the gMSA will be associated
$gMsaHost = Get-AdComputer -Identity 'CLIENT-PROD'
$msaName = 'lobService'
$params = @{
Name = $msaName
DNSHostName = 'lobService.techsnips.local'
PrincipalsAllowedToRetrieveManagedPassword = $gMsaHost
Enabled = $true
# ServicePrincipalNames = @('http/www', 'http/www.contoso.com')
# OtherAttributes @{ 'msDS-AllowedToDelegateTo' = 'http/backend' } ## Optional --to enable constrained delegation https://technet.microsoft.com/en-us/library/jj553400
}
New-AdServiceAccount @params
Get-ADServiceAccount -Filter *
#endregion
#region Associate the new MSA with a target computer in Active Directory
Add-ADComputerServiceAccount -Identity $gMsaHost -ServiceAccount $msaName
Get-ADComputerServiceAccount -Identity $gMsaHost
#endregion
#region Ensure the following prereqs are on the computer that's going to be using the MSA
# ## This verifies that the computer is eligible to host the gMSA, retrieves the credentials and stores the account information on the local computer
## Let's disconnect from the domain controller PSSession now and go into the client
$clientIp = 'x.x.x.x'
Enter-PSSession -ComputerName $clientIp -Credential $domainCred -Authentication Credssp
Install-ADServiceAccount -Identity 'lobService'
#endregion
#region Testing the MSA
Test-ADServiceAccount 'lobService'
#endregion
#region Run services under your MSA
## Create a dummy service
$serviceName = 'testservice'
New-Service -Name $serviceName -BinaryPathName "C:\WINDOWS\System32\svchost.exe -k netsvcs"
## Assign the gMSA to the service
$service = Get-Wmiobject Win32_Service -Filter "name='$serviceName'"
$invParams = $service.psbase.getMethodParameters('Change')
$invParams['StartName'] = 'techsnips.local\lobService$'
$invParams['StartPassword'] = $null
$service.InvokeMethod('Change',$invParams,$null)
Get-CimInstance -ClassName Win32_Service -Filter "name='$serviceName'" -Property StartName | Select-Object -Property StartName
#endregion
#region Removing a MSA
## Optionally, remove the service account from Active Directory. You can skip this step if you just want to reassign an existing MSA from one computer to another.
Remove-ADComputerServiceAccount –Identity (Get-AdComputer -Identity 'CLIENT-PROD') -ServiceAccount 'lobService'
## Remove the MSA
Remove-ADServiceAccount –Identity 'lobService'
#endregion | {
"pile_set_name": "Github"
} |
/*
*
* Copyright (c) International Business Machines Corp., 2001
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
* the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* NAME
* hugetlb.c
*
* DESCRIPTION
* common routines for the hugepage tests.
*
* The library contains the following routines:
*
* getipckey()
* getuserid()
* rm_shm()
*/
#define TST_NO_DEFAULT_MAIN
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/timeb.h>
#include <pwd.h>
#include "hugetlb.h"
key_t shmkey;
/*
* getipckey() - generates and returns a message key used by the "get"
* calls to create an IPC resource.
*/
int getipckey(void)
{
const char a = 'a';
int ascii_a = (int)a;
char *curdir = NULL;
size_t size = 0;
key_t ipc_key;
struct timeb time_info;
curdir = getcwd(curdir, size);
if (curdir == NULL)
tst_brk(TBROK | TERRNO, "getcwd(curdir)");
/*
* Get a Sys V IPC key
*
* ftok() requires a character as a second argument. This is
* refered to as a "project identifier" in the man page. In
* order to maximize the chance of getting a unique key, the
* project identifier is a "random character" produced by
* generating a random number between 0 and 25 and then adding
* that to the ascii value of 'a'. The "seed" for the random
* number is the millisecond value that is set in the timeb
* structure after calling ftime().
*/
ftime(&time_info);
srandom((unsigned int)time_info.millitm);
ipc_key = ftok(curdir, ascii_a + random() % 26);
if (ipc_key == -1)
tst_brk(TBROK | TERRNO, __func__);
return ipc_key;
}
/*
* getuserid() - return the integer value for the "user" id
*/
int getuserid(char *user)
{
struct passwd *ent;
ent = getpwnam(user);
if (ent == NULL)
tst_brk(TBROK | TERRNO, "getpwnam");
return ent->pw_uid;
}
/*
* rm_shm() - removes a shared memory segment.
*/
void rm_shm(int shm_id)
{
if (shm_id == -1)
return;
/*
* check for # of attaches ?
*/
if (shmctl(shm_id, IPC_RMID, NULL) == -1) {
tst_res(TINFO, "WARNING: shared memory deletion failed.");
tst_res(TINFO, "This could lead to IPC resource problems.");
tst_res(TINFO, "id = %d", shm_id);
}
}
| {
"pile_set_name": "Github"
} |
using System;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Cms
{
internal interface CmsSecureReadable
{
AlgorithmIdentifier Algorithm { get; }
object CryptoObject { get; }
CmsReadable GetReadable(KeyParameter key);
}
}
| {
"pile_set_name": "Github"
} |
/*
Copyright (C) 2010 Willow Garage <http://www.willowgarage.com>
Copyright (C) 2009 - 2010 Ivo van Doorn <[email protected]>
Copyright (C) 2009 Mattias Nissler <[email protected]>
Copyright (C) 2009 Felix Fietkau <[email protected]>
Copyright (C) 2009 Xose Vazquez Perez <[email protected]>
Copyright (C) 2009 Axel Kollhofer <[email protected]>
<http://rt2x00.serialmonkey.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
/*
Module: rt2800usb
Abstract: rt2800usb device specific routines.
Supported chipsets: RT2800U.
*/
#include <linux/delay.h>
#include <linux/etherdevice.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/usb.h>
#include "rt2x00.h"
#include "rt2x00usb.h"
#include "rt2800lib.h"
#include "rt2800.h"
#include "rt2800usb.h"
/*
* Allow hardware encryption to be disabled.
*/
static bool modparam_nohwcrypt;
module_param_named(nohwcrypt, modparam_nohwcrypt, bool, S_IRUGO);
MODULE_PARM_DESC(nohwcrypt, "Disable hardware encryption.");
static bool rt2800usb_hwcrypt_disabled(struct rt2x00_dev *rt2x00dev)
{
return modparam_nohwcrypt;
}
/*
* Queue handlers.
*/
static void rt2800usb_start_queue(struct data_queue *queue)
{
struct rt2x00_dev *rt2x00dev = queue->rt2x00dev;
u32 reg;
switch (queue->qid) {
case QID_RX:
reg = rt2x00usb_register_read(rt2x00dev, MAC_SYS_CTRL);
rt2x00_set_field32(®, MAC_SYS_CTRL_ENABLE_RX, 1);
rt2x00usb_register_write(rt2x00dev, MAC_SYS_CTRL, reg);
break;
case QID_BEACON:
reg = rt2x00usb_register_read(rt2x00dev, BCN_TIME_CFG);
rt2x00_set_field32(®, BCN_TIME_CFG_TSF_TICKING, 1);
rt2x00_set_field32(®, BCN_TIME_CFG_TBTT_ENABLE, 1);
rt2x00_set_field32(®, BCN_TIME_CFG_BEACON_GEN, 1);
rt2x00usb_register_write(rt2x00dev, BCN_TIME_CFG, reg);
break;
default:
break;
}
}
static void rt2800usb_stop_queue(struct data_queue *queue)
{
struct rt2x00_dev *rt2x00dev = queue->rt2x00dev;
u32 reg;
switch (queue->qid) {
case QID_RX:
reg = rt2x00usb_register_read(rt2x00dev, MAC_SYS_CTRL);
rt2x00_set_field32(®, MAC_SYS_CTRL_ENABLE_RX, 0);
rt2x00usb_register_write(rt2x00dev, MAC_SYS_CTRL, reg);
break;
case QID_BEACON:
reg = rt2x00usb_register_read(rt2x00dev, BCN_TIME_CFG);
rt2x00_set_field32(®, BCN_TIME_CFG_TSF_TICKING, 0);
rt2x00_set_field32(®, BCN_TIME_CFG_TBTT_ENABLE, 0);
rt2x00_set_field32(®, BCN_TIME_CFG_BEACON_GEN, 0);
rt2x00usb_register_write(rt2x00dev, BCN_TIME_CFG, reg);
break;
default:
break;
}
}
/*
* test if there is an entry in any TX queue for which DMA is done
* but the TX status has not been returned yet
*/
static bool rt2800usb_txstatus_pending(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
tx_queue_for_each(rt2x00dev, queue) {
if (rt2x00queue_get_entry(queue, Q_INDEX_DMA_DONE) !=
rt2x00queue_get_entry(queue, Q_INDEX_DONE))
return true;
}
return false;
}
static inline bool rt2800usb_entry_txstatus_timeout(struct queue_entry *entry)
{
bool tout;
if (!test_bit(ENTRY_DATA_STATUS_PENDING, &entry->flags))
return false;
tout = time_after(jiffies, entry->last_action + msecs_to_jiffies(500));
if (unlikely(tout))
rt2x00_dbg(entry->queue->rt2x00dev,
"TX status timeout for entry %d in queue %d\n",
entry->entry_idx, entry->queue->qid);
return tout;
}
static bool rt2800usb_txstatus_timeout(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
struct queue_entry *entry;
tx_queue_for_each(rt2x00dev, queue) {
entry = rt2x00queue_get_entry(queue, Q_INDEX_DONE);
if (rt2800usb_entry_txstatus_timeout(entry))
return true;
}
return false;
}
#define TXSTATUS_READ_INTERVAL 1000000
static bool rt2800usb_tx_sta_fifo_read_completed(struct rt2x00_dev *rt2x00dev,
int urb_status, u32 tx_status)
{
bool valid;
if (urb_status) {
rt2x00_warn(rt2x00dev, "TX status read failed %d\n",
urb_status);
goto stop_reading;
}
valid = rt2x00_get_field32(tx_status, TX_STA_FIFO_VALID);
if (valid) {
if (!kfifo_put(&rt2x00dev->txstatus_fifo, tx_status))
rt2x00_warn(rt2x00dev, "TX status FIFO overrun\n");
queue_work(rt2x00dev->workqueue, &rt2x00dev->txdone_work);
/* Reschedule urb to read TX status again instantly */
return true;
}
/* Check if there is any entry that timedout waiting on TX status */
if (rt2800usb_txstatus_timeout(rt2x00dev))
queue_work(rt2x00dev->workqueue, &rt2x00dev->txdone_work);
if (rt2800usb_txstatus_pending(rt2x00dev)) {
/* Read register after 1 ms */
hrtimer_start(&rt2x00dev->txstatus_timer,
TXSTATUS_READ_INTERVAL,
HRTIMER_MODE_REL);
return false;
}
stop_reading:
clear_bit(TX_STATUS_READING, &rt2x00dev->flags);
/*
* There is small race window above, between txstatus pending check and
* clear_bit someone could do rt2x00usb_interrupt_txdone, so recheck
* here again if status reading is needed.
*/
if (rt2800usb_txstatus_pending(rt2x00dev) &&
!test_and_set_bit(TX_STATUS_READING, &rt2x00dev->flags))
return true;
else
return false;
}
static void rt2800usb_async_read_tx_status(struct rt2x00_dev *rt2x00dev)
{
if (test_and_set_bit(TX_STATUS_READING, &rt2x00dev->flags))
return;
/* Read TX_STA_FIFO register after 2 ms */
hrtimer_start(&rt2x00dev->txstatus_timer,
2 * TXSTATUS_READ_INTERVAL,
HRTIMER_MODE_REL);
}
static void rt2800usb_tx_dma_done(struct queue_entry *entry)
{
struct rt2x00_dev *rt2x00dev = entry->queue->rt2x00dev;
rt2800usb_async_read_tx_status(rt2x00dev);
}
static enum hrtimer_restart rt2800usb_tx_sta_fifo_timeout(struct hrtimer *timer)
{
struct rt2x00_dev *rt2x00dev =
container_of(timer, struct rt2x00_dev, txstatus_timer);
rt2x00usb_register_read_async(rt2x00dev, TX_STA_FIFO,
rt2800usb_tx_sta_fifo_read_completed);
return HRTIMER_NORESTART;
}
/*
* Firmware functions
*/
static int rt2800usb_autorun_detect(struct rt2x00_dev *rt2x00dev)
{
__le32 *reg;
u32 fw_mode;
int ret;
reg = kmalloc(sizeof(*reg), GFP_KERNEL);
if (reg == NULL)
return -ENOMEM;
/* cannot use rt2x00usb_register_read here as it uses different
* mode (MULTI_READ vs. DEVICE_MODE) and does not pass the
* magic value USB_MODE_AUTORUN (0x11) to the device, thus the
* returned value would be invalid.
*/
ret = rt2x00usb_vendor_request(rt2x00dev, USB_DEVICE_MODE,
USB_VENDOR_REQUEST_IN, 0,
USB_MODE_AUTORUN, reg, sizeof(*reg),
REGISTER_TIMEOUT_FIRMWARE);
fw_mode = le32_to_cpu(*reg);
kfree(reg);
if (ret < 0)
return ret;
if ((fw_mode & 0x00000003) == 2)
return 1;
return 0;
}
static char *rt2800usb_get_firmware_name(struct rt2x00_dev *rt2x00dev)
{
return FIRMWARE_RT2870;
}
static int rt2800usb_write_firmware(struct rt2x00_dev *rt2x00dev,
const u8 *data, const size_t len)
{
int status;
u32 offset;
u32 length;
int retval;
/*
* Check which section of the firmware we need.
*/
if (rt2x00_rt(rt2x00dev, RT2860) ||
rt2x00_rt(rt2x00dev, RT2872) ||
rt2x00_rt(rt2x00dev, RT3070)) {
offset = 0;
length = 4096;
} else {
offset = 4096;
length = 4096;
}
/*
* Write firmware to device.
*/
retval = rt2800usb_autorun_detect(rt2x00dev);
if (retval < 0)
return retval;
if (retval) {
rt2x00_info(rt2x00dev,
"Firmware loading not required - NIC in AutoRun mode\n");
__clear_bit(REQUIRE_FIRMWARE, &rt2x00dev->cap_flags);
} else {
rt2x00usb_register_multiwrite(rt2x00dev, FIRMWARE_IMAGE_BASE,
data + offset, length);
}
rt2x00usb_register_write(rt2x00dev, H2M_MAILBOX_CID, ~0);
rt2x00usb_register_write(rt2x00dev, H2M_MAILBOX_STATUS, ~0);
/*
* Send firmware request to device to load firmware,
* we need to specify a long timeout time.
*/
status = rt2x00usb_vendor_request_sw(rt2x00dev, USB_DEVICE_MODE,
0, USB_MODE_FIRMWARE,
REGISTER_TIMEOUT_FIRMWARE);
if (status < 0) {
rt2x00_err(rt2x00dev, "Failed to write Firmware to device\n");
return status;
}
msleep(10);
rt2x00usb_register_write(rt2x00dev, H2M_MAILBOX_CSR, 0);
return 0;
}
/*
* Device state switch handlers.
*/
static int rt2800usb_init_registers(struct rt2x00_dev *rt2x00dev)
{
u32 reg;
/*
* Wait until BBP and RF are ready.
*/
if (rt2800_wait_csr_ready(rt2x00dev))
return -EBUSY;
reg = rt2x00usb_register_read(rt2x00dev, PBF_SYS_CTRL);
rt2x00usb_register_write(rt2x00dev, PBF_SYS_CTRL, reg & ~0x00002000);
reg = 0;
rt2x00_set_field32(®, MAC_SYS_CTRL_RESET_CSR, 1);
rt2x00_set_field32(®, MAC_SYS_CTRL_RESET_BBP, 1);
rt2x00usb_register_write(rt2x00dev, MAC_SYS_CTRL, reg);
rt2x00usb_vendor_request_sw(rt2x00dev, USB_DEVICE_MODE, 0,
USB_MODE_RESET, REGISTER_TIMEOUT);
rt2x00usb_register_write(rt2x00dev, MAC_SYS_CTRL, 0x00000000);
return 0;
}
static int rt2800usb_enable_radio(struct rt2x00_dev *rt2x00dev)
{
u32 reg = 0;
if (unlikely(rt2800_wait_wpdma_ready(rt2x00dev)))
return -EIO;
rt2x00_set_field32(®, USB_DMA_CFG_PHY_CLEAR, 0);
rt2x00_set_field32(®, USB_DMA_CFG_RX_BULK_AGG_EN, 0);
rt2x00_set_field32(®, USB_DMA_CFG_RX_BULK_AGG_TIMEOUT, 128);
/*
* Total room for RX frames in kilobytes, PBF might still exceed
* this limit so reduce the number to prevent errors.
*/
rt2x00_set_field32(®, USB_DMA_CFG_RX_BULK_AGG_LIMIT,
((rt2x00dev->rx->limit * DATA_FRAME_SIZE)
/ 1024) - 3);
rt2x00_set_field32(®, USB_DMA_CFG_RX_BULK_EN, 1);
rt2x00_set_field32(®, USB_DMA_CFG_TX_BULK_EN, 1);
rt2x00usb_register_write(rt2x00dev, USB_DMA_CFG, reg);
return rt2800_enable_radio(rt2x00dev);
}
static void rt2800usb_disable_radio(struct rt2x00_dev *rt2x00dev)
{
rt2800_disable_radio(rt2x00dev);
}
static int rt2800usb_set_state(struct rt2x00_dev *rt2x00dev,
enum dev_state state)
{
if (state == STATE_AWAKE)
rt2800_mcu_request(rt2x00dev, MCU_WAKEUP, 0xff, 0, 2);
else
rt2800_mcu_request(rt2x00dev, MCU_SLEEP, 0xff, 0xff, 2);
return 0;
}
static int rt2800usb_set_device_state(struct rt2x00_dev *rt2x00dev,
enum dev_state state)
{
int retval = 0;
switch (state) {
case STATE_RADIO_ON:
/*
* Before the radio can be enabled, the device first has
* to be woken up. After that it needs a bit of time
* to be fully awake and then the radio can be enabled.
*/
rt2800usb_set_state(rt2x00dev, STATE_AWAKE);
msleep(1);
retval = rt2800usb_enable_radio(rt2x00dev);
break;
case STATE_RADIO_OFF:
/*
* After the radio has been disabled, the device should
* be put to sleep for powersaving.
*/
rt2800usb_disable_radio(rt2x00dev);
rt2800usb_set_state(rt2x00dev, STATE_SLEEP);
break;
case STATE_RADIO_IRQ_ON:
case STATE_RADIO_IRQ_OFF:
/* No support, but no error either */
break;
case STATE_DEEP_SLEEP:
case STATE_SLEEP:
case STATE_STANDBY:
case STATE_AWAKE:
retval = rt2800usb_set_state(rt2x00dev, state);
break;
default:
retval = -ENOTSUPP;
break;
}
if (unlikely(retval))
rt2x00_err(rt2x00dev, "Device failed to enter state %d (%d)\n",
state, retval);
return retval;
}
/*
* TX descriptor initialization
*/
static __le32 *rt2800usb_get_txwi(struct queue_entry *entry)
{
if (entry->queue->qid == QID_BEACON)
return (__le32 *) (entry->skb->data);
else
return (__le32 *) (entry->skb->data + TXINFO_DESC_SIZE);
}
static void rt2800usb_write_tx_desc(struct queue_entry *entry,
struct txentry_desc *txdesc)
{
struct skb_frame_desc *skbdesc = get_skb_frame_desc(entry->skb);
__le32 *txi = (__le32 *) entry->skb->data;
u32 word;
/*
* Initialize TXINFO descriptor
*/
word = rt2x00_desc_read(txi, 0);
/*
* The size of TXINFO_W0_USB_DMA_TX_PKT_LEN is
* TXWI + 802.11 header + L2 pad + payload + pad,
* so need to decrease size of TXINFO.
*/
rt2x00_set_field32(&word, TXINFO_W0_USB_DMA_TX_PKT_LEN,
roundup(entry->skb->len, 4) - TXINFO_DESC_SIZE);
rt2x00_set_field32(&word, TXINFO_W0_WIV,
!test_bit(ENTRY_TXD_ENCRYPT_IV, &txdesc->flags));
rt2x00_set_field32(&word, TXINFO_W0_QSEL, 2);
rt2x00_set_field32(&word, TXINFO_W0_SW_USE_LAST_ROUND, 0);
rt2x00_set_field32(&word, TXINFO_W0_USB_DMA_NEXT_VALID, 0);
rt2x00_set_field32(&word, TXINFO_W0_USB_DMA_TX_BURST,
test_bit(ENTRY_TXD_BURST, &txdesc->flags));
rt2x00_desc_write(txi, 0, word);
/*
* Register descriptor details in skb frame descriptor.
*/
skbdesc->flags |= SKBDESC_DESC_IN_SKB;
skbdesc->desc = txi;
skbdesc->desc_len = TXINFO_DESC_SIZE + entry->queue->winfo_size;
}
/*
* TX data initialization
*/
static int rt2800usb_get_tx_data_len(struct queue_entry *entry)
{
/*
* pad(1~3 bytes) is needed after each 802.11 payload.
* USB end pad(4 bytes) is needed at each USB bulk out packet end.
* TX frame format is :
* | TXINFO | TXWI | 802.11 header | L2 pad | payload | pad | USB end pad |
* |<------------- tx_pkt_len ------------->|
*/
return roundup(entry->skb->len, 4) + 4;
}
/*
* TX control handlers
*/
static bool rt2800usb_txdone_entry_check(struct queue_entry *entry, u32 reg)
{
__le32 *txwi;
u32 word;
int wcid, ack, pid;
int tx_wcid, tx_ack, tx_pid, is_agg;
/*
* This frames has returned with an IO error,
* so the status report is not intended for this
* frame.
*/
if (test_bit(ENTRY_DATA_IO_FAILED, &entry->flags))
return false;
wcid = rt2x00_get_field32(reg, TX_STA_FIFO_WCID);
ack = rt2x00_get_field32(reg, TX_STA_FIFO_TX_ACK_REQUIRED);
pid = rt2x00_get_field32(reg, TX_STA_FIFO_PID_TYPE);
is_agg = rt2x00_get_field32(reg, TX_STA_FIFO_TX_AGGRE);
/*
* Validate if this TX status report is intended for
* this entry by comparing the WCID/ACK/PID fields.
*/
txwi = rt2800usb_get_txwi(entry);
word = rt2x00_desc_read(txwi, 1);
tx_wcid = rt2x00_get_field32(word, TXWI_W1_WIRELESS_CLI_ID);
tx_ack = rt2x00_get_field32(word, TXWI_W1_ACK);
tx_pid = rt2x00_get_field32(word, TXWI_W1_PACKETID);
if (wcid != tx_wcid || ack != tx_ack || (!is_agg && pid != tx_pid)) {
rt2x00_dbg(entry->queue->rt2x00dev,
"TX status report missed for queue %d entry %d\n",
entry->queue->qid, entry->entry_idx);
return false;
}
return true;
}
static void rt2800usb_txdone(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
struct queue_entry *entry;
u32 reg;
u8 qid;
bool match;
while (kfifo_get(&rt2x00dev->txstatus_fifo, ®)) {
/*
* TX_STA_FIFO_PID_QUEUE is a 2-bit field, thus qid is
* guaranteed to be one of the TX QIDs .
*/
qid = rt2x00_get_field32(reg, TX_STA_FIFO_PID_QUEUE);
queue = rt2x00queue_get_tx_queue(rt2x00dev, qid);
if (unlikely(rt2x00queue_empty(queue))) {
rt2x00_dbg(rt2x00dev, "Got TX status for an empty queue %u, dropping\n",
qid);
break;
}
entry = rt2x00queue_get_entry(queue, Q_INDEX_DONE);
if (unlikely(test_bit(ENTRY_OWNER_DEVICE_DATA, &entry->flags) ||
!test_bit(ENTRY_DATA_STATUS_PENDING, &entry->flags))) {
rt2x00_warn(rt2x00dev, "Data pending for entry %u in queue %u\n",
entry->entry_idx, qid);
break;
}
match = rt2800usb_txdone_entry_check(entry, reg);
rt2800_txdone_entry(entry, reg, rt2800usb_get_txwi(entry), match);
}
}
static void rt2800usb_txdone_nostatus(struct rt2x00_dev *rt2x00dev)
{
struct data_queue *queue;
struct queue_entry *entry;
/*
* Process any trailing TX status reports for IO failures,
* we loop until we find the first non-IO error entry. This
* can either be a frame which is free, is being uploaded,
* or has completed the upload but didn't have an entry
* in the TX_STAT_FIFO register yet.
*/
tx_queue_for_each(rt2x00dev, queue) {
while (!rt2x00queue_empty(queue)) {
entry = rt2x00queue_get_entry(queue, Q_INDEX_DONE);
if (test_bit(ENTRY_OWNER_DEVICE_DATA, &entry->flags) ||
!test_bit(ENTRY_DATA_STATUS_PENDING, &entry->flags))
break;
if (test_bit(ENTRY_DATA_IO_FAILED, &entry->flags) ||
rt2800usb_entry_txstatus_timeout(entry))
rt2x00lib_txdone_noinfo(entry, TXDONE_FAILURE);
else
break;
}
}
}
static void rt2800usb_work_txdone(struct work_struct *work)
{
struct rt2x00_dev *rt2x00dev =
container_of(work, struct rt2x00_dev, txdone_work);
while (!kfifo_is_empty(&rt2x00dev->txstatus_fifo) ||
rt2800usb_txstatus_timeout(rt2x00dev)) {
rt2800usb_txdone(rt2x00dev);
rt2800usb_txdone_nostatus(rt2x00dev);
/*
* The hw may delay sending the packet after DMA complete
* if the medium is busy, thus the TX_STA_FIFO entry is
* also delayed -> use a timer to retrieve it.
*/
if (rt2800usb_txstatus_pending(rt2x00dev))
rt2800usb_async_read_tx_status(rt2x00dev);
}
}
/*
* RX control handlers
*/
static void rt2800usb_fill_rxdone(struct queue_entry *entry,
struct rxdone_entry_desc *rxdesc)
{
struct skb_frame_desc *skbdesc = get_skb_frame_desc(entry->skb);
__le32 *rxi = (__le32 *)entry->skb->data;
__le32 *rxd;
u32 word;
int rx_pkt_len;
/*
* Copy descriptor to the skbdesc->desc buffer, making it safe from
* moving of frame data in rt2x00usb.
*/
memcpy(skbdesc->desc, rxi, skbdesc->desc_len);
/*
* RX frame format is :
* | RXINFO | RXWI | header | L2 pad | payload | pad | RXD | USB pad |
* |<------------ rx_pkt_len -------------->|
*/
word = rt2x00_desc_read(rxi, 0);
rx_pkt_len = rt2x00_get_field32(word, RXINFO_W0_USB_DMA_RX_PKT_LEN);
/*
* Remove the RXINFO structure from the sbk.
*/
skb_pull(entry->skb, RXINFO_DESC_SIZE);
/*
* Check for rx_pkt_len validity. Return if invalid, leaving
* rxdesc->size zeroed out by the upper level.
*/
if (unlikely(rx_pkt_len == 0 ||
rx_pkt_len > entry->queue->data_size)) {
rt2x00_err(entry->queue->rt2x00dev,
"Bad frame size %d, forcing to 0\n", rx_pkt_len);
return;
}
rxd = (__le32 *)(entry->skb->data + rx_pkt_len);
/*
* It is now safe to read the descriptor on all architectures.
*/
word = rt2x00_desc_read(rxd, 0);
if (rt2x00_get_field32(word, RXD_W0_CRC_ERROR))
rxdesc->flags |= RX_FLAG_FAILED_FCS_CRC;
rxdesc->cipher_status = rt2x00_get_field32(word, RXD_W0_CIPHER_ERROR);
if (rt2x00_get_field32(word, RXD_W0_DECRYPTED)) {
/*
* Hardware has stripped IV/EIV data from 802.11 frame during
* decryption. Unfortunately the descriptor doesn't contain
* any fields with the EIV/IV data either, so they can't
* be restored by rt2x00lib.
*/
rxdesc->flags |= RX_FLAG_IV_STRIPPED;
/*
* The hardware has already checked the Michael Mic and has
* stripped it from the frame. Signal this to mac80211.
*/
rxdesc->flags |= RX_FLAG_MMIC_STRIPPED;
if (rxdesc->cipher_status == RX_CRYPTO_SUCCESS) {
rxdesc->flags |= RX_FLAG_DECRYPTED;
} else if (rxdesc->cipher_status == RX_CRYPTO_FAIL_MIC) {
/*
* In order to check the Michael Mic, the packet must have
* been decrypted. Mac80211 doesnt check the MMIC failure
* flag to initiate MMIC countermeasures if the decoded flag
* has not been set.
*/
rxdesc->flags |= RX_FLAG_DECRYPTED;
rxdesc->flags |= RX_FLAG_MMIC_ERROR;
}
}
if (rt2x00_get_field32(word, RXD_W0_MY_BSS))
rxdesc->dev_flags |= RXDONE_MY_BSS;
if (rt2x00_get_field32(word, RXD_W0_L2PAD))
rxdesc->dev_flags |= RXDONE_L2PAD;
/*
* Remove RXD descriptor from end of buffer.
*/
skb_trim(entry->skb, rx_pkt_len);
/*
* Process the RXWI structure.
*/
rt2800_process_rxwi(entry, rxdesc);
}
/*
* Device probe functions.
*/
static int rt2800usb_efuse_detect(struct rt2x00_dev *rt2x00dev)
{
int retval;
retval = rt2800usb_autorun_detect(rt2x00dev);
if (retval < 0)
return retval;
if (retval)
return 1;
return rt2800_efuse_detect(rt2x00dev);
}
static int rt2800usb_read_eeprom(struct rt2x00_dev *rt2x00dev)
{
int retval;
retval = rt2800usb_efuse_detect(rt2x00dev);
if (retval < 0)
return retval;
if (retval)
retval = rt2800_read_eeprom_efuse(rt2x00dev);
else
retval = rt2x00usb_eeprom_read(rt2x00dev, rt2x00dev->eeprom,
EEPROM_SIZE);
return retval;
}
static int rt2800usb_probe_hw(struct rt2x00_dev *rt2x00dev)
{
int retval;
retval = rt2800_probe_hw(rt2x00dev);
if (retval)
return retval;
/*
* Set txstatus timer function.
*/
rt2x00dev->txstatus_timer.function = rt2800usb_tx_sta_fifo_timeout;
/*
* Overwrite TX done handler
*/
INIT_WORK(&rt2x00dev->txdone_work, rt2800usb_work_txdone);
return 0;
}
static const struct ieee80211_ops rt2800usb_mac80211_ops = {
.tx = rt2x00mac_tx,
.start = rt2x00mac_start,
.stop = rt2x00mac_stop,
.add_interface = rt2x00mac_add_interface,
.remove_interface = rt2x00mac_remove_interface,
.config = rt2x00mac_config,
.configure_filter = rt2x00mac_configure_filter,
.set_tim = rt2x00mac_set_tim,
.set_key = rt2x00mac_set_key,
.sw_scan_start = rt2x00mac_sw_scan_start,
.sw_scan_complete = rt2x00mac_sw_scan_complete,
.get_stats = rt2x00mac_get_stats,
.get_key_seq = rt2800_get_key_seq,
.set_rts_threshold = rt2800_set_rts_threshold,
.sta_add = rt2x00mac_sta_add,
.sta_remove = rt2x00mac_sta_remove,
.bss_info_changed = rt2x00mac_bss_info_changed,
.conf_tx = rt2800_conf_tx,
.get_tsf = rt2800_get_tsf,
.rfkill_poll = rt2x00mac_rfkill_poll,
.ampdu_action = rt2800_ampdu_action,
.flush = rt2x00mac_flush,
.get_survey = rt2800_get_survey,
.get_ringparam = rt2x00mac_get_ringparam,
.tx_frames_pending = rt2x00mac_tx_frames_pending,
};
static const struct rt2800_ops rt2800usb_rt2800_ops = {
.register_read = rt2x00usb_register_read,
.register_read_lock = rt2x00usb_register_read_lock,
.register_write = rt2x00usb_register_write,
.register_write_lock = rt2x00usb_register_write_lock,
.register_multiread = rt2x00usb_register_multiread,
.register_multiwrite = rt2x00usb_register_multiwrite,
.regbusy_read = rt2x00usb_regbusy_read,
.read_eeprom = rt2800usb_read_eeprom,
.hwcrypt_disabled = rt2800usb_hwcrypt_disabled,
.drv_write_firmware = rt2800usb_write_firmware,
.drv_init_registers = rt2800usb_init_registers,
.drv_get_txwi = rt2800usb_get_txwi,
};
static const struct rt2x00lib_ops rt2800usb_rt2x00_ops = {
.probe_hw = rt2800usb_probe_hw,
.get_firmware_name = rt2800usb_get_firmware_name,
.check_firmware = rt2800_check_firmware,
.load_firmware = rt2800_load_firmware,
.initialize = rt2x00usb_initialize,
.uninitialize = rt2x00usb_uninitialize,
.clear_entry = rt2x00usb_clear_entry,
.set_device_state = rt2800usb_set_device_state,
.rfkill_poll = rt2800_rfkill_poll,
.link_stats = rt2800_link_stats,
.reset_tuner = rt2800_reset_tuner,
.link_tuner = rt2800_link_tuner,
.gain_calibration = rt2800_gain_calibration,
.vco_calibration = rt2800_vco_calibration,
.start_queue = rt2800usb_start_queue,
.kick_queue = rt2x00usb_kick_queue,
.stop_queue = rt2800usb_stop_queue,
.flush_queue = rt2x00usb_flush_queue,
.tx_dma_done = rt2800usb_tx_dma_done,
.write_tx_desc = rt2800usb_write_tx_desc,
.write_tx_data = rt2800_write_tx_data,
.write_beacon = rt2800_write_beacon,
.clear_beacon = rt2800_clear_beacon,
.get_tx_data_len = rt2800usb_get_tx_data_len,
.fill_rxdone = rt2800usb_fill_rxdone,
.config_shared_key = rt2800_config_shared_key,
.config_pairwise_key = rt2800_config_pairwise_key,
.config_filter = rt2800_config_filter,
.config_intf = rt2800_config_intf,
.config_erp = rt2800_config_erp,
.config_ant = rt2800_config_ant,
.config = rt2800_config,
.sta_add = rt2800_sta_add,
.sta_remove = rt2800_sta_remove,
};
static void rt2800usb_queue_init(struct data_queue *queue)
{
struct rt2x00_dev *rt2x00dev = queue->rt2x00dev;
unsigned short txwi_size, rxwi_size;
rt2800_get_txwi_rxwi_size(rt2x00dev, &txwi_size, &rxwi_size);
switch (queue->qid) {
case QID_RX:
queue->limit = 128;
queue->data_size = AGGREGATION_SIZE;
queue->desc_size = RXINFO_DESC_SIZE;
queue->winfo_size = rxwi_size;
queue->priv_size = sizeof(struct queue_entry_priv_usb);
break;
case QID_AC_VO:
case QID_AC_VI:
case QID_AC_BE:
case QID_AC_BK:
queue->limit = 16;
queue->data_size = AGGREGATION_SIZE;
queue->desc_size = TXINFO_DESC_SIZE;
queue->winfo_size = txwi_size;
queue->priv_size = sizeof(struct queue_entry_priv_usb);
break;
case QID_BEACON:
queue->limit = 8;
queue->data_size = MGMT_FRAME_SIZE;
queue->desc_size = TXINFO_DESC_SIZE;
queue->winfo_size = txwi_size;
queue->priv_size = sizeof(struct queue_entry_priv_usb);
break;
case QID_ATIM:
/* fallthrough */
default:
BUG();
break;
}
}
static const struct rt2x00_ops rt2800usb_ops = {
.name = KBUILD_MODNAME,
.drv_data_size = sizeof(struct rt2800_drv_data),
.max_ap_intf = 8,
.eeprom_size = EEPROM_SIZE,
.rf_size = RF_SIZE,
.tx_queues = NUM_TX_QUEUES,
.queue_init = rt2800usb_queue_init,
.lib = &rt2800usb_rt2x00_ops,
.drv = &rt2800usb_rt2800_ops,
.hw = &rt2800usb_mac80211_ops,
#ifdef CONFIG_RT2X00_LIB_DEBUGFS
.debugfs = &rt2800_rt2x00debug,
#endif /* CONFIG_RT2X00_LIB_DEBUGFS */
};
/*
* rt2800usb module information.
*/
static const struct usb_device_id rt2800usb_device_table[] = {
/* Abocom */
{ USB_DEVICE(0x07b8, 0x2870) },
{ USB_DEVICE(0x07b8, 0x2770) },
{ USB_DEVICE(0x07b8, 0x3070) },
{ USB_DEVICE(0x07b8, 0x3071) },
{ USB_DEVICE(0x07b8, 0x3072) },
{ USB_DEVICE(0x1482, 0x3c09) },
/* AirTies */
{ USB_DEVICE(0x1eda, 0x2012) },
{ USB_DEVICE(0x1eda, 0x2210) },
{ USB_DEVICE(0x1eda, 0x2310) },
/* Allwin */
{ USB_DEVICE(0x8516, 0x2070) },
{ USB_DEVICE(0x8516, 0x2770) },
{ USB_DEVICE(0x8516, 0x2870) },
{ USB_DEVICE(0x8516, 0x3070) },
{ USB_DEVICE(0x8516, 0x3071) },
{ USB_DEVICE(0x8516, 0x3072) },
/* Alpha Networks */
{ USB_DEVICE(0x14b2, 0x3c06) },
{ USB_DEVICE(0x14b2, 0x3c07) },
{ USB_DEVICE(0x14b2, 0x3c09) },
{ USB_DEVICE(0x14b2, 0x3c12) },
{ USB_DEVICE(0x14b2, 0x3c23) },
{ USB_DEVICE(0x14b2, 0x3c25) },
{ USB_DEVICE(0x14b2, 0x3c27) },
{ USB_DEVICE(0x14b2, 0x3c28) },
{ USB_DEVICE(0x14b2, 0x3c2c) },
/* Amit */
{ USB_DEVICE(0x15c5, 0x0008) },
/* Askey */
{ USB_DEVICE(0x1690, 0x0740) },
/* ASUS */
{ USB_DEVICE(0x0b05, 0x1731) },
{ USB_DEVICE(0x0b05, 0x1732) },
{ USB_DEVICE(0x0b05, 0x1742) },
{ USB_DEVICE(0x0b05, 0x1784) },
{ USB_DEVICE(0x1761, 0x0b05) },
/* AzureWave */
{ USB_DEVICE(0x13d3, 0x3247) },
{ USB_DEVICE(0x13d3, 0x3273) },
{ USB_DEVICE(0x13d3, 0x3305) },
{ USB_DEVICE(0x13d3, 0x3307) },
{ USB_DEVICE(0x13d3, 0x3321) },
/* Belkin */
{ USB_DEVICE(0x050d, 0x8053) },
{ USB_DEVICE(0x050d, 0x805c) },
{ USB_DEVICE(0x050d, 0x815c) },
{ USB_DEVICE(0x050d, 0x825a) },
{ USB_DEVICE(0x050d, 0x825b) },
{ USB_DEVICE(0x050d, 0x935a) },
{ USB_DEVICE(0x050d, 0x935b) },
/* Buffalo */
{ USB_DEVICE(0x0411, 0x00e8) },
{ USB_DEVICE(0x0411, 0x0158) },
{ USB_DEVICE(0x0411, 0x015d) },
{ USB_DEVICE(0x0411, 0x016f) },
{ USB_DEVICE(0x0411, 0x01a2) },
{ USB_DEVICE(0x0411, 0x01ee) },
{ USB_DEVICE(0x0411, 0x01a8) },
{ USB_DEVICE(0x0411, 0x01fd) },
/* Corega */
{ USB_DEVICE(0x07aa, 0x002f) },
{ USB_DEVICE(0x07aa, 0x003c) },
{ USB_DEVICE(0x07aa, 0x003f) },
{ USB_DEVICE(0x18c5, 0x0012) },
/* D-Link */
{ USB_DEVICE(0x07d1, 0x3c09) },
{ USB_DEVICE(0x07d1, 0x3c0a) },
{ USB_DEVICE(0x07d1, 0x3c0d) },
{ USB_DEVICE(0x07d1, 0x3c0e) },
{ USB_DEVICE(0x07d1, 0x3c0f) },
{ USB_DEVICE(0x07d1, 0x3c11) },
{ USB_DEVICE(0x07d1, 0x3c13) },
{ USB_DEVICE(0x07d1, 0x3c15) },
{ USB_DEVICE(0x07d1, 0x3c16) },
{ USB_DEVICE(0x07d1, 0x3c17) },
{ USB_DEVICE(0x2001, 0x3317) },
{ USB_DEVICE(0x2001, 0x3c1b) },
{ USB_DEVICE(0x2001, 0x3c25) },
/* Draytek */
{ USB_DEVICE(0x07fa, 0x7712) },
/* DVICO */
{ USB_DEVICE(0x0fe9, 0xb307) },
/* Edimax */
{ USB_DEVICE(0x7392, 0x4085) },
{ USB_DEVICE(0x7392, 0x7711) },
{ USB_DEVICE(0x7392, 0x7717) },
{ USB_DEVICE(0x7392, 0x7718) },
{ USB_DEVICE(0x7392, 0x7722) },
/* Encore */
{ USB_DEVICE(0x203d, 0x1480) },
{ USB_DEVICE(0x203d, 0x14a9) },
/* EnGenius */
{ USB_DEVICE(0x1740, 0x9701) },
{ USB_DEVICE(0x1740, 0x9702) },
{ USB_DEVICE(0x1740, 0x9703) },
{ USB_DEVICE(0x1740, 0x9705) },
{ USB_DEVICE(0x1740, 0x9706) },
{ USB_DEVICE(0x1740, 0x9707) },
{ USB_DEVICE(0x1740, 0x9708) },
{ USB_DEVICE(0x1740, 0x9709) },
/* Gemtek */
{ USB_DEVICE(0x15a9, 0x0012) },
/* Gigabyte */
{ USB_DEVICE(0x1044, 0x800b) },
{ USB_DEVICE(0x1044, 0x800d) },
/* Hawking */
{ USB_DEVICE(0x0e66, 0x0001) },
{ USB_DEVICE(0x0e66, 0x0003) },
{ USB_DEVICE(0x0e66, 0x0009) },
{ USB_DEVICE(0x0e66, 0x000b) },
{ USB_DEVICE(0x0e66, 0x0013) },
{ USB_DEVICE(0x0e66, 0x0017) },
{ USB_DEVICE(0x0e66, 0x0018) },
/* I-O DATA */
{ USB_DEVICE(0x04bb, 0x0945) },
{ USB_DEVICE(0x04bb, 0x0947) },
{ USB_DEVICE(0x04bb, 0x0948) },
/* Linksys */
{ USB_DEVICE(0x13b1, 0x0031) },
{ USB_DEVICE(0x1737, 0x0070) },
{ USB_DEVICE(0x1737, 0x0071) },
{ USB_DEVICE(0x1737, 0x0077) },
{ USB_DEVICE(0x1737, 0x0078) },
/* Logitec */
{ USB_DEVICE(0x0789, 0x0162) },
{ USB_DEVICE(0x0789, 0x0163) },
{ USB_DEVICE(0x0789, 0x0164) },
{ USB_DEVICE(0x0789, 0x0166) },
/* Motorola */
{ USB_DEVICE(0x100d, 0x9031) },
/* MSI */
{ USB_DEVICE(0x0db0, 0x3820) },
{ USB_DEVICE(0x0db0, 0x3821) },
{ USB_DEVICE(0x0db0, 0x3822) },
{ USB_DEVICE(0x0db0, 0x3870) },
{ USB_DEVICE(0x0db0, 0x3871) },
{ USB_DEVICE(0x0db0, 0x6899) },
{ USB_DEVICE(0x0db0, 0x821a) },
{ USB_DEVICE(0x0db0, 0x822a) },
{ USB_DEVICE(0x0db0, 0x822b) },
{ USB_DEVICE(0x0db0, 0x822c) },
{ USB_DEVICE(0x0db0, 0x870a) },
{ USB_DEVICE(0x0db0, 0x871a) },
{ USB_DEVICE(0x0db0, 0x871b) },
{ USB_DEVICE(0x0db0, 0x871c) },
{ USB_DEVICE(0x0db0, 0x899a) },
/* Ovislink */
{ USB_DEVICE(0x1b75, 0x3070) },
{ USB_DEVICE(0x1b75, 0x3071) },
{ USB_DEVICE(0x1b75, 0x3072) },
{ USB_DEVICE(0x1b75, 0xa200) },
/* Para */
{ USB_DEVICE(0x20b8, 0x8888) },
/* Pegatron */
{ USB_DEVICE(0x1d4d, 0x0002) },
{ USB_DEVICE(0x1d4d, 0x000c) },
{ USB_DEVICE(0x1d4d, 0x000e) },
{ USB_DEVICE(0x1d4d, 0x0011) },
/* Philips */
{ USB_DEVICE(0x0471, 0x200f) },
/* Planex */
{ USB_DEVICE(0x2019, 0x5201) },
{ USB_DEVICE(0x2019, 0xab25) },
{ USB_DEVICE(0x2019, 0xed06) },
/* Quanta */
{ USB_DEVICE(0x1a32, 0x0304) },
/* Ralink */
{ USB_DEVICE(0x148f, 0x2070) },
{ USB_DEVICE(0x148f, 0x2770) },
{ USB_DEVICE(0x148f, 0x2870) },
{ USB_DEVICE(0x148f, 0x3070) },
{ USB_DEVICE(0x148f, 0x3071) },
{ USB_DEVICE(0x148f, 0x3072) },
/* Samsung */
{ USB_DEVICE(0x04e8, 0x2018) },
/* Siemens */
{ USB_DEVICE(0x129b, 0x1828) },
/* Sitecom */
{ USB_DEVICE(0x0df6, 0x0017) },
{ USB_DEVICE(0x0df6, 0x002b) },
{ USB_DEVICE(0x0df6, 0x002c) },
{ USB_DEVICE(0x0df6, 0x002d) },
{ USB_DEVICE(0x0df6, 0x0039) },
{ USB_DEVICE(0x0df6, 0x003b) },
{ USB_DEVICE(0x0df6, 0x003d) },
{ USB_DEVICE(0x0df6, 0x003e) },
{ USB_DEVICE(0x0df6, 0x003f) },
{ USB_DEVICE(0x0df6, 0x0040) },
{ USB_DEVICE(0x0df6, 0x0042) },
{ USB_DEVICE(0x0df6, 0x0047) },
{ USB_DEVICE(0x0df6, 0x0048) },
{ USB_DEVICE(0x0df6, 0x0051) },
{ USB_DEVICE(0x0df6, 0x005f) },
{ USB_DEVICE(0x0df6, 0x0060) },
/* SMC */
{ USB_DEVICE(0x083a, 0x6618) },
{ USB_DEVICE(0x083a, 0x7511) },
{ USB_DEVICE(0x083a, 0x7512) },
{ USB_DEVICE(0x083a, 0x7522) },
{ USB_DEVICE(0x083a, 0x8522) },
{ USB_DEVICE(0x083a, 0xa618) },
{ USB_DEVICE(0x083a, 0xa701) },
{ USB_DEVICE(0x083a, 0xa702) },
{ USB_DEVICE(0x083a, 0xa703) },
{ USB_DEVICE(0x083a, 0xb522) },
/* Sparklan */
{ USB_DEVICE(0x15a9, 0x0006) },
/* Sweex */
{ USB_DEVICE(0x177f, 0x0153) },
{ USB_DEVICE(0x177f, 0x0164) },
{ USB_DEVICE(0x177f, 0x0302) },
{ USB_DEVICE(0x177f, 0x0313) },
{ USB_DEVICE(0x177f, 0x0323) },
{ USB_DEVICE(0x177f, 0x0324) },
/* U-Media */
{ USB_DEVICE(0x157e, 0x300e) },
{ USB_DEVICE(0x157e, 0x3013) },
/* ZCOM */
{ USB_DEVICE(0x0cde, 0x0022) },
{ USB_DEVICE(0x0cde, 0x0025) },
/* Zinwell */
{ USB_DEVICE(0x5a57, 0x0280) },
{ USB_DEVICE(0x5a57, 0x0282) },
{ USB_DEVICE(0x5a57, 0x0283) },
{ USB_DEVICE(0x5a57, 0x5257) },
/* Zyxel */
{ USB_DEVICE(0x0586, 0x3416) },
{ USB_DEVICE(0x0586, 0x3418) },
{ USB_DEVICE(0x0586, 0x341a) },
{ USB_DEVICE(0x0586, 0x341e) },
{ USB_DEVICE(0x0586, 0x343e) },
#ifdef CONFIG_RT2800USB_RT33XX
/* Belkin */
{ USB_DEVICE(0x050d, 0x945b) },
/* D-Link */
{ USB_DEVICE(0x2001, 0x3c17) },
/* Panasonic */
{ USB_DEVICE(0x083a, 0xb511) },
/* Accton/Arcadyan/Epson */
{ USB_DEVICE(0x083a, 0xb512) },
/* Philips */
{ USB_DEVICE(0x0471, 0x20dd) },
/* Ralink */
{ USB_DEVICE(0x148f, 0x3370) },
{ USB_DEVICE(0x148f, 0x8070) },
/* Sitecom */
{ USB_DEVICE(0x0df6, 0x0050) },
/* Sweex */
{ USB_DEVICE(0x177f, 0x0163) },
{ USB_DEVICE(0x177f, 0x0165) },
#endif
#ifdef CONFIG_RT2800USB_RT35XX
/* Allwin */
{ USB_DEVICE(0x8516, 0x3572) },
/* Askey */
{ USB_DEVICE(0x1690, 0x0744) },
{ USB_DEVICE(0x1690, 0x0761) },
{ USB_DEVICE(0x1690, 0x0764) },
/* ASUS */
{ USB_DEVICE(0x0b05, 0x179d) },
/* Cisco */
{ USB_DEVICE(0x167b, 0x4001) },
/* EnGenius */
{ USB_DEVICE(0x1740, 0x9801) },
/* I-O DATA */
{ USB_DEVICE(0x04bb, 0x0944) },
/* Linksys */
{ USB_DEVICE(0x13b1, 0x002f) },
{ USB_DEVICE(0x1737, 0x0079) },
/* Logitec */
{ USB_DEVICE(0x0789, 0x0170) },
/* Ralink */
{ USB_DEVICE(0x148f, 0x3572) },
/* Sitecom */
{ USB_DEVICE(0x0df6, 0x0041) },
{ USB_DEVICE(0x0df6, 0x0062) },
{ USB_DEVICE(0x0df6, 0x0065) },
{ USB_DEVICE(0x0df6, 0x0066) },
{ USB_DEVICE(0x0df6, 0x0068) },
/* Toshiba */
{ USB_DEVICE(0x0930, 0x0a07) },
/* Zinwell */
{ USB_DEVICE(0x5a57, 0x0284) },
#endif
#ifdef CONFIG_RT2800USB_RT3573
/* AirLive */
{ USB_DEVICE(0x1b75, 0x7733) },
/* ASUS */
{ USB_DEVICE(0x0b05, 0x17bc) },
{ USB_DEVICE(0x0b05, 0x17ad) },
/* Belkin */
{ USB_DEVICE(0x050d, 0x1103) },
/* Cameo */
{ USB_DEVICE(0x148f, 0xf301) },
/* D-Link */
{ USB_DEVICE(0x2001, 0x3c1f) },
/* Edimax */
{ USB_DEVICE(0x7392, 0x7733) },
/* Hawking */
{ USB_DEVICE(0x0e66, 0x0020) },
{ USB_DEVICE(0x0e66, 0x0021) },
/* I-O DATA */
{ USB_DEVICE(0x04bb, 0x094e) },
/* Linksys */
{ USB_DEVICE(0x13b1, 0x003b) },
/* Logitec */
{ USB_DEVICE(0x0789, 0x016b) },
/* NETGEAR */
{ USB_DEVICE(0x0846, 0x9012) },
{ USB_DEVICE(0x0846, 0x9013) },
{ USB_DEVICE(0x0846, 0x9019) },
/* Planex */
{ USB_DEVICE(0x2019, 0xed19) },
/* Ralink */
{ USB_DEVICE(0x148f, 0x3573) },
/* Sitecom */
{ USB_DEVICE(0x0df6, 0x0067) },
{ USB_DEVICE(0x0df6, 0x006a) },
{ USB_DEVICE(0x0df6, 0x006e) },
/* ZyXEL */
{ USB_DEVICE(0x0586, 0x3421) },
#endif
#ifdef CONFIG_RT2800USB_RT53XX
/* Arcadyan */
{ USB_DEVICE(0x043e, 0x7a12) },
{ USB_DEVICE(0x043e, 0x7a32) },
/* ASUS */
{ USB_DEVICE(0x0b05, 0x17e8) },
/* Azurewave */
{ USB_DEVICE(0x13d3, 0x3329) },
{ USB_DEVICE(0x13d3, 0x3365) },
/* D-Link */
{ USB_DEVICE(0x2001, 0x3c15) },
{ USB_DEVICE(0x2001, 0x3c19) },
{ USB_DEVICE(0x2001, 0x3c1c) },
{ USB_DEVICE(0x2001, 0x3c1d) },
{ USB_DEVICE(0x2001, 0x3c1e) },
{ USB_DEVICE(0x2001, 0x3c20) },
{ USB_DEVICE(0x2001, 0x3c22) },
{ USB_DEVICE(0x2001, 0x3c23) },
/* LG innotek */
{ USB_DEVICE(0x043e, 0x7a22) },
{ USB_DEVICE(0x043e, 0x7a42) },
/* Panasonic */
{ USB_DEVICE(0x04da, 0x1801) },
{ USB_DEVICE(0x04da, 0x1800) },
{ USB_DEVICE(0x04da, 0x23f6) },
/* Philips */
{ USB_DEVICE(0x0471, 0x2104) },
{ USB_DEVICE(0x0471, 0x2126) },
{ USB_DEVICE(0x0471, 0x2180) },
{ USB_DEVICE(0x0471, 0x2181) },
{ USB_DEVICE(0x0471, 0x2182) },
/* Ralink */
{ USB_DEVICE(0x148f, 0x5370) },
{ USB_DEVICE(0x148f, 0x5372) },
#endif
#ifdef CONFIG_RT2800USB_RT55XX
/* Arcadyan */
{ USB_DEVICE(0x043e, 0x7a32) },
/* AVM GmbH */
{ USB_DEVICE(0x057c, 0x8501) },
/* Buffalo */
{ USB_DEVICE(0x0411, 0x0241) },
{ USB_DEVICE(0x0411, 0x0253) },
/* D-Link */
{ USB_DEVICE(0x2001, 0x3c1a) },
{ USB_DEVICE(0x2001, 0x3c21) },
/* Proware */
{ USB_DEVICE(0x043e, 0x7a13) },
/* Ralink */
{ USB_DEVICE(0x148f, 0x5572) },
/* TRENDnet */
{ USB_DEVICE(0x20f4, 0x724a) },
#endif
#ifdef CONFIG_RT2800USB_UNKNOWN
/*
* Unclear what kind of devices these are (they aren't supported by the
* vendor linux driver).
*/
/* Abocom */
{ USB_DEVICE(0x07b8, 0x3073) },
{ USB_DEVICE(0x07b8, 0x3074) },
/* Alpha Networks */
{ USB_DEVICE(0x14b2, 0x3c08) },
{ USB_DEVICE(0x14b2, 0x3c11) },
/* Amigo */
{ USB_DEVICE(0x0e0b, 0x9031) },
{ USB_DEVICE(0x0e0b, 0x9041) },
/* ASUS */
{ USB_DEVICE(0x0b05, 0x166a) },
{ USB_DEVICE(0x0b05, 0x1760) },
{ USB_DEVICE(0x0b05, 0x1761) },
{ USB_DEVICE(0x0b05, 0x1790) },
{ USB_DEVICE(0x0b05, 0x17a7) },
/* AzureWave */
{ USB_DEVICE(0x13d3, 0x3262) },
{ USB_DEVICE(0x13d3, 0x3284) },
{ USB_DEVICE(0x13d3, 0x3322) },
{ USB_DEVICE(0x13d3, 0x3340) },
{ USB_DEVICE(0x13d3, 0x3399) },
{ USB_DEVICE(0x13d3, 0x3400) },
{ USB_DEVICE(0x13d3, 0x3401) },
/* Belkin */
{ USB_DEVICE(0x050d, 0x1003) },
/* Buffalo */
{ USB_DEVICE(0x0411, 0x012e) },
{ USB_DEVICE(0x0411, 0x0148) },
{ USB_DEVICE(0x0411, 0x0150) },
/* Corega */
{ USB_DEVICE(0x07aa, 0x0041) },
{ USB_DEVICE(0x07aa, 0x0042) },
{ USB_DEVICE(0x18c5, 0x0008) },
/* D-Link */
{ USB_DEVICE(0x07d1, 0x3c0b) },
/* Encore */
{ USB_DEVICE(0x203d, 0x14a1) },
/* EnGenius */
{ USB_DEVICE(0x1740, 0x0600) },
{ USB_DEVICE(0x1740, 0x0602) },
/* Gemtek */
{ USB_DEVICE(0x15a9, 0x0010) },
/* Gigabyte */
{ USB_DEVICE(0x1044, 0x800c) },
/* Hercules */
{ USB_DEVICE(0x06f8, 0xe036) },
/* Huawei */
{ USB_DEVICE(0x148f, 0xf101) },
/* I-O DATA */
{ USB_DEVICE(0x04bb, 0x094b) },
/* LevelOne */
{ USB_DEVICE(0x1740, 0x0605) },
{ USB_DEVICE(0x1740, 0x0615) },
/* Logitec */
{ USB_DEVICE(0x0789, 0x0168) },
{ USB_DEVICE(0x0789, 0x0169) },
/* Motorola */
{ USB_DEVICE(0x100d, 0x9032) },
/* Pegatron */
{ USB_DEVICE(0x05a6, 0x0101) },
{ USB_DEVICE(0x1d4d, 0x0010) },
/* Planex */
{ USB_DEVICE(0x2019, 0xab24) },
{ USB_DEVICE(0x2019, 0xab29) },
/* Qcom */
{ USB_DEVICE(0x18e8, 0x6259) },
/* RadioShack */
{ USB_DEVICE(0x08b9, 0x1197) },
/* Sitecom */
{ USB_DEVICE(0x0df6, 0x003c) },
{ USB_DEVICE(0x0df6, 0x004a) },
{ USB_DEVICE(0x0df6, 0x004d) },
{ USB_DEVICE(0x0df6, 0x0053) },
{ USB_DEVICE(0x0df6, 0x0069) },
{ USB_DEVICE(0x0df6, 0x006f) },
{ USB_DEVICE(0x0df6, 0x0078) },
/* SMC */
{ USB_DEVICE(0x083a, 0xa512) },
{ USB_DEVICE(0x083a, 0xc522) },
{ USB_DEVICE(0x083a, 0xd522) },
{ USB_DEVICE(0x083a, 0xf511) },
/* Sweex */
{ USB_DEVICE(0x177f, 0x0254) },
/* TP-LINK */
{ USB_DEVICE(0xf201, 0x5370) },
#endif
{ 0, }
};
MODULE_AUTHOR(DRV_PROJECT);
MODULE_VERSION(DRV_VERSION);
MODULE_DESCRIPTION("Ralink RT2800 USB Wireless LAN driver.");
MODULE_SUPPORTED_DEVICE("Ralink RT2870 USB chipset based cards");
MODULE_DEVICE_TABLE(usb, rt2800usb_device_table);
MODULE_FIRMWARE(FIRMWARE_RT2870);
MODULE_LICENSE("GPL");
static int rt2800usb_probe(struct usb_interface *usb_intf,
const struct usb_device_id *id)
{
return rt2x00usb_probe(usb_intf, &rt2800usb_ops);
}
static struct usb_driver rt2800usb_driver = {
.name = KBUILD_MODNAME,
.id_table = rt2800usb_device_table,
.probe = rt2800usb_probe,
.disconnect = rt2x00usb_disconnect,
.suspend = rt2x00usb_suspend,
.resume = rt2x00usb_resume,
.reset_resume = rt2x00usb_resume,
.disable_hub_initiated_lpm = 1,
};
module_usb_driver(rt2800usb_driver);
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2009 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.launcher3;
import android.appwidget.AppWidgetHostView;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Process;
import com.android.launcher3.model.PackageItemInfo;
import com.android.launcher3.util.ContentWriter;
/**
* Represents a widget (either instantiated or about to be) in the Launcher.
*/
public class LauncherAppWidgetInfo extends ItemInfo {
public static final int RESTORE_COMPLETED = 0;
/**
* This is set during the package backup creation.
*/
public static final int FLAG_ID_NOT_VALID = 1;
/**
* Indicates that the provider is not available yet.
*/
public static final int FLAG_PROVIDER_NOT_READY = 2;
/**
* Indicates that the widget UI is not yet ready, and user needs to set it up again.
*/
public static final int FLAG_UI_NOT_READY = 4;
/**
* Indicates that the widget restore has started.
*/
public static final int FLAG_RESTORE_STARTED = 8;
/**
* Indicates that the widget has been allocated an Id. The id is still not valid, as it has
* not been bound yet.
*/
public static final int FLAG_ID_ALLOCATED = 16;
/**
* Indicates that the widget does not need to show config activity, even if it has a
* configuration screen. It can also optionally have some extras which are sent during bind.
*/
public static final int FLAG_DIRECT_CONFIG = 32;
/**
* Indicates that the widget hasn't been instantiated yet.
*/
public static final int NO_ID = -1;
/**
* Indicates that this is a locally defined widget and hence has no system allocated id.
*/
static final int CUSTOM_WIDGET_ID = -100;
/**
* Identifier for this widget when talking with
* {@link android.appwidget.AppWidgetManager} for updates.
*/
public int appWidgetId = NO_ID;
public ComponentName providerName;
/**
* Indicates the restore status of the widget.
*/
public int restoreStatus;
/**
* Indicates the installation progress of the widget provider
*/
public int installProgress = -1;
/**
* Optional extras sent during widget bind. See {@link #FLAG_DIRECT_CONFIG}.
*/
public Intent bindOptions;
/**
* Nonnull for pending widgets. We use this to get the icon and title for the widget.
*/
public PackageItemInfo pendingItemInfo;
private boolean mHasNotifiedInitialWidgetSizeChanged;
public LauncherAppWidgetInfo(int appWidgetId, ComponentName providerName) {
if (appWidgetId == CUSTOM_WIDGET_ID) {
itemType = LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
} else {
itemType = LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET;
}
this.appWidgetId = appWidgetId;
this.providerName = providerName;
// Since the widget isn't instantiated yet, we don't know these values. Set them to -1
// to indicate that they should be calculated based on the layout and minWidth/minHeight
spanX = -1;
spanY = -1;
// We only support app widgets on current user.
user = Process.myUserHandle();
restoreStatus = RESTORE_COMPLETED;
}
/** Used for testing **/
public LauncherAppWidgetInfo() {
itemType = LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET;
}
public boolean isCustomWidget() {
return appWidgetId == CUSTOM_WIDGET_ID;
}
@Override
public void onAddToDatabase(ContentWriter writer) {
super.onAddToDatabase(writer);
writer.put(LauncherSettings.Favorites.APPWIDGET_ID, appWidgetId)
.put(LauncherSettings.Favorites.APPWIDGET_PROVIDER, providerName.flattenToString())
.put(LauncherSettings.Favorites.RESTORED, restoreStatus)
.put(LauncherSettings.Favorites.INTENT, bindOptions);
}
/**
* When we bind the widget, we should notify the widget that the size has changed if we have not
* done so already (only really for default workspace widgets).
*/
void onBindAppWidget(Launcher launcher, AppWidgetHostView hostView) {
if (!mHasNotifiedInitialWidgetSizeChanged) {
AppWidgetResizeFrame.updateWidgetSizeRanges(hostView, launcher, spanX, spanY);
mHasNotifiedInitialWidgetSizeChanged = true;
}
}
@Override
protected String dumpProperties() {
return super.dumpProperties() + " appWidgetId=" + appWidgetId;
}
public final boolean isWidgetIdAllocated() {
return (restoreStatus & FLAG_ID_NOT_VALID) == 0 ||
(restoreStatus & FLAG_ID_ALLOCATED) == FLAG_ID_ALLOCATED;
}
public final boolean hasRestoreFlag(int flag) {
return (restoreStatus & flag) == flag;
}
}
| {
"pile_set_name": "Github"
} |
1.0.5
| {
"pile_set_name": "Github"
} |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
module ConsoleApplication.Program
open System
[<EntryPoint>]
let main argv =
printfn "Hello World!"
0
| {
"pile_set_name": "Github"
} |
// Package ostype is define OS type of SakuraCloud public archive
package ostype
//go:generate stringer -type=ArchiveOSTypes
// ArchiveOSTypes パブリックアーカイブOS種別
type ArchiveOSTypes int
const (
// CentOS OS種別:CentOS
CentOS ArchiveOSTypes = iota
// CentOS6 OS種別:CentOS6
CentOS6
// Ubuntu OS種別:Ubuntu
Ubuntu
// Debian OS種別:Debian
Debian
// CoreOS OS種別:CoreOS
CoreOS
// RancherOS OS種別:RancherOS
RancherOS
// K3OS OS種別: k3OS
K3OS
// Kusanagi OS種別:Kusanagi(CentOS)
Kusanagi
// SophosUTM OS種別:Sophos UTM
SophosUTM
// FreeBSD OS種別:FreeBSD
FreeBSD
// Netwiser OS種別: Netwiser Virtual Edition
Netwiser
// OPNsense OS種別: OPNsense
OPNsense
// Windows2016 OS種別:Windows Server 2016 Datacenter Edition
Windows2016
// Windows2016RDS OS種別:Windows Server 2016 RDS
Windows2016RDS
// Windows2016RDSOffice OS種別:Windows Server 2016 RDS(Office)
Windows2016RDSOffice
// Windows2016SQLServerWeb OS種別:Windows Server 2016 SQLServer(Web)
Windows2016SQLServerWeb
// Windows2016SQLServerStandard OS種別:Windows Server 2016 SQLServer 2016(Standard)
Windows2016SQLServerStandard
// Windows2016SQLServer2017Standard OS種別:Windows Server 2016 SQLServer 2017(Standard)
Windows2016SQLServer2017Standard
// Windows2016SQLServerStandardAll OS種別:Windows Server 2016 SQLServer(Standard) + RDS + Office
Windows2016SQLServerStandardAll
// Windows2016SQLServer2017StandardAll OS種別:Windows Server 2016 SQLServer 2017(Standard) + RDS + Office
Windows2016SQLServer2017StandardAll
// Windows2019 OS種別:Windows Server 2019 Datacenter Edition
Windows2019
// Custom OS種別:カスタム
Custom
)
// OSTypeShortNames OSTypeとして利用できる文字列のリスト
var OSTypeShortNames = []string{
"centos", "centos6", "ubuntu", "debian", "coreos",
"rancheros", "k3os", "kusanagi", "sophos-utm", "freebsd",
"netwiser", "opnsense",
"windows2016", "windows2016-rds", "windows2016-rds-office",
"windows2016-sql-web", "windows2016-sql-standard", "windows2016-sql-standard-all",
"windows2016-sql2017-standard", "windows2016-sql2017-standard-all",
"windows2019",
}
// IsWindows Windowsか
func (o ArchiveOSTypes) IsWindows() bool {
switch o {
case Windows2016, Windows2016RDS, Windows2016RDSOffice,
Windows2016SQLServerWeb, Windows2016SQLServerStandard, Windows2016SQLServerStandardAll,
Windows2016SQLServer2017Standard, Windows2016SQLServer2017StandardAll,
Windows2019:
return true
default:
return false
}
}
// IsSupportDiskEdit ディスクの修正機能をフルサポートしているか(Windowsは一部サポートのためfalseを返す)
func (o ArchiveOSTypes) IsSupportDiskEdit() bool {
switch o {
case CentOS, CentOS6, Ubuntu, Debian, CoreOS, RancherOS, K3OS, Kusanagi, FreeBSD:
return true
default:
return false
}
}
// StrToOSType 文字列からArchiveOSTypesへの変換
func StrToOSType(osType string) ArchiveOSTypes {
switch osType {
case "centos":
return CentOS
case "centos6":
return CentOS6
case "ubuntu":
return Ubuntu
case "debian":
return Debian
case "coreos":
return CoreOS
case "rancheros":
return RancherOS
case "k3os":
return K3OS
case "kusanagi":
return Kusanagi
case "sophos-utm":
return SophosUTM
case "freebsd":
return FreeBSD
case "netwiser":
return Netwiser
case "opnsense":
return OPNsense
case "windows2016":
return Windows2016
case "windows2016-rds":
return Windows2016RDS
case "windows2016-rds-office":
return Windows2016RDSOffice
case "windows2016-sql-web":
return Windows2016SQLServerWeb
case "windows2016-sql-standard":
return Windows2016SQLServerStandard
case "windows2016-sql2017-standard":
return Windows2016SQLServer2017Standard
case "windows2016-sql-standard-all":
return Windows2016SQLServerStandardAll
case "windows2016-sql2017-standard-all":
return Windows2016SQLServer2017StandardAll
case "windows2019":
return Windows2019
default:
return Custom
}
}
| {
"pile_set_name": "Github"
} |
/* _______ ____ __ ___ ___
* \ _ \ \ / \ / \ \ / / ' ' '
* | | \ \ | | || | \/ | . .
* | | | | | | || ||\ /| |
* | | | | | | || || \/ | | ' ' '
* | | | | | | || || | | . .
* | |_/ / \ \__// || | |
* /_______/ynamic \____/niversal /__\ /____\usic /| . . ibliotheque
* / \
* / . \
* loadokt.c - Code to read an Oktalyzer module / / \ \
* file, opening and closing it for | < / \_
* you. | \/ /\ /
* \_ / > /
* By Chris Moeller. | \ / /
* | ' /
* \__/
*/
#include "dumb.h"
#include "internal/it.h"
/* dumb_load_okt_quick(): loads an OKT file into a DUH struct, returning a
* pointer to the DUH struct. When you have finished with it, you must
* pass the pointer to unload_duh() so that the memory can be freed.
*/
DUH *dumb_load_okt_quick(const char *filename)
{
DUH *duh;
DUMBFILE *f = dumbfile_open(filename);
if (!f)
return NULL;
duh = dumb_read_okt_quick(f);
dumbfile_close(f);
return duh;
}
| {
"pile_set_name": "Github"
} |
package logrus
import (
"bytes"
"fmt"
"os"
"runtime"
"sort"
"strings"
"sync"
"time"
)
const (
red = 31
yellow = 33
blue = 36
gray = 37
)
var baseTimestamp time.Time
func init() {
baseTimestamp = time.Now()
}
// TextFormatter formats logs into text
type TextFormatter struct {
// Set to true to bypass checking for a TTY before outputting colors.
ForceColors bool
// Force disabling colors.
DisableColors bool
// Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/
EnvironmentOverrideColors bool
// Disable timestamp logging. useful when output is redirected to logging
// system that already adds timestamps.
DisableTimestamp bool
// Enable logging the full timestamp when a TTY is attached instead of just
// the time passed since beginning of execution.
FullTimestamp bool
// TimestampFormat to use for display when a full timestamp is printed
TimestampFormat string
// The fields are sorted by default for a consistent output. For applications
// that log extremely frequently and don't use the JSON formatter this may not
// be desired.
DisableSorting bool
// The keys sorting function, when uninitialized it uses sort.Strings.
SortingFunc func([]string)
// Disables the truncation of the level text to 4 characters.
DisableLevelTruncation bool
// QuoteEmptyFields will wrap empty fields in quotes if true
QuoteEmptyFields bool
// Whether the logger's out is to a terminal
isTerminal bool
// FieldMap allows users to customize the names of keys for default fields.
// As an example:
// formatter := &TextFormatter{
// FieldMap: FieldMap{
// FieldKeyTime: "@timestamp",
// FieldKeyLevel: "@level",
// FieldKeyMsg: "@message"}}
FieldMap FieldMap
// CallerPrettyfier can be set by the user to modify the content
// of the function and file keys in the data when ReportCaller is
// activated. If any of the returned value is the empty string the
// corresponding key will be removed from fields.
CallerPrettyfier func(*runtime.Frame) (function string, file string)
terminalInitOnce sync.Once
}
func (f *TextFormatter) init(entry *Entry) {
if entry.Logger != nil {
f.isTerminal = checkIfTerminal(entry.Logger.Out)
}
}
func (f *TextFormatter) isColored() bool {
isColored := f.ForceColors || (f.isTerminal && (runtime.GOOS != "windows"))
if f.EnvironmentOverrideColors {
if force, ok := os.LookupEnv("CLICOLOR_FORCE"); ok && force != "0" {
isColored = true
} else if ok && force == "0" {
isColored = false
} else if os.Getenv("CLICOLOR") == "0" {
isColored = false
}
}
return isColored && !f.DisableColors
}
// Format renders a single log entry
func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
data := make(Fields)
for k, v := range entry.Data {
data[k] = v
}
prefixFieldClashes(data, f.FieldMap, entry.HasCaller())
keys := make([]string, 0, len(data))
for k := range data {
keys = append(keys, k)
}
var funcVal, fileVal string
fixedKeys := make([]string, 0, 4+len(data))
if !f.DisableTimestamp {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime))
}
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel))
if entry.Message != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg))
}
if entry.err != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError))
}
if entry.HasCaller() {
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
} else {
funcVal = entry.Caller.Function
fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
}
if funcVal != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFunc))
}
if fileVal != "" {
fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFile))
}
}
if !f.DisableSorting {
if f.SortingFunc == nil {
sort.Strings(keys)
fixedKeys = append(fixedKeys, keys...)
} else {
if !f.isColored() {
fixedKeys = append(fixedKeys, keys...)
f.SortingFunc(fixedKeys)
} else {
f.SortingFunc(keys)
}
}
} else {
fixedKeys = append(fixedKeys, keys...)
}
var b *bytes.Buffer
if entry.Buffer != nil {
b = entry.Buffer
} else {
b = &bytes.Buffer{}
}
f.terminalInitOnce.Do(func() { f.init(entry) })
timestampFormat := f.TimestampFormat
if timestampFormat == "" {
timestampFormat = defaultTimestampFormat
}
if f.isColored() {
f.printColored(b, entry, keys, data, timestampFormat)
} else {
for _, key := range fixedKeys {
var value interface{}
switch {
case key == f.FieldMap.resolve(FieldKeyTime):
value = entry.Time.Format(timestampFormat)
case key == f.FieldMap.resolve(FieldKeyLevel):
value = entry.Level.String()
case key == f.FieldMap.resolve(FieldKeyMsg):
value = entry.Message
case key == f.FieldMap.resolve(FieldKeyLogrusError):
value = entry.err
case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller():
value = funcVal
case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller():
value = fileVal
default:
value = data[key]
}
f.appendKeyValue(b, key, value)
}
}
b.WriteByte('\n')
return b.Bytes(), nil
}
func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string) {
var levelColor int
switch entry.Level {
case DebugLevel, TraceLevel:
levelColor = gray
case WarnLevel:
levelColor = yellow
case ErrorLevel, FatalLevel, PanicLevel:
levelColor = red
default:
levelColor = blue
}
levelText := strings.ToUpper(entry.Level.String())
if !f.DisableLevelTruncation {
levelText = levelText[0:4]
}
// Remove a single newline if it already exists in the message to keep
// the behavior of logrus text_formatter the same as the stdlib log package
entry.Message = strings.TrimSuffix(entry.Message, "\n")
caller := ""
if entry.HasCaller() {
funcVal := fmt.Sprintf("%s()", entry.Caller.Function)
fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line)
if f.CallerPrettyfier != nil {
funcVal, fileVal = f.CallerPrettyfier(entry.Caller)
}
if fileVal == "" {
caller = funcVal
} else if funcVal == "" {
caller = fileVal
} else {
caller = fileVal + " " + funcVal
}
}
if f.DisableTimestamp {
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message)
} else if !f.FullTimestamp {
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message)
} else {
fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message)
}
for _, k := range keys {
v := data[k]
fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k)
f.appendValue(b, v)
}
}
func (f *TextFormatter) needsQuoting(text string) bool {
if f.QuoteEmptyFields && len(text) == 0 {
return true
}
for _, ch := range text {
if !((ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch >= '0' && ch <= '9') ||
ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') {
return true
}
}
return false
}
func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
if b.Len() > 0 {
b.WriteByte(' ')
}
b.WriteString(key)
b.WriteByte('=')
f.appendValue(b, value)
}
func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) {
stringVal, ok := value.(string)
if !ok {
stringVal = fmt.Sprint(value)
}
if !f.needsQuoting(stringVal) {
b.WriteString(stringVal)
} else {
b.WriteString(fmt.Sprintf("%q", stringVal))
}
}
| {
"pile_set_name": "Github"
} |
/*
* The Wine project - Xinput Joystick Library
* Copyright 2008 Andrew Fenn
*
* 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 St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#ifndef __WINE_XINPUT_H
#define __WINE_XINPUT_H
#include <windef.h>
/*
* Bitmasks for the joysticks buttons, determines what has
* been pressed on the joystick, these need to be mapped
* to whatever device you're using instead of an xbox 360
* joystick
*/
#define XINPUT_GAMEPAD_DPAD_UP 0x0001
#define XINPUT_GAMEPAD_DPAD_DOWN 0x0002
#define XINPUT_GAMEPAD_DPAD_LEFT 0x0004
#define XINPUT_GAMEPAD_DPAD_RIGHT 0x0008
#define XINPUT_GAMEPAD_START 0x0010
#define XINPUT_GAMEPAD_BACK 0x0020
#define XINPUT_GAMEPAD_LEFT_THUMB 0x0040
#define XINPUT_GAMEPAD_RIGHT_THUMB 0x0080
#define XINPUT_GAMEPAD_LEFT_SHOULDER 0x0100
#define XINPUT_GAMEPAD_RIGHT_SHOULDER 0x0200
#define XINPUT_GAMEPAD_A 0x1000
#define XINPUT_GAMEPAD_B 0x2000
#define XINPUT_GAMEPAD_X 0x4000
#define XINPUT_GAMEPAD_Y 0x8000
/*
* Defines the flags used to determine if the user is pushing
* down on a button, not holding a button, etc
*/
#define XINPUT_KEYSTROKE_KEYDOWN 0x0001
#define XINPUT_KEYSTROKE_KEYUP 0x0002
#define XINPUT_KEYSTROKE_REPEAT 0x0004
/*
* Defines the codes which are returned by XInputGetKeystroke
*/
#define VK_PAD_A 0x5800
#define VK_PAD_B 0x5801
#define VK_PAD_X 0x5802
#define VK_PAD_Y 0x5803
#define VK_PAD_RSHOULDER 0x5804
#define VK_PAD_LSHOULDER 0x5805
#define VK_PAD_LTRIGGER 0x5806
#define VK_PAD_RTRIGGER 0x5807
#define VK_PAD_DPAD_UP 0x5810
#define VK_PAD_DPAD_DOWN 0x5811
#define VK_PAD_DPAD_LEFT 0x5812
#define VK_PAD_DPAD_RIGHT 0x5813
#define VK_PAD_START 0x5814
#define VK_PAD_BACK 0x5815
#define VK_PAD_LTHUMB_PRESS 0x5816
#define VK_PAD_RTHUMB_PRESS 0x5817
#define VK_PAD_LTHUMB_UP 0x5820
#define VK_PAD_LTHUMB_DOWN 0x5821
#define VK_PAD_LTHUMB_RIGHT 0x5822
#define VK_PAD_LTHUMB_LEFT 0x5823
#define VK_PAD_LTHUMB_UPLEFT 0x5824
#define VK_PAD_LTHUMB_UPRIGHT 0x5825
#define VK_PAD_LTHUMB_DOWNRIGHT 0x5826
#define VK_PAD_LTHUMB_DOWNLEFT 0x5827
#define VK_PAD_RTHUMB_UP 0x5830
#define VK_PAD_RTHUMB_DOWN 0x5831
#define VK_PAD_RTHUMB_RIGHT 0x5832
#define VK_PAD_RTHUMB_LEFT 0x5833
#define VK_PAD_RTHUMB_UPLEFT 0x5834
#define VK_PAD_RTHUMB_UPRIGHT 0x5835
#define VK_PAD_RTHUMB_DOWNRIGHT 0x5836
#define VK_PAD_RTHUMB_DOWNLEFT 0x5837
/*
* Deadzones are for analogue joystick controls on the joypad
* which determine when input should be assumed to be in the
* middle of the pad. This is a threshold to stop a joypad
* controlling the game when the player isn't touching the
* controls.
*/
#define XINPUT_GAMEPAD_LEFT_THUMB_DEADZONE 7849
#define XINPUT_GAMEPAD_RIGHT_THUMB_DEADZONE 8689
#define XINPUT_GAMEPAD_TRIGGER_THRESHOLD 30
/*
* Defines what type of abilities the type of joystick has
* DEVTYPE_GAMEPAD is available for all joysticks, however
* there may be more specific identifiers for other joysticks
* which are being used.
*/
#define XINPUT_DEVTYPE_GAMEPAD 0x01
#define XINPUT_DEVSUBTYPE_GAMEPAD 0x01
#define XINPUT_DEVSUBTYPE_WHEEL 0x02
#define XINPUT_DEVSUBTYPE_ARCADE_STICK 0x03
#define XINPUT_DEVSUBTYPE_FLIGHT_SICK 0x04
#define XINPUT_DEVSUBTYPE_DANCE_PAD 0x05
#define XINPUT_DEVSUBTYPE_GUITAR 0x06
#define XINPUT_DEVSUBTYPE_DRUM_KIT 0x08
/*
* These are used with the XInputGetCapabilities function to
* determine the abilities to the joystick which has been
* plugged in.
*/
#define XINPUT_CAPS_VOICE_SUPPORTED 0x0004
#define XINPUT_FLAG_GAMEPAD 0x00000001
/*
* Defines the status of the battery if one is used in the
* attached joystick. The first two define if the joystick
* supports a battery. Disconnected means that the joystick
* isn't connected. Wired shows that the joystick is a wired
* joystick.
*/
#define BATTERY_DEVTYPE_GAMEPAD 0x00
#define BATTERY_DEVTYPE_HEADSET 0x01
#define BATTERY_TYPE_DISCONNECTED 0x00
#define BATTERY_TYPE_WIRED 0x01
#define BATTERY_TYPE_ALKALINE 0x02
#define BATTERY_TYPE_NIMH 0x03
#define BATTERY_TYPE_UNKNOWN 0xFF
#define BATTERY_LEVEL_EMPTY 0x00
#define BATTERY_LEVEL_LOW 0x01
#define BATTERY_LEVEL_MEDIUM 0x02
#define BATTERY_LEVEL_FULL 0x03
/*
* How many joysticks can be used with this library. Games that
* use the xinput library will not go over this number.
*/
#define XUSER_MAX_COUNT 4
#define XUSER_INDEX_ANY 0x000000FF
/*
* Defines the structure of an xbox 360 joystick.
*/
typedef struct _XINPUT_GAMEPAD {
WORD wButtons;
BYTE bLeftTrigger;
BYTE bRightTrigger;
SHORT sThumbLX;
SHORT sThumbLY;
SHORT sThumbRX;
SHORT sThumbRY;
} XINPUT_GAMEPAD, *PXINPUT_GAMEPAD;
typedef struct _XINPUT_STATE {
DWORD dwPacketNumber;
XINPUT_GAMEPAD Gamepad;
} XINPUT_STATE, *PXINPUT_STATE;
/*
* Defines the structure of how much vibration is set on both the
* right and left motors in a joystick. If you're not using a 360
* joystick you will have to map these to your device.
*/
typedef struct _XINPUT_VIBRATION {
WORD wLeftMotorSpeed;
WORD wRightMotorSpeed;
} XINPUT_VIBRATION, *PXINPUT_VIBRATION;
/*
* Defines the structure for what kind of abilities the joystick has
* such abilities are things such as if the joystick has the ability
* to send and receive audio, if the joystick is in fact a driving
* wheel or perhaps if the joystick is some kind of dance pad or
* guitar.
*/
typedef struct _XINPUT_CAPABILITIES {
BYTE Type;
BYTE SubType;
WORD Flags;
XINPUT_GAMEPAD Gamepad;
XINPUT_VIBRATION Vibration;
} XINPUT_CAPABILITIES, *PXINPUT_CAPABILITIES;
/*
* Defines the structure for a joystick input event which is
* retrieved using the function XInputGetKeystroke
*/
typedef struct _XINPUT_KEYSTROKE {
WORD VirtualKey;
WCHAR Unicode;
WORD Flags;
BYTE UserIndex;
BYTE HidCode;
} XINPUT_KEYSTROKE, *PXINPUT_KEYSTROKE;
typedef struct _XINPUT_BATTERY_INFORMATION
{
BYTE BatteryType;
BYTE BatteryLevel;
} XINPUT_BATTERY_INFORMATION, *PXINPUT_BATTERY_INFORMATION;
#ifdef __cplusplus
extern "C" {
#endif
void WINAPI XInputEnable(WINBOOL);
DWORD WINAPI XInputSetState(DWORD, XINPUT_VIBRATION*);
DWORD WINAPI XInputGetState(DWORD, XINPUT_STATE*);
DWORD WINAPI XInputGetKeystroke(DWORD, DWORD, PXINPUT_KEYSTROKE);
DWORD WINAPI XInputGetCapabilities(DWORD, DWORD, XINPUT_CAPABILITIES*);
DWORD WINAPI XInputGetDSoundAudioDeviceGuids(DWORD, GUID*, GUID*);
DWORD WINAPI XInputGetBatteryInformation(DWORD, BYTE, XINPUT_BATTERY_INFORMATION*);
#ifdef __cplusplus
}
#endif
#endif /* __WINE_XINPUT_H */
| {
"pile_set_name": "Github"
} |
//
// Copyright 2020 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// IOSurfaceSurfaceVkMac.h:
// Subclasses SurfaceVk for the Mac platform to implement PBuffers using an IOSurface
//
#ifndef LIBANGLE_RENDERER_VULKAN_MAC_IOSURFACESURFACEVKMAC_H_
#define LIBANGLE_RENDERER_VULKAN_MAC_IOSURFACESURFACEVKMAC_H_
#include "libANGLE/renderer/vulkan/SurfaceVk.h"
struct __IOSurface;
typedef __IOSurface *IOSurfaceRef;
namespace egl
{
class AttributeMap;
} // namespace egl
namespace rx
{
class IOSurfaceSurfaceVkMac : public OffscreenSurfaceVk
{
public:
IOSurfaceSurfaceVkMac(const egl::SurfaceState &state,
EGLClientBuffer buffer,
const egl::AttributeMap &attribs);
~IOSurfaceSurfaceVkMac() override;
egl::Error initialize(const egl::Display *display) override;
egl::Error unMakeCurrent(const gl::Context *context) override;
egl::Error bindTexImage(const gl::Context *context,
gl::Texture *texture,
EGLint buffer) override;
egl::Error releaseTexImage(const gl::Context *context, EGLint buffer) override;
static bool ValidateAttributes(const DisplayVk *displayVk,
EGLClientBuffer buffer,
const egl::AttributeMap &attribs);
protected:
angle::Result initializeImpl(DisplayVk *displayVk) override;
private:
IOSurfaceRef mIOSurface;
int mPlane;
int mFormatIndex;
};
} // namespace rx
#endif // LIBANGLE_RENDERER_VULKAN_MAC_IOSURFACESURFACEVKMAC_H_
| {
"pile_set_name": "Github"
} |
dnl PowerPC-64 mpn_rshift -- rp[] = up[] << cnt
dnl Copyright 2003, 2005, 2010, 2013 Free Software Foundation, Inc.
dnl This file is part of the GNU MP Library.
dnl
dnl The GNU MP Library is free software; you can redistribute it and/or modify
dnl it under the terms of either:
dnl
dnl * the GNU Lesser General Public License as published by the Free
dnl Software Foundation; either version 3 of the License, or (at your
dnl option) any later version.
dnl
dnl or
dnl
dnl * the GNU General Public License as published by the Free Software
dnl Foundation; either version 2 of the License, or (at your option) any
dnl later version.
dnl
dnl or both in parallel, as here.
dnl
dnl The GNU MP Library is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
dnl or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
dnl for more details.
dnl
dnl You should have received copies of the GNU General Public License and the
dnl GNU Lesser General Public License along with the GNU MP Library. If not,
dnl see https://www.gnu.org/licenses/.
include(`../config.m4')
C cycles/limb
C POWER3/PPC630 ?
C POWER4/PPC970 ?
C POWER5 2
C POWER6 3.5 (mysteriously 3.0 for cnt=1)
C TODO
C * Micro-optimise header code
C * Perhaps do 4-way unrolling, for 2.5 c/l on POWER6. The code is 4248
C bytes, 4-way code would become about 50% larger.
C INPUT PARAMETERS
define(`rp_param', `r3')
define(`up', `r4')
define(`n', `r5')
define(`cnt', `r6')
define(`tnc',`r0')
define(`retval',`r3')
define(`rp', `r7')
ASM_START()
PROLOGUE(mpn_rshift,toc)
ifdef(`HAVE_ABI_mode32',`
rldicl n, n, 0,32 C FIXME: avoid this zero extend
')
mflr r12
LEAL( r11, L(e1)) C address of L(e1) label in SHIFT(1)
sldi r10, cnt, 6 C multiply cnt by size of a SHIFT block
add r11, r11, r10 C address of L(oN) for N = cnt
srdi r10, n, 1
mr rp, rp_param
subfic tnc, cnt, 64
rlwinm. r8, n, 0,31,31 C extract bit 0
mtctr r10
beq L(evn)
L(odd): ld r9, 0(up)
cmpdi cr0, n, 1 C n = 1?
beq L(1)
ld r8, 8(up)
addi r11, r11, -84 C L(o1) - L(e1) - 64
mtlr r11
sld r3, r9, tnc C retval
addi up, up, 8
addi rp, rp, 8
blr C branch to L(oN)
L(evn): ld r8, 0(up)
ld r9, 8(up)
addi r11, r11, -64
mtlr r11
sld r3, r8, tnc C retval
addi up, up, 16
blr C branch to L(eN)
L(1): sld r3, r9, tnc C retval
srd r8, r9, cnt
std r8, 0(rp)
mtlr r12
ifdef(`HAVE_ABI_mode32',
` mr r4, r3
srdi r3, r3, 32
')
blr
define(SHIFT,`
L(lo$1):ld r8, 0(up)
std r11, 0(rp)
addi rp, rp, 16
L(o$1): srdi r10, r9, $1
rldimi r10, r8, eval(64-$1), 0
ld r9, 8(up)
addi up, up, 16
std r10, -8(rp)
L(e$1): srdi r11, r8, $1
rldimi r11, r9, eval(64-$1), 0
bdnz L(lo$1)
std r11, 0(rp)
srdi r10, r9, $1
b L(com)
nop
nop
')
ALIGN(64)
forloop(`i',1,63,`SHIFT(i)')
L(com): std r10, 8(rp)
mtlr r12
ifdef(`HAVE_ABI_mode32',
` mr r4, r3
srdi r3, r3, 32
')
blr
EPILOGUE()
ASM_END()
| {
"pile_set_name": "Github"
} |
require "spec_helper"
module RailsEventStore
module RSpec
::RSpec.describe Publish do
let(:matchers) { Object.new.tap { |o| o.extend(Matchers) } }
let(:event_store) do
RailsEventStore::Client.new(
repository: RailsEventStore::InMemoryRepository.new,
mapper: RubyEventStore::Mappers::PipelineMapper.new(
RubyEventStore::Mappers::Pipeline.new(to_domain_event: IdentityMapTransformation.new)
)
)
end
def matcher(*expected)
Publish.new(*expected)
end
specify do
expect {
expect {
true
}.to matcher
}.to raise_error(SyntaxError, "You have to set the event store instance with `in`, e.g. `expect { ... }.to publish(an_event(MyEvent)).in(event_store)`")
end
specify do
expect {
true
}.not_to matcher.in(event_store)
end
specify do
expect {
event_store.publish(FooEvent.new)
}.to matcher.in(event_store)
end
specify do
expect {
event_store.publish(FooEvent.new, stream_name: 'Foo$1')
}.to matcher.in(event_store).in_stream('Foo$1')
end
specify do
expect {
event_store.publish(FooEvent.new, stream_name: 'Foo$1')
}.not_to matcher.in(event_store).in_stream('Bar$1')
end
specify do
expect {
event_store.publish(FooEvent.new)
}.not_to matcher(matchers.an_event(BarEvent)).in(event_store)
end
specify do
expect {
event_store.publish(FooEvent.new)
}.to matcher(matchers.an_event(FooEvent)).in(event_store)
end
specify do
expect {
event_store.publish(FooEvent.new, stream_name: "Foo$1")
}.to matcher(matchers.an_event(FooEvent)).in(event_store).in_stream("Foo$1")
end
specify do
expect {
event_store.publish(FooEvent.new)
}.not_to matcher(matchers.an_event(FooEvent)).in(event_store).in_stream("Foo$1")
end
specify do
event_store.publish(FooEvent.new)
event_store.publish(FooEvent.new)
event_store.publish(FooEvent.new)
expect {
event_store.publish(BarEvent.new)
}.to matcher(matchers.an_event(BarEvent)).in(event_store)
expect {
event_store.publish(BarEvent.new)
}.not_to matcher(matchers.an_event(FooEvent)).in(event_store)
end
specify do
foo_event = FooEvent.new
bar_event = BarEvent.new
expect {
event_store.publish(foo_event, stream_name: "Foo$1")
event_store.publish(bar_event, stream_name: "Bar$1")
}.to matcher(matchers.an_event(FooEvent), matchers.an_event(BarEvent)).in(event_store)
end
specify do
foo_event = FooEvent.new
bar_event = BarEvent.new
event_store.publish(foo_event)
expect {
event_store.publish(bar_event)
}.not_to matcher(matchers.an_event(FooEvent)).in(event_store)
end
specify do
expect {
true
}.not_to matcher.in(event_store)
end
specify do
matcher_ = matcher.in(event_store)
matcher_.matches?(Proc.new { })
expect(matcher_.failure_message_when_negated.to_s).to eq(<<~EOS.strip)
expected block not to have published any events
EOS
end
specify do
matcher_ = matcher.in(event_store)
matcher_.matches?(Proc.new { })
expect(matcher_.failure_message.to_s).to eq(<<~EOS.strip)
expected block to have published any events
EOS
end
specify do
matcher_ = matcher(actual = matchers.an_event(FooEvent)).in(event_store)
matcher_.matches?(Proc.new { })
expect(matcher_.failure_message.to_s).to eq(<<~EOS)
expected block to have published:
#{[actual].inspect}
but published:
[]
EOS
end
specify do
matcher_ = matcher(actual = matchers.an_event(FooEvent)).in_stream('foo').in(event_store)
matcher_.matches?(Proc.new { })
expect(matcher_.failure_message.to_s).to eq(<<~EOS)
expected block to have published:
#{[actual].inspect}
in stream foo but published:
[]
EOS
end
specify do
foo_event = FooEvent.new
matcher_ = matcher(actual = matchers.an_event(FooEvent)).in(event_store)
matcher_.matches?(Proc.new { event_store.publish(foo_event) })
expect(matcher_.failure_message_when_negated.to_s).to eq(<<~EOS)
expected block not to have published:
#{[actual].inspect}
but published:
#{[foo_event].inspect}
EOS
end
specify do
foo_event = FooEvent.new
matcher_ = matcher(actual = matchers.an_event(FooEvent)).in_stream('foo').in(event_store)
matcher_.matches?(Proc.new { event_store.publish(foo_event, stream_name: 'foo') })
expect(matcher_.failure_message_when_negated.to_s).to eq(<<~EOS)
expected block not to have published:
#{[actual].inspect}
in stream foo but published:
#{[foo_event].inspect}
EOS
end
specify do
matcher_ = matcher
expect(matcher_.description).to eq("publish events")
end
end
end
end
| {
"pile_set_name": "Github"
} |
.\" $Id: tiffcp.1,v 1.6 2005/11/02 11:07:19 dron Exp $
.\"
.\" Copyright (c) 1988-1997 Sam Leffler
.\" Copyright (c) 1991-1997 Silicon Graphics, Inc.
.\"
.\" Permission to use, copy, modify, distribute, and sell this software and
.\" its documentation for any purpose is hereby granted without fee, provided
.\" that (i) the above copyright notices and this permission notice appear in
.\" all copies of the software and related documentation, and (ii) the names of
.\" Sam Leffler and Silicon Graphics may not be used in any advertising or
.\" publicity relating to the software without the specific, prior written
.\" permission of Sam Leffler and Silicon Graphics.
.\"
.\" THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
.\" EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
.\" WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
.\"
.\" IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
.\" ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
.\" OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
.\" WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
.\" LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
.\" OF THIS SOFTWARE.
.\"
.if n .po 0
.TH TIFFCP 1 "September 20, 2005" "libtiff"
.SH NAME
tiffcp \- copy (and possibly convert) a
.SM TIFF
file
.SH SYNOPSIS
.B tiffcp
[
.I options
]
.I "src1.tif ... srcN.tif dst.tif"
.SH DESCRIPTION
.I tiffcp
combines one or more files created according
to the Tag Image File Format, Revision 6.0
into a single
.SM TIFF
file.
Because the output file may be compressed using a different
algorithm than the input files,
.I tiffcp
is most often used to convert between different compression
schemes.
.PP
By default,
.I tiffcp
will copy all the understood tags in a
.SM TIFF
directory of an input
file to the associated directory in the output file.
.PP
.I tiffcp
can be used to reorganize the storage characteristics of data
in a file, but it is explicitly intended to not alter or convert
the image data content in any way.
.SH OPTIONS
.TP
.B \-b image
subtract the following monochrome image from all others
processed. This can be used to remove a noise bias
from a set of images. This bias image is typically an
image of noise the camera saw with its shutter closed.
.TP
.B \-B
Force output to be written with Big-Endian byte order.
This option only has an effect when the output file is created or
overwritten and not when it is appended to.
.TP
.B \-C
Suppress the use of ``strip chopping'' when reading images
that have a single strip/tile of uncompressed data.
.TP
.B \-c
Specify the compression to use for data written to the output file:
.B none
for no compression,
.B packbits
for PackBits compression,
.B lzw
for Lempel-Ziv & Welch compression,
.B jpeg
for baseline JPEG compression,
.B zip
for Deflate compression,
.B g3
for CCITT Group 3 (T.4) compression,
and
.B g4
for CCITT Group 4 (T.6) compression.
By default
.I tiffcp
will compress data according to the value of the
.I Compression
tag found in the source file.
.IP
The
.SM CCITT
Group 3 and Group 4 compression algorithms can only
be used with bilevel data.
.IP
Group 3 compression can be specified together with several
T.4-specific options:
.B 1d
for 1-dimensional encoding,
.B 2d
for 2-dimensional encoding,
and
.B fill
to force each encoded scanline to be zero-filled so that the
terminating EOL code lies on a byte boundary.
Group 3-specific options are specified by appending a ``:''-separated
list to the ``g3'' option; e.g.
.B "\-c g3:2d:fill"
to get 2D-encoded data with byte-aligned EOL codes.
.IP
.SM LZW
compression can be specified together with a
.I predictor
value.
A predictor value of 2 causes
each scanline of the output image to undergo horizontal
differencing before it is encoded; a value
of 1 forces each scanline to be encoded without differencing.
LZW-specific options are specified by appending a ``:''-separated
list to the ``lzw'' option; e.g.
.B "\-c lzw:2"
for
.SM LZW
compression with horizontal differencing.
.TP
.B \-f
Specify the bit fill order to use in writing output data.
By default,
.I tiffcp
will create a new file with the same fill order as the original.
Specifying
.B "\-f lsb2msb"
will force data to be written with the FillOrder tag set to
.SM LSB2MSB,
while
.B "\-f msb2lsb"
will force data to be written with the FillOrder tag set to
.SM MSB2LSB.
.TP
.B \-l
Specify the length of a tile (in pixels).
.I tiffcp
attempts to set the tile dimensions so
that no more than 8 kilobytes of data appear in a tile.
.TP
.B \-L
Force output to be written with Little-Endian byte order.
This option only has an effect when the output file is created or
overwritten and not when it is appended to.
.TP
.B \-M
Suppress the use of memory-mapped files when reading images.
.TP
.B \-p
Specify the planar configuration to use in writing image data
that has one 8-bit sample per pixel.
By default,
.I tiffcp
will create a new file with the same planar configuration as
the original.
Specifying
.B "\-p contig"
will force data to be written with multi-sample data packed
together, while
.B "\-p separate"
will force samples to be written in separate planes.
.TP
.B \-r
Specify the number of rows (scanlines) in each strip of data
written to the output file.
By default (or when value
.B 0
is specified),
.I tiffcp
attempts to set the rows/strip
that no more than 8 kilobytes of data appear in a strip. If you specify
special value
.B -1
it will results in infinite number of the rows per strip. The entire image
will be the one strip in that case.
.TP
.B \-s
Force the output file to be written with data organized in strips
(rather than tiles).
.TP
.B \-t
Force the output file to be written with data organized in tiles
(rather than strips).
options can be used to force the resultant image to be written
as strips or tiles of data, respectively.
.TP
.B \-w
Specify the width of a tile (in pixels).
.I tiffcp
attempts to set the tile dimensions so
that no more than 8 kilobytes of data appear in a tile.
.I tiffcp
attempts to set the tile dimensions so
that no more than 8 kilobytes of data appear in a tile.
.TP
.B \-,={character}
substitute {character} for ',' in parsing image directory indices
in files. This is necessary if filenames contain commas.
Note that ',=' with whitespace immediately following will disable
the special meaning of the ',' entirely. See examples.
.SH EXAMPLES
The following concatenates two files and writes the result using
.SM LZW
encoding:
.RS
.nf
tiffcp -c lzw a.tif b.tif result.tif
.fi
.RE
.PP
To convert a G3 1d-encoded
.SM TIFF
to a single strip of G4-encoded data the following might be used:
.RS
.nf
tiffcp -c g4 -r 10000 g3.tif g4.tif
.fi
.RE
(1000 is just a number that is larger than the number of rows in
the source file.)
To extract a selected set of images from a multi-image
TIFF file, the file name may be immediately followed by a ','
separated list of image directory indices. The first image
is always in directory 0. Thus, to copy the 1st and 3rd
images of image file "album.tif" to "result.tif":
.RS
.nf
tiffcp album.tif,0,2 result.tif
.fi
.RE
Given file "CCD.tif" whose first image is a noise bias
followed by images which include that bias,
subtract the noise from all those images following it
(while decompressing) with the command:
.RS
.nf
tiffcp -c none -b CCD.tif CCD.tif,1, result.tif
.fi
.RE
If the file above were named "CCD,X.tif", the "-,=" option would
be required to correctly parse this filename with image numbers,
as follows:
.RS
.nf
tiffcp -c none -,=% -b CCD,X.tif CCD,X%1%.tif result.tif
.SH "SEE ALSO"
.BR pal2rgb (1),
.BR tiffinfo (1),
.BR tiffcmp (1),
.BR tiffmedian (1),
.BR tiffsplit (1),
.BR libtiff (3TIFF)
.PP
Libtiff library home page:
.BR http://www.remotesensing.org/libtiff/
| {
"pile_set_name": "Github"
} |
(* Egbert's E-systems *)
require "../std/hippy.m31"
signature catWithTerms = {
ctx : Type,
fam : ctx → Type,
trm : ∏ (Γ : ctx), fam Γ → Type,
emptyCtx : ctx,
emptyFam : ∏ (Γ : ctx), fam Γ,
ctxExt : ∏ (Γ : ctx), fam Γ → ctx,
famExt : ∏ (Γ : ctx) (A : fam Γ), fam (ctxExt Γ A) → fam Γ,
assocCtxExt :
∏ (Γ : ctx) (A : fam Γ) (P : fam (ctxExt Γ A)),
ctxExt (ctxExt Γ A) P ≡ ctxExt Γ (famExt Γ A P),
assocFamExt :
(now betas = add_beta assocCtxExt betas in
∏ (Γ : ctx) (A : fam Γ) (P : fam (ctxExt Γ A))
(Q : fam (ctxExt (ctxExt Γ A) P)),
famExt Γ (famExt Γ A P) Q ≡
famExt Γ A (famExt (ctxExt Γ A) P Q)),
emptyCtxExt :
∏ (Γ : ctx), ctxExt Γ (emptyFam Γ) ≡ Γ,
emptyFamLeft :
(now betas = add_beta emptyCtxExt betas in
∏ (Γ : ctx) (A : fam Γ), famExt Γ (emptyFam Γ) A ≡ A),
emptyFamRight :
∏ (Γ : ctx) (A : fam Γ),
famExt Γ A (emptyFam (ctxExt Γ A)) ≡ A
}
signature functorWithTerms = {
dom : catWithTerms,
cod : catWithTerms,
ctx : dom.ctx → cod.ctx,
fam :
∏ (Γ : dom.ctx),
dom.fam Γ → cod.fam (ctx Γ),
trm :
∏ (Γ : dom.ctx) (A : dom.fam Γ),
dom.trm Γ A → cod.trm (ctx Γ) (fam Γ A),
ctxExt :
∏ (Γ : dom.ctx) (A : dom.fam Γ),
ctx (dom.ctxExt Γ A) ≡ cod.ctxExt (ctx Γ) (fam Γ A),
ctxFam :
(now betas = add_beta ctxExt betas in
∏ (Γ : dom.ctx) (A : dom.fam Γ) (P : dom.fam (dom.ctxExt Γ A)),
fam Γ (dom.famExt Γ A P) ≡
cod.famExt (ctx Γ) (fam Γ A) (fam (dom.ctxExt Γ A) P)),
emptyFam :
∏ (Γ : dom.ctx),
fam Γ (dom.emptyFam Γ) ≡ cod.emptyFam (ctx Γ)
}
let slice =
(λ C Γ,
now betas = add_beta C.assocCtxExt betas in
{
ctx = C.fam Γ,
fam = λ A, C.fam (C.ctxExt Γ A),
trm = λ A P, C.trm (C.ctxExt Γ A) P,
emptyCtx = C.emptyFam Γ,
emptyFam = λ A, C.emptyFam (C.ctxExt Γ A),
ctxExt = C.famExt Γ,
famExt = λ A, C.famExt (C.ctxExt Γ A),
assocCtxExt = hippy,
assocFamExt = hippy,
emptyCtxExt = hippy,
emptyFamLeft = hippy,
emptyFamRight = hippy
} : catWithTerms
)
: ∏ (C : catWithTerms), C.ctx → catWithTerms
| {
"pile_set_name": "Github"
} |
module.exports = require('./uniq');
| {
"pile_set_name": "Github"
} |
using Swashbuckle.AspNetCore.Filters;
namespace WebApi.Models.Examples
{
internal class MaleRequestExample : IExamplesProvider<MaleRequest>
{
public MaleRequest GetExamples()
{
return new MaleRequest { Title = Title.Mr, Age = 24, FirstName = "Steve Auto", Income = null };
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2011-2013, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
/*jslint node:true*/
'use strict';
var debug = require('debug')('app'),
express = require('express'),
libmojito = require('../../../'),
app;
app = express();
app.set('port', process.env.PORT || 8666);
libmojito.extend(app);
app.use(libmojito.middleware());
// To use the routing configured in `routes.json`, which
// is deprecated, you uncomment this line.
// app.mojito.attachRoutes();
app.get('/status', function (req, res) {
res.send('200 OK');
});
app.get('/', libmojito.dispatch('frame.index'));
app.get('/example1', libmojito.dispatch('frame.example1'));
app.listen(app.get('port'), function () {
debug('Server listening on port ' + app.get('port') + ' ' +
'in ' + app.get('env') + ' mode');
});
module.exports = app;
| {
"pile_set_name": "Github"
} |
caption: $:/tags/Exporter
created: 20180926170345251
description: marks the exporters
modified: 20180926171456497
tags: SystemTags
title: SystemTag: $:/tags/Exporter
type: text/vnd.tiddlywiki
The [[system tag|SystemTags]] `$:/tags/Exporter` marks the exporters | {
"pile_set_name": "Github"
} |
# Contributing
## Issues
* Request features and report bugs using the [GitHub Issue Tracker](https://github.com/fsnotify/fsnotify/issues).
* Please indicate the platform you are using fsnotify on.
* A code example to reproduce the problem is appreciated.
## Pull Requests
### Contributor License Agreement
fsnotify is derived from code in the [golang.org/x/exp](https://godoc.org/golang.org/x/exp) package and it may be included [in the standard library](https://github.com/fsnotify/fsnotify/issues/1) in the future. Therefore fsnotify carries the same [LICENSE](https://github.com/fsnotify/fsnotify/blob/master/LICENSE) as Go. Contributors retain their copyright, so you need to fill out a short form before we can accept your contribution: [Google Individual Contributor License Agreement](https://developers.google.com/open-source/cla/individual).
Please indicate that you have signed the CLA in your pull request.
### How fsnotify is Developed
* Development is done on feature branches.
* Tests are run on BSD, Linux, macOS and Windows.
* Pull requests are reviewed and [applied to master][am] using [hub][].
* Maintainers may modify or squash commits rather than asking contributors to.
* To issue a new release, the maintainers will:
* Update the CHANGELOG
* Tag a version, which will become available through gopkg.in.
### How to Fork
For smooth sailing, always use the original import path. Installing with `go get` makes this easy.
1. Install from GitHub (`go get -u github.com/fsnotify/fsnotify`)
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Ensure everything works and the tests pass (see below)
4. Commit your changes (`git commit -am 'Add some feature'`)
Contribute upstream:
1. Fork fsnotify on GitHub
2. Add your remote (`git remote add fork [email protected]:mycompany/repo.git`)
3. Push to the branch (`git push fork my-new-feature`)
4. Create a new Pull Request on GitHub
This workflow is [thoroughly explained by Katrina Owen](https://splice.com/blog/contributing-open-source-git-repositories-go/).
### Testing
fsnotify uses build tags to compile different code on Linux, BSD, macOS, and Windows.
Before doing a pull request, please do your best to test your changes on multiple platforms, and list which platforms you were able/unable to test on.
To aid in cross-platform testing there is a Vagrantfile for Linux and BSD.
* Install [Vagrant](http://www.vagrantup.com/) and [VirtualBox](https://www.virtualbox.org/)
* Setup [Vagrant Gopher](https://github.com/nathany/vagrant-gopher) in your `src` folder.
* Run `vagrant up` from the project folder. You can also setup just one box with `vagrant up linux` or `vagrant up bsd` (note: the BSD box doesn't support Windows hosts at this time, and NFS may prompt for your host OS password)
* Once setup, you can run the test suite on a given OS with a single command `vagrant ssh linux -c 'cd fsnotify/fsnotify; go test'`.
* When you're done, you will want to halt or destroy the Vagrant boxes.
Notice: fsnotify file system events won't trigger in shared folders. The tests get around this limitation by using the /tmp directory.
Right now there is no equivalent solution for Windows and macOS, but there are Windows VMs [freely available from Microsoft](http://www.modern.ie/en-us/virtualization-tools#downloads).
### Maintainers
Help maintaining fsnotify is welcome. To be a maintainer:
* Submit a pull request and sign the CLA as above.
* You must be able to run the test suite on Mac, Windows, Linux and BSD.
To keep master clean, the fsnotify project uses the "apply mail" workflow outlined in Nathaniel Talbott's post ["Merge pull request" Considered Harmful][am]. This requires installing [hub][].
All code changes should be internal pull requests.
Releases are tagged using [Semantic Versioning](http://semver.org/).
[hub]: https://github.com/github/hub
[am]: http://blog.spreedly.com/2014/06/24/merge-pull-request-considered-harmful/#.VGa5yZPF_Zs
| {
"pile_set_name": "Github"
} |
<presence xmlns="urn:cesnet:mod6"/>
| {
"pile_set_name": "Github"
} |
//--------------------------------------------------------------------------------------------------
/** @file Level.java
*
* Copyright (C) Sierra Wireless Inc.
*/
//--------------------------------------------------------------------------------------------------
package io.legato;
// -------------------------------------------------------------------------------------------------
/**
* Custom log levels to better integrate with the Legato log.
*/
// -------------------------------------------------------------------------------------------------
public class Level extends java.util.logging.Level {
private static final long serialVersionUID = 6691808493564990397L;
public static Level EMERG = new Level("EMERG", 1000);
public static Level CRIT = new Level("CRIT", 900);
public static Level ERR = new Level("ERR", 800);
public static Level WARN = new Level("WARN", 700);
public static Level INFO = new Level("INFO", 600);
public static Level DEBUG = new Level("DEBUG", 300);
protected Level(String name, int level) {
super(name, level);
}
}
| {
"pile_set_name": "Github"
} |
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`<Headline /> should render h2 headline 1`] = `
.c0 {
-webkit-letter-spacing: 0.5px;
-moz-letter-spacing: 0.5px;
-ms-letter-spacing: 0.5px;
letter-spacing: 0.5px;
font-weight: 300;
margin: 0;
padding: 0 0 0.5rem 0;
font-family: inherit;
color: inherit;
}
@media (min-width:980px) {
.c0 {
font-size: 2rem;
}
}
@media (max-width:979px) {
.c0 {
font-size: 1.5rem;
}
}
@media (min-width:980px) {
.c0 {
line-height: 2.25rem;
}
}
@media (max-width:979px) {
.c0 {
line-height: 1.75rem;
}
}
<Headline
level={2}
>
<styled.h2
level={2}
>
<StyledComponent
forwardedComponent={
Object {
"$$typeof": Symbol(react.forward_ref),
"attrs": Array [],
"componentStyle": ComponentStyle {
"componentId": "sc-bwzfXH",
"isStatic": false,
"lastClassName": "c0",
"rules": Array [
[Function],
],
},
"displayName": "styled.h2",
"foldedComponentIds": Array [],
"render": [Function],
"styledComponentId": "sc-bwzfXH",
"target": "h2",
"toString": [Function],
"warnTooManyClasses": [Function],
"withComponent": [Function],
}
}
forwardedRef={null}
level={2}
>
<h2
className="c0"
>
h2 Headline
</h2>
</StyledComponent>
</styled.h2>
</Headline>
`;
| {
"pile_set_name": "Github"
} |
// WimHandlerOut.cpp
#include "../../../Common/ComTry.h"
#include "../../../Common/IntToString.h"
#include "../../../Common/StringToInt.h"
#include "../../../Common/UTFConvert.h"
#include "../../../Common/Wildcard.h"
#include "../../../Windows/PropVariant.h"
#include "../../../Windows/TimeUtils.h"
#include "../../Common/LimitedStreams.h"
#include "../../Common/ProgressUtils.h"
#include "../../Common/StreamUtils.h"
#include "../../Common/UniqBlocks.h"
#include "../../Crypto/RandGen.h"
#include "../../Crypto/Sha1Cls.h"
#include "WimHandler.h"
using namespace NWindows;
namespace NArchive {
namespace NWim {
static int AddUniqHash(const CStreamInfo *streams, CUIntVector &sorted, const Byte *h, int streamIndexForInsert)
{
unsigned left = 0, right = sorted.Size();
while (left != right)
{
unsigned mid = (left + right) / 2;
unsigned index = sorted[mid];
const Byte *hash2 = streams[index].Hash;
unsigned i;
for (i = 0; i < kHashSize; i++)
if (h[i] != hash2[i])
break;
if (i == kHashSize)
return index;
if (h[i] < hash2[i])
right = mid;
else
left = mid + 1;
}
if (streamIndexForInsert >= 0)
sorted.Insert(left, streamIndexForInsert);
return -1;
}
struct CAltStream
{
int UpdateIndex;
int HashIndex;
UInt64 Size;
UString Name;
bool Skip;
CAltStream(): UpdateIndex(-1), HashIndex(-1), Skip(false) {}
};
struct CMetaItem
{
int UpdateIndex;
int HashIndex;
UInt64 Size;
FILETIME CTime;
FILETIME ATime;
FILETIME MTime;
UInt32 Attrib;
UInt64 FileID;
UInt64 VolID;
UString Name;
UString ShortName;
int SecurityId; // -1: means no secutity ID
bool IsDir;
bool Skip;
unsigned NumSkipAltStreams;
CObjectVector<CAltStream> AltStreams;
CByteBuffer Reparse;
unsigned GetNumAltStreams() const { return AltStreams.Size() - NumSkipAltStreams; }
CMetaItem(): UpdateIndex(-1), HashIndex(-1), SecurityId(-1),
FileID(0), VolID(0),
Skip(false), NumSkipAltStreams(0) {}
};
static int Compare_HardLink_MetaItems(const CMetaItem &a1, const CMetaItem &a2)
{
if (a1.VolID < a2.VolID) return -1;
if (a1.VolID > a2.VolID) return 1;
if (a1.FileID < a2.FileID) return -1;
if (a1.FileID > a2.FileID) return 1;
if (a1.Size < a2.Size) return -1;
if (a1.Size > a2.Size) return 1;
return ::CompareFileTime(&a1.MTime, &a2.MTime);
}
static int AddToHardLinkList(const CObjectVector<CMetaItem> &metaItems, unsigned indexOfItem, CUIntVector &indexes)
{
const CMetaItem &mi = metaItems[indexOfItem];
unsigned left = 0, right = indexes.Size();
while (left != right)
{
unsigned mid = (left + right) / 2;
unsigned index = indexes[mid];
int comp = Compare_HardLink_MetaItems(mi, metaItems[index]);
if (comp == 0)
return index;
if (comp < 0)
right = mid;
else
left = mid + 1;
}
indexes.Insert(left, indexOfItem);
return -1;
}
struct CUpdateItem
{
unsigned CallbackIndex; // index in callback
int MetaIndex; // index in in MetaItems[]
int AltStreamIndex; // index in CMetaItem::AltStreams vector
// -1: if not alt stream?
int InArcIndex; // >= 0, if we use OLD Data
// -1, if we use NEW Data
CUpdateItem(): MetaIndex(-1), AltStreamIndex(-1), InArcIndex(-1) {}
};
struct CDir
{
int MetaIndex;
CObjectVector<CDir> Dirs;
CUIntVector Files; // indexes in MetaItems[]
CDir(): MetaIndex(-1) {}
unsigned GetNumDirs() const;
unsigned GetNumFiles() const;
UInt64 GetTotalSize(const CObjectVector<CMetaItem> &metaItems) const;
bool FindDir(const CObjectVector<CMetaItem> &items, const UString &name, unsigned &index);
};
/* imagex counts Junctions as files (not as dirs).
We suppose that it's not correct */
unsigned CDir::GetNumDirs() const
{
unsigned num = Dirs.Size();
FOR_VECTOR (i, Dirs)
num += Dirs[i].GetNumDirs();
return num;
}
unsigned CDir::GetNumFiles() const
{
unsigned num = Files.Size();
FOR_VECTOR (i, Dirs)
num += Dirs[i].GetNumFiles();
return num;
}
UInt64 CDir::GetTotalSize(const CObjectVector<CMetaItem> &metaItems) const
{
UInt64 sum = 0;
unsigned i;
for (i = 0; i < Files.Size(); i++)
sum += metaItems[Files[i]].Size;
for (i = 0; i < Dirs.Size(); i++)
sum += Dirs[i].GetTotalSize(metaItems);
return sum;
}
bool CDir::FindDir(const CObjectVector<CMetaItem> &items, const UString &name, unsigned &index)
{
unsigned left = 0, right = Dirs.Size();
while (left != right)
{
unsigned mid = (left + right) / 2;
int comp = CompareFileNames(name, items[Dirs[mid].MetaIndex].Name);
if (comp == 0)
{
index = mid;
return true;
}
if (comp < 0)
right = mid;
else
left = mid + 1;
}
index = left;
return false;
}
STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type)
{
*type = NFileTimeType::kWindows;
return S_OK;
}
HRESULT CHandler::GetOutProperty(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, PROPVARIANT *value)
{
if (arcIndex >= 0)
return GetProperty(arcIndex, propID, value);
return callback->GetProperty(callbackIndex, propID, value);
}
HRESULT CHandler::GetTime(IArchiveUpdateCallback *callback, UInt32 callbackIndex, Int32 arcIndex, PROPID propID, FILETIME &ft)
{
ft.dwLowDateTime = ft.dwHighDateTime = 0;
NCOM::CPropVariant prop;
RINOK(GetOutProperty(callback, callbackIndex, arcIndex, propID, &prop));
if (prop.vt == VT_FILETIME)
ft = prop.filetime;
else if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
return S_OK;
}
static HRESULT GetRootTime(
IArchiveGetRootProps *callback,
IArchiveGetRootProps *arcRoot,
PROPID propID, FILETIME &ft)
{
NCOM::CPropVariant prop;
if (callback)
{
RINOK(callback->GetRootProp(propID, &prop));
if (prop.vt == VT_FILETIME)
{
ft = prop.filetime;
return S_OK;
}
if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
}
if (arcRoot)
{
RINOK(arcRoot->GetRootProp(propID, &prop));
if (prop.vt == VT_FILETIME)
{
ft = prop.filetime;
return S_OK;
}
if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
}
return S_OK;
}
#define Set16(p, d) SetUi16(p, d)
#define Set32(p, d) SetUi32(p, d)
#define Set64(p, d) SetUi64(p, d)
void CResource::WriteTo(Byte *p) const
{
Set64(p, PackSize);
p[7] = Flags;
Set64(p + 8, Offset);
Set64(p + 16, UnpackSize);
}
void CHeader::WriteTo(Byte *p) const
{
memcpy(p, kSignature, kSignatureSize);
Set32(p + 8, kHeaderSizeMax);
Set32(p + 0xC, Version);
Set32(p + 0x10, Flags);
Set32(p + 0x14, ChunkSize);
memcpy(p + 0x18, Guid, 16);
Set16(p + 0x28, PartNumber);
Set16(p + 0x2A, NumParts);
Set32(p + 0x2C, NumImages);
OffsetResource.WriteTo(p + 0x30);
XmlResource.WriteTo(p + 0x48);
MetadataResource.WriteTo(p + 0x60);
IntegrityResource.WriteTo(p + 0x7C);
Set32(p + 0x78, BootIndex);
memset(p + 0x94, 0, 60);
}
void CStreamInfo::WriteTo(Byte *p) const
{
Resource.WriteTo(p);
Set16(p + 0x18, PartNumber);
Set32(p + 0x1A, RefCount);
memcpy(p + 0x1E, Hash, kHashSize);
}
class CInStreamWithSha1:
public ISequentialInStream,
public CMyUnknownImp
{
CMyComPtr<ISequentialInStream> _stream;
UInt64 _size;
NCrypto::NSha1::CContext _sha;
public:
MY_UNKNOWN_IMP1(IInStream)
STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
void SetStream(ISequentialInStream *stream) { _stream = stream; }
void Init()
{
_size = 0;
_sha.Init();
}
void ReleaseStream() { _stream.Release(); }
UInt64 GetSize() const { return _size; }
void Final(Byte *digest) { _sha.Final(digest); }
};
STDMETHODIMP CInStreamWithSha1::Read(void *data, UInt32 size, UInt32 *processedSize)
{
UInt32 realProcessedSize;
HRESULT result = _stream->Read(data, size, &realProcessedSize);
_size += realProcessedSize;
_sha.Update((const Byte *)data, realProcessedSize);
if (processedSize)
*processedSize = realProcessedSize;
return result;
}
static void SetFileTimeToMem(Byte *p, const FILETIME &ft)
{
Set32(p, ft.dwLowDateTime);
Set32(p + 4, ft.dwHighDateTime);
}
static size_t WriteItem_Dummy(const CMetaItem &item)
{
if (item.Skip)
return 0;
unsigned fileNameLen = item.Name.Len() * 2;
// we write fileNameLen + 2 + 2 to be same as original WIM.
unsigned fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2);
unsigned shortNameLen = item.ShortName.Len() * 2;
unsigned shortNameLen2 = (shortNameLen == 0 ? 2 : shortNameLen + 4);
size_t totalLen = ((kDirRecordSize + fileNameLen2 + shortNameLen2 + 6) & ~7);
if (item.GetNumAltStreams() != 0)
{
if (!item.IsDir)
{
UInt32 curLen = (((0x26 + 0) + 6) & ~7);
totalLen += curLen;
}
FOR_VECTOR (i, item.AltStreams)
{
const CAltStream &ss = item.AltStreams[i];
if (ss.Skip)
continue;
fileNameLen = ss.Name.Len() * 2;
fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2 + 2);
UInt32 curLen = (((0x26 + fileNameLen2) + 6) & ~7);
totalLen += curLen;
}
}
return totalLen;
}
static size_t WriteItem(const CStreamInfo *streams, const CMetaItem &item, Byte *p)
{
if (item.Skip)
return 0;
unsigned fileNameLen = item.Name.Len() * 2;
unsigned fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2);
unsigned shortNameLen = item.ShortName.Len() * 2;
unsigned shortNameLen2 = (shortNameLen == 0 ? 2 : shortNameLen + 4);
size_t totalLen = ((kDirRecordSize + fileNameLen2 + shortNameLen2 + 6) & ~7);
memset(p, 0, totalLen);
Set64(p, totalLen);
Set64(p + 8, item.Attrib);
Set32(p + 0xC, (Int32)item.SecurityId);
SetFileTimeToMem(p + 0x28, item.CTime);
SetFileTimeToMem(p + 0x30, item.ATime);
SetFileTimeToMem(p + 0x38, item.MTime);
/* WIM format probably doesn't support hard links to symbolic links.
In these cases it just stores symbolic links (REPARSE TAGS).
Check it in new versions of WIM software form MS !!!
We also follow that scheme */
if (item.Reparse.Size() != 0)
{
UInt32 tag = GetUi32(item.Reparse);
Set32(p + 0x58, tag);
// Set32(p + 0x5C, 0); // probably it's always ZERO
}
else if (item.FileID != 0)
{
Set64(p + 0x58, item.FileID);
}
Set16(p + 0x62, (UInt16)shortNameLen);
Set16(p + 0x64, (UInt16)fileNameLen);
unsigned i;
for (i = 0; i * 2 < fileNameLen; i++)
Set16(p + kDirRecordSize + i * 2, item.Name[i]);
for (i = 0; i * 2 < shortNameLen; i++)
Set16(p + kDirRecordSize + fileNameLen2 + i * 2, item.ShortName[i]);
if (item.GetNumAltStreams() == 0)
{
if (item.HashIndex >= 0)
memcpy(p + 0x40, streams[item.HashIndex].Hash, kHashSize);
}
else
{
Set16(p + 0x60, (UInt16)(item.GetNumAltStreams() + (item.IsDir ? 0 : 1)));
p += totalLen;
if (!item.IsDir)
{
UInt32 curLen = (((0x26 + 0) + 6) & ~7);
memset(p, 0, curLen);
Set64(p, curLen);
if (item.HashIndex >= 0)
memcpy(p + 0x10, streams[item.HashIndex].Hash, kHashSize);
totalLen += curLen;
p += curLen;
}
FOR_VECTOR (si, item.AltStreams)
{
const CAltStream &ss = item.AltStreams[si];
if (ss.Skip)
continue;
fileNameLen = ss.Name.Len() * 2;
fileNameLen2 = (fileNameLen == 0 ? 0 : fileNameLen + 2 + 2);
UInt32 curLen = (((0x26 + fileNameLen2) + 6) & ~7);
memset(p, 0, curLen);
Set64(p, curLen);
if (ss.HashIndex >= 0)
memcpy(p + 0x10, streams[ss.HashIndex].Hash, kHashSize);
Set16(p + 0x24, (UInt16)fileNameLen);
for (i = 0; i * 2 < fileNameLen; i++)
Set16(p + 0x26 + i * 2, ss.Name[i]);
totalLen += curLen;
p += curLen;
}
}
return totalLen;
}
struct CDb
{
CMetaItem DefaultDirItem;
const CStreamInfo *Hashes;
CObjectVector<CMetaItem> MetaItems;
CRecordVector<CUpdateItem> UpdateItems;
CUIntVector UpdateIndexes; /* indexes in UpdateItems in order of writing data streams
to disk (the order of tree items). */
size_t WriteTree_Dummy(const CDir &tree) const;
void WriteTree(const CDir &tree, Byte *dest, size_t &pos) const;
void WriteOrderList(const CDir &tree);
};
size_t CDb::WriteTree_Dummy(const CDir &tree) const
{
unsigned i;
size_t pos = 0;
for (i = 0; i < tree.Files.Size(); i++)
pos += WriteItem_Dummy(MetaItems[tree.Files[i]]);
for (i = 0; i < tree.Dirs.Size(); i++)
{
const CDir &subDir = tree.Dirs[i];
pos += WriteItem_Dummy(MetaItems[subDir.MetaIndex]);
pos += WriteTree_Dummy(subDir);
}
return pos + 8;
}
void CDb::WriteTree(const CDir &tree, Byte *dest, size_t &pos) const
{
unsigned i;
for (i = 0; i < tree.Files.Size(); i++)
pos += WriteItem(Hashes, MetaItems[tree.Files[i]], dest + pos);
size_t posStart = pos;
for (i = 0; i < tree.Dirs.Size(); i++)
pos += WriteItem_Dummy(MetaItems[tree.Dirs[i].MetaIndex]);
Set64(dest + pos, 0);
pos += 8;
for (i = 0; i < tree.Dirs.Size(); i++)
{
const CDir &subDir = tree.Dirs[i];
const CMetaItem &metaItem = MetaItems[subDir.MetaIndex];
bool needCreateTree = (metaItem.Reparse.Size() == 0)
|| !subDir.Files.IsEmpty()
|| !subDir.Dirs.IsEmpty();
size_t len = WriteItem(Hashes, metaItem, dest + posStart);
posStart += len;
if (needCreateTree)
{
Set64(dest + posStart - len + 0x10, pos); // subdirOffset
WriteTree(subDir, dest, pos);
}
}
}
void CDb::WriteOrderList(const CDir &tree)
{
if (tree.MetaIndex >= 0)
{
const CMetaItem &mi = MetaItems[tree.MetaIndex];
if (mi.UpdateIndex >= 0)
UpdateIndexes.Add(mi.UpdateIndex);
FOR_VECTOR (si, mi.AltStreams)
UpdateIndexes.Add(mi.AltStreams[si].UpdateIndex);
}
unsigned i;
for (i = 0; i < tree.Files.Size(); i++)
{
const CMetaItem &mi = MetaItems[tree.Files[i]];
UpdateIndexes.Add(mi.UpdateIndex);
FOR_VECTOR (si, mi.AltStreams)
UpdateIndexes.Add(mi.AltStreams[si].UpdateIndex);
}
for (i = 0; i < tree.Dirs.Size(); i++)
WriteOrderList(tree.Dirs[i]);
}
static void AddTag_ToString(AString &s, const char *name, const char *value)
{
s += '<';
s += name;
s += '>';
s += value;
s += '<';
s += '/';
s += name;
s += '>';
}
static void AddTagUInt64_ToString(AString &s, const char *name, UInt64 value)
{
char temp[32];
ConvertUInt64ToString(value, temp);
AddTag_ToString(s, name, temp);
}
static CXmlItem &AddUniqueTag(CXmlItem &parentItem, const char *name)
{
int index = parentItem.FindSubTag(name);
if (index < 0)
{
CXmlItem &subItem = parentItem.SubItems.AddNew();
subItem.IsTag = true;
subItem.Name = name;
return subItem;
}
CXmlItem &subItem = parentItem.SubItems[index];
subItem.SubItems.Clear();
return subItem;
}
static void AddTag_UInt64_2(CXmlItem &item, UInt64 value)
{
CXmlItem &subItem = item.SubItems.AddNew();
subItem.IsTag = false;
char temp[32];
ConvertUInt64ToString(value, temp);
subItem.Name = temp;
}
static void AddTag_UInt64(CXmlItem &parentItem, const char *name, UInt64 value)
{
AddTag_UInt64_2(AddUniqueTag(parentItem, name), value);
}
static void AddTag_Hex(CXmlItem &item, const char *name, UInt32 value)
{
item.IsTag = true;
item.Name = name;
char temp[16];
temp[0] = '0';
temp[1] = 'x';
ConvertUInt32ToHex8Digits(value, temp + 2);
CXmlItem &subItem = item.SubItems.AddNew();
subItem.IsTag = false;
subItem.Name = temp;
}
static void AddTag_Time_2(CXmlItem &item, const FILETIME &ft)
{
AddTag_Hex(item.SubItems.AddNew(), "HIGHPART", ft.dwHighDateTime);
AddTag_Hex(item.SubItems.AddNew(), "LOWPART", ft.dwLowDateTime);
}
static void AddTag_Time(CXmlItem &parentItem, const char *name, const FILETIME &ft)
{
AddTag_Time_2(AddUniqueTag(parentItem, name), ft);
}
static void AddTag_String_IfEmpty(CXmlItem &parentItem, const char *name, const char *value)
{
int index = parentItem.FindSubTag(name);
if (index >= 0)
return;
CXmlItem &tag = parentItem.SubItems.AddNew();
tag.IsTag = true;
tag.Name = name;
CXmlItem &subItem = tag.SubItems.AddNew();
subItem.IsTag = false;
subItem.Name = value;
}
void CHeader::SetDefaultFields(bool useLZX)
{
Version = k_Version_NonSolid;
Flags = NHeaderFlags::kReparsePointFixup;
ChunkSize = 0;
if (useLZX)
{
Flags |= NHeaderFlags::kCompression | NHeaderFlags::kLZX;
ChunkSize = kChunkSize;
ChunkSizeBits = kChunkSizeBits;
}
g_RandomGenerator.Generate(Guid, 16);
PartNumber = 1;
NumParts = 1;
NumImages = 1;
BootIndex = 0;
OffsetResource.Clear();
XmlResource.Clear();
MetadataResource.Clear();
IntegrityResource.Clear();
}
static void AddTrees(CObjectVector<CDir> &trees, CObjectVector<CMetaItem> &metaItems, const CMetaItem &ri, int curTreeIndex)
{
while (curTreeIndex >= (int)trees.Size())
trees.AddNew().Dirs.AddNew().MetaIndex = metaItems.Add(ri);
}
#define IS_LETTER_CHAR(c) ((c) >= 'a' && (c) <= 'z' || (c) >= 'A' && (c) <= 'Z')
STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outSeqStream, UInt32 numItems, IArchiveUpdateCallback *callback)
{
COM_TRY_BEGIN
if (!IsUpdateSupported())
return E_NOTIMPL;
bool isUpdate = (_volumes.Size() != 0);
int defaultImageIndex = _defaultImageNumber - 1;
bool showImageNumber;
if (isUpdate)
{
showImageNumber = _showImageNumber;
if (!showImageNumber)
defaultImageIndex = _db.IndexOfUserImage;
}
else
{
showImageNumber = (_set_use_ShowImageNumber && _set_showImageNumber);
if (!showImageNumber)
defaultImageIndex = 0;
}
if (defaultImageIndex >= kNumImagesMaxUpdate)
return E_NOTIMPL;
CMyComPtr<IOutStream> outStream;
RINOK(outSeqStream->QueryInterface(IID_IOutStream, (void **)&outStream));
if (!outStream)
return E_NOTIMPL;
if (!callback)
return E_FAIL;
CDb db;
CObjectVector<CDir> trees;
CMetaItem ri; // default DIR item
FILETIME ftCur;
NTime::GetCurUtcFileTime(ftCur);
ri.MTime = ri.ATime = ri.CTime = ftCur;
ri.Attrib = FILE_ATTRIBUTE_DIRECTORY;
ri.IsDir = true;
// ---------- Detect changed images ----------
unsigned i;
CBoolVector isChangedImage;
{
CUIntVector numUnchangedItemsInImage;
for (i = 0; i < _db.Images.Size(); i++)
{
numUnchangedItemsInImage.Add(0);
isChangedImage.Add(false);
}
for (i = 0; i < numItems; i++)
{
UInt32 indexInArchive;
Int32 newData, newProps;
RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive));
if (newProps == 0)
{
if (indexInArchive >= _db.SortedItems.Size())
continue;
const CItem &item = _db.Items[_db.SortedItems[indexInArchive]];
if (newData == 0)
{
if (item.ImageIndex >= 0)
numUnchangedItemsInImage[item.ImageIndex]++;
}
else
{
// oldProps & newData. Current version of 7-Zip doesn't use it
if (item.ImageIndex >= 0)
isChangedImage[item.ImageIndex] = true;
}
}
else if (!showImageNumber)
{
if (defaultImageIndex >= 0 && defaultImageIndex < (int)isChangedImage.Size())
isChangedImage[defaultImageIndex] = true;
}
else
{
NCOM::CPropVariant prop;
RINOK(callback->GetProperty(i, kpidPath, &prop));
if (prop.vt != VT_BSTR)
return E_INVALIDARG;
const wchar_t *path = prop.bstrVal;
if (!path)
return E_INVALIDARG;
const wchar_t *end;
UInt64 val = ConvertStringToUInt64(path, &end);
if (end == path)
return E_INVALIDARG;
if (val == 0 || val > kNumImagesMaxUpdate)
return E_INVALIDARG;
wchar_t c = *end;
if (c != 0 && c != ':' && c != L'/' && c != WCHAR_PATH_SEPARATOR)
return E_INVALIDARG;
unsigned imageIndex = (unsigned)val - 1;
if (imageIndex < _db.Images.Size())
isChangedImage[imageIndex] = true;
if (_defaultImageNumber > 0 && val != (unsigned)_defaultImageNumber)
return E_INVALIDARG;
}
}
for (i = 0; i < _db.Images.Size(); i++)
if (!isChangedImage[i])
isChangedImage[i] = _db.GetNumUserItemsInImage(i) != numUnchangedItemsInImage[i];
}
if (defaultImageIndex >= 0)
{
for (i = 0; i < _db.Images.Size(); i++)
if ((int)i != defaultImageIndex)
isChangedImage[i] = false;
}
CMyComPtr<IArchiveGetRawProps> getRawProps;
callback->QueryInterface(IID_IArchiveGetRawProps, (void **)&getRawProps);
CMyComPtr<IArchiveGetRootProps> getRootProps;
callback->QueryInterface(IID_IArchiveGetRootProps, (void **)&getRootProps);
CObjectVector<CUniqBlocks> secureBlocks;
if (!showImageNumber && (getRootProps || isUpdate) &&
(
defaultImageIndex >= (int)isChangedImage.Size()
|| defaultImageIndex < 0 // test it
|| isChangedImage[defaultImageIndex]
))
{
// Fill Root Item: Metadata and security
CMetaItem rootItem = ri;
{
const void *data = NULL;
UInt32 dataSize = 0;
UInt32 propType = 0;
if (getRootProps)
{
RINOK(getRootProps->GetRootRawProp(kpidNtSecure, &data, &dataSize, &propType));
}
if (dataSize == 0 && isUpdate)
{
RINOK(GetRootRawProp(kpidNtSecure, &data, &dataSize, &propType));
}
if (dataSize != 0)
{
if (propType != NPropDataType::kRaw)
return E_FAIL;
while (defaultImageIndex >= (int)secureBlocks.Size())
secureBlocks.AddNew();
CUniqBlocks &secUniqBlocks = secureBlocks[defaultImageIndex];
rootItem.SecurityId = secUniqBlocks.AddUniq((const Byte *)data, dataSize);
}
}
IArchiveGetRootProps *thisGetRoot = isUpdate ? this : NULL;
RINOK(GetRootTime(getRootProps, thisGetRoot, kpidCTime, rootItem.CTime));
RINOK(GetRootTime(getRootProps, thisGetRoot, kpidATime, rootItem.ATime));
RINOK(GetRootTime(getRootProps, thisGetRoot, kpidMTime, rootItem.MTime));
{
NCOM::CPropVariant prop;
if (getRootProps)
{
RINOK(getRootProps->GetRootProp(kpidAttrib, &prop));
if (prop.vt == VT_UI4)
rootItem.Attrib = prop.ulVal;
else if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
}
if (prop.vt == VT_EMPTY && thisGetRoot)
{
RINOK(GetRootProp(kpidAttrib, &prop));
if (prop.vt == VT_UI4)
rootItem.Attrib = prop.ulVal;
else if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
}
rootItem.Attrib |= FILE_ATTRIBUTE_DIRECTORY;
}
AddTrees(trees, db.MetaItems, ri, defaultImageIndex);
db.MetaItems[trees[defaultImageIndex].Dirs[0].MetaIndex] = rootItem;
}
// ---------- Request Metadata for changed items ----------
UString fileName;
for (i = 0; i < numItems; i++)
{
CUpdateItem ui;
UInt32 indexInArchive;
Int32 newData, newProps;
RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive));
if (newData == 0 || newProps == 0)
{
if (indexInArchive >= _db.SortedItems.Size())
continue;
const CItem &item = _db.Items[_db.SortedItems[indexInArchive]];
if (item.ImageIndex >= 0)
{
if (!isChangedImage[item.ImageIndex])
{
if (newData == 0 && newProps == 0)
continue;
return E_FAIL;
}
}
else
{
// if deleted item was not renamed, we just skip it
if (newProps == 0)
continue;
if (item.StreamIndex >= 0)
{
// we don't support property change for SolidBig streams
if (_db.DataStreams[item.StreamIndex].Resource.IsSolidBig())
return E_NOTIMPL;
}
}
if (newData == 0)
ui.InArcIndex = indexInArchive;
}
// we set arcIndex only if we must use old props
Int32 arcIndex = (newProps ? -1 : indexInArchive);
bool isDir = false;
{
NCOM::CPropVariant prop;
RINOK(GetOutProperty(callback, i, arcIndex, kpidIsDir, &prop));
if (prop.vt == VT_BOOL)
isDir = (prop.boolVal != VARIANT_FALSE);
else if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
}
bool isAltStream = false;
{
NCOM::CPropVariant prop;
RINOK(GetOutProperty(callback, i, arcIndex, kpidIsAltStream, &prop));
if (prop.vt == VT_BOOL)
isAltStream = (prop.boolVal != VARIANT_FALSE);
else if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
}
if (isDir && isAltStream)
return E_INVALIDARG;
UInt64 size = 0;
UInt64 iNode = 0;
if (!isDir)
{
if (!newData)
{
NCOM::CPropVariant prop;
GetProperty(indexInArchive, kpidINode, &prop);
if (prop.vt == VT_UI8)
iNode = prop.uhVal.QuadPart;
}
NCOM::CPropVariant prop;
if (newData)
{
RINOK(callback->GetProperty(i, kpidSize, &prop));
}
else
{
RINOK(GetProperty(indexInArchive, kpidSize, &prop));
}
if (prop.vt == VT_UI8)
size = prop.uhVal.QuadPart;
else if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
}
{
NCOM::CPropVariant propPath;
const wchar_t *path = NULL;
RINOK(GetOutProperty(callback, i, arcIndex, kpidPath, &propPath));
if (propPath.vt == VT_BSTR)
path = propPath.bstrVal;
else if (propPath.vt != VT_EMPTY)
return E_INVALIDARG;
if (!path)
return E_INVALIDARG;
CDir *curItem = NULL;
bool isRootImageDir = false;
fileName.Empty();
int imageIndex;
if (!showImageNumber)
{
imageIndex = defaultImageIndex;
AddTrees(trees, db.MetaItems, ri, imageIndex);
curItem = &trees[imageIndex].Dirs[0];
}
else
{
const wchar_t *end;
UInt64 val = ConvertStringToUInt64(path, &end);
if (end == path)
return E_INVALIDARG;
if (val == 0 || val > kNumImagesMaxUpdate)
return E_INVALIDARG;
imageIndex = (int)val - 1;
if (imageIndex < (int)isChangedImage.Size())
if (!isChangedImage[imageIndex])
return E_FAIL;
AddTrees(trees, db.MetaItems, ri, imageIndex);
curItem = &trees[imageIndex].Dirs[0];
wchar_t c = *end;
if (c == 0)
{
if (!isDir || isAltStream)
return E_INVALIDARG;
ui.MetaIndex = curItem->MetaIndex;
isRootImageDir = true;
}
else if (c == ':')
{
if (isDir || !isAltStream)
return E_INVALIDARG;
ui.MetaIndex = curItem->MetaIndex;
CAltStream ss;
ss.Size = size;
ss.Name = end + 1;
ss.UpdateIndex = db.UpdateItems.Size();
ui.AltStreamIndex = db.MetaItems[ui.MetaIndex].AltStreams.Add(ss);
}
else if (c == WCHAR_PATH_SEPARATOR || c == L'/')
{
path = end + 1;
if (*path == 0)
return E_INVALIDARG;
}
else
return E_INVALIDARG;
}
if (ui.MetaIndex < 0)
{
for (;;)
{
wchar_t c = *path++;
if (c == 0)
break;
if (c == WCHAR_PATH_SEPARATOR || c == L'/')
{
unsigned indexOfDir;
if (!curItem->FindDir(db.MetaItems, fileName, indexOfDir))
{
CDir &dir = curItem->Dirs.InsertNew(indexOfDir);
dir.MetaIndex = db.MetaItems.Add(ri);
db.MetaItems.Back().Name = fileName;
}
curItem = &curItem->Dirs[indexOfDir];
fileName.Empty();
}
else
fileName += c;
}
if (isAltStream)
{
int colonPos = fileName.Find(L':');
if (colonPos < 0)
return E_INVALIDARG;
// we want to support cases of c::substream, where c: is drive name
if (colonPos == 1 && fileName[2] == L':' && IS_LETTER_CHAR(fileName[0]))
colonPos = 2;
const UString mainName = fileName.Left(colonPos);
unsigned indexOfDir;
if (mainName.IsEmpty())
ui.MetaIndex = curItem->MetaIndex;
else if (curItem->FindDir(db.MetaItems, mainName, indexOfDir))
ui.MetaIndex = curItem->Dirs[indexOfDir].MetaIndex;
else
{
for (int j = (int)curItem->Files.Size() - 1; j >= 0; j--)
{
int metaIndex = curItem->Files[j];
const CMetaItem &mi = db.MetaItems[metaIndex];
if (CompareFileNames(mainName, mi.Name) == 0)
{
ui.MetaIndex = metaIndex;
break;
}
}
}
if (ui.MetaIndex >= 0)
{
CAltStream ss;
ss.Size = size;
ss.Name = fileName.Ptr(colonPos + 1);
ss.UpdateIndex = db.UpdateItems.Size();
ui.AltStreamIndex = db.MetaItems[ui.MetaIndex].AltStreams.Add(ss);
}
}
}
if (ui.MetaIndex < 0 || isRootImageDir)
{
if (!isRootImageDir)
{
ui.MetaIndex = db.MetaItems.Size();
db.MetaItems.AddNew();
}
CMetaItem &mi = db.MetaItems[ui.MetaIndex];
mi.Size = size;
mi.IsDir = isDir;
mi.Name = fileName;
mi.UpdateIndex = db.UpdateItems.Size();
{
NCOM::CPropVariant prop;
RINOK(GetOutProperty(callback, i, arcIndex, kpidAttrib, &prop));
if (prop.vt == VT_EMPTY)
mi.Attrib = 0;
else if (prop.vt == VT_UI4)
mi.Attrib = prop.ulVal;
else
return E_INVALIDARG;
if (isDir)
mi.Attrib |= FILE_ATTRIBUTE_DIRECTORY;
}
RINOK(GetTime(callback, i, arcIndex, kpidCTime, mi.CTime));
RINOK(GetTime(callback, i, arcIndex, kpidATime, mi.ATime));
RINOK(GetTime(callback, i, arcIndex, kpidMTime, mi.MTime));
{
NCOM::CPropVariant prop;
RINOK(GetOutProperty(callback, i, arcIndex, kpidShortName, &prop));
if (prop.vt == VT_BSTR)
mi.ShortName.SetFromBstr(prop.bstrVal);
else if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
}
while (imageIndex >= (int)secureBlocks.Size())
secureBlocks.AddNew();
if (!isAltStream && (getRawProps || arcIndex >= 0))
{
CUniqBlocks &secUniqBlocks = secureBlocks[imageIndex];
const void *data;
UInt32 dataSize;
UInt32 propType;
data = NULL;
dataSize = 0;
propType = 0;
if (arcIndex >= 0)
{
GetRawProp(arcIndex, kpidNtSecure, &data, &dataSize, &propType);
}
else
{
getRawProps->GetRawProp(i, kpidNtSecure, &data, &dataSize, &propType);
}
if (dataSize != 0)
{
if (propType != NPropDataType::kRaw)
return E_FAIL;
mi.SecurityId = secUniqBlocks.AddUniq((const Byte *)data, dataSize);
}
data = NULL;
dataSize = 0;
propType = 0;
if (arcIndex >= 0)
{
GetRawProp(arcIndex, kpidNtReparse, &data, &dataSize, &propType);
}
else
{
getRawProps->GetRawProp(i, kpidNtReparse, &data, &dataSize, &propType);
}
if (dataSize != 0)
{
if (propType != NPropDataType::kRaw)
return E_FAIL;
mi.Reparse.CopyFrom((const Byte *)data, dataSize);
}
}
if (!isRootImageDir)
{
if (isDir)
{
unsigned indexOfDir;
if (curItem->FindDir(db.MetaItems, fileName, indexOfDir))
curItem->Dirs[indexOfDir].MetaIndex = ui.MetaIndex;
else
curItem->Dirs.InsertNew(indexOfDir).MetaIndex = ui.MetaIndex;
}
else
curItem->Files.Add(ui.MetaIndex);
}
}
}
if (iNode != 0 && ui.MetaIndex >= 0 && ui.AltStreamIndex < 0)
db.MetaItems[ui.MetaIndex].FileID = iNode;
ui.CallbackIndex = i;
db.UpdateItems.Add(ui);
}
unsigned numNewImages = trees.Size();
for (i = numNewImages; i < isChangedImage.Size(); i++)
if (!isChangedImage[i])
numNewImages = i + 1;
AddTrees(trees, db.MetaItems, ri, numNewImages - 1);
for (i = 0; i < trees.Size(); i++)
if (i >= isChangedImage.Size() || isChangedImage[i])
db.WriteOrderList(trees[i]);
UInt64 complexity = 0;
unsigned numDataStreams = _db.DataStreams.Size();
CUIntArr streamsRefs(numDataStreams);
for (i = 0; i < numDataStreams; i++)
streamsRefs[i] = 0;
// ---------- Calculate Streams Refs Counts in unchanged images
for (i = 0; i < _db.Images.Size(); i++)
{
if (isChangedImage[i])
continue;
complexity += _db.MetaStreams[i].Resource.PackSize;
const CImage &image = _db.Images[i];
unsigned endItem = image.StartItem + image.NumItems;
for (unsigned k = image.StartItem; k < endItem; k++)
{
const CItem &item = _db.Items[k];
if (item.StreamIndex >= 0)
streamsRefs[(unsigned)item.StreamIndex]++;
}
}
// ---------- Update Streams Refs Counts in changed images
for (i = 0; i < db.UpdateIndexes.Size(); i++)
{
const CUpdateItem &ui = db.UpdateItems[db.UpdateIndexes[i]];
if (ui.InArcIndex >= 0)
{
if ((unsigned)ui.InArcIndex >= _db.SortedItems.Size())
continue;
const CItem &item = _db.Items[_db.SortedItems[ui.InArcIndex]];
if (item.StreamIndex >= 0)
streamsRefs[(unsigned)item.StreamIndex]++;
}
else
{
const CMetaItem &mi = db.MetaItems[ui.MetaIndex];
UInt64 size;
if (ui.AltStreamIndex < 0)
size = mi.Size;
else
size = mi.AltStreams[ui.AltStreamIndex].Size;
complexity += size;
}
}
// Clear ref counts for SolidBig streams
for (i = 0; i < _db.DataStreams.Size(); i++)
if (_db.DataStreams[i].Resource.IsSolidBig())
streamsRefs[i] = 0;
// Set ref counts for SolidBig streams
for (i = 0; i < _db.DataStreams.Size(); i++)
if (streamsRefs[i] != 0)
{
const CResource &rs = _db.DataStreams[i].Resource;
if (rs.IsSolidSmall())
streamsRefs[_db.Solids[rs.SolidIndex].StreamIndex] = 1;
}
for (i = 0; i < _db.DataStreams.Size(); i++)
if (streamsRefs[i] != 0)
{
const CResource &rs = _db.DataStreams[i].Resource;
if (!rs.IsSolidSmall())
complexity += rs.PackSize;
}
RINOK(callback->SetTotal(complexity));
UInt64 totalComplexity = complexity;
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder;
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(callback, true);
complexity = 0;
// bool useResourceCompression = false;
// use useResourceCompression only if CHeader::Flags compression is also set
CHeader header;
header.SetDefaultFields(false);
if (isUpdate)
{
const CHeader &srcHeader = _volumes[1].Header;
header.Flags = srcHeader.Flags;
header.Version = srcHeader.Version;
header.ChunkSize = srcHeader.ChunkSize;
header.ChunkSizeBits = srcHeader.ChunkSizeBits;
}
{
Byte buf[kHeaderSizeMax];
header.WriteTo(buf);
RINOK(WriteStream(outStream, buf, kHeaderSizeMax));
}
UInt64 curPos = kHeaderSizeMax;
CInStreamWithSha1 *inShaStreamSpec = new CInStreamWithSha1;
CMyComPtr<ISequentialInStream> inShaStream = inShaStreamSpec;
CLimitedSequentialInStream *inStreamLimitedSpec = NULL;
CMyComPtr<CLimitedSequentialInStream> inStreamLimited;
if (_volumes.Size() == 2)
{
inStreamLimitedSpec = new CLimitedSequentialInStream;
inStreamLimited = inStreamLimitedSpec;
inStreamLimitedSpec->SetStream(_volumes[1].Stream);
}
CRecordVector<CStreamInfo> streams;
CUIntVector sortedHashes; // indexes to streams, sorted by SHA1
// ---------- Copy unchanged data streams ----------
UInt64 solidRunOffset = 0;
UInt64 curSolidSize = 0;
for (i = 0; i < _db.DataStreams.Size(); i++)
{
const CStreamInfo &siOld = _db.DataStreams[i];
const CResource &rs = siOld.Resource;
unsigned numRefs = streamsRefs[i];
if (numRefs == 0)
{
if (!rs.IsSolidSmall())
continue;
if (streamsRefs[_db.Solids[rs.SolidIndex].StreamIndex] == 0)
continue;
}
lps->InSize = lps->OutSize = complexity;
RINOK(lps->SetCur());
int streamIndex = streams.Size();
CStreamInfo s;
s.Resource = rs;
s.PartNumber = 1;
s.RefCount = numRefs;
memcpy(s.Hash, siOld.Hash, kHashSize);
if (rs.IsSolid())
{
CSolid &ss = _db.Solids[rs.SolidIndex];
if (rs.IsSolidSmall())
{
UInt64 oldOffset = ss.SolidOffset;
if (rs.Offset < oldOffset)
return E_FAIL;
UInt64 relatOffset = rs.Offset - oldOffset;
s.Resource.Offset = solidRunOffset + relatOffset;
}
else
{
// IsSolidBig
solidRunOffset += curSolidSize;
curSolidSize = ss.UnpackSize;
}
}
else
{
solidRunOffset = 0;
curSolidSize = 0;
}
if (!rs.IsSolid() || rs.IsSolidSmall())
{
int find = AddUniqHash(&streams.Front(), sortedHashes, siOld.Hash, streamIndex);
if (find >= 0)
return E_FAIL; // two streams with same SHA-1
}
if (!rs.IsSolid() || rs.IsSolidBig())
{
RINOK(_volumes[siOld.PartNumber].Stream->Seek(rs.Offset, STREAM_SEEK_SET, NULL));
inStreamLimitedSpec->Init(rs.PackSize);
RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress));
if (copyCoderSpec->TotalSize != rs.PackSize)
return E_FAIL;
s.Resource.Offset = curPos;
curPos += rs.PackSize;
lps->ProgressOffset += rs.PackSize;
}
streams.Add(s);
}
// ---------- Write new items ----------
CUIntVector hlIndexes; // sorted indexes for hard link items
for (i = 0; i < db.UpdateIndexes.Size(); i++)
{
lps->InSize = lps->OutSize = complexity;
RINOK(lps->SetCur());
const CUpdateItem &ui = db.UpdateItems[db.UpdateIndexes[i]];
CMetaItem &mi = db.MetaItems[ui.MetaIndex];
UInt64 size = 0;
if (ui.AltStreamIndex >= 0)
{
if (mi.Skip)
continue;
size = mi.AltStreams[ui.AltStreamIndex].Size;
}
else
{
size = mi.Size;
if (mi.IsDir)
{
// we support LINK files here
if (mi.Reparse.Size() == 0)
continue;
}
}
if (ui.InArcIndex >= 0)
{
// data streams with OLD Data were written already
// we just need to find HashIndex in hashes.
if ((unsigned)ui.InArcIndex >= _db.SortedItems.Size())
return E_FAIL;
const CItem &item = _db.Items[_db.SortedItems[ui.InArcIndex]];
if (item.StreamIndex < 0)
{
if (size == 0)
continue;
// if (_db.ItemHasStream(item))
return E_FAIL;
}
// We support empty file (size = 0, but with stream and SHA-1) from old archive
const CStreamInfo &siOld = _db.DataStreams[item.StreamIndex];
int index = AddUniqHash(&streams.Front(), sortedHashes, siOld.Hash, -1);
// we must have written that stream already
if (index < 0)
return E_FAIL;
if (ui.AltStreamIndex < 0)
mi.HashIndex = index;
else
mi.AltStreams[ui.AltStreamIndex].HashIndex = index;
continue;
}
CMyComPtr<ISequentialInStream> fileInStream;
HRESULT res = callback->GetStream(ui.CallbackIndex, &fileInStream);
if (res == S_FALSE)
{
if (ui.AltStreamIndex >= 0)
{
mi.NumSkipAltStreams++;
mi.AltStreams[ui.AltStreamIndex].Skip = true;
}
else
mi.Skip = true;
}
else
{
RINOK(res);
int miIndex = -1;
if (!fileInStream)
{
if (!mi.IsDir)
return E_INVALIDARG;
}
else if (ui.AltStreamIndex < 0)
{
CMyComPtr<IStreamGetProps2> getProps2;
fileInStream->QueryInterface(IID_IStreamGetProps2, (void **)&getProps2);
if (getProps2)
{
CStreamFileProps props;
if (getProps2->GetProps2(&props) == S_OK)
{
mi.Attrib = props.Attrib;
mi.CTime = props.CTime;
mi.ATime = props.ATime;
mi.MTime = props.MTime;
mi.FileID = props.FileID_Low;
if (props.NumLinks <= 1)
mi.FileID = 0;
mi.VolID = props.VolID;
if (mi.FileID != 0)
miIndex = AddToHardLinkList(db.MetaItems, ui.MetaIndex, hlIndexes);
if (props.Size != size && props.Size != (UInt64)(Int64)-1)
{
Int64 delta = (Int64)props.Size - (Int64)size;
Int64 newComplexity = totalComplexity + delta;
if (newComplexity > 0)
{
totalComplexity = newComplexity;
callback->SetTotal(totalComplexity);
}
mi.Size = props.Size;
size = props.Size;
}
}
}
}
if (miIndex >= 0)
{
mi.HashIndex = db.MetaItems[miIndex].HashIndex;
if (mi.HashIndex >= 0)
streams[mi.HashIndex].RefCount++;
// fix for future: maybe we need to check also that real size is equal to size from IStreamGetProps2
}
else if (ui.AltStreamIndex < 0 && mi.Reparse.Size() != 0)
{
if (mi.Reparse.Size() < 8)
return E_FAIL;
NCrypto::NSha1::CContext sha1;
sha1.Init();
size_t packSize = mi.Reparse.Size() - 8;
sha1.Update((const Byte *)mi.Reparse + 8, packSize);
Byte hash[kHashSize];
sha1.Final(hash);
int index = AddUniqHash(&streams.Front(), sortedHashes, hash, streams.Size());
if (index >= 0)
streams[index].RefCount++;
else
{
index = streams.Size();
RINOK(WriteStream(outStream, (const Byte *)mi.Reparse + 8, packSize));
CStreamInfo s;
s.Resource.PackSize = packSize;
s.Resource.Offset = curPos;
s.Resource.UnpackSize = packSize;
s.Resource.Flags = 0; // check it
/*
if (useResourceCompression)
s.Resource.Flags = NResourceFlags::Compressed;
*/
s.PartNumber = 1;
s.RefCount = 1;
memcpy(s.Hash, hash, kHashSize);
curPos += packSize;
streams.Add(s);
}
mi.HashIndex = index;
}
else
{
inShaStreamSpec->SetStream(fileInStream);
fileInStream.Release();
inShaStreamSpec->Init();
UInt64 offsetBlockSize = 0;
/*
if (useResourceCompression)
{
for (UInt64 t = kChunkSize; t < size; t += kChunkSize)
{
Byte buf[8];
SetUi32(buf, (UInt32)t);
RINOK(WriteStream(outStream, buf, 4));
offsetBlockSize += 4;
}
}
*/
RINOK(copyCoder->Code(inShaStream, outStream, NULL, NULL, progress));
size = copyCoderSpec->TotalSize;
if (size != 0)
{
Byte hash[kHashSize];
UInt64 packSize = offsetBlockSize + size;
inShaStreamSpec->Final(hash);
int index = AddUniqHash(&streams.Front(), sortedHashes, hash, streams.Size());
if (index >= 0)
{
streams[index].RefCount++;
outStream->Seek(-(Int64)packSize, STREAM_SEEK_CUR, &curPos);
outStream->SetSize(curPos);
}
else
{
index = streams.Size();
CStreamInfo s;
s.Resource.PackSize = packSize;
s.Resource.Offset = curPos;
s.Resource.UnpackSize = size;
s.Resource.Flags = 0;
/*
if (useResourceCompression)
s.Resource.Flags = NResourceFlags::Compressed;
*/
s.PartNumber = 1;
s.RefCount = 1;
memcpy(s.Hash, hash, kHashSize);
curPos += packSize;
streams.Add(s);
}
if (ui.AltStreamIndex < 0)
mi.HashIndex = index;
else
mi.AltStreams[ui.AltStreamIndex].HashIndex = index;
}
}
}
fileInStream.Release();
complexity += size;
RINOK(callback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK));
}
while (secureBlocks.Size() < numNewImages)
secureBlocks.AddNew();
// ---------- Write Images ----------
for (i = 0; i < numNewImages; i++)
{
lps->InSize = lps->OutSize = complexity;
RINOK(lps->SetCur());
if (i < isChangedImage.Size() && !isChangedImage[i])
{
CStreamInfo s = _db.MetaStreams[i];
RINOK(_volumes[1].Stream->Seek(s.Resource.Offset, STREAM_SEEK_SET, NULL));
inStreamLimitedSpec->Init(s.Resource.PackSize);
RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress));
if (copyCoderSpec->TotalSize != s.Resource.PackSize)
return E_FAIL;
s.Resource.Offset = curPos;
s.PartNumber = 1;
s.RefCount = 1;
streams.Add(s);
if (_bootIndex != 0 && _bootIndex == (UInt32)i + 1)
{
header.MetadataResource = s.Resource;
header.BootIndex = _bootIndex;
}
lps->ProgressOffset += s.Resource.PackSize;
curPos += s.Resource.PackSize;
// printf("\nWrite old image %x\n", i + 1);
continue;
}
const CDir &tree = trees[i];
const UInt32 kSecuritySize = 8;
size_t pos = kSecuritySize;
const CUniqBlocks &secUniqBlocks = secureBlocks[i];
const CObjectVector<CByteBuffer> &secBufs = secUniqBlocks.Bufs;
pos += (size_t)secUniqBlocks.GetTotalSizeInBytes();
pos += secBufs.Size() * 8;
pos = (pos + 7) & ~(size_t)7;
db.DefaultDirItem = ri;
pos += db.WriteTree_Dummy(tree);
CByteArr meta(pos);
Set32((Byte *)meta + 4, secBufs.Size()); // num security entries
pos = kSecuritySize;
if (secBufs.Size() == 0)
{
// we can write 0 here only if there is no security data, imageX does it,
// but some programs expect size = 8
Set32((Byte *)meta, 8); // size of security data
// Set32((Byte *)meta, 0);
}
else
{
unsigned k;
for (k = 0; k < secBufs.Size(); k++, pos += 8)
{
Set64(meta + pos, secBufs[k].Size());
}
for (k = 0; k < secBufs.Size(); k++)
{
const CByteBuffer &buf = secBufs[k];
size_t size = buf.Size();
if (size != 0)
{
memcpy(meta + pos, buf, size);
pos += size;
}
}
while ((pos & 7) != 0)
meta[pos++] = 0;
Set32((Byte *)meta, (UInt32)pos); // size of security data
}
db.Hashes = &streams.Front();
db.WriteTree(tree, (Byte *)meta, pos);
{
NCrypto::NSha1::CContext sha;
sha.Init();
sha.Update((const Byte *)meta, pos);
Byte digest[kHashSize];
sha.Final(digest);
CStreamInfo s;
s.Resource.PackSize = pos;
s.Resource.Offset = curPos;
s.Resource.UnpackSize = pos;
s.Resource.Flags = NResourceFlags::kMetadata;
s.PartNumber = 1;
s.RefCount = 1;
memcpy(s.Hash, digest, kHashSize);
streams.Add(s);
if (_bootIndex != 0 && _bootIndex == (UInt32)i + 1)
{
header.MetadataResource = s.Resource;
header.BootIndex = _bootIndex;
}
RINOK(WriteStream(outStream, (const Byte *)meta, pos));
meta.Free();
curPos += pos;
}
}
lps->InSize = lps->OutSize = complexity;
RINOK(lps->SetCur());
header.OffsetResource.UnpackSize = header.OffsetResource.PackSize = (UInt64)streams.Size() * kStreamInfoSize;
header.OffsetResource.Offset = curPos;
header.OffsetResource.Flags = NResourceFlags::kMetadata;
// ---------- Write Streams Info Tables ----------
for (i = 0; i < streams.Size(); i++)
{
Byte buf[kStreamInfoSize];
streams[i].WriteTo(buf);
RINOK(WriteStream(outStream, buf, kStreamInfoSize));
curPos += kStreamInfoSize;
}
AString xml = "<WIM>";
AddTagUInt64_ToString(xml, "TOTALBYTES", curPos);
for (i = 0; i < trees.Size(); i++)
{
CDir &tree = trees[i];
CXmlItem item;
if (_xmls.Size() == 1)
{
const CWimXml &_oldXml = _xmls[0];
if ((int)i < _oldXml.Images.Size())
{
// int ttt = _oldXml.Images[i].ItemIndexInXml;
item = _oldXml.Xml.Root.SubItems[_oldXml.Images[i].ItemIndexInXml];
}
}
if (i >= isChangedImage.Size() || isChangedImage[i])
{
char temp[16];
if (item.Name.IsEmpty())
{
ConvertUInt32ToString(i + 1, temp);
item.Name = "IMAGE";
item.IsTag = true;
CXmlProp &prop = item.Props.AddNew();
prop.Name = "INDEX";
prop.Value = temp;
}
AddTag_String_IfEmpty(item, "NAME", temp);
AddTag_UInt64(item, "DIRCOUNT", tree.GetNumDirs() - 1);
AddTag_UInt64(item, "FILECOUNT", tree.GetNumFiles());
AddTag_UInt64(item, "TOTALBYTES", tree.GetTotalSize(db.MetaItems));
AddTag_Time(item, "CREATIONTIME", ftCur);
AddTag_Time(item, "LASTMODIFICATIONTIME", ftCur);
}
item.AppendTo(xml);
}
xml += "</WIM>";
size_t xmlSize;
{
UString utf16;
if (!ConvertUTF8ToUnicode(xml, utf16))
return S_FALSE;
xmlSize = (utf16.Len() + 1) * 2;
CByteArr xmlBuf(xmlSize);
Set16((Byte *)xmlBuf, 0xFEFF);
for (i = 0; i < (unsigned)utf16.Len(); i++)
Set16((Byte *)xmlBuf + 2 + i * 2, utf16[i]);
RINOK(WriteStream(outStream, (const Byte *)xmlBuf, xmlSize));
}
header.XmlResource.UnpackSize = header.XmlResource.PackSize = xmlSize;
header.XmlResource.Offset = curPos;
header.XmlResource.Flags = NResourceFlags::kMetadata;
outStream->Seek(0, STREAM_SEEK_SET, NULL);
header.NumImages = trees.Size();
{
Byte buf[kHeaderSizeMax];
header.WriteTo(buf);
return WriteStream(outStream, buf, kHeaderSizeMax);
}
COM_TRY_END
}
}}
| {
"pile_set_name": "Github"
} |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\BrowserKit;
use Symfony\Component\BrowserKit\Exception\BadMethodCallException;
use Symfony\Component\DomCrawler\Crawler;
use Symfony\Component\DomCrawler\Form;
use Symfony\Component\DomCrawler\Link;
use Symfony\Component\Process\PhpProcess;
/**
* Simulates a browser.
*
* To make the actual request, you need to implement the doRequest() method.
*
* If you want to be able to run requests in their own process (insulated flag),
* you need to also implement the getScript() method.
*
* @author Fabien Potencier <[email protected]>
*/
abstract class AbstractBrowser
{
protected $history;
protected $cookieJar;
protected $server = [];
protected $internalRequest;
protected $request;
protected $internalResponse;
protected $response;
protected $crawler;
protected $insulated = false;
protected $redirect;
protected $followRedirects = true;
protected $followMetaRefresh = false;
private $maxRedirects = -1;
private $redirectCount = 0;
private $redirects = [];
private $isMainRequest = true;
/**
* @param array $server The server parameters (equivalent of $_SERVER)
*/
public function __construct(array $server = [], History $history = null, CookieJar $cookieJar = null)
{
$this->setServerParameters($server);
$this->history = $history ?: new History();
$this->cookieJar = $cookieJar ?: new CookieJar();
}
/**
* Sets whether to automatically follow redirects or not.
*/
public function followRedirects(bool $followRedirects = true)
{
$this->followRedirects = $followRedirects;
}
/**
* Sets whether to automatically follow meta refresh redirects or not.
*/
public function followMetaRefresh(bool $followMetaRefresh = true)
{
$this->followMetaRefresh = $followMetaRefresh;
}
/**
* Returns whether client automatically follows redirects or not.
*
* @return bool
*/
public function isFollowingRedirects()
{
return $this->followRedirects;
}
/**
* Sets the maximum number of redirects that crawler can follow.
*/
public function setMaxRedirects(int $maxRedirects)
{
$this->maxRedirects = $maxRedirects < 0 ? -1 : $maxRedirects;
$this->followRedirects = -1 != $this->maxRedirects;
}
/**
* Returns the maximum number of redirects that crawler can follow.
*
* @return int
*/
public function getMaxRedirects()
{
return $this->maxRedirects;
}
/**
* Sets the insulated flag.
*
* @param bool $insulated Whether to insulate the requests or not
*
* @throws \RuntimeException When Symfony Process Component is not installed
*/
public function insulate(bool $insulated = true)
{
if ($insulated && !class_exists('Symfony\\Component\\Process\\Process')) {
throw new \LogicException('Unable to isolate requests as the Symfony Process Component is not installed.');
}
$this->insulated = $insulated;
}
/**
* Sets server parameters.
*
* @param array $server An array of server parameters
*/
public function setServerParameters(array $server)
{
$this->server = array_merge([
'HTTP_USER_AGENT' => 'Symfony BrowserKit',
], $server);
}
/**
* Sets single server parameter.
*/
public function setServerParameter(string $key, string $value)
{
$this->server[$key] = $value;
}
/**
* Gets single server parameter for specified key.
*
* @param mixed $default A default value when key is undefined
*
* @return mixed A value of the parameter
*/
public function getServerParameter(string $key, $default = '')
{
return isset($this->server[$key]) ? $this->server[$key] : $default;
}
public function xmlHttpRequest(string $method, string $uri, array $parameters = [], array $files = [], array $server = [], string $content = null, bool $changeHistory = true): Crawler
{
$this->setServerParameter('HTTP_X_REQUESTED_WITH', 'XMLHttpRequest');
try {
return $this->request($method, $uri, $parameters, $files, $server, $content, $changeHistory);
} finally {
unset($this->server['HTTP_X_REQUESTED_WITH']);
}
}
/**
* Returns the History instance.
*
* @return History A History instance
*/
public function getHistory()
{
return $this->history;
}
/**
* Returns the CookieJar instance.
*
* @return CookieJar A CookieJar instance
*/
public function getCookieJar()
{
return $this->cookieJar;
}
/**
* Returns the current Crawler instance.
*
* @return Crawler A Crawler instance
*/
public function getCrawler()
{
if (null === $this->crawler) {
throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
}
return $this->crawler;
}
/**
* Returns the current BrowserKit Response instance.
*
* @return Response A BrowserKit Response instance
*/
public function getInternalResponse()
{
if (null === $this->internalResponse) {
throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
}
return $this->internalResponse;
}
/**
* Returns the current origin response instance.
*
* The origin response is the response instance that is returned
* by the code that handles requests.
*
* @return object A response instance
*
* @see doRequest()
*/
public function getResponse()
{
if (null === $this->response) {
throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
}
return $this->response;
}
/**
* Returns the current BrowserKit Request instance.
*
* @return Request A BrowserKit Request instance
*/
public function getInternalRequest()
{
if (null === $this->internalRequest) {
throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
}
return $this->internalRequest;
}
/**
* Returns the current origin Request instance.
*
* The origin request is the request instance that is sent
* to the code that handles requests.
*
* @return object A Request instance
*
* @see doRequest()
*/
public function getRequest()
{
if (null === $this->request) {
throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
}
return $this->request;
}
/**
* Clicks on a given link.
*
* @return Crawler
*/
public function click(Link $link)
{
if ($link instanceof Form) {
return $this->submit($link);
}
return $this->request($link->getMethod(), $link->getUri());
}
/**
* Clicks the first link (or clickable image) that contains the given text.
*
* @param string $linkText The text of the link or the alt attribute of the clickable image
*/
public function clickLink(string $linkText): Crawler
{
if (null === $this->crawler) {
throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
}
return $this->click($this->crawler->selectLink($linkText)->link());
}
/**
* Submits a form.
*
* @param array $values An array of form field values
* @param array $serverParameters An array of server parameters
*
* @return Crawler
*/
public function submit(Form $form, array $values = [], array $serverParameters = [])
{
$form->setValues($values);
return $this->request($form->getMethod(), $form->getUri(), $form->getPhpValues(), $form->getPhpFiles(), $serverParameters);
}
/**
* Finds the first form that contains a button with the given content and
* uses it to submit the given form field values.
*
* @param string $button The text content, id, value or name of the form <button> or <input type="submit">
* @param array $fieldValues Use this syntax: ['my_form[name]' => '...', 'my_form[email]' => '...']
* @param string $method The HTTP method used to submit the form
* @param array $serverParameters These values override the ones stored in $_SERVER (HTTP headers must include a HTTP_ prefix as PHP does)
*/
public function submitForm(string $button, array $fieldValues = [], string $method = 'POST', array $serverParameters = []): Crawler
{
if (null === $this->crawler) {
throw new BadMethodCallException(sprintf('The "request()" method must be called before "%s()".', __METHOD__));
}
$buttonNode = $this->crawler->selectButton($button);
$form = $buttonNode->form($fieldValues, $method);
return $this->submit($form, [], $serverParameters);
}
/**
* Calls a URI.
*
* @param string $method The request method
* @param string $uri The URI to fetch
* @param array $parameters The Request parameters
* @param array $files The files
* @param array $server The server parameters (HTTP headers are referenced with a HTTP_ prefix as PHP does)
* @param string $content The raw body data
* @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
*
* @return Crawler
*/
public function request(string $method, string $uri, array $parameters = [], array $files = [], array $server = [], string $content = null, bool $changeHistory = true)
{
if ($this->isMainRequest) {
$this->redirectCount = 0;
} else {
++$this->redirectCount;
}
$originalUri = $uri;
$uri = $this->getAbsoluteUri($uri);
$server = array_merge($this->server, $server);
if (!empty($server['HTTP_HOST']) && null === parse_url($originalUri, \PHP_URL_HOST)) {
$uri = preg_replace('{^(https?\://)'.preg_quote($this->extractHost($uri)).'}', '${1}'.$server['HTTP_HOST'], $uri);
}
if (isset($server['HTTPS']) && null === parse_url($originalUri, \PHP_URL_SCHEME)) {
$uri = preg_replace('{^'.parse_url($uri, \PHP_URL_SCHEME).'}', $server['HTTPS'] ? 'https' : 'http', $uri);
}
if (!isset($server['HTTP_REFERER']) && !$this->history->isEmpty()) {
$server['HTTP_REFERER'] = $this->history->current()->getUri();
}
if (empty($server['HTTP_HOST'])) {
$server['HTTP_HOST'] = $this->extractHost($uri);
}
$server['HTTPS'] = 'https' == parse_url($uri, \PHP_URL_SCHEME);
$this->internalRequest = new Request($uri, $method, $parameters, $files, $this->cookieJar->allValues($uri), $server, $content);
$this->request = $this->filterRequest($this->internalRequest);
if (true === $changeHistory) {
$this->history->add($this->internalRequest);
}
if ($this->insulated) {
$this->response = $this->doRequestInProcess($this->request);
} else {
$this->response = $this->doRequest($this->request);
}
$this->internalResponse = $this->filterResponse($this->response);
$this->cookieJar->updateFromResponse($this->internalResponse, $uri);
$status = $this->internalResponse->getStatusCode();
if ($status >= 300 && $status < 400) {
$this->redirect = $this->internalResponse->getHeader('Location');
} else {
$this->redirect = null;
}
if ($this->followRedirects && $this->redirect) {
$this->redirects[serialize($this->history->current())] = true;
return $this->crawler = $this->followRedirect();
}
$this->crawler = $this->createCrawlerFromContent($this->internalRequest->getUri(), $this->internalResponse->getContent(), $this->internalResponse->getHeader('Content-Type') ?? '');
// Check for meta refresh redirect
if ($this->followMetaRefresh && null !== $redirect = $this->getMetaRefreshUrl()) {
$this->redirect = $redirect;
$this->redirects[serialize($this->history->current())] = true;
$this->crawler = $this->followRedirect();
}
return $this->crawler;
}
/**
* Makes a request in another process.
*
* @param object $request An origin request instance
*
* @return object An origin response instance
*
* @throws \RuntimeException When processing returns exit code
*/
protected function doRequestInProcess($request)
{
$deprecationsFile = tempnam(sys_get_temp_dir(), 'deprec');
putenv('SYMFONY_DEPRECATIONS_SERIALIZE='.$deprecationsFile);
$_ENV['SYMFONY_DEPRECATIONS_SERIALIZE'] = $deprecationsFile;
$process = new PhpProcess($this->getScript($request), null, null);
$process->run();
if (file_exists($deprecationsFile)) {
$deprecations = file_get_contents($deprecationsFile);
unlink($deprecationsFile);
foreach ($deprecations ? unserialize($deprecations) : [] as $deprecation) {
if ($deprecation[0]) {
// unsilenced on purpose
trigger_error($deprecation[1], \E_USER_DEPRECATED);
} else {
@trigger_error($deprecation[1], \E_USER_DEPRECATED);
}
}
}
if (!$process->isSuccessful() || !preg_match('/^O\:\d+\:/', $process->getOutput())) {
throw new \RuntimeException(sprintf('OUTPUT: %s ERROR OUTPUT: %s.', $process->getOutput(), $process->getErrorOutput()));
}
return unserialize($process->getOutput());
}
/**
* Makes a request.
*
* @param object $request An origin request instance
*
* @return object An origin response instance
*/
abstract protected function doRequest($request);
/**
* Returns the script to execute when the request must be insulated.
*
* @param object $request An origin request instance
*
* @throws \LogicException When this abstract class is not implemented
*/
protected function getScript($request)
{
throw new \LogicException('To insulate requests, you need to override the getScript() method.');
}
/**
* Filters the BrowserKit request to the origin one.
*
* @return object An origin request instance
*/
protected function filterRequest(Request $request)
{
return $request;
}
/**
* Filters the origin response to the BrowserKit one.
*
* @param object $response The origin response to filter
*
* @return Response An BrowserKit Response instance
*/
protected function filterResponse($response)
{
return $response;
}
/**
* Creates a crawler.
*
* This method returns null if the DomCrawler component is not available.
*
* @return Crawler|null
*/
protected function createCrawlerFromContent(string $uri, string $content, string $type)
{
if (!class_exists('Symfony\Component\DomCrawler\Crawler')) {
return null;
}
$crawler = new Crawler(null, $uri);
$crawler->addContent($content, $type);
return $crawler;
}
/**
* Goes back in the browser history.
*
* @return Crawler
*/
public function back()
{
do {
$request = $this->history->back();
} while (\array_key_exists(serialize($request), $this->redirects));
return $this->requestFromRequest($request, false);
}
/**
* Goes forward in the browser history.
*
* @return Crawler
*/
public function forward()
{
do {
$request = $this->history->forward();
} while (\array_key_exists(serialize($request), $this->redirects));
return $this->requestFromRequest($request, false);
}
/**
* Reloads the current browser.
*
* @return Crawler
*/
public function reload()
{
return $this->requestFromRequest($this->history->current(), false);
}
/**
* Follow redirects?
*
* @return Crawler
*
* @throws \LogicException If request was not a redirect
*/
public function followRedirect()
{
if (empty($this->redirect)) {
throw new \LogicException('The request was not redirected.');
}
if (-1 !== $this->maxRedirects) {
if ($this->redirectCount > $this->maxRedirects) {
$this->redirectCount = 0;
throw new \LogicException(sprintf('The maximum number (%d) of redirections was reached.', $this->maxRedirects));
}
}
$request = $this->internalRequest;
if (\in_array($this->internalResponse->getStatusCode(), [301, 302, 303])) {
$method = 'GET';
$files = [];
$content = null;
} else {
$method = $request->getMethod();
$files = $request->getFiles();
$content = $request->getContent();
}
if ('GET' === strtoupper($method)) {
// Don't forward parameters for GET request as it should reach the redirection URI
$parameters = [];
} else {
$parameters = $request->getParameters();
}
$server = $request->getServer();
$server = $this->updateServerFromUri($server, $this->redirect);
$this->isMainRequest = false;
$response = $this->request($method, $this->redirect, $parameters, $files, $server, $content);
$this->isMainRequest = true;
return $response;
}
/**
* @see https://dev.w3.org/html5/spec-preview/the-meta-element.html#attr-meta-http-equiv-refresh
*/
private function getMetaRefreshUrl(): ?string
{
$metaRefresh = $this->getCrawler()->filter('head meta[http-equiv="refresh"]');
foreach ($metaRefresh->extract(['content']) as $content) {
if (preg_match('/^\s*0\s*;\s*URL\s*=\s*(?|\'([^\']++)|"([^"]++)|([^\'"].*))/i', $content, $m)) {
return str_replace("\t\r\n", '', rtrim($m[1]));
}
}
return null;
}
/**
* Restarts the client.
*
* It flushes history and all cookies.
*/
public function restart()
{
$this->cookieJar->clear();
$this->history->clear();
}
/**
* Takes a URI and converts it to absolute if it is not already absolute.
*
* @param string $uri A URI
*
* @return string An absolute URI
*/
protected function getAbsoluteUri(string $uri)
{
// already absolute?
if (0 === strpos($uri, 'http://') || 0 === strpos($uri, 'https://')) {
return $uri;
}
if (!$this->history->isEmpty()) {
$currentUri = $this->history->current()->getUri();
} else {
$currentUri = sprintf('http%s://%s/',
isset($this->server['HTTPS']) ? 's' : '',
isset($this->server['HTTP_HOST']) ? $this->server['HTTP_HOST'] : 'localhost'
);
}
// protocol relative URL
if (0 === strpos($uri, '//')) {
return parse_url($currentUri, \PHP_URL_SCHEME).':'.$uri;
}
// anchor or query string parameters?
if (!$uri || '#' == $uri[0] || '?' == $uri[0]) {
return preg_replace('/[#?].*?$/', '', $currentUri).$uri;
}
if ('/' !== $uri[0]) {
$path = parse_url($currentUri, \PHP_URL_PATH);
if ('/' !== substr($path, -1)) {
$path = substr($path, 0, strrpos($path, '/') + 1);
}
$uri = $path.$uri;
}
return preg_replace('#^(.*?//[^/]+)\/.*$#', '$1', $currentUri).$uri;
}
/**
* Makes a request from a Request object directly.
*
* @param bool $changeHistory Whether to update the history or not (only used internally for back(), forward(), and reload())
*
* @return Crawler
*/
protected function requestFromRequest(Request $request, $changeHistory = true)
{
return $this->request($request->getMethod(), $request->getUri(), $request->getParameters(), $request->getFiles(), $request->getServer(), $request->getContent(), $changeHistory);
}
private function updateServerFromUri(array $server, string $uri): array
{
$server['HTTP_HOST'] = $this->extractHost($uri);
$scheme = parse_url($uri, \PHP_URL_SCHEME);
$server['HTTPS'] = null === $scheme ? $server['HTTPS'] : 'https' == $scheme;
unset($server['HTTP_IF_NONE_MATCH'], $server['HTTP_IF_MODIFIED_SINCE']);
return $server;
}
private function extractHost(string $uri): ?string
{
$host = parse_url($uri, \PHP_URL_HOST);
if ($port = parse_url($uri, \PHP_URL_PORT)) {
return $host.':'.$port;
}
return $host;
}
}
| {
"pile_set_name": "Github"
} |
/**
* Adapted from :
* Real-Time Polygonal-Light Shading with Linearly Transformed Cosines.
* Eric Heitz, Jonathan Dupuy, Stephen Hill and David Neubelt.
* ACM Transactions on Graphics (Proceedings of ACM SIGGRAPH 2016) 35(4), 2016.
* Project page: https://eheitzresearch.wordpress.com/415-2/
*/
#define USE_LTC
#ifndef UTIL_TEX
# define UTIL_TEX
uniform sampler2DArray utilTex;
# define texelfetch_noise_tex(coord) texelFetch(utilTex, ivec3(ivec2(coord) % LUT_SIZE, 2.0), 0)
#endif /* UTIL_TEX */
/* Diffuse *clipped* sphere integral. */
float diffuse_sphere_integral(float avg_dir_z, float form_factor)
{
#if 1
/* use tabulated horizon-clipped sphere */
vec2 uv = vec2(avg_dir_z * 0.5 + 0.5, form_factor);
uv = uv * (LUT_SIZE - 1.0) / LUT_SIZE + 0.5 / LUT_SIZE;
return texture(utilTex, vec3(uv, 3.0)).x;
#else
/* Cheap approximation. Less smooth and have energy issues. */
return max((form_factor * form_factor + avg_dir_z) / (form_factor + 1.0), 0.0);
#endif
}
/**
* An extended version of the implementation from
* "How to solve a cubic equation, revisited"
* http://momentsingraphics.de/?p=105
*/
vec3 solve_cubic(vec4 coefs)
{
/* Normalize the polynomial */
coefs.xyz /= coefs.w;
/* Divide middle coefficients by three */
coefs.yz /= 3.0;
float A = coefs.w;
float B = coefs.z;
float C = coefs.y;
float D = coefs.x;
/* Compute the Hessian and the discriminant */
vec3 delta = vec3(-coefs.z * coefs.z + coefs.y,
-coefs.y * coefs.z + coefs.x,
dot(vec2(coefs.z, -coefs.y), coefs.xy));
/* Discriminant */
float discr = dot(vec2(4.0 * delta.x, -delta.y), delta.zy);
vec2 xlc, xsc;
/* Algorithm A */
{
float A_a = 1.0;
float C_a = delta.x;
float D_a = -2.0 * B * delta.x + delta.y;
/* Take the cubic root of a normalized complex number */
float theta = atan(sqrt(discr), -D_a) / 3.0;
float x_1a = 2.0 * sqrt(-C_a) * cos(theta);
float x_3a = 2.0 * sqrt(-C_a) * cos(theta + (2.0 / 3.0) * M_PI);
float xl;
if ((x_1a + x_3a) > 2.0 * B) {
xl = x_1a;
}
else {
xl = x_3a;
}
xlc = vec2(xl - B, A);
}
/* Algorithm D */
{
float A_d = D;
float C_d = delta.z;
float D_d = -D * delta.y + 2.0 * C * delta.z;
/* Take the cubic root of a normalized complex number */
float theta = atan(D * sqrt(discr), -D_d) / 3.0;
float x_1d = 2.0 * sqrt(-C_d) * cos(theta);
float x_3d = 2.0 * sqrt(-C_d) * cos(theta + (2.0 / 3.0) * M_PI);
float xs;
if (x_1d + x_3d < 2.0 * C) {
xs = x_1d;
}
else {
xs = x_3d;
}
xsc = vec2(-D, xs + C);
}
float E = xlc.y * xsc.y;
float F = -xlc.x * xsc.y - xlc.y * xsc.x;
float G = xlc.x * xsc.x;
vec2 xmc = vec2(C * F - B * G, -B * F + C * E);
vec3 root = vec3(xsc.x / xsc.y, xmc.x / xmc.y, xlc.x / xlc.y);
if (root.x < root.y && root.x < root.z) {
root.xyz = root.yxz;
}
else if (root.z < root.x && root.z < root.y) {
root.xyz = root.xzy;
}
return root;
}
/* from Real-Time Area Lighting: a Journey from Research to Production
* Stephen Hill and Eric Heitz */
vec3 edge_integral_vec(vec3 v1, vec3 v2)
{
float x = dot(v1, v2);
float y = abs(x);
float a = 0.8543985 + (0.4965155 + 0.0145206 * y) * y;
float b = 3.4175940 + (4.1616724 + y) * y;
float v = a / b;
float theta_sintheta = (x > 0.0) ? v : 0.5 * inversesqrt(max(1.0 - x * x, 1e-7)) - v;
return cross(v1, v2) * theta_sintheta;
}
mat3 ltc_matrix(vec4 lut)
{
/* load inverse matrix */
mat3 Minv = mat3(vec3(lut.x, 0, lut.y), vec3(0, 1, 0), vec3(lut.z, 0, lut.w));
return Minv;
}
void ltc_transform_quad(vec3 N, vec3 V, mat3 Minv, inout vec3 corners[4])
{
/* Avoid dot(N, V) == 1 in ortho mode, leading T1 normalize to fail. */
V = normalize(V + 1e-8);
/* construct orthonormal basis around N */
vec3 T1, T2;
T1 = normalize(V - N * dot(N, V));
T2 = cross(N, T1);
/* rotate area light in (T1, T2, R) basis */
Minv = Minv * transpose(mat3(T1, T2, N));
/* Apply LTC inverse matrix. */
corners[0] = normalize(Minv * corners[0]);
corners[1] = normalize(Minv * corners[1]);
corners[2] = normalize(Minv * corners[2]);
corners[3] = normalize(Minv * corners[3]);
}
/* If corners have already pass through ltc_transform_quad(),
* then N **MUST** be vec3(0.0, 0.0, 1.0), corresponding to the Up axis of the shading basis. */
float ltc_evaluate_quad(vec3 corners[4], vec3 N)
{
/* Approximation using a sphere of the same solid angle than the quad.
* Finding the clipped sphere diffuse integral is easier than clipping the quad. */
vec3 avg_dir;
avg_dir = edge_integral_vec(corners[0], corners[1]);
avg_dir += edge_integral_vec(corners[1], corners[2]);
avg_dir += edge_integral_vec(corners[2], corners[3]);
avg_dir += edge_integral_vec(corners[3], corners[0]);
float form_factor = length(avg_dir);
float avg_dir_z = dot(N, avg_dir / form_factor);
return form_factor * diffuse_sphere_integral(avg_dir_z, form_factor);
}
/* If disk does not need to be transformed and is already front facing. */
float ltc_evaluate_disk_simple(float disk_radius, float NL)
{
float r_sqr = disk_radius * disk_radius;
float one_r_sqr = 1.0 + r_sqr;
float form_factor = r_sqr * inversesqrt(one_r_sqr * one_r_sqr);
return form_factor * diffuse_sphere_integral(NL, form_factor);
}
/* disk_points are WS vectors from the shading point to the disk "bounding domain" */
float ltc_evaluate_disk(vec3 N, vec3 V, mat3 Minv, vec3 disk_points[3])
{
/* Avoid dot(N, V) == 1 in ortho mode, leading T1 normalize to fail. */
V = normalize(V + 1e-8);
/* construct orthonormal basis around N */
vec3 T1, T2;
T1 = normalize(V - N * dot(V, N));
T2 = cross(N, T1);
/* rotate area light in (T1, T2, R) basis */
mat3 R = transpose(mat3(T1, T2, N));
/* Intermediate step: init ellipse. */
vec3 L_[3];
L_[0] = mul(R, disk_points[0]);
L_[1] = mul(R, disk_points[1]);
L_[2] = mul(R, disk_points[2]);
vec3 C = 0.5 * (L_[0] + L_[2]);
vec3 V1 = 0.5 * (L_[1] - L_[2]);
vec3 V2 = 0.5 * (L_[1] - L_[0]);
/* Transform ellipse by Minv. */
C = Minv * C;
V1 = Minv * V1;
V2 = Minv * V2;
/* Compute eigenvectors of new ellipse. */
float d11 = dot(V1, V1);
float d22 = dot(V2, V2);
float d12 = dot(V1, V2);
float a, b; /* Eigenvalues */
const float threshold = 0.0007; /* Can be adjusted. Fix artifacts. */
if (abs(d12) / sqrt(d11 * d22) > threshold) {
float tr = d11 + d22;
float det = -d12 * d12 + d11 * d22;
/* use sqrt matrix to solve for eigenvalues */
det = sqrt(det);
float u = 0.5 * sqrt(tr - 2.0 * det);
float v = 0.5 * sqrt(tr + 2.0 * det);
float e_max = (u + v);
float e_min = (u - v);
e_max *= e_max;
e_min *= e_min;
vec3 V1_, V2_;
if (d11 > d22) {
V1_ = d12 * V1 + (e_max - d11) * V2;
V2_ = d12 * V1 + (e_min - d11) * V2;
}
else {
V1_ = d12 * V2 + (e_max - d22) * V1;
V2_ = d12 * V2 + (e_min - d22) * V1;
}
a = 1.0 / e_max;
b = 1.0 / e_min;
V1 = normalize(V1_);
V2 = normalize(V2_);
}
else {
a = 1.0 / d11;
b = 1.0 / d22;
V1 *= sqrt(a);
V2 *= sqrt(b);
}
/* Now find front facing ellipse with same solid angle. */
vec3 V3 = normalize(cross(V1, V2));
if (dot(C, V3) < 0.0) {
V3 *= -1.0;
}
float L = dot(V3, C);
float x0 = dot(V1, C) / L;
float y0 = dot(V2, C) / L;
a *= L * L;
b *= L * L;
float c0 = a * b;
float c1 = a * b * (1.0 + x0 * x0 + y0 * y0) - a - b;
float c2 = 1.0 - a * (1.0 + x0 * x0) - b * (1.0 + y0 * y0);
float c3 = 1.0;
vec3 roots = solve_cubic(vec4(c0, c1, c2, c3));
float e1 = roots.x;
float e2 = roots.y;
float e3 = roots.z;
vec3 avg_dir = vec3(a * x0 / (a - e2), b * y0 / (b - e2), 1.0);
mat3 rotate = mat3(V1, V2, V3);
avg_dir = rotate * avg_dir;
avg_dir = normalize(avg_dir);
/* L1, L2 are the extends of the front facing ellipse. */
float L1 = sqrt(-e2 / e3);
float L2 = sqrt(-e2 / e1);
/* Find the sphere and compute lighting. */
float form_factor = max(0.0, L1 * L2 * inversesqrt((1.0 + L1 * L1) * (1.0 + L2 * L2)));
return form_factor * diffuse_sphere_integral(avg_dir.z, form_factor);
}
| {
"pile_set_name": "Github"
} |
//===-- WasmException.h - Wasm Exception Framework -------------*- C++ -*--===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains support for writing WebAssembly exception info into asm
// files.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_LIB_CODEGEN_ASMPRINTER_WASMEXCEPTION_H
#define LLVM_LIB_CODEGEN_ASMPRINTER_WASMEXCEPTION_H
#include "EHStreamer.h"
#include "llvm/CodeGen/AsmPrinter.h"
namespace llvm {
class LLVM_LIBRARY_VISIBILITY WasmException : public EHStreamer {
public:
WasmException(AsmPrinter *A) : EHStreamer(A) {}
void endModule() override;
void beginFunction(const MachineFunction *MF) override {}
virtual void markFunctionEnd() override;
void endFunction(const MachineFunction *MF) override;
protected:
// Compute the call site table for wasm EH.
void computeCallSiteTable(
SmallVectorImpl<CallSiteEntry> &CallSites,
const SmallVectorImpl<const LandingPadInfo *> &LandingPads,
const SmallVectorImpl<unsigned> &FirstActions) override;
};
} // End of namespace llvm
#endif
| {
"pile_set_name": "Github"
} |
rule m2319_4b1d3ec1c8000b12
{
meta:
copyright="Copyright (c) 2014-2018 Support Intelligence Inc, All Rights Reserved."
engine="saphire/1.3.1 divinorum/0.998 icewater/0.4"
viz_url="http://icewater.io/en/cluster/query?h64=m2319.4b1d3ec1c8000b12"
cluster="m2319.4b1d3ec1c8000b12"
cluster_size="5"
filetype = "text/html"
tlp = "amber"
version = "icewater snowflake"
author = "Rick Wesson (@wessorh) [email protected]"
date = "20171121"
license = "RIL-1.0 [Rick's Internet License] "
family="likejack faceliker clicker"
md5_hashes="['07aa2174012ad399f6e79bafc06890c2','73655b3ac5f309173281f7fddd4aeb91','c6e11d0ee5f670a3fd43cd27ec4abaa7']"
strings:
$hex_string = { 6d656e7442794964282750726f66696c653127292c207b7d2c2027646973706c61794d6f646546756c6c2729293b0a5f5769646765744d616e616765722e5f52 }
condition:
filesize > 65536 and filesize < 262144
and $hex_string
}
| {
"pile_set_name": "Github"
} |
const chain = require('chain-sdk')
// This demo is written to run on either one or two cores. Simply provide
// different URLs to the following clients for the two-core version.
const client = new chain.Client()
const otherClient = new chain.Client()
const signer = new chain.HsmSigner()
let aliceKey, bobKey
Promise.all([
client.mockHsm.keys.create(),
otherClient.mockHsm.keys.create()
]).then(keys => {
aliceKey = keys[0].xpub,
bobKey = keys[1].xpub
signer.addKey(aliceKey, client.mockHsm.signerConnection)
}).then(() => Promise.all([
client.assets.create({
alias: 'gold',
rootXpubs: [aliceKey],
quorum: 1
}),
client.assets.create({
alias: 'silver',
rootXpubs: [aliceKey],
quorum: 1
}),
client.accounts.create({
alias: 'alice',
rootXpubs: [aliceKey],
quorum: 1
}),
otherClient.accounts.create({
alias: 'bob',
rootXpubs: [bobKey],
quorum: 1
})
])).then(() =>
// snippet issue-within-core
client.transactions.build(builder => {
builder.issue({
assetAlias: 'silver',
amount: 1000
})
builder.controlWithAccount({
accountAlias: 'alice',
assetAlias: 'silver',
amount: 1000
})
})
.then(issuance => signer.sign(issuance))
.then(signed => client.transactions.submit(signed))
// endsnippet
).then(() =>
client.transactions.build(builder => {
builder.issue({
assetAlias: 'gold',
amount: 1000
})
builder.controlWithAccount({
accountAlias: 'alice',
assetAlias: 'gold',
amount: 1000
})
})
.then(issuance => signer.sign(issuance))
.then(signed => client.transactions.submit(signed))
).then(() =>
// snippet create-bob-issue-receiver
otherClient.accounts.createReceiver({
accountAlias: 'bob'
}).then(bobIssuanceReceiver => {
return JSON.stringify(bobIssuanceReceiver)
})
// endsnippet
).then(bobIssuanceReceiverSerialized => {
return (
// snippet issue-to-bob-receiver
client.transactions.build(builder => {
builder.issue({
assetAlias: 'gold',
amount: 10
})
builder.controlWithReceiver({
receiver: JSON.parse(bobIssuanceReceiverSerialized),
assetAlias: 'gold',
amount: 10
})
})
.then(issuance => signer.sign(issuance))
.then(signed => client.transactions.submit(signed))
// endsnippet
)
}).then(() => {
if (client.baseUrl == otherClient.baseUrl){
// snippet pay-within-core
return client.transactions.build(builder => {
builder.spendFromAccount({
accountAlias: 'alice',
assetAlias: 'gold',
amount: 10
})
builder.controlWithAccount({
accountAlias: 'bob',
assetAlias: 'gold',
amount: 10
})
})
.then(payment => signer.sign(payment))
.then(signed => client.transactions.submit(signed))
// endsnippet
} else {
return
}
}).then(() =>
// snippet create-bob-payment-receiver
otherClient.accounts.createReceiver({
accountAlias: 'bob'
}).then(bobPaymentReceiver => {
return JSON.stringify(bobPaymentReceiver)
})
// endsnippet
).then(bobPaymentReceiverSerialized => {
return (
// snippet pay-between-cores
client.transactions.build(builder => {
builder.spendFromAccount({
accountAlias: 'alice',
assetAlias: 'gold',
amount: 10
})
builder.controlWithReceiver({
receiver: JSON.parse(bobPaymentReceiverSerialized),
assetAlias: 'gold',
amount: 10
})
})
.then(payment => signer.sign(payment))
.then(signed => client.transactions.submit(signed))
// endsnippet
)
}).then(() => {
if (client.baseUrl == otherClient.baseUrl){
//snippet multiasset-within-core
return client.transactions.build(builder => {
builder.spendFromAccount({
accountAlias: 'alice',
assetAlias: 'gold',
amount: 10
})
builder.spendFromAccount({
accountAlias: 'alice',
assetAlias: 'silver',
amount: 20
})
builder.controlWithAccount({
accountAlias: 'bob',
assetAlias: 'gold',
amount: 10
})
builder.controlWithAccount({
accountAlias: 'bob',
assetAlias: 'silver',
amount: 20
})
})
.then(payment => signer.sign(payment))
.then(signed => client.transactions.submit(signed))
// endsnippet
} else {
return
}
}).then(() => {
return (
// snippet create-bob-multiasset-receiver
Promise.all([
otherClient.accounts.createReceiver({
accountAlias: 'bob'
}),
otherClient.accounts.createReceiver({
accountAlias: 'bob'
}),
]).then(receivers => {
return {
bobGoldReceiverSerialized: JSON.stringify(receivers[0]),
bobSilverReceiverSerialized: JSON.stringify(receivers[1]),
}
})
// endsnippet
)
}).then(({bobGoldReceiverSerialized, bobSilverReceiverSerialized}) => {
return (
// snippet multiasset-between-cores
client.transactions.build(builder => {
builder.spendFromAccount({
accountAlias: 'alice',
assetAlias: 'gold',
amount: 10
})
builder.spendFromAccount({
accountAlias: 'alice',
assetAlias: 'silver',
amount: 20
})
builder.controlWithReceiver({
receiver: JSON.parse(bobGoldReceiverSerialized),
assetAlias: 'gold',
amount: 10
})
builder.controlWithReceiver({
receiver: JSON.parse(bobSilverReceiverSerialized),
assetAlias: 'silver',
amount: 20
})
})
.then(payment => signer.sign(payment))
.then(signed => client.transactions.submit(signed))
// endsnippet
)
}).then(() =>
// snippet retire
client.transactions.build(builder => {
builder.spendFromAccount({
accountAlias: 'alice',
assetAlias: 'gold',
amount: 50
})
builder.retire({
assetAlias: 'gold',
amount: 50
})
})
.then(retirement => signer.sign(retirement))
.then(signed => client.transactions.submit(signed))
// endsnippet
).catch(err =>
process.nextTick(() => { throw err })
)
| {
"pile_set_name": "Github"
} |
//= require flot/jquery.flot.js
//= require flot/jquery.flot.tooltip.min.js
//= require flot/jquery.flot.resize.js
//= require flot/jquery.flot.pie.js
//= require flot/jquery.flot.time.js
//= require flot/jquery.flot.spline.js
//= require sparkline/jquery.sparkline.min.js
//= require chartjs/Chart.min.js
//= require morris/raphael-2.1.0.min.js
//= require morris/morris.js
//= require rickshaw/vendor/d3.v3.js
//= require rickshaw/rickshaw.min.js
//= require chartist/chartist.min.js
//= require d3/d3.min.js
//= require c3/c3.min.js | {
"pile_set_name": "Github"
} |
namespace ClassLib047
{
public class Class078
{
public static string Property => "ClassLib047";
}
}
| {
"pile_set_name": "Github"
} |
// This optional code is used to register a service worker.
// register() is not called by default.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on subsequent visits to a page, after all the
// existing tabs open on the page have been closed, since previously cached
// resources are updated in the background.
// To learn more about the benefits of this model and instructions on how to
// opt-in, read https://bit.ly/CRA-PWA
const isLocalhost = Boolean(
window.location.hostname === "localhost" ||
// [::1] is the IPv6 localhost address.
window.location.hostname === "[::1]" ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);
export function register(config) {
if (process.env.NODE_ENV === "production" && "serviceWorker" in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
return;
}
window.addEventListener("load", () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
"This web app is being served cache-first by a service " +
"worker. To learn more, visit https://bit.ly/CRA-PWA"
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === "installed") {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
"New content is available and will be used when all " +
"tabs for this page are closed. See https://bit.ly/CRA-PWA."
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log("Content is cached for offline use.");
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error("Error during service worker registration:", error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get("content-type");
if (response.status === 404 || (contentType != null && contentType.indexOf("javascript") === -1)) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log("No internet connection found. App is running in offline mode.");
});
}
export function unregister() {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 2019, 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.
*
* 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.
*/
package org.openjdk.skara.bots.mlbridge;
import org.openjdk.skara.bot.*;
import org.openjdk.skara.email.EmailAddress;
import org.openjdk.skara.forge.HostedRepository;
import org.openjdk.skara.network.URIBuilder;
import org.openjdk.skara.json.*;
import org.openjdk.skara.mailinglist.MailingListServerFactory;
import java.nio.file.Path;
import java.time.Duration;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
public class MailingListBridgeBotFactory implements BotFactory {
@Override
public String name() {
return "mlbridge";
}
private MailingListConfiguration parseList(JSONObject configuration) {
var listAddress = EmailAddress.parse(configuration.get("email").asString());
Set<String> labels = configuration.contains("labels") ?
configuration.get("labels").stream()
.map(JSONValue::asString)
.collect(Collectors.toSet()) :
Set.of();
return new MailingListConfiguration(listAddress, labels);
}
private List<MailingListConfiguration> parseLists(JSONValue configuration) {
if (configuration.isArray()) {
return configuration.stream()
.map(JSONValue::asObject)
.map(this::parseList)
.collect(Collectors.toList());
} else {
return List.of(parseList(configuration.asObject()));
}
}
@Override
public List<Bot> create(BotConfiguration configuration) {
var ret = new ArrayList<Bot>();
var specific = configuration.specific();
var from = EmailAddress.from(specific.get("name").asString(), specific.get("mail").asString());
var ignoredUsers = specific.get("ignored").get("users").stream()
.map(JSONValue::asString)
.collect(Collectors.toSet());
var ignoredComments = specific.get("ignored").get("comments").stream()
.map(JSONValue::asString)
.map(pattern -> Pattern.compile(pattern, Pattern.MULTILINE | Pattern.DOTALL))
.collect(Collectors.toSet());
var listArchive = URIBuilder.base(specific.get("server").get("archive").asString()).build();
var listSmtp = specific.get("server").get("smtp").asString();
var interval = specific.get("server").contains("interval") ? Duration.parse(specific.get("server").get("interval").asString()) : Duration.ofSeconds(1);
var webrevHTMLRepo = configuration.repository(specific.get("webrevs").get("repository").get("html").asString());
var webrevJSONRepo = configuration.repository(specific.get("webrevs").get("repository").get("json").asString());
var webrevRef = specific.get("webrevs").get("ref").asString();
var webrevWeb = specific.get("webrevs").get("web").asString();
var archiveRepo = configuration.repository(specific.get("archive").asString());
var archiveRef = configuration.repositoryRef(specific.get("archive").asString());
var issueTracker = URIBuilder.base(specific.get("issues").asString()).build();
var listNamesForReading = new HashSet<EmailAddress>();
var allRepositories = new HashSet<HostedRepository>();
var readyLabels = specific.get("ready").get("labels").stream()
.map(JSONValue::asString)
.collect(Collectors.toSet());
var readyComments = specific.get("ready").get("comments").stream()
.map(JSONValue::asObject)
.collect(Collectors.toMap(obj -> obj.get("user").asString(),
obj -> Pattern.compile(obj.get("pattern").asString())));
var cooldown = specific.contains("cooldown") ? Duration.parse(specific.get("cooldown").asString()) : Duration.ofMinutes(1);
for (var repoConfig : specific.get("repositories").asArray()) {
var repo = repoConfig.get("repository").asString();
var censusRepo = configuration.repository(repoConfig.get("census").asString());
var censusRef = configuration.repositoryRef(repoConfig.get("census").asString());
Map<String, String> headers = repoConfig.contains("headers") ?
repoConfig.get("headers").fields().stream()
.collect(Collectors.toMap(JSONObject.Field::name, field -> field.value().asString())) :
Map.of();
var lists = parseLists(repoConfig.get("lists"));
var folder = repoConfig.contains("folder") ? repoConfig.get("folder").asString() : configuration.repositoryName(repo);
var webrevGenerateHTML = true;
if (repoConfig.contains("webrevs") &&
repoConfig.get("webrevs").contains("html") &&
repoConfig.get("webrevs").get("html").asBoolean() == false) {
webrevGenerateHTML = false;
}
var webrevGenerateJSON = repoConfig.contains("webrevs") &&
repoConfig.get("webrevs").contains("json") &&
repoConfig.get("webrevs").get("json").asBoolean();
var botBuilder = MailingListBridgeBot.newBuilder().from(from)
.repo(configuration.repository(repo))
.archive(archiveRepo)
.archiveRef(archiveRef)
.censusRepo(censusRepo)
.censusRef(censusRef)
.lists(lists)
.ignoredUsers(ignoredUsers)
.ignoredComments(ignoredComments)
.listArchive(listArchive)
.smtpServer(listSmtp)
.webrevStorageHTMLRepository(webrevHTMLRepo)
.webrevStorageJSONRepository(webrevJSONRepo)
.webrevStorageRef(webrevRef)
.webrevStorageBase(Path.of(folder))
.webrevStorageBaseUri(URIBuilder.base(webrevWeb).build())
.webrevGenerateHTML(webrevGenerateHTML)
.webrevGenerateJSON(webrevGenerateJSON)
.readyLabels(readyLabels)
.readyComments(readyComments)
.issueTracker(issueTracker)
.headers(headers)
.sendInterval(interval)
.cooldown(cooldown)
.seedStorage(configuration.storageFolder().resolve("seeds"));
if (repoConfig.contains("reponame")) {
botBuilder.repoInSubject(repoConfig.get("reponame").asBoolean());
}
if (repoConfig.contains("branchname")) {
botBuilder.branchInSubject(Pattern.compile(repoConfig.get("branchname").asString()));
}
ret.add(botBuilder.build());
if (!repoConfig.contains("bidirectional") || repoConfig.get("bidirectional").asBoolean()) {
for (var list : lists) {
listNamesForReading.add(list.list());
}
}
allRepositories.add(configuration.repository(repo));
}
var mailmanServer = MailingListServerFactory.createMailmanServer(listArchive, listSmtp, Duration.ZERO);
var listsForReading = listNamesForReading.stream()
.map(name -> mailmanServer.getList(name.toString()))
.collect(Collectors.toSet());
var bot = new MailingListArchiveReaderBot(from, listsForReading, allRepositories);
ret.add(bot);
return ret;
}
}
| {
"pile_set_name": "Github"
} |
#import "Expecta.h"
EXPMatcherInterface(haveCountOf, (NSUInteger expected));
#define haveCount haveCountOf
#define haveACountOf haveCountOf
#define haveLength haveCountOf
#define haveLengthOf haveCountOf
#define haveALengthOf haveCountOf
#define beEmpty() haveCountOf(0)
| {
"pile_set_name": "Github"
} |
/*
* YAFFS: Yet Another Flash File System. A NAND-flash specific file system.
*
* Copyright (C) 2002-2011 Aleph One Ltd.
* for Toby Churchill Ltd and Brightstar Engineering
*
* Created by Charles Manning <[email protected]>
*
* 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.
*/
#include "yaffs_allocator.h"
#include "yaffs_guts.h"
#include "yaffs_trace.h"
#include "yportenv.h"
/*
* Each entry in yaffs_tnode_list and yaffs_obj_list hold blocks
* of approx 100 objects that are themn allocated singly.
* This is basically a simplified slab allocator.
*
* We don't use the Linux slab allocator because slab does not allow
* us to dump all the objects in one hit when we do a umount and tear
* down all the tnodes and objects. slab requires that we first free
* the individual objects.
*
* Once yaffs has been mainlined I shall try to motivate for a change
* to slab to provide the extra features we need here.
*/
struct yaffs_tnode_list {
struct yaffs_tnode_list *next;
struct yaffs_tnode *tnodes;
};
struct yaffs_obj_list {
struct yaffs_obj_list *next;
struct yaffs_obj *objects;
};
struct yaffs_allocator {
int n_tnodes_created;
struct yaffs_tnode *free_tnodes;
int n_free_tnodes;
struct yaffs_tnode_list *alloc_tnode_list;
int n_obj_created;
struct list_head free_objs;
int n_free_objects;
struct yaffs_obj_list *allocated_obj_list;
};
static void yaffs_deinit_raw_tnodes(struct yaffs_dev *dev)
{
struct yaffs_allocator *allocator =
(struct yaffs_allocator *)dev->allocator;
struct yaffs_tnode_list *tmp;
if (!allocator) {
BUG();
return;
}
while (allocator->alloc_tnode_list) {
tmp = allocator->alloc_tnode_list->next;
kfree(allocator->alloc_tnode_list->tnodes);
kfree(allocator->alloc_tnode_list);
allocator->alloc_tnode_list = tmp;
}
allocator->free_tnodes = NULL;
allocator->n_free_tnodes = 0;
allocator->n_tnodes_created = 0;
}
static void yaffs_init_raw_tnodes(struct yaffs_dev *dev)
{
struct yaffs_allocator *allocator = dev->allocator;
if (!allocator) {
BUG();
return;
}
allocator->alloc_tnode_list = NULL;
allocator->free_tnodes = NULL;
allocator->n_free_tnodes = 0;
allocator->n_tnodes_created = 0;
}
static int yaffs_create_tnodes(struct yaffs_dev *dev, int n_tnodes)
{
struct yaffs_allocator *allocator =
(struct yaffs_allocator *)dev->allocator;
int i;
struct yaffs_tnode *new_tnodes;
u8 *mem;
struct yaffs_tnode *curr;
struct yaffs_tnode *next;
struct yaffs_tnode_list *tnl;
if (!allocator) {
BUG();
return YAFFS_FAIL;
}
if (n_tnodes < 1)
return YAFFS_OK;
/* make these things */
new_tnodes = kmalloc(n_tnodes * dev->tnode_size, GFP_NOFS);
mem = (u8 *) new_tnodes;
if (!new_tnodes) {
yaffs_trace(YAFFS_TRACE_ERROR,
"yaffs: Could not allocate Tnodes");
return YAFFS_FAIL;
}
/* New hookup for wide tnodes */
for (i = 0; i < n_tnodes - 1; i++) {
curr = (struct yaffs_tnode *)&mem[i * dev->tnode_size];
next = (struct yaffs_tnode *)&mem[(i + 1) * dev->tnode_size];
curr->internal[0] = next;
}
curr = (struct yaffs_tnode *)&mem[(n_tnodes - 1) * dev->tnode_size];
curr->internal[0] = allocator->free_tnodes;
allocator->free_tnodes = (struct yaffs_tnode *)mem;
allocator->n_free_tnodes += n_tnodes;
allocator->n_tnodes_created += n_tnodes;
/* Now add this bunch of tnodes to a list for freeing up.
* NB If we can't add this to the management list it isn't fatal
* but it just means we can't free this bunch of tnodes later.
*/
tnl = kmalloc(sizeof(struct yaffs_tnode_list), GFP_NOFS);
if (!tnl) {
yaffs_trace(YAFFS_TRACE_ERROR,
"Could not add tnodes to management list");
return YAFFS_FAIL;
} else {
tnl->tnodes = new_tnodes;
tnl->next = allocator->alloc_tnode_list;
allocator->alloc_tnode_list = tnl;
}
yaffs_trace(YAFFS_TRACE_ALLOCATE, "Tnodes added");
return YAFFS_OK;
}
struct yaffs_tnode *yaffs_alloc_raw_tnode(struct yaffs_dev *dev)
{
struct yaffs_allocator *allocator =
(struct yaffs_allocator *)dev->allocator;
struct yaffs_tnode *tn = NULL;
if (!allocator) {
BUG();
return NULL;
}
/* If there are none left make more */
if (!allocator->free_tnodes)
yaffs_create_tnodes(dev, YAFFS_ALLOCATION_NTNODES);
if (allocator->free_tnodes) {
tn = allocator->free_tnodes;
allocator->free_tnodes = allocator->free_tnodes->internal[0];
allocator->n_free_tnodes--;
}
return tn;
}
/* FreeTnode frees up a tnode and puts it back on the free list */
void yaffs_free_raw_tnode(struct yaffs_dev *dev, struct yaffs_tnode *tn)
{
struct yaffs_allocator *allocator = dev->allocator;
if (!allocator) {
BUG();
return;
}
if (tn) {
tn->internal[0] = allocator->free_tnodes;
allocator->free_tnodes = tn;
allocator->n_free_tnodes++;
}
dev->checkpoint_blocks_required = 0; /* force recalculation */
}
/*--------------- yaffs_obj alloaction ------------------------
*
* Free yaffs_objs are stored in a list using obj->siblings.
* The blocks of allocated objects are stored in a linked list.
*/
static void yaffs_init_raw_objs(struct yaffs_dev *dev)
{
struct yaffs_allocator *allocator = dev->allocator;
if (!allocator) {
BUG();
return;
}
allocator->allocated_obj_list = NULL;
INIT_LIST_HEAD(&allocator->free_objs);
allocator->n_free_objects = 0;
}
static void yaffs_deinit_raw_objs(struct yaffs_dev *dev)
{
struct yaffs_allocator *allocator = dev->allocator;
struct yaffs_obj_list *tmp;
if (!allocator) {
BUG();
return;
}
while (allocator->allocated_obj_list) {
tmp = allocator->allocated_obj_list->next;
kfree(allocator->allocated_obj_list->objects);
kfree(allocator->allocated_obj_list);
allocator->allocated_obj_list = tmp;
}
INIT_LIST_HEAD(&allocator->free_objs);
allocator->n_free_objects = 0;
allocator->n_obj_created = 0;
}
static int yaffs_create_free_objs(struct yaffs_dev *dev, int n_obj)
{
struct yaffs_allocator *allocator = dev->allocator;
int i;
struct yaffs_obj *new_objs;
struct yaffs_obj_list *list;
if (!allocator) {
BUG();
return YAFFS_FAIL;
}
if (n_obj < 1)
return YAFFS_OK;
/* make these things */
new_objs = kmalloc(n_obj * sizeof(struct yaffs_obj), GFP_NOFS);
list = kmalloc(sizeof(struct yaffs_obj_list), GFP_NOFS);
if (!new_objs || !list) {
kfree(new_objs);
new_objs = NULL;
kfree(list);
list = NULL;
yaffs_trace(YAFFS_TRACE_ALLOCATE,
"Could not allocate more objects");
return YAFFS_FAIL;
}
/* Hook them into the free list */
for (i = 0; i < n_obj; i++)
list_add(&new_objs[i].siblings, &allocator->free_objs);
allocator->n_free_objects += n_obj;
allocator->n_obj_created += n_obj;
/* Now add this bunch of Objects to a list for freeing up. */
list->objects = new_objs;
list->next = allocator->allocated_obj_list;
allocator->allocated_obj_list = list;
return YAFFS_OK;
}
struct yaffs_obj *yaffs_alloc_raw_obj(struct yaffs_dev *dev)
{
struct yaffs_obj *obj = NULL;
struct list_head *lh;
struct yaffs_allocator *allocator = dev->allocator;
if (!allocator) {
BUG();
return obj;
}
/* If there are none left make more */
if (list_empty(&allocator->free_objs))
yaffs_create_free_objs(dev, YAFFS_ALLOCATION_NOBJECTS);
if (!list_empty(&allocator->free_objs)) {
lh = allocator->free_objs.next;
obj = list_entry(lh, struct yaffs_obj, siblings);
list_del_init(lh);
allocator->n_free_objects--;
}
return obj;
}
void yaffs_free_raw_obj(struct yaffs_dev *dev, struct yaffs_obj *obj)
{
struct yaffs_allocator *allocator = dev->allocator;
if (!allocator) {
BUG();
return;
}
/* Link into the free list. */
list_add(&obj->siblings, &allocator->free_objs);
allocator->n_free_objects++;
}
void yaffs_deinit_raw_tnodes_and_objs(struct yaffs_dev *dev)
{
if (!dev->allocator) {
BUG();
return;
}
yaffs_deinit_raw_tnodes(dev);
yaffs_deinit_raw_objs(dev);
kfree(dev->allocator);
dev->allocator = NULL;
}
void yaffs_init_raw_tnodes_and_objs(struct yaffs_dev *dev)
{
struct yaffs_allocator *allocator;
if (dev->allocator) {
BUG();
return;
}
allocator = kmalloc(sizeof(struct yaffs_allocator), GFP_NOFS);
if (allocator) {
dev->allocator = allocator;
yaffs_init_raw_tnodes(dev);
yaffs_init_raw_objs(dev);
}
}
| {
"pile_set_name": "Github"
} |
# Example Use: Creating a building classifier in Vietnam using MXNet and SageMaker
As one of the tropical countries in Asia, Vietnam has quite a variety of land use types. From the satellite imagery, you could easily spot tropical forests in dark green, deforestation patches that mix green with bare earth, rice paddy with light green and buildings with a vast variety of roof colors. It would be an interesting challenge to build a building classifier with MXNet and to train in Amazon SageMaker specifically. [Amazon SageMaker](https://aws.amazon.com/sagemaker/) is a new service from Amazon Web Services (AWS) that enables users to develop, train, deploy and scale machine learning approaches in a fairly straightforward way.
# Download Training Dataset
Before playing with SageMaker, we need to get the training dataset prepared using Label Maker.
- Install: `pip install label_maker`;
- Create Vietnam.json like shown in following json file;
```json
{
"country": "vietnam",
"bounding_box": [105.42,20.75,106.41,21.53],
"zoom": 17,
"classes": [
{ "name": "Buildings", "filter": ["has", "building"] }
],
"imagery": "http://a.tiles.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.jpg?access_token=ACCESS_TOKEN",
"background_ratio": 1,
"ml_type": "classification"
}
```
We're using the same configuration from [another walkthrough](../examples/walkthrough-classification-aws.md) with changes to location:
- `country` and `bounding_box`: changed to indicated the location in Vietnam to download data from.
- `zoom`: Buildings in Vietnam have quite a variety in size, so zoom 15 (roughly 5m resolution) will allow us spot building(s) in the tile.
# Training dataset generation
We'll follow the [CLI commands from the README](https://github.com/developmentseed/label-maker#command-line-use) but use a separate folder to keep our project well-managed.
```bash
$ label-maker download --dest Vietnam_building --config Vietnam.json
$ label-maker labels --dest Vietnam_building --config Vietnam.json
```
These commands will download and retile the OpenStreetMap QA tiles and use it to create our label data as `labels.npz`. We'll also get a file for inspection `classifcation.geojson`:
<p align="center">
<img src="images/Vietnam_tiles.png" width="500" />
</p>
_Purple building tile labels overlaid over [Mapbox Satellite Imagery](https://www.mapbox.com/maps/satellite/)_
Preview the data with
```bash
$ label-maker preview -n 10 --dest Vietnam_building --config Vietnam.json
```
Example satellite images will be at `Vietnam_building/examples`, and here we're showing three tiles here.
<p align="center">
<img src="images/Vietnam_Buildings.png" width="700" />
</p>
When you're ready, download all 2290 imagery tiles and package it into our final file, if you wanna download less tiles you could adjust the bounding box above in the json file:
```bash
$ label-maker images --dest Vietnam_building --config Vietnam.json
$ label-maker package --dest Vietnam_building --config Vietnam.json
```
We'll use the final file `Vietnam_building/data.npz` to start training the model on Sagemaker.
# Setup Amazon Sagemaker
Here are few steps to follow if you are interested in using it to train an image classification with MXNet:
- Go to your [AWS console](https://console.aws.amazon.com)
- Log in your account and go to the [Sagemaker home page](https://console.aws.amazon.com/sagemaker/)
- Create a Notebook Instance!
<p align="center">
<img src="images/sagemaker.png" width="700" />
</p>
Click on `Create notebook Instance`. You will have three instance options, `ml.t2.medium`, `ml.m4.xlarge` and `ml.p2.xlarge` to choose from. We recommend you use the p2 machine (a GPU machine) to train this image classification.
Once you have your p2 instance notebook set up, you are ready to train a classifier. Specifically, you are going to learn how to plug your own script into Amazon SageMaker MXNet Estimator and train the classifier we prepared for detecting buildings in images.
# Train the model with MXNet on AWS SageMaker
Training a LeNet building classifier using MXNet Estimator:
- Upload the [`SageMaker_mx-lenet.ipynb` notebook](https://github.com/developmentseed/label-maker/blob/master/examples/nets/SageMaker_mx-lenet.ipynb). You can make updates to the first cell, `mx_lenet_sagemaker.py`, to customize the network architecture.
- The second cell in the notebook calls the first script as the entry-point to running SageMaker. By executing the cell you will save a `mx_lenet_sagemaker.py` to the current notebook directory in your SageMaker instance machine. We call the estimator with the following arguments:
- The prepared script in the notebook: `mx_lenet_sagemaker.py`:
- Your SageMaker `role` and it can be obtained with `get_execution_role`
- The `train_instance_type`, we used and also recommend GPU instance `ml.p2.xlarge` here
- The `train_instance_count` is equal to 1, which means we are going to train this LeNet on only one machine. You can also train the model with multiple machines using SageMaker.
- Pass your training data to `mxnet_estimator.fit()` from a S3 bucket.
- Using `mxnet_estimator.deploy()`, now you are using the Sagemaker MXNet model server to host your trained model.
- Now you are ready to read or download test tiles from your S3 bucket using [Boto3](https://boto3.readthedocs.io/en/latest/) like we show in the ipython notebook, and make a prediction from your trained model.
| {
"pile_set_name": "Github"
} |
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: alchaplinsky
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
| {
"pile_set_name": "Github"
} |
//////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Ion Gaztanaga 2005-2015. 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/container for documentation.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_CONTAINER_DEQUE_HPP
#define BOOST_CONTAINER_DEQUE_HPP
#ifndef BOOST_CONFIG_HPP
# include <boost/config.hpp>
#endif
#if defined(BOOST_HAS_PRAGMA_ONCE)
# pragma once
#endif
#include <boost/container/detail/config_begin.hpp>
#include <boost/container/detail/workaround.hpp>
// container
#include <boost/container/allocator_traits.hpp>
#include <boost/container/container_fwd.hpp>
#include <boost/container/new_allocator.hpp> //new_allocator
#include <boost/container/throw_exception.hpp>
// container/detail
#include <boost/container/detail/advanced_insert_int.hpp>
#include <boost/container/detail/algorithm.hpp> //algo_equal(), algo_lexicographical_compare
#include <boost/container/detail/alloc_helpers.hpp>
#include <boost/container/detail/copy_move_algo.hpp>
#include <boost/container/detail/iterator.hpp>
#include <boost/move/detail/iterator_to_raw_pointer.hpp>
#include <boost/container/detail/iterators.hpp>
#include <boost/container/detail/min_max.hpp>
#include <boost/container/detail/mpl.hpp>
#include <boost/move/detail/to_raw_pointer.hpp>
#include <boost/container/detail/type_traits.hpp>
// move
#include <boost/move/adl_move_swap.hpp>
#include <boost/move/iterator.hpp>
#include <boost/move/traits.hpp>
#include <boost/move/utility_core.hpp>
// move/detail
#if defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#include <boost/move/detail/fwd_macros.hpp>
#endif
#include <boost/move/detail/move_helpers.hpp>
// other
#include <boost/assert.hpp>
#include <boost/core/no_exceptions_support.hpp>
// std
#include <cstddef>
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
#include <initializer_list>
#endif
namespace boost {
namespace container {
#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
template <class T, class Allocator>
class deque;
template <class T>
struct deque_value_traits
{
typedef T value_type;
static const bool trivial_dctr = dtl::is_trivially_destructible<value_type>::value;
static const bool trivial_dctr_after_move = ::boost::has_trivial_destructor_after_move<value_type>::value;
};
// Note: this function is simply a kludge to work around several compilers'
// bugs in handling constant expressions.
template<class T>
struct deque_buf_size
{
static const std::size_t min_size = 512u;
static const std::size_t sizeof_t = sizeof(T);
static const std::size_t value = sizeof_t < min_size ? (min_size/sizeof_t) : std::size_t(1);
};
namespace dtl {
// Class invariants:
// For any nonsingular iterator i:
// i.node is the address of an element in the map array. The
// contents of i.node is a pointer to the beginning of a node.
// i.first == //(i.node)
// i.last == i.first + node_size
// i.cur is a pointer in the range [i.first, i.last). NOTE:
// the implication of this is that i.cur is always a dereferenceable
// pointer, even if i is a past-the-end iterator.
// Start and Finish are always nonsingular iterators. NOTE: this means
// that an empty deque must have one node, and that a deque
// with N elements, where N is the buffer size, must have two nodes.
// For every node other than start.node and finish.node, every element
// in the node is an initialized object. If start.node == finish.node,
// then [start.cur, finish.cur) are initialized objects, and
// the elements outside that range are uninitialized storage. Otherwise,
// [start.cur, start.last) and [finish.first, finish.cur) are initialized
// objects, and [start.first, start.cur) and [finish.cur, finish.last)
// are uninitialized storage.
// [map, map + map_size) is a valid, non-empty range.
// [start.node, finish.node] is a valid range contained within
// [map, map + map_size).
// A pointer in the range [map, map + map_size) points to an allocated node
// if and only if the pointer is in the range [start.node, finish.node].
template<class Pointer, bool IsConst>
class deque_iterator
{
public:
typedef std::random_access_iterator_tag iterator_category;
typedef typename boost::intrusive::pointer_traits<Pointer>::element_type value_type;
typedef typename boost::intrusive::pointer_traits<Pointer>::difference_type difference_type;
typedef typename if_c
< IsConst
, typename boost::intrusive::pointer_traits<Pointer>::template
rebind_pointer<const value_type>::type
, Pointer
>::type pointer;
typedef typename if_c
< IsConst
, const value_type&
, value_type&
>::type reference;
class nat;
typedef typename dtl::if_c< IsConst
, deque_iterator<Pointer, false>
, nat>::type nonconst_iterator;
BOOST_CONTAINER_FORCEINLINE static std::size_t s_buffer_size()
{ return deque_buf_size<value_type>::value; }
typedef Pointer val_alloc_ptr;
typedef typename boost::intrusive::pointer_traits<Pointer>::
template rebind_pointer<Pointer>::type index_pointer;
Pointer m_cur;
Pointer m_first;
Pointer m_last;
index_pointer m_node;
public:
BOOST_CONTAINER_FORCEINLINE Pointer get_cur() const { return m_cur; }
BOOST_CONTAINER_FORCEINLINE Pointer get_first() const { return m_first; }
BOOST_CONTAINER_FORCEINLINE Pointer get_last() const { return m_last; }
BOOST_CONTAINER_FORCEINLINE index_pointer get_node() const { return m_node; }
BOOST_CONTAINER_FORCEINLINE deque_iterator(val_alloc_ptr x, index_pointer y) BOOST_NOEXCEPT_OR_NOTHROW
: m_cur(x), m_first(*y), m_last(*y + s_buffer_size()), m_node(y)
{}
BOOST_CONTAINER_FORCEINLINE deque_iterator() BOOST_NOEXCEPT_OR_NOTHROW
: m_cur(), m_first(), m_last(), m_node() //Value initialization to achieve "null iterators" (N3644)
{}
BOOST_CONTAINER_FORCEINLINE deque_iterator(const deque_iterator& x) BOOST_NOEXCEPT_OR_NOTHROW
: m_cur(x.get_cur()), m_first(x.get_first()), m_last(x.get_last()), m_node(x.get_node())
{}
BOOST_CONTAINER_FORCEINLINE deque_iterator(const nonconst_iterator& x) BOOST_NOEXCEPT_OR_NOTHROW
: m_cur(x.get_cur()), m_first(x.get_first()), m_last(x.get_last()), m_node(x.get_node())
{}
deque_iterator(Pointer cur, Pointer first, Pointer last, index_pointer node) BOOST_NOEXCEPT_OR_NOTHROW
: m_cur(cur), m_first(first), m_last(last), m_node(node)
{}
BOOST_CONTAINER_FORCEINLINE deque_iterator& operator=(const deque_iterator& x) BOOST_NOEXCEPT_OR_NOTHROW
{ m_cur = x.get_cur(); m_first = x.get_first(); m_last = x.get_last(); m_node = x.get_node(); return *this; }
BOOST_CONTAINER_FORCEINLINE deque_iterator<Pointer, false> unconst() const BOOST_NOEXCEPT_OR_NOTHROW
{
return deque_iterator<Pointer, false>(this->get_cur(), this->get_first(), this->get_last(), this->get_node());
}
BOOST_CONTAINER_FORCEINLINE reference operator*() const BOOST_NOEXCEPT_OR_NOTHROW
{ return *this->m_cur; }
BOOST_CONTAINER_FORCEINLINE pointer operator->() const BOOST_NOEXCEPT_OR_NOTHROW
{ return this->m_cur; }
difference_type operator-(const deque_iterator& x) const BOOST_NOEXCEPT_OR_NOTHROW
{
if(!this->m_cur && !x.m_cur){
return 0;
}
return difference_type(this->s_buffer_size()) * (this->m_node - x.m_node - 1) +
(this->m_cur - this->m_first) + (x.m_last - x.m_cur);
}
deque_iterator& operator++() BOOST_NOEXCEPT_OR_NOTHROW
{
++this->m_cur;
if (this->m_cur == this->m_last) {
this->priv_set_node(this->m_node + 1);
this->m_cur = this->m_first;
}
return *this;
}
BOOST_CONTAINER_FORCEINLINE deque_iterator operator++(int) BOOST_NOEXCEPT_OR_NOTHROW
{
deque_iterator tmp(*this);
++*this;
return tmp;
}
deque_iterator& operator--() BOOST_NOEXCEPT_OR_NOTHROW
{
if (this->m_cur == this->m_first) {
this->priv_set_node(this->m_node - 1);
this->m_cur = this->m_last;
}
--this->m_cur;
return *this;
}
BOOST_CONTAINER_FORCEINLINE deque_iterator operator--(int) BOOST_NOEXCEPT_OR_NOTHROW
{
deque_iterator tmp(*this);
--*this;
return tmp;
}
deque_iterator& operator+=(difference_type n) BOOST_NOEXCEPT_OR_NOTHROW
{
difference_type offset = n + (this->m_cur - this->m_first);
if (offset >= 0 && offset < difference_type(this->s_buffer_size()))
this->m_cur += n;
else {
difference_type node_offset =
offset > 0 ? offset / difference_type(this->s_buffer_size())
: -difference_type((-offset - 1) / this->s_buffer_size()) - 1;
this->priv_set_node(this->m_node + node_offset);
this->m_cur = this->m_first +
(offset - node_offset * difference_type(this->s_buffer_size()));
}
return *this;
}
BOOST_CONTAINER_FORCEINLINE deque_iterator operator+(difference_type n) const BOOST_NOEXCEPT_OR_NOTHROW
{ deque_iterator tmp(*this); return tmp += n; }
BOOST_CONTAINER_FORCEINLINE deque_iterator& operator-=(difference_type n) BOOST_NOEXCEPT_OR_NOTHROW
{ return *this += -n; }
BOOST_CONTAINER_FORCEINLINE deque_iterator operator-(difference_type n) const BOOST_NOEXCEPT_OR_NOTHROW
{ deque_iterator tmp(*this); return tmp -= n; }
BOOST_CONTAINER_FORCEINLINE reference operator[](difference_type n) const BOOST_NOEXCEPT_OR_NOTHROW
{ return *(*this + n); }
BOOST_CONTAINER_FORCEINLINE friend bool operator==(const deque_iterator& l, const deque_iterator& r) BOOST_NOEXCEPT_OR_NOTHROW
{ return l.m_cur == r.m_cur; }
BOOST_CONTAINER_FORCEINLINE friend bool operator!=(const deque_iterator& l, const deque_iterator& r) BOOST_NOEXCEPT_OR_NOTHROW
{ return l.m_cur != r.m_cur; }
BOOST_CONTAINER_FORCEINLINE friend bool operator<(const deque_iterator& l, const deque_iterator& r) BOOST_NOEXCEPT_OR_NOTHROW
{ return (l.m_node == r.m_node) ? (l.m_cur < r.m_cur) : (l.m_node < r.m_node); }
BOOST_CONTAINER_FORCEINLINE friend bool operator>(const deque_iterator& l, const deque_iterator& r) BOOST_NOEXCEPT_OR_NOTHROW
{ return r < l; }
BOOST_CONTAINER_FORCEINLINE friend bool operator<=(const deque_iterator& l, const deque_iterator& r) BOOST_NOEXCEPT_OR_NOTHROW
{ return !(r < l); }
BOOST_CONTAINER_FORCEINLINE friend bool operator>=(const deque_iterator& l, const deque_iterator& r) BOOST_NOEXCEPT_OR_NOTHROW
{ return !(l < r); }
BOOST_CONTAINER_FORCEINLINE void priv_set_node(index_pointer new_node) BOOST_NOEXCEPT_OR_NOTHROW
{
this->m_node = new_node;
this->m_first = *new_node;
this->m_last = this->m_first + this->s_buffer_size();
}
BOOST_CONTAINER_FORCEINLINE friend deque_iterator operator+(difference_type n, deque_iterator x) BOOST_NOEXCEPT_OR_NOTHROW
{ return x += n; }
};
} //namespace dtl {
// Deque base class. It has two purposes. First, its constructor
// and destructor allocate (but don't initialize) storage. This makes
// exception safety easier.
template <class Allocator>
class deque_base
{
BOOST_COPYABLE_AND_MOVABLE(deque_base)
public:
typedef allocator_traits<Allocator> val_alloc_traits_type;
typedef typename val_alloc_traits_type::value_type val_alloc_val;
typedef typename val_alloc_traits_type::pointer val_alloc_ptr;
typedef typename val_alloc_traits_type::const_pointer val_alloc_cptr;
typedef typename val_alloc_traits_type::reference val_alloc_ref;
typedef typename val_alloc_traits_type::const_reference val_alloc_cref;
typedef typename val_alloc_traits_type::difference_type val_alloc_diff;
typedef typename val_alloc_traits_type::size_type val_alloc_size;
typedef typename val_alloc_traits_type::template
portable_rebind_alloc<val_alloc_ptr>::type ptr_alloc_t;
typedef allocator_traits<ptr_alloc_t> ptr_alloc_traits_type;
typedef typename ptr_alloc_traits_type::value_type ptr_alloc_val;
typedef typename ptr_alloc_traits_type::pointer ptr_alloc_ptr;
typedef typename ptr_alloc_traits_type::const_pointer ptr_alloc_cptr;
typedef typename ptr_alloc_traits_type::reference ptr_alloc_ref;
typedef typename ptr_alloc_traits_type::const_reference ptr_alloc_cref;
typedef Allocator allocator_type;
typedef allocator_type stored_allocator_type;
typedef val_alloc_size size_type;
protected:
typedef deque_value_traits<val_alloc_val> traits_t;
typedef ptr_alloc_t map_allocator_type;
BOOST_CONTAINER_FORCEINLINE static size_type s_buffer_size() BOOST_NOEXCEPT_OR_NOTHROW
{ return deque_buf_size<val_alloc_val>::value; }
BOOST_CONTAINER_FORCEINLINE val_alloc_ptr priv_allocate_node()
{ return this->alloc().allocate(s_buffer_size()); }
BOOST_CONTAINER_FORCEINLINE void priv_deallocate_node(val_alloc_ptr p) BOOST_NOEXCEPT_OR_NOTHROW
{ this->alloc().deallocate(p, s_buffer_size()); }
BOOST_CONTAINER_FORCEINLINE ptr_alloc_ptr priv_allocate_map(size_type n)
{ return this->ptr_alloc().allocate(n); }
BOOST_CONTAINER_FORCEINLINE void priv_deallocate_map(ptr_alloc_ptr p, size_type n) BOOST_NOEXCEPT_OR_NOTHROW
{ this->ptr_alloc().deallocate(p, n); }
typedef dtl::deque_iterator<val_alloc_ptr, false> iterator;
typedef dtl::deque_iterator<val_alloc_ptr, true > const_iterator;
BOOST_CONTAINER_FORCEINLINE deque_base(size_type num_elements, const allocator_type& a)
: members_(a)
{ this->priv_initialize_map(num_elements); }
BOOST_CONTAINER_FORCEINLINE explicit deque_base(const allocator_type& a)
: members_(a)
{}
BOOST_CONTAINER_FORCEINLINE deque_base()
: members_()
{}
BOOST_CONTAINER_FORCEINLINE explicit deque_base(BOOST_RV_REF(deque_base) x)
: members_( boost::move(x.ptr_alloc())
, boost::move(x.alloc()) )
{}
~deque_base()
{
if (this->members_.m_map) {
this->priv_destroy_nodes(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1);
this->priv_deallocate_map(this->members_.m_map, this->members_.m_map_size);
}
}
private:
deque_base(const deque_base&);
protected:
void swap_members(deque_base &x) BOOST_NOEXCEPT_OR_NOTHROW
{
::boost::adl_move_swap(this->members_.m_start, x.members_.m_start);
::boost::adl_move_swap(this->members_.m_finish, x.members_.m_finish);
::boost::adl_move_swap(this->members_.m_map, x.members_.m_map);
::boost::adl_move_swap(this->members_.m_map_size, x.members_.m_map_size);
}
void priv_initialize_map(size_type num_elements)
{
// if(num_elements){
size_type num_nodes = num_elements / s_buffer_size() + 1;
this->members_.m_map_size = dtl::max_value((size_type) InitialMapSize, num_nodes + 2);
this->members_.m_map = this->priv_allocate_map(this->members_.m_map_size);
ptr_alloc_ptr nstart = this->members_.m_map + (this->members_.m_map_size - num_nodes) / 2;
ptr_alloc_ptr nfinish = nstart + num_nodes;
BOOST_TRY {
this->priv_create_nodes(nstart, nfinish);
}
BOOST_CATCH(...){
this->priv_deallocate_map(this->members_.m_map, this->members_.m_map_size);
this->members_.m_map = 0;
this->members_.m_map_size = 0;
BOOST_RETHROW
}
BOOST_CATCH_END
this->members_.m_start.priv_set_node(nstart);
this->members_.m_finish.priv_set_node(nfinish - 1);
this->members_.m_start.m_cur = this->members_.m_start.m_first;
this->members_.m_finish.m_cur = this->members_.m_finish.m_first +
num_elements % s_buffer_size();
// }
}
void priv_create_nodes(ptr_alloc_ptr nstart, ptr_alloc_ptr nfinish)
{
ptr_alloc_ptr cur = nstart;
BOOST_TRY {
for (; cur < nfinish; ++cur)
*cur = this->priv_allocate_node();
}
BOOST_CATCH(...){
this->priv_destroy_nodes(nstart, cur);
BOOST_RETHROW
}
BOOST_CATCH_END
}
void priv_destroy_nodes(ptr_alloc_ptr nstart, ptr_alloc_ptr nfinish) BOOST_NOEXCEPT_OR_NOTHROW
{
for (ptr_alloc_ptr n = nstart; n < nfinish; ++n)
this->priv_deallocate_node(*n);
}
void priv_clear_map() BOOST_NOEXCEPT_OR_NOTHROW
{
if (this->members_.m_map) {
this->priv_destroy_nodes(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1);
this->priv_deallocate_map(this->members_.m_map, this->members_.m_map_size);
this->members_.m_map = 0;
this->members_.m_map_size = 0;
this->members_.m_start = iterator();
this->members_.m_finish = this->members_.m_start;
}
}
enum { InitialMapSize = 8 };
protected:
struct members_holder
: public ptr_alloc_t
, public allocator_type
{
members_holder()
: map_allocator_type(), allocator_type()
, m_map(0), m_map_size(0)
, m_start(), m_finish(m_start)
{}
explicit members_holder(const allocator_type &a)
: map_allocator_type(a), allocator_type(a)
, m_map(0), m_map_size(0)
, m_start(), m_finish(m_start)
{}
template<class ValAllocConvertible, class PtrAllocConvertible>
members_holder(BOOST_FWD_REF(PtrAllocConvertible) pa, BOOST_FWD_REF(ValAllocConvertible) va)
: map_allocator_type(boost::forward<PtrAllocConvertible>(pa))
, allocator_type (boost::forward<ValAllocConvertible>(va))
, m_map(0), m_map_size(0)
, m_start(), m_finish(m_start)
{}
ptr_alloc_ptr m_map;
val_alloc_size m_map_size;
iterator m_start;
iterator m_finish;
} members_;
BOOST_CONTAINER_FORCEINLINE ptr_alloc_t &ptr_alloc() BOOST_NOEXCEPT_OR_NOTHROW
{ return members_; }
BOOST_CONTAINER_FORCEINLINE const ptr_alloc_t &ptr_alloc() const BOOST_NOEXCEPT_OR_NOTHROW
{ return members_; }
BOOST_CONTAINER_FORCEINLINE allocator_type &alloc() BOOST_NOEXCEPT_OR_NOTHROW
{ return members_; }
BOOST_CONTAINER_FORCEINLINE const allocator_type &alloc() const BOOST_NOEXCEPT_OR_NOTHROW
{ return members_; }
};
#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
#ifdef BOOST_CONTAINER_DOXYGEN_INVOKED
//! A double-ended queue is a sequence that supports random access to elements, constant time insertion
//! and removal of elements at the end of the sequence, and linear time insertion and removal of elements in the middle.
//!
//! \tparam T The type of object that is stored in the deque
//! \tparam Allocator The allocator used for all internal memory management
template <class T, class Allocator = new_allocator<T> >
#else
template <class T, class Allocator>
#endif
class deque : protected deque_base<typename real_allocator<T, Allocator>::type>
{
#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
private:
typedef deque_base<typename real_allocator<T, Allocator>::type> Base;
#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
typedef typename real_allocator<T, Allocator>::type ValAllocator;
public:
//////////////////////////////////////////////
//
// types
//
//////////////////////////////////////////////
typedef T value_type;
typedef ValAllocator allocator_type;
typedef typename ::boost::container::allocator_traits<ValAllocator>::pointer pointer;
typedef typename ::boost::container::allocator_traits<ValAllocator>::const_pointer const_pointer;
typedef typename ::boost::container::allocator_traits<ValAllocator>::reference reference;
typedef typename ::boost::container::allocator_traits<ValAllocator>::const_reference const_reference;
typedef typename ::boost::container::allocator_traits<ValAllocator>::size_type size_type;
typedef typename ::boost::container::allocator_traits<ValAllocator>::difference_type difference_type;
typedef BOOST_CONTAINER_IMPDEF(allocator_type) stored_allocator_type;
typedef BOOST_CONTAINER_IMPDEF(typename Base::iterator) iterator;
typedef BOOST_CONTAINER_IMPDEF(typename Base::const_iterator) const_iterator;
typedef BOOST_CONTAINER_IMPDEF(boost::container::reverse_iterator<iterator>) reverse_iterator;
typedef BOOST_CONTAINER_IMPDEF(boost::container::reverse_iterator<const_iterator>) const_reverse_iterator;
#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
private: // Internal typedefs
BOOST_COPYABLE_AND_MOVABLE(deque)
typedef typename Base::ptr_alloc_ptr index_pointer;
BOOST_CONTAINER_FORCEINLINE static size_type s_buffer_size()
{ return Base::s_buffer_size(); }
typedef allocator_traits<ValAllocator> allocator_traits_type;
#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
public:
//////////////////////////////////////////////
//
// construct/copy/destroy
//
//////////////////////////////////////////////
//! <b>Effects</b>: Default constructors a deque.
//!
//! <b>Throws</b>: If allocator_type's default constructor throws.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE deque() BOOST_NOEXCEPT_IF(dtl::is_nothrow_default_constructible<ValAllocator>::value)
: Base()
{}
//! <b>Effects</b>: Constructs a deque taking the allocator as parameter.
//!
//! <b>Throws</b>: Nothing
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE explicit deque(const allocator_type& a) BOOST_NOEXCEPT_OR_NOTHROW
: Base(a)
{}
//! <b>Effects</b>: Constructs a deque
//! and inserts n value initialized values.
//!
//! <b>Throws</b>: If allocator_type's default constructor
//! throws or T's value initialization throws.
//!
//! <b>Complexity</b>: Linear to n.
BOOST_CONTAINER_FORCEINLINE explicit deque(size_type n)
: Base(n, allocator_type())
{
dtl::insert_value_initialized_n_proxy<ValAllocator, iterator> proxy;
proxy.uninitialized_copy_n_and_update(this->alloc(), this->begin(), n);
//deque_base will deallocate in case of exception...
}
//! <b>Effects</b>: Constructs a deque
//! and inserts n default initialized values.
//!
//! <b>Throws</b>: If allocator_type's default constructor
//! throws or T's default initialization or copy constructor throws.
//!
//! <b>Complexity</b>: Linear to n.
//!
//! <b>Note</b>: Non-standard extension
BOOST_CONTAINER_FORCEINLINE deque(size_type n, default_init_t)
: Base(n, allocator_type())
{
dtl::insert_default_initialized_n_proxy<ValAllocator, iterator> proxy;
proxy.uninitialized_copy_n_and_update(this->alloc(), this->begin(), n);
//deque_base will deallocate in case of exception...
}
//! <b>Effects</b>: Constructs a deque that will use a copy of allocator a
//! and inserts n value initialized values.
//!
//! <b>Throws</b>: If allocator_type's default constructor
//! throws or T's value initialization throws.
//!
//! <b>Complexity</b>: Linear to n.
BOOST_CONTAINER_FORCEINLINE explicit deque(size_type n, const allocator_type &a)
: Base(n, a)
{
dtl::insert_value_initialized_n_proxy<ValAllocator, iterator> proxy;
proxy.uninitialized_copy_n_and_update(this->alloc(), this->begin(), n);
//deque_base will deallocate in case of exception...
}
//! <b>Effects</b>: Constructs a deque that will use a copy of allocator a
//! and inserts n default initialized values.
//!
//! <b>Throws</b>: If allocator_type's default constructor
//! throws or T's default initialization or copy constructor throws.
//!
//! <b>Complexity</b>: Linear to n.
//!
//! <b>Note</b>: Non-standard extension
BOOST_CONTAINER_FORCEINLINE deque(size_type n, default_init_t, const allocator_type &a)
: Base(n, a)
{
dtl::insert_default_initialized_n_proxy<ValAllocator, iterator> proxy;
proxy.uninitialized_copy_n_and_update(this->alloc(), this->begin(), n);
//deque_base will deallocate in case of exception...
}
//! <b>Effects</b>: Constructs a deque that will use a copy of allocator a
//! and inserts n copies of value.
//!
//! <b>Throws</b>: If allocator_type's default constructor
//! throws or T's copy constructor throws.
//!
//! <b>Complexity</b>: Linear to n.
BOOST_CONTAINER_FORCEINLINE deque(size_type n, const value_type& value)
: Base(n, allocator_type())
{ this->priv_fill_initialize(value); }
//! <b>Effects</b>: Constructs a deque that will use a copy of allocator a
//! and inserts n copies of value.
//!
//! <b>Throws</b>: If allocator_type's default constructor
//! throws or T's copy constructor throws.
//!
//! <b>Complexity</b>: Linear to n.
BOOST_CONTAINER_FORCEINLINE deque(size_type n, const value_type& value, const allocator_type& a)
: Base(n, a)
{ this->priv_fill_initialize(value); }
//! <b>Effects</b>: Constructs a deque that will use a copy of allocator a
//! and inserts a copy of the range [first, last) in the deque.
//!
//! <b>Throws</b>: If allocator_type's default constructor
//! throws or T's constructor taking a dereferenced InIt throws.
//!
//! <b>Complexity</b>: Linear to the range [first, last).
template <class InIt>
BOOST_CONTAINER_FORCEINLINE deque(InIt first, InIt last
#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
, typename dtl::disable_if_convertible
<InIt, size_type>::type * = 0
#endif
)
: Base(allocator_type())
{
this->priv_range_initialize(first, last);
}
//! <b>Effects</b>: Constructs a deque that will use a copy of allocator a
//! and inserts a copy of the range [first, last) in the deque.
//!
//! <b>Throws</b>: If allocator_type's default constructor
//! throws or T's constructor taking a dereferenced InIt throws.
//!
//! <b>Complexity</b>: Linear to the range [first, last).
template <class InIt>
BOOST_CONTAINER_FORCEINLINE deque(InIt first, InIt last, const allocator_type& a
#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
, typename dtl::disable_if_convertible
<InIt, size_type>::type * = 0
#endif
)
: Base(a)
{
this->priv_range_initialize(first, last);
}
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
//! <b>Effects</b>: Constructs a deque that will use a copy of allocator a
//! and inserts a copy of the range [il.begin(), il.end()) in the deque.
//!
//! <b>Throws</b>: If allocator_type's default constructor
//! throws or T's constructor taking a dereferenced std::initializer_list iterator throws.
//!
//! <b>Complexity</b>: Linear to the range [il.begin(), il.end()).
BOOST_CONTAINER_FORCEINLINE deque(std::initializer_list<value_type> il, const allocator_type& a = allocator_type())
: Base(a)
{
this->priv_range_initialize(il.begin(), il.end());
}
#endif
//! <b>Effects</b>: Copy constructs a deque.
//!
//! <b>Postcondition</b>: x == *this.
//!
//! <b>Complexity</b>: Linear to the elements x contains.
BOOST_CONTAINER_FORCEINLINE deque(const deque& x)
: Base(allocator_traits_type::select_on_container_copy_construction(x.alloc()))
{
if(x.size()){
this->priv_initialize_map(x.size());
boost::container::uninitialized_copy_alloc
(this->alloc(), x.begin(), x.end(), this->members_.m_start);
}
}
//! <b>Effects</b>: Move constructor. Moves x's resources to *this.
//!
//! <b>Throws</b>: If allocator_type's copy constructor throws.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE deque(BOOST_RV_REF(deque) x) BOOST_NOEXCEPT_OR_NOTHROW
: Base(BOOST_MOVE_BASE(Base, x))
{ this->swap_members(x); }
//! <b>Effects</b>: Copy constructs a vector using the specified allocator.
//!
//! <b>Postcondition</b>: x == *this.
//!
//! <b>Throws</b>: If allocation
//! throws or T's copy constructor throws.
//!
//! <b>Complexity</b>: Linear to the elements x contains.
deque(const deque& x, const allocator_type &a)
: Base(a)
{
if(x.size()){
this->priv_initialize_map(x.size());
boost::container::uninitialized_copy_alloc
(this->alloc(), x.begin(), x.end(), this->members_.m_start);
}
}
//! <b>Effects</b>: Move constructor using the specified allocator.
//! Moves x's resources to *this if a == allocator_type().
//! Otherwise copies values from x to *this.
//!
//! <b>Throws</b>: If allocation or T's copy constructor throws.
//!
//! <b>Complexity</b>: Constant if a == x.get_allocator(), linear otherwise.
deque(BOOST_RV_REF(deque) x, const allocator_type &a)
: Base(a)
{
if(x.alloc() == a){
this->swap_members(x);
}
else{
if(x.size()){
this->priv_initialize_map(x.size());
boost::container::uninitialized_copy_alloc
( this->alloc(), boost::make_move_iterator(x.begin())
, boost::make_move_iterator(x.end()), this->members_.m_start);
}
}
}
//! <b>Effects</b>: Destroys the deque. All stored values are destroyed
//! and used memory is deallocated.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Linear to the number of elements.
BOOST_CONTAINER_FORCEINLINE ~deque() BOOST_NOEXCEPT_OR_NOTHROW
{
this->priv_destroy_range(this->members_.m_start, this->members_.m_finish);
}
//! <b>Effects</b>: Makes *this contain the same elements as x.
//!
//! <b>Postcondition</b>: this->size() == x.size(). *this contains a copy
//! of each of x's elements.
//!
//! <b>Throws</b>: If memory allocation throws or T's copy constructor throws.
//!
//! <b>Complexity</b>: Linear to the number of elements in x.
deque& operator= (BOOST_COPY_ASSIGN_REF(deque) x)
{
if (&x != this){
allocator_type &this_alloc = this->alloc();
const allocator_type &x_alloc = x.alloc();
dtl::bool_<allocator_traits_type::
propagate_on_container_copy_assignment::value> flag;
if(flag && this_alloc != x_alloc){
this->clear();
this->shrink_to_fit();
}
dtl::assign_alloc(this->alloc(), x.alloc(), flag);
dtl::assign_alloc(this->ptr_alloc(), x.ptr_alloc(), flag);
this->assign(x.cbegin(), x.cend());
}
return *this;
}
//! <b>Effects</b>: Move assignment. All x's values are transferred to *this.
//!
//! <b>Throws</b>: If allocator_traits_type::propagate_on_container_move_assignment
//! is false and (allocation throws or value_type's move constructor throws)
//!
//! <b>Complexity</b>: Constant if allocator_traits_type::
//! propagate_on_container_move_assignment is true or
//! this->get>allocator() == x.get_allocator(). Linear otherwise.
deque& operator= (BOOST_RV_REF(deque) x)
BOOST_NOEXCEPT_IF(allocator_traits_type::propagate_on_container_move_assignment::value
|| allocator_traits_type::is_always_equal::value)
{
BOOST_ASSERT(this != &x);
allocator_type &this_alloc = this->alloc();
allocator_type &x_alloc = x.alloc();
const bool propagate_alloc = allocator_traits_type::
propagate_on_container_move_assignment::value;
dtl::bool_<propagate_alloc> flag;
const bool allocators_equal = this_alloc == x_alloc; (void)allocators_equal;
//Resources can be transferred if both allocators are
//going to be equal after this function (either propagated or already equal)
if(propagate_alloc || allocators_equal){
//Destroy objects but retain memory in case x reuses it in the future
this->clear();
//Move allocator if needed
dtl::move_alloc(this_alloc, x_alloc, flag);
dtl::move_alloc(this->ptr_alloc(), x.ptr_alloc(), flag);
//Nothrow swap
this->swap_members(x);
}
//Else do a one by one move
else{
this->assign( boost::make_move_iterator(x.begin())
, boost::make_move_iterator(x.end()));
}
return *this;
}
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
//! <b>Effects</b>: Makes *this contain the same elements as il.
//!
//! <b>Postcondition</b>: this->size() == il.size(). *this contains a copy
//! of each of x's elements.
//!
//! <b>Throws</b>: If memory allocation throws or T's copy constructor throws.
//!
//! <b>Complexity</b>: Linear to the number of elements in il.
BOOST_CONTAINER_FORCEINLINE deque& operator=(std::initializer_list<value_type> il)
{
this->assign(il.begin(), il.end());
return *this;
}
#endif
//! <b>Effects</b>: Assigns the n copies of val to *this.
//!
//! <b>Throws</b>: If memory allocation throws or T's copy constructor throws.
//!
//! <b>Complexity</b>: Linear to n.
BOOST_CONTAINER_FORCEINLINE void assign(size_type n, const T& val)
{
typedef constant_iterator<value_type, difference_type> c_it;
this->assign(c_it(val, n), c_it());
}
//! <b>Effects</b>: Assigns the the range [first, last) to *this.
//!
//! <b>Throws</b>: If memory allocation throws or
//! T's constructor from dereferencing InIt throws.
//!
//! <b>Complexity</b>: Linear to n.
template <class InIt>
void assign(InIt first, InIt last
#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
, typename dtl::disable_if_or
< void
, dtl::is_convertible<InIt, size_type>
, dtl::is_not_input_iterator<InIt>
>::type * = 0
#endif
)
{
iterator cur = this->begin();
for ( ; first != last && cur != end(); ++cur, ++first){
*cur = *first;
}
if (first == last){
this->erase(cur, this->cend());
}
else{
this->insert(this->cend(), first, last);
}
}
#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
template <class FwdIt>
void assign(FwdIt first, FwdIt last
, typename dtl::disable_if_or
< void
, dtl::is_convertible<FwdIt, size_type>
, dtl::is_input_iterator<FwdIt>
>::type * = 0
)
{
const size_type len = boost::container::iterator_distance(first, last);
if (len > size()) {
FwdIt mid = first;
boost::container::iterator_advance(mid, this->size());
boost::container::copy(first, mid, begin());
this->insert(this->cend(), mid, last);
}
else{
this->erase(boost::container::copy(first, last, this->begin()), cend());
}
}
#endif
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
//! <b>Effects</b>: Assigns the the range [il.begin(), il.end()) to *this.
//!
//! <b>Throws</b>: If memory allocation throws or
//! T's constructor from dereferencing std::initializer_list iterator throws.
//!
//! <b>Complexity</b>: Linear to il.size().
BOOST_CONTAINER_FORCEINLINE void assign(std::initializer_list<value_type> il)
{ this->assign(il.begin(), il.end()); }
#endif
//! <b>Effects</b>: Returns a copy of the internal allocator.
//!
//! <b>Throws</b>: If allocator's copy constructor throws.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE allocator_type get_allocator() const BOOST_NOEXCEPT_OR_NOTHROW
{ return Base::alloc(); }
//! <b>Effects</b>: Returns a reference to the internal allocator.
//!
//! <b>Throws</b>: Nothing
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension.
BOOST_CONTAINER_FORCEINLINE const stored_allocator_type &get_stored_allocator() const BOOST_NOEXCEPT_OR_NOTHROW
{ return Base::alloc(); }
//////////////////////////////////////////////
//
// iterators
//
//////////////////////////////////////////////
//! <b>Effects</b>: Returns a reference to the internal allocator.
//!
//! <b>Throws</b>: Nothing
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension.
BOOST_CONTAINER_FORCEINLINE stored_allocator_type &get_stored_allocator() BOOST_NOEXCEPT_OR_NOTHROW
{ return Base::alloc(); }
//! <b>Effects</b>: Returns an iterator to the first element contained in the deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE iterator begin() BOOST_NOEXCEPT_OR_NOTHROW
{ return this->members_.m_start; }
//! <b>Effects</b>: Returns a const_iterator to the first element contained in the deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_iterator begin() const BOOST_NOEXCEPT_OR_NOTHROW
{ return this->members_.m_start; }
//! <b>Effects</b>: Returns an iterator to the end of the deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE iterator end() BOOST_NOEXCEPT_OR_NOTHROW
{ return this->members_.m_finish; }
//! <b>Effects</b>: Returns a const_iterator to the end of the deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_iterator end() const BOOST_NOEXCEPT_OR_NOTHROW
{ return this->members_.m_finish; }
//! <b>Effects</b>: Returns a reverse_iterator pointing to the beginning
//! of the reversed deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE reverse_iterator rbegin() BOOST_NOEXCEPT_OR_NOTHROW
{ return reverse_iterator(this->members_.m_finish); }
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning
//! of the reversed deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_reverse_iterator rbegin() const BOOST_NOEXCEPT_OR_NOTHROW
{ return const_reverse_iterator(this->members_.m_finish); }
//! <b>Effects</b>: Returns a reverse_iterator pointing to the end
//! of the reversed deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE reverse_iterator rend() BOOST_NOEXCEPT_OR_NOTHROW
{ return reverse_iterator(this->members_.m_start); }
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end
//! of the reversed deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_reverse_iterator rend() const BOOST_NOEXCEPT_OR_NOTHROW
{ return const_reverse_iterator(this->members_.m_start); }
//! <b>Effects</b>: Returns a const_iterator to the first element contained in the deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_iterator cbegin() const BOOST_NOEXCEPT_OR_NOTHROW
{ return this->members_.m_start; }
//! <b>Effects</b>: Returns a const_iterator to the end of the deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_iterator cend() const BOOST_NOEXCEPT_OR_NOTHROW
{ return this->members_.m_finish; }
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning
//! of the reversed deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_reverse_iterator crbegin() const BOOST_NOEXCEPT_OR_NOTHROW
{ return const_reverse_iterator(this->members_.m_finish); }
//! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end
//! of the reversed deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_reverse_iterator crend() const BOOST_NOEXCEPT_OR_NOTHROW
{ return const_reverse_iterator(this->members_.m_start); }
//////////////////////////////////////////////
//
// capacity
//
//////////////////////////////////////////////
//! <b>Effects</b>: Returns true if the deque contains no elements.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE bool empty() const BOOST_NOEXCEPT_OR_NOTHROW
{ return this->members_.m_finish == this->members_.m_start; }
//! <b>Effects</b>: Returns the number of the elements contained in the deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE size_type size() const BOOST_NOEXCEPT_OR_NOTHROW
{ return this->members_.m_finish - this->members_.m_start; }
//! <b>Effects</b>: Returns the largest possible size of the deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE size_type max_size() const BOOST_NOEXCEPT_OR_NOTHROW
{ return allocator_traits_type::max_size(this->alloc()); }
//! <b>Effects</b>: Inserts or erases elements at the end such that
//! the size becomes n. New elements are value initialized.
//!
//! <b>Throws</b>: If memory allocation throws, or T's constructor throws.
//!
//! <b>Complexity</b>: Linear to the difference between size() and new_size.
void resize(size_type new_size)
{
const size_type len = size();
if (new_size < len)
this->priv_erase_last_n(len - new_size);
else{
const size_type n = new_size - this->size();
dtl::insert_value_initialized_n_proxy<ValAllocator, iterator> proxy;
priv_insert_back_aux_impl(n, proxy);
}
}
//! <b>Effects</b>: Inserts or erases elements at the end such that
//! the size becomes n. New elements are default initialized.
//!
//! <b>Throws</b>: If memory allocation throws, or T's constructor throws.
//!
//! <b>Complexity</b>: Linear to the difference between size() and new_size.
//!
//! <b>Note</b>: Non-standard extension
void resize(size_type new_size, default_init_t)
{
const size_type len = size();
if (new_size < len)
this->priv_erase_last_n(len - new_size);
else{
const size_type n = new_size - this->size();
dtl::insert_default_initialized_n_proxy<ValAllocator, iterator> proxy;
priv_insert_back_aux_impl(n, proxy);
}
}
//! <b>Effects</b>: Inserts or erases elements at the end such that
//! the size becomes n. New elements are copy constructed from x.
//!
//! <b>Throws</b>: If memory allocation throws, or T's copy constructor throws.
//!
//! <b>Complexity</b>: Linear to the difference between size() and new_size.
void resize(size_type new_size, const value_type& x)
{
const size_type len = size();
if (new_size < len)
this->erase(this->members_.m_start + new_size, this->members_.m_finish);
else
this->insert(this->members_.m_finish, new_size - len, x);
}
//! <b>Effects</b>: Tries to deallocate the excess of memory created
//! with previous allocations. The size of the deque is unchanged
//!
//! <b>Throws</b>: If memory allocation throws.
//!
//! <b>Complexity</b>: Constant.
void shrink_to_fit()
{
//This deque implementation already
//deallocates excess nodes when erasing
//so there is nothing to do except for
//empty deque
if(this->empty()){
this->priv_clear_map();
}
}
//////////////////////////////////////////////
//
// element access
//
//////////////////////////////////////////////
//! <b>Requires</b>: !empty()
//!
//! <b>Effects</b>: Returns a reference to the first
//! element of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE reference front() BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(!this->empty());
return *this->members_.m_start;
}
//! <b>Requires</b>: !empty()
//!
//! <b>Effects</b>: Returns a const reference to the first element
//! from the beginning of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_reference front() const BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(!this->empty());
return *this->members_.m_start;
}
//! <b>Requires</b>: !empty()
//!
//! <b>Effects</b>: Returns a reference to the last
//! element of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE reference back() BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(!this->empty());
return *(end()-1);
}
//! <b>Requires</b>: !empty()
//!
//! <b>Effects</b>: Returns a const reference to the last
//! element of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_reference back() const BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(!this->empty());
return *(cend()-1);
}
//! <b>Requires</b>: size() > n.
//!
//! <b>Effects</b>: Returns a reference to the nth element
//! from the beginning of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE reference operator[](size_type n) BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(this->size() > n);
return this->members_.m_start[difference_type(n)];
}
//! <b>Requires</b>: size() > n.
//!
//! <b>Effects</b>: Returns a const reference to the nth element
//! from the beginning of the container.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_reference operator[](size_type n) const BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(this->size() > n);
return this->members_.m_start[difference_type(n)];
}
//! <b>Requires</b>: size() >= n.
//!
//! <b>Effects</b>: Returns an iterator to the nth element
//! from the beginning of the container. Returns end()
//! if n == size().
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension
BOOST_CONTAINER_FORCEINLINE iterator nth(size_type n) BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(this->size() >= n);
return iterator(this->begin()+n);
}
//! <b>Requires</b>: size() >= n.
//!
//! <b>Effects</b>: Returns a const_iterator to the nth element
//! from the beginning of the container. Returns end()
//! if n == size().
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension
BOOST_CONTAINER_FORCEINLINE const_iterator nth(size_type n) const BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(this->size() >= n);
return const_iterator(this->cbegin()+n);
}
//! <b>Requires</b>: begin() <= p <= end().
//!
//! <b>Effects</b>: Returns the index of the element pointed by p
//! and size() if p == end().
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension
BOOST_CONTAINER_FORCEINLINE size_type index_of(iterator p) BOOST_NOEXCEPT_OR_NOTHROW
{
//Range checked priv_index_of
return this->priv_index_of(p);
}
//! <b>Requires</b>: begin() <= p <= end().
//!
//! <b>Effects</b>: Returns the index of the element pointed by p
//! and size() if p == end().
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
//!
//! <b>Note</b>: Non-standard extension
BOOST_CONTAINER_FORCEINLINE size_type index_of(const_iterator p) const BOOST_NOEXCEPT_OR_NOTHROW
{
//Range checked priv_index_of
return this->priv_index_of(p);
}
//! <b>Requires</b>: size() > n.
//!
//! <b>Effects</b>: Returns a reference to the nth element
//! from the beginning of the container.
//!
//! <b>Throws</b>: std::range_error if n >= size()
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE reference at(size_type n)
{
this->priv_throw_if_out_of_range(n);
return (*this)[n];
}
//! <b>Requires</b>: size() > n.
//!
//! <b>Effects</b>: Returns a const reference to the nth element
//! from the beginning of the container.
//!
//! <b>Throws</b>: std::range_error if n >= size()
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE const_reference at(size_type n) const
{
this->priv_throw_if_out_of_range(n);
return (*this)[n];
}
//////////////////////////////////////////////
//
// modifiers
//
//////////////////////////////////////////////
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Inserts an object of type T constructed with
//! std::forward<Args>(args)... in the beginning of the deque.
//!
//! <b>Returns</b>: A reference to the created object.
//!
//! <b>Throws</b>: If memory allocation throws or the in-place constructor throws.
//!
//! <b>Complexity</b>: Amortized constant time
template <class... Args>
reference emplace_front(BOOST_FWD_REF(Args)... args)
{
if(this->priv_push_front_simple_available()){
reference r = *this->priv_push_front_simple_pos();
allocator_traits_type::construct
( this->alloc()
, this->priv_push_front_simple_pos()
, boost::forward<Args>(args)...);
this->priv_push_front_simple_commit();
return r;
}
else{
typedef dtl::insert_nonmovable_emplace_proxy<ValAllocator, iterator, Args...> type;
return *this->priv_insert_front_aux_impl(1, type(boost::forward<Args>(args)...));
}
}
//! <b>Effects</b>: Inserts an object of type T constructed with
//! std::forward<Args>(args)... in the end of the deque.
//!
//! <b>Returns</b>: A reference to the created object.
//!
//! <b>Throws</b>: If memory allocation throws or the in-place constructor throws.
//!
//! <b>Complexity</b>: Amortized constant time
template <class... Args>
reference emplace_back(BOOST_FWD_REF(Args)... args)
{
if(this->priv_push_back_simple_available()){
reference r = *this->priv_push_back_simple_pos();
allocator_traits_type::construct
( this->alloc()
, this->priv_push_back_simple_pos()
, boost::forward<Args>(args)...);
this->priv_push_back_simple_commit();
return r;
}
else{
typedef dtl::insert_nonmovable_emplace_proxy<ValAllocator, iterator, Args...> type;
return *this->priv_insert_back_aux_impl(1, type(boost::forward<Args>(args)...));
}
}
//! <b>Requires</b>: p must be a valid iterator of *this.
//!
//! <b>Effects</b>: Inserts an object of type T constructed with
//! std::forward<Args>(args)... before p
//!
//! <b>Throws</b>: If memory allocation throws or the in-place constructor throws.
//!
//! <b>Complexity</b>: If p is end(), amortized constant time
//! Linear time otherwise.
template <class... Args>
iterator emplace(const_iterator p, BOOST_FWD_REF(Args)... args)
{
BOOST_ASSERT(this->priv_in_range_or_end(p));
if(p == this->cbegin()){
this->emplace_front(boost::forward<Args>(args)...);
return this->begin();
}
else if(p == this->cend()){
this->emplace_back(boost::forward<Args>(args)...);
return (this->end()-1);
}
else{
typedef dtl::insert_emplace_proxy<ValAllocator, iterator, Args...> type;
return this->priv_insert_aux_impl(p, 1, type(boost::forward<Args>(args)...));
}
}
#else //!defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#define BOOST_CONTAINER_DEQUE_EMPLACE_CODE(N) \
BOOST_MOVE_TMPL_LT##N BOOST_MOVE_CLASS##N BOOST_MOVE_GT##N\
reference emplace_front(BOOST_MOVE_UREF##N)\
{\
if(priv_push_front_simple_available()){\
reference r = *this->priv_push_front_simple_pos();\
allocator_traits_type::construct\
( this->alloc(), this->priv_push_front_simple_pos() BOOST_MOVE_I##N BOOST_MOVE_FWD##N);\
priv_push_front_simple_commit();\
return r;\
}\
else{\
typedef dtl::insert_nonmovable_emplace_proxy##N\
<ValAllocator, iterator BOOST_MOVE_I##N BOOST_MOVE_TARG##N> type;\
return *priv_insert_front_aux_impl(1, type(BOOST_MOVE_FWD##N));\
}\
}\
\
BOOST_MOVE_TMPL_LT##N BOOST_MOVE_CLASS##N BOOST_MOVE_GT##N\
reference emplace_back(BOOST_MOVE_UREF##N)\
{\
if(priv_push_back_simple_available()){\
reference r = *this->priv_push_back_simple_pos();\
allocator_traits_type::construct\
( this->alloc(), this->priv_push_back_simple_pos() BOOST_MOVE_I##N BOOST_MOVE_FWD##N);\
priv_push_back_simple_commit();\
return r;\
}\
else{\
typedef dtl::insert_nonmovable_emplace_proxy##N\
<ValAllocator, iterator BOOST_MOVE_I##N BOOST_MOVE_TARG##N> type;\
return *priv_insert_back_aux_impl(1, type(BOOST_MOVE_FWD##N));\
}\
}\
\
BOOST_MOVE_TMPL_LT##N BOOST_MOVE_CLASS##N BOOST_MOVE_GT##N\
iterator emplace(const_iterator p BOOST_MOVE_I##N BOOST_MOVE_UREF##N)\
{\
BOOST_ASSERT(this->priv_in_range_or_end(p));\
if(p == this->cbegin()){\
this->emplace_front(BOOST_MOVE_FWD##N);\
return this->begin();\
}\
else if(p == cend()){\
this->emplace_back(BOOST_MOVE_FWD##N);\
return (--this->end());\
}\
else{\
typedef dtl::insert_emplace_proxy_arg##N\
<ValAllocator, iterator BOOST_MOVE_I##N BOOST_MOVE_TARG##N> type;\
return this->priv_insert_aux_impl(p, 1, type(BOOST_MOVE_FWD##N));\
}\
}
//
BOOST_MOVE_ITERATE_0TO9(BOOST_CONTAINER_DEQUE_EMPLACE_CODE)
#undef BOOST_CONTAINER_DEQUE_EMPLACE_CODE
#endif // !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Inserts a copy of x at the front of the deque.
//!
//! <b>Throws</b>: If memory allocation throws or
//! T's copy constructor throws.
//!
//! <b>Complexity</b>: Amortized constant time.
void push_front(const T &x);
//! <b>Effects</b>: Constructs a new element in the front of the deque
//! and moves the resources of x to this new element.
//!
//! <b>Throws</b>: If memory allocation throws.
//!
//! <b>Complexity</b>: Amortized constant time.
void push_front(T &&x);
#else
BOOST_MOVE_CONVERSION_AWARE_CATCH(push_front, T, void, priv_push_front)
#endif
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Effects</b>: Inserts a copy of x at the end of the deque.
//!
//! <b>Throws</b>: If memory allocation throws or
//! T's copy constructor throws.
//!
//! <b>Complexity</b>: Amortized constant time.
void push_back(const T &x);
//! <b>Effects</b>: Constructs a new element in the end of the deque
//! and moves the resources of x to this new element.
//!
//! <b>Throws</b>: If memory allocation throws.
//!
//! <b>Complexity</b>: Amortized constant time.
void push_back(T &&x);
#else
BOOST_MOVE_CONVERSION_AWARE_CATCH(push_back, T, void, priv_push_back)
#endif
#if defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
//! <b>Requires</b>: p must be a valid iterator of *this.
//!
//! <b>Effects</b>: Insert a copy of x before p.
//!
//! <b>Returns</b>: an iterator to the inserted element.
//!
//! <b>Throws</b>: If memory allocation throws or x's copy constructor throws.
//!
//! <b>Complexity</b>: If p is end(), amortized constant time
//! Linear time otherwise.
iterator insert(const_iterator p, const T &x);
//! <b>Requires</b>: p must be a valid iterator of *this.
//!
//! <b>Effects</b>: Insert a new element before p with x's resources.
//!
//! <b>Returns</b>: an iterator to the inserted element.
//!
//! <b>Throws</b>: If memory allocation throws.
//!
//! <b>Complexity</b>: If p is end(), amortized constant time
//! Linear time otherwise.
iterator insert(const_iterator p, T &&x);
#else
BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, T, iterator, priv_insert, const_iterator, const_iterator)
#endif
//! <b>Requires</b>: pos must be a valid iterator of *this.
//!
//! <b>Effects</b>: Insert n copies of x before pos.
//!
//! <b>Returns</b>: an iterator to the first inserted element or pos if n is 0.
//!
//! <b>Throws</b>: If memory allocation throws or T's copy constructor throws.
//!
//! <b>Complexity</b>: Linear to n.
BOOST_CONTAINER_FORCEINLINE iterator insert(const_iterator pos, size_type n, const value_type& x)
{
//Range check of p is done by insert()
typedef constant_iterator<value_type, difference_type> c_it;
return this->insert(pos, c_it(x, n), c_it());
}
//! <b>Requires</b>: pos must be a valid iterator of *this.
//!
//! <b>Effects</b>: Insert a copy of the [first, last) range before pos.
//!
//! <b>Returns</b>: an iterator to the first inserted element or pos if first == last.
//!
//! <b>Throws</b>: If memory allocation throws, T's constructor from a
//! dereferenced InIt throws or T's copy constructor throws.
//!
//! <b>Complexity</b>: Linear to distance [first, last).
template <class InIt>
iterator insert(const_iterator pos, InIt first, InIt last
#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
, typename dtl::disable_if_or
< void
, dtl::is_convertible<InIt, size_type>
, dtl::is_not_input_iterator<InIt>
>::type * = 0
#endif
)
{
BOOST_ASSERT(this->priv_in_range_or_end(pos));
size_type n = 0;
iterator it(pos.unconst());
for(;first != last; ++first, ++n){
it = this->emplace(it, *first);
++it;
}
it -= n;
return it;
}
#if !defined(BOOST_NO_CXX11_HDR_INITIALIZER_LIST)
//! <b>Requires</b>: pos must be a valid iterator of *this.
//!
//! <b>Effects</b>: Insert a copy of the [il.begin(), il.end()) range before pos.
//!
//! <b>Returns</b>: an iterator to the first inserted element or pos if il.begin() == il.end().
//!
//! <b>Throws</b>: If memory allocation throws, T's constructor from a
//! dereferenced std::initializer_list throws or T's copy constructor throws.
//!
//! <b>Complexity</b>: Linear to distance [il.begin(), il.end()).
BOOST_CONTAINER_FORCEINLINE iterator insert(const_iterator pos, std::initializer_list<value_type> il)
{
//Range check os pos is done in insert()
return insert(pos, il.begin(), il.end());
}
#endif
#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
template <class FwdIt>
BOOST_CONTAINER_FORCEINLINE iterator insert(const_iterator p, FwdIt first, FwdIt last
#if !defined(BOOST_CONTAINER_DOXYGEN_INVOKED)
, typename dtl::disable_if_or
< void
, dtl::is_convertible<FwdIt, size_type>
, dtl::is_input_iterator<FwdIt>
>::type * = 0
#endif
)
{
BOOST_ASSERT(this->priv_in_range_or_end(p));
dtl::insert_range_proxy<ValAllocator, FwdIt, iterator> proxy(first);
return priv_insert_aux_impl(p, boost::container::iterator_distance(first, last), proxy);
}
#endif
//! <b>Effects</b>: Removes the first element from the deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant time.
void pop_front() BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(!this->empty());
if (this->members_.m_start.m_cur != this->members_.m_start.m_last - 1) {
allocator_traits_type::destroy
( this->alloc()
, boost::movelib::to_raw_pointer(this->members_.m_start.m_cur)
);
++this->members_.m_start.m_cur;
}
else
this->priv_pop_front_aux();
}
//! <b>Effects</b>: Removes the last element from the deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant time.
void pop_back() BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(!this->empty());
if (this->members_.m_finish.m_cur != this->members_.m_finish.m_first) {
--this->members_.m_finish.m_cur;
allocator_traits_type::destroy
( this->alloc()
, boost::movelib::to_raw_pointer(this->members_.m_finish.m_cur)
);
}
else
this->priv_pop_back_aux();
}
//! <b>Effects</b>: Erases the element at p.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Linear to the elements between pos and the
//! last element (if pos is near the end) or the first element
//! if(pos is near the beginning).
//! Constant if pos is the first or the last element.
iterator erase(const_iterator pos) BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(this->priv_in_range(pos));
iterator next = pos.unconst();
++next;
size_type index = pos - this->members_.m_start;
if (index < (this->size()/2)) {
boost::container::move_backward(this->begin(), pos.unconst(), next);
pop_front();
}
else {
boost::container::move(next, this->end(), pos.unconst());
pop_back();
}
return this->members_.m_start + index;
}
//! <b>Effects</b>: Erases the elements pointed by [first, last).
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Linear to the distance between first and
//! last plus the elements between pos and the
//! last element (if pos is near the end) or the first element
//! if(pos is near the beginning).
iterator erase(const_iterator first, const_iterator last) BOOST_NOEXCEPT_OR_NOTHROW
{
BOOST_ASSERT(first == last ||
(first < last && this->priv_in_range(first) && this->priv_in_range_or_end(last)));
if (first == this->members_.m_start && last == this->members_.m_finish) {
this->clear();
return this->members_.m_finish;
}
else {
const size_type n = static_cast<size_type>(last - first);
const size_type elems_before = static_cast<size_type>(first - this->members_.m_start);
if (elems_before < (this->size() - n) - elems_before) {
boost::container::move_backward(begin(), first.unconst(), last.unconst());
iterator new_start = this->members_.m_start + n;
this->priv_destroy_range(this->members_.m_start, new_start);
this->priv_destroy_nodes(this->members_.m_start.m_node, new_start.m_node);
this->members_.m_start = new_start;
}
else {
boost::container::move(last.unconst(), end(), first.unconst());
iterator new_finish = this->members_.m_finish - n;
this->priv_destroy_range(new_finish, this->members_.m_finish);
this->priv_destroy_nodes(new_finish.m_node + 1, this->members_.m_finish.m_node + 1);
this->members_.m_finish = new_finish;
}
return this->members_.m_start + elems_before;
}
}
//! <b>Effects</b>: Swaps the contents of *this and x.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE void swap(deque &x)
BOOST_NOEXCEPT_IF(allocator_traits_type::propagate_on_container_swap::value
|| allocator_traits_type::is_always_equal::value)
{
this->swap_members(x);
dtl::bool_<allocator_traits_type::propagate_on_container_swap::value> flag;
dtl::swap_alloc(this->alloc(), x.alloc(), flag);
dtl::swap_alloc(this->ptr_alloc(), x.ptr_alloc(), flag);
}
//! <b>Effects</b>: Erases all the elements of the deque.
//!
//! <b>Throws</b>: Nothing.
//!
//! <b>Complexity</b>: Linear to the number of elements in the deque.
void clear() BOOST_NOEXCEPT_OR_NOTHROW
{
for (index_pointer node = this->members_.m_start.m_node + 1;
node < this->members_.m_finish.m_node;
++node) {
this->priv_destroy_range(*node, *node + this->s_buffer_size());
this->priv_deallocate_node(*node);
}
if (this->members_.m_start.m_node != this->members_.m_finish.m_node) {
this->priv_destroy_range(this->members_.m_start.m_cur, this->members_.m_start.m_last);
this->priv_destroy_range(this->members_.m_finish.m_first, this->members_.m_finish.m_cur);
this->priv_deallocate_node(this->members_.m_finish.m_first);
}
else
this->priv_destroy_range(this->members_.m_start.m_cur, this->members_.m_finish.m_cur);
this->members_.m_finish = this->members_.m_start;
}
//! <b>Effects</b>: Returns true if x and y are equal
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
BOOST_CONTAINER_FORCEINLINE friend bool operator==(const deque& x, const deque& y)
{ return x.size() == y.size() && ::boost::container::algo_equal(x.begin(), x.end(), y.begin()); }
//! <b>Effects</b>: Returns true if x and y are unequal
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
BOOST_CONTAINER_FORCEINLINE friend bool operator!=(const deque& x, const deque& y)
{ return !(x == y); }
//! <b>Effects</b>: Returns true if x is less than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
BOOST_CONTAINER_FORCEINLINE friend bool operator<(const deque& x, const deque& y)
{ return ::boost::container::algo_lexicographical_compare(x.begin(), x.end(), y.begin(), y.end()); }
//! <b>Effects</b>: Returns true if x is greater than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
BOOST_CONTAINER_FORCEINLINE friend bool operator>(const deque& x, const deque& y)
{ return y < x; }
//! <b>Effects</b>: Returns true if x is equal or less than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
BOOST_CONTAINER_FORCEINLINE friend bool operator<=(const deque& x, const deque& y)
{ return !(y < x); }
//! <b>Effects</b>: Returns true if x is equal or greater than y
//!
//! <b>Complexity</b>: Linear to the number of elements in the container.
BOOST_CONTAINER_FORCEINLINE friend bool operator>=(const deque& x, const deque& y)
{ return !(x < y); }
//! <b>Effects</b>: x.swap(y)
//!
//! <b>Complexity</b>: Constant.
BOOST_CONTAINER_FORCEINLINE friend void swap(deque& x, deque& y)
{ x.swap(y); }
#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
private:
BOOST_CONTAINER_FORCEINLINE size_type priv_index_of(const_iterator p) const
{
BOOST_ASSERT(this->cbegin() <= p);
BOOST_ASSERT(p <= this->cend());
return static_cast<size_type>(p - this->cbegin());
}
void priv_erase_last_n(size_type n)
{
if(n == this->size()) {
this->clear();
}
else {
iterator new_finish = this->members_.m_finish - n;
this->priv_destroy_range(new_finish, this->members_.m_finish);
this->priv_destroy_nodes(new_finish.m_node + 1, this->members_.m_finish.m_node + 1);
this->members_.m_finish = new_finish;
}
}
void priv_throw_if_out_of_range(size_type n) const
{
if (n >= this->size())
throw_out_of_range("deque::at out of range");
}
BOOST_CONTAINER_FORCEINLINE bool priv_in_range(const_iterator pos) const
{
return (this->begin() <= pos) && (pos < this->end());
}
BOOST_CONTAINER_FORCEINLINE bool priv_in_range_or_end(const_iterator pos) const
{
return (this->begin() <= pos) && (pos <= this->end());
}
template <class U>
iterator priv_insert(const_iterator p, BOOST_FWD_REF(U) x)
{
BOOST_ASSERT(this->priv_in_range_or_end(p));
if (p == cbegin()){
this->push_front(::boost::forward<U>(x));
return begin();
}
else if (p == cend()){
this->push_back(::boost::forward<U>(x));
return --end();
}
else {
return priv_insert_aux_impl
( p, (size_type)1
, dtl::get_insert_value_proxy<iterator, ValAllocator>(::boost::forward<U>(x)));
}
}
template <class U>
void priv_push_front(BOOST_FWD_REF(U) x)
{
if(this->priv_push_front_simple_available()){
allocator_traits_type::construct
( this->alloc(), this->priv_push_front_simple_pos(), ::boost::forward<U>(x));
this->priv_push_front_simple_commit();
}
else{
priv_insert_aux_impl
( this->cbegin(), (size_type)1
, dtl::get_insert_value_proxy<iterator, ValAllocator>(::boost::forward<U>(x)));
}
}
template <class U>
void priv_push_back(BOOST_FWD_REF(U) x)
{
if(this->priv_push_back_simple_available()){
allocator_traits_type::construct
( this->alloc(), this->priv_push_back_simple_pos(), ::boost::forward<U>(x));
this->priv_push_back_simple_commit();
}
else{
priv_insert_aux_impl
( this->cend(), (size_type)1
, dtl::get_insert_value_proxy<iterator, ValAllocator>(::boost::forward<U>(x)));
}
}
BOOST_CONTAINER_FORCEINLINE bool priv_push_back_simple_available() const
{
return this->members_.m_map &&
(this->members_.m_finish.m_cur != (this->members_.m_finish.m_last - 1));
}
BOOST_CONTAINER_FORCEINLINE T *priv_push_back_simple_pos() const
{
return boost::movelib::to_raw_pointer(this->members_.m_finish.m_cur);
}
BOOST_CONTAINER_FORCEINLINE void priv_push_back_simple_commit()
{
++this->members_.m_finish.m_cur;
}
BOOST_CONTAINER_FORCEINLINE bool priv_push_front_simple_available() const
{
return this->members_.m_map &&
(this->members_.m_start.m_cur != this->members_.m_start.m_first);
}
BOOST_CONTAINER_FORCEINLINE T *priv_push_front_simple_pos() const
{ return boost::movelib::to_raw_pointer(this->members_.m_start.m_cur) - 1; }
BOOST_CONTAINER_FORCEINLINE void priv_push_front_simple_commit()
{ --this->members_.m_start.m_cur; }
void priv_destroy_range(iterator p, iterator p2)
{
if(!Base::traits_t::trivial_dctr){
for(;p != p2; ++p){
allocator_traits_type::destroy(this->alloc(), boost::movelib::iterator_to_raw_pointer(p));
}
}
}
void priv_destroy_range(pointer p, pointer p2)
{
if(!Base::traits_t::trivial_dctr){
for(;p != p2; ++p){
allocator_traits_type::destroy(this->alloc(), boost::movelib::iterator_to_raw_pointer(p));
}
}
}
template<class InsertProxy>
iterator priv_insert_aux_impl(const_iterator p, size_type n, InsertProxy proxy)
{
iterator pos(p.unconst());
const size_type pos_n = p - this->cbegin();
if(!this->members_.m_map){
this->priv_initialize_map(0);
pos = this->begin();
}
const size_type elemsbefore = static_cast<size_type>(pos - this->members_.m_start);
const size_type length = this->size();
if (elemsbefore < length / 2) {
const iterator new_start = this->priv_reserve_elements_at_front(n);
const iterator old_start = this->members_.m_start;
if(!elemsbefore){
proxy.uninitialized_copy_n_and_update(this->alloc(), new_start, n);
this->members_.m_start = new_start;
}
else{
pos = this->members_.m_start + elemsbefore;
if (elemsbefore >= n) {
const iterator start_n = this->members_.m_start + n;
::boost::container::uninitialized_move_alloc
(this->alloc(), this->members_.m_start, start_n, new_start);
this->members_.m_start = new_start;
boost::container::move(start_n, pos, old_start);
proxy.copy_n_and_update(this->alloc(), pos - n, n);
}
else {
const size_type mid_count = n - elemsbefore;
const iterator mid_start = old_start - mid_count;
proxy.uninitialized_copy_n_and_update(this->alloc(), mid_start, mid_count);
this->members_.m_start = mid_start;
::boost::container::uninitialized_move_alloc
(this->alloc(), old_start, pos, new_start);
this->members_.m_start = new_start;
proxy.copy_n_and_update(this->alloc(), old_start, elemsbefore);
}
}
}
else {
const iterator new_finish = this->priv_reserve_elements_at_back(n);
const iterator old_finish = this->members_.m_finish;
const size_type elemsafter = length - elemsbefore;
if(!elemsafter){
proxy.uninitialized_copy_n_and_update(this->alloc(), old_finish, n);
this->members_.m_finish = new_finish;
}
else{
pos = old_finish - elemsafter;
if (elemsafter >= n) {
iterator finish_n = old_finish - difference_type(n);
::boost::container::uninitialized_move_alloc
(this->alloc(), finish_n, old_finish, old_finish);
this->members_.m_finish = new_finish;
boost::container::move_backward(pos, finish_n, old_finish);
proxy.copy_n_and_update(this->alloc(), pos, n);
}
else {
const size_type raw_gap = n - elemsafter;
::boost::container::uninitialized_move_alloc
(this->alloc(), pos, old_finish, old_finish + raw_gap);
BOOST_TRY{
proxy.copy_n_and_update(this->alloc(), pos, elemsafter);
proxy.uninitialized_copy_n_and_update(this->alloc(), old_finish, raw_gap);
}
BOOST_CATCH(...){
this->priv_destroy_range(old_finish, old_finish + elemsafter);
BOOST_RETHROW
}
BOOST_CATCH_END
this->members_.m_finish = new_finish;
}
}
}
return this->begin() + pos_n;
}
template <class InsertProxy>
iterator priv_insert_back_aux_impl(size_type n, InsertProxy proxy)
{
if(!this->members_.m_map){
this->priv_initialize_map(0);
}
iterator new_finish = this->priv_reserve_elements_at_back(n);
iterator old_finish = this->members_.m_finish;
proxy.uninitialized_copy_n_and_update(this->alloc(), old_finish, n);
this->members_.m_finish = new_finish;
return iterator(this->members_.m_finish - n);
}
template <class InsertProxy>
iterator priv_insert_front_aux_impl(size_type n, InsertProxy proxy)
{
if(!this->members_.m_map){
this->priv_initialize_map(0);
}
iterator new_start = this->priv_reserve_elements_at_front(n);
proxy.uninitialized_copy_n_and_update(this->alloc(), new_start, n);
this->members_.m_start = new_start;
return new_start;
}
BOOST_CONTAINER_FORCEINLINE iterator priv_fill_insert(const_iterator pos, size_type n, const value_type& x)
{
typedef constant_iterator<value_type, difference_type> c_it;
return this->insert(pos, c_it(x, n), c_it());
}
// Precondition: this->members_.m_start and this->members_.m_finish have already been initialized,
// but none of the deque's elements have yet been constructed.
void priv_fill_initialize(const value_type& value)
{
index_pointer cur = this->members_.m_start.m_node;
BOOST_TRY {
for ( ; cur < this->members_.m_finish.m_node; ++cur){
boost::container::uninitialized_fill_alloc
(this->alloc(), *cur, *cur + this->s_buffer_size(), value);
}
boost::container::uninitialized_fill_alloc
(this->alloc(), this->members_.m_finish.m_first, this->members_.m_finish.m_cur, value);
}
BOOST_CATCH(...){
this->priv_destroy_range(this->members_.m_start, iterator(*cur, cur));
BOOST_RETHROW
}
BOOST_CATCH_END
}
template <class InIt>
void priv_range_initialize(InIt first, InIt last, typename iterator_enable_if_tag<InIt, std::input_iterator_tag>::type* =0)
{
this->priv_initialize_map(0);
BOOST_TRY {
for ( ; first != last; ++first)
this->emplace_back(*first);
}
BOOST_CATCH(...){
this->clear();
BOOST_RETHROW
}
BOOST_CATCH_END
}
template <class FwdIt>
void priv_range_initialize(FwdIt first, FwdIt last, typename iterator_disable_if_tag<FwdIt, std::input_iterator_tag>::type* =0)
{
size_type n = 0;
n = boost::container::iterator_distance(first, last);
this->priv_initialize_map(n);
index_pointer cur_node = this->members_.m_start.m_node;
BOOST_TRY {
for (; cur_node < this->members_.m_finish.m_node; ++cur_node) {
FwdIt mid = first;
boost::container::iterator_advance(mid, this->s_buffer_size());
::boost::container::uninitialized_copy_alloc(this->alloc(), first, mid, *cur_node);
first = mid;
}
::boost::container::uninitialized_copy_alloc(this->alloc(), first, last, this->members_.m_finish.m_first);
}
BOOST_CATCH(...){
this->priv_destroy_range(this->members_.m_start, iterator(*cur_node, cur_node));
BOOST_RETHROW
}
BOOST_CATCH_END
}
// Called only if this->members_.m_finish.m_cur == this->members_.m_finish.m_first.
void priv_pop_back_aux() BOOST_NOEXCEPT_OR_NOTHROW
{
this->priv_deallocate_node(this->members_.m_finish.m_first);
this->members_.m_finish.priv_set_node(this->members_.m_finish.m_node - 1);
this->members_.m_finish.m_cur = this->members_.m_finish.m_last - 1;
allocator_traits_type::destroy
( this->alloc()
, boost::movelib::to_raw_pointer(this->members_.m_finish.m_cur)
);
}
// Called only if this->members_.m_start.m_cur == this->members_.m_start.m_last - 1. Note that
// if the deque has at least one element (a precondition for this member
// function), and if this->members_.m_start.m_cur == this->members_.m_start.m_last, then the deque
// must have at least two nodes.
void priv_pop_front_aux() BOOST_NOEXCEPT_OR_NOTHROW
{
allocator_traits_type::destroy
( this->alloc()
, boost::movelib::to_raw_pointer(this->members_.m_start.m_cur)
);
this->priv_deallocate_node(this->members_.m_start.m_first);
this->members_.m_start.priv_set_node(this->members_.m_start.m_node + 1);
this->members_.m_start.m_cur = this->members_.m_start.m_first;
}
iterator priv_reserve_elements_at_front(size_type n)
{
size_type vacancies = this->members_.m_start.m_cur - this->members_.m_start.m_first;
if (n > vacancies){
size_type new_elems = n-vacancies;
size_type new_nodes = (new_elems + this->s_buffer_size() - 1) /
this->s_buffer_size();
size_type s = (size_type)(this->members_.m_start.m_node - this->members_.m_map);
if (new_nodes > s){
this->priv_reallocate_map(new_nodes, true);
}
size_type i = 1;
BOOST_TRY {
for (; i <= new_nodes; ++i)
*(this->members_.m_start.m_node - i) = this->priv_allocate_node();
}
BOOST_CATCH(...) {
for (size_type j = 1; j < i; ++j)
this->priv_deallocate_node(*(this->members_.m_start.m_node - j));
BOOST_RETHROW
}
BOOST_CATCH_END
}
return this->members_.m_start - difference_type(n);
}
iterator priv_reserve_elements_at_back(size_type n)
{
size_type vacancies = (this->members_.m_finish.m_last - this->members_.m_finish.m_cur) - 1;
if (n > vacancies){
size_type new_elems = n - vacancies;
size_type new_nodes = (new_elems + this->s_buffer_size() - 1)/s_buffer_size();
size_type s = (size_type)(this->members_.m_map_size - (this->members_.m_finish.m_node - this->members_.m_map));
if (new_nodes + 1 > s){
this->priv_reallocate_map(new_nodes, false);
}
size_type i = 1;
BOOST_TRY {
for (; i <= new_nodes; ++i)
*(this->members_.m_finish.m_node + i) = this->priv_allocate_node();
}
BOOST_CATCH(...) {
for (size_type j = 1; j < i; ++j)
this->priv_deallocate_node(*(this->members_.m_finish.m_node + j));
BOOST_RETHROW
}
BOOST_CATCH_END
}
return this->members_.m_finish + difference_type(n);
}
void priv_reallocate_map(size_type nodes_to_add, bool add_at_front)
{
size_type old_num_nodes = this->members_.m_finish.m_node - this->members_.m_start.m_node + 1;
size_type new_num_nodes = old_num_nodes + nodes_to_add;
index_pointer new_nstart;
if (this->members_.m_map_size > 2 * new_num_nodes) {
new_nstart = this->members_.m_map + (this->members_.m_map_size - new_num_nodes) / 2
+ (add_at_front ? nodes_to_add : 0);
if (new_nstart < this->members_.m_start.m_node)
boost::container::move(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1, new_nstart);
else
boost::container::move_backward
(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1, new_nstart + old_num_nodes);
}
else {
size_type new_map_size =
this->members_.m_map_size + dtl::max_value(this->members_.m_map_size, nodes_to_add) + 2;
index_pointer new_map = this->priv_allocate_map(new_map_size);
new_nstart = new_map + (new_map_size - new_num_nodes) / 2
+ (add_at_front ? nodes_to_add : 0);
boost::container::move(this->members_.m_start.m_node, this->members_.m_finish.m_node + 1, new_nstart);
this->priv_deallocate_map(this->members_.m_map, this->members_.m_map_size);
this->members_.m_map = new_map;
this->members_.m_map_size = new_map_size;
}
this->members_.m_start.priv_set_node(new_nstart);
this->members_.m_finish.priv_set_node(new_nstart + old_num_nodes - 1);
}
#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
};
#ifndef BOOST_CONTAINER_NO_CXX17_CTAD
template <typename InputIterator>
deque(InputIterator, InputIterator) -> deque<typename iterator_traits<InputIterator>::value_type>;
template <typename InputIterator, typename Allocator>
deque(InputIterator, InputIterator, Allocator const&) -> deque<typename iterator_traits<InputIterator>::value_type, Allocator>;
#endif
}}
#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
namespace boost {
//!has_trivial_destructor_after_move<> == true_type
//!specialization for optimizations
template <class T, class Allocator>
struct has_trivial_destructor_after_move<boost::container::deque<T, Allocator> >
{
typedef typename ::boost::container::allocator_traits<Allocator>::pointer pointer;
static const bool value = ::boost::has_trivial_destructor_after_move<Allocator>::value &&
::boost::has_trivial_destructor_after_move<pointer>::value;
};
}
#endif //#ifndef BOOST_CONTAINER_DOXYGEN_INVOKED
#include <boost/container/detail/config_end.hpp>
#endif // #ifndef BOOST_CONTAINER_DEQUE_HPP
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdlib.h>
#include <openssl/obj_mac.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include "internal/refcount.h"
#include "crypto/ec.h"
#if defined(__SUNPRO_C)
# if __SUNPRO_C >= 0x520
# pragma error_messages (off,E_ARRAY_OF_INCOMPLETE_NONAME,E_ARRAY_OF_INCOMPLETE)
# endif
#endif
/* Use default functions for poin2oct, oct2point and compressed coordinates */
#define EC_FLAGS_DEFAULT_OCT 0x1
/* Use custom formats for EC_GROUP, EC_POINT and EC_KEY */
#define EC_FLAGS_CUSTOM_CURVE 0x2
/* Curve does not support signing operations */
#define EC_FLAGS_NO_SIGN 0x4
/*
* Structure details are not part of the exported interface, so all this may
* change in future versions.
*/
struct ec_method_st {
/* Various method flags */
int flags;
/* used by EC_METHOD_get_field_type: */
int field_type; /* a NID */
/*
* used by EC_GROUP_new, EC_GROUP_free, EC_GROUP_clear_free,
* EC_GROUP_copy:
*/
int (*group_init) (EC_GROUP *);
void (*group_finish) (EC_GROUP *);
void (*group_clear_finish) (EC_GROUP *);
int (*group_copy) (EC_GROUP *, const EC_GROUP *);
/* used by EC_GROUP_set_curve, EC_GROUP_get_curve: */
int (*group_set_curve) (EC_GROUP *, const BIGNUM *p, const BIGNUM *a,
const BIGNUM *b, BN_CTX *);
int (*group_get_curve) (const EC_GROUP *, BIGNUM *p, BIGNUM *a, BIGNUM *b,
BN_CTX *);
/* used by EC_GROUP_get_degree: */
int (*group_get_degree) (const EC_GROUP *);
int (*group_order_bits) (const EC_GROUP *);
/* used by EC_GROUP_check: */
int (*group_check_discriminant) (const EC_GROUP *, BN_CTX *);
/*
* used by EC_POINT_new, EC_POINT_free, EC_POINT_clear_free,
* EC_POINT_copy:
*/
int (*point_init) (EC_POINT *);
void (*point_finish) (EC_POINT *);
void (*point_clear_finish) (EC_POINT *);
int (*point_copy) (EC_POINT *, const EC_POINT *);
/*-
* used by EC_POINT_set_to_infinity,
* EC_POINT_set_Jprojective_coordinates_GFp,
* EC_POINT_get_Jprojective_coordinates_GFp,
* EC_POINT_set_affine_coordinates,
* EC_POINT_get_affine_coordinates,
* EC_POINT_set_compressed_coordinates:
*/
int (*point_set_to_infinity) (const EC_GROUP *, EC_POINT *);
int (*point_set_Jprojective_coordinates_GFp) (const EC_GROUP *,
EC_POINT *, const BIGNUM *x,
const BIGNUM *y,
const BIGNUM *z, BN_CTX *);
int (*point_get_Jprojective_coordinates_GFp) (const EC_GROUP *,
const EC_POINT *, BIGNUM *x,
BIGNUM *y, BIGNUM *z,
BN_CTX *);
int (*point_set_affine_coordinates) (const EC_GROUP *, EC_POINT *,
const BIGNUM *x, const BIGNUM *y,
BN_CTX *);
int (*point_get_affine_coordinates) (const EC_GROUP *, const EC_POINT *,
BIGNUM *x, BIGNUM *y, BN_CTX *);
int (*point_set_compressed_coordinates) (const EC_GROUP *, EC_POINT *,
const BIGNUM *x, int y_bit,
BN_CTX *);
/* used by EC_POINT_point2oct, EC_POINT_oct2point: */
size_t (*point2oct) (const EC_GROUP *, const EC_POINT *,
point_conversion_form_t form, unsigned char *buf,
size_t len, BN_CTX *);
int (*oct2point) (const EC_GROUP *, EC_POINT *, const unsigned char *buf,
size_t len, BN_CTX *);
/* used by EC_POINT_add, EC_POINT_dbl, ECP_POINT_invert: */
int (*add) (const EC_GROUP *, EC_POINT *r, const EC_POINT *a,
const EC_POINT *b, BN_CTX *);
int (*dbl) (const EC_GROUP *, EC_POINT *r, const EC_POINT *a, BN_CTX *);
int (*invert) (const EC_GROUP *, EC_POINT *, BN_CTX *);
/*
* used by EC_POINT_is_at_infinity, EC_POINT_is_on_curve, EC_POINT_cmp:
*/
int (*is_at_infinity) (const EC_GROUP *, const EC_POINT *);
int (*is_on_curve) (const EC_GROUP *, const EC_POINT *, BN_CTX *);
int (*point_cmp) (const EC_GROUP *, const EC_POINT *a, const EC_POINT *b,
BN_CTX *);
/* used by EC_POINT_make_affine, EC_POINTs_make_affine: */
int (*make_affine) (const EC_GROUP *, EC_POINT *, BN_CTX *);
int (*points_make_affine) (const EC_GROUP *, size_t num, EC_POINT *[],
BN_CTX *);
/*
* used by EC_POINTs_mul, EC_POINT_mul, EC_POINT_precompute_mult,
* EC_POINT_have_precompute_mult (default implementations are used if the
* 'mul' pointer is 0):
*/
/*-
* mul() calculates the value
*
* r := generator * scalar
* + points[0] * scalars[0]
* + ...
* + points[num-1] * scalars[num-1].
*
* For a fixed point multiplication (scalar != NULL, num == 0)
* or a variable point multiplication (scalar == NULL, num == 1),
* mul() must use a constant time algorithm: in both cases callers
* should provide an input scalar (either scalar or scalars[0])
* in the range [0, ec_group_order); for robustness, implementers
* should handle the case when the scalar has not been reduced, but
* may treat it as an unusual input, without any constant-timeness
* guarantee.
*/
int (*mul) (const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
size_t num, const EC_POINT *points[], const BIGNUM *scalars[],
BN_CTX *);
int (*precompute_mult) (EC_GROUP *group, BN_CTX *);
int (*have_precompute_mult) (const EC_GROUP *group);
/* internal functions */
/*
* 'field_mul', 'field_sqr', and 'field_div' can be used by 'add' and
* 'dbl' so that the same implementations of point operations can be used
* with different optimized implementations of expensive field
* operations:
*/
int (*field_mul) (const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
const BIGNUM *b, BN_CTX *);
int (*field_sqr) (const EC_GROUP *, BIGNUM *r, const BIGNUM *a, BN_CTX *);
int (*field_div) (const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
const BIGNUM *b, BN_CTX *);
/*-
* 'field_inv' computes the multiplicative inverse of a in the field,
* storing the result in r.
*
* If 'a' is zero (or equivalent), you'll get an EC_R_CANNOT_INVERT error.
*/
int (*field_inv) (const EC_GROUP *, BIGNUM *r, const BIGNUM *a, BN_CTX *);
/* e.g. to Montgomery */
int (*field_encode) (const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
BN_CTX *);
/* e.g. from Montgomery */
int (*field_decode) (const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
BN_CTX *);
int (*field_set_to_one) (const EC_GROUP *, BIGNUM *r, BN_CTX *);
/* private key operations */
size_t (*priv2oct)(const EC_KEY *eckey, unsigned char *buf, size_t len);
int (*oct2priv)(EC_KEY *eckey, const unsigned char *buf, size_t len);
int (*set_private)(EC_KEY *eckey, const BIGNUM *priv_key);
int (*keygen)(EC_KEY *eckey);
int (*keycheck)(const EC_KEY *eckey);
int (*keygenpub)(EC_KEY *eckey);
int (*keycopy)(EC_KEY *dst, const EC_KEY *src);
void (*keyfinish)(EC_KEY *eckey);
/* custom ECDH operation */
int (*ecdh_compute_key)(unsigned char **pout, size_t *poutlen,
const EC_POINT *pub_key, const EC_KEY *ecdh);
/* Inverse modulo order */
int (*field_inverse_mod_ord)(const EC_GROUP *, BIGNUM *r,
const BIGNUM *x, BN_CTX *);
int (*blind_coordinates)(const EC_GROUP *group, EC_POINT *p, BN_CTX *ctx);
int (*ladder_pre)(const EC_GROUP *group,
EC_POINT *r, EC_POINT *s,
EC_POINT *p, BN_CTX *ctx);
int (*ladder_step)(const EC_GROUP *group,
EC_POINT *r, EC_POINT *s,
EC_POINT *p, BN_CTX *ctx);
int (*ladder_post)(const EC_GROUP *group,
EC_POINT *r, EC_POINT *s,
EC_POINT *p, BN_CTX *ctx);
};
/*
* Types and functions to manipulate pre-computed values.
*/
typedef struct nistp224_pre_comp_st NISTP224_PRE_COMP;
typedef struct nistp256_pre_comp_st NISTP256_PRE_COMP;
typedef struct nistp521_pre_comp_st NISTP521_PRE_COMP;
typedef struct nistz256_pre_comp_st NISTZ256_PRE_COMP;
typedef struct ec_pre_comp_st EC_PRE_COMP;
struct ec_group_st {
const EC_METHOD *meth;
EC_POINT *generator; /* optional */
BIGNUM *order, *cofactor;
int curve_name; /* optional NID for named curve */
int asn1_flag; /* flag to control the asn1 encoding */
int decoded_from_explicit_params; /* set if decoded from explicit
* curve parameters encoding */
point_conversion_form_t asn1_form;
unsigned char *seed; /* optional seed for parameters (appears in
* ASN1) */
size_t seed_len;
/*
* The following members are handled by the method functions, even if
* they appear generic
*/
/*
* Field specification. For curves over GF(p), this is the modulus; for
* curves over GF(2^m), this is the irreducible polynomial defining the
* field.
*/
BIGNUM *field;
/*
* Field specification for curves over GF(2^m). The irreducible f(t) is
* then of the form: t^poly[0] + t^poly[1] + ... + t^poly[k] where m =
* poly[0] > poly[1] > ... > poly[k] = 0. The array is terminated with
* poly[k+1]=-1. All elliptic curve irreducibles have at most 5 non-zero
* terms.
*/
int poly[6];
/*
* Curve coefficients. (Here the assumption is that BIGNUMs can be used
* or abused for all kinds of fields, not just GF(p).) For characteristic
* > 3, the curve is defined by a Weierstrass equation of the form y^2 =
* x^3 + a*x + b. For characteristic 2, the curve is defined by an
* equation of the form y^2 + x*y = x^3 + a*x^2 + b.
*/
BIGNUM *a, *b;
/* enable optimized point arithmetics for special case */
int a_is_minus3;
/* method-specific (e.g., Montgomery structure) */
void *field_data1;
/* method-specific */
void *field_data2;
/* method-specific */
int (*field_mod_func) (BIGNUM *, const BIGNUM *, const BIGNUM *,
BN_CTX *);
/* data for ECDSA inverse */
BN_MONT_CTX *mont_data;
/*
* Precomputed values for speed. The PCT_xxx names match the
* pre_comp.xxx union names; see the SETPRECOMP and HAVEPRECOMP
* macros, below.
*/
enum {
PCT_none,
PCT_nistp224, PCT_nistp256, PCT_nistp521, PCT_nistz256,
PCT_ec
} pre_comp_type;
union {
NISTP224_PRE_COMP *nistp224;
NISTP256_PRE_COMP *nistp256;
NISTP521_PRE_COMP *nistp521;
NISTZ256_PRE_COMP *nistz256;
EC_PRE_COMP *ec;
} pre_comp;
};
#define SETPRECOMP(g, type, pre) \
g->pre_comp_type = PCT_##type, g->pre_comp.type = pre
#define HAVEPRECOMP(g, type) \
g->pre_comp_type == PCT_##type && g->pre_comp.type != NULL
struct ec_key_st {
const EC_KEY_METHOD *meth;
ENGINE *engine;
int version;
EC_GROUP *group;
EC_POINT *pub_key;
BIGNUM *priv_key;
unsigned int enc_flag;
point_conversion_form_t conv_form;
CRYPTO_REF_COUNT references;
int flags;
CRYPTO_EX_DATA ex_data;
CRYPTO_RWLOCK *lock;
};
struct ec_point_st {
const EC_METHOD *meth;
/* NID for the curve if known */
int curve_name;
/*
* All members except 'meth' are handled by the method functions, even if
* they appear generic
*/
BIGNUM *X;
BIGNUM *Y;
BIGNUM *Z; /* Jacobian projective coordinates: * (X, Y,
* Z) represents (X/Z^2, Y/Z^3) if Z != 0 */
int Z_is_one; /* enable optimized point arithmetics for
* special case */
};
static ossl_inline int ec_point_is_compat(const EC_POINT *point,
const EC_GROUP *group)
{
if (group->meth != point->meth
|| (group->curve_name != 0
&& point->curve_name != 0
&& group->curve_name != point->curve_name))
return 0;
return 1;
}
NISTP224_PRE_COMP *EC_nistp224_pre_comp_dup(NISTP224_PRE_COMP *);
NISTP256_PRE_COMP *EC_nistp256_pre_comp_dup(NISTP256_PRE_COMP *);
NISTP521_PRE_COMP *EC_nistp521_pre_comp_dup(NISTP521_PRE_COMP *);
NISTZ256_PRE_COMP *EC_nistz256_pre_comp_dup(NISTZ256_PRE_COMP *);
NISTP256_PRE_COMP *EC_nistp256_pre_comp_dup(NISTP256_PRE_COMP *);
EC_PRE_COMP *EC_ec_pre_comp_dup(EC_PRE_COMP *);
void EC_pre_comp_free(EC_GROUP *group);
void EC_nistp224_pre_comp_free(NISTP224_PRE_COMP *);
void EC_nistp256_pre_comp_free(NISTP256_PRE_COMP *);
void EC_nistp521_pre_comp_free(NISTP521_PRE_COMP *);
void EC_nistz256_pre_comp_free(NISTZ256_PRE_COMP *);
void EC_ec_pre_comp_free(EC_PRE_COMP *);
/*
* method functions in ec_mult.c (ec_lib.c uses these as defaults if
* group->method->mul is 0)
*/
int ec_wNAF_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *scalar,
size_t num, const EC_POINT *points[], const BIGNUM *scalars[],
BN_CTX *);
int ec_wNAF_precompute_mult(EC_GROUP *group, BN_CTX *);
int ec_wNAF_have_precompute_mult(const EC_GROUP *group);
/* method functions in ecp_smpl.c */
int ec_GFp_simple_group_init(EC_GROUP *);
void ec_GFp_simple_group_finish(EC_GROUP *);
void ec_GFp_simple_group_clear_finish(EC_GROUP *);
int ec_GFp_simple_group_copy(EC_GROUP *, const EC_GROUP *);
int ec_GFp_simple_group_set_curve(EC_GROUP *, const BIGNUM *p,
const BIGNUM *a, const BIGNUM *b, BN_CTX *);
int ec_GFp_simple_group_get_curve(const EC_GROUP *, BIGNUM *p, BIGNUM *a,
BIGNUM *b, BN_CTX *);
int ec_GFp_simple_group_get_degree(const EC_GROUP *);
int ec_GFp_simple_group_check_discriminant(const EC_GROUP *, BN_CTX *);
int ec_GFp_simple_point_init(EC_POINT *);
void ec_GFp_simple_point_finish(EC_POINT *);
void ec_GFp_simple_point_clear_finish(EC_POINT *);
int ec_GFp_simple_point_copy(EC_POINT *, const EC_POINT *);
int ec_GFp_simple_point_set_to_infinity(const EC_GROUP *, EC_POINT *);
int ec_GFp_simple_set_Jprojective_coordinates_GFp(const EC_GROUP *,
EC_POINT *, const BIGNUM *x,
const BIGNUM *y,
const BIGNUM *z, BN_CTX *);
int ec_GFp_simple_get_Jprojective_coordinates_GFp(const EC_GROUP *,
const EC_POINT *, BIGNUM *x,
BIGNUM *y, BIGNUM *z,
BN_CTX *);
int ec_GFp_simple_point_set_affine_coordinates(const EC_GROUP *, EC_POINT *,
const BIGNUM *x,
const BIGNUM *y, BN_CTX *);
int ec_GFp_simple_point_get_affine_coordinates(const EC_GROUP *,
const EC_POINT *, BIGNUM *x,
BIGNUM *y, BN_CTX *);
int ec_GFp_simple_set_compressed_coordinates(const EC_GROUP *, EC_POINT *,
const BIGNUM *x, int y_bit,
BN_CTX *);
size_t ec_GFp_simple_point2oct(const EC_GROUP *, const EC_POINT *,
point_conversion_form_t form,
unsigned char *buf, size_t len, BN_CTX *);
int ec_GFp_simple_oct2point(const EC_GROUP *, EC_POINT *,
const unsigned char *buf, size_t len, BN_CTX *);
int ec_GFp_simple_add(const EC_GROUP *, EC_POINT *r, const EC_POINT *a,
const EC_POINT *b, BN_CTX *);
int ec_GFp_simple_dbl(const EC_GROUP *, EC_POINT *r, const EC_POINT *a,
BN_CTX *);
int ec_GFp_simple_invert(const EC_GROUP *, EC_POINT *, BN_CTX *);
int ec_GFp_simple_is_at_infinity(const EC_GROUP *, const EC_POINT *);
int ec_GFp_simple_is_on_curve(const EC_GROUP *, const EC_POINT *, BN_CTX *);
int ec_GFp_simple_cmp(const EC_GROUP *, const EC_POINT *a, const EC_POINT *b,
BN_CTX *);
int ec_GFp_simple_make_affine(const EC_GROUP *, EC_POINT *, BN_CTX *);
int ec_GFp_simple_points_make_affine(const EC_GROUP *, size_t num,
EC_POINT *[], BN_CTX *);
int ec_GFp_simple_field_mul(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
const BIGNUM *b, BN_CTX *);
int ec_GFp_simple_field_sqr(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
BN_CTX *);
int ec_GFp_simple_field_inv(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
BN_CTX *);
int ec_GFp_simple_blind_coordinates(const EC_GROUP *group, EC_POINT *p,
BN_CTX *ctx);
int ec_GFp_simple_ladder_pre(const EC_GROUP *group,
EC_POINT *r, EC_POINT *s,
EC_POINT *p, BN_CTX *ctx);
int ec_GFp_simple_ladder_step(const EC_GROUP *group,
EC_POINT *r, EC_POINT *s,
EC_POINT *p, BN_CTX *ctx);
int ec_GFp_simple_ladder_post(const EC_GROUP *group,
EC_POINT *r, EC_POINT *s,
EC_POINT *p, BN_CTX *ctx);
/* method functions in ecp_mont.c */
int ec_GFp_mont_group_init(EC_GROUP *);
int ec_GFp_mont_group_set_curve(EC_GROUP *, const BIGNUM *p, const BIGNUM *a,
const BIGNUM *b, BN_CTX *);
void ec_GFp_mont_group_finish(EC_GROUP *);
void ec_GFp_mont_group_clear_finish(EC_GROUP *);
int ec_GFp_mont_group_copy(EC_GROUP *, const EC_GROUP *);
int ec_GFp_mont_field_mul(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
const BIGNUM *b, BN_CTX *);
int ec_GFp_mont_field_sqr(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
BN_CTX *);
int ec_GFp_mont_field_inv(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
BN_CTX *);
int ec_GFp_mont_field_encode(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
BN_CTX *);
int ec_GFp_mont_field_decode(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
BN_CTX *);
int ec_GFp_mont_field_set_to_one(const EC_GROUP *, BIGNUM *r, BN_CTX *);
/* method functions in ecp_nist.c */
int ec_GFp_nist_group_copy(EC_GROUP *dest, const EC_GROUP *src);
int ec_GFp_nist_group_set_curve(EC_GROUP *, const BIGNUM *p, const BIGNUM *a,
const BIGNUM *b, BN_CTX *);
int ec_GFp_nist_field_mul(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
const BIGNUM *b, BN_CTX *);
int ec_GFp_nist_field_sqr(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
BN_CTX *);
/* method functions in ec2_smpl.c */
int ec_GF2m_simple_group_init(EC_GROUP *);
void ec_GF2m_simple_group_finish(EC_GROUP *);
void ec_GF2m_simple_group_clear_finish(EC_GROUP *);
int ec_GF2m_simple_group_copy(EC_GROUP *, const EC_GROUP *);
int ec_GF2m_simple_group_set_curve(EC_GROUP *, const BIGNUM *p,
const BIGNUM *a, const BIGNUM *b,
BN_CTX *);
int ec_GF2m_simple_group_get_curve(const EC_GROUP *, BIGNUM *p, BIGNUM *a,
BIGNUM *b, BN_CTX *);
int ec_GF2m_simple_group_get_degree(const EC_GROUP *);
int ec_GF2m_simple_group_check_discriminant(const EC_GROUP *, BN_CTX *);
int ec_GF2m_simple_point_init(EC_POINT *);
void ec_GF2m_simple_point_finish(EC_POINT *);
void ec_GF2m_simple_point_clear_finish(EC_POINT *);
int ec_GF2m_simple_point_copy(EC_POINT *, const EC_POINT *);
int ec_GF2m_simple_point_set_to_infinity(const EC_GROUP *, EC_POINT *);
int ec_GF2m_simple_point_set_affine_coordinates(const EC_GROUP *, EC_POINT *,
const BIGNUM *x,
const BIGNUM *y, BN_CTX *);
int ec_GF2m_simple_point_get_affine_coordinates(const EC_GROUP *,
const EC_POINT *, BIGNUM *x,
BIGNUM *y, BN_CTX *);
int ec_GF2m_simple_set_compressed_coordinates(const EC_GROUP *, EC_POINT *,
const BIGNUM *x, int y_bit,
BN_CTX *);
size_t ec_GF2m_simple_point2oct(const EC_GROUP *, const EC_POINT *,
point_conversion_form_t form,
unsigned char *buf, size_t len, BN_CTX *);
int ec_GF2m_simple_oct2point(const EC_GROUP *, EC_POINT *,
const unsigned char *buf, size_t len, BN_CTX *);
int ec_GF2m_simple_add(const EC_GROUP *, EC_POINT *r, const EC_POINT *a,
const EC_POINT *b, BN_CTX *);
int ec_GF2m_simple_dbl(const EC_GROUP *, EC_POINT *r, const EC_POINT *a,
BN_CTX *);
int ec_GF2m_simple_invert(const EC_GROUP *, EC_POINT *, BN_CTX *);
int ec_GF2m_simple_is_at_infinity(const EC_GROUP *, const EC_POINT *);
int ec_GF2m_simple_is_on_curve(const EC_GROUP *, const EC_POINT *, BN_CTX *);
int ec_GF2m_simple_cmp(const EC_GROUP *, const EC_POINT *a, const EC_POINT *b,
BN_CTX *);
int ec_GF2m_simple_make_affine(const EC_GROUP *, EC_POINT *, BN_CTX *);
int ec_GF2m_simple_points_make_affine(const EC_GROUP *, size_t num,
EC_POINT *[], BN_CTX *);
int ec_GF2m_simple_field_mul(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
const BIGNUM *b, BN_CTX *);
int ec_GF2m_simple_field_sqr(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
BN_CTX *);
int ec_GF2m_simple_field_div(const EC_GROUP *, BIGNUM *r, const BIGNUM *a,
const BIGNUM *b, BN_CTX *);
#ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
/* method functions in ecp_nistp224.c */
int ec_GFp_nistp224_group_init(EC_GROUP *group);
int ec_GFp_nistp224_group_set_curve(EC_GROUP *group, const BIGNUM *p,
const BIGNUM *a, const BIGNUM *n,
BN_CTX *);
int ec_GFp_nistp224_point_get_affine_coordinates(const EC_GROUP *group,
const EC_POINT *point,
BIGNUM *x, BIGNUM *y,
BN_CTX *ctx);
int ec_GFp_nistp224_mul(const EC_GROUP *group, EC_POINT *r,
const BIGNUM *scalar, size_t num,
const EC_POINT *points[], const BIGNUM *scalars[],
BN_CTX *);
int ec_GFp_nistp224_points_mul(const EC_GROUP *group, EC_POINT *r,
const BIGNUM *scalar, size_t num,
const EC_POINT *points[],
const BIGNUM *scalars[], BN_CTX *ctx);
int ec_GFp_nistp224_precompute_mult(EC_GROUP *group, BN_CTX *ctx);
int ec_GFp_nistp224_have_precompute_mult(const EC_GROUP *group);
/* method functions in ecp_nistp256.c */
int ec_GFp_nistp256_group_init(EC_GROUP *group);
int ec_GFp_nistp256_group_set_curve(EC_GROUP *group, const BIGNUM *p,
const BIGNUM *a, const BIGNUM *n,
BN_CTX *);
int ec_GFp_nistp256_point_get_affine_coordinates(const EC_GROUP *group,
const EC_POINT *point,
BIGNUM *x, BIGNUM *y,
BN_CTX *ctx);
int ec_GFp_nistp256_mul(const EC_GROUP *group, EC_POINT *r,
const BIGNUM *scalar, size_t num,
const EC_POINT *points[], const BIGNUM *scalars[],
BN_CTX *);
int ec_GFp_nistp256_points_mul(const EC_GROUP *group, EC_POINT *r,
const BIGNUM *scalar, size_t num,
const EC_POINT *points[],
const BIGNUM *scalars[], BN_CTX *ctx);
int ec_GFp_nistp256_precompute_mult(EC_GROUP *group, BN_CTX *ctx);
int ec_GFp_nistp256_have_precompute_mult(const EC_GROUP *group);
/* method functions in ecp_nistp521.c */
int ec_GFp_nistp521_group_init(EC_GROUP *group);
int ec_GFp_nistp521_group_set_curve(EC_GROUP *group, const BIGNUM *p,
const BIGNUM *a, const BIGNUM *n,
BN_CTX *);
int ec_GFp_nistp521_point_get_affine_coordinates(const EC_GROUP *group,
const EC_POINT *point,
BIGNUM *x, BIGNUM *y,
BN_CTX *ctx);
int ec_GFp_nistp521_mul(const EC_GROUP *group, EC_POINT *r,
const BIGNUM *scalar, size_t num,
const EC_POINT *points[], const BIGNUM *scalars[],
BN_CTX *);
int ec_GFp_nistp521_points_mul(const EC_GROUP *group, EC_POINT *r,
const BIGNUM *scalar, size_t num,
const EC_POINT *points[],
const BIGNUM *scalars[], BN_CTX *ctx);
int ec_GFp_nistp521_precompute_mult(EC_GROUP *group, BN_CTX *ctx);
int ec_GFp_nistp521_have_precompute_mult(const EC_GROUP *group);
/* utility functions in ecp_nistputil.c */
void ec_GFp_nistp_points_make_affine_internal(size_t num, void *point_array,
size_t felem_size,
void *tmp_felems,
void (*felem_one) (void *out),
int (*felem_is_zero) (const void
*in),
void (*felem_assign) (void *out,
const void
*in),
void (*felem_square) (void *out,
const void
*in),
void (*felem_mul) (void *out,
const void
*in1,
const void
*in2),
void (*felem_inv) (void *out,
const void
*in),
void (*felem_contract) (void
*out,
const
void
*in));
void ec_GFp_nistp_recode_scalar_bits(unsigned char *sign,
unsigned char *digit, unsigned char in);
#endif
int ec_group_simple_order_bits(const EC_GROUP *group);
#ifdef ECP_NISTZ256_ASM
/** Returns GFp methods using montgomery multiplication, with x86-64 optimized
* P256. See http://eprint.iacr.org/2013/816.
* \return EC_METHOD object
*/
const EC_METHOD *EC_GFp_nistz256_method(void);
#endif
size_t ec_key_simple_priv2oct(const EC_KEY *eckey,
unsigned char *buf, size_t len);
int ec_key_simple_oct2priv(EC_KEY *eckey, const unsigned char *buf, size_t len);
int ec_key_simple_generate_key(EC_KEY *eckey);
int ec_key_simple_generate_public_key(EC_KEY *eckey);
int ec_key_simple_check_key(const EC_KEY *eckey);
int ec_curve_nid_from_params(const EC_GROUP *group, BN_CTX *ctx);
/* EC_METHOD definitions */
struct ec_key_method_st {
const char *name;
int32_t flags;
int (*init)(EC_KEY *key);
void (*finish)(EC_KEY *key);
int (*copy)(EC_KEY *dest, const EC_KEY *src);
int (*set_group)(EC_KEY *key, const EC_GROUP *grp);
int (*set_private)(EC_KEY *key, const BIGNUM *priv_key);
int (*set_public)(EC_KEY *key, const EC_POINT *pub_key);
int (*keygen)(EC_KEY *key);
int (*compute_key)(unsigned char **pout, size_t *poutlen,
const EC_POINT *pub_key, const EC_KEY *ecdh);
int (*sign)(int type, const unsigned char *dgst, int dlen, unsigned char
*sig, unsigned int *siglen, const BIGNUM *kinv,
const BIGNUM *r, EC_KEY *eckey);
int (*sign_setup)(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp);
ECDSA_SIG *(*sign_sig)(const unsigned char *dgst, int dgst_len,
const BIGNUM *in_kinv, const BIGNUM *in_r,
EC_KEY *eckey);
int (*verify)(int type, const unsigned char *dgst, int dgst_len,
const unsigned char *sigbuf, int sig_len, EC_KEY *eckey);
int (*verify_sig)(const unsigned char *dgst, int dgst_len,
const ECDSA_SIG *sig, EC_KEY *eckey);
};
#define EC_KEY_METHOD_DYNAMIC 1
int ossl_ec_key_gen(EC_KEY *eckey);
int ossl_ecdh_compute_key(unsigned char **pout, size_t *poutlen,
const EC_POINT *pub_key, const EC_KEY *ecdh);
int ecdh_simple_compute_key(unsigned char **pout, size_t *poutlen,
const EC_POINT *pub_key, const EC_KEY *ecdh);
struct ECDSA_SIG_st {
BIGNUM *r;
BIGNUM *s;
};
int ossl_ecdsa_sign_setup(EC_KEY *eckey, BN_CTX *ctx_in, BIGNUM **kinvp,
BIGNUM **rp);
int ossl_ecdsa_sign(int type, const unsigned char *dgst, int dlen,
unsigned char *sig, unsigned int *siglen,
const BIGNUM *kinv, const BIGNUM *r, EC_KEY *eckey);
ECDSA_SIG *ossl_ecdsa_sign_sig(const unsigned char *dgst, int dgst_len,
const BIGNUM *in_kinv, const BIGNUM *in_r,
EC_KEY *eckey);
int ossl_ecdsa_verify(int type, const unsigned char *dgst, int dgst_len,
const unsigned char *sigbuf, int sig_len, EC_KEY *eckey);
int ossl_ecdsa_verify_sig(const unsigned char *dgst, int dgst_len,
const ECDSA_SIG *sig, EC_KEY *eckey);
int ED25519_sign(uint8_t *out_sig, const uint8_t *message, size_t message_len,
const uint8_t public_key[32], const uint8_t private_key[32]);
int ED25519_verify(const uint8_t *message, size_t message_len,
const uint8_t signature[64], const uint8_t public_key[32]);
void ED25519_public_from_private(uint8_t out_public_key[32],
const uint8_t private_key[32]);
int X25519(uint8_t out_shared_key[32], const uint8_t private_key[32],
const uint8_t peer_public_value[32]);
void X25519_public_from_private(uint8_t out_public_value[32],
const uint8_t private_key[32]);
/*-
* This functions computes a single point multiplication over the EC group,
* using, at a high level, a Montgomery ladder with conditional swaps, with
* various timing attack defenses.
*
* It performs either a fixed point multiplication
* (scalar * generator)
* when point is NULL, or a variable point multiplication
* (scalar * point)
* when point is not NULL.
*
* `scalar` cannot be NULL and should be in the range [0,n) otherwise all
* constant time bets are off (where n is the cardinality of the EC group).
*
* This function expects `group->order` and `group->cardinality` to be well
* defined and non-zero: it fails with an error code otherwise.
*
* NB: This says nothing about the constant-timeness of the ladder step
* implementation (i.e., the default implementation is based on EC_POINT_add and
* EC_POINT_dbl, which of course are not constant time themselves) or the
* underlying multiprecision arithmetic.
*
* The product is stored in `r`.
*
* This is an internal function: callers are in charge of ensuring that the
* input parameters `group`, `r`, `scalar` and `ctx` are not NULL.
*
* Returns 1 on success, 0 otherwise.
*/
int ec_scalar_mul_ladder(const EC_GROUP *group, EC_POINT *r,
const BIGNUM *scalar, const EC_POINT *point,
BN_CTX *ctx);
int ec_point_blind_coordinates(const EC_GROUP *group, EC_POINT *p, BN_CTX *ctx);
static ossl_inline int ec_point_ladder_pre(const EC_GROUP *group,
EC_POINT *r, EC_POINT *s,
EC_POINT *p, BN_CTX *ctx)
{
if (group->meth->ladder_pre != NULL)
return group->meth->ladder_pre(group, r, s, p, ctx);
if (!EC_POINT_copy(s, p)
|| !EC_POINT_dbl(group, r, s, ctx))
return 0;
return 1;
}
static ossl_inline int ec_point_ladder_step(const EC_GROUP *group,
EC_POINT *r, EC_POINT *s,
EC_POINT *p, BN_CTX *ctx)
{
if (group->meth->ladder_step != NULL)
return group->meth->ladder_step(group, r, s, p, ctx);
if (!EC_POINT_add(group, s, r, s, ctx)
|| !EC_POINT_dbl(group, r, r, ctx))
return 0;
return 1;
}
static ossl_inline int ec_point_ladder_post(const EC_GROUP *group,
EC_POINT *r, EC_POINT *s,
EC_POINT *p, BN_CTX *ctx)
{
if (group->meth->ladder_post != NULL)
return group->meth->ladder_post(group, r, s, p, ctx);
return 1;
}
| {
"pile_set_name": "Github"
} |
/*
Copyright 2009-2020, Sumeet Chhetri
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.
*/
/*
* JobScheduler.cpp
*
* Created on: 15-Jul-2013
* Author: sumeetc
*/
#include "JobScheduler.h"
JobScheduler* JobScheduler::instance = NULL;
JobScheduler::JobScheduler() {
isStarted = false;
}
JobScheduler::~JobScheduler() {
}
void JobScheduler::init(const std::string& fileName, const std::string& appName) {
SimpleXmlParser parser("Parser");
Document doc;
parser.readDocument(fileName, doc);
const Element& root = doc.getRootElement();
if(root.getTagName()=="job-procs" && root.getChildElements().size()>0)
{
init(root.getChildElements(), appName);
}
}
void JobScheduler::init(const ElementList& tabs, const std::string& appName) {
if(instance!=NULL)
return;
Logger logger = LoggerFactory::getLogger("JOB", "JobScheduler");
instance = new JobScheduler();
logger << "Initialized JobScheduler" << std::endl;
for (unsigned int dn = 0; dn < tabs.size(); dn++)
{
if(tabs.at(dn).getTagName()!="job-proc")
{
logger << "Invalid Element Tag found inside job-procs, should be job-proc..." << std::endl;
continue;
}
std::string clas = tabs.at(dn).getAttribute("class");
std::string cron = tabs.at(dn).getAttribute("cron");
std::string meth = tabs.at(dn).getAttribute("method");
std::string name = tabs.at(dn).getAttribute("name");
if(clas!="" && meth!="" && cron!="" && name!="")
{
JobConfig config;
config.name = name;
config.cron = cron;
config.clas = clas;
config.meth = meth;
config.app = appName;
instance->configs.push_back(config);
logger << "Added JobConfig inside JobScheduler" << std::endl;
}
else
{
logger << "Cannot add Job Process as some mandatory elements are missing from the configuration" << std::endl;
}
}
}
void JobScheduler::start() {
Reflector* ref = GenericObject::getReflector();
if(instance==NULL || (instance!=NULL && instance->isStarted))
return;
Logger logger = LoggerFactory::getLogger("JOB", "JobScheduler");
instance->isStarted = true;
for (int dn = 0; dn < (int)instance->configs.size(); dn++)
{
std::string clas = instance->configs.at(dn).clas;
std::string cron = instance->configs.at(dn).cron;
std::string method = instance->configs.at(dn).meth;
std::string name = instance->configs.at(dn).name;
std::string appName = instance->configs.at(dn).app;
if(clas!="" && method!="" && cron!="" && name!="")
{
StringUtil::replaceAll(appName, "-", "_");
RegexUtil::replace(appName, "[^a-zA-Z0-9_]+", "");
CommonUtils::setAppName(appName);
ClassInfo* claz = ref->getClassInfo(clas, appName);
logger << "JobScheduler - Got class " + claz->getClassName() << std::endl;
if(claz->getClassName()!="")
{
args argus;
Method meth = claz->getMethod(method, argus);
Constructor ctor = claz->getConstructor(argus);
logger << "JobScheduler - Got method,class " + meth.getMethodName() + "," + ctor.getName() << std::endl;
if(meth.getMethodName()!="" && ctor.getName()!="")
{
void* objIns = ref->newInstanceGVP(ctor);
JobFunction f = (JobFunction)ref->getMethodInstance(meth);
logger << "JobScheduler - Got objins,func " << objIns << "," << f << std::endl;
if(objIns!=NULL && f!=NULL)
{
JobTask* task = new JobTask;
task->objIns = objIns;
task->cron = cron;
task->clas = clas;
task->name = name;
task->meth = meth;
task->appName = appName;
task->doRun = true;
Thread* pthread = new Thread(&JobScheduler::service, task);
pthread->execute();
instance->tasks.push_back(task);
logger << "Added Job Process successfully" << std::endl;
}
else
{
logger << "Cannot add Job Process as could not initialize class instance and method" << std::endl;
}
}
else
{
logger << "Cannot add Job Process as method was not found or public no argument constructor not defined for class" << std::endl;
}
}
else
{
logger << "Cannot add Job Process as class information was not found" << std::endl;
}
}
else
{
logger << "Cannot add Job Process as some mandatory elements are missing from the configuration" << std::endl;
}
}
}
void JobScheduler::stop() {
if(instance==NULL)
{
return;
}
for (int var = 0; var < (int)instance->tasks.size(); ++var) {
instance->tasks.at(var)->doRun = false;
}
Logger logger = LoggerFactory::getLogger("JOB", "JobScheduler");
logger << "Waiting 10 seconds for all Job Processes to shutdown....";
sleep(10);
delete instance;
}
void* JobScheduler::service(void* arg)
{
JobTask *task = static_cast<JobTask*>(arg);
CommonUtils::setAppName(task->appName);
task->run();
delete task;
return NULL;
}
void JobScheduler::JobTask::run() {
Logger logger = LoggerFactory::getLogger("JOB", "JobTask");
try {
CronTimer timer(cron);
vals values;
timer.nextRunDate = Date();
Reflector* ref = GenericObject::getReflector();
JobFunction f = (JobFunction)ref->getMethodInstance(meth);
while(doRun)
{
sleep(1);
Date d2;
if(timer.isValid(5, d2.getYear(), timer.nextRunDate.getYear()))
{
if(timer.isValid(3, d2.getMonth(), timer.nextRunDate.getMonth()))
{
if(timer.isValid(2, d2.getDay(), timer.nextRunDate.getDay()))
{
if(timer.isValid(1, d2.getHours(), timer.nextRunDate.getHours()))
{
if(timer.isValid(0, d2.getMinutes(), timer.nextRunDate.getMinutes()))
{
logger << "Running Job Process " + name << std::endl;
f(objIns, values);
bool incrementDone = false;
incrementDone = timer.tryIncrement(0, timer.nextRunDate.getMinutes());
if(!incrementDone) {
incrementDone = timer.tryIncrement(1, timer.nextRunDate.getHours());
}
if(!incrementDone) {
incrementDone = timer.tryIncrement(2, timer.nextRunDate.getDay());
}
if(!incrementDone) {
incrementDone = timer.tryIncrement(3, timer.nextRunDate.getMonth());
}
if(!incrementDone) {
incrementDone = timer.tryIncrement(5, timer.nextRunDate.getYear());
}
logger << "Running Job Process " + name + " complete" << std::endl;
}
}
}
}
}
}
if(objIns!=NULL) {
ref->destroy(objIns, clas, appName);
objIns = NULL;
}
} catch(const std::exception& ex) {
logger << "Cannot run Job as the cron std::string is invalid" << std::endl;
}
}
int JobScheduler::JobTask::getTid() {
return -1;
}
void JobScheduler::JobTask::setTid(int tid) {
}
| {
"pile_set_name": "Github"
} |
# Plugin Support
!!! info "Plugin Support"
:construction: Plugin support is the main theme of [VersionPress 4.0](https://github.com/versionpress/versionpress/milestone/16) which is currently in [beta](https://github.com/versionpress/versionpress/releases/tag/4.0-beta). Plugin developers, we'd like your feedback on this, feel free to [open new issues](https://github.com/versionpress/versionpress/issues/new) or chat with us [on Gitter](https://gitter.im/versionpress/versionpress).
VersionPress needs to understand plugin data, actions, shortcodes and other things to automatically provide version control for them. This document describes how plugins (and themes, later) can hook into VersionPress functionality.
## Introduction
Plugins are described to VersionPress by a set of files stored in the `.versionpress` folder in the plugin root (with other discovery options available, see below). They include:
- `actions.yml` – plugin actions, i.e., what the plugin does
- `schema.yml` – database schema (how the plugin stores data)
- `shortcodes.yml` – shortcodes
- `hooks.php` – other hooks
All files are optional so for example, if a plugin doesn't define any new shortcodes it can omit the `shortcodes.yml` file. Simple plugins like _Hello Dolly_ might even omit everything.
!!! tip
WordPress core is described using the very same format and you can find the definition files in the [`.versionpress`](../../../../plugins/versionpress/.versionpress) folder inside the plugin.
## Actions
Actions represent what the plugin does. For example, WordPress core has actions like "update option", "publish post" and many others. They are the smallest changes in a WordPress site and are eventually stored as Git commits by VersionPress.
An action is identified by a string like `option/edit` or `post/publish`, commits some file(s) with it and has a human-readable message like "Updated option blogname", "Published post Hello World", etc.
Some commits may even contain multiple actions. For example, if a user switches to a new theme that also creates some options of its own, a single commit with `theme/switch` and several `option/create` actions will be created. When this operation is undone, it takes back both the theme switching and options creation.
Actions are described in the `actions.yml` file.
### `actions.yml`
Here's an example from the [WordPress core `actions.yml` file](../../../../plugins/versionpress/.versionpress/actions.yml):
```yaml
post:
tags:
VP-Post-Title: post_title
VP-Post-Type: post_type
actions:
create: Created %VP-Post-Type% '%VP-Post-Title%'
edit:
message: Edited %VP-Post-Type% '%VP-Post-Title%'
priority: 12
postmeta:
tags:
VP-Post-Id: vp_post_id
VP-Post-Title: /
parent-id-tag: VP-Post-Id
actions:
...
theme:
tags:
VP-Theme-Name: /
actions:
install: Installed theme '%VP-Theme-Name%'
update: Updated theme '%VP-Theme-Name%'
```
These are the main elements:
- The top-level elements are **scopes** that basically group related actions together. For example, actions related to posts are in the `post` scope, theme actions are in the `theme` scope, etc. Scopes use a singular form.
- **Tags** are values saved in commit messages and are typically used to make user-facing messages more useful. For example, it's better to display _Created post 'Hello World'_ than _Created post 123_ and tags make this possible.
- Tags are either mapped to database fields as in the `post` example, or use the `/` character to indicate that the value is provided by a filter (see below).
- **The `actions` section** defines all actions of a scope.
- An action has a **message** that can reference tags to make it more user-friendly. Messages use past tense.
- Each action has a **priority** – 10 by default. Priorities behave like on WordPress filters and actions: the lower the number, the higher the priority. A more important action beats the less important one if both appear in the same commit. For example, `theme/switch` beats `option/edit` which means that the user will see a message about changing themes, not updating some internal option.
- Priorities can be set dynamically using the `vp_action_priority_{$scope}` filter, see [WPLANG handling](https://github.com/versionpress/versionpress/blob/7a500248a363472127c93a2ffffaec11f486e6e5/plugins/versionpress/.versionpress/hooks.php#L160-L166) as an example.
- A combination of a scope and an action, e.g., `post/create` or `theme/install`, uniquely identifies the action and can be [searched for in the UI](https://docs.versionpress.net/en/feature-focus/searching-history).
- An action has a **message**, usually in past tense, and a **priority**. If priority is not set, the default value of 10 is used.
- Priorities behave like on WordPress filters and actions: the lower the number, the higher the priority. A more important action beats the less important one if both appear in the same commit. For example, `theme/switch` beats `option/edit` which means that the user will see a message about changing themes, not updating some internal option.
- **Meta entities** also contain **`parent-id-tag`** with the name of a tag containing ID of the parent entity.
### Action detection
There are generally two types of actions:
- **Database actions** like manipulating posts, options, users, etc.
- **Non-database actions** like updating WordPress, deleting themes, etc.
**Database actions** are more common (at least in WordPress core) and get a pretty convenient treatment by default. Based on the SQL query issued, a `create`, `edit` or `delete` action is created automatically.
If you need more specific actions like `post/trash` or `comment/approve`, filters are used: [`vp_entity_action_{$entityName}`](https://github.com/versionpress/versionpress/blob/0a29069de769841ed545556cecf4d2323a92741b/plugins/versionpress/src/Storages/DirectoryStorage.php#L225-L225) for standard entities and [`vp_meta_entity_action_{$entityName}`](https://github.com/versionpress/versionpress/blob/49fdc0ba737b40560c40129d791e0cf63b1031e0/plugins/versionpress/src/Storages/MetaEntityStorage.php#L166-L16) for meta entities.
> 🚧 Hooks are not properly documented yet, please click through the hook names to at least browse the source codes on GitHub.
Tags are automatically extracted from the database entity. For example,
```yaml
tags:
VP-Post-Title: post_title
```
makes sure that the message (defined as `Created post '%VP-Post-Title%'`) automatically stores the real post title.
Tags can be altered (or created entirely if the YAML only uses `/` as a tag value) by filters [`vp_entity_tags_{$entityName}`](https://github.com/versionpress/versionpress/blob/0a29069de769841ed545556cecf4d2323a92741b/plugins/versionpress/src/Storages/DirectoryStorage.php#L226-L226) and [`vp_meta_entity_tags_{$entityName}`](https://github.com/versionpress/versionpress/blob/49fdc0ba737b40560c40129d791e0cf63b1031e0/plugins/versionpress/src/Storages/MetaEntityStorage.php#L167-L16).
**Non-database actions** are tracked manually by calling a global [`vp_force_action()`](https://github.com/versionpress/versionpress/blob/3b0b242b11804d39c838b15a21ffbd7a27b404b4/plugins/versionpress/public-functions.php#L18-L18) function. This overwrites all other actions VersionPress might have collected during the request. For example, this is how `wordpress/update` action is tracked:
```php
vp_force_action('wordpress', 'update', $version, [], $wpFiles);
```
> :construction: We're planning to change this for the final VersionPress 4.0 release. Some filter will probably be used instead.
### Files to commit with an action
Every action has a message and some content. It's this content that is undone when the user clicks the Undo button in the UI.
For **database actions**, VersionPress automatically commits the corresponding INI file. For example, for a `post/edit` action, a post's INI file is committed.
> Side note: VersionPress stores database entities in the `wp-content/vpdb` folder as a set of INI files.
This behavior is sufficient most of the time, however, some changes should commit more files. For example, when the post is an attachment, the uploaded file should also be committed. For this, the list of files to commit can be filtered using the `vp_entity_files_{$entityName}` or `vp_meta_entity_files_{$entityName}` filters.
The array of files to commit can contain three different types of items:
!!! note
Concepts like VPIDs are explained in the "[Database schema](#database-schema)" section below.
1. Single file corresponding to an entity, for example:
```php
[
'type' => 'storage-file',
'entity' => 'post',
'id' => $vpid,
'parent-id' => $parentVpid // for meta entities
]
```
VersionPress automatically calculates the right path to the file.
2. All files of an entity type:
```php
[
'type' => 'all-storage-files',
'entity' => 'option'
]
```
3. Path on the filesystem:
```php
[
'type' => 'path',
'path' => 'some/path/supports/wildcards/*'
]
```
The full example might look something like this:
```php
[
['type' => 'storage-file', 'entity' => 'post', 'id' => $vpid, 'parent-id' => null],
['type' => 'storage-file', 'entity' => 'usermeta', 'id' => $vpid, 'parent-id' => $userVpid],
['type' => 'all-storage-files', 'entity' => 'option'],
['type' => 'path', 'path' => '/var/www/wp/example.txt'],
['type' => 'path', 'path' => '/var/www/wp/folder/*']
]
```
For **non-database actions**, this list is one of the arguments of the [`vp_force_action()`](https://github.com/versionpress/versionpress/blob/3b0b242b11804d39c838b15a21ffbd7a27b404b4/plugins/versionpress/public-functions.php#L18-L18) function.
> As noted above, we'll be getting rid of this approach so this is temporary info.
## Database schema
If the plugin adds custom data into the database it must provide a `schema.yml` file describing the database model. For example, this is how WordPress posts are described:
```yaml
post:
table: posts
id: ID
references:
post_author: user
post_parent: post
mn-references:
term_relationships.term_taxonomy_id: term_taxonomy
ignored-entities:
- 'post_type: revision'
- 'post_status: auto-draft'
ignored-columns:
- comment_count: '@vp_fix_comments_count'
clean-cache:
- post: id
```
### Defining entities
The top-level keys define entities such as `post`, `comment`, `option` or `postmeta`. Entity names use a singular form.
By default, entity names match database table names without the `wp_` (or custom) prefix. It is possible to specify a different table using the `table` property:
```yaml
post:
table: posts
...
```
Again, this is prefix-less; `wp_` or another prefix will be added automatically.
### Identifying entities
VersionPress needs to know how to identify entities. There are two approaches and they are represented by either using a `id` or `vpid` property in the schema:
- **`id`** points to a standard WordPress auto-increment primary key. **VersionPress will generate VPIDs** (globally unique IDs) for such entities. Most entities are of this type – posts, comments, users etc.
- **`vpid`** points VersionPress directly to use the given column as a unique identifier and skip the whole VPID generation and maintenance process. Entities of this type **will not have artificial VPIDs**. The `options` table is an example of this – even though it has an `option_id` auto-increment primary key, from VersionPress' point of view the unique identifier is `option_name`.
Examples:
```yaml
post:
table: posts
id: ID
option:
table: options
vpid: option_name
```
### References
VersionPress needs to understand relationships between entities so that it can update their IDs between environments. There are several types of references, each using a slightly different notation in the schema file.
#### Basic references
The most basic references are "foreign keys". For example:
```yaml
post:
references:
post_author: user
post_parent: post
```
This says that the `post_author` field points to a user while the `post_parent` references another post.
#### Value references
Value references are used when a reference to an entity depends on another column value. For example, options might point to posts, terms or users and it will depend on which option it is. This is how it's encoded:
```yaml
option:
value-references:
option_name@option_value:
page_on_front: post
default_category: term
...
```
This is the simplest case but it can also get more fancy:
If the entity type needs to be **determined dynamically** it can reference a PHP function:
```yaml
postmeta:
value-references:
meta_key@meta_value:
_menu_item_object_id: '@\VersionPress\Database\VpidRepository::getMenuReference'
```
Note that there are no parenthesis at the end of this (it's a method reference, not a call) and that it is prefixed with `@`. The function gets the entity as a parameter and returns a target entity name. For example, for `_menu_item_object_id`, the function looks for a related DB row with `_menu_item_type` and returns its value.
If the **ID is in a serialized object**, you can specify the path by a suffix of the source column. It looks like an array access but also supports regular expressions, for example:
```yaml
option:
value-references:
option_name@option_value:
widget_pages[/\d+/]["exclude"]: post
```
To visualize this, the `widget_pages` option contains a value like `a:2:{i:2;a:3:{s:5:"title";s:0:"";s:7:"exclude";s:7:"1, 2, 3";...}...}` which, unserialized, looks like this:
```php
[
2 => [
"title" => "",
"sortby" => "post_title",
"exclude" => "1, 2, 3"
],
"_multiwidget" => 1
]
```
The schema says that the numbers in the "exclude" key reference posts.
Value references also support **wildcards** in the name of the source column. It's useful e.g. for options named `theme_mods_<name of theme>`. An example that mixes this with the serialized data syntax is:
```yaml
option:
value-references:
option_name@option_value:
theme_mods_*["nav_menu_locations"][/.*/]: term
theme_mods_*["header_image_data"]["attachment_id"]: post
theme_mods_*["custom_logo"]: post
```
It probably won't surprise you that this is a real example used in WordPress' `schema.yml`. :stuck_out_tongue_winking_eye:
Another supported feature are IDs in serialized data in serialized data (really).
An example from WooCommerce: `a:1:{s:4:"cart";s:99:"a:1:{s:32:"a5bfc9e07964f8dddeb95fc584cd965d";a:2:{s:10:"product_id";i:37;s:12:"variation_id";i:0;}}";}`.
```yaml
session:
value-references:
session_key@session_value:
"*[\"cart\"]..[/.*/][\"product_id\"]": product
"*[\"cart\"]..[/.*/][\"variation_id\"]": variation
```
The complete syntax is:
```yaml
value-references:
<source_column_name>@<value_column_name>:
<source_column_value>: <foreign_entity_name | @mapping_function>
<source_column_value>["path-in-serialized-objects"][/\d+/][0]..["key-in-nested-serialized-array"]: <foreign_entity_name | @mapping_function>
<columns_with_prefix_*>: <foreign_entity_name | @mapping_function>
```
#### M:N references
Some entities are in an M:N relationship like posts and term_taxonomies. This is how it's written:
```yaml
post:
mn-references:
term_relationships.term_taxonomy_id: term_taxonomy
```
One entity is considered the main one which is kind of arbitrary as technically, VersionPress treats them equally. Here, we decided that posts will store tags and categories in them, not the other way around.
The syntax is:
```yaml
mn-references:
<junction_table_name_without_prefix>.<column_name>: <foreign_entity_name>
```
References can also be prefixed with a tilde (`~`) which makes them **"virtual"**:
```yaml
mn-references:
~<junction_table_name_without_prefix>.<column_name>: <foreign_entity_name>
```
A virtual reference is not stored in the INI file but the relationships are still checked during reverts. For example, when a revert would delete a category (revert of `term_taxonomy/create`) and there is some post referencing it, the operation would fail. This is ensured by:
```yaml
term_taxonomy:
mn-references:
~term_relationships.object_id: post
```
#### Parent references
Some entities are stored within other entities, for example, postmeta are stored in the same INI file as their parent post. This is captured using a `parent-reference` property:
```yaml
postmeta:
parent-reference: post_id
references:
post_id: post
```
This references one of the basic reference column names, not the final entity. The notation above reads "postmeta stores a parent reference in the `post_id` column, and that points to the `post` entity".
### Frequently written entities
Some entities are changed very often, e.g., view counters, Akismet spam count, etc. VersionPress only saves them once in a while and the `frequently-written` section influences this:
```yaml
entity:
frequently-written:
- 'column_name: value'
- query: 'column1_name: value1 column2_name: value2'
interval: 5min
```
The values in the `frequently-written` array can either be strings which are then interpreted as queries, or objects with `query` and `interval` keys.
- **Queries** identify entities via [this syntax](#query-syntax).
- The **interval** is parsed by the `strtotime()` function and the default value is one hour.
### Ignoring entities
Some entities should be ignored (not tracked at all) like transient options, environment-specific options, etc. [Queries](#query-syntax) are used again:
```yaml
ignored-entities:
- 'option_name: _transient_*'
- 'option_name: _site_transient_*'
- 'option_name: siteurl'
```
### Ignoring columns
It is possible to ignore just parts of entities. The columns might either be ignored entirely or computed dynamically using a PHP function:
```yaml
entity:
ignored-columns:
- column_name_1
- column_name_2
- computed_column_name: '@functionReference'
```
The function is called whenever VersionPress does its INI files => DB synchronization. The function will get an instance of `VersionPress\Database\Database` as an argument and is expected to update the database appropriately. The `Database` class has the same methods as `wpdb` but the changes it make are not tracked by VersionPress itself.
### Cache invalidation
WordPress uses cache for posts, comments, users, terms, etc. This cache needs to be invalidated when VersionPress updates database (on undo, rollback, pull, etc.). It is possible to tell VersionPress which cache to invalidate and where to find the related IDs.
For example, when some post is deleted using the Undo functionality, it is necessary to call `clean_post_cache(<post-id>)`. VersionPress will do it automatically based on following piece of schema:
```yaml
post:
table: posts
id: ID
clean-cache:
- post: id
```
It tells VersionPress to delete the post cache (VP resolves the function name as `clean_<cache-type>_cache`). You can use `id` as the source of IDs for invalidation or a reference. For example like this:
```yaml
post:
references:
post_author: user
post_parent: post
clean-cache:
- post: id
- user: post_author
- post: post_parent
```
## Shortcodes
Similarly to database schema, VersionPress needs to understand shortcodes as they can also contain entity references. `shortcodes.yml` describes this, here is an example:
```yaml
shortcode-locations:
post:
- post_content
shortcodes:
gallery:
id: post
ids: post
include:
exclude: post
playlist:
id: post
ids: post
include: post
exclude: post
```
The **`shortcode-locations`** array tells VersionPress where the shortcodes can appear. By default, WordPress only allows shortcodes in post content but here's an example of how it could look if it also supported them in post titles and comments:
```yaml
shortcode-locations:
post:
- post_content
- post_title
comment:
- comment_content
```
Note that WordPress doesn't restrict shortcode *type* for various locations, so if some shortcode is supported in e.g. `comment_content`, all shortcodes are.
The `shortcodes` array holds the actual shortcodes, but only those that contain references to other entities so things like `[embed]` or `[audio]` are not present. Here's an example:
```yaml
shortcodes:
gallery:
id: post
ids: post
include:
exclude: post
playlist:
id: post
ids: post
include: post
exclude: post
```
For example the `[gallery]` shortcode has four attributes that can contain references, and they all point to the `post` entity (it's an entity, not a table; the table will eventually be something like `wp_posts`).
Note that you don't have to worry about the attribute type, whether it contains a single ID or a list of IDs. VersionPress handles both cases automatically:
```php
[gallery id="1"]
[gallery id="1,2,3,6,11,20"]
```
## Hooks
If something cannot be described statically, VersionPress offers several filters, actions and functions to define behavior through code. Implement them in the `hooks.php` file.
Most of the filters have already been discussed in the text above, you can find the full API reference below.
## Ignored folders
Feel free to use custom `.gitignore` for files in the plugin directory. You can also ignore files / directories outside the plugin directory. There will be a filter to let VersionPress know which files / directories you want to ignore.
## Discovery mechanism
VersionPress looks for plugin definitions in these locations, in this order:
1. `WP_CONTENT_DIR/.versionpress/plugins/<plugin-slug>` (user-editable definitions in the `wp-content` directory)
2. `WP_PLUGIN_DIR/<plugin-slug>/.versionpress` (definitions bundled with plugins)
The first definition found is used.
## Resources
- Issue [#1036](https://github.com/versionpress/versionpress/issues/1036) – everything was discussed there.
## API reference
TODO this will be auto-generated from code.
### Filters
- `vp_entity_action_{$entityName}`
- `apply_filters("vp_entity_action_{$entityName}", $action, $oldEntity, $newEntity)`
- `vp_meta_entity_action_{$entityName}`
- `apply_filters("vp_meta_entity_action_{$entityName}", $action, $oldEntity, $newEntity, $oldParentEntity, $newParentEntity)`
- `vp_entity_tags_{$entityName}`
- `apply_filters("vp_entity_tags_{$entityName}", $tags, $oldEntity, $newEntity, $action)`
- `vp_meta_entity_tags_{$entityName}`
- `apply_filters("vp_meta_entity_tags_{$entityName}", $tags, $oldEntity, $newEntity, $action, $oldParentEntity, $newParentEntity)`
- `vp_entity_files_{$entityName}`
- `apply_filters("vp_entity_files_{$entityName}", $files, $oldEntity, $newEntity)`
- `vp_meta_entity_files_{$entityName}`
- `apply_filters("vp_meta_entity_files_{$entityName}", $files, $oldEntity, $newEntity, $oldParentEntity, $newParentEntity)`
- `vp_entity_should_be_saved_{$entityName}`
- `apply_filters("vp_entity_should_be_saved_{$entityName}", $shouldBeSaved, $data, $storage)`
- `vp_bulk_change_description_{$entityName}`
- `apply_filters("vp_bulk_change_description_{$entityName}", $description, $action, $count, $tags)`
- `vp_action_description_{$scope}`
- `apply_filters("vp_action_description_{$scope}", $message, $action, $vpid, $tags)`
- `vp_action_priority_{$scope}`
- `apply_filters("vp_action_priority_{$entityName}", $defaultPriority, $action, $vpid, $entity)`
- `apply_filters("vp_action_priority_{$entityName}", $defaultPriority, $action, $vpid)`
### Actions (API)
- `vp_before_synchronization_{$entityName}`
- `do_action("vp_before_synchronization_{$entityName}")`
- `vp_after_synchronization_{$entityName}`
- `do_action("vp_after_synchronization_{$entityName}")`
### Functions
- `vp_force_action`
- `vp_force_action($scope, $action, $id = '', $tags = [], $files = [])`
### Query syntax
[Ignored](#ignoring-entities) and [frequently written](#frequently-written-entities) entities are identified using small queries that look like this:
```yaml
frequently-written:
- 'option_name: akismet_spam_count'
ignored-entities:
- 'option_name: _transient_*'
- 'option_name: cron'
- ...
```
The syntax is generally shared with the [commit search](../feature-focus/searching-history.md):
- Everything is case insensitive. `field: value` is equivalent to `field: VALUE` or `FiELd: vaLUE`.
- One caveat is that your database might be configured to use case sensitive comparisons, in which case you'll need to be precise. (WordPress uses the case insensitive `utf8_general_ci` collation by default.)
- Wildcards are supported.
- Multiple fields can be used, for example, `field1:value field2:value`.
Unlike the full search, you can only target entity fields, not things like commit authors, date ranges, etc.
| {
"pile_set_name": "Github"
} |
// Copyright 2001-2019 Crytek GmbH / Crytek Group. All rights reserved.
#include "StdAfx.h"
#include "PolygonDecomposer.h"
#include "BSPTree2D.h"
#include "Core/SmoothingGroup.h"
#include "Convexes.h"
#include "LoopPolygons.h"
#include <stack>
namespace Designer
{
typedef std::pair<BrushFloat, BrushFloat> YXPair;
bool PolygonDecomposer::TriangulatePolygon(PolygonPtr pPolygon, std::vector<PolygonPtr>& outTrianglePolygons)
{
FlexibleMesh mesh;
if (!TriangulatePolygon(pPolygon, mesh))
return false;
for (int i = 0, iFaceList(mesh.faceList.size()); i < iFaceList; ++i)
{
std::vector<BrushVec3> face;
face.push_back(BrushVec3(mesh.vertexList[mesh.faceList[i].v[0]].pos));
face.push_back(BrushVec3(mesh.vertexList[mesh.faceList[i].v[1]].pos));
face.push_back(BrushVec3(mesh.vertexList[mesh.faceList[i].v[2]].pos));
PolygonPtr pTriangulatedPolygon = new Polygon(face);
pTriangulatedPolygon->SetSubMatID(pPolygon->GetSubMatID());
pTriangulatedPolygon->SetTexInfo(pPolygon->GetTexInfo());
pTriangulatedPolygon->SetFlag(pPolygon->GetFlag());
pTriangulatedPolygon->RemoveFlags(ePolyFlag_NonplanarQuad);
pTriangulatedPolygon->SetPlane(pPolygon->GetPlane());
outTrianglePolygons.push_back(pTriangulatedPolygon);
}
return true;
}
bool PolygonDecomposer::TriangulatePolygon(PolygonPtr pPolygon, FlexibleMesh& outMesh)
{
if (!pPolygon || pPolygon->IsOpen())
return false;
m_bGenerateConvexes = false;
outMesh.faceList.reserve(pPolygon->GetVertexCount());
m_pPolygon = pPolygon;
m_Plane = pPolygon->GetPlane();
m_nBasedVertexIndex = 0;
m_pOutData = &outMesh;
if (pPolygon->CheckFlags(ePolyFlag_NonplanarQuad))
{
if (!DecomposeNonplanarQuad())
return false;
}
else
{
if (!Decompose())
return false;
}
for (int i = 0, faceCount(outMesh.faceList.size()); i < faceCount; ++i)
outMesh.faceList[i].nSubset = 0;
return true;
}
bool PolygonDecomposer::DecomposeNonplanarQuad()
{
if (!m_pPolygon->CheckFlags(ePolyFlag_NonplanarQuad) || !m_pPolygon->IsValid())
return false;
int v_order[] = { 0, 1, 2, 2, 3, 0 };
int n_order[] = { 2, 0, 2, 2, 1, 2 };
std::vector<Vertex> vList;
m_pPolygon->GetLinkedVertices(vList);
BrushVec3 nList[3] = {
ComputeNormal(vList[v_order[0]].pos, vList[v_order[1]].pos, vList[v_order[2]].pos),
ComputeNormal(vList[v_order[3]].pos, vList[v_order[4]].pos, vList[v_order[5]].pos),
(nList[0] + nList[1]).GetNormalized()
};
for (int i = 0; i < 2; ++i)
{
int offset = i * 3;
SMeshFace f;
for (int k = 0; k < 3; ++k)
{
m_pOutData->vertexList.push_back(vList[v_order[offset + k]]);
m_pOutData->normalList.push_back(nList[n_order[offset + k]]);
f.v[k] = offset + k;
}
m_pOutData->faceList.push_back(f);
}
return true;
}
void PolygonDecomposer::DecomposeToConvexes(PolygonPtr pPolygon, Convexes& outConvexes)
{
if (!pPolygon || pPolygon->IsOpen())
return;
if (pPolygon->GetVertexCount() <= 4)
{
Convex convex;
pPolygon->GetLinkedVertices(convex);
outConvexes.AddConvex(convex);
}
else
{
m_bGenerateConvexes = true;
m_pPolygon = pPolygon;
m_Plane = pPolygon->GetPlane();
m_nBasedVertexIndex = 0;
m_pBrushConvexes = &outConvexes;
FlexibleMesh mesh;
m_pOutData = &mesh;
Decompose();
}
}
bool PolygonDecomposer::Decompose()
{
PolygonPtr pPolygon = m_pPolygon;
if (!pPolygon)
return false;
if (pPolygon->HasBridgeEdges())
{
pPolygon = pPolygon->Clone();
pPolygon->RemoveBridgeEdges();
}
bool bOptimizePolygon = !CheckFlag(eDF_SkipOptimizationOfPolygonResults);
std::vector<PolygonPtr> outerPolygons = pPolygon->GetLoops(bOptimizePolygon)->GetOuterClones();
std::vector<PolygonPtr> innerPolygons = pPolygon->GetLoops(bOptimizePolygon)->GetHoleClones();
for (int k = 0, iOuterPolygonsCount(outerPolygons.size()); k < iOuterPolygonsCount; ++k)
{
PolygonPtr pOuterPolygon = outerPolygons[k];
if (!pOuterPolygon)
return false;
IndexList initialIndexList;
m_VertexList.clear();
m_PointList.clear();
if (m_bGenerateConvexes)
RemoveAllConvexData();
FillVertexListFromPolygon(pOuterPolygon, m_VertexList);
if (m_bGenerateConvexes)
{
for (int i = 0, iVertexCount(m_VertexList.size()); i < iVertexCount; ++i)
m_InitialEdgesSortedByEdge.insert(GetSortedEdgePair(i, (i + 1) % iVertexCount));
}
int iVertexSize(m_VertexList.size());
for (int i = 0; i < iVertexSize; ++i)
{
initialIndexList.push_back(i);
m_PointList.push_back(Point(Convert3DTo2D(m_VertexList[i].pos), ((i - 1) + iVertexSize) % iVertexSize, (i + 1) % iVertexSize));
}
bool bHasInnerHull = false;
for (int i = 0, innerPolygonSize(innerPolygons.size()); i < innerPolygonSize; ++i)
{
if (!pOuterPolygon->IncludeAllEdges(innerPolygons[i]))
continue;
bHasInnerHull = true;
int nBaseIndex = m_PointList.size();
std::vector<Vertex> innerVertexList;
FillVertexListFromPolygon(innerPolygons[i], innerVertexList);
for (int k = 0, nVertexSize(innerVertexList.size()); k < nVertexSize; ++k)
{
int nPrevIndex = k == 0 ? nBaseIndex + nVertexSize - 1 : nBaseIndex + k - 1;
int nNextIndex = k < nVertexSize - 1 ? m_PointList.size() + 1 : nBaseIndex;
m_PointList.push_back(Point(Convert3DTo2D(innerVertexList[k].pos), nPrevIndex, nNextIndex));
initialIndexList.push_back(initialIndexList.size());
}
m_VertexList.insert(m_VertexList.end(), innerVertexList.begin(), innerVertexList.end());
if (m_bGenerateConvexes)
{
for (int i = 0, iVertexCount(innerVertexList.size()); i < iVertexCount; ++i)
m_InitialEdgesSortedByEdge.insert(GetSortedEdgePair(i + nBaseIndex, (i + 1) % iVertexCount + nBaseIndex));
}
}
m_pOutData->vertexList.insert(m_pOutData->vertexList.end(), m_VertexList.begin(), m_VertexList.end());
if (!DecomposeToTriangules(&initialIndexList, bHasInnerHull))
return false;
if (m_bGenerateConvexes)
CreateConvexes();
m_nBasedVertexIndex += m_VertexList.size();
}
int vertexCount(m_pOutData->vertexList.size());
const BrushVec3& normal = pPolygon->GetPlane().Normal();
for (int i = 0; i < vertexCount; ++i)
m_pOutData->normalList.push_back(normal);
return true;
}
bool PolygonDecomposer::DecomposeToTriangules(IndexList* pIndexList, bool bHasInnerHull)
{
bool bSuccessfulTriangulate = false;
if (IsConvex(*pIndexList, false) && !bHasInnerHull)
bSuccessfulTriangulate = TriangulateConvex(*pIndexList, m_pOutData->faceList);
else
bSuccessfulTriangulate = TriangulateConcave(*pIndexList, m_pOutData->faceList);
if (!bSuccessfulTriangulate)
return false;
return true;
}
void PolygonDecomposer::FillVertexListFromPolygon(PolygonPtr pPolygon, std::vector<Vertex>& outVertexList)
{
if (pPolygon == NULL)
return;
for (int i = 0, iEdgeCount(pPolygon->GetEdgeCount()); i < iEdgeCount; ++i)
{
const IndexPair& rEdge = pPolygon->GetEdgeIndexPair(i);
outVertexList.push_back(pPolygon->GetVertex(rEdge.m_i[0]));
}
}
bool PolygonDecomposer::TriangulateConvex(const IndexList& indexList, std::vector<SMeshFace>& outFaceList) const
{
int iIndexCount(indexList.size());
if (iIndexCount < 3)
return false;
int nStartIndex = 0;
if (iIndexCount >= 4)
{
bool bHasInvalidTriangle = true;
while (bHasInvalidTriangle)
{
bHasInvalidTriangle = false;
for (int i = 1; i < iIndexCount - 1; ++i)
{
if (!HasArea(indexList[nStartIndex], indexList[(nStartIndex + i) % iIndexCount], indexList[(nStartIndex + i + 1) % iIndexCount]))
{
bHasInvalidTriangle = true;
break;
}
}
if (bHasInvalidTriangle)
{
if ((++nStartIndex) >= iIndexCount)
{
nStartIndex = 0;
break;
}
}
}
}
for (int i = 1; i < iIndexCount - 1; ++i)
AddTriangle(indexList[nStartIndex], indexList[(nStartIndex + i) % iIndexCount], indexList[(nStartIndex + i + 1) % iIndexCount], outFaceList);
return true;
}
BSPTree2D* PolygonDecomposer::GenerateBSPTree(const IndexList& indexList) const
{
std::vector<BrushEdge3D> edgeList;
for (int i = 0, iIndexListCount(indexList.size()); i < iIndexListCount; ++i)
{
int nCurr = indexList[i];
int nNext = indexList[(i + 1) % iIndexListCount];
edgeList.push_back(BrushEdge3D(m_VertexList[nCurr].pos, m_VertexList[nNext].pos));
}
BSPTree2D* pBSPTree = new BSPTree2D;
pBSPTree->BuildTree(m_pPolygon->GetPlane(), edgeList);
return pBSPTree;
}
void PolygonDecomposer::BuildEdgeListHavingSameY(const IndexList& indexList, EdgeListMap& outEdgeList) const
{
for (int i = 0, nIndexBuffSize(indexList.size()); i < nIndexBuffSize; ++i)
{
int nNext = (i + 1) % nIndexBuffSize;
const BrushVec2& v0 = m_PointList[indexList[i]].pos;
const BrushVec2& v1 = m_PointList[indexList[nNext]].pos;
if (DecomposerComp::IsEquivalent(v0.y, v1.y))
{
BrushFloat fY = v0.y;
if (outEdgeList.find(fY) != outEdgeList.end())
{
IndexList& edgeList = outEdgeList[fY];
bool bInserted = false;
for (int k = 0, edgeListCount(edgeList.size()); k < edgeListCount; ++k)
{
if (v0.x < m_PointList[indexList[edgeList[k]]].pos.x)
{
edgeList.insert(edgeList.begin() + k, i);
bInserted = true;
break;
}
}
if (!bInserted)
edgeList.push_back(i);
}
else
{
outEdgeList[fY].push_back(i);
}
}
}
}
void PolygonDecomposer::BuildPointSideList(const IndexList& indexList, const EdgeListMap& edgeListHavingSameY, std::vector<EDirection>& outPointSideList, std::map<PointComp, std::pair<int, int>>& outSortedPointsMap) const
{
outPointSideList.resize(m_VertexList.size());
int nLeftTopIndex = FindLeftTopVertexIndex(indexList);
int nRightBottomIndex = FindRightBottomVertexIndex(indexList);
for (int i = 0, nIndexBuffSize(indexList.size()); i < nIndexBuffSize; ++i)
{
outPointSideList[indexList[i]] = QueryPointSide(i, indexList, nLeftTopIndex, nRightBottomIndex);
BrushFloat fY(m_PointList[indexList[i]].pos.y);
int xPriority = outPointSideList[indexList[i]] == eDirection_Left ? 0 : 100;
PointComp pointComp(m_PointList[indexList[i]].pos.y, xPriority);
EDirection iSide = outPointSideList[indexList[i]];
auto ifY = edgeListHavingSameY.find(fY);
if (ifY != edgeListHavingSameY.end())
{
const IndexList& indexEdgeList = ifY->second;
for (int k = 0, iIndexEdgeCount(indexEdgeList.size()); k < iIndexEdgeCount; ++k)
{
if (indexEdgeList[k] == i)
{
if (iSide == eDirection_Left)
pointComp.m_XPriority += k * 2;
else if (iSide == eDirection_Right)
pointComp.m_XPriority += k * 2 + 1;
break;
}
else if ((indexEdgeList[k] + 1) % nIndexBuffSize == i)
{
if (iSide == eDirection_Left)
pointComp.m_XPriority += k * 2 + 1;
else if (iSide == eDirection_Right)
pointComp.m_XPriority += k * 2;
break;
}
}
}
outSortedPointsMap[pointComp] = std::pair<int, int>(indexList[i], i);
}
DESIGNER_ASSERT(outSortedPointsMap.size() == indexList.size());
}
bool PolygonDecomposer::TriangulateMonotonePolygon(const IndexList& indexList, std::vector<SMeshFace>& outFaceList) const
{
BSPTree2DPtr pBSPTree = GenerateBSPTree(indexList);
EdgeListMap edgeListHavingSameY;
BuildEdgeListHavingSameY(indexList, edgeListHavingSameY);
std::vector<EDirection> sideList;
std::map<PointComp, std::pair<int, int>> yxSortedPoints;
BuildPointSideList(indexList, edgeListHavingSameY, sideList, yxSortedPoints);
std::stack<int> vertexStack;
auto ii = yxSortedPoints.begin();
vertexStack.push(ii->second.first);
++ii;
vertexStack.push(ii->second.first);
auto ii_prev = ii;
++ii;
for (; ii != yxSortedPoints.end(); ++ii)
{
int top = vertexStack.top();
int current = ii->second.first;
DESIGNER_ASSERT(vertexStack.size() >= 2);
vertexStack.pop();
int prev = vertexStack.top();
vertexStack.push(top);
EDirection topSide = sideList[top];
EDirection currentSide = sideList[current];
if (topSide != currentSide)
{
while (!vertexStack.empty())
{
top = vertexStack.top();
if (IsCCW(current, prev, top))
AddFace(current, prev, top, indexList, outFaceList);
else
AddFace(current, top, prev, indexList, outFaceList);
prev = top;
vertexStack.pop();
}
vertexStack.push(ii_prev->second.first);
}
else if (currentSide == eDirection_Right && IsCCW(current, top, prev) || currentSide == eDirection_Left && IsCW(current, top, prev))
{
prev = top;
vertexStack.pop();
while (!vertexStack.empty())
{
top = vertexStack.top();
if (IsInside(pBSPTree, current, top))
{
if (IsCCW(current, prev, top))
AddFace(current, prev, top, indexList, outFaceList);
else
AddFace(current, top, prev, indexList, outFaceList);
}
else
{
break;
}
prev = top;
vertexStack.pop();
}
vertexStack.push(prev);
}
vertexStack.push(ii->second.first);
ii_prev = ii;
}
return true;
}
bool PolygonDecomposer::TriangulateConcave(const IndexList& indexList, std::vector<SMeshFace>& outFaceList)
{
std::vector<IndexList> monotonePieces;
if (!DecomposePolygonIntoMonotonePieces(indexList, monotonePieces))
return false;
for (int i = 0, iMonotonePiecesCount(monotonePieces.size()); i < iMonotonePiecesCount; ++i)
{
if (IsConvex(monotonePieces[i], false))
TriangulateConvex(monotonePieces[i], outFaceList);
else
TriangulateMonotonePolygon(monotonePieces[i], outFaceList);
}
return true;
}
bool PolygonDecomposer::IsCCW(int i0, int i1, int i2) const
{
return IsCCW(m_PointList[i0].pos, m_PointList[i1].pos, m_PointList[i2].pos);
}
BrushFloat PolygonDecomposer::IsCCW(const BrushVec2& prev, const BrushVec2& current, const BrushVec2& next) const
{
const BrushVec3& v0(prev);
const BrushVec3& v1(current);
const BrushVec3& v2(next);
BrushVec3 v10 = (v0 - v1).GetNormalized();
BrushVec3 v12 = (v2 - v1).GetNormalized();
BrushVec3 v10_x_v12 = v10.Cross(v12);
return v10_x_v12.z > -kDecomposerEpsilon;
}
BrushFloat PolygonDecomposer::IsCW(const BrushVec2& prev, const BrushVec2& current, const BrushVec2& next) const
{
return !IsCCW(prev, current, next);
}
bool PolygonDecomposer::IsCCW(const IndexList& indexList, int nCurr) const
{
int nIndexListCount = indexList.size();
return IsCCW(indexList[((nCurr - 1) + nIndexListCount) % nIndexListCount], indexList[nCurr], indexList[(nCurr + 1) % nIndexListCount]);
}
bool PolygonDecomposer::IsConvex(const IndexList& indexList, bool bGetPrevNextFromPointList) const
{
int iIndexCount(indexList.size());
if (iIndexCount <= 3)
return true;
for (int i = 0; i < iIndexCount; ++i)
{
int nPrev = bGetPrevNextFromPointList ? m_PointList[indexList[i]].prev : indexList[((i - 1) + iIndexCount) % iIndexCount];
int nNext = bGetPrevNextFromPointList ? m_PointList[indexList[i]].next : indexList[(i + 1) % iIndexCount];
if (!IsCCW(nPrev, indexList[i], nNext))
return false;
}
return true;
}
BrushFloat PolygonDecomposer::Cosine(int i0, int i1, int i2) const
{
const BrushVec2 p10 = (m_PointList[i0].pos - m_PointList[i1].pos).GetNormalized();
const BrushVec2 p12 = (m_PointList[i2].pos - m_PointList[i1].pos).GetNormalized();
return p10.Dot(p12);
}
bool PolygonDecomposer::GetNextIndex(int nCurr, const IndexList& indices, int& nOutNextIndex) const
{
for (int i = 0, iSize(indices.size()); i < iSize; ++i)
{
if (indices[i] == nCurr)
{
nOutNextIndex = indices[(i + 1) % iSize];
return true;
}
}
return false;
}
bool PolygonDecomposer::HasArea(int i0, int i1, int i2) const
{
if (i0 == i1 || i0 == i2 || i1 == i2)
return false;
const BrushVec2& p0 = m_PointList[i0].pos;
const BrushVec2& p1 = m_PointList[i1].pos;
const BrushVec2& p2 = m_PointList[i2].pos;
if (p0.IsEquivalent(p1, kDecomposerEpsilon) || p0.IsEquivalent(p2, kDecomposerEpsilon) || p1.IsEquivalent(p2, kDecomposerEpsilon))
return false;
if (IsColinear(p0, p1, p2))
return false;
return true;
}
void PolygonDecomposer::AddFace(int i0, int i1, int i2, const IndexList& indices, std::vector<SMeshFace>& outFaceList) const
{
if (!HasArea(i0, i1, i2))
return;
bool bAddedSubTriangles = false;
int faceIndex[3] = { i0, i1, i2 };
for (int i = 0; i < 3; ++i)
{
int nPrev = faceIndex[((i - 1) + 3) % 3];
int nCurr = faceIndex[i];
int nNext = faceIndex[(i + 1) % 3];
int nIndex = 0;
int nPrevIndex = nNext;
if (!GetNextIndex(nPrevIndex, indices, nIndex))
return;
int nCounter = 0;
while (nIndex != nCurr)
{
if (IsInsideEdge(nNext, nPrev, nIndex))
{
if (!(nCurr == i0 && nPrevIndex == i1 && nIndex == i2 || nCurr == i1 && nPrevIndex == i2 && nIndex == i0 || nCurr == i2 && nPrevIndex == i0 && nIndex == i1))
{
bAddedSubTriangles = true;
AddTriangle(nCurr, nPrevIndex, nIndex, outFaceList);
}
nPrevIndex = nIndex;
}
if (!GetNextIndex(nIndex, indices, nIndex))
break;
if ((nCounter++) > indices.size())
{
DESIGNER_ASSERT(0 && "This seems to fall into a infinite loop");
break;
}
}
}
if (!bAddedSubTriangles)
AddTriangle(i0, i1, i2, outFaceList);
}
void PolygonDecomposer::AddTriangle(int i0, int i1, int i2, std::vector<SMeshFace>& outFaceList) const
{
if (!HasArea(i0, i1, i2))
return;
SMeshFace newFace;
int nBaseVertexIndex = m_nBasedVertexIndex;
int _i0 = i0 + nBaseVertexIndex;
int _i1 = i1 + nBaseVertexIndex;
int _i2 = i2 + nBaseVertexIndex;
if (HasAlreadyAdded(_i0, _i1, _i2, outFaceList))
return;
if (m_bGenerateConvexes)
{
IndexList triangle(3);
triangle[0] = i0;
triangle[1] = i1;
triangle[2] = i2;
int nConvexIndex = m_Convexes.size();
m_Convexes.push_back(triangle);
std::pair<int, int> e[3] = { GetSortedEdgePair(i0, i1), GetSortedEdgePair(i1, i2), GetSortedEdgePair(i2, i0) };
for (int i = 0; i < 3; ++i)
{
if (m_InitialEdgesSortedByEdge.find(e[i]) != m_InitialEdgesSortedByEdge.end())
continue;
m_ConvexesSortedByEdge[e[i]].push_back(nConvexIndex);
m_EdgesSortedByConvex[nConvexIndex].insert(e[i]);
}
}
newFace.v[0] = _i0;
newFace.v[1] = _i1;
newFace.v[2] = _i2;
outFaceList.push_back(newFace);
}
bool PolygonDecomposer::IsInside(BSPTree2D* pBSPTree, int i0, int i1) const
{
if (!pBSPTree)
return true;
return pBSPTree->IsInside(BrushEdge3D(m_VertexList[i0].pos, m_VertexList[i1].pos), false);
}
bool PolygonDecomposer::IsOnEdge(BSPTree2D* pBSPTree, int i0, int i1) const
{
if (!pBSPTree)
return true;
return pBSPTree->IsOnEdge(BrushEdge3D(m_VertexList[i0].pos, m_VertexList[i1].pos));
}
bool PolygonDecomposer::IsColinear(const BrushVec2& p0, const BrushVec2& p1, const BrushVec2& p2) const
{
BrushVec2 p10 = (p0 - p1).GetNormalized();
BrushVec2 p12 = (p2 - p1).GetNormalized();
if (p10.IsEquivalent(p12, kDecomposerEpsilon) || p10.IsEquivalent(-p12, kDecomposerEpsilon))
return true;
return false;
}
bool PolygonDecomposer::HasAlreadyAdded(int i0, int i1, int i2, const std::vector<SMeshFace>& faceList) const
{
for (int i = 0, iFaceCount(faceList.size()); i < iFaceCount; ++i)
{
if (faceList[i].v[0] == i0 && (faceList[i].v[1] == i1 && faceList[i].v[2] == i2 || faceList[i].v[1] == i2 && faceList[i].v[2] == i1))
return true;
if (faceList[i].v[1] == i0 && (faceList[i].v[0] == i1 && faceList[i].v[2] == i2 || faceList[i].v[0] == i2 && faceList[i].v[2] == i1))
return true;
if (faceList[i].v[2] == i0 && (faceList[i].v[0] == i1 && faceList[i].v[1] == i2 || faceList[i].v[0] == i2 && faceList[i].v[1] == i1))
return true;
}
return false;
}
bool PolygonDecomposer::IsInsideEdge(int i0, int i1, int i2) const
{
const BrushVec2& v0 = m_PointList[i0].pos;
const BrushVec2& v1 = m_PointList[i1].pos;
const BrushVec2& v2 = m_PointList[i2].pos;
return BrushEdge(v0, v1).IsInside(v2, kDecomposerEpsilon);
}
bool PolygonDecomposer::IsDifferenceOne(int i0, int i1, const IndexList& indexList) const
{
int nIndexCount = indexList.size();
if (i0 == 0 && i1 == nIndexCount - 1 || i0 == nIndexCount - 1 && i1 == 0)
return true;
return std::abs(i0 - i1) == 1;
}
int PolygonDecomposer::FindLeftTopVertexIndex(const IndexList& indexList) const
{
return FindExtreamVertexIndex<std::less<YXPair>>(indexList);
}
int PolygonDecomposer::FindRightBottomVertexIndex(const IndexList& indexList) const
{
return FindExtreamVertexIndex<std::greater<YXPair>>(indexList);
}
template<class _Pr>
int PolygonDecomposer::FindExtreamVertexIndex(const IndexList& indexList) const
{
std::map<YXPair, int, _Pr> YXSortedList;
for (int i = 0, nIndexBuffSize(indexList.size()); i < nIndexBuffSize; ++i)
YXSortedList[YXPair(m_PointList[indexList[i]].pos.y, m_PointList[indexList[i]].pos.x)] = i;
DESIGNER_ASSERT(!YXSortedList.empty());
return YXSortedList.begin()->second;
}
PolygonDecomposer::EDirection PolygonDecomposer::QueryPointSide(int nIndex, const IndexList& indexList, int nLeftTopIndex, int nRightBottomIndex) const
{
int nBoundary[] = { nLeftTopIndex, nRightBottomIndex };
PolygonDecomposer::EDirection side[] = { eDirection_Left, eDirection_Right };
int nIndexBuffSize = indexList.size();
for (int i = 0, iSize(sizeof(nBoundary) / sizeof(*nBoundary)); i < iSize; ++i)
{
int nTraceIndex = nBoundary[i];
while (nTraceIndex != nBoundary[1 - i])
{
if (nTraceIndex == nIndex)
return side[i];
++nTraceIndex;
if (nTraceIndex >= nIndexBuffSize)
nTraceIndex = 0;
}
}
DESIGNER_ASSERT(0 && "Return Value should be either eDirection_Left or eDirection_Right");
return eDirection_Invalid;
}
int PolygonDecomposer::FindDirectlyLeftEdge(int nBeginIndex, const IndexList& edgeSearchList, const IndexList& indexList) const
{
const BrushVec2& point = m_PointList[nBeginIndex].pos;
const BrushVec2 leftDir(-1.0f, 0);
BrushFloat nearestDist = 3e10f;
int nNearestEdge = -1;
for (int i = 0, iEdgeCount(edgeSearchList.size()); i < iEdgeCount; ++i)
{
int nIndex = indexList[edgeSearchList[i]];
int nNextIndex = m_PointList[nIndex].next;
BrushEdge edge(m_PointList[nIndex].pos, m_PointList[nNextIndex].pos);
BrushLine line(edge.m_v[0], edge.m_v[1]);
if (line.Distance(point) > 0)
continue;
if (point.y < edge.m_v[0].y - kDecomposerEpsilon || point.y > edge.m_v[1].y + kDecomposerEpsilon)
continue;
BrushFloat dist;
if (line.HitTest(point, point + leftDir, &dist))
dist = std::abs(dist);
else if (DecomposerComp::IsEquivalent(edge.m_v[0].y, point.y) && DecomposerComp::IsEquivalent(edge.m_v[0].y, edge.m_v[1].y))
dist = std::min((point - edge.m_v[0]).GetLength(), (point - edge.m_v[1]).GetLength());
else
continue;
if (dist < nearestDist)
{
nNearestEdge = edgeSearchList[i];
nearestDist = dist;
}
}
return nNearestEdge;
}
void PolygonDecomposer::EraseElement(int nIndex, IndexList& indexList) const
{
for (int i = 0, indexCount(indexList.size()); i < indexCount; ++i)
{
if (indexList[i] != nIndex)
continue;
indexList.erase(indexList.begin() + i);
return;
}
}
void PolygonDecomposer::AddDiagonalEdge(int i0, int i1, EdgeSet& diagonalSet) const
{
int i0Prev = m_PointList[i0].prev;
int i0Next = m_PointList[i0].next;
int i1Prev = m_PointList[i1].prev;
int i1Next = m_PointList[i1].next;
if (i0Prev == i1 || i0Next == i1 || i1Prev == i0 || i1Next == i0)
return;
if (DecomposerComp::IsEquivalent(m_PointList[i0].pos.y, m_PointList[i1].pos.y))
{
if (i1 != i0Prev && DecomposerComp::IsEquivalent(m_PointList[i0].pos.y, m_PointList[i0Prev].pos.y) && IsInsideEdge(i0, i1, i0Prev))
{
diagonalSet.insert(IndexPair(i1, i0Prev));
diagonalSet.insert(IndexPair(i0Prev, i1));
return;
}
else if (i1 != i0Next && DecomposerComp::IsEquivalent(m_PointList[i0].pos.y, m_PointList[i0Next].pos.y) && IsInsideEdge(i0, i1, i0Next))
{
diagonalSet.insert(IndexPair(i1, i0Next));
diagonalSet.insert(IndexPair(i0Next, i1));
return;
}
else if (i0 != i1Prev && DecomposerComp::IsEquivalent(m_PointList[i1].pos.y, m_PointList[i1Prev].pos.y) && IsInsideEdge(i0, i1, i1Prev))
{
diagonalSet.insert(IndexPair(i0, i1Prev));
diagonalSet.insert(IndexPair(i1Prev, i0));
return;
}
else if (i0 != i1Next && DecomposerComp::IsEquivalent(m_PointList[i1].pos.y, m_PointList[i1Next].pos.y) && IsInsideEdge(i0, i1, i1Next))
{
diagonalSet.insert(IndexPair(i0, i1Next));
diagonalSet.insert(IndexPair(i1Next, i0));
return;
}
}
diagonalSet.insert(IndexPair(i0, i1));
diagonalSet.insert(IndexPair(i1, i0));
}
bool PolygonDecomposer::DecomposePolygonIntoMonotonePieces(const IndexList& indexList, std::vector<IndexList>& outMonatonePieces)
{
std::vector<EPointType> pointTypeList;
IndexList helperList;
IndexList edgeSearchList;
EdgeSet diagonalSet;
std::map<PointComp, int, std::less<PointComp>> yMap;
for (int i = 0, nIndexCount(indexList.size()); i < nIndexCount; ++i)
{
pointTypeList.push_back(QueryPointType(i, indexList));
PointComp newPoint(m_PointList[indexList[i]].pos.y, (int)((m_PointList[indexList[i]].pos.x) * 10000.0f));
if (yMap.find(newPoint) != yMap.end())
--newPoint.m_XPriority;
yMap[newPoint] = i;
helperList.push_back(-1);
}
auto yIter = yMap.begin();
for (; yIter != yMap.end(); ++yIter)
{
int index = yIter->second;
int prev = m_PointList[index].prev;
switch (pointTypeList[index])
{
case ePointType_Start:
helperList[index] = index;
edgeSearchList.push_back(index);
break;
case ePointType_End:
if (helperList[prev] != -1)
{
if (pointTypeList[helperList[prev]] == ePointType_Merge)
AddDiagonalEdge(index, helperList[prev], diagonalSet);
EraseElement(prev, edgeSearchList);
}
break;
case ePointType_Split:
{
int nDirectlyLeftEdgeIndex = FindDirectlyLeftEdge(index, edgeSearchList, indexList);
DESIGNER_ASSERT(nDirectlyLeftEdgeIndex != -1);
if (nDirectlyLeftEdgeIndex != -1)
{
AddDiagonalEdge(index, helperList[nDirectlyLeftEdgeIndex], diagonalSet);
helperList[nDirectlyLeftEdgeIndex] = index;
}
edgeSearchList.push_back(index);
helperList[index] = index;
}
break;
case ePointType_Merge:
{
if (helperList[prev] != -1)
{
if (pointTypeList[helperList[prev]] == ePointType_Merge)
AddDiagonalEdge(index, helperList[prev], diagonalSet);
}
EraseElement(prev, edgeSearchList);
int nDirectlyLeftEdgeIndex = FindDirectlyLeftEdge(index, edgeSearchList, indexList);
DESIGNER_ASSERT(nDirectlyLeftEdgeIndex != -1);
if (nDirectlyLeftEdgeIndex != -1)
{
if (pointTypeList[helperList[nDirectlyLeftEdgeIndex]] == ePointType_Merge)
AddDiagonalEdge(index, helperList[nDirectlyLeftEdgeIndex], diagonalSet);
helperList[nDirectlyLeftEdgeIndex] = index;
}
}
break;
case ePointType_Regular:
{
EDirection interiorDir = QueryInteriorDirection(index, indexList);
if (interiorDir == eDirection_Right)
{
if (helperList[prev] != -1)
{
if (pointTypeList[helperList[prev]] == ePointType_Merge)
AddDiagonalEdge(index, helperList[prev], diagonalSet);
}
EraseElement(prev, edgeSearchList);
edgeSearchList.push_back(index);
helperList[index] = index;
}
else if (interiorDir == eDirection_Left)
{
int nDirectlyLeftEdgeIndex = FindDirectlyLeftEdge(index, edgeSearchList, indexList);
DESIGNER_ASSERT(nDirectlyLeftEdgeIndex != -1);
if (nDirectlyLeftEdgeIndex != -1)
{
if (pointTypeList[helperList[nDirectlyLeftEdgeIndex]] == ePointType_Merge)
AddDiagonalEdge(index, helperList[nDirectlyLeftEdgeIndex], diagonalSet);
helperList[nDirectlyLeftEdgeIndex] = index;
}
}
else
{
DESIGNER_ASSERT(0 && "Interior should lie to the right or the left of point.");
}
}
break;
}
}
SearchMonotoneLoops(diagonalSet, indexList, outMonatonePieces);
return true;
}
void PolygonDecomposer::SearchMonotoneLoops(EdgeSet& diagonalSet, const IndexList& indexList, std::vector<IndexList>& monotonePieces) const
{
int iIndexListCount(indexList.size());
EdgeSet handledEdgeSet;
EdgeSet edgeSet;
EdgeMap edgeMap;
for (int i = 0; i < iIndexListCount; ++i)
{
edgeSet.insert(IndexPair(indexList[i], m_PointList[indexList[i]].next));
edgeMap[indexList[i]].insert(m_PointList[indexList[i]].next);
}
auto iDiagonalEdgeSet = diagonalSet.begin();
for (; iDiagonalEdgeSet != diagonalSet.end(); ++iDiagonalEdgeSet)
{
edgeSet.insert(*iDiagonalEdgeSet);
edgeMap[(*iDiagonalEdgeSet).m_i[0]].insert((*iDiagonalEdgeSet).m_i[1]);
}
int nCounter(0);
auto iEdgeSet = edgeSet.begin();
for (iEdgeSet = edgeSet.begin(); iEdgeSet != edgeSet.end(); ++iEdgeSet)
{
if (handledEdgeSet.find(*iEdgeSet) != handledEdgeSet.end())
continue;
IndexList monotonePiece;
IndexPair edge = *iEdgeSet;
handledEdgeSet.insert(edge);
do
{
monotonePiece.push_back(edge.m_i[0]);
DESIGNER_ASSERT(edgeMap.find(edge.m_i[1]) != edgeMap.end());
EdgeIndexSet& secondIndexSet = edgeMap[edge.m_i[1]];
if (secondIndexSet.size() == 1)
{
edge = IndexPair(edge.m_i[1], *secondIndexSet.begin());
secondIndexSet.clear();
}
else if (secondIndexSet.size() > 1)
{
BrushFloat ccwCosMax = -1.5f;
BrushFloat cwCosMin = 1.5f;
int ccwIndex = -1;
int cwIndex = -1;
auto iSecondIndexSet = secondIndexSet.begin();
for (; iSecondIndexSet != secondIndexSet.end(); ++iSecondIndexSet)
{
if (*iSecondIndexSet == edge.m_i[0])
continue;
BrushFloat cosine = Cosine(edge.m_i[0], edge.m_i[1], *iSecondIndexSet);
if (IsCCW(edge.m_i[0], edge.m_i[1], *iSecondIndexSet))
{
if (cosine > ccwCosMax)
{
ccwIndex = *iSecondIndexSet;
ccwCosMax = cosine;
}
}
else if (cosine < cwCosMin)
{
cwIndex = *iSecondIndexSet;
cwCosMin = cosine;
}
}
if (ccwIndex != -1)
{
edge = IndexPair(edge.m_i[1], ccwIndex);
secondIndexSet.erase(ccwIndex);
}
else
{
edge = IndexPair(edge.m_i[1], cwIndex);
secondIndexSet.erase(cwIndex);
}
}
handledEdgeSet.insert(edge);
if (++nCounter > 10000)
{
DESIGNER_ASSERT(0 && "PolygonDecomposer::SearchMonotoneLoops() - Searching connected an edge doesn't seem possible.");
return;
}
}
while (edge.m_i[1] != (*iEdgeSet).m_i[0]);
monotonePiece.push_back(edge.m_i[0]);
monotonePieces.push_back(monotonePiece);
}
}
PolygonDecomposer::EPointType PolygonDecomposer::QueryPointType(int nIndex, const IndexList& indexList) const
{
int nCurrIndex = indexList[nIndex];
int nPrevIndex = m_PointList[nCurrIndex].prev;
int nNextIndex = m_PointList[nCurrIndex].next;
const BrushVec2& prev = m_PointList[nPrevIndex].pos;
const BrushVec2& current = m_PointList[nIndex].pos;
const BrushVec2& next = m_PointList[nNextIndex].pos;
bool bCCW = IsCCW(prev, current, next);
bool bCW = !bCCW;
if (DecomposerComp::IsEquivalent(prev.y, current.y))
{
if (bCW)
{
if (QueryInteriorDirection(nIndex, indexList) == eDirection_Left)
return ePointType_Merge;
else
return ePointType_Regular;
}
else if (DecomposerComp::IsGreaterEqual(next.y, current.y))
return ePointType_Start;
else
return ePointType_End;
}
else if (DecomposerComp::IsEquivalent(current.y, next.y))
{
if (bCW)
{
if (QueryInteriorDirection(nIndex, indexList) == eDirection_Right)
return ePointType_Regular;
else
return ePointType_Split;
}
else if (DecomposerComp::IsGreaterEqual(prev.y, current.y))
return ePointType_Start;
else
return ePointType_End;
}
else if (DecomposerComp::IsGreaterEqual(prev.y, current.y) && DecomposerComp::IsGreaterEqual(next.y, current.y))
{
if (bCCW)
return ePointType_Start;
else
return ePointType_Split;
}
else if (DecomposerComp::IsLessEqual(prev.y, current.y) && DecomposerComp::IsLessEqual(next.y, current.y))
{
if (bCCW)
return ePointType_End;
else
return ePointType_Merge;
}
else if (DecomposerComp::IsLessEqual(prev.y, current.y) && DecomposerComp::IsGreaterEqual(next.y, current.y) ||
DecomposerComp::IsGreaterEqual(prev.y, current.y) && DecomposerComp::IsLessEqual(next.y, current.y))
{
return ePointType_Regular;
}
DESIGNER_ASSERT(0 && "ePointType_Invalid can't be returned.");
return ePointType_Invalid;
}
PolygonDecomposer::EDirection PolygonDecomposer::QueryInteriorDirection(int nIndex, const IndexList& indexList) const
{
int nCurrIndex = indexList[nIndex];
int nPrevIndex = m_PointList[nCurrIndex].prev;
int nNextIndex = m_PointList[nCurrIndex].next;
const BrushVec2& prev = m_PointList[nPrevIndex].pos;
const BrushVec2& current = m_PointList[nCurrIndex].pos;
const BrushVec2& next = m_PointList[nNextIndex].pos;
if (DecomposerComp::IsGreaterEqual(prev.y, current.y) && DecomposerComp::IsGreaterEqual(current.y, next.y))
return eDirection_Left;
if (DecomposerComp::IsLessEqual(prev.y, current.y) && DecomposerComp::IsLessEqual(current.y, next.y))
return eDirection_Right;
return eDirection_Invalid;
}
void PolygonDecomposer::RemoveIndexWithSameAdjacentPoint(IndexList& indexList) const
{
auto ii = indexList.begin();
int nStart = *ii;
for (; ii != indexList.end(); )
{
int nCurr = *ii;
int nNext = (ii + 1) == indexList.end() ? nStart : *(ii + 1);
if (m_VertexList[nCurr].IsEquivalent(m_VertexList[nNext], kDecomposerEpsilon))
ii = indexList.erase(ii);
else
++ii;
}
}
void PolygonDecomposer::FindMatchedConnectedVertexIndices(int iV0, int iV1, const IndexList& indexList, int& nOutIndex0, int& nOutIndex1) const
{
int i0 = -1, i1 = -1;
for (int i = 0, iVertexCount(indexList.size()); i < iVertexCount; ++i)
{
int nNext = (i + 1) % iVertexCount;
if (indexList[i] == iV0 && indexList[nNext] == iV1 || indexList[nNext] == iV0 && indexList[i] == iV1)
{
i0 = i;
i1 = nNext;
break;
}
}
nOutIndex0 = i0;
nOutIndex1 = i1;
}
bool PolygonDecomposer::MergeTwoConvexes(int iV0, int iV1, int iConvex0, int iConvex1, IndexList& outMergedPolygon)
{
DESIGNER_ASSERT(!m_Convexes[iConvex0].empty());
DESIGNER_ASSERT(!m_Convexes[iConvex1].empty());
if (m_Convexes[iConvex0].empty() || m_Convexes[iConvex1].empty())
return false;
int i00 = -1, i01 = -1;
FindMatchedConnectedVertexIndices(iV0, iV1, m_Convexes[iConvex0], i00, i01);
DESIGNER_ASSERT(i00 != -1 && i01 != -1);
if (i00 == -1 || i01 == -1)
return false;
int i10 = -1, i11 = -1;
FindMatchedConnectedVertexIndices(iV0, iV1, m_Convexes[iConvex1], i10, i11);
DESIGNER_ASSERT(i10 != -1 && i11 != -1);
if (i10 == -1 || i11 == -1)
return false;
outMergedPolygon.clear();
for (int i = 0, iVertexCount(m_Convexes[iConvex0].size()); i < iVertexCount; ++i)
outMergedPolygon.push_back(m_Convexes[iConvex0][(i + i01) % iVertexCount]);
for (int i = 0, iVertexCount(m_Convexes[iConvex1].size()); i < iVertexCount - 2; ++i)
outMergedPolygon.push_back(m_Convexes[iConvex1][(i + i11 + 1) % iVertexCount]);
return true;
}
void PolygonDecomposer::CreateConvexes()
{
if (!m_bGenerateConvexes)
return;
auto ii = m_ConvexesSortedByEdge.begin();
for (; ii != m_ConvexesSortedByEdge.end(); ++ii)
{
DESIGNER_ASSERT(ii->second.size() == 2);
if (ii->second.size() != 2)
continue;
int i0 = ii->first.first;
int i1 = ii->first.second;
bool bReflex0 = IsCW(m_PointList[i0].prev, i0, m_PointList[i0].next);
bool bReflex1 = IsCW(m_PointList[i1].prev, i1, m_PointList[i1].next);
IndexList mergedPolygon;
bool bIsResultConvex = false;
if (!bReflex0 && !bReflex1)
{
bIsResultConvex = MergeTwoConvexes(i0, i1, ii->second[0], ii->second[1], mergedPolygon);
}
else
{
if (MergeTwoConvexes(i0, i1, ii->second[0], ii->second[1], mergedPolygon))
bIsResultConvex = IsConvex(mergedPolygon, false);
}
if (bIsResultConvex)
{
int nConvexIndex = ii->second[0];
m_Convexes[nConvexIndex].clear();
m_Convexes[ii->second[1]] = mergedPolygon;
auto iEdge = m_EdgesSortedByConvex[nConvexIndex].begin();
for (; iEdge != m_EdgesSortedByConvex[nConvexIndex].end(); ++iEdge)
{
if (nConvexIndex == m_ConvexesSortedByEdge[*iEdge][0])
{
m_ConvexesSortedByEdge[*iEdge][0] = ii->second[1];
m_EdgesSortedByConvex[ii->second[1]].insert(*iEdge);
}
if (nConvexIndex == m_ConvexesSortedByEdge[*iEdge][1])
{
m_ConvexesSortedByEdge[*iEdge][1] = ii->second[1];
m_EdgesSortedByConvex[ii->second[1]].insert(*iEdge);
}
}
m_EdgesSortedByConvex.erase(nConvexIndex);
}
}
for (int i = 0, iConvexCount(m_Convexes.size()); i < iConvexCount; ++i)
{
if (m_Convexes[i].empty())
continue;
Convex convex;
for (int k = 0, iVListCount(m_Convexes[i].size()); k < iVListCount; ++k)
convex.push_back(m_VertexList[m_Convexes[i][k]]);
m_pBrushConvexes->AddConvex(convex);
}
}
BrushVec2 PolygonDecomposer::Convert3DTo2D(const BrushVec3& pos) const
{
static BrushMatrix33 tmRot = Matrix33::CreateRotationZ(static_cast<float>(PI * 0.09));
BrushVec3 rotatedPos = tmRot.TransformVector(m_Plane.W2P(pos));
return BrushVec2(rotatedPos.x, rotatedPos.y);
}
}
| {
"pile_set_name": "Github"
} |
/*
* HD audio interface patch for Cirrus Logic CS420x chip
*
* Copyright (c) 2009 Takashi Iwai <[email protected]>
*
* This driver 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 2 of the License, or
* (at your option) any later version.
*
* This driver 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/init.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <sound/core.h>
#include "hda_codec.h"
#include "hda_local.h"
/*
*/
struct cs_spec {
int board_config;
struct auto_pin_cfg autocfg;
struct hda_multi_out multiout;
struct snd_kcontrol *vmaster_sw;
struct snd_kcontrol *vmaster_vol;
hda_nid_t dac_nid[AUTO_CFG_MAX_OUTS];
hda_nid_t slave_dig_outs[2];
unsigned int input_idx[AUTO_PIN_LAST];
unsigned int capsrc_idx[AUTO_PIN_LAST];
hda_nid_t adc_nid[AUTO_PIN_LAST];
unsigned int adc_idx[AUTO_PIN_LAST];
unsigned int num_inputs;
unsigned int cur_input;
unsigned int automic_idx;
hda_nid_t cur_adc;
unsigned int cur_adc_stream_tag;
unsigned int cur_adc_format;
hda_nid_t dig_in;
struct hda_bind_ctls *capture_bind[2];
unsigned int gpio_mask;
unsigned int gpio_dir;
unsigned int gpio_data;
struct hda_pcm pcm_rec[2]; /* PCM information */
unsigned int hp_detect:1;
unsigned int mic_detect:1;
};
/* available models */
enum {
CS420X_MBP55,
CS420X_IMAC27,
CS420X_AUTO,
CS420X_MODELS
};
/* Vendor-specific processing widget */
#define CS420X_VENDOR_NID 0x11
#define CS_DIG_OUT1_PIN_NID 0x10
#define CS_DIG_OUT2_PIN_NID 0x15
#define CS_DMIC1_PIN_NID 0x12
#define CS_DMIC2_PIN_NID 0x0e
/* coef indices */
#define IDX_SPDIF_STAT 0x0000
#define IDX_SPDIF_CTL 0x0001
#define IDX_ADC_CFG 0x0002
/* SZC bitmask, 4 modes below:
* 0 = immediate,
* 1 = digital immediate, analog zero-cross
* 2 = digtail & analog soft-ramp
* 3 = digital soft-ramp, analog zero-cross
*/
#define CS_COEF_ADC_SZC_MASK (3 << 0)
#define CS_COEF_ADC_MIC_SZC_MODE (3 << 0) /* SZC setup for mic */
#define CS_COEF_ADC_LI_SZC_MODE (3 << 0) /* SZC setup for line-in */
/* PGA mode: 0 = differential, 1 = signle-ended */
#define CS_COEF_ADC_MIC_PGA_MODE (1 << 5) /* PGA setup for mic */
#define CS_COEF_ADC_LI_PGA_MODE (1 << 6) /* PGA setup for line-in */
#define IDX_DAC_CFG 0x0003
/* SZC bitmask, 4 modes below:
* 0 = Immediate
* 1 = zero-cross
* 2 = soft-ramp
* 3 = soft-ramp on zero-cross
*/
#define CS_COEF_DAC_HP_SZC_MODE (3 << 0) /* nid 0x02 */
#define CS_COEF_DAC_LO_SZC_MODE (3 << 2) /* nid 0x03 */
#define CS_COEF_DAC_SPK_SZC_MODE (3 << 4) /* nid 0x04 */
#define IDX_BEEP_CFG 0x0004
/* 0x0008 - test reg key */
/* 0x0009 - 0x0014 -> 12 test regs */
/* 0x0015 - visibility reg */
static inline int cs_vendor_coef_get(struct hda_codec *codec, unsigned int idx)
{
snd_hda_codec_write(codec, CS420X_VENDOR_NID, 0,
AC_VERB_SET_COEF_INDEX, idx);
return snd_hda_codec_read(codec, CS420X_VENDOR_NID, 0,
AC_VERB_GET_PROC_COEF, 0);
}
static inline void cs_vendor_coef_set(struct hda_codec *codec, unsigned int idx,
unsigned int coef)
{
snd_hda_codec_write(codec, CS420X_VENDOR_NID, 0,
AC_VERB_SET_COEF_INDEX, idx);
snd_hda_codec_write(codec, CS420X_VENDOR_NID, 0,
AC_VERB_SET_PROC_COEF, coef);
}
#define HP_EVENT 1
#define MIC_EVENT 2
/*
* PCM callbacks
*/
static int cs_playback_pcm_open(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct cs_spec *spec = codec->spec;
return snd_hda_multi_out_analog_open(codec, &spec->multiout, substream,
hinfo);
}
static int cs_playback_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct cs_spec *spec = codec->spec;
return snd_hda_multi_out_analog_prepare(codec, &spec->multiout,
stream_tag, format, substream);
}
static int cs_playback_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct cs_spec *spec = codec->spec;
return snd_hda_multi_out_analog_cleanup(codec, &spec->multiout);
}
/*
* Digital out
*/
static int cs_dig_playback_pcm_open(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct cs_spec *spec = codec->spec;
return snd_hda_multi_out_dig_open(codec, &spec->multiout);
}
static int cs_dig_playback_pcm_close(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct cs_spec *spec = codec->spec;
return snd_hda_multi_out_dig_close(codec, &spec->multiout);
}
static int cs_dig_playback_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct cs_spec *spec = codec->spec;
return snd_hda_multi_out_dig_prepare(codec, &spec->multiout, stream_tag,
format, substream);
}
static int cs_dig_playback_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct cs_spec *spec = codec->spec;
return snd_hda_multi_out_dig_cleanup(codec, &spec->multiout);
}
/*
* Analog capture
*/
static int cs_capture_pcm_prepare(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
unsigned int stream_tag,
unsigned int format,
struct snd_pcm_substream *substream)
{
struct cs_spec *spec = codec->spec;
spec->cur_adc = spec->adc_nid[spec->cur_input];
spec->cur_adc_stream_tag = stream_tag;
spec->cur_adc_format = format;
snd_hda_codec_setup_stream(codec, spec->cur_adc, stream_tag, 0, format);
return 0;
}
static int cs_capture_pcm_cleanup(struct hda_pcm_stream *hinfo,
struct hda_codec *codec,
struct snd_pcm_substream *substream)
{
struct cs_spec *spec = codec->spec;
snd_hda_codec_cleanup_stream(codec, spec->cur_adc);
spec->cur_adc = 0;
return 0;
}
/*
*/
static struct hda_pcm_stream cs_pcm_analog_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
.ops = {
.open = cs_playback_pcm_open,
.prepare = cs_playback_pcm_prepare,
.cleanup = cs_playback_pcm_cleanup
},
};
static struct hda_pcm_stream cs_pcm_analog_capture = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
.ops = {
.prepare = cs_capture_pcm_prepare,
.cleanup = cs_capture_pcm_cleanup
},
};
static struct hda_pcm_stream cs_pcm_digital_playback = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
.ops = {
.open = cs_dig_playback_pcm_open,
.close = cs_dig_playback_pcm_close,
.prepare = cs_dig_playback_pcm_prepare,
.cleanup = cs_dig_playback_pcm_cleanup
},
};
static struct hda_pcm_stream cs_pcm_digital_capture = {
.substreams = 1,
.channels_min = 2,
.channels_max = 2,
};
static int cs_build_pcms(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
struct hda_pcm *info = spec->pcm_rec;
codec->pcm_info = info;
codec->num_pcms = 0;
info->name = "Cirrus Analog";
info->stream[SNDRV_PCM_STREAM_PLAYBACK] = cs_pcm_analog_playback;
info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid = spec->dac_nid[0];
info->stream[SNDRV_PCM_STREAM_PLAYBACK].channels_max =
spec->multiout.max_channels;
info->stream[SNDRV_PCM_STREAM_CAPTURE] = cs_pcm_analog_capture;
info->stream[SNDRV_PCM_STREAM_CAPTURE].nid =
spec->adc_nid[spec->cur_input];
codec->num_pcms++;
if (!spec->multiout.dig_out_nid && !spec->dig_in)
return 0;
info++;
info->name = "Cirrus Digital";
info->pcm_type = spec->autocfg.dig_out_type[0];
if (!info->pcm_type)
info->pcm_type = HDA_PCM_TYPE_SPDIF;
if (spec->multiout.dig_out_nid) {
info->stream[SNDRV_PCM_STREAM_PLAYBACK] =
cs_pcm_digital_playback;
info->stream[SNDRV_PCM_STREAM_PLAYBACK].nid =
spec->multiout.dig_out_nid;
}
if (spec->dig_in) {
info->stream[SNDRV_PCM_STREAM_CAPTURE] =
cs_pcm_digital_capture;
info->stream[SNDRV_PCM_STREAM_CAPTURE].nid = spec->dig_in;
}
codec->num_pcms++;
return 0;
}
/*
* parse codec topology
*/
static hda_nid_t get_dac(struct hda_codec *codec, hda_nid_t pin)
{
hda_nid_t dac;
if (!pin)
return 0;
if (snd_hda_get_connections(codec, pin, &dac, 1) != 1)
return 0;
return dac;
}
static int is_ext_mic(struct hda_codec *codec, unsigned int idx)
{
struct cs_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
hda_nid_t pin = cfg->input_pins[idx];
unsigned int val = snd_hda_query_pin_caps(codec, pin);
if (!(val & AC_PINCAP_PRES_DETECT))
return 0;
val = snd_hda_codec_get_pincfg(codec, pin);
return (get_defcfg_connect(val) == AC_JACK_PORT_COMPLEX);
}
static hda_nid_t get_adc(struct hda_codec *codec, hda_nid_t pin,
unsigned int *idxp)
{
int i;
hda_nid_t nid;
nid = codec->start_nid;
for (i = 0; i < codec->num_nodes; i++, nid++) {
hda_nid_t pins[2];
unsigned int type;
int j, nums;
type = (get_wcaps(codec, nid) & AC_WCAP_TYPE)
>> AC_WCAP_TYPE_SHIFT;
if (type != AC_WID_AUD_IN)
continue;
nums = snd_hda_get_connections(codec, nid, pins,
ARRAY_SIZE(pins));
if (nums <= 0)
continue;
for (j = 0; j < nums; j++) {
if (pins[j] == pin) {
*idxp = j;
return nid;
}
}
}
return 0;
}
static int is_active_pin(struct hda_codec *codec, hda_nid_t nid)
{
unsigned int val;
val = snd_hda_codec_get_pincfg(codec, nid);
return (get_defcfg_connect(val) != AC_JACK_PORT_NONE);
}
static int parse_output(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
int i, extra_nids;
hda_nid_t dac;
for (i = 0; i < cfg->line_outs; i++) {
dac = get_dac(codec, cfg->line_out_pins[i]);
if (!dac)
break;
spec->dac_nid[i] = dac;
}
spec->multiout.num_dacs = i;
spec->multiout.dac_nids = spec->dac_nid;
spec->multiout.max_channels = i * 2;
/* add HP and speakers */
extra_nids = 0;
for (i = 0; i < cfg->hp_outs; i++) {
dac = get_dac(codec, cfg->hp_pins[i]);
if (!dac)
break;
if (!i)
spec->multiout.hp_nid = dac;
else
spec->multiout.extra_out_nid[extra_nids++] = dac;
}
for (i = 0; i < cfg->speaker_outs; i++) {
dac = get_dac(codec, cfg->speaker_pins[i]);
if (!dac)
break;
spec->multiout.extra_out_nid[extra_nids++] = dac;
}
if (cfg->line_out_type == AUTO_PIN_SPEAKER_OUT) {
cfg->speaker_outs = cfg->line_outs;
memcpy(cfg->speaker_pins, cfg->line_out_pins,
sizeof(cfg->speaker_pins));
cfg->line_outs = 0;
}
return 0;
}
static int parse_input(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
int i;
for (i = 0; i < AUTO_PIN_LAST; i++) {
hda_nid_t pin = cfg->input_pins[i];
if (!pin)
continue;
spec->input_idx[spec->num_inputs] = i;
spec->capsrc_idx[i] = spec->num_inputs++;
spec->cur_input = i;
spec->adc_nid[i] = get_adc(codec, pin, &spec->adc_idx[i]);
}
if (!spec->num_inputs)
return 0;
/* check whether the automatic mic switch is available */
if (spec->num_inputs == 2 &&
spec->adc_nid[AUTO_PIN_MIC] && spec->adc_nid[AUTO_PIN_FRONT_MIC]) {
if (is_ext_mic(codec, cfg->input_pins[AUTO_PIN_FRONT_MIC])) {
if (!is_ext_mic(codec, cfg->input_pins[AUTO_PIN_MIC])) {
spec->mic_detect = 1;
spec->automic_idx = AUTO_PIN_FRONT_MIC;
}
} else {
if (is_ext_mic(codec, cfg->input_pins[AUTO_PIN_MIC])) {
spec->mic_detect = 1;
spec->automic_idx = AUTO_PIN_MIC;
}
}
}
return 0;
}
static int parse_digital_output(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
hda_nid_t nid;
if (!cfg->dig_outs)
return 0;
if (snd_hda_get_connections(codec, cfg->dig_out_pins[0], &nid, 1) < 1)
return 0;
spec->multiout.dig_out_nid = nid;
spec->multiout.share_spdif = 1;
if (cfg->dig_outs > 1 &&
snd_hda_get_connections(codec, cfg->dig_out_pins[1], &nid, 1) > 0) {
spec->slave_dig_outs[0] = nid;
codec->slave_dig_outs = spec->slave_dig_outs;
}
return 0;
}
static int parse_digital_input(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
int idx;
if (cfg->dig_in_pin)
spec->dig_in = get_adc(codec, cfg->dig_in_pin, &idx);
return 0;
}
/*
* create mixer controls
*/
static const char *dir_sfx[2] = { "Playback", "Capture" };
static int add_mute(struct hda_codec *codec, const char *name, int index,
unsigned int pval, int dir, struct snd_kcontrol **kctlp)
{
char tmp[44];
struct snd_kcontrol_new knew =
HDA_CODEC_MUTE_IDX(tmp, index, 0, 0, HDA_OUTPUT);
knew.private_value = pval;
snprintf(tmp, sizeof(tmp), "%s %s Switch", name, dir_sfx[dir]);
*kctlp = snd_ctl_new1(&knew, codec);
return snd_hda_ctl_add(codec, get_amp_nid_(pval), *kctlp);
}
static int add_volume(struct hda_codec *codec, const char *name,
int index, unsigned int pval, int dir,
struct snd_kcontrol **kctlp)
{
char tmp[32];
struct snd_kcontrol_new knew =
HDA_CODEC_VOLUME_IDX(tmp, index, 0, 0, HDA_OUTPUT);
knew.private_value = pval;
snprintf(tmp, sizeof(tmp), "%s %s Volume", name, dir_sfx[dir]);
*kctlp = snd_ctl_new1(&knew, codec);
return snd_hda_ctl_add(codec, get_amp_nid_(pval), *kctlp);
}
static void fix_volume_caps(struct hda_codec *codec, hda_nid_t dac)
{
unsigned int caps;
/* set the upper-limit for mixer amp to 0dB */
caps = query_amp_caps(codec, dac, HDA_OUTPUT);
caps &= ~(0x7f << AC_AMPCAP_NUM_STEPS_SHIFT);
caps |= ((caps >> AC_AMPCAP_OFFSET_SHIFT) & 0x7f)
<< AC_AMPCAP_NUM_STEPS_SHIFT;
snd_hda_override_amp_caps(codec, dac, HDA_OUTPUT, caps);
}
static int add_vmaster(struct hda_codec *codec, hda_nid_t dac)
{
struct cs_spec *spec = codec->spec;
unsigned int tlv[4];
int err;
spec->vmaster_sw =
snd_ctl_make_virtual_master("Master Playback Switch", NULL);
err = snd_hda_ctl_add(codec, dac, spec->vmaster_sw);
if (err < 0)
return err;
snd_hda_set_vmaster_tlv(codec, dac, HDA_OUTPUT, tlv);
spec->vmaster_vol =
snd_ctl_make_virtual_master("Master Playback Volume", tlv);
err = snd_hda_ctl_add(codec, dac, spec->vmaster_vol);
if (err < 0)
return err;
return 0;
}
static int add_output(struct hda_codec *codec, hda_nid_t dac, int idx,
int num_ctls, int type)
{
struct cs_spec *spec = codec->spec;
const char *name;
int err, index;
struct snd_kcontrol *kctl;
static char *speakers[] = {
"Front Speaker", "Surround Speaker", "Bass Speaker"
};
static char *line_outs[] = {
"Front Line-Out", "Surround Line-Out", "Bass Line-Out"
};
fix_volume_caps(codec, dac);
if (!spec->vmaster_sw) {
err = add_vmaster(codec, dac);
if (err < 0)
return err;
}
index = 0;
switch (type) {
case AUTO_PIN_HP_OUT:
name = "Headphone";
index = idx;
break;
case AUTO_PIN_SPEAKER_OUT:
if (num_ctls > 1)
name = speakers[idx];
else
name = "Speaker";
break;
default:
if (num_ctls > 1)
name = line_outs[idx];
else
name = "Line-Out";
break;
}
err = add_mute(codec, name, index,
HDA_COMPOSE_AMP_VAL(dac, 3, 0, HDA_OUTPUT), 0, &kctl);
if (err < 0)
return err;
err = snd_ctl_add_slave(spec->vmaster_sw, kctl);
if (err < 0)
return err;
err = add_volume(codec, name, index,
HDA_COMPOSE_AMP_VAL(dac, 3, 0, HDA_OUTPUT), 0, &kctl);
if (err < 0)
return err;
err = snd_ctl_add_slave(spec->vmaster_vol, kctl);
if (err < 0)
return err;
return 0;
}
static int build_output(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
int i, err;
for (i = 0; i < cfg->line_outs; i++) {
err = add_output(codec, get_dac(codec, cfg->line_out_pins[i]),
i, cfg->line_outs, cfg->line_out_type);
if (err < 0)
return err;
}
for (i = 0; i < cfg->hp_outs; i++) {
err = add_output(codec, get_dac(codec, cfg->hp_pins[i]),
i, cfg->hp_outs, AUTO_PIN_HP_OUT);
if (err < 0)
return err;
}
for (i = 0; i < cfg->speaker_outs; i++) {
err = add_output(codec, get_dac(codec, cfg->speaker_pins[i]),
i, cfg->speaker_outs, AUTO_PIN_SPEAKER_OUT);
if (err < 0)
return err;
}
return 0;
}
/*
*/
static struct snd_kcontrol_new cs_capture_ctls[] = {
HDA_BIND_SW("Capture Switch", 0),
HDA_BIND_VOL("Capture Volume", 0),
};
static int change_cur_input(struct hda_codec *codec, unsigned int idx,
int force)
{
struct cs_spec *spec = codec->spec;
if (spec->cur_input == idx && !force)
return 0;
if (spec->cur_adc && spec->cur_adc != spec->adc_nid[idx]) {
/* stream is running, let's swap the current ADC */
snd_hda_codec_cleanup_stream(codec, spec->cur_adc);
spec->cur_adc = spec->adc_nid[idx];
snd_hda_codec_setup_stream(codec, spec->cur_adc,
spec->cur_adc_stream_tag, 0,
spec->cur_adc_format);
}
snd_hda_codec_write(codec, spec->cur_adc, 0,
AC_VERB_SET_CONNECT_SEL,
spec->adc_idx[idx]);
spec->cur_input = idx;
return 1;
}
static int cs_capture_source_info(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_info *uinfo)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct cs_spec *spec = codec->spec;
unsigned int idx;
uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
uinfo->count = 1;
uinfo->value.enumerated.items = spec->num_inputs;
if (uinfo->value.enumerated.item >= spec->num_inputs)
uinfo->value.enumerated.item = spec->num_inputs - 1;
idx = spec->input_idx[uinfo->value.enumerated.item];
strcpy(uinfo->value.enumerated.name, auto_pin_cfg_labels[idx]);
return 0;
}
static int cs_capture_source_get(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct cs_spec *spec = codec->spec;
ucontrol->value.enumerated.item[0] = spec->capsrc_idx[spec->cur_input];
return 0;
}
static int cs_capture_source_put(struct snd_kcontrol *kcontrol,
struct snd_ctl_elem_value *ucontrol)
{
struct hda_codec *codec = snd_kcontrol_chip(kcontrol);
struct cs_spec *spec = codec->spec;
unsigned int idx = ucontrol->value.enumerated.item[0];
if (idx >= spec->num_inputs)
return -EINVAL;
idx = spec->input_idx[idx];
return change_cur_input(codec, idx, 0);
}
static struct snd_kcontrol_new cs_capture_source = {
.iface = SNDRV_CTL_ELEM_IFACE_MIXER,
.name = "Capture Source",
.access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
.info = cs_capture_source_info,
.get = cs_capture_source_get,
.put = cs_capture_source_put,
};
static struct hda_bind_ctls *make_bind_capture(struct hda_codec *codec,
struct hda_ctl_ops *ops)
{
struct cs_spec *spec = codec->spec;
struct hda_bind_ctls *bind;
int i, n;
bind = kzalloc(sizeof(*bind) + sizeof(long) * (spec->num_inputs + 1),
GFP_KERNEL);
if (!bind)
return NULL;
bind->ops = ops;
n = 0;
for (i = 0; i < AUTO_PIN_LAST; i++) {
if (!spec->adc_nid[i])
continue;
bind->values[n++] =
HDA_COMPOSE_AMP_VAL(spec->adc_nid[i], 3,
spec->adc_idx[i], HDA_INPUT);
}
return bind;
}
static int build_input(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
int i, err;
if (!spec->num_inputs)
return 0;
/* make bind-capture */
spec->capture_bind[0] = make_bind_capture(codec, &snd_hda_bind_sw);
spec->capture_bind[1] = make_bind_capture(codec, &snd_hda_bind_vol);
for (i = 0; i < 2; i++) {
struct snd_kcontrol *kctl;
if (!spec->capture_bind[i])
return -ENOMEM;
kctl = snd_ctl_new1(&cs_capture_ctls[i], codec);
if (!kctl)
return -ENOMEM;
kctl->private_value = (long)spec->capture_bind[i];
err = snd_hda_ctl_add(codec, 0, kctl);
if (err < 0)
return err;
}
if (spec->num_inputs > 1 && !spec->mic_detect) {
err = snd_hda_ctl_add(codec, 0,
snd_ctl_new1(&cs_capture_source, codec));
if (err < 0)
return err;
}
return 0;
}
/*
*/
static int build_digital_output(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
int err;
if (!spec->multiout.dig_out_nid)
return 0;
err = snd_hda_create_spdif_out_ctls(codec, spec->multiout.dig_out_nid);
if (err < 0)
return err;
err = snd_hda_create_spdif_share_sw(codec, &spec->multiout);
if (err < 0)
return err;
return 0;
}
static int build_digital_input(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
if (spec->dig_in)
return snd_hda_create_spdif_in_ctls(codec, spec->dig_in);
return 0;
}
/*
* auto-mute and auto-mic switching
*/
static void cs_automute(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
unsigned int caps, hp_present;
hda_nid_t nid;
int i;
hp_present = 0;
for (i = 0; i < cfg->hp_outs; i++) {
nid = cfg->hp_pins[i];
caps = snd_hda_query_pin_caps(codec, nid);
if (!(caps & AC_PINCAP_PRES_DETECT))
continue;
hp_present = snd_hda_jack_detect(codec, nid);
if (hp_present)
break;
}
for (i = 0; i < cfg->speaker_outs; i++) {
nid = cfg->speaker_pins[i];
snd_hda_codec_write(codec, nid, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL,
hp_present ? 0 : PIN_OUT);
}
if (spec->board_config == CS420X_MBP55 ||
spec->board_config == CS420X_IMAC27) {
unsigned int gpio = hp_present ? 0x02 : 0x08;
snd_hda_codec_write(codec, 0x01, 0,
AC_VERB_SET_GPIO_DATA, gpio);
}
}
static void cs_automic(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
hda_nid_t nid;
unsigned int present;
nid = cfg->input_pins[spec->automic_idx];
present = snd_hda_jack_detect(codec, nid);
if (present)
change_cur_input(codec, spec->automic_idx, 0);
else {
unsigned int imic = (spec->automic_idx == AUTO_PIN_MIC) ?
AUTO_PIN_FRONT_MIC : AUTO_PIN_MIC;
change_cur_input(codec, imic, 0);
}
}
/*
*/
static void init_output(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
int i;
/* mute first */
for (i = 0; i < spec->multiout.num_dacs; i++)
snd_hda_codec_write(codec, spec->multiout.dac_nids[i], 0,
AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE);
if (spec->multiout.hp_nid)
snd_hda_codec_write(codec, spec->multiout.hp_nid, 0,
AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE);
for (i = 0; i < ARRAY_SIZE(spec->multiout.extra_out_nid); i++) {
if (!spec->multiout.extra_out_nid[i])
break;
snd_hda_codec_write(codec, spec->multiout.extra_out_nid[i], 0,
AC_VERB_SET_AMP_GAIN_MUTE, AMP_OUT_MUTE);
}
/* set appropriate pin controls */
for (i = 0; i < cfg->line_outs; i++)
snd_hda_codec_write(codec, cfg->line_out_pins[i], 0,
AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT);
for (i = 0; i < cfg->hp_outs; i++) {
hda_nid_t nid = cfg->hp_pins[i];
snd_hda_codec_write(codec, nid, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_HP);
if (!cfg->speaker_outs)
continue;
if (get_wcaps(codec, nid) & AC_WCAP_UNSOL_CAP) {
snd_hda_codec_write(codec, nid, 0,
AC_VERB_SET_UNSOLICITED_ENABLE,
AC_USRSP_EN | HP_EVENT);
spec->hp_detect = 1;
}
}
for (i = 0; i < cfg->speaker_outs; i++)
snd_hda_codec_write(codec, cfg->speaker_pins[i], 0,
AC_VERB_SET_PIN_WIDGET_CONTROL, PIN_OUT);
if (spec->hp_detect)
cs_automute(codec);
}
static void init_input(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
struct auto_pin_cfg *cfg = &spec->autocfg;
unsigned int coef;
int i;
for (i = 0; i < AUTO_PIN_LAST; i++) {
unsigned int ctl;
hda_nid_t pin = cfg->input_pins[i];
if (!pin || !spec->adc_nid[i])
continue;
/* set appropriate pin control and mute first */
ctl = PIN_IN;
if (i <= AUTO_PIN_FRONT_MIC) {
unsigned int caps = snd_hda_query_pin_caps(codec, pin);
caps >>= AC_PINCAP_VREF_SHIFT;
if (caps & AC_PINCAP_VREF_80)
ctl = PIN_VREF80;
}
snd_hda_codec_write(codec, pin, 0,
AC_VERB_SET_PIN_WIDGET_CONTROL, ctl);
snd_hda_codec_write(codec, spec->adc_nid[i], 0,
AC_VERB_SET_AMP_GAIN_MUTE,
AMP_IN_MUTE(spec->adc_idx[i]));
if (spec->mic_detect && spec->automic_idx == i)
snd_hda_codec_write(codec, pin, 0,
AC_VERB_SET_UNSOLICITED_ENABLE,
AC_USRSP_EN | MIC_EVENT);
}
change_cur_input(codec, spec->cur_input, 1);
if (spec->mic_detect)
cs_automic(codec);
coef = 0x000a; /* ADC1/2 - Digital and Analog Soft Ramp */
if (is_active_pin(codec, CS_DMIC2_PIN_NID))
coef |= 0x0500; /* DMIC2 enable 2 channels, disable GPIO1 */
if (is_active_pin(codec, CS_DMIC1_PIN_NID))
coef |= 0x1800; /* DMIC1 enable 2 channels, disable GPIO0
* No effect if SPDIF_OUT2 is selected in
* IDX_SPDIF_CTL.
*/
cs_vendor_coef_set(codec, IDX_ADC_CFG, coef);
}
static struct hda_verb cs_coef_init_verbs[] = {
{0x11, AC_VERB_SET_PROC_STATE, 1},
{0x11, AC_VERB_SET_COEF_INDEX, IDX_DAC_CFG},
{0x11, AC_VERB_SET_PROC_COEF,
(0x002a /* DAC1/2/3 SZCMode Soft Ramp */
| 0x0040 /* Mute DACs on FIFO error */
| 0x1000 /* Enable DACs High Pass Filter */
| 0x0400 /* Disable Coefficient Auto increment */
)},
/* Beep */
{0x11, AC_VERB_SET_COEF_INDEX, IDX_DAC_CFG},
{0x11, AC_VERB_SET_PROC_COEF, 0x0007}, /* Enable Beep thru DAC1/2/3 */
{} /* terminator */
};
/* SPDIF setup */
static void init_digital(struct hda_codec *codec)
{
unsigned int coef;
coef = 0x0002; /* SRC_MUTE soft-mute on SPDIF (if no lock) */
coef |= 0x0008; /* Replace with mute on error */
if (is_active_pin(codec, CS_DIG_OUT2_PIN_NID))
coef |= 0x4000; /* RX to TX1 or TX2 Loopthru / SPDIF2
* SPDIF_OUT2 is shared with GPIO1 and
* DMIC_SDA2.
*/
cs_vendor_coef_set(codec, IDX_SPDIF_CTL, coef);
}
static int cs_init(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
snd_hda_sequence_write(codec, cs_coef_init_verbs);
if (spec->gpio_mask) {
snd_hda_codec_write(codec, 0x01, 0, AC_VERB_SET_GPIO_MASK,
spec->gpio_mask);
snd_hda_codec_write(codec, 0x01, 0, AC_VERB_SET_GPIO_DIRECTION,
spec->gpio_dir);
snd_hda_codec_write(codec, 0x01, 0, AC_VERB_SET_GPIO_DATA,
spec->gpio_data);
}
init_output(codec);
init_input(codec);
init_digital(codec);
return 0;
}
static int cs_build_controls(struct hda_codec *codec)
{
int err;
err = build_output(codec);
if (err < 0)
return err;
err = build_input(codec);
if (err < 0)
return err;
err = build_digital_output(codec);
if (err < 0)
return err;
err = build_digital_input(codec);
if (err < 0)
return err;
return cs_init(codec);
}
static void cs_free(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
kfree(spec->capture_bind[0]);
kfree(spec->capture_bind[1]);
kfree(codec->spec);
}
static void cs_unsol_event(struct hda_codec *codec, unsigned int res)
{
switch ((res >> 26) & 0x7f) {
case HP_EVENT:
cs_automute(codec);
break;
case MIC_EVENT:
cs_automic(codec);
break;
}
}
static struct hda_codec_ops cs_patch_ops = {
.build_controls = cs_build_controls,
.build_pcms = cs_build_pcms,
.init = cs_init,
.free = cs_free,
.unsol_event = cs_unsol_event,
};
static int cs_parse_auto_config(struct hda_codec *codec)
{
struct cs_spec *spec = codec->spec;
int err;
err = snd_hda_parse_pin_def_config(codec, &spec->autocfg, NULL);
if (err < 0)
return err;
err = parse_output(codec);
if (err < 0)
return err;
err = parse_input(codec);
if (err < 0)
return err;
err = parse_digital_output(codec);
if (err < 0)
return err;
err = parse_digital_input(codec);
if (err < 0)
return err;
return 0;
}
static const char *cs420x_models[CS420X_MODELS] = {
[CS420X_MBP55] = "mbp55",
[CS420X_IMAC27] = "imac27",
[CS420X_AUTO] = "auto",
};
static struct snd_pci_quirk cs420x_cfg_tbl[] = {
SND_PCI_QUIRK(0x10de, 0xcb79, "MacBookPro 5,5", CS420X_MBP55),
SND_PCI_QUIRK(0x8086, 0x7270, "IMac 27 Inch", CS420X_IMAC27),
{} /* terminator */
};
struct cs_pincfg {
hda_nid_t nid;
u32 val;
};
static struct cs_pincfg mbp55_pincfgs[] = {
{ 0x09, 0x012b4030 },
{ 0x0a, 0x90100121 },
{ 0x0b, 0x90100120 },
{ 0x0c, 0x400000f0 },
{ 0x0d, 0x90a00110 },
{ 0x0e, 0x400000f0 },
{ 0x0f, 0x400000f0 },
{ 0x10, 0x014be040 },
{ 0x12, 0x400000f0 },
{ 0x15, 0x400000f0 },
{} /* terminator */
};
static struct cs_pincfg imac27_pincfgs[] = {
{ 0x09, 0x012b4050 },
{ 0x0a, 0x90100140 },
{ 0x0b, 0x90100142 },
{ 0x0c, 0x018b3020 },
{ 0x0d, 0x90a00110 },
{ 0x0e, 0x400000f0 },
{ 0x0f, 0x01cbe030 },
{ 0x10, 0x014be060 },
{ 0x12, 0x01ab9070 },
{ 0x15, 0x400000f0 },
{} /* terminator */
};
static struct cs_pincfg *cs_pincfgs[CS420X_MODELS] = {
[CS420X_MBP55] = mbp55_pincfgs,
[CS420X_IMAC27] = imac27_pincfgs,
};
static void fix_pincfg(struct hda_codec *codec, int model)
{
const struct cs_pincfg *cfg = cs_pincfgs[model];
if (!cfg)
return;
for (; cfg->nid; cfg++)
snd_hda_codec_set_pincfg(codec, cfg->nid, cfg->val);
}
static int patch_cs420x(struct hda_codec *codec)
{
struct cs_spec *spec;
int err;
spec = kzalloc(sizeof(*spec), GFP_KERNEL);
if (!spec)
return -ENOMEM;
codec->spec = spec;
spec->board_config =
snd_hda_check_board_config(codec, CS420X_MODELS,
cs420x_models, cs420x_cfg_tbl);
if (spec->board_config >= 0)
fix_pincfg(codec, spec->board_config);
switch (spec->board_config) {
case CS420X_IMAC27:
case CS420X_MBP55:
/* GPIO1 = headphones */
/* GPIO3 = speakers */
spec->gpio_mask = 0x0a;
spec->gpio_dir = 0x0a;
break;
}
err = cs_parse_auto_config(codec);
if (err < 0)
goto error;
codec->patch_ops = cs_patch_ops;
return 0;
error:
kfree(codec->spec);
codec->spec = NULL;
return err;
}
/*
* patch entries
*/
static struct hda_codec_preset snd_hda_preset_cirrus[] = {
{ .id = 0x10134206, .name = "CS4206", .patch = patch_cs420x },
{ .id = 0x10134207, .name = "CS4207", .patch = patch_cs420x },
{} /* terminator */
};
MODULE_ALIAS("snd-hda-codec-id:10134206");
MODULE_ALIAS("snd-hda-codec-id:10134207");
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Cirrus Logic HD-audio codec");
static struct hda_codec_preset_list cirrus_list = {
.preset = snd_hda_preset_cirrus,
.owner = THIS_MODULE,
};
static int __init patch_cirrus_init(void)
{
return snd_hda_add_codec_preset(&cirrus_list);
}
static void __exit patch_cirrus_exit(void)
{
snd_hda_delete_codec_preset(&cirrus_list);
}
module_init(patch_cirrus_init)
module_exit(patch_cirrus_exit)
| {
"pile_set_name": "Github"
} |
use ExtUtils::MakeMaker;
# See lib/ExtUtils/MakeMaker.pm for details of how to influence
# the contents of the Makefile that is written.
WriteMakefile(
'NAME' => 'Crypt::CBC',
'VERSION_FROM' => 'CBC.pm', # finds $VERSION
'PREREQ_PM' => {'Digest::MD5' => '2.00' },
'LIBS' => [''], # e.g., '-lm'
'DEFINE' => '', # e.g., '-DHAVE_SOMETHING'
'INC' => '', # e.g., '-I/usr/include/other'
'dist' => {'COMPRESS'=>'gzip -9f', 'SUFFIX' => 'gz',
'ZIP'=>'/usr/bin/zip','ZIPFLAGS'=>'-rl'}
);
| {
"pile_set_name": "Github"
} |
// (C) Copyright Gennadiy Rozental 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)
// See http://www.boost.org/libs/test for the library home page.
//
// File : $RCSfile$
//
// Version : $Revision$
//
// Description : simple facilities for accessing type information at runtime
// ***************************************************************************
#ifndef BOOST_TEST_UTILS_RTTI_HPP
#define BOOST_TEST_UTILS_RTTI_HPP
// C Runtime
#include <cstddef>
#include <boost/test/detail/config.hpp>
namespace boost {
namespace rtti {
// ************************************************************************** //
// ************** rtti::type_id ************** //
// ************************************************************************** //
typedef std::ptrdiff_t id_t;
namespace rtti_detail {
template<typename T>
struct BOOST_TEST_DECL rttid_holder {
static id_t id() { return reinterpret_cast<id_t>( &inst() ); }
private:
struct rttid {};
static rttid const& inst() { static rttid s_inst; return s_inst; }
};
} // namespace rtti_detail
//____________________________________________________________________________//
template<typename T>
BOOST_TEST_DECL inline id_t
type_id()
{
return rtti_detail::rttid_holder<T>::id();
}
//____________________________________________________________________________//
#define BOOST_RTTI_SWITCH( type_id_ ) if( ::boost::rtti::id_t switch_by_id = type_id_ )
#define BOOST_RTTI_CASE( type ) if( switch_by_id == ::boost::rtti::type_id<type>() )
//____________________________________________________________________________//
} // namespace rtti
} // namespace boost
#endif // BOOST_TEST_UTILS_RTTI_HPP
| {
"pile_set_name": "Github"
} |
// Copyright 2014 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.
/*
The benchcmp command displays performance changes between benchmarks.
Benchcmp parses the output of two 'go test' benchmark runs,
correlates the results per benchmark, and displays the deltas.
To measure the performance impact of a change, use 'go test'
to run benchmarks before and after the change:
go test -run=NONE -bench=. ./... > old.txt
# make changes
go test -run=NONE -bench=. ./... > new.txt
Then feed the benchmark results to benchcmp:
benchcmp old.txt new.txt
Benchcmp will summarize and display the performance changes,
in a format like this:
$ benchcmp old.txt new.txt
benchmark old ns/op new ns/op delta
BenchmarkConcat 523 68.6 -86.88%
benchmark old allocs new allocs delta
BenchmarkConcat 3 1 -66.67%
benchmark old bytes new bytes delta
BenchmarkConcat 80 48 -40.00%
*/
package main // import "golang.org/x/tools/cmd/benchcmp"
| {
"pile_set_name": "Github"
} |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Capabilities gradeexport plugin.
*
* @package gradeexport_xml
* @copyright 2007 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$capabilities = array(
'gradeexport/xml:view' => array(
'riskbitmask' => RISK_PERSONAL,
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'archetypes' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'manager' => CAP_ALLOW
)
),
'gradeexport/xml:publish' => array(
'riskbitmask' => RISK_PERSONAL,
'captype' => 'read',
'contextlevel' => CONTEXT_COURSE,
'archetypes' => array(
'manager' => CAP_ALLOW
)
)
);
| {
"pile_set_name": "Github"
} |
source include/master-slave.inc;
connection master;
CREATE TABLE t1 (
a int not null,
b char (10) not null,
doc document) engine=innodb;
insert into t1 values (1,'@1','{ "id":101, "name":"Alex", "phone":6507770001, "address":{ "houseNumber":1001, "streetName":"1st", "zipcode":98761, "state":"CA" }, "intstr":"1001", "dt":"1001" }');
insert into t1 values (2,'@2','{ "id":102, "name":"Bob", "phone":6507770002, "address":{ "houseNumber":1002, "streetName":"2nd", "zipcode":98762, "state":"AZ" }, "int64":2222222220123456789, "intstr":"1002", "dt":"0123456789ABCDEFGHIGKLMNOPQRSTUVWXYZ0123456789" }');
sync_slave_with_master;
select * from t1;
connection master;
drop table t1;
source include/rpl_end.inc;
| {
"pile_set_name": "Github"
} |
/*
* Copyright 2014 Guidewire Software, Inc.
*/
package gw.internal.gosu.compiler;
import gw.test.TestClass;
import gw.lang.reflect.gs.BytecodeOptions;
/**
* Created by IntelliJ IDEA.
* User: akeefer
* Date: Oct 1, 2009
* Time: 4:52:36 PM
* To change this template use File | Settings | File Templates.
*/
public class GosuSpecTestBase extends TestClass {
private static GosuSpecTestFixture _fixtureDelegate;
@Override
public void beforeTestClass() {
_fixtureDelegate = new GosuSpecBytecodeTestFixture();
// _fixtureDelegate = new GosuSpecInterpretedTestFixture();
}
protected Object newInstance(String typeName) {
return _fixtureDelegate.newInstance(typeName);
}
protected Object invokeMethod(Object context, String methodName, Object... args) {
return _fixtureDelegate.invokeMethod(context, methodName, args);
}
protected Object invokeStaticMethod(String typeName, String methodName, Object... args) {
return _fixtureDelegate.invokeStaticMethod(typeName, methodName, args);
}
}
| {
"pile_set_name": "Github"
} |
from __future__ import print_function
import codecs
import os
import re
from setuptools import setup
def read(filename):
"""Read and return `filename` in root dir of project and return string"""
here = os.path.abspath(os.path.dirname(__file__))
return codecs.open(os.path.join(here, filename), 'r').read()
# https://github.com/kennethreitz/requests/blob/master/setup.py#L32
with open('piazza_api/__init__.py', 'r') as fd:
version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"]',
fd.read(), re.MULTILINE).group(1)
install_requires = read("requirements.txt").split()
long_description = read('README.md')
setup(
name='piazza-api',
version=version,
url='http://github.com/hfaran/piazza-api/',
license='MIT License',
author='Hamza Faran',
install_requires=install_requires,
description="Unofficial Client for Piazza's Internal API",
long_description=long_description,
long_description_content_type='text/markdown',
packages=['piazza_api'],
platforms='any',
classifiers = [
'Programming Language :: Python',
'Development Status :: 3 - Alpha',
'Natural Language :: English',
'Environment :: Web Environment',
'Intended Audience :: Developers',
"License :: OSI Approved :: MIT License",
'Operating System :: OS Independent',
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| {
"pile_set_name": "Github"
} |
/**
* An implementation of a hash-table using open addressing with linear probing as a collision
* resolution method.
*
* @author William Fiset, [email protected]
*/
package com.williamfiset.algorithms.datastructures.hashtable;
public class HashTableLinearProbing<K, V> extends HashTableOpenAddressingBase<K, V> {
// This is the linear constant used in the linear probing, it can be
// any positive number. The table capacity will be adjusted so that
// the GCD(capacity, LINEAR_CONSTANT) = 1 so that all buckets can be probed.
private static final int LINEAR_CONSTANT = 17;
public HashTableLinearProbing() {
super();
}
public HashTableLinearProbing(int capacity) {
super(capacity);
}
public HashTableLinearProbing(int capacity, double loadFactor) {
super(capacity, loadFactor);
}
@Override
protected void setupProbing(K key) {}
@Override
protected int probe(int x) {
return LINEAR_CONSTANT * x;
}
// Adjust the capacity so that the linear constant and
// the table capacity are relatively prime.
@Override
protected void adjustCapacity() {
while (gcd(LINEAR_CONSTANT, capacity) != 1) {
capacity++;
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright © 2008 Chris Wilson
*
* Permission to use, copy, modify, distribute, and sell this software
* and its documentation for any purpose is hereby granted without
* fee, provided that the above copyright notice appear in all copies
* and that both that copyright notice and this permission notice
* appear in supporting documentation, and that the name of
* Chris Wilson not be used in advertising or publicity pertaining to
* distribution of the software without specific, written prior
* permission. Chris Wilson makes no representations about the
* suitability of this software for any purpose. It is provided "as
* is" without express or implied warranty.
*
* CHRIS WILSON DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
* SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS, IN NO EVENT SHALL CHRIS WILSON BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
* Author: Chris Wilson <[email protected]>
*/
#include "cairo-test.h"
#include <assert.h>
/* Test the idempotency of write_png->read_png */
#define RGB_MASK 0x00ffffff
static cairo_bool_t
image_surface_equals (cairo_surface_t *A, cairo_surface_t *B)
{
if (cairo_image_surface_get_format (A) !=
cairo_image_surface_get_format (B))
return 0;
if (cairo_image_surface_get_width (A) !=
cairo_image_surface_get_width (B))
return 0;
if (cairo_image_surface_get_height (A) !=
cairo_image_surface_get_height (B))
return 0;
return 1;
}
static const char *
format_to_string (cairo_format_t format)
{
switch (format) {
case CAIRO_FORMAT_A1: return "a1";
case CAIRO_FORMAT_A8: return "a8";
case CAIRO_FORMAT_RGB16_565: return "rgb16";
case CAIRO_FORMAT_RGB24: return "rgb24";
case CAIRO_FORMAT_RGB30: return "rgb30";
case CAIRO_FORMAT_ARGB32: return "argb32";
case CAIRO_FORMAT_INVALID:
default: return "???";
}
}
static void
print_surface (const cairo_test_context_t *ctx, cairo_surface_t *surface)
{
cairo_test_log (ctx,
"%s (%dx%d)\n",
format_to_string (cairo_image_surface_get_format (surface)),
cairo_image_surface_get_width (surface),
cairo_image_surface_get_height (surface));
}
static cairo_test_status_t
preamble (cairo_test_context_t *ctx)
{
const char *filename = "png.out.png";
cairo_surface_t *surface0, *surface1;
cairo_status_t status;
uint32_t argb32 = 0xdeadbede;
surface0 = cairo_image_surface_create_for_data ((unsigned char *) &argb32,
CAIRO_FORMAT_ARGB32,
1, 1, 4);
status = cairo_surface_write_to_png (surface0, filename);
if (status) {
cairo_test_log (ctx, "Error writing '%s': %s\n",
filename, cairo_status_to_string (status));
cairo_surface_destroy (surface0);
return cairo_test_status_from_status (ctx, status);
}
surface1 = cairo_image_surface_create_from_png (filename);
status = cairo_surface_status (surface1);
if (status) {
cairo_test_log (ctx, "Error reading '%s': %s\n",
filename, cairo_status_to_string (status));
cairo_surface_destroy (surface1);
cairo_surface_destroy (surface0);
return cairo_test_status_from_status (ctx, status);
}
if (! image_surface_equals (surface0, surface1)) {
cairo_test_log (ctx, "Error surface mismatch.\n");
cairo_test_log (ctx, "to png: "); print_surface (ctx, surface0);
cairo_test_log (ctx, "from png: "); print_surface (ctx, surface1);
cairo_surface_destroy (surface0);
cairo_surface_destroy (surface1);
return CAIRO_TEST_FAILURE;
}
assert (*(uint32_t *) cairo_image_surface_get_data (surface1) == argb32);
cairo_surface_destroy (surface0);
cairo_surface_destroy (surface1);
surface0 = cairo_image_surface_create_for_data ((unsigned char *) &argb32,
CAIRO_FORMAT_RGB24,
1, 1, 4);
status = cairo_surface_write_to_png (surface0, filename);
if (status) {
cairo_test_log (ctx, "Error writing '%s': %s\n",
filename, cairo_status_to_string (status));
cairo_surface_destroy (surface0);
return cairo_test_status_from_status (ctx, status);
}
surface1 = cairo_image_surface_create_from_png (filename);
status = cairo_surface_status (surface1);
if (status) {
cairo_test_log (ctx, "Error reading '%s': %s\n",
filename, cairo_status_to_string (status));
cairo_surface_destroy (surface1);
cairo_surface_destroy (surface0);
return cairo_test_status_from_status (ctx, status);
}
if (! image_surface_equals (surface0, surface1)) {
cairo_test_log (ctx, "Error surface mismatch.\n");
cairo_test_log (ctx, "to png: "); print_surface (ctx, surface0);
cairo_test_log (ctx, "from png: "); print_surface (ctx, surface1);
cairo_surface_destroy (surface0);
cairo_surface_destroy (surface1);
return CAIRO_TEST_FAILURE;
}
assert ((*(uint32_t *) cairo_image_surface_get_data (surface1) & RGB_MASK)
== (argb32 & RGB_MASK));
cairo_surface_destroy (surface0);
cairo_surface_destroy (surface1);
return CAIRO_TEST_SUCCESS;
}
CAIRO_TEST (png,
"Check that the png export/import is idempotent.",
"png, api", /* keywords */
NULL, /* requirements */
0, 0,
preamble, NULL)
| {
"pile_set_name": "Github"
} |
<!DOCTYPE html>
<!--
Template Name: Metronic - Responsive Admin Dashboard Template build with Twitter Bootstrap 3.3.2
Version: 3.7.0
Author: KeenThemes
Website: http://www.keenthemes.com/
Contact: [email protected]
Follow: www.twitter.com/keenthemes
Like: www.facebook.com/keenthemes
Purchase: http://themeforest.net/item/metronic-responsive-admin-dashboard-template/4021469?ref=keenthemes
License: You must have a valid license purchased only from themeforest(the above link) in order to legally use the theme for your project.
-->
<!--[if IE 8]> <html lang="en" class="ie8 no-js"> <![endif]-->
<!--[if IE 9]> <html lang="en" class="ie9 no-js"> <![endif]-->
<!--[if !IE]><!-->
<html lang="en">
<!--<![endif]-->
<!-- BEGIN HEAD -->
<head>
<meta charset="utf-8"/>
<title>Metronic | eCommerce - Products</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta content="" name="description"/>
<meta content="" name="author"/>
<!-- BEGIN GLOBAL MANDATORY STYLES -->
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700&subset=all" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/simple-line-icons/simple-line-icons.min.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/uniform/css/uniform.default.css" rel="stylesheet" type="text/css">
<link href="../../assets/global/plugins/bootstrap-switch/css/bootstrap-switch.min.css" rel="stylesheet" type="text/css"/>
<!-- END GLOBAL MANDATORY STYLES -->
<!-- BEGIN PAGE LEVEL STYLES -->
<link rel="stylesheet" type="text/css" href="../../assets/global/plugins/select2/select2.css"/>
<link rel="stylesheet" type="text/css" href="../../assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="../../assets/global/plugins/bootstrap-datepicker/css/datepicker.css"/>
<!-- END PAGE LEVEL STYLES -->
<!-- BEGIN THEME STYLES -->
<link href="../../assets/global/css/components-rounded.css" id="style_components" rel="stylesheet" type="text/css"/>
<link href="../../assets/global/css/plugins.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/admin/layout4/css/layout.css" rel="stylesheet" type="text/css"/>
<link id="style_color" href="../../assets/admin/layout4/css/themes/light.css" rel="stylesheet" type="text/css"/>
<link href="../../assets/admin/layout4/css/custom.css" rel="stylesheet" type="text/css"/>
<!-- END THEME STYLES -->
<link rel="shortcut icon" href="favicon.ico"/>
</head>
<!-- END HEAD -->
<!-- BEGIN BODY -->
<!-- DOC: Apply "page-header-fixed-mobile" and "page-footer-fixed-mobile" class to body element to force fixed header or footer in mobile devices -->
<!-- DOC: Apply "page-sidebar-closed" class to the body and "page-sidebar-menu-closed" class to the sidebar menu element to hide the sidebar by default -->
<!-- DOC: Apply "page-sidebar-hide" class to the body to make the sidebar completely hidden on toggle -->
<!-- DOC: Apply "page-sidebar-closed-hide-logo" class to the body element to make the logo hidden on sidebar toggle -->
<!-- DOC: Apply "page-sidebar-hide" class to body element to completely hide the sidebar on sidebar toggle -->
<!-- DOC: Apply "page-sidebar-fixed" class to have fixed sidebar -->
<!-- DOC: Apply "page-footer-fixed" class to the body element to have fixed footer -->
<!-- DOC: Apply "page-sidebar-reversed" class to put the sidebar on the right side -->
<!-- DOC: Apply "page-full-width" class to the body element to have full width page without the sidebar menu -->
<body class="page-header-fixed page-sidebar-closed-hide-logo ">
<!-- BEGIN HEADER -->
<div class="page-header navbar navbar-fixed-top">
<!-- BEGIN HEADER INNER -->
<div class="page-header-inner">
<!-- BEGIN LOGO -->
<div class="page-logo">
<a href="index.html">
<img src="../../assets/admin/layout4/img/logo-light.png" alt="logo" class="logo-default"/>
</a>
<div class="menu-toggler sidebar-toggler">
<!-- DOC: Remove the above "hide" to enable the sidebar toggler button on header -->
</div>
</div>
<!-- END LOGO -->
<!-- BEGIN RESPONSIVE MENU TOGGLER -->
<a href="javascript:;" class="menu-toggler responsive-toggler" data-toggle="collapse" data-target=".navbar-collapse">
</a>
<!-- END RESPONSIVE MENU TOGGLER -->
<!-- BEGIN PAGE ACTIONS -->
<!-- DOC: Remove "hide" class to enable the page header actions -->
<div class="page-actions">
<div class="btn-group">
<button type="button" class="btn red-haze btn-sm dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<span class="hidden-sm hidden-xs">Actions </span><i class="fa fa-angle-down"></i>
</button>
<ul class="dropdown-menu" role="menu">
<li>
<a href="javascript:;">
<i class="icon-docs"></i> New Post </a>
</li>
<li>
<a href="javascript:;">
<i class="icon-tag"></i> New Comment </a>
</li>
<li>
<a href="javascript:;">
<i class="icon-share"></i> Share </a>
</li>
<li class="divider">
</li>
<li>
<a href="javascript:;">
<i class="icon-flag"></i> Comments <span class="badge badge-success">4</span>
</a>
</li>
<li>
<a href="javascript:;">
<i class="icon-users"></i> Feedbacks <span class="badge badge-danger">2</span>
</a>
</li>
</ul>
</div>
</div>
<!-- END PAGE ACTIONS -->
<!-- BEGIN PAGE TOP -->
<div class="page-top">
<!-- BEGIN HEADER SEARCH BOX -->
<!-- DOC: Apply "search-form-expanded" right after the "search-form" class to have half expanded search box -->
<form class="search-form" action="extra_search.html" method="GET">
<div class="input-group">
<input type="text" class="form-control input-sm" placeholder="Search..." name="query">
<span class="input-group-btn">
<a href="javascript:;" class="btn submit"><i class="icon-magnifier"></i></a>
</span>
</div>
</form>
<!-- END HEADER SEARCH BOX -->
<!-- BEGIN TOP NAVIGATION MENU -->
<div class="top-menu">
<ul class="nav navbar-nav pull-right">
<li class="separator hide">
</li>
<!-- BEGIN NOTIFICATION DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-notification dropdown-dark" id="header_notification_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-bell"></i>
<span class="badge badge-success">
7 </span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3><span class="bold">12 pending</span> notifications</h3>
<a href="extra_profile.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 250px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="time">just now</span>
<span class="details">
<span class="label label-sm label-icon label-success">
<i class="fa fa-plus"></i>
</span>
New user registered. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 mins</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Server #12 overloaded. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">10 mins</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span>
Server #2 not responding. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">14 hrs</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
Application error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">2 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Database overloaded 68%. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">3 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
A user IP blocked. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">4 days</span>
<span class="details">
<span class="label label-sm label-icon label-warning">
<i class="fa fa-bell-o"></i>
</span>
Storage Server #4 not responding dfdfdfd. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">5 days</span>
<span class="details">
<span class="label label-sm label-icon label-info">
<i class="fa fa-bullhorn"></i>
</span>
System Error. </span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="time">9 days</span>
<span class="details">
<span class="label label-sm label-icon label-danger">
<i class="fa fa-bolt"></i>
</span>
Storage server failed. </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END NOTIFICATION DROPDOWN -->
<li class="separator hide">
</li>
<!-- BEGIN INBOX DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-inbox dropdown-dark" id="header_inbox_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-envelope-open"></i>
<span class="badge badge-danger">
4 </span>
</a>
<ul class="dropdown-menu">
<li class="external">
<h3>You have <span class="bold">7 New</span> Messages</h3>
<a href="inbox.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Lisa Wong </span>
<span class="time">Just Now </span>
</span>
<span class="message">
Vivamus sed auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Richard Doe </span>
<span class="time">16 mins </span>
</span>
<span class="message">
Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar1.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Bob Nilson </span>
<span class="time">2 hrs </span>
</span>
<span class="message">
Vivamus sed nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar2.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Lisa Wong </span>
<span class="time">40 mins </span>
</span>
<span class="message">
Vivamus sed auctor 40% nibh congue nibh... </span>
</a>
</li>
<li>
<a href="inbox.html?a=view">
<span class="photo">
<img src="../../assets/admin/layout3/img/avatar3.jpg" class="img-circle" alt="">
</span>
<span class="subject">
<span class="from">
Richard Doe </span>
<span class="time">46 mins </span>
</span>
<span class="message">
Vivamus sed congue nibh auctor nibh congue nibh. auctor nibh auctor nibh... </span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END INBOX DROPDOWN -->
<li class="separator hide">
</li>
<!-- BEGIN TODO DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-extended dropdown-tasks dropdown-dark" id="header_task_bar">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<i class="icon-calendar"></i>
<span class="badge badge-primary">
3 </span>
</a>
<ul class="dropdown-menu extended tasks">
<li class="external">
<h3>You have <span class="bold">12 pending</span> tasks</h3>
<a href="page_todo.html">view all</a>
</li>
<li>
<ul class="dropdown-menu-list scroller" style="height: 275px;" data-handle-color="#637283">
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New release v1.2 </span>
<span class="percent">30%</span>
</span>
<span class="progress">
<span style="width: 40%;" class="progress-bar progress-bar-success" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">40% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Application deployment</span>
<span class="percent">65%</span>
</span>
<span class="progress">
<span style="width: 65%;" class="progress-bar progress-bar-danger" aria-valuenow="65" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">65% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile app release</span>
<span class="percent">98%</span>
</span>
<span class="progress">
<span style="width: 98%;" class="progress-bar progress-bar-success" aria-valuenow="98" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">98% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Database migration</span>
<span class="percent">10%</span>
</span>
<span class="progress">
<span style="width: 10%;" class="progress-bar progress-bar-warning" aria-valuenow="10" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">10% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Web server upgrade</span>
<span class="percent">58%</span>
</span>
<span class="progress">
<span style="width: 58%;" class="progress-bar progress-bar-info" aria-valuenow="58" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">58% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">Mobile development</span>
<span class="percent">85%</span>
</span>
<span class="progress">
<span style="width: 85%;" class="progress-bar progress-bar-success" aria-valuenow="85" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">85% Complete</span></span>
</span>
</a>
</li>
<li>
<a href="javascript:;">
<span class="task">
<span class="desc">New UI release</span>
<span class="percent">38%</span>
</span>
<span class="progress progress-striped">
<span style="width: 38%;" class="progress-bar progress-bar-important" aria-valuenow="18" aria-valuemin="0" aria-valuemax="100"><span class="sr-only">38% Complete</span></span>
</span>
</a>
</li>
</ul>
</li>
</ul>
</li>
<!-- END TODO DROPDOWN -->
<!-- BEGIN USER LOGIN DROPDOWN -->
<!-- DOC: Apply "dropdown-dark" class after below "dropdown-extended" to change the dropdown styte -->
<li class="dropdown dropdown-user dropdown-dark">
<a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-close-others="true">
<span class="username username-hide-on-mobile">
Nick </span>
<!-- DOC: Do not remove below empty space( ) as its purposely used -->
<img alt="" class="img-circle" src="../../assets/admin/layout4/img/avatar9.jpg"/>
</a>
<ul class="dropdown-menu dropdown-menu-default">
<li>
<a href="extra_profile.html">
<i class="icon-user"></i> My Profile </a>
</li>
<li>
<a href="page_calendar.html">
<i class="icon-calendar"></i> My Calendar </a>
</li>
<li>
<a href="inbox.html">
<i class="icon-envelope-open"></i> My Inbox <span class="badge badge-danger">
3 </span>
</a>
</li>
<li>
<a href="page_todo.html">
<i class="icon-rocket"></i> My Tasks <span class="badge badge-success">
7 </span>
</a>
</li>
<li class="divider">
</li>
<li>
<a href="extra_lock.html">
<i class="icon-lock"></i> Lock Screen </a>
</li>
<li>
<a href="login.html">
<i class="icon-key"></i> Log Out </a>
</li>
</ul>
</li>
<!-- END USER LOGIN DROPDOWN -->
</ul>
</div>
<!-- END TOP NAVIGATION MENU -->
</div>
<!-- END PAGE TOP -->
</div>
<!-- END HEADER INNER -->
</div>
<!-- END HEADER -->
<div class="clearfix">
</div>
<!-- BEGIN CONTAINER -->
<div class="page-container">
<!-- BEGIN SIDEBAR -->
<div class="page-sidebar-wrapper">
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Change data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<div class="page-sidebar navbar-collapse collapse">
<!-- BEGIN SIDEBAR MENU -->
<!-- DOC: Apply "page-sidebar-menu-light" class right after "page-sidebar-menu" to enable light sidebar menu style(without borders) -->
<!-- DOC: Apply "page-sidebar-menu-hover-submenu" class right after "page-sidebar-menu" to enable hoverable(hover vs accordion) sub menu mode -->
<!-- DOC: Apply "page-sidebar-menu-closed" class right after "page-sidebar-menu" to collapse("page-sidebar-closed" class must be applied to the body element) the sidebar sub menu mode -->
<!-- DOC: Set data-auto-scroll="false" to disable the sidebar from auto scrolling/focusing -->
<!-- DOC: Set data-keep-expand="true" to keep the submenues expanded -->
<!-- DOC: Set data-auto-speed="200" to adjust the sub menu slide up/down speed -->
<ul class="page-sidebar-menu " data-keep-expanded="false" data-auto-scroll="true" data-slide-speed="200">
<li class="start ">
<a href="index.html">
<i class="icon-home"></i>
<span class="title">Dashboard</span>
</a>
</li>
<li class="active open">
<a href="javascript:;">
<i class="icon-basket"></i>
<span class="title">eCommerce</span>
<span class="arrow open"></span>
</a>
<ul class="sub-menu">
<li>
<a href="ecommerce_index.html">
<i class="icon-home"></i>
Dashboard</a>
</li>
<li>
<a href="ecommerce_orders.html">
<i class="icon-basket"></i>
Orders</a>
</li>
<li>
<a href="ecommerce_orders_view.html">
<i class="icon-tag"></i>
Order View</a>
</li>
<li class="active">
<a href="ecommerce_products.html">
<i class="icon-handbag"></i>
Products</a>
</li>
<li>
<a href="ecommerce_products_edit.html">
<i class="icon-pencil"></i>
Product Edit</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-rocket"></i>
<span class="title">Page Layouts</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="layout_sidebar_reversed.html">
<span class="badge badge-warning">new</span>Right Sidebar Page</a>
</li>
<li>
<a href="layout_sidebar_fixed.html">
Sidebar Fixed Page</a>
</li>
<li>
<a href="layout_sidebar_closed.html">
Sidebar Closed Page</a>
</li>
<li>
<a href="layout_blank_page.html">
Blank Page</a>
</li>
<li>
<a href="layout_boxed_page.html">
Boxed Page</a>
</li>
<li>
<a href="layout_language_bar.html">
Language Switch Bar</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-diamond"></i>
<span class="title">UI Features</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="ui_general.html">
General Components</a>
</li>
<li>
<a href="ui_buttons.html">
Buttons</a>
</li>
<li>
<a href="ui_icons.html">
<span class="badge badge-danger">new</span>Font Icons</a>
</li>
<li>
<a href="ui_colors.html">
Flat UI Colors</a>
</li>
<li>
<a href="ui_typography.html">
Typography</a>
</li>
<li>
<a href="ui_tabs_accordions_navs.html">
Tabs, Accordions & Navs</a>
</li>
<li>
<a href="ui_tree.html">
<span class="badge badge-danger">new</span>Tree View</a>
</li>
<li>
<a href="ui_page_progress_style_1.html">
<span class="badge badge-warning">new</span>Page Progress Bar - Style 1</a>
</li>
<li>
<a href="ui_blockui.html">
Block UI</a>
</li>
<li>
<a href="ui_bootstrap_growl.html">
<span class="badge badge-roundless badge-warning">new</span>Bootstrap Growl Notifications</a>
</li>
<li>
<a href="ui_notific8.html">
Notific8 Notifications</a>
</li>
<li>
<a href="ui_toastr.html">
Toastr Notifications</a>
</li>
<li>
<a href="ui_alert_dialog_api.html">
<span class="badge badge-danger">new</span>Alerts & Dialogs API</a>
</li>
<li>
<a href="ui_session_timeout.html">
Session Timeout</a>
</li>
<li>
<a href="ui_idle_timeout.html">
User Idle Timeout</a>
</li>
<li>
<a href="ui_modals.html">
Modals</a>
</li>
<li>
<a href="ui_extended_modals.html">
Extended Modals</a>
</li>
<li>
<a href="ui_tiles.html">
Tiles</a>
</li>
<li>
<a href="ui_datepaginator.html">
<span class="badge badge-success">new</span>Date Paginator</a>
</li>
<li>
<a href="ui_nestable.html">
Nestable List</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-puzzle"></i>
<span class="title">UI Components</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="components_pickers.html">
Date & Time Pickers</a>
</li>
<li>
<a href="components_context_menu.html">
Context Menu</a>
</li>
<li>
<a href="components_dropdowns.html">
Custom Dropdowns</a>
</li>
<li>
<a href="components_form_tools.html">
Form Widgets & Tools</a>
</li>
<li>
<a href="components_form_tools2.html">
Form Widgets & Tools 2</a>
</li>
<li>
<a href="components_editors.html">
Markdown & WYSIWYG Editors</a>
</li>
<li>
<a href="components_ion_sliders.html">
Ion Range Sliders</a>
</li>
<li>
<a href="components_noui_sliders.html">
NoUI Range Sliders</a>
</li>
<li>
<a href="components_jqueryui_sliders.html">
jQuery UI Sliders</a>
</li>
<li>
<a href="components_knob_dials.html">
Knob Circle Dials</a>
</li>
</ul>
</li>
<!-- BEGIN ANGULARJS LINK -->
<li class="tooltips" data-container="body" data-placement="right" data-html="true" data-original-title="AngularJS version demo">
<a href="angularjs" target="_blank">
<i class="icon-paper-plane"></i>
<span class="title">
AngularJS Version </span>
</a>
</li>
<!-- END ANGULARJS LINK -->
<li>
<a href="javascript:;">
<i class="icon-settings"></i>
<span class="title">Form Stuff</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="form_controls_md.html">
<span class="badge badge-roundless badge-danger">new</span>Material Design<br>
Form Controls</a>
</li>
<li>
<a href="form_controls.html">
Bootstrap<br>
Form Controls</a>
</li>
<li>
<a href="form_layouts.html">
Form Layouts</a>
</li>
<li>
<a href="form_editable.html">
<span class="badge badge-warning">new</span>Form X-editable</a>
</li>
<li>
<a href="form_wizard.html">
Form Wizard</a>
</li>
<li>
<a href="form_validation.html">
Form Validation</a>
</li>
<li>
<a href="form_image_crop.html">
<span class="badge badge-danger">new</span>Image Cropping</a>
</li>
<li>
<a href="form_fileupload.html">
Multiple File Upload</a>
</li>
<li>
<a href="form_dropzone.html">
Dropzone File Upload</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-briefcase"></i>
<span class="title">Data Tables</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="table_basic.html">
Basic Datatables</a>
</li>
<li>
<a href="table_tree.html">
Tree Datatables</a>
</li>
<li>
<a href="table_responsive.html">
Responsive Datatables</a>
</li>
<li>
<a href="table_managed.html">
Managed Datatables</a>
</li>
<li>
<a href="table_editable.html">
Editable Datatables</a>
</li>
<li>
<a href="table_advanced.html">
Advanced Datatables</a>
</li>
<li>
<a href="table_ajax.html">
Ajax Datatables</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-wallet"></i>
<span class="title">Portlets</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="portlet_general.html">
General Portlets</a>
</li>
<li>
<a href="portlet_general2.html">
<span class="badge badge-danger">new</span>New Portlets #1</a>
</li>
<li>
<a href="portlet_general3.html">
<span class="badge badge-danger">new</span>New Portlets #2</a>
</li>
<li>
<a href="portlet_ajax.html">
Ajax Portlets</a>
</li>
<li>
<a href="portlet_draggable.html">
Draggable Portlets</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-bar-chart"></i>
<span class="title">Charts</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="charts_amcharts.html">
Amchart</a>
</li>
<li>
<a href="charts_flotcharts.html">
Flotchart</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-docs"></i>
<span class="title">Pages</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="page_timeline.html">
<i class="icon-paper-plane"></i>
<span class="badge badge-warning">2</span>New Timeline</a>
</li>
<li>
<a href="extra_profile.html">
<i class="icon-user-following"></i>
<span class="badge badge-success badge-roundless">new</span>New User Profile</a>
</li>
<li>
<a href="page_todo.html">
<i class="icon-hourglass"></i>
<span class="badge badge-danger">4</span>Todo</a>
</li>
<li>
<a href="inbox.html">
<i class="icon-envelope"></i>
<span class="badge badge-danger">4</span>Inbox</a>
</li>
<li>
<a href="extra_faq.html">
<i class="icon-info"></i>
FAQ</a>
</li>
<li>
<a href="page_portfolio.html">
<i class="icon-feed"></i>
Portfolio</a>
</li>
<li>
<a href="page_timeline.html">
<i class="icon-clock"></i>
<span class="badge badge-info">4</span>Timeline</a>
</li>
<li>
<a href="page_coming_soon.html">
<i class="icon-flag"></i>
Coming Soon</a>
</li>
<li>
<a href="page_calendar.html">
<i class="icon-calendar"></i>
<span class="badge badge-danger">14</span>Calendar</a>
</li>
<li>
<a href="extra_invoice.html">
<i class="icon-flag"></i>
Invoice</a>
</li>
<li>
<a href="page_blog.html">
<i class="icon-speech"></i>
Blog</a>
</li>
<li>
<a href="page_blog_item.html">
<i class="icon-link"></i>
Blog Post</a>
</li>
<li>
<a href="page_news.html">
<i class="icon-eye"></i>
<span class="badge badge-success">9</span>News</a>
</li>
<li>
<a href="page_news_item.html">
<i class="icon-bell"></i>
News View</a>
</li>
<li>
<a href="page_timeline_old.html">
<i class="icon-paper-plane"></i>
<span class="badge badge-warning">2</span>Old Timeline</a>
</li>
<li>
<a href="extra_profile_old.html">
<i class="icon-user"></i>
Old User Profile</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-present"></i>
<span class="title">Extra</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="page_about.html">
About Us</a>
</li>
<li>
<a href="page_contact.html">
Contact Us</a>
</li>
<li>
<a href="extra_search.html">
Search Results</a>
</li>
<li>
<a href="extra_pricing_table.html">
Pricing Tables</a>
</li>
<li>
<a href="extra_404_option1.html">
404 Page Option 1</a>
</li>
<li>
<a href="extra_404_option2.html">
404 Page Option 2</a>
</li>
<li>
<a href="extra_404_option3.html">
404 Page Option 3</a>
</li>
<li>
<a href="extra_500_option1.html">
500 Page Option 1</a>
</li>
<li>
<a href="extra_500_option2.html">
500 Page Option 2</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-folder"></i>
<span class="title">Multi Level Menu</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:;">
<i class="icon-settings"></i> Item 1 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="javascript:;">
<i class="icon-user"></i>
Sample Link 1 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="#"><i class="icon-power"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-paper-plane"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-star"></i> Sample Link 1</a>
</li>
</ul>
</li>
<li>
<a href="#"><i class="icon-camera"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-link"></i> Sample Link 2</a>
</li>
<li>
<a href="#"><i class="icon-pointer"></i> Sample Link 3</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-globe"></i> Item 2 <span class="arrow"></span>
</a>
<ul class="sub-menu">
<li>
<a href="#"><i class="icon-tag"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-pencil"></i> Sample Link 1</a>
</li>
<li>
<a href="#"><i class="icon-graph"></i> Sample Link 1</a>
</li>
</ul>
</li>
<li>
<a href="#">
<i class="icon-bar-chart"></i>
Item 3 </a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-user"></i>
<span class="title">Login Options</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="login.html">
Login Form 1</a>
</li>
<li>
<a href="login_2.html">
Login Form 2</a>
</li>
<li>
<a href="login_3.html">
Login Form 3</a>
</li>
<li>
<a href="login_soft.html">
Login Form 4</a>
</li>
<li>
<a href="extra_lock.html">
Lock Screen 1</a>
</li>
<li>
<a href="extra_lock2.html">
Lock Screen 2</a>
</li>
</ul>
</li>
<li>
<a href="javascript:;">
<i class="icon-envelope-open"></i>
<span class="title">Email Templates</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="email_template1.html">
New Email Template 1</a>
</li>
<li>
<a href="email_template2.html">
New Email Template 2</a>
</li>
<li>
<a href="email_template3.html">
New Email Template 3</a>
</li>
<li>
<a href="email_template4.html">
New Email Template 4</a>
</li>
<li>
<a href="email_newsletter.html">
Old Email Template 1</a>
</li>
<li>
<a href="email_system.html">
Old Email Template 2</a>
</li>
</ul>
</li>
<li class="last ">
<a href="javascript:;">
<i class="icon-pointer"></i>
<span class="title">Maps</span>
<span class="arrow "></span>
</a>
<ul class="sub-menu">
<li>
<a href="maps_google.html">
Google Maps</a>
</li>
<li>
<a href="maps_vector.html">
Vector Maps</a>
</li>
</ul>
</li>
</ul>
<!-- END SIDEBAR MENU -->
</div>
</div>
<!-- END SIDEBAR -->
<!-- BEGIN CONTENT -->
<div class="page-content-wrapper">
<div class="page-content">
<!-- BEGIN SAMPLE PORTLET CONFIGURATION MODAL FORM-->
<div class="modal fade" id="portlet-config" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
Widget settings form goes here
</div>
<div class="modal-footer">
<button type="button" class="btn blue">Save changes</button>
<button type="button" class="btn default" data-dismiss="modal">Close</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<!-- END SAMPLE PORTLET CONFIGURATION MODAL FORM-->
<!-- BEGIN PAGE HEADER-->
<!-- BEGIN PAGE HEAD -->
<div class="page-head">
<!-- BEGIN PAGE TITLE -->
<div class="page-title">
<h1>Products <small>product listing</small></h1>
</div>
<!-- END PAGE TITLE -->
<!-- BEGIN PAGE TOOLBAR -->
<div class="page-toolbar">
<!-- BEGIN THEME PANEL -->
<div class="btn-group btn-theme-panel">
<a href="javascript:;" class="btn dropdown-toggle" data-toggle="dropdown">
<i class="icon-settings"></i>
</a>
<div class="dropdown-menu theme-panel pull-right dropdown-custom hold-on-click">
<div class="row">
<div class="col-md-4 col-sm-4 col-xs-12">
<h3>THEME</h3>
<ul class="theme-colors">
<li class="theme-color theme-color-default active" data-theme="default">
<span class="theme-color-view"></span>
<span class="theme-color-name">Dark Header</span>
</li>
<li class="theme-color theme-color-light" data-theme="light">
<span class="theme-color-view"></span>
<span class="theme-color-name">Light Header</span>
</li>
</ul>
</div>
<div class="col-md-8 col-sm-8 col-xs-12 seperator">
<h3>LAYOUT</h3>
<ul class="theme-settings">
<li>
Theme Style
<select class="layout-style-option form-control input-small input-sm">
<option value="square" selected="selected">Square corners</option>
<option value="rounded">Rounded corners</option>
</select>
</li>
<li>
Layout
<select class="layout-option form-control input-small input-sm">
<option value="fluid" selected="selected">Fluid</option>
<option value="boxed">Boxed</option>
</select>
</li>
<li>
Header
<select class="page-header-option form-control input-small input-sm">
<option value="fixed" selected="selected">Fixed</option>
<option value="default">Default</option>
</select>
</li>
<li>
Top Dropdowns
<select class="page-header-top-dropdown-style-option form-control input-small input-sm">
<option value="light">Light</option>
<option value="dark" selected="selected">Dark</option>
</select>
</li>
<li>
Sidebar Mode
<select class="sidebar-option form-control input-small input-sm">
<option value="fixed">Fixed</option>
<option value="default" selected="selected">Default</option>
</select>
</li>
<li>
Sidebar Menu
<select class="sidebar-menu-option form-control input-small input-sm">
<option value="accordion" selected="selected">Accordion</option>
<option value="hover">Hover</option>
</select>
</li>
<li>
Sidebar Position
<select class="sidebar-pos-option form-control input-small input-sm">
<option value="left" selected="selected">Left</option>
<option value="right">Right</option>
</select>
</li>
<li>
Footer
<select class="page-footer-option form-control input-small input-sm">
<option value="fixed">Fixed</option>
<option value="default" selected="selected">Default</option>
</select>
</li>
</ul>
</div>
</div>
</div>
</div>
<!-- END THEME PANEL -->
</div>
<!-- END PAGE TOOLBAR -->
</div>
<!-- END PAGE HEAD -->
<!-- BEGIN PAGE BREADCRUMB -->
<ul class="page-breadcrumb breadcrumb">
<li>
<a href="index.html">Home</a>
<i class="fa fa-circle"></i>
</li>
<li>
<a href="#">eCommerce</a>
<i class="fa fa-circle"></i>
</li>
<li>
<a href="#">Products</a>
</li>
</ul>
<!-- END PAGE BREADCRUMB -->
<!-- END PAGE HEADER-->
<!-- BEGIN PAGE CONTENT-->
<div class="row">
<div class="col-md-12">
<div class="note note-danger note-shadow">
<p>
NOTE: The below datatable is not connected to a real database so the filter and sorting is just simulated for demo purposes only.
</p>
</div>
<!-- Begin: life time stats -->
<div class="portlet light">
<div class="portlet-title">
<div class="caption">
<i class="fa fa-gift font-green-sharp"></i>
<span class="caption-subject font-green-sharp bold uppercase">Products</span>
<span class="caption-helper">manage products...</span>
</div>
<div class="actions">
<div class="btn-group">
<a class="btn btn-default btn-circle" href="javascript:;" data-toggle="dropdown">
<i class="fa fa-share"></i> Tools <i class="fa fa-angle-down"></i>
</a>
<ul class="dropdown-menu pull-right">
<li>
<a href="javascript:;">
Export to Excel </a>
</li>
<li>
<a href="javascript:;">
Export to CSV </a>
</li>
<li>
<a href="javascript:;">
Export to XML </a>
</li>
<li class="divider">
</li>
<li>
<a href="javascript:;">
Print Invoices </a>
</li>
</ul>
</div>
</div>
</div>
<div class="portlet-body">
<div class="table-container">
<div class="table-actions-wrapper">
<span>
</span>
<select class="table-group-action-input form-control input-inline input-small input-sm">
<option value="">Select...</option>
<option value="publish">Publish</option>
<option value="unpublished">Un-publish</option>
<option value="delete">Delete</option>
</select>
<button class="btn btn-sm yellow table-group-action-submit"><i class="fa fa-check"></i> Submit</button>
</div>
<table class="table table-striped table-bordered table-hover" id="datatable_products">
<thead>
<tr role="row" class="heading">
<th width="1%">
<input type="checkbox" class="group-checkable">
</th>
<th width="10%">
ID
</th>
<th width="15%">
Product Name
</th>
<th width="15%">
Category
</th>
<th width="10%">
Price
</th>
<th width="10%">
Quantity
</th>
<th width="15%">
Date Created
</th>
<th width="10%">
Status
</th>
<th width="10%">
Actions
</th>
</tr>
<tr role="row" class="filter">
<td>
</td>
<td>
<input type="text" class="form-control form-filter input-sm" name="product_id">
</td>
<td>
<input type="text" class="form-control form-filter input-sm" name="product_name">
</td>
<td>
<select name="product_category" class="form-control form-filter input-sm">
<option value="">Select...</option>
<option value="1">Mens</option>
<option value="2"> Footwear</option>
<option value="3"> Clothing</option>
<option value="4"> Accessories</option>
<option value="5"> Fashion Outlet</option>
<option value="6">Football Shirts</option>
<option value="7"> Premier League</option>
<option value="8"> Football League</option>
<option value="9"> Serie A</option>
<option value="10"> Bundesliga</option>
<option value="11">Brands</option>
<option value="12"> Adidas</option>
<option value="13"> Nike</option>
<option value="14"> Airwalk</option>
<option value="15"> USA Pro</option>
<option value="16"> Kangol</option>
</select>
</td>
<td>
<div class="margin-bottom-5">
<input type="text" class="form-control form-filter input-sm" name="product_price_from" placeholder="From"/>
</div>
<input type="text" class="form-control form-filter input-sm" name="product_price_to" placeholder="To"/>
</td>
<td>
<div class="margin-bottom-5">
<input type="text" class="form-control form-filter input-sm" name="product_quantity_from" placeholder="From"/>
</div>
<input type="text" class="form-control form-filter input-sm" name="product_quantity_to" placeholder="To"/>
</td>
<td>
<div class="input-group date date-picker margin-bottom-5" data-date-format="dd/mm/yyyy">
<input type="text" class="form-control form-filter input-sm" readonly name="product_created_from" placeholder="From">
<span class="input-group-btn">
<button class="btn btn-sm default" type="button"><i class="fa fa-calendar"></i></button>
</span>
</div>
<div class="input-group date date-picker" data-date-format="dd/mm/yyyy">
<input type="text" class="form-control form-filter input-sm" readonly name="product_created_to " placeholder="To">
<span class="input-group-btn">
<button class="btn btn-sm default" type="button"><i class="fa fa-calendar"></i></button>
</span>
</div>
</td>
<td>
<select name="product_status" class="form-control form-filter input-sm">
<option value="">Select...</option>
<option value="published">Published</option>
<option value="notpublished">Not Published</option>
<option value="deleted">Deleted</option>
</select>
</td>
<td>
<div class="margin-bottom-5">
<button class="btn btn-sm yellow filter-submit margin-bottom"><i class="fa fa-search"></i> Search</button>
</div>
<button class="btn btn-sm red filter-cancel"><i class="fa fa-times"></i> Reset</button>
</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
<!-- End: life time stats -->
</div>
</div>
<!-- END PAGE CONTENT-->
</div>
</div>
<!-- END CONTENT -->
</div>
<!-- END CONTAINER -->
<!-- BEGIN FOOTER -->
<div class="page-footer">
<div class="page-footer-inner">
2014 © Metronic by keenthemes.
</div>
<div class="scroll-to-top">
<i class="icon-arrow-up"></i>
</div>
</div>
<!-- END FOOTER -->
<!-- BEGIN JAVASCRIPTS(Load javascripts at bottom, this will reduce page load time) -->
<!-- BEGIN CORE PLUGINS -->
<!--[if lt IE 9]>
<script src="../../assets/global/plugins/respond.min.js"></script>
<script src="../../assets/global/plugins/excanvas.min.js"></script>
<![endif]-->
<script src="../../assets/global/plugins/jquery.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery-migrate.min.js" type="text/javascript"></script>
<!-- IMPORTANT! Load jquery-ui.min.js before bootstrap.min.js to fix bootstrap tooltip conflict with jquery ui tooltip -->
<script src="../../assets/global/plugins/jquery-ui/jquery-ui.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap-hover-dropdown/bootstrap-hover-dropdown.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery-slimscroll/jquery.slimscroll.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery.blockui.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/jquery.cokie.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/uniform/jquery.uniform.min.js" type="text/javascript"></script>
<script src="../../assets/global/plugins/bootstrap-switch/js/bootstrap-switch.min.js" type="text/javascript"></script>
<!-- END CORE PLUGINS -->
<!-- BEGIN PAGE LEVEL PLUGINS -->
<script type="text/javascript" src="../../assets/global/plugins/select2/select2.min.js"></script>
<script type="text/javascript" src="../../assets/global/plugins/datatables/media/js/jquery.dataTables.min.js"></script>
<script type="text/javascript" src="../../assets/global/plugins/datatables/plugins/bootstrap/dataTables.bootstrap.js"></script>
<script type="text/javascript" src="../../assets/global/plugins/bootstrap-datepicker/js/bootstrap-datepicker.js"></script>
<!-- END PAGE LEVEL PLUGINS -->
<!-- BEGIN PAGE LEVEL SCRIPTS -->
<script src="../../assets/global/scripts/metronic.js" type="text/javascript"></script>
<script src="../../assets/admin/layout4/scripts/layout.js" type="text/javascript"></script>
<script src="../../assets/admin/layout4/scripts/demo.js" type="text/javascript"></script>
<script src="../../assets/global/scripts/datatable.js"></script>
<script src="../../assets/admin/pages/scripts/ecommerce-products.js"></script>
<!-- END PAGE LEVEL SCRIPTS -->
<script>
jQuery(document).ready(function() {
Metronic.init(); // init metronic core components
Layout.init(); // init current layout
Demo.init(); // init demo features
EcommerceProducts.init();
});
</script>
<!-- END JAVASCRIPTS -->
</body>
<!-- END BODY -->
</html> | {
"pile_set_name": "Github"
} |
/* Copyright (C) 2006 Free Software Foundation, Inc.
* SPDX-License-Identifier: GPL-2.0+
*/
/* Moderately Space-optimized libgcc routines for the Renesas SH /
STMicroelectronics ST40 CPUs.
Contributed by J"orn Rennecke [email protected]. */
/* Size: 186 bytes jointly for udivsi3_i4i and sdivsi3_i4i
sh4-200 run times:
udiv small divisor: 55 cycles
udiv large divisor: 52 cycles
sdiv small divisor, positive result: 59 cycles
sdiv large divisor, positive result: 56 cycles
sdiv small divisor, negative result: 65 cycles (*)
sdiv large divisor, negative result: 62 cycles (*)
(*): r2 is restored in the rts delay slot and has a lingering latency
of two more cycles. */
.balign 4
.global __udivsi3_i4i
.global __udivsi3_i4
.set __udivsi3_i4, __udivsi3_i4i
.type __udivsi3_i4i, @function
.type __sdivsi3_i4i, @function
__udivsi3_i4i:
sts pr,r1
mov.l r4,@-r15
extu.w r5,r0
cmp/eq r5,r0
swap.w r4,r0
shlr16 r4
bf/s large_divisor
div0u
mov.l r5,@-r15
shll16 r5
sdiv_small_divisor:
div1 r5,r4
bsr div6
div1 r5,r4
div1 r5,r4
bsr div6
div1 r5,r4
xtrct r4,r0
xtrct r0,r4
bsr div7
swap.w r4,r4
div1 r5,r4
bsr div7
div1 r5,r4
xtrct r4,r0
mov.l @r15+,r5
swap.w r0,r0
mov.l @r15+,r4
jmp @r1
rotcl r0
div7:
div1 r5,r4
div6:
div1 r5,r4; div1 r5,r4; div1 r5,r4
div1 r5,r4; div1 r5,r4; rts; div1 r5,r4
divx3:
rotcl r0
div1 r5,r4
rotcl r0
div1 r5,r4
rotcl r0
rts
div1 r5,r4
large_divisor:
mov.l r5,@-r15
sdiv_large_divisor:
xor r4,r0
.rept 4
rotcl r0
bsr divx3
div1 r5,r4
.endr
mov.l @r15+,r5
mov.l @r15+,r4
jmp @r1
rotcl r0
.global __sdivsi3_i4i
.global __sdivsi3_i4
.global __sdivsi3
.set __sdivsi3_i4, __sdivsi3_i4i
.set __sdivsi3, __sdivsi3_i4i
__sdivsi3_i4i:
mov.l r4,@-r15
cmp/pz r5
mov.l r5,@-r15
bt/s pos_divisor
cmp/pz r4
neg r5,r5
extu.w r5,r0
bt/s neg_result
cmp/eq r5,r0
neg r4,r4
pos_result:
swap.w r4,r0
bra sdiv_check_divisor
sts pr,r1
pos_divisor:
extu.w r5,r0
bt/s pos_result
cmp/eq r5,r0
neg r4,r4
neg_result:
mova negate_result,r0
;
mov r0,r1
swap.w r4,r0
lds r2,macl
sts pr,r2
sdiv_check_divisor:
shlr16 r4
bf/s sdiv_large_divisor
div0u
bra sdiv_small_divisor
shll16 r5
.balign 4
negate_result:
neg r0,r0
jmp @r2
sts macl,r2
| {
"pile_set_name": "Github"
} |
package com.applozic.mobicomkit.uiwidgets.conversation;
import android.content.Context;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
/**
* Created by ashish on 05/02/18.
*/
public class AlLinearLayoutManager extends LinearLayoutManager {
public AlLinearLayoutManager(Context context) {
super(context);
}
@Override
public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
try {
super.onLayoutChildren(recycler, state);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
}
| {
"pile_set_name": "Github"
} |
<?php
/**
* module: invite.php
*
* send email invitations to join social network
*
*/
function invite_post(&$a) {
if(! local_channel()) {
notice( t('Permission denied.') . EOL);
return;
}
check_form_security_token_redirectOnErr('/', 'send_invite');
$max_invites = intval(get_config('system','max_invites'));
if(! $max_invites)
$max_invites = 50;
$current_invites = intval(get_pconfig(local_channel(),'system','sent_invites'));
if($current_invites > $max_invites) {
notice( t('Total invitation limit exceeded.') . EOL);
return;
};
$recips = ((x($_POST,'recipients')) ? explode("\n",$_POST['recipients']) : array());
$message = ((x($_POST,'message')) ? notags(trim($_POST['message'])) : '');
$total = 0;
if(get_config('system','invitation_only')) {
$invonly = true;
$x = get_pconfig(local_channel(),'system','invites_remaining');
if((! $x) && (! is_site_admin()))
return;
}
foreach($recips as $recip) {
$recip = trim($recip);
if(! $recip)
continue;
if(! valid_email($recip)) {
notice( sprintf( t('%s : Not a valid email address.'), $recip) . EOL);
continue;
}
if($invonly && ($x || is_site_admin())) {
$code = autoname(8) . srand(1000,9999);
$nmessage = str_replace('$invite_code',$code,$message);
$r = q("INSERT INTO `register` (`hash`,`created`) VALUES ('%s', '%s') ",
dbesc($code),
dbesc(datetime_convert())
);
if(! is_site_admin()) {
$x --;
if($x >= 0)
set_pconfig(local_channel(),'system','invites_remaining',$x);
else
return;
}
}
else
$nmessage = $message;
$account = $a->get_account();
$res = mail($recip, sprintf( t('Please join us on Red'), $a->config['sitename']),
$nmessage,
"From: " . $account['account_email'] . "\n"
. 'Content-type: text/plain; charset=UTF-8' . "\n"
. 'Content-transfer-encoding: 8bit' );
if($res) {
$total ++;
$current_invites ++;
set_pconfig(local_channel(),'system','sent_invites',$current_invites);
if($current_invites > $max_invites) {
notice( t('Invitation limit exceeded. Please contact your site administrator.') . EOL);
return;
}
}
else {
notice( sprintf( t('%s : Message delivery failed.'), $recip) . EOL);
}
}
notice( sprintf( tt("%d message sent.", "%d messages sent.", $total) , $total) . EOL);
return;
}
function invite_content(&$a) {
if(! local_channel()) {
notice( t('Permission denied.') . EOL);
return;
}
$tpl = get_markup_template('invite.tpl');
$invonly = false;
if(get_config('system','invitation_only')) {
$invonly = true;
$x = get_pconfig(local_channel(),'system','invites_remaining');
if((! $x) && (! is_site_admin())) {
notice( t('You have no more invitations available') . EOL);
return '';
}
}
$ob = $a->get_observer();
if(! $ob)
return $o;
$channel = $a->get_channel();
$o = replace_macros($tpl, array(
'$form_security_token' => get_form_security_token("send_invite"),
'$invite' => t('Send invitations'),
'$addr_text' => t('Enter email addresses, one per line:'),
'$msg_text' => t('Your message:'),
'$default_message' => t('Please join my community on RedMatrix.') . "\r\n" . "\r\n"
. $linktxt
. (($invonly) ? "\r\n" . "\r\n" . t('You will need to supply this invitation code: ') . $invite_code . "\r\n" . "\r\n" : '')
. t('1. Register at any RedMatrix location (they are all inter-connected)')
. "\r\n" . "\r\n" . z_root() . '/register'
. "\r\n" . "\r\n" . t('2. Enter my RedMatrix network address into the site searchbar.')
. "\r\n" . "\r\n" . $ob['xchan_addr'] . ' (' . t('or visit ') . z_root() . '/channel/' . $channel['channel_address'] . ')'
. "\r\n" . "\r\n"
. t('3. Click [Connect]')
. "\r\n" . "\r\n" ,
'$submit' => t('Submit')
));
return $o;
} | {
"pile_set_name": "Github"
} |
/*
* Copyright (c) 1997, 2003, 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.
*/
package java.awt.dnd;
import java.util.EventListener;
/**
* The {@code DragSourceListener} defines the
* event interface for originators of
* Drag and Drop operations to track the state of the user's gesture, and to
* provide appropriate "drag over"
* feedback to the user throughout the
* Drag and Drop operation.
* <p>
* The drop site is <i>associated with the previous {@code dragEnter()}
* invocation</i> if the latest invocation of {@code dragEnter()} on this
* listener:
* <ul>
* <li>corresponds to that drop site and
* <li> is not followed by a {@code dragExit()} invocation on this listener.
* </ul>
*
* @since 1.2
*/
public interface DragSourceListener extends EventListener {
/**
* Called as the cursor's hotspot enters a platform-dependent drop site.
* This method is invoked when all the following conditions are true:
* <UL>
* <LI>The cursor's hotspot enters the operable part of a platform-
* dependent drop site.
* <LI>The drop site is active.
* <LI>The drop site accepts the drag.
* </UL>
*
* @param dsde the {@code DragSourceDragEvent}
*/
void dragEnter(DragSourceDragEvent dsde);
/**
* Called as the cursor's hotspot moves over a platform-dependent drop site.
* This method is invoked when all the following conditions are true:
* <UL>
* <LI>The cursor's hotspot has moved, but still intersects the
* operable part of the drop site associated with the previous
* dragEnter() invocation.
* <LI>The drop site is still active.
* <LI>The drop site accepts the drag.
* </UL>
*
* @param dsde the {@code DragSourceDragEvent}
*/
void dragOver(DragSourceDragEvent dsde);
/**
* Called when the user has modified the drop gesture.
* This method is invoked when the state of the input
* device(s) that the user is interacting with changes.
* Such devices are typically the mouse buttons or keyboard
* modifiers that the user is interacting with.
*
* @param dsde the {@code DragSourceDragEvent}
*/
void dropActionChanged(DragSourceDragEvent dsde);
/**
* Called as the cursor's hotspot exits a platform-dependent drop site.
* This method is invoked when any of the following conditions are true:
* <UL>
* <LI>The cursor's hotspot no longer intersects the operable part
* of the drop site associated with the previous dragEnter() invocation.
* </UL>
* OR
* <UL>
* <LI>The drop site associated with the previous dragEnter() invocation
* is no longer active.
* </UL>
* OR
* <UL>
* <LI> The drop site associated with the previous dragEnter() invocation
* has rejected the drag.
* </UL>
*
* @param dse the {@code DragSourceEvent}
*/
void dragExit(DragSourceEvent dse);
/**
* This method is invoked to signify that the Drag and Drop
* operation is complete. The getDropSuccess() method of
* the {@code DragSourceDropEvent} can be used to
* determine the termination state. The getDropAction() method
* returns the operation that the drop site selected
* to apply to the Drop operation. Once this method is complete, the
* current {@code DragSourceContext} and
* associated resources become invalid.
*
* @param dsde the {@code DragSourceDropEvent}
*/
void dragDropEnd(DragSourceDropEvent dsde);
}
| {
"pile_set_name": "Github"
} |
#
# board/renesas/lager/Makefile
#
# Copyright (C) 2013 Renesas Electronics Corporation
#
# SPDX-License-Identifier: GPL-2.0
#
ifdef CONFIG_SPL_BUILD
obj-y := lager_spl.o
else
obj-y := lager.o qos.o
endif
| {
"pile_set_name": "Github"
} |
;;; tablegen-mode.el --- Major mode for TableGen description files (part of LLVM project)
;; Maintainer: The LLVM team, http://llvm.org/
;;; Commentary:
;; A major mode for TableGen description files in LLVM.
(require 'comint)
(require 'custom)
(require 'ansi-color)
;; Create mode-specific tables.
;;; Code:
(defvar td-decorators-face 'td-decorators-face
"Face method decorators.")
(make-face 'td-decorators-face)
(defvar tablegen-font-lock-keywords
(let ((kw (regexp-opt '("class" "defm" "def" "field" "include" "in"
"let" "multiclass" "foreach")
'words))
(type-kw (regexp-opt '("bit" "bits" "code" "dag" "int" "list" "string")
'words))
)
(list
;; Comments
;; '("\/\/" . font-lock-comment-face)
;; Strings
'("\"[^\"]+\"" . font-lock-string-face)
;; Hex constants
'("\\<0x[0-9A-Fa-f]+\\>" . font-lock-preprocessor-face)
;; Binary constants
'("\\<0b[01]+\\>" . font-lock-preprocessor-face)
;; Integer literals
'("\\<[-]?[0-9]+\\>" . font-lock-preprocessor-face)
;; Floating point constants
'("\\<[-+]?[0-9]+\.[0-9]*\([eE][-+]?[0-9]+\)?\\>" . font-lock-preprocessor-face)
'("^[ \t]*\\(@.+\\)" 1 'td-decorators-face)
;; Keywords
(cons (concat kw "[ \n\t(]") 1)
;; Type keywords
(cons (concat type-kw "[ \n\t(]") 1)
))
"Additional expressions to highlight in TableGen mode.")
(put 'tablegen-mode 'font-lock-defaults '(tablegen-font-lock-keywords))
;; ---------------------- Syntax table ---------------------------
;; Shamelessly ripped from jasmin.el
;; URL: http://www.neilvandyke.org/jasmin-emacs/jasmin.el
(defvar tablegen-mode-syntax-table nil
"Syntax table used in `tablegen-mode' buffers.")
(when (not tablegen-mode-syntax-table)
(setq tablegen-mode-syntax-table (make-syntax-table))
;; whitespace (` ')
(modify-syntax-entry ?\ " " tablegen-mode-syntax-table)
(modify-syntax-entry ?\t " " tablegen-mode-syntax-table)
(modify-syntax-entry ?\r " " tablegen-mode-syntax-table)
(modify-syntax-entry ?\n " " tablegen-mode-syntax-table)
(modify-syntax-entry ?\f " " tablegen-mode-syntax-table)
;; word constituents (`w')
(modify-syntax-entry ?\% "w" tablegen-mode-syntax-table)
(modify-syntax-entry ?\_ "w" tablegen-mode-syntax-table)
;; comments
(modify-syntax-entry ?/ ". 124b" tablegen-mode-syntax-table)
(modify-syntax-entry ?* ". 23" tablegen-mode-syntax-table)
(modify-syntax-entry ?\n "> b" tablegen-mode-syntax-table)
;; open paren (`(')
(modify-syntax-entry ?\( "(" tablegen-mode-syntax-table)
(modify-syntax-entry ?\[ "(" tablegen-mode-syntax-table)
(modify-syntax-entry ?\{ "(" tablegen-mode-syntax-table)
(modify-syntax-entry ?\< "(" tablegen-mode-syntax-table)
;; close paren (`)')
(modify-syntax-entry ?\) ")" tablegen-mode-syntax-table)
(modify-syntax-entry ?\] ")" tablegen-mode-syntax-table)
(modify-syntax-entry ?\} ")" tablegen-mode-syntax-table)
(modify-syntax-entry ?\> ")" tablegen-mode-syntax-table)
;; string quote ('"')
(modify-syntax-entry ?\" "\"" tablegen-mode-syntax-table)
)
;; --------------------- Abbrev table -----------------------------
(defvar tablegen-mode-abbrev-table nil
"Abbrev table used while in TableGen mode.")
(define-abbrev-table 'tablegen-mode-abbrev-table ())
(defvar tablegen-mode-hook nil)
(defvar tablegen-mode-map nil) ; Create a mode-specific keymap.
(if (not tablegen-mode-map)
() ; Do not change the keymap if it is already set up.
(setq tablegen-mode-map (make-sparse-keymap))
(define-key tablegen-mode-map "\t" 'tab-to-tab-stop)
(define-key tablegen-mode-map "\es" 'center-line)
(define-key tablegen-mode-map "\eS" 'center-paragraph))
;;;###autoload
(defun tablegen-mode ()
"Major mode for editing TableGen description files.
\\{tablegen-mode-map}
Runs `tablegen-mode-hook' on startup."
(interactive)
(kill-all-local-variables)
(use-local-map tablegen-mode-map) ; Provides the local keymap.
(make-local-variable 'font-lock-defaults)
(setq major-mode 'tablegen-mode ; This is how describe-mode
; finds the doc string to print.
mode-name "TableGen" ; This name goes into the modeline.
local-abbrev-table tablegen-mode-abbrev-table
font-lock-defaults `(tablegen-font-lock-keywords)
require-final-newline t
)
(set-syntax-table tablegen-mode-syntax-table)
(make-local-variable 'comment-start)
(setq comment-start "//")
(setq indent-tabs-mode nil)
(run-hooks 'tablegen-mode-hook)) ; Finally, this permits the user to
; customize the mode with a hook.
;; Associate .td files with tablegen-mode
;;;###autoload
(add-to-list 'auto-mode-alist (cons (purecopy "\\.td\\'") 'tablegen-mode))
(provide 'tablegen-mode)
;;; tablegen-mode.el ends here
| {
"pile_set_name": "Github"
} |
"use strict";
var httpProxy = require("http-proxy");
var utils = require("./utils");
var proxyUtils = require("./proxy-utils");
var Immutable = require("immutable");
var Map = require("immutable").Map;
var List = require("immutable").List;
/**
* Default options that are passed along to http-proxy
*/
var defaultHttpProxyOptions = Map({
/**
* This ensures targets are more likely to
* accept each request
*/
changeOrigin: true,
/**
* This handles redirects
*/
autoRewrite: true,
/**
* This allows our self-signed certs to be used for development
*/
secure: false,
ws: true
});
var defaultCookieOptions = Map({
stripDomain: true
});
var ProxyOption = Immutable.Record({
route: "",
target: "",
rewriteRules: true,
/**
* Functions to be called on proxy request
* with args [proxyReq, req, res, options]
*/
proxyReq: List([]),
/**
* Functions to be called on proxy response
* with args [proxyRes, req, res]
*/
proxyRes: List([]),
/**
* Functions to be called on proxy response
* with args [proxyReq, req, socket, options, head]
*/
proxyReqWs: List([]),
errHandler: undefined,
url: Map({}),
proxyOptions: Map(defaultHttpProxyOptions),
cookies: Map(defaultCookieOptions),
ws: false,
middleware: List([]),
reqHeaders: undefined
});
/**
* @param {BrowserSync} bs
* @param {String} scripts
* @returns {*}
*/
module.exports = function createProxyServer (bs) {
var opt = new ProxyOption().mergeDeep(bs.options.get("proxy"));
var proxy = httpProxy.createProxyServer(opt.get("proxyOptions").set("target", opt.get("target")).toJS());
var target = opt.get("target");
var proxyReq = getProxyReqFunctions(opt.get("proxyReq"), opt, bs);
var proxyRes = getProxyResFunctions(opt.get("proxyRes"), opt);
var proxyResWs = opt.get("proxyReqWs");
bs.options = bs.options.update("middleware", function (mw) {
return mw.concat({
id: "Browsersync Proxy",
route: opt.get("route"),
handle: function (req, res) {
proxy.web(req, res, {
target: target
});
}
});
});
var app = utils.getBaseApp(bs);
/**
* @type {*|{server, app}}
*/
var browserSyncServer = utils.getServer(app, bs.options);
browserSyncServer.proxy = proxy;
if (opt.get("ws")) {
// debug(`+ ws upgrade for: ${x.get("target")}`);
browserSyncServer.server.on("upgrade", function (req, socket, head) {
proxy.ws(req, socket, head);
});
}
/**
* Add any user provided functions for proxyReq, proxyReqWs and proxyRes
*/
applyFns("proxyReq", proxyReq);
applyFns("proxyRes", proxyRes);
applyFns("proxyReqWs", proxyResWs);
/**
* Handle Proxy errors
*/
proxy.on("error", function (err) {
if (typeof opt.get("errHandler") === "function") {
opt.get("errHandler").call(null, err);
}
});
/**
* Apply functions to proxy events
* @param {string} name - the name of the http-proxy event
* @param {Array} fns - functions to call on each event
*/
function applyFns (name, fns) {
if (!List.isList(fns)) fns = [fns];
proxy.on(name, function () {
var args = arguments;
fns.forEach(function(fn) {
if (typeof fn === "function") {
fn.apply(null, args);
}
});
});
}
return browserSyncServer;
};
/**
* @param resFns
* @returns {*}
*/
function getProxyResFunctions (resFns, opt) {
if (opt.getIn(["cookies", "stripDomain"])) {
return resFns.push(proxyUtils.checkCookies);
}
return resFns;
}
/**
* @param reqFns
* @returns {*}
*/
function getProxyReqFunctions (reqFns, opt, bs) {
var reqHeaders = opt.getIn(["reqHeaders"]);
if (!reqHeaders) {
return reqFns;
}
/**
* Back-compat for old `reqHeaders` option here a
* function was given that returned an object
* where key:value was header-name:header-value
* This didn't really work as it clobbered all other headers,
* but it remains for the unlucky few who used it.
*/
if (typeof reqHeaders === "function") {
var output = reqHeaders.call(bs, opt.toJS());
if (Object.keys(output).length) {
return reqFns.concat(function (proxyReq) {
Object.keys(output).forEach(function (key) {
proxyReq.setHeader(key, output[key]);
});
});
}
}
/**
* Now, if {key:value} given, set the each header
*
* eg: reqHeaders: {
* 'is-dev': 'true'
* }
*/
if (Map.isMap(reqHeaders)) {
return reqFns.concat(function (proxyReq) {
reqHeaders.forEach(function (value, key) {
proxyReq.setHeader(key, value);
});
});
}
return reqFns;
}
| {
"pile_set_name": "Github"
} |
---
title: "Why can't I switch Microsoft 365 for business plans?"
f1.keywords:
- NOCSH
ms.author: cmcatee
author: cmcatee-MSFT
manager: mnirkhe
audience: Admin
ms.topic: article
ms.service: o365-administration
localization_priority: Normal
ms.collection:
- M365-subscription-management
- Adm_O365
- Adm_NonTOC
- commerce
ms.custom: AdminSurgePortfolio
search.appverid:
- BCS160
- MET150
- MOE150
- BEA160
- GEA150
ms.assetid: e81e09d2-cd52-4212-8550-5405864b6d62
ROBOTS: NOINDEX
description: "Understand the reasons why sometimes switching plans has to be done manually or by calling support."
---
# Why can't I switch Microsoft 365 for business plans?
::: moniker range="o365-worldwide"
> [!NOTE]
> This article applies to the old admin center. To view the article about the admin center (preview), see [Why can't I upgrade plans?](upgrade-to-different-plan.md#why-cant-i-upgrade-plans). The preview is available to all Microsoft 365 admins, you can opt in by selecting **Try the preview** toggle located at the top of the Home page. For more information, see [About the new Microsoft 365 admin center](../../admin/microsoft-365-admin-center-preview.md).
::: moniker-end
If you don't see the **Switch plans** button, your plan can't be switched automatically. In some cases, you might be able to resolve the issue so that you can use the **Switch plans** button, or you might be able to [switch plans manually](switch-plans-manually.md), instead. Position your mouse over the info icon to view a message that explains why the **Switch plans** button is not available. Use the information in this article to resolve the issue.
::: moniker range="o365-worldwide"
**Need something else?** [Buy another subscription](../buy-another-subscription.md) | [Cancel your subscription](cancel-your-subscription.md) | [Subscriptions and billing](../index.yml) | [Call support](../../admin/contact-support-for-business-products.md)
::: moniker-end
::: moniker range="o365-germany"
**Need something else?** [Buy another subscription](../buy-another-subscription.md) | [Cancel your subscription](cancel-your-subscription.md) | [Subscriptions and billing](../index.yml) | [Call support](../../admin/contact-support-for-business-products.md)
::: moniker-end
::: moniker range="o365-21vianet"
**Need something else?** [Buy or try subscriptions for Office 365 operated by 21Vianet](../../admin/services-in-china/buy-or-try-subscriptions.md) | [Cancel your subscription](cancel-your-subscription.md) | [Call support](../../admin/contact-support-for-business-products.md)
::: moniker-end
## Why isn't the Switch plans button available for my subscription?
### You can't switch subscriptions now because you have more users than licenses.
::: moniker range="o365-worldwide"
To use the **Switch plans** button to switch plans automatically, all of your users need to be assigned valid licenses. If you have assigned more licenses than you have purchased, you'll see an alert on the <a href="https://go.microsoft.com/fwlink/p/?linkid=842264" target="_blank">Licenses</a> page that says you have a licensing conflict that needs to be resolved. [Learn how to resolve license conflicts](../../admin/manage/resolve-license-conflicts.md). After you have resolved any licensing conflicts, you should see the **Switch plans** button. If not, you can [switch plans manually](switch-plans-manually.md), or [call support](../../admin/contact-support-for-business-products.md).
::: moniker-end
::: moniker range="o365-germany"
To use the **Switch plans** button to switch plans automatically, all of your users need to be assigned valid licenses. If you have assigned more licenses than you have purchased, you'll see an alert on the <a href="https://go.microsoft.com/fwlink/p/?linkid=848038" target="_blank">Licenses</a> page that says you have a licensing conflict that needs to be resolved. [Learn how to resolve license conflicts](../../admin/manage/resolve-license-conflicts.md). After you have resolved any licensing conflicts, you should see the **Switch plans** button. If not, you can [switch plans manually](switch-plans-manually.md), or [call support](../../admin/contact-support-for-business-products.md).
::: moniker-end
::: moniker range="o365-21vianet"
To use the **Switch plans** button to switch plans automatically, all of your users need to be assigned valid licenses. If you have assigned more licenses than you have purchased, you'll see an alert on the <a href="https://go.microsoft.com/fwlink/p/?linkid=850625" target="_blank">Licenses</a> page that says you have a licensing conflict that needs to be resolved. [Learn how to resolve license conflicts](../../admin/manage/resolve-license-conflicts.md). After you have resolved any licensing conflicts, you should see the **Switch plans** button. If not, you can [switch plans manually](switch-plans-manually.md), or [call support](../../admin/contact-support-for-business-products.md).
::: moniker-end
### You can't switch subscriptions right now because this subscription isn't fully set up or the service isn't available.
::: moniker range="o365-worldwide"
To see if there are provisioning or service health issues, in the admin center, go to the <a href="https://go.microsoft.com/fwlink/p/?linkid=842900" target="_blank">Service health</a> page, or select **Health** \> **Service health**.
::: moniker-end
::: moniker range="o365-germany"
To see if there are provisioning or service health issues, in the Microsoft 365 admin center, go to the <a href="https://go.microsoft.com/fwlink/p/?linkid=848042" target="_blank">Service health</a> page, or select **Health** \> **Service health**.
::: moniker-end
::: moniker range="o365-21vianet"
To see if there are provisioning or service health issues, in the Microsoft 365 admin center, go to the <a href="https://go.microsoft.com/fwlink/p/?linkid=850629" target="_blank">Service health</a> page, or select **Health** \> **Service health**.
::: moniker-end
If you find that a service is not fully provisioned, or you have a service health issue, please wait a few hours for your service to become available, and try again. If you still have a problem, please [call support](../../admin/contact-support-for-business-products.md).
### You can't switch plans because another plan is in the process of being switched and is pending a credit check.
Wait until the credit check has been completed before switching plans. Credit checks can take up to two working days.
### Currently, this subscription is not eligible to switch plans.
You can [switch plans manually](switch-plans-manually.md) or [call support](../../admin/contact-support-for-business-products.md).
### I see a different message than what's listed here.
You can [switch plans manually](switch-plans-manually.md) or [call support](../../admin/contact-support-for-business-products.md).
## Additional reasons the Switch plans button is unavailable
### You have a prepaid plan
If you've paid for your subscription in advance, you might be able to [switch plans manually](switch-plans-manually.md). However, you won't receive a credit for unused time remaining on your current subscription if you switch plans before the current plan expires.
You can also [call support](../../admin/contact-support-for-business-products.md) for help.
### You have a government or non-profit plan
If you have a government or non-profit plan, you can [switch plans manually](switch-plans-manually.md) or [call support](../../admin/contact-support-for-business-products.md) for help.
### 3,000 or more licenses have been purchased and assigned for the subscription
The **Switch plans** button is unavailable for subscriptions that have 3,000 or more licenses assigned to users. However, you might be able to [switch plans manually](switch-plans-manually.md). You can also [call support](../../admin/contact-support-for-business-products.md) for help.
### The subscription that you want to switch from has a temporary issue
The **Switch plans** button can become temporarily unavailable because the service is in the process of switching a high volume of plans. Try again in about an hour after your first attempt.
### The plan that you want to switch to isn't a supported option
When you switch plans, the plans that are available for you to switch to are displayed based on the services in your current plan. You can only switch to a plan that has the same data-related services, such as Exchange Online or SharePoint Online, or to a higher version of them. This ensures that users don't lose data related to those services during the switch.
If your plan isn't eligible to switch plans automatically, you might be able to [switch plans manually](switch-plans-manually.md), instead. You can also [call support](../../admin/contact-support-for-business-products.md) for help.
> [!NOTE]
> Manually switching from an Office 365 Small Business, Office 365 Small Business Premium, or Office 365 Midsize Business plan is not supported.
## Call support to help you switch plans
[Call support](../../admin/contact-support-for-business-products.md) | {
"pile_set_name": "Github"
} |
// VulcanizeDB
// Copyright © 2019 Vulcanize
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package cmd
import (
"fmt"
"time"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
st "github.com/vulcanize/vulcanizedb/libraries/shared/transformer"
"github.com/vulcanize/vulcanizedb/pkg/config"
ht "github.com/vulcanize/vulcanizedb/pkg/eth/contract_watcher/header/transformer"
"github.com/vulcanize/vulcanizedb/utils"
)
// contractWatcherCmd represents the contractWatcher command
var contractWatcherCmd = &cobra.Command{
Use: "contractWatcher",
Short: "Watches events at the provided contract address using fully synced vDB",
Long: `Uses input contract address and event filters to watch events
Expects an ethereum node to be running
Expects an archival node synced into vulcanizeDB
Requires a .toml config file:
[database]
name = "vulcanize_public"
hostname = "localhost"
port = 5432
[client]
ipcPath = "/Users/user/Library/Ethereum/geth.ipc"
[contract]
network = ""
addresses = [
"contractAddress1",
"contractAddress2"
]
[contract.contractAddress1]
abi = 'ABI for contract 1'
startingBlock = 982463
[contract.contractAddress2]
abi = 'ABI for contract 2'
events = [
"event1",
"event2"
]
eventArgs = [
"arg1",
"arg2"
]
methods = [
"method1",
"method2"
]
methodArgs = [
"arg1",
"arg2"
]
startingBlock = 4448566
piping = true
`,
Run: func(cmd *cobra.Command, args []string) {
subCommand = cmd.CalledAs()
logWithCommand = *log.WithField("SubCommand", subCommand)
contractWatcher()
},
}
var (
mode string
)
func contractWatcher() {
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
blockChain := getBlockChain()
db := utils.LoadPostgres(databaseConfig, blockChain.Node())
var t st.ContractTransformer
con := config.ContractConfig{}
con.PrepConfig()
t = ht.NewTransformer(con, blockChain, &db)
err := t.Init()
if err != nil {
logWithCommand.Fatal(fmt.Sprintf("Failed to initialize transformer, err: %v ", err))
}
for range ticker.C {
err = t.Execute()
if err != nil {
logWithCommand.Error("Execution error for transformer: ", t.GetConfig().Name, err)
}
}
}
func init() {
rootCmd.AddCommand(contractWatcherCmd)
}
| {
"pile_set_name": "Github"
} |
/*
Copyright Charly Chevalier 2015
Copyright Joel Falcou 2015
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)
*/
#if !defined(BOOST_PREDEF_HARDWARE_H) || defined(BOOST_PREDEF_INTERNAL_GENERATE_TESTS)
#ifndef BOOST_PREDEF_HARDWARE_H
#define BOOST_PREDEF_HARDWARE_H
#endif
#include <boost/predef/hardware/simd.h>
#endif
| {
"pile_set_name": "Github"
} |
<subsystem xmlns="urn:jboss:domain:modeshape:3.0">
<repository name="sample">
<custom-binary-storage mime-type-detection="content" min-string-size="10" min-value-size="4096"
classname="org.modeshape.test.SomeStore" module="org.modeshape.test"/>
</repository>
</subsystem> | {
"pile_set_name": "Github"
} |
package net.corda.nodeapi.internal.crypto
import net.corda.core.crypto.newSecureRandom
import net.corda.core.utilities.Try
import net.corda.core.utilities.contextLogger
import net.corda.nodeapi.internal.config.CertificateStore
import net.corda.nodeapi.internal.protonwrapper.netty.init
import org.assertj.core.api.Assertions
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.io.DataInputStream
import java.io.DataOutputStream
import java.io.IOException
import java.net.InetAddress
import java.net.InetSocketAddress
import javax.net.ssl.*
import kotlin.concurrent.thread
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
@RunWith(Parameterized::class)
class TlsDiffAlgorithmsTest(private val serverAlgo: String, private val clientAlgo: String,
private val cipherSuites: Array<String>, private val shouldFail: Boolean) {
companion object {
private val CIPHER_SUITES_ALL = arrayOf(
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
)
private val CIPHER_SUITES_JUST_RSA = arrayOf(
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
)
private val CIPHER_SUITES_JUST_EC = arrayOf(
"TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"
)
@Parameterized.Parameters(name = "ServerAlgo: {0}, ClientAlgo: {1}, Should fail: {3}")
@JvmStatic
fun data() = listOf(
arrayOf("ec", "ec", CIPHER_SUITES_ALL, false), arrayOf("rsa", "rsa", CIPHER_SUITES_ALL, false), arrayOf("ec", "rsa", CIPHER_SUITES_ALL, false), arrayOf("rsa", "ec", CIPHER_SUITES_ALL, false),
arrayOf("ec", "ec", CIPHER_SUITES_JUST_RSA, true), arrayOf("rsa", "rsa", CIPHER_SUITES_JUST_RSA, false), arrayOf("ec", "rsa", CIPHER_SUITES_JUST_RSA, true), arrayOf("rsa", "ec", CIPHER_SUITES_JUST_RSA, false),
arrayOf("ec", "ec", CIPHER_SUITES_JUST_EC, false), arrayOf("rsa", "rsa", CIPHER_SUITES_JUST_EC, true), arrayOf("ec", "rsa", CIPHER_SUITES_JUST_EC, false), arrayOf("rsa", "ec", CIPHER_SUITES_JUST_EC, true)
)
private val logger = contextLogger()
}
@Rule
@JvmField
val tempFolder = TemporaryFolder()
@Test(timeout=300_000)
fun testClientServerTlsExchange() {
//System.setProperty("javax.net.debug", "all")
logger.info("Testing: ServerAlgo: $serverAlgo, ClientAlgo: $clientAlgo, Suites: ${cipherSuites.toList()}, Should fail: $shouldFail")
val trustStore = CertificateStore.fromResource("net/corda/nodeapi/internal/crypto/keystores/trust.jks", "trustpass", "trustpass")
val rootCa = trustStore.value.getCertificate("root")
val serverKeyStore = CertificateStore.fromResource("net/corda/nodeapi/internal/crypto/keystores/float_$serverAlgo.jks", "floatpass", "floatpass")
val serverCa = serverKeyStore.value.getCertificateAndKeyPair("floatcert", "floatpass")
val clientKeyStore = CertificateStore.fromResource("net/corda/nodeapi/internal/crypto/keystores/bridge_$clientAlgo.jks", "bridgepass", "bridgepass")
//val clientCa = clientKeyStore.value.getCertificateAndKeyPair("bridgecert", "bridgepass")
val serverSocketFactory = createSslContext(serverKeyStore, trustStore).serverSocketFactory
val clientSocketFactory = createSslContext(clientKeyStore, trustStore).socketFactory
val serverSocket = (serverSocketFactory.createServerSocket(0) as SSLServerSocket).apply {
// use 0 to get first free socket
val serverParams = SSLParameters(cipherSuites, arrayOf("TLSv1.2"))
serverParams.wantClientAuth = true
serverParams.needClientAuth = true
serverParams.endpointIdentificationAlgorithm = null // Reconfirm default no server name indication, use our own validator.
sslParameters = serverParams
useClientMode = false
}
val clientSocket = (clientSocketFactory.createSocket() as SSLSocket).apply {
val clientParams = SSLParameters(cipherSuites, arrayOf("TLSv1.2"))
clientParams.endpointIdentificationAlgorithm = null // Reconfirm default no server name indication, use our own validator.
sslParameters = clientParams
useClientMode = true
// We need to specify this explicitly because by default the client binds to 'localhost' and we want it to bind
// to whatever <hostname> resolves to(as that's what the server binds to). In particular on Debian <hostname>
// resolves to 127.0.1.1 instead of the external address of the interface, so the ssl handshake fails.
bind(InetSocketAddress(InetAddress.getLocalHost(), 0))
}
val lock = Object()
var done = false
var serverError = false
val testPhrase = "Hello World"
val serverThread = thread {
try {
val sslServerSocket = serverSocket.accept()
assertTrue(sslServerSocket.isConnected)
val serverInput = DataInputStream(sslServerSocket.inputStream)
val receivedString = serverInput.readUTF()
assertEquals(testPhrase, receivedString)
synchronized(lock) {
done = true
lock.notifyAll()
}
sslServerSocket.close()
} catch (ex: Exception) {
serverError = true
}
}
clientSocket.connect(InetSocketAddress(InetAddress.getLocalHost(), serverSocket.localPort))
assertTrue(clientSocket.isConnected)
// Double check hostname manually
val peerChainTry = Try.on { clientSocket.session.peerCertificates.x509 }
assertEquals(!shouldFail, peerChainTry.isSuccess)
when(peerChainTry) {
is Try.Success -> {
val peerChain = peerChainTry.getOrThrow()
val peerX500Principal = peerChain[0].subjectX500Principal
assertEquals(serverCa.certificate.subjectX500Principal, peerX500Principal)
X509Utilities.validateCertificateChain(rootCa, peerChain)
with(DataOutputStream(clientSocket.outputStream)) {
writeUTF(testPhrase)
}
var timeout = 0
synchronized(lock) {
while (!done) {
timeout++
if (timeout > 10) throw IOException("Timed out waiting for server to complete")
lock.wait(1000)
}
}
clientSocket.close()
serverThread.join(1000)
assertFalse { serverError }
serverSocket.close()
assertTrue(done)
}
is Try.Failure -> {
Assertions.assertThatThrownBy {
peerChainTry.getOrThrow()
}.isInstanceOf(SSLPeerUnverifiedException::class.java)
// Tidy-up in case of failure
clientSocket.close()
serverSocket.close()
serverThread.interrupt()
}
}
}
private fun createSslContext(keyStore: CertificateStore, trustStore: CertificateStore): SSLContext {
return SSLContext.getInstance("TLS").apply {
val keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm())
keyManagerFactory.init(keyStore)
val keyManagers = keyManagerFactory.keyManagers
val trustMgrFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustMgrFactory.init(trustStore)
val trustManagers = trustMgrFactory.trustManagers
init(keyManagers, trustManagers, newSecureRandom())
}
}
} | {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include <stdint.h>
#include "gtest/gtest.h"
#include "scoped_ptrs_util.h"
#include "nss.h"
#include "prerror.h"
#include "secasn1.h"
#include "secder.h"
#include "secerr.h"
#include "secitem.h"
namespace nss_test {
struct TemplateAndInput {
const SEC_ASN1Template* t;
SECItem input;
};
class QuickDERTest : public ::testing::Test,
public ::testing::WithParamInterface<TemplateAndInput> {};
static const uint8_t kBitstringTag = 0x03;
static const uint8_t kNullTag = 0x05;
static const uint8_t kLongLength = 0x80;
const SEC_ASN1Template kBitstringTemplate[] = {
{SEC_ASN1_BIT_STRING, 0, NULL, sizeof(SECItem)}, {0}};
// Empty bitstring with unused bits.
static uint8_t kEmptyBitstringUnused[] = {kBitstringTag, 1, 1};
// Bitstring with 8 unused bits.
static uint8_t kBitstring8Unused[] = {kBitstringTag, 3, 8, 0xff, 0x00};
// Bitstring with >8 unused bits.
static uint8_t kBitstring9Unused[] = {kBitstringTag, 3, 9, 0xff, 0x80};
const SEC_ASN1Template kNullTemplate[] = {
{SEC_ASN1_NULL, 0, NULL, sizeof(SECItem)}, {0}};
// Length of zero wrongly encoded as 0x80 instead of 0x00.
static uint8_t kOverlongLength_0_0[] = {kNullTag, kLongLength | 0};
// Length of zero wrongly encoded as { 0x81, 0x00 } instead of 0x00.
static uint8_t kOverlongLength_1_0[] = {kNullTag, kLongLength | 1, 0x00};
// Length of zero wrongly encoded as:
//
// { 0x90, <arbitrary junk of 12 bytes>,
// 0x00, 0x00, 0x00, 0x00 }
//
// instead of 0x00. Note in particular that if there is an integer overflow
// then the arbitrary junk is likely get left-shifted away, as long as there
// are at least sizeof(length) bytes following it. This would be a good way to
// smuggle arbitrary input into DER-encoded data in a way that an non-careful
// parser would ignore.
static uint8_t kOverlongLength_16_0[] = {kNullTag, kLongLength | 0x10,
0x11, 0x22,
0x33, 0x44,
0x55, 0x66,
0x77, 0x88,
0x99, 0xAA,
0xBB, 0xCC,
0x00, 0x00,
0x00, 0x00};
#define TI(t, x) \
{ \
t, { siBuffer, x, sizeof(x) } \
}
static const TemplateAndInput kInvalidDER[] = {
TI(kBitstringTemplate, kEmptyBitstringUnused),
TI(kBitstringTemplate, kBitstring8Unused),
TI(kBitstringTemplate, kBitstring9Unused),
TI(kNullTemplate, kOverlongLength_0_0),
TI(kNullTemplate, kOverlongLength_1_0),
TI(kNullTemplate, kOverlongLength_16_0),
};
#undef TI
TEST_P(QuickDERTest, InvalidLengths) {
const SECItem& original_input(GetParam().input);
ScopedSECItem copy_of_input(SECITEM_AllocItem(nullptr, nullptr, 0U));
ASSERT_TRUE(copy_of_input);
ASSERT_EQ(SECSuccess,
SECITEM_CopyItem(nullptr, copy_of_input.get(), &original_input));
PORTCheapArenaPool pool;
PORT_InitCheapArena(&pool, DER_DEFAULT_CHUNKSIZE);
StackSECItem parsed_value;
ASSERT_EQ(SECFailure,
SEC_QuickDERDecodeItem(&pool.arena, &parsed_value, GetParam().t,
copy_of_input.get()));
ASSERT_EQ(SEC_ERROR_BAD_DER, PR_GetError());
PORT_DestroyCheapArena(&pool);
}
INSTANTIATE_TEST_CASE_P(QuickderTestsInvalidLengths, QuickDERTest,
testing::ValuesIn(kInvalidDER));
} // namespace nss_test
| {
"pile_set_name": "Github"
} |
/* ______ ___ ___
* /\ _ \ /\_ \ /\_ \
* \ \ \L\ \\//\ \ \//\ \ __ __ _ __ ___
* \ \ __ \ \ \ \ \ \ \ /'__`\ /'_ `\/\`'__\/ __`\
* \ \ \/\ \ \_\ \_ \_\ \_/\ __//\ \L\ \ \ \//\ \L\ \
* \ \_\ \_\/\____\/\____\ \____\ \____ \ \_\\ \____/
* \/_/\/_/\/____/\/____/\/____/\/___L\ \/_/ \/___/
* /\____/
* \_/__/
*
* Windowed mode gfx driver using gdi.
*
* By Stefan Schimanski.
*
* Dirty rectangles mechanism and hardware mouse cursor emulation
* by Eric Botcazou.
*
* See readme.txt for copyright information.
*/
#include "allegro.h"
#include "allegro/internal/aintern.h"
#include "allegro/platform/aintwin.h"
#ifndef ALLEGRO_WINDOWS
#error something is wrong with the makefile
#endif
#define PREFIX_I "al-wgdi INFO: "
#define PREFIX_W "al-wgdi WARNING: "
#define PREFIX_E "al-wgdi ERROR: "
static void gfx_gdi_autolock(struct BITMAP* bmp);
static void gfx_gdi_unlock(struct BITMAP* bmp);
/* This is used only in asmlock.s and this file. */
char *gdi_dirty_lines = NULL; /* used in WRITE_BANK() */
/* If custom (asm) calling conversions are used, then the code in asmlock.s is
* used instead.
*/
#if defined(ALLEGRO_NO_ASM)
uintptr_t gfx_gdi_write_bank(BITMAP *bmp, int line)
{
gdi_dirty_lines[bmp->y_ofs +line] = 1;
if (!(bmp->id & BMP_ID_LOCKED))
gfx_gdi_autolock(bmp);
return (uintptr_t) bmp->line[line];
}
void gfx_gdi_unwrite_bank(BITMAP *bmp)
{
if (!(bmp->id & BMP_ID_AUTOLOCK))
return;
gfx_gdi_unlock(bmp);
bmp->id &= ~ BMP_ID_AUTOLOCK;
}
#else /* !defined(ALLEGRO_NO_ASM) */
/* asmlock.s requires these two variables */
void (*ptr_gfx_gdi_autolock)(struct BITMAP* bmp) = gfx_gdi_autolock;
void (*ptr_gfx_gdi_unlock)(struct BITMAP* bmp) = gfx_gdi_unlock;
/* wddraw.h, despite its name, includes the exports from asmlock.s */
#include "wddraw.h"
#endif /* !defined(ALLEGRO_NO_ASM) */
static struct BITMAP *gfx_gdi_init(int w, int h, int v_w, int v_h, int color_depth);
static void gfx_gdi_exit(struct BITMAP *b);
static void gfx_gdi_set_palette(AL_CONST struct RGB *p, int from, int to, int vsync);
static void gfx_gdi_vsync(void);
/* hardware mouse cursor emulation */
static int gfx_gdi_set_mouse_sprite(struct BITMAP *sprite, int xfocus, int yfocus);
static int gfx_gdi_show_mouse(struct BITMAP *bmp, int x, int y);
static void gfx_gdi_hide_mouse(void);
static void gfx_gdi_move_mouse(int x, int y);
GFX_DRIVER gfx_gdi =
{
GFX_GDI,
empty_string,
empty_string,
"GDI",
gfx_gdi_init,
gfx_gdi_exit,
NULL, // AL_METHOD(int, scroll, (int x, int y));
gfx_gdi_vsync,
gfx_gdi_set_palette,
NULL, // AL_METHOD(int, request_scroll, (int x, int y));
NULL, // AL_METHOD(int poll_scroll, (void));
NULL, // AL_METHOD(void, enable_triple_buffer, (void));
NULL, NULL, NULL, NULL, NULL, NULL,
gfx_gdi_set_mouse_sprite,
gfx_gdi_show_mouse,
gfx_gdi_hide_mouse,
gfx_gdi_move_mouse,
NULL, // AL_METHOD(void, drawing_mode, (void));
NULL, // AL_METHOD(void, save_video_state, (void*));
NULL, // AL_METHOD(void, restore_video_state, (void*));
NULL, // AL_METHOD(void, set_blender_mode, (int mode, int r, int g, int b, int a));
NULL, // AL_METHOD(int, fetch_mode_list, (void));
0, 0, // int w, h;
TRUE, // int linear;
0, // long bank_size;
0, // long bank_gran;
0, // long vid_mem;
0, // long vid_phys_base;
TRUE // int windowed;
};
static void gdi_enter_sysmode(void);
static void gdi_exit_sysmode(void);
static void gdi_update_window(RECT *rect);
static WIN_GFX_DRIVER win_gfx_driver_gdi =
{
TRUE,
NULL, // AL_METHOD(void, switch_in, (void));
NULL, // AL_METHOD(void, switch_out, (void));
gdi_enter_sysmode,
gdi_exit_sysmode,
NULL, // AL_METHOD(void, move, (int x, int y, int w, int h));
NULL, // AL_METHOD(void, iconify, (void));
gdi_update_window
};
static char *screen_surf;
static BITMAP *gdi_screen;
static int lock_nesting = 0;
static int render_semaphore = FALSE;
static PALETTE palette;
static HANDLE vsync_event;
#define RENDER_DELAY (1000/70) /* 70 Hz */
/* hardware mouse cursor emulation */
static int mouse_on = FALSE;
static int mouse_was_on = FALSE;
static BITMAP *wgdi_mouse_sprite = NULL;
static BITMAP *mouse_frontbuffer = NULL;
static BITMAP *mouse_backbuffer = NULL;
static int mouse_xfocus, mouse_yfocus;
static int mouse_xpos, mouse_ypos;
/* gfx_gdi_set_mouse_sprite:
*/
static int gfx_gdi_set_mouse_sprite(struct BITMAP *sprite, int xfocus, int yfocus)
{
if (wgdi_mouse_sprite) {
destroy_bitmap(wgdi_mouse_sprite);
wgdi_mouse_sprite = NULL;
destroy_bitmap(mouse_frontbuffer);
mouse_frontbuffer = NULL;
destroy_bitmap(mouse_backbuffer);
mouse_backbuffer = NULL;
}
wgdi_mouse_sprite = create_bitmap(sprite->w, sprite->h);
blit(sprite, wgdi_mouse_sprite, 0, 0, 0, 0, sprite->w, sprite->h);
mouse_xfocus = xfocus;
mouse_yfocus = yfocus;
mouse_frontbuffer = create_bitmap(sprite->w, sprite->h);
mouse_backbuffer = create_bitmap(sprite->w, sprite->h);
return 0;
}
/* update_mouse_pointer:
* Worker function that updates the mouse pointer.
*/
static void update_mouse_pointer(int x, int y, int retrace)
{
HDC hdc;
HWND allegro_wnd = win_get_window();
/* put the screen contents located at the new position into the frontbuffer */
blit(gdi_screen, mouse_frontbuffer, x, y, 0, 0, mouse_frontbuffer->w, mouse_frontbuffer->h);
/* draw the mouse pointer onto the frontbuffer */
draw_sprite(mouse_frontbuffer, wgdi_mouse_sprite, 0, 0);
hdc = GetDC(allegro_wnd);
if (_color_depth == 8)
set_palette_to_hdc(hdc, palette);
if (retrace) {
/* restore the screen contents located at the old position */
blit_to_hdc(mouse_backbuffer, hdc, 0, 0, mouse_xpos, mouse_ypos, mouse_backbuffer->w, mouse_backbuffer->h);
}
/* blit the mouse pointer onto the screen */
blit_to_hdc(mouse_frontbuffer, hdc, 0, 0, x, y, mouse_frontbuffer->w, mouse_frontbuffer->h);
ReleaseDC(allegro_wnd, hdc);
/* save the screen contents located at the new position into the backbuffer */
blit(gdi_screen, mouse_backbuffer, x, y, 0, 0, mouse_backbuffer->w, mouse_backbuffer->h);
/* save the new position */
mouse_xpos = x;
mouse_ypos = y;
}
/* gfx_gdi_show_mouse:
*/
static int gfx_gdi_show_mouse(struct BITMAP *bmp, int x, int y)
{
/* handle only the screen */
if (bmp != gdi_screen)
return -1;
mouse_on = TRUE;
x -= mouse_xfocus;
y -= mouse_yfocus;
update_mouse_pointer(x, y, FALSE);
return 0;
}
/* gfx_gdi_hide_mouse:
*/
static void gfx_gdi_hide_mouse(void)
{
HDC hdc;
HWND allegro_wnd = win_get_window();
if (!mouse_on)
return;
hdc = GetDC(allegro_wnd);
if (_color_depth == 8)
set_palette_to_hdc(hdc, palette);
/* restore the screen contents located at the old position */
blit_to_hdc(mouse_backbuffer, hdc, 0, 0, mouse_xpos, mouse_ypos, mouse_backbuffer->w, mouse_backbuffer->h);
ReleaseDC(allegro_wnd, hdc);
mouse_on = FALSE;
}
/* gfx_gdi_move_mouse:
*/
static void gfx_gdi_move_mouse(int x, int y)
{
if (!mouse_on)
return;
x -= mouse_xfocus;
y -= mouse_yfocus;
if ((mouse_xpos == x) && (mouse_ypos == y))
return;
update_mouse_pointer(x, y, TRUE);
}
/* render_proc:
* Timer proc that updates the window.
*/
static void render_proc(void)
{
int top_line, bottom_line;
HDC hdc = NULL;
HWND allegro_wnd = win_get_window();
/* to prevent reentrant calls */
if (render_semaphore)
return;
render_semaphore = TRUE;
/* to prevent the drawing threads and the rendering proc
* from concurrently accessing the dirty lines array.
*/
_enter_gfx_critical();
if (!gdi_screen) {
_exit_gfx_critical();
render_semaphore = FALSE;
return;
}
/* pseudo dirty rectangles mechanism:
* at most only one GDI call is performed for each frame,
* a true dirty rectangles mechanism makes the demo game
* unplayable in 640x480 on my system.
*/
/* find the first dirty line */
top_line = 0;
while (!gdi_dirty_lines[top_line])
top_line++;
if (top_line < gfx_gdi.h) {
/* find the last dirty line */
bottom_line = gfx_gdi.h-1;
while (!gdi_dirty_lines[bottom_line])
bottom_line--;
hdc = GetDC(allegro_wnd);
if (_color_depth == 8)
set_palette_to_hdc(hdc, palette);
blit_to_hdc(gdi_screen, hdc, 0, top_line, 0, top_line,
gfx_gdi.w, bottom_line - top_line + 1);
/* update mouse pointer if needed */
if (mouse_on) {
if ((mouse_ypos+wgdi_mouse_sprite->h > top_line) && (mouse_ypos <= bottom_line)) {
blit(gdi_screen, mouse_backbuffer, mouse_xpos, mouse_ypos, 0, 0,
mouse_backbuffer->w, mouse_backbuffer->h);
update_mouse_pointer(mouse_xpos, mouse_ypos, TRUE);
}
}
/* clean up the dirty lines */
while (top_line <= bottom_line)
gdi_dirty_lines[top_line++] = 0;
ReleaseDC(allegro_wnd, hdc);
}
_exit_gfx_critical();
/* simulate vertical retrace */
PulseEvent(vsync_event);
render_semaphore = FALSE;
}
/* gdi_enter_sysmode:
*/
static void gdi_enter_sysmode(void)
{
/* hide the mouse pointer */
if (mouse_on) {
mouse_was_on = TRUE;
gfx_gdi_hide_mouse();
_TRACE(PREFIX_I "mouse pointer off\n");
}
}
/* gdi_exit_sysmode:
*/
static void gdi_exit_sysmode(void)
{
if (mouse_was_on) {
mouse_on = TRUE;
mouse_was_on = FALSE;
_TRACE(PREFIX_I "mouse pointer on\n");
}
}
/* gdi_update_window:
* Updates the window.
*/
static void gdi_update_window(RECT *rect)
{
HDC hdc;
HWND allegro_wnd = win_get_window();
_enter_gfx_critical();
if (!gdi_screen) {
_exit_gfx_critical();
return;
}
hdc = GetDC(allegro_wnd);
if (_color_depth == 8)
set_palette_to_hdc(hdc, palette);
blit_to_hdc(gdi_screen, hdc, rect->left, rect->top, rect->left, rect->top,
rect->right - rect->left, rect->bottom - rect->top);
ReleaseDC(allegro_wnd, hdc);
_exit_gfx_critical();
}
/* gfx_gdi_lock:
*/
static void gfx_gdi_lock(struct BITMAP *bmp)
{
/* to prevent the drawing threads and the rendering proc
* from concurrently accessing the dirty lines array
*/
_enter_gfx_critical();
/* arrange for drawing requests to pause when we are in the background */
if (!_win_app_foreground) {
/* stop timer */
remove_int(render_proc);
_exit_gfx_critical();
if (GFX_CRITICAL_RELEASED)
_win_thread_switch_out();
_enter_gfx_critical();
/* restart timer */
install_int(render_proc, RENDER_DELAY);
}
lock_nesting++;
bmp->id |= BMP_ID_LOCKED;
}
/* gfx_gdi_autolock:
*/
static void gfx_gdi_autolock(struct BITMAP *bmp)
{
gfx_gdi_lock(bmp);
bmp->id |= BMP_ID_AUTOLOCK;
}
/* gfx_gdi_unlock:
*/
static void gfx_gdi_unlock(struct BITMAP *bmp)
{
if (lock_nesting > 0) {
lock_nesting--;
if (!lock_nesting)
bmp->id &= ~BMP_ID_LOCKED;
_exit_gfx_critical();
}
}
/* gfx_gdi_init:
*/
static struct BITMAP *gfx_gdi_init(int w, int h, int v_w, int v_h, int color_depth)
{
/* virtual screen are not supported */
if ((v_w!=0 && v_w!=w) || (v_h!=0 && v_h!=h))
return NULL;
_enter_critical();
gfx_gdi.w = w;
gfx_gdi.h = h;
if (adjust_window(w, h) != 0) {
_TRACE(PREFIX_E "window size not supported.\n");
ustrzcpy(allegro_error, ALLEGRO_ERROR_SIZE, get_config_text("Resolution not supported"));
goto Error;
}
/* the last flag serves as an end of loop delimiter */
gdi_dirty_lines = _AL_MALLOC_ATOMIC((h+1) * sizeof(char));
ASSERT(gdi_dirty_lines);
memset(gdi_dirty_lines, 0, (h+1) * sizeof(char));
gdi_dirty_lines[h] = 1;
/* create the screen surface */
screen_surf = _AL_MALLOC_ATOMIC(w * h * BYTES_PER_PIXEL(color_depth));
gdi_screen = _make_bitmap(w, h, (unsigned long)screen_surf, &gfx_gdi, color_depth, w * BYTES_PER_PIXEL(color_depth));
gdi_screen->write_bank = gfx_gdi_write_bank;
_screen_vtable.acquire = gfx_gdi_lock;
_screen_vtable.release = gfx_gdi_unlock;
_screen_vtable.unwrite_bank = gfx_gdi_unwrite_bank;
/* create render timer */
vsync_event = CreateEvent(NULL, FALSE, FALSE, NULL);
install_int(render_proc, RENDER_DELAY);
/* connect to the system driver */
win_gfx_driver = &win_gfx_driver_gdi;
/* set the default switching policy */
set_display_switch_mode(SWITCH_PAUSE);
/* grab input devices */
win_grab_input();
_exit_critical();
return gdi_screen;
Error:
_exit_critical();
gfx_gdi_exit(NULL);
return NULL;
}
/* gfx_gdi_exit:
*/
static void gfx_gdi_exit(struct BITMAP *bmp)
{
_enter_critical();
_enter_gfx_critical();
if (bmp) {
save_window_pos();
clear_bitmap(bmp);
}
/* stop timer */
remove_int(render_proc);
CloseHandle(vsync_event);
/* disconnect from the system driver */
win_gfx_driver = NULL;
/* destroy dirty lines array */
_AL_FREE(gdi_dirty_lines);
gdi_dirty_lines = NULL;
/* destroy screen surface */
_AL_FREE(screen_surf);
gdi_screen = NULL;
/* destroy mouse bitmaps */
if (wgdi_mouse_sprite) {
destroy_bitmap(wgdi_mouse_sprite);
wgdi_mouse_sprite = NULL;
destroy_bitmap(mouse_frontbuffer);
mouse_frontbuffer = NULL;
destroy_bitmap(mouse_backbuffer);
mouse_backbuffer = NULL;
}
_exit_gfx_critical();
/* before restoring video mode, hide window */
set_display_switch_mode(SWITCH_PAUSE);
system_driver->restore_console_state();
restore_window_style();
_exit_critical();
}
/* gfx_gdi_set_palette:
*/
static void gfx_gdi_set_palette(AL_CONST struct RGB *p, int from, int to, int vsync)
{
int c;
for (c=from; c<=to; c++)
palette[c] = p[c];
/* invalidate the whole screen */
_enter_gfx_critical();
gdi_dirty_lines[0] = gdi_dirty_lines[gfx_gdi.h-1] = 1;
_exit_gfx_critical();
}
/* gfx_gdi_vsync:
*/
static void gfx_gdi_vsync(void)
{
WaitForSingleObject(vsync_event, INFINITE);
}
| {
"pile_set_name": "Github"
} |
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"vorm.",
"nachm."
],
"DAY": [
"Sonntag",
"Montag",
"Dienstag",
"Mittwoch",
"Donnerstag",
"Freitag",
"Samstag"
],
"ERANAMES": [
"v. Chr.",
"n. Chr."
],
"ERAS": [
"v. Chr.",
"n. Chr."
],
"MONTH": [
"Januar",
"Februar",
"M\u00e4rz",
"April",
"Mai",
"Juni",
"Juli",
"August",
"September",
"Oktober",
"November",
"Dezember"
],
"SHORTDAY": [
"So.",
"Mo.",
"Di.",
"Mi.",
"Do.",
"Fr.",
"Sa."
],
"SHORTMONTH": [
"Jan.",
"Feb.",
"M\u00e4rz",
"Apr.",
"Mai",
"Juni",
"Juli",
"Aug.",
"Sep.",
"Okt.",
"Nov.",
"Dez."
],
"fullDate": "EEEE, d. MMMM y",
"longDate": "d. MMMM y",
"medium": "dd.MM.y HH:mm:ss",
"mediumDate": "dd.MM.y",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy HH:mm",
"shortDate": "dd.MM.yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
]
},
"id": "de-de",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
| {
"pile_set_name": "Github"
} |
{% extends "base.html" %}
{% load url from future %}
{% block extra_js %}
<script>$(showForm);</script>
{% endblock %}
{% block main %}
{% for room in rooms %}
<div class="room">
<h1><a href="{{ room.get_absolute_url }}">{{ room }}</a></h1>
<ul>
{% for user in room.users.all %}
<li>{{ user }}</li>
{% endfor %}
</ul>
</div>
{% empty %}
<p>There are currently no rooms! Add one below.</p>
{% endfor %}
<br clear="all">
{% endblock %}
{% block form %}
<form method="post" action="{% url "create" %}">
<input type="text" id="name" name="name">
<input type="submit" id="submit" value="Add Room">
{% csrf_token %}
</form>
{% endblock %}
| {
"pile_set_name": "Github"
} |
package cc.blynk.server.application.handlers.main.logic;
import cc.blynk.server.Holder;
import cc.blynk.server.application.handlers.main.auth.MobileStateHolder;
import cc.blynk.server.core.dao.SessionDao;
import cc.blynk.server.core.dao.SharedTokenManager;
import cc.blynk.server.core.model.DashBoard;
import cc.blynk.server.core.protocol.model.messages.StringMessage;
import io.netty.channel.ChannelHandlerContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import static cc.blynk.server.internal.CommonByteBufUtil.ok;
/**
* The Blynk Project.
* Created by Dmitriy Dumanskiy.
* Created on 2/1/2015.
*
*/
public final class MobileDeActivateDashboardLogic {
private static final Logger log = LogManager.getLogger(MobileActivateDashboardLogic.class);
private MobileDeActivateDashboardLogic() {
}
public static void messageReceived(Holder holder, ChannelHandlerContext ctx,
MobileStateHolder state, StringMessage message) {
var user = state.user;
String sharedToken;
if (message.body.length() > 0) {
log.debug("DeActivating dash {} for user {}", message.body, user.email);
int dashId = Integer.parseInt(message.body);
DashBoard dashBoard = user.profile.getDashByIdOrThrow(dashId);
dashBoard.deactivate();
sharedToken = dashBoard.sharedToken;
} else {
for (DashBoard dashBoard : user.profile.dashBoards) {
dashBoard.deactivate();
}
sharedToken = SharedTokenManager.ALL;
}
user.lastModifiedTs = System.currentTimeMillis();
SessionDao sessionDao = holder.sessionDao;
var session = sessionDao.get(state.userKey);
session.sendToSharedApps(ctx.channel(), sharedToken, message.command, message.id, message.body);
ctx.writeAndFlush(ok(message.id), ctx.voidPromise());
}
}
| {
"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="zh">
<head>
<!-- Generated by javadoc (1.8.0_102) on Fri Jun 21 17:27:20 CST 2019 -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>BaseAdapter (music-player-lib API)</title>
<meta name="date" content="2019-06-21">
<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="BaseAdapter (music-player-lib API)";
}
}
catch(err) {
}
//-->
var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":6,"i8":10,"i9":6,"i10":10,"i11":10,"i12":10,"i13":10,"i14":10,"i15":10,"i16":10,"i17":10,"i18":10,"i19":10,"i20":10,"i21":10};
var tabs = {65535:["t0","所有方法"],2:["t2","实例方法"],4:["t3","抽象方法"],8:["t4","具体方法"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</script>
<noscript>
<div>您的浏览器已禁用 JavaScript。</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="跳过导航链接">跳过导航链接</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../../../overview-summary.html">概览</a></li>
<li><a href="package-summary.html">程序包</a></li>
<li class="navBarCell1Rev">类</li>
<li><a href="package-tree.html">树</a></li>
<li><a href="../../../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../../../index-all.html">索引</a></li>
<li><a href="../../../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>上一个类</li>
<li><a href="../../../../../../com/music/player/lib/adapter/base/OnItemClickListener.html" title="com.music.player.lib.adapter.base中的接口"><span class="typeNameLink">下一个类</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/music/player/lib/adapter/base/BaseAdapter.html" target="_top">框架</a></li>
<li><a href="BaseAdapter.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">所有类</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>
<div>
<ul class="subNavList">
<li>概要: </li>
<li>嵌套 | </li>
<li><a href="#field.summary">字段</a> | </li>
<li><a href="#constructor.summary">构造器</a> | </li>
<li><a href="#method.summary">方法</a></li>
</ul>
<ul class="subNavList">
<li>详细资料: </li>
<li><a href="#field.detail">字段</a> | </li>
<li><a href="#constructor.detail">构造器</a> | </li>
<li><a href="#method.detail">方法</a></li>
</ul>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">com.music.player.lib.adapter.base</div>
<h2 title="类 BaseAdapter" class="title">类 BaseAdapter<T,V extends RecyclerView.ViewHolder></h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li><any></li>
<li>
<ul class="inheritance">
<li>com.music.player.lib.adapter.base.BaseAdapter<T,V></li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>直接已知子类:</dt>
<dd><a href="../../../../../../com/music/player/lib/adapter/MusicAlarmAdapter.html" title="com.music.player.lib.adapter中的类">MusicAlarmAdapter</a>, <a href="../../../../../../com/music/player/lib/adapter/MusicPlayerListAdapter.html" title="com.music.player.lib.adapter中的类">MusicPlayerListAdapter</a></dd>
</dl>
<hr>
<br>
<pre>public abstract class <span class="typeNameLabel">BaseAdapter<T,V extends RecyclerView.ViewHolder></span>
extends <any></pre>
<div class="block">[email protected]
2019/3/23
BaseAdapter T:DateType,V:ViewHolder</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== FIELD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.summary">
<!-- -->
</a>
<h3>字段概要</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="字段概要表, 列表字段和解释">
<caption><span>字段</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">限定符和类型</th>
<th class="colLast" scope="col">字段和说明</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected Context</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#mContext">mContext</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected java.util.List<<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#mData">mData</a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>protected LayoutInflater</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#mInflater">mInflater</a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#TAG">TAG</a></span></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>构造器概要</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="构造器概要表, 列表构造器和解释">
<caption><span>构造器</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">构造器和说明</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#BaseAdapter-Context-">BaseAdapter</a></span>(Context context)</code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#BaseAdapter-Context-java.util.List-">BaseAdapter</a></span>(Context context,
java.util.List<<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a>> data)</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>方法概要</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="方法概要表, 列表方法和解释">
<caption><span id="t0" class="activeTableTab"><span>所有方法</span><span class="tabEnd"> </span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">实例方法</a></span><span class="tabEnd"> </span></span><span id="t3" class="tableTab"><span><a href="javascript:show(4);">抽象方法</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">具体方法</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">限定符和类型</th>
<th class="colLast" scope="col">方法和说明</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#addData-java.util.List-">addData</a></span>(java.util.List<<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a>> data)</code>
<div class="block">追加一个数据集</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#addData-T-">addData</a></span>(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a> data)</code>
<div class="block">追加一个元素至底部</div>
</td>
</tr>
<tr id="i2" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#addDataToTop-T-">addDataToTop</a></span>(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a> data)</code>
<div class="block">向顶部添加一个元素</div>
</td>
</tr>
<tr id="i3" class="rowColor">
<td class="colFirst"><code>Context</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#getContext--">getContext</a></span>()</code> </td>
</tr>
<tr id="i4" class="altColor">
<td class="colFirst"><code>java.util.List<<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a>></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#getData--">getData</a></span>()</code>
<div class="block">返回列表数据集</div>
</td>
</tr>
<tr id="i5" class="rowColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#getItemCount--">getItemCount</a></span>()</code> </td>
</tr>
<tr id="i6" class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#getItemData-int-">getItemData</a></span>(int position)</code>
<div class="block">返回数据集中的元素</div>
</td>
</tr>
<tr id="i7" class="rowColor">
<td class="colFirst"><code>abstract void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#inBindViewHolder-V-int-">inBindViewHolder</a></span>(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a> viewHolder,
int position)</code>
<div class="block">全量刷新</div>
</td>
</tr>
<tr id="i8" class="altColor">
<td class="colFirst"><code>protected void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#inBindViewHolder-V-int-java.util.List-">inBindViewHolder</a></span>(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a> viewHolder,
int position,
java.util.List<java.lang.Object> payloads)</code>
<div class="block">局部刷新</div>
</td>
</tr>
<tr id="i9" class="rowColor">
<td class="colFirst"><code>abstract <a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#inCreateViewHolder-ViewGroup-int-">inCreateViewHolder</a></span>(ViewGroup viewGroup,
int viewType)</code>
<div class="block">ViewHolder Init</div>
</td>
</tr>
<tr id="i10" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#onBindViewHolder-V-int-">onBindViewHolder</a></span>(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a> holder,
int position)</code> </td>
</tr>
<tr id="i11" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#onBindViewHolder-V-int-java.util.List-">onBindViewHolder</a></span>(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a> holder,
int position,
java.util.List<java.lang.Object> payloads)</code> </td>
</tr>
<tr id="i12" class="altColor">
<td class="colFirst"><code><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#onCreateViewHolder-ViewGroup-int-">onCreateViewHolder</a></span>(ViewGroup parent,
int viewType)</code> </td>
</tr>
<tr id="i13" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#onDestroy--">onDestroy</a></span>()</code>
<div class="block">对应生命周期调用</div>
</td>
</tr>
<tr id="i14" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#onLoadComplete--">onLoadComplete</a></span>()</code>
<div class="block">加载成功</div>
</td>
</tr>
<tr id="i15" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#onLoadEnd--">onLoadEnd</a></span>()</code>
<div class="block">加载完成</div>
</td>
</tr>
<tr id="i16" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#onLoadError--">onLoadError</a></span>()</code>
<div class="block">加载失败</div>
</td>
</tr>
<tr id="i17" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#setEmptyView-View-">setEmptyView</a></span>(View emptyView)</code>
<div class="block">设置占位布局</div>
</td>
</tr>
<tr id="i18" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#setNewData-java.util.List-">setNewData</a></span>(java.util.List<<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a>> data)</code>
<div class="block">更新适配器</div>
</td>
</tr>
<tr id="i19" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#setOnItemClickListener-com.music.player.lib.adapter.base.OnItemClickListener-">setOnItemClickListener</a></span>(<a href="../../../../../../com/music/player/lib/adapter/base/OnItemClickListener.html" title="com.music.player.lib.adapter.base中的接口">OnItemClickListener</a> onItemClickListener)</code> </td>
</tr>
<tr id="i20" class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#setOnLoadMoreListener-com.music.player.lib.adapter.base.OnLoadMoreListener-RecyclerView-">setOnLoadMoreListener</a></span>(<a href="../../../../../../com/music/player/lib/adapter/base/OnLoadMoreListener.html" title="com.music.player.lib.adapter.base中的类">OnLoadMoreListener</a> loadMoreListener,
RecyclerView recyclerView)</code> </td>
</tr>
<tr id="i21" class="rowColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html#setOnLongItemClickListener-com.music.player.lib.adapter.base.OnItemLongClickListener-">setOnLongItemClickListener</a></span>(<a href="../../../../../../com/music/player/lib/adapter/base/OnItemLongClickListener.html" title="com.music.player.lib.adapter.base中的接口">OnItemLongClickListener</a> onLongItemClickListener)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>从类继承的方法 java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ FIELD DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="field.detail">
<!-- -->
</a>
<h3>字段详细资料</h3>
<a name="TAG">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>TAG</h4>
<pre>protected static final java.lang.String TAG</pre>
<dl>
<dt><span class="seeLabel">另请参阅:</span></dt>
<dd><a href="../../../../../../constant-values.html#com.music.player.lib.adapter.base.BaseAdapter.TAG">常量字段值</a></dd>
</dl>
</li>
</ul>
<a name="mContext">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>mContext</h4>
<pre>protected Context mContext</pre>
</li>
</ul>
<a name="mInflater">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>mInflater</h4>
<pre>protected LayoutInflater mInflater</pre>
</li>
</ul>
<a name="mData">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>mData</h4>
<pre>protected java.util.List<<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a>> mData</pre>
</li>
</ul>
</li>
</ul>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>构造器详细资料</h3>
<a name="BaseAdapter-Context-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>BaseAdapter</h4>
<pre>public BaseAdapter(Context context)</pre>
</li>
</ul>
<a name="BaseAdapter-Context-java.util.List-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>BaseAdapter</h4>
<pre>public BaseAdapter(Context context,
java.util.List<<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a>> data)</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>方法详细资料</h3>
<a name="onCreateViewHolder-ViewGroup-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>onCreateViewHolder</h4>
<pre>public <a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a> onCreateViewHolder(ViewGroup parent,
int viewType)</pre>
</li>
</ul>
<a name="onBindViewHolder-RecyclerView.ViewHolder-int-">
<!-- -->
</a><a name="onBindViewHolder-V-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>onBindViewHolder</h4>
<pre>public void onBindViewHolder(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a> holder,
int position)</pre>
</li>
</ul>
<a name="onBindViewHolder-RecyclerView.ViewHolder-int-java.util.List-">
<!-- -->
</a><a name="onBindViewHolder-V-int-java.util.List-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>onBindViewHolder</h4>
<pre>public void onBindViewHolder(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a> holder,
int position,
java.util.List<java.lang.Object> payloads)</pre>
</li>
</ul>
<a name="getItemCount--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getItemCount</h4>
<pre>public int getItemCount()</pre>
</li>
</ul>
<a name="getContext--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getContext</h4>
<pre>public Context getContext()</pre>
</li>
</ul>
<a name="inCreateViewHolder-ViewGroup-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>inCreateViewHolder</h4>
<pre>public abstract <a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a> inCreateViewHolder(ViewGroup viewGroup,
int viewType)</pre>
<div class="block">ViewHolder Init</div>
<dl>
<dt><span class="paramLabel">参数:</span></dt>
<dd><code>viewGroup</code> - </dd>
<dd><code>viewType</code> - </dd>
<dt><span class="returnLabel">返回:</span></dt>
<dd>默认或你定义的ViewHolder</dd>
</dl>
</li>
</ul>
<a name="inBindViewHolder-RecyclerView.ViewHolder-int-">
<!-- -->
</a><a name="inBindViewHolder-V-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>inBindViewHolder</h4>
<pre>public abstract void inBindViewHolder(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a> viewHolder,
int position)</pre>
<div class="block">全量刷新</div>
<dl>
<dt><span class="paramLabel">参数:</span></dt>
<dd><code>viewHolder</code> - </dd>
<dd><code>position</code> - </dd>
</dl>
</li>
</ul>
<a name="inBindViewHolder-RecyclerView.ViewHolder-int-java.util.List-">
<!-- -->
</a><a name="inBindViewHolder-V-int-java.util.List-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>inBindViewHolder</h4>
<pre>protected void inBindViewHolder(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">V</a> viewHolder,
int position,
java.util.List<java.lang.Object> payloads)</pre>
<div class="block">局部刷新</div>
<dl>
<dt><span class="paramLabel">参数:</span></dt>
<dd><code>viewHolder</code> - </dd>
<dd><code>position</code> - </dd>
<dd><code>payloads</code> - </dd>
</dl>
</li>
</ul>
<a name="getItemData-int-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getItemData</h4>
<pre>protected <a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a> getItemData(int position)</pre>
<div class="block">返回数据集中的元素</div>
<dl>
<dt><span class="paramLabel">参数:</span></dt>
<dd><code>position</code> - Lists position</dd>
<dt><span class="returnLabel">返回:</span></dt>
<dd>适配器持有的数据集</dd>
</dl>
</li>
</ul>
<a name="getData--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getData</h4>
<pre>public java.util.List<<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a>> getData()</pre>
<div class="block">返回列表数据集</div>
<dl>
<dt><span class="returnLabel">返回:</span></dt>
<dd>数据集</dd>
</dl>
</li>
</ul>
<a name="setNewData-java.util.List-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setNewData</h4>
<pre>public void setNewData(java.util.List<<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a>> data)</pre>
<div class="block">更新适配器</div>
<dl>
<dt><span class="paramLabel">参数:</span></dt>
<dd><code>data</code> - </dd>
</dl>
</li>
</ul>
<a name="addData-java.util.List-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addData</h4>
<pre>public void addData(java.util.List<<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a>> data)</pre>
<div class="block">追加一个数据集</div>
<dl>
<dt><span class="paramLabel">参数:</span></dt>
<dd><code>data</code> - </dd>
</dl>
</li>
</ul>
<a name="addData-java.lang.Object-">
<!-- -->
</a><a name="addData-T-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addData</h4>
<pre>public void addData(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a> data)</pre>
<div class="block">追加一个元素至底部</div>
<dl>
<dt><span class="paramLabel">参数:</span></dt>
<dd><code>data</code> - </dd>
</dl>
</li>
</ul>
<a name="addDataToTop-java.lang.Object-">
<!-- -->
</a><a name="addDataToTop-T-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>addDataToTop</h4>
<pre>public void addDataToTop(<a href="../../../../../../com/music/player/lib/adapter/base/BaseAdapter.html" title="BaseAdapter中的类型参数">T</a> data)</pre>
<div class="block">向顶部添加一个元素</div>
<dl>
<dt><span class="paramLabel">参数:</span></dt>
<dd><code>data</code> - </dd>
</dl>
</li>
</ul>
<a name="onDestroy--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>onDestroy</h4>
<pre>public void onDestroy()</pre>
<div class="block">对应生命周期调用</div>
</li>
</ul>
<a name="setOnItemClickListener-com.music.player.lib.adapter.base.OnItemClickListener-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setOnItemClickListener</h4>
<pre>public void setOnItemClickListener(<a href="../../../../../../com/music/player/lib/adapter/base/OnItemClickListener.html" title="com.music.player.lib.adapter.base中的接口">OnItemClickListener</a> onItemClickListener)</pre>
</li>
</ul>
<a name="setOnLongItemClickListener-com.music.player.lib.adapter.base.OnItemLongClickListener-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setOnLongItemClickListener</h4>
<pre>public void setOnLongItemClickListener(<a href="../../../../../../com/music/player/lib/adapter/base/OnItemLongClickListener.html" title="com.music.player.lib.adapter.base中的接口">OnItemLongClickListener</a> onLongItemClickListener)</pre>
</li>
</ul>
<a name="setOnLoadMoreListener-com.music.player.lib.adapter.base.OnLoadMoreListener-RecyclerView-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>setOnLoadMoreListener</h4>
<pre>public void setOnLoadMoreListener(<a href="../../../../../../com/music/player/lib/adapter/base/OnLoadMoreListener.html" title="com.music.player.lib.adapter.base中的类">OnLoadMoreListener</a> loadMoreListener,
RecyclerView recyclerView)</pre>
</li>
</ul>
<a name="onLoadComplete--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>onLoadComplete</h4>
<pre>public void onLoadComplete()</pre>
<div class="block">加载成功</div>
</li>
</ul>
<a name="onLoadEnd--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>onLoadEnd</h4>
<pre>public void onLoadEnd()</pre>
<div class="block">加载完成</div>
</li>
</ul>
<a name="onLoadError--">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>onLoadError</h4>
<pre>public void onLoadError()</pre>
<div class="block">加载失败</div>
</li>
</ul>
<a name="setEmptyView-View-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>setEmptyView</h4>
<pre>public void setEmptyView(View emptyView)</pre>
<div class="block">设置占位布局</div>
<dl>
<dt><span class="paramLabel">参数:</span></dt>
<dd><code>emptyView</code> - </dd>
</dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="跳过导航链接">跳过导航链接</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="导航">
<li><a href="../../../../../../overview-summary.html">概览</a></li>
<li><a href="package-summary.html">程序包</a></li>
<li class="navBarCell1Rev">类</li>
<li><a href="package-tree.html">树</a></li>
<li><a href="../../../../../../deprecated-list.html">已过时</a></li>
<li><a href="../../../../../../index-all.html">索引</a></li>
<li><a href="../../../../../../help-doc.html">帮助</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>上一个类</li>
<li><a href="../../../../../../com/music/player/lib/adapter/base/OnItemClickListener.html" title="com.music.player.lib.adapter.base中的接口"><span class="typeNameLink">下一个类</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/music/player/lib/adapter/base/BaseAdapter.html" target="_top">框架</a></li>
<li><a href="BaseAdapter.html" target="_top">无框架</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">所有类</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>
<div>
<ul class="subNavList">
<li>概要: </li>
<li>嵌套 | </li>
<li><a href="#field.summary">字段</a> | </li>
<li><a href="#constructor.summary">构造器</a> | </li>
<li><a href="#method.summary">方法</a></li>
</ul>
<ul class="subNavList">
<li>详细资料: </li>
<li><a href="#field.detail">字段</a> | </li>
<li><a href="#constructor.detail">构造器</a> | </li>
<li><a href="#method.detail">方法</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"pile_set_name": "Github"
} |
/*------------------------------------------------------------------------
* Copyright 2007-2009 (c) Jeff Brown <[email protected]>
*
* This file is part of the ZBar Bar Code Reader.
*
* The ZBar Bar Code Reader is free software; you can redistribute it
* and/or modify it under the terms of the GNU Lesser Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* The ZBar Bar Code Reader 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with the ZBar Bar Code Reader; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*
* http://sourceforge.net/projects/zbar
*------------------------------------------------------------------------*/
#include "processor.h"
#include <assert.h>
/* the processor api lock is a recursive mutex with added capabilities
* to completely drop all lock levels before blocking and atomically
* unblock a waiting set. the lock is implemented using a variation
* of the "specific notification pattern" [cargill], which makes it
* easy to provide these features across platforms with consistent,
* predictable semantics. probably overkill, but additional overhead
* associated with this mechanism should fall in the noise, as locks
* are only exchanged O(frame/image)
*
* [cargill]
* http://www.profcon.com/profcon/cargill/jgf/9809/SpecificNotification.html
*/
static inline proc_waiter_t *proc_waiter_queue (zbar_processor_t *proc)
{
proc_waiter_t *waiter = proc->free_waiter;
if(waiter) {
proc->free_waiter = waiter->next;
waiter->events = 0;
}
else {
waiter = calloc(1, sizeof(proc_waiter_t));
_zbar_event_init(&waiter->notify);
}
waiter->next = NULL;
waiter->requester = _zbar_thread_self();
if(proc->wait_head)
proc->wait_tail->next = waiter;
else
proc->wait_head = waiter;
proc->wait_tail = waiter;
return(waiter);
}
static inline proc_waiter_t *proc_waiter_dequeue (zbar_processor_t *proc)
{
proc_waiter_t *prev = proc->wait_next, *waiter;
if(prev)
waiter = prev->next;
else
waiter = proc->wait_head;
while(waiter && (waiter->events & EVENTS_PENDING)) {
prev = waiter;
proc->wait_next = waiter;
waiter = waiter->next;
}
if(waiter) {
if(prev)
prev->next = waiter->next;
else
proc->wait_head = waiter->next;
if(!waiter->next)
proc->wait_tail = prev;
waiter->next = NULL;
proc->lock_level = 1;
proc->lock_owner = waiter->requester;
}
return(waiter);
}
static inline void proc_waiter_release (zbar_processor_t *proc,
proc_waiter_t *waiter)
{
if(waiter) {
waiter->next = proc->free_waiter;
proc->free_waiter = waiter;
}
}
int _zbar_processor_lock (zbar_processor_t *proc)
{
if(!proc->lock_level) {
proc->lock_owner = _zbar_thread_self();
proc->lock_level = 1;
return(0);
}
if(_zbar_thread_is_self(proc->lock_owner)) {
proc->lock_level++;
return(0);
}
proc_waiter_t *waiter = proc_waiter_queue(proc);
_zbar_event_wait(&waiter->notify, &proc->mutex, NULL);
assert(proc->lock_level == 1);
assert(_zbar_thread_is_self(proc->lock_owner));
proc_waiter_release(proc, waiter);
return(0);
}
int _zbar_processor_unlock (zbar_processor_t *proc,
int all)
{
assert(proc->lock_level > 0);
assert(_zbar_thread_is_self(proc->lock_owner));
if(all)
proc->lock_level = 0;
else
proc->lock_level--;
if(!proc->lock_level) {
proc_waiter_t *waiter = proc_waiter_dequeue(proc);
if(waiter)
_zbar_event_trigger(&waiter->notify);
}
return(0);
}
void _zbar_processor_notify (zbar_processor_t *proc,
unsigned events)
{
proc->wait_next = NULL;
proc_waiter_t *waiter;
for(waiter = proc->wait_head; waiter; waiter = waiter->next)
waiter->events = ((waiter->events & ~events) |
(events & EVENT_CANCELED));
if(!proc->lock_level) {
waiter = proc_waiter_dequeue(proc);
if(waiter)
_zbar_event_trigger(&waiter->notify);
}
}
static inline int proc_wait_unthreaded (zbar_processor_t *proc,
proc_waiter_t *waiter,
zbar_timer_t *timeout)
{
int blocking = proc->streaming && zbar_video_get_fd(proc->video) < 0;
_zbar_mutex_unlock(&proc->mutex);
int rc = 1;
while(rc > 0 && (waiter->events & EVENTS_PENDING)) {
/* FIXME lax w/the locking (though shouldn't matter...) */
if(blocking) {
zbar_image_t *img = zbar_video_next_image(proc->video);
if(!img) {
rc = -1;
break;
}
/* FIXME reacquire API lock! (refactor w/video thread?) */
_zbar_mutex_lock(&proc->mutex);
_zbar_process_image(proc, img);
zbar_image_destroy(img);
_zbar_mutex_unlock(&proc->mutex);
}
int reltime = _zbar_timer_check(timeout);
if(blocking && (reltime < 0 || reltime > MAX_INPUT_BLOCK))
reltime = MAX_INPUT_BLOCK;
rc = _zbar_processor_input_wait(proc, NULL, reltime);
}
_zbar_mutex_lock(&proc->mutex);
return(rc);
}
int _zbar_processor_wait (zbar_processor_t *proc,
unsigned events,
zbar_timer_t *timeout)
{
_zbar_mutex_lock(&proc->mutex);
int save_level = proc->lock_level;
proc_waiter_t *waiter = proc_waiter_queue(proc);
waiter->events = events & EVENTS_PENDING;
_zbar_processor_unlock(proc, 1);
int rc;
if(proc->threaded)
rc = _zbar_event_wait(&waiter->notify, &proc->mutex, timeout);
else
rc = proc_wait_unthreaded(proc, waiter, timeout);
if(rc <= 0 || !proc->threaded) {
/* reacquire api lock */
waiter->events &= EVENT_CANCELED;
proc->wait_next = NULL;
if(!proc->lock_level) {
proc_waiter_t *w = proc_waiter_dequeue(proc);
assert(w == waiter);
}
else
_zbar_event_wait(&waiter->notify, &proc->mutex, NULL);
}
if(rc > 0 && (waiter->events & EVENT_CANCELED))
rc = -1;
assert(proc->lock_level == 1);
assert(_zbar_thread_is_self(proc->lock_owner));
proc->lock_level = save_level;
proc_waiter_release(proc, waiter);
_zbar_mutex_unlock(&proc->mutex);
return(rc);
}
| {
"pile_set_name": "Github"
} |
#include "ofApp.h"
void ofApp::setup() {
// each 512x512x3 texture is about .7MB
// so n = 512 will use about 400MB of texture memory
int n = 512;
for(int i = 0; i < n; i++) {
ofTexture cur;
cur.allocate(512, 512, GL_RGB);
textures.push_back(cur);
}
}
void ofApp::update() {
}
void ofApp::draw() {
int i = ofMap(mouseX, 0, ofGetWidth(), 0, textures.size() - 1, true);
textures[i].draw(0, 0);
} | {
"pile_set_name": "Github"
} |
#!/bin/bash
travis_fold() {
local action="${1}"
local name="${2}"
echo -en "travis_fold:${action}:${name}\r"
}
build_containers() {
# Build Docker images
travis_fold start docker_image_build
DOCKER_IMAGES=(django nginx)
for docker_image in "${DOCKER_IMAGES[@]}"
do
docker build \
--tag "defectdojo/defectdojo-${docker_image}" \
--file "Dockerfile.${docker_image}" \
.
return_value=${?}
if [ ${return_value} -ne 0 ]; then
(>&2 echo "ERROR: cannot build '${docker_image}' image")
exit ${return_value}
fi
done
travis_fold end docker_image_build
}
return_value=0
if [ -z "${TEST}" ]; then
build_containers
# Start Minikube
travis_fold start minikube_install
sudo minikube start \
--vm-driver=none \
--kubernetes-version="${K8S_VERSION}"
# Configure Kubernetes context and test it
sudo minikube update-context
sudo kubectl cluster-info
# Enable Nginx ingress add-on and wait for it
sudo minikube addons enable ingress
echo -n "Waiting for Nginx ingress controller "
until [[ "True" == "$(sudo kubectl get pod \
--selector=app.kubernetes.io/name=nginx-ingress-controller \
--namespace=kube-system \
-o 'jsonpath={.items[*].status.conditions[?(@.type=="Ready")].status}')" ]]
do
sleep 1
echo -n "."
done
echo
# Create Helm and wait for Tiller to become ready
sudo helm init
echo -n "Waiting for Tiller "
until [[ "True" == "$(sudo kubectl get pod \
--selector=name=tiller \
--namespace=kube-system \
-o 'jsonpath={.items[*].status.conditions[?(@.type=="Ready")].status}')" ]]
do
sleep 1
echo -n "."
done
echo
# Update Helm repository
sudo helm repo update
# Update Helm dependencies for DefectDojo
sudo helm dependency update ./helm/defectdojo
# Set Helm settings for the broker
case "${BROKER}" in
rabbitmq)
HELM_BROKER_SETTINGS=" \
--set redis.enabled=false \
--set rabbitmq.enabled=true \
--set celery.broker=rabbitmq \
--set createRabbitMqSecret=true \
"
;;
redis)
HELM_BROKER_SETTINGS=" \
--set redis.enabled=true \
--set rabbitmq.enabled=false \
--set celery.broker=redis \
--set createRedisSecret=true \
"
;;
*)
(>&2 echo "ERROR: 'BROKER' must be 'redis' or 'rabbitmq'")
exit 1
;;
esac
# Set Helm settings for the database
case "${DATABASE}" in
mysql)
HELM_DATABASE_SETTINGS=" \
--set database=mysql \
--set postgresql.enabled=false \
--set mysql.enabled=true \
--set createMysqlSecret=true \
"
;;
postgresql)
HELM_DATABASE_SETTINGS=" \
--set database=postgresql \
--set postgresql.enabled=true \
--set mysql.enabled=false \
--set createPostgresqlSecret=true \
"
;;
*)
(>&2 echo "ERROR: 'DATABASE' must be 'mysql' or 'postgresql'")
exit 1
;;
esac
# Install DefectDojo into Kubernetes and wait for it
sudo helm install \
./helm/defectdojo \
--name=defectdojo \
--set django.ingress.enabled=false \
--set imagePullPolicy=Never \
${HELM_BROKER_SETTINGS} \
${HELM_DATABASE_SETTINGS} \
--set createSecret=true
echo -n "Waiting for DefectDojo to become ready "
i=0
# Timeout value so that the wait doesn't timeout the travis build (faster fail)
TIMEOUT=20
until [[ "True" == "$(sudo kubectl get pod \
--selector=defectdojo.org/component=django \
-o 'jsonpath={.items[*].status.conditions[?(@.type=="Ready")].status}')" \
|| ${i} -gt ${TIMEOUT} ]]
do
((i++))
sleep 6
echo -n "."
done
if [[ ${i} -gt ${TIMEOUT} ]]; then
return_value=1
fi
echo
echo "UWSGI logs"
sudo kubectl logs --selector=defectdojo.org/component=django -c uwsgi
echo
echo "DefectDojo is up and running."
sudo kubectl get pods
travis_fold end minikube_install
# Run all tests
travis_fold start defectdojo_tests
echo "Running tests."
sudo helm test defectdojo
# Check exit status
return_value=${?}
echo
echo "Unit test results"
sudo kubectl logs defectdojo-unit-tests
echo
echo "Pods"
sudo kubectl get pods
# Uninstall
echo "Deleting DefectDojo from Kubernetes"
sudo helm delete defectdojo --purge
sudo kubectl get pods
travis_fold end defectdojo_tests
exit ${return_value}
else
echo "Running test ${TEST}"
case "${TEST}" in
flake8)
echo "${TRAVIS_BRANCH}"
if [[ "${TRAVIS_BRANCH}" == "dev" ]]
then
echo "Running Flake8 tests on dev branch aka pull requests"
# We need to checkout dev for flake8-diff to work properly
git checkout dev
sudo pip3 install pep8 flake8==3.7.9 flake8-diff
flake8-diff
else
echo "Skipping because not on dev branch"
fi
;;
docker_integration_tests)
echo "Validating docker compose"
# change user id withn Docker container to user id of travis user
sed -i -e "s/USER\ 1001/USER\ `id -u`/g" ./Dockerfile.django
cp ./dojo/settings/settings.dist.py ./dojo/settings/settings.py
# incase of failure and you need to debug
# change the 'release' mode to 'dev' mode in order to activate debug=True
# make sure you remember to change back to 'release' before making a PR
source ./docker/setEnv.sh release
docker-compose build
docker-compose up -d
echo "Waiting for services to start"
# Wait for services to become available
sleep 80
echo "Testing DefectDojo Service"
curl -s -o "/dev/null" http://localhost:8080 -m 120
CR=$(curl -s -m 10 -I http://localhost:8080/login?next= | egrep "^HTTP" | cut -d' ' -f2)
if [ "$CR" != 200 ]; then
echo "ERROR: cannot display login screen; got HTTP code $CR"
docker-compose logs --tail="all" uwsgi
exit 1
fi
echo "Docker compose container status"
docker-compose -f docker-compose.yml ps
echo "run integration_test scripts"
source ./travis/integration_test-script.sh
;;
snyk)
echo "Snyk security testing on containers"
build_containers
snyk monitor --docker defectdojo/defectdojo-django:latest
snyk monitor --docker defectdojo/defectdojo-nginx:latest
;;
deploy)
echo "Deploy and container push"
build_containers
source ./travis/deploy.sh
deploy_demo
docker_hub
;;
esac
fi
| {
"pile_set_name": "Github"
} |
package com.grapeshot.halfnes.mappers;
import com.grapeshot.halfnes.*;
public class Mapper182 extends Mapper {
//Pirate MMC3 clone with scrambled registers
private int whichbank = 0;
private boolean prgconfig = false;
private boolean chrconfig = false;
private int irqctrreload = 0;
private int irqctr = 0;
private boolean irqenable = false;
private boolean irqreload = false;
private int bank6 = 0;
private int[] chrreg = {0, 0, 0, 0, 0, 0};
private boolean interrupted = false;
@Override
public void loadrom() throws BadMapperException {
//needs to be in every mapper. Fill with initial cfg
super.loadrom();
for (int i = 1; i <= 32; ++i) {
prg_map[32 - i] = prgsize - (1024 * i);
}
for (int i = 0; i < 8; ++i) {
chr_map[i] = 0;
}
setbank6();
//cpuram.setPrgRAMEnable(false);
}
@Override
public final void cartWrite(int addr, int data) {
if (addr < 0x8000 || addr > 0xffff) {
super.cartWrite(addr, data);
return;
}
//bankswitches here
//different register for even/odd writes
if (((addr & (utils.BIT0)) != 0)) {
//odd registers
if ((addr >= 0x8000) && (addr <= 0x9fff)) {
//mirroring setup
setmirroring(((data & (utils.BIT0)) != 0) ? MirrorType.H_MIRROR : MirrorType.V_MIRROR);
} else if ((addr >= 0xA000) && (addr <= 0xBFFF)) {
//prg ram write protect
//cpuram.setPrgRAMEnable(!utils.getbit(data, 7));
} else if ((addr >= 0xC000) && (addr <= 0xDFFF)) {
//any value here reloads irq counter _@ end of scanline_
irqreload = true;
irqctrreload = data;
} else if ((addr >= 0xE000) && (addr <= 0xFFFF)) {
//any value here enables interrupts
irqenable = true;
}
} else {
//even registers
if ((addr >= 0xA000) && (addr <= 0xBFFF)) {
//bank select
whichbank = data & 7;
prgconfig = ((data & (utils.BIT4)) != 0);
//if bit is false, 8000-9fff swappable and c000-dfff fixed to 2nd to last bank
//if bit is true, c000-dfff swappable and 8000-9fff fixed to 2nd to last bank
chrconfig = ((data & (utils.BIT5)) != 0);
//if false: 2 2k banks @ 0000-0fff, 4 1k banks in 1000-1fff
//if true: 4 1k banks @ 0000-0fff, 2 2k banks @ 1000-1fff
setupchr();
setbank6(); //OOPS FORGOT THIS I GUESS
} else if ((addr >= 0xC000) && (addr <= 0xDFFF)) {
//bank select
switch (whichbank) {
case 0:
chrreg[0] = data;
setupchr();
break;
case 1:
chrreg[3] = data;
setupchr();
break;
case 2:
chrreg[1] = data;
setupchr();
break;
case 3:
chrreg[5] = data;
setupchr();
break;
case 4:
bank6 = data;
setbank6();
break;
case 5:
//bank 5 always swappable, always in same place
for (int i = 0; i < 8; ++i) {
prg_map[i + 8] = (1024 * (i + (data * 8))) % prgsize;
}
break;
case 6:
chrreg[2] = data;
setupchr();
break;
case 7:
chrreg[4] = data;
setupchr();
break;
}
} else if ((addr >= 0xE000) && (addr <= 0xFFFF)) {
//any value here disables IRQ and acknowledges
if (interrupted) {
--cpu.interrupt;
}
interrupted = false;
irqenable = false;
irqctr = irqctrreload;
}
}
}
private void setupchr() {
if (chrconfig) {
setppubank(1, 0, chrreg[2]);
setppubank(1, 1, chrreg[3]);
setppubank(1, 2, chrreg[4]);
setppubank(1, 3, chrreg[5]);
//Lowest bit of bank number IS IGNORED for the 2k banks
setppubank(2, 4, (chrreg[0] >> 1) << 1);
setppubank(2, 6, (chrreg[1] >> 1) << 1);
} else {
setppubank(1, 4, chrreg[2]);
setppubank(1, 5, chrreg[3]);
setppubank(1, 6, chrreg[4]);
setppubank(1, 7, chrreg[5]);
setppubank(2, 0, (chrreg[0] >> 1) << 1);
setppubank(2, 2, (chrreg[1] >> 1) << 1);
}
}
private void setbank6() {
if (!prgconfig) {
//map c000-dfff to last bank, 8000-9fff to selected bank
for (int i = 0; i < 8; ++i) {
prg_map[i] = (1024 * (i + (bank6 * 8))) % prgsize;
prg_map[i + 16] = ((prgsize - 16384) + 1024 * i);
}
} else {
//map 8000-9fff to last bank, c000 to dfff to selected bank
for (int i = 0; i < 8; ++i) {
prg_map[i] = ((prgsize - 16384) + 1024 * i);
prg_map[i + 16] = (1024 * (i + (bank6 * 8))) % prgsize;
}
}
}
@Override
public void notifyscanline(int scanline) {
//Scanline counter
if (scanline > 239 && scanline != 261) {
//clocked on LAST line of vblank and all lines of frame. Not on 240.
return;
}
if (!ppu.mmc3CounterClocking()) {
return;
}
if (irqreload) {
irqreload = false;
irqctr = irqctrreload;
}
if (irqctr-- <= 0) {
if (irqctrreload == 0) {
return;
//irqs stop being generated if reload set to zero
}
if (irqenable && !interrupted) {
++cpu.interrupt;
interrupted = true;
}
irqctr = irqctrreload;
}
}
private void setppubank(int banksize, int bankpos, int banknum) {
// System.err.println(banksize + ", " + bankpos + ", "+ banknum);
for (int i = 0; i < banksize; ++i) {
chr_map[i + bankpos] = (1024 * ((banknum) + i)) % chrsize;
}
}
}
| {
"pile_set_name": "Github"
} |
/*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not read 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.
*/
#include "gtest/gtest.h"
#include "nodes.h"
#include "primitive.h"
namespace art {
/**
* Tests for the SideEffects class.
*/
//
// Helper methods.
//
void testWriteAndReadSanity(SideEffects write, SideEffects read) {
EXPECT_FALSE(write.DoesNothing());
EXPECT_FALSE(read.DoesNothing());
EXPECT_TRUE(write.DoesAnyWrite());
EXPECT_FALSE(write.DoesAnyRead());
EXPECT_FALSE(read.DoesAnyWrite());
EXPECT_TRUE(read.DoesAnyRead());
// All-dependences.
SideEffects all = SideEffects::All();
EXPECT_TRUE(all.MayDependOn(write));
EXPECT_FALSE(write.MayDependOn(all));
EXPECT_FALSE(all.MayDependOn(read));
EXPECT_TRUE(read.MayDependOn(all));
// None-dependences.
SideEffects none = SideEffects::None();
EXPECT_FALSE(none.MayDependOn(write));
EXPECT_FALSE(write.MayDependOn(none));
EXPECT_FALSE(none.MayDependOn(read));
EXPECT_FALSE(read.MayDependOn(none));
}
void testWriteAndReadDependence(SideEffects write, SideEffects read) {
testWriteAndReadSanity(write, read);
// Dependence only in one direction.
EXPECT_FALSE(write.MayDependOn(read));
EXPECT_TRUE(read.MayDependOn(write));
}
void testNoWriteAndReadDependence(SideEffects write, SideEffects read) {
testWriteAndReadSanity(write, read);
// No dependence in any direction.
EXPECT_FALSE(write.MayDependOn(read));
EXPECT_FALSE(read.MayDependOn(write));
}
//
// Actual tests.
//
TEST(SideEffectsTest, All) {
SideEffects all = SideEffects::All();
EXPECT_TRUE(all.DoesAnyWrite());
EXPECT_TRUE(all.DoesAnyRead());
EXPECT_FALSE(all.DoesNothing());
EXPECT_TRUE(all.DoesAllReadWrite());
}
TEST(SideEffectsTest, None) {
SideEffects none = SideEffects::None();
EXPECT_FALSE(none.DoesAnyWrite());
EXPECT_FALSE(none.DoesAnyRead());
EXPECT_TRUE(none.DoesNothing());
EXPECT_FALSE(none.DoesAllReadWrite());
}
TEST(SideEffectsTest, DependencesAndNoDependences) {
// Apply test to each individual primitive type.
for (Primitive::Type type = Primitive::kPrimNot;
type < Primitive::kPrimVoid;
type = Primitive::Type(type + 1)) {
// Same primitive type and access type: proper write/read dep.
testWriteAndReadDependence(
SideEffects::FieldWriteOfType(type, false),
SideEffects::FieldReadOfType(type, false));
testWriteAndReadDependence(
SideEffects::ArrayWriteOfType(type),
SideEffects::ArrayReadOfType(type));
// Same primitive type but different access type: no write/read dep.
testNoWriteAndReadDependence(
SideEffects::FieldWriteOfType(type, false),
SideEffects::ArrayReadOfType(type));
testNoWriteAndReadDependence(
SideEffects::ArrayWriteOfType(type),
SideEffects::FieldReadOfType(type, false));
}
}
TEST(SideEffectsTest, NoDependences) {
// Different primitive type, same access type: no write/read dep.
testNoWriteAndReadDependence(
SideEffects::FieldWriteOfType(Primitive::kPrimInt, false),
SideEffects::FieldReadOfType(Primitive::kPrimDouble, false));
testNoWriteAndReadDependence(
SideEffects::ArrayWriteOfType(Primitive::kPrimInt),
SideEffects::ArrayReadOfType(Primitive::kPrimDouble));
// Everything different: no write/read dep.
testNoWriteAndReadDependence(
SideEffects::FieldWriteOfType(Primitive::kPrimInt, false),
SideEffects::ArrayReadOfType(Primitive::kPrimDouble));
testNoWriteAndReadDependence(
SideEffects::ArrayWriteOfType(Primitive::kPrimInt),
SideEffects::FieldReadOfType(Primitive::kPrimDouble, false));
}
TEST(SideEffectsTest, VolatileDependences) {
SideEffects volatile_write =
SideEffects::FieldWriteOfType(Primitive::kPrimInt, /* is_volatile */ true);
SideEffects any_write =
SideEffects::FieldWriteOfType(Primitive::kPrimInt, /* is_volatile */ false);
SideEffects volatile_read =
SideEffects::FieldReadOfType(Primitive::kPrimByte, /* is_volatile */ true);
SideEffects any_read =
SideEffects::FieldReadOfType(Primitive::kPrimByte, /* is_volatile */ false);
EXPECT_FALSE(volatile_write.MayDependOn(any_read));
EXPECT_TRUE(any_read.MayDependOn(volatile_write));
EXPECT_TRUE(volatile_write.MayDependOn(any_write));
EXPECT_FALSE(any_write.MayDependOn(volatile_write));
EXPECT_FALSE(volatile_read.MayDependOn(any_read));
EXPECT_TRUE(any_read.MayDependOn(volatile_read));
EXPECT_TRUE(volatile_read.MayDependOn(any_write));
EXPECT_FALSE(any_write.MayDependOn(volatile_read));
}
TEST(SideEffectsTest, SameWidthTypesNoAlias) {
// Type I/F.
testNoWriteAndReadDependence(
SideEffects::FieldWriteOfType(Primitive::kPrimInt, /* is_volatile */ false),
SideEffects::FieldReadOfType(Primitive::kPrimFloat, /* is_volatile */ false));
testNoWriteAndReadDependence(
SideEffects::ArrayWriteOfType(Primitive::kPrimInt),
SideEffects::ArrayReadOfType(Primitive::kPrimFloat));
// Type L/D.
testNoWriteAndReadDependence(
SideEffects::FieldWriteOfType(Primitive::kPrimLong, /* is_volatile */ false),
SideEffects::FieldReadOfType(Primitive::kPrimDouble, /* is_volatile */ false));
testNoWriteAndReadDependence(
SideEffects::ArrayWriteOfType(Primitive::kPrimLong),
SideEffects::ArrayReadOfType(Primitive::kPrimDouble));
}
TEST(SideEffectsTest, AllWritesAndReads) {
SideEffects s = SideEffects::None();
// Keep taking the union of different writes and reads.
for (Primitive::Type type = Primitive::kPrimNot;
type < Primitive::kPrimVoid;
type = Primitive::Type(type + 1)) {
s = s.Union(SideEffects::FieldWriteOfType(type, /* is_volatile */ false));
s = s.Union(SideEffects::ArrayWriteOfType(type));
s = s.Union(SideEffects::FieldReadOfType(type, /* is_volatile */ false));
s = s.Union(SideEffects::ArrayReadOfType(type));
}
EXPECT_TRUE(s.DoesAllReadWrite());
}
TEST(SideEffectsTest, GC) {
SideEffects can_trigger_gc = SideEffects::CanTriggerGC();
SideEffects depends_on_gc = SideEffects::DependsOnGC();
SideEffects all_changes = SideEffects::AllChanges();
SideEffects all_dependencies = SideEffects::AllDependencies();
EXPECT_TRUE(depends_on_gc.MayDependOn(can_trigger_gc));
EXPECT_TRUE(depends_on_gc.Union(can_trigger_gc).MayDependOn(can_trigger_gc));
EXPECT_FALSE(can_trigger_gc.MayDependOn(depends_on_gc));
EXPECT_TRUE(depends_on_gc.MayDependOn(all_changes));
EXPECT_TRUE(depends_on_gc.Union(can_trigger_gc).MayDependOn(all_changes));
EXPECT_FALSE(can_trigger_gc.MayDependOn(all_changes));
EXPECT_TRUE(all_changes.Includes(can_trigger_gc));
EXPECT_FALSE(all_changes.Includes(depends_on_gc));
EXPECT_TRUE(all_dependencies.Includes(depends_on_gc));
EXPECT_FALSE(all_dependencies.Includes(can_trigger_gc));
}
TEST(SideEffectsTest, BitStrings) {
EXPECT_STREQ(
"|||||||",
SideEffects::None().ToString().c_str());
EXPECT_STREQ(
"|GC|DFJISCBZL|DFJISCBZL|GC|DFJISCBZL|DFJISCBZL|",
SideEffects::All().ToString().c_str());
EXPECT_STREQ(
"|||||DFJISCBZL|DFJISCBZL|",
SideEffects::AllWrites().ToString().c_str());
EXPECT_STREQ(
"||DFJISCBZL|DFJISCBZL||||",
SideEffects::AllReads().ToString().c_str());
EXPECT_STREQ(
"||||||L|",
SideEffects::FieldWriteOfType(Primitive::kPrimNot, false).ToString().c_str());
EXPECT_STREQ(
"||DFJISCBZL|DFJISCBZL||DFJISCBZL|DFJISCBZL|",
SideEffects::FieldWriteOfType(Primitive::kPrimNot, true).ToString().c_str());
EXPECT_STREQ(
"|||||Z||",
SideEffects::ArrayWriteOfType(Primitive::kPrimBoolean).ToString().c_str());
EXPECT_STREQ(
"|||||C||",
SideEffects::ArrayWriteOfType(Primitive::kPrimChar).ToString().c_str());
EXPECT_STREQ(
"|||||S||",
SideEffects::ArrayWriteOfType(Primitive::kPrimShort).ToString().c_str());
EXPECT_STREQ(
"|||B||||",
SideEffects::FieldReadOfType(Primitive::kPrimByte, false).ToString().c_str());
EXPECT_STREQ(
"||D|||||",
SideEffects::ArrayReadOfType(Primitive::kPrimDouble).ToString().c_str());
EXPECT_STREQ(
"||J|||||",
SideEffects::ArrayReadOfType(Primitive::kPrimLong).ToString().c_str());
EXPECT_STREQ(
"||F|||||",
SideEffects::ArrayReadOfType(Primitive::kPrimFloat).ToString().c_str());
EXPECT_STREQ(
"||I|||||",
SideEffects::ArrayReadOfType(Primitive::kPrimInt).ToString().c_str());
SideEffects s = SideEffects::None();
s = s.Union(SideEffects::FieldWriteOfType(Primitive::kPrimChar, /* is_volatile */ false));
s = s.Union(SideEffects::FieldWriteOfType(Primitive::kPrimLong, /* is_volatile */ false));
s = s.Union(SideEffects::ArrayWriteOfType(Primitive::kPrimShort));
s = s.Union(SideEffects::FieldReadOfType(Primitive::kPrimInt, /* is_volatile */ false));
s = s.Union(SideEffects::ArrayReadOfType(Primitive::kPrimFloat));
s = s.Union(SideEffects::ArrayReadOfType(Primitive::kPrimDouble));
EXPECT_STREQ("||DF|I||S|JC|", s.ToString().c_str());
}
} // namespace art
| {
"pile_set_name": "Github"
} |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef nsICSSRule_h___
#define nsICSSRule_h___
#include "nsIStyleRule.h"
class nsICSSStyleSheet;
class nsICSSGroupRule;
class nsIDOMCSSRule;
class nsAString;
// IID for the nsICSSRule interface {b9791e20-1a04-11d3-805a-006008159b5a}
#define NS_ICSS_RULE_IID \
{0xb9791e20, 0x1a04, 0x11d3, {0x80, 0x5a, 0x00, 0x60, 0x08, 0x15, 0x9b, 0x5a}}
class nsICSSRule : public nsIStyleRule {
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_ICSS_RULE_IID)
enum {
UNKNOWN_RULE = 0,
STYLE_RULE = 1,
IMPORT_RULE = 2,
MEDIA_RULE = 3,
FONT_FACE_RULE = 4,
PAGE_RULE = 5,
CHARSET_RULE = 6,
NAMESPACE_RULE = 7,
DOCUMENT_RULE = 8
};
NS_IMETHOD GetType(PRInt32& aType) const = 0;
NS_IMETHOD GetStyleSheet(nsIStyleSheet*& aSheet) const = 0;
NS_IMETHOD SetStyleSheet(nsICSSStyleSheet* aSheet) = 0;
NS_IMETHOD SetParentRule(nsICSSGroupRule* aRule) = 0;
NS_IMETHOD Clone(nsICSSRule*& aClone) const = 0;
// Note that this returns null for inline style rules since they aren't
// supposed to have a DOM rule representation (and our code wouldn't work).
NS_IMETHOD GetDOMRule(nsIDOMCSSRule** aDOMRule) = 0;
};
/* Define global NS_New* functions for rules that don't need their own
interfaces here */
nsresult
NS_NewCSSCharsetRule(nsICSSRule** aInstancePtrResult,
const nsAString& aEncoding);
#endif /* nsICSSRule_h___ */
| {
"pile_set_name": "Github"
} |
/******************************************************************************
*******************************************************************************
**
** Copyright (C) Sistina Software, Inc. 1997-2003 All rights reserved.
** Copyright (C) 2004-2009 Red Hat, Inc. All rights reserved.
**
** This copyrighted material is made available to anyone wishing to use,
** modify, copy, or redistribute it subject to the terms and conditions
** of the GNU General Public License v.2.
**
*******************************************************************************
******************************************************************************/
#ifndef __LOWCOMMS_DOT_H__
#define __LOWCOMMS_DOT_H__
int dlm_lowcomms_start(void);
void dlm_lowcomms_stop(void);
void dlm_lowcomms_exit(void);
int dlm_lowcomms_close(int nodeid);
void *dlm_lowcomms_get_buffer(int nodeid, int len, gfp_t allocation, char **ppc);
void dlm_lowcomms_commit_buffer(void *mh);
int dlm_lowcomms_connect_node(int nodeid);
int dlm_lowcomms_addr(int nodeid, struct sockaddr_storage *addr, int len);
#endif /* __LOWCOMMS_DOT_H__ */
| {
"pile_set_name": "Github"
} |
[Info]
ID=Google Earth
Ver=1.0
Desc=This will download ninite installer for Google Earth
Dev=Ninite
DevURL=https://ninite.com/
Evaluation=App
EvaluationColor=002BAE
Update=False
[Variables]
GoogleEarth=googleearth
[Code]
File1=Get,https://ninite.com/%GoogleEarth%/ninite.exe,DEFAULT
Task1=Start(),ninite.exe
[Undo]
Info1=Msg,This script will ONLY download an application.\nNo system changes are made here! | {
"pile_set_name": "Github"
} |
package com.sequenceiq.freeipa.flow.freeipa.chain;
import static org.junit.Assert.assertEquals;
import java.util.List;
import java.util.Queue;
import java.util.stream.Collectors;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import com.sequenceiq.cloudbreak.common.event.Selectable;
import com.sequenceiq.freeipa.flow.chain.FlowChainTriggers;
import com.sequenceiq.freeipa.flow.chain.RepairFlowEventChainFactory;
import com.sequenceiq.freeipa.flow.freeipa.repair.event.RepairEvent;
public class RepairFlowEventChainFactoryTest {
private static final long STACK_ID = 1L;
private static final String OPERATION_ID = "operation-id";
private static final int INSTANCE_COUNT_BY_GROUP = 2;
private static final List<String> INSTANCE_IDS_TO_REPAIR = List.of("instance1");
private static final List<String> TERMINATED_INSTANCE_IDS = List.of("instance2");
@InjectMocks
private RepairFlowEventChainFactory underTest;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testRepair() {
RepairEvent event = new RepairEvent(FlowChainTriggers.REPAIR_TRIGGER_EVENT, STACK_ID,
OPERATION_ID, INSTANCE_COUNT_BY_GROUP, INSTANCE_IDS_TO_REPAIR, TERMINATED_INSTANCE_IDS);
Queue<Selectable> eventQueues = underTest.createFlowTriggerEventQueue(event);
List<String> triggeredOperations = eventQueues.stream().map(Selectable::selector).collect(Collectors.toList());
assertEquals(List.of("CHANGE_PRIMARY_GATEWAY_EVENT", "DOWNSCALE_EVENT", "UPSCALE_EVENT", "CHANGE_PRIMARY_GATEWAY_EVENT"), triggeredOperations);
}
}
| {
"pile_set_name": "Github"
} |
/-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura
-/
import Lean.Environment
namespace Lean
/- Given a structure `S`, Lean automatically creates an auxiliary definition (projection function)
for each field. This structure caches information about these auxiliary definitions. -/
structure ProjectionFunctionInfo :=
(ctorName : Name) -- Constructor associated with the auxiliary projection function.
(nparams : Nat) -- Number of parameters in the structure
(i : Nat) -- The field index associated with the auxiliary projection function.
(fromClass : Bool) -- `true` if the structure is a class
@[export lean_mk_projection_info]
def mkProjectionInfoEx (ctorName : Name) (nparams : Nat) (i : Nat) (fromClass : Bool) : ProjectionFunctionInfo :=
{ctorName := ctorName, nparams := nparams, i := i, fromClass := fromClass }
@[export lean_projection_info_from_class]
def ProjectionFunctionInfo.fromClassEx (info : ProjectionFunctionInfo) : Bool := info.fromClass
instance ProjectionFunctionInfo.inhabited : Inhabited ProjectionFunctionInfo :=
⟨{ ctorName := arbitrary _, nparams := arbitrary _, i := 0, fromClass := false }⟩
def mkProjectionFnInfoExtension : IO (SimplePersistentEnvExtension (Name × ProjectionFunctionInfo) (NameMap ProjectionFunctionInfo)) :=
registerSimplePersistentEnvExtension {
name := `projinfo,
addImportedFn := fun as => {},
addEntryFn := fun s p => s.insert p.1 p.2,
toArrayFn := fun es => es.toArray.qsort (fun a b => Name.quickLt a.1 b.1)
}
@[init mkProjectionFnInfoExtension]
constant projectionFnInfoExt : SimplePersistentEnvExtension (Name × ProjectionFunctionInfo) (NameMap ProjectionFunctionInfo) := arbitrary _
@[export lean_add_projection_info]
def addProjectionFnInfo (env : Environment) (projName : Name) (ctorName : Name) (nparams : Nat) (i : Nat) (fromClass : Bool) : Environment :=
projectionFnInfoExt.addEntry env (projName, { ctorName := ctorName, nparams := nparams, i := i, fromClass := fromClass })
namespace Environment
@[export lean_get_projection_info]
def getProjectionFnInfo? (env : Environment) (projName : Name) : Option ProjectionFunctionInfo :=
match env.getModuleIdxFor? projName with
| some modIdx =>
match (projectionFnInfoExt.getModuleEntries env modIdx).binSearch (projName, arbitrary _) (fun a b => Name.quickLt a.1 b.1) with
| some e => some e.2
| none => none
| none => (projectionFnInfoExt.getState env).find? projName
def isProjectionFn (env : Environment) (n : Name) : Bool :=
match env.getModuleIdxFor? n with
| some modIdx => (projectionFnInfoExt.getModuleEntries env modIdx).binSearchContains (n, arbitrary _) (fun a b => Name.quickLt a.1 b.1)
| none => (projectionFnInfoExt.getState env).contains n
/-- If `projName` is the name of a projection function, return the associated structure name -/
def getProjectionStructureName? (env : Environment) (projName : Name) : Option Name :=
match env.getProjectionFnInfo? projName with
| none => none
| some projInfo =>
match env.find? projInfo.ctorName with
| some (ConstantInfo.ctorInfo val) => some val.induct
| _ => none
end Environment
end Lean
| {
"pile_set_name": "Github"
} |
#import "Expecta.h"
EXPMatcherInterface(notify, (id expectedNotification));
| {
"pile_set_name": "Github"
} |
// Copyright 2010 Google Inc. All Rights Reserved.
//
// Use of this source code is governed by a BSD-style license
// that can be found in the COPYING file in the root of the source
// tree. An additional intellectual property rights grant can be found
// in the file PATENTS. All contributing project authors may
// be found in the AUTHORS file in the root of the source tree.
// -----------------------------------------------------------------------------
//
// Frame-reconstruction function. Memory allocation.
//
// Author: Skal ([email protected])
#include <stdlib.h>
#include "src/dec/vp8i_dec.h"
#include "src/utils/utils.h"
//------------------------------------------------------------------------------
// Main reconstruction function.
static const uint16_t kScan[16] = {
0 + 0 * BPS, 4 + 0 * BPS, 8 + 0 * BPS, 12 + 0 * BPS,
0 + 4 * BPS, 4 + 4 * BPS, 8 + 4 * BPS, 12 + 4 * BPS,
0 + 8 * BPS, 4 + 8 * BPS, 8 + 8 * BPS, 12 + 8 * BPS,
0 + 12 * BPS, 4 + 12 * BPS, 8 + 12 * BPS, 12 + 12 * BPS
};
static int CheckMode(int mb_x, int mb_y, int mode) {
if (mode == B_DC_PRED) {
if (mb_x == 0) {
return (mb_y == 0) ? B_DC_PRED_NOTOPLEFT : B_DC_PRED_NOLEFT;
} else {
return (mb_y == 0) ? B_DC_PRED_NOTOP : B_DC_PRED;
}
}
return mode;
}
static void Copy32b(uint8_t* const dst, const uint8_t* const src) {
memcpy(dst, src, 4);
}
static WEBP_INLINE void DoTransform(uint32_t bits, const int16_t* const src,
uint8_t* const dst) {
switch (bits >> 30) {
case 3:
VP8Transform(src, dst, 0);
break;
case 2:
VP8TransformAC3(src, dst);
break;
case 1:
VP8TransformDC(src, dst);
break;
default:
break;
}
}
static void DoUVTransform(uint32_t bits, const int16_t* const src,
uint8_t* const dst) {
if (bits & 0xff) { // any non-zero coeff at all?
if (bits & 0xaa) { // any non-zero AC coefficient?
VP8TransformUV(src, dst); // note we don't use the AC3 variant for U/V
} else {
VP8TransformDCUV(src, dst);
}
}
}
static void ReconstructRow(const VP8Decoder* const dec,
const VP8ThreadContext* ctx) {
int j;
int mb_x;
const int mb_y = ctx->mb_y_;
const int cache_id = ctx->id_;
uint8_t* const y_dst = dec->yuv_b_ + Y_OFF;
uint8_t* const u_dst = dec->yuv_b_ + U_OFF;
uint8_t* const v_dst = dec->yuv_b_ + V_OFF;
// Initialize left-most block.
for (j = 0; j < 16; ++j) {
y_dst[j * BPS - 1] = 129;
}
for (j = 0; j < 8; ++j) {
u_dst[j * BPS - 1] = 129;
v_dst[j * BPS - 1] = 129;
}
// Init top-left sample on left column too.
if (mb_y > 0) {
y_dst[-1 - BPS] = u_dst[-1 - BPS] = v_dst[-1 - BPS] = 129;
} else {
// we only need to do this init once at block (0,0).
// Afterward, it remains valid for the whole topmost row.
memset(y_dst - BPS - 1, 127, 16 + 4 + 1);
memset(u_dst - BPS - 1, 127, 8 + 1);
memset(v_dst - BPS - 1, 127, 8 + 1);
}
// Reconstruct one row.
for (mb_x = 0; mb_x < dec->mb_w_; ++mb_x) {
const VP8MBData* const block = ctx->mb_data_ + mb_x;
// Rotate in the left samples from previously decoded block. We move four
// pixels at a time for alignment reason, and because of in-loop filter.
if (mb_x > 0) {
for (j = -1; j < 16; ++j) {
Copy32b(&y_dst[j * BPS - 4], &y_dst[j * BPS + 12]);
}
for (j = -1; j < 8; ++j) {
Copy32b(&u_dst[j * BPS - 4], &u_dst[j * BPS + 4]);
Copy32b(&v_dst[j * BPS - 4], &v_dst[j * BPS + 4]);
}
}
{
// bring top samples into the cache
VP8TopSamples* const top_yuv = dec->yuv_t_ + mb_x;
const int16_t* const coeffs = block->coeffs_;
uint32_t bits = block->non_zero_y_;
int n;
if (mb_y > 0) {
memcpy(y_dst - BPS, top_yuv[0].y, 16);
memcpy(u_dst - BPS, top_yuv[0].u, 8);
memcpy(v_dst - BPS, top_yuv[0].v, 8);
}
// predict and add residuals
if (block->is_i4x4_) { // 4x4
uint32_t* const top_right = (uint32_t*)(y_dst - BPS + 16);
if (mb_y > 0) {
if (mb_x >= dec->mb_w_ - 1) { // on rightmost border
memset(top_right, top_yuv[0].y[15], sizeof(*top_right));
} else {
memcpy(top_right, top_yuv[1].y, sizeof(*top_right));
}
}
// replicate the top-right pixels below
top_right[BPS] = top_right[2 * BPS] = top_right[3 * BPS] = top_right[0];
// predict and add residuals for all 4x4 blocks in turn.
for (n = 0; n < 16; ++n, bits <<= 2) {
uint8_t* const dst = y_dst + kScan[n];
VP8PredLuma4[block->imodes_[n]](dst);
DoTransform(bits, coeffs + n * 16, dst);
}
} else { // 16x16
const int pred_func = CheckMode(mb_x, mb_y, block->imodes_[0]);
VP8PredLuma16[pred_func](y_dst);
if (bits != 0) {
for (n = 0; n < 16; ++n, bits <<= 2) {
DoTransform(bits, coeffs + n * 16, y_dst + kScan[n]);
}
}
}
{
// Chroma
const uint32_t bits_uv = block->non_zero_uv_;
const int pred_func = CheckMode(mb_x, mb_y, block->uvmode_);
VP8PredChroma8[pred_func](u_dst);
VP8PredChroma8[pred_func](v_dst);
DoUVTransform(bits_uv >> 0, coeffs + 16 * 16, u_dst);
DoUVTransform(bits_uv >> 8, coeffs + 20 * 16, v_dst);
}
// stash away top samples for next block
if (mb_y < dec->mb_h_ - 1) {
memcpy(top_yuv[0].y, y_dst + 15 * BPS, 16);
memcpy(top_yuv[0].u, u_dst + 7 * BPS, 8);
memcpy(top_yuv[0].v, v_dst + 7 * BPS, 8);
}
}
// Transfer reconstructed samples from yuv_b_ cache to final destination.
{
const int y_offset = cache_id * 16 * dec->cache_y_stride_;
const int uv_offset = cache_id * 8 * dec->cache_uv_stride_;
uint8_t* const y_out = dec->cache_y_ + mb_x * 16 + y_offset;
uint8_t* const u_out = dec->cache_u_ + mb_x * 8 + uv_offset;
uint8_t* const v_out = dec->cache_v_ + mb_x * 8 + uv_offset;
for (j = 0; j < 16; ++j) {
memcpy(y_out + j * dec->cache_y_stride_, y_dst + j * BPS, 16);
}
for (j = 0; j < 8; ++j) {
memcpy(u_out + j * dec->cache_uv_stride_, u_dst + j * BPS, 8);
memcpy(v_out + j * dec->cache_uv_stride_, v_dst + j * BPS, 8);
}
}
}
}
//------------------------------------------------------------------------------
// Filtering
// kFilterExtraRows[] = How many extra lines are needed on the MB boundary
// for caching, given a filtering level.
// Simple filter: up to 2 luma samples are read and 1 is written.
// Complex filter: up to 4 luma samples are read and 3 are written. Same for
// U/V, so it's 8 samples total (because of the 2x upsampling).
static const uint8_t kFilterExtraRows[3] = { 0, 2, 8 };
static void DoFilter(const VP8Decoder* const dec, int mb_x, int mb_y) {
const VP8ThreadContext* const ctx = &dec->thread_ctx_;
const int cache_id = ctx->id_;
const int y_bps = dec->cache_y_stride_;
const VP8FInfo* const f_info = ctx->f_info_ + mb_x;
uint8_t* const y_dst = dec->cache_y_ + cache_id * 16 * y_bps + mb_x * 16;
const int ilevel = f_info->f_ilevel_;
const int limit = f_info->f_limit_;
if (limit == 0) {
return;
}
assert(limit >= 3);
if (dec->filter_type_ == 1) { // simple
if (mb_x > 0) {
VP8SimpleHFilter16(y_dst, y_bps, limit + 4);
}
if (f_info->f_inner_) {
VP8SimpleHFilter16i(y_dst, y_bps, limit);
}
if (mb_y > 0) {
VP8SimpleVFilter16(y_dst, y_bps, limit + 4);
}
if (f_info->f_inner_) {
VP8SimpleVFilter16i(y_dst, y_bps, limit);
}
} else { // complex
const int uv_bps = dec->cache_uv_stride_;
uint8_t* const u_dst = dec->cache_u_ + cache_id * 8 * uv_bps + mb_x * 8;
uint8_t* const v_dst = dec->cache_v_ + cache_id * 8 * uv_bps + mb_x * 8;
const int hev_thresh = f_info->hev_thresh_;
if (mb_x > 0) {
VP8HFilter16(y_dst, y_bps, limit + 4, ilevel, hev_thresh);
VP8HFilter8(u_dst, v_dst, uv_bps, limit + 4, ilevel, hev_thresh);
}
if (f_info->f_inner_) {
VP8HFilter16i(y_dst, y_bps, limit, ilevel, hev_thresh);
VP8HFilter8i(u_dst, v_dst, uv_bps, limit, ilevel, hev_thresh);
}
if (mb_y > 0) {
VP8VFilter16(y_dst, y_bps, limit + 4, ilevel, hev_thresh);
VP8VFilter8(u_dst, v_dst, uv_bps, limit + 4, ilevel, hev_thresh);
}
if (f_info->f_inner_) {
VP8VFilter16i(y_dst, y_bps, limit, ilevel, hev_thresh);
VP8VFilter8i(u_dst, v_dst, uv_bps, limit, ilevel, hev_thresh);
}
}
}
// Filter the decoded macroblock row (if needed)
static void FilterRow(const VP8Decoder* const dec) {
int mb_x;
const int mb_y = dec->thread_ctx_.mb_y_;
assert(dec->thread_ctx_.filter_row_);
for (mb_x = dec->tl_mb_x_; mb_x < dec->br_mb_x_; ++mb_x) {
DoFilter(dec, mb_x, mb_y);
}
}
//------------------------------------------------------------------------------
// Precompute the filtering strength for each segment and each i4x4/i16x16 mode.
static void PrecomputeFilterStrengths(VP8Decoder* const dec) {
if (dec->filter_type_ > 0) {
int s;
const VP8FilterHeader* const hdr = &dec->filter_hdr_;
for (s = 0; s < NUM_MB_SEGMENTS; ++s) {
int i4x4;
// First, compute the initial level
int base_level;
if (dec->segment_hdr_.use_segment_) {
base_level = dec->segment_hdr_.filter_strength_[s];
if (!dec->segment_hdr_.absolute_delta_) {
base_level += hdr->level_;
}
} else {
base_level = hdr->level_;
}
for (i4x4 = 0; i4x4 <= 1; ++i4x4) {
VP8FInfo* const info = &dec->fstrengths_[s][i4x4];
int level = base_level;
if (hdr->use_lf_delta_) {
level += hdr->ref_lf_delta_[0];
if (i4x4) {
level += hdr->mode_lf_delta_[0];
}
}
level = (level < 0) ? 0 : (level > 63) ? 63 : level;
if (level > 0) {
int ilevel = level;
if (hdr->sharpness_ > 0) {
if (hdr->sharpness_ > 4) {
ilevel >>= 2;
} else {
ilevel >>= 1;
}
if (ilevel > 9 - hdr->sharpness_) {
ilevel = 9 - hdr->sharpness_;
}
}
if (ilevel < 1) ilevel = 1;
info->f_ilevel_ = ilevel;
info->f_limit_ = 2 * level + ilevel;
info->hev_thresh_ = (level >= 40) ? 2 : (level >= 15) ? 1 : 0;
} else {
info->f_limit_ = 0; // no filtering
}
info->f_inner_ = i4x4;
}
}
}
}
//------------------------------------------------------------------------------
// Dithering
// minimal amp that will provide a non-zero dithering effect
#define MIN_DITHER_AMP 4
#define DITHER_AMP_TAB_SIZE 12
static const uint8_t kQuantToDitherAmp[DITHER_AMP_TAB_SIZE] = {
// roughly, it's dqm->uv_mat_[1]
8, 7, 6, 4, 4, 2, 2, 2, 1, 1, 1, 1
};
void VP8InitDithering(const WebPDecoderOptions* const options,
VP8Decoder* const dec) {
assert(dec != NULL);
if (options != NULL) {
const int d = options->dithering_strength;
const int max_amp = (1 << VP8_RANDOM_DITHER_FIX) - 1;
const int f = (d < 0) ? 0 : (d > 100) ? max_amp : (d * max_amp / 100);
if (f > 0) {
int s;
int all_amp = 0;
for (s = 0; s < NUM_MB_SEGMENTS; ++s) {
VP8QuantMatrix* const dqm = &dec->dqm_[s];
if (dqm->uv_quant_ < DITHER_AMP_TAB_SIZE) {
const int idx = (dqm->uv_quant_ < 0) ? 0 : dqm->uv_quant_;
dqm->dither_ = (f * kQuantToDitherAmp[idx]) >> 3;
}
all_amp |= dqm->dither_;
}
if (all_amp != 0) {
VP8InitRandom(&dec->dithering_rg_, 1.0f);
dec->dither_ = 1;
}
}
// potentially allow alpha dithering
dec->alpha_dithering_ = options->alpha_dithering_strength;
if (dec->alpha_dithering_ > 100) {
dec->alpha_dithering_ = 100;
} else if (dec->alpha_dithering_ < 0) {
dec->alpha_dithering_ = 0;
}
}
}
// Convert to range: [-2,2] for dither=50, [-4,4] for dither=100
static void Dither8x8(VP8Random* const rg, uint8_t* dst, int bps, int amp) {
uint8_t dither[64];
int i;
for (i = 0; i < 8 * 8; ++i) {
dither[i] = VP8RandomBits2(rg, VP8_DITHER_AMP_BITS + 1, amp);
}
VP8DitherCombine8x8(dither, dst, bps);
}
static void DitherRow(VP8Decoder* const dec) {
int mb_x;
assert(dec->dither_);
for (mb_x = dec->tl_mb_x_; mb_x < dec->br_mb_x_; ++mb_x) {
const VP8ThreadContext* const ctx = &dec->thread_ctx_;
const VP8MBData* const data = ctx->mb_data_ + mb_x;
const int cache_id = ctx->id_;
const int uv_bps = dec->cache_uv_stride_;
if (data->dither_ >= MIN_DITHER_AMP) {
uint8_t* const u_dst = dec->cache_u_ + cache_id * 8 * uv_bps + mb_x * 8;
uint8_t* const v_dst = dec->cache_v_ + cache_id * 8 * uv_bps + mb_x * 8;
Dither8x8(&dec->dithering_rg_, u_dst, uv_bps, data->dither_);
Dither8x8(&dec->dithering_rg_, v_dst, uv_bps, data->dither_);
}
}
}
//------------------------------------------------------------------------------
// This function is called after a row of macroblocks is finished decoding.
// It also takes into account the following restrictions:
// * In case of in-loop filtering, we must hold off sending some of the bottom
// pixels as they are yet unfiltered. They will be when the next macroblock
// row is decoded. Meanwhile, we must preserve them by rotating them in the
// cache area. This doesn't hold for the very bottom row of the uncropped
// picture of course.
// * we must clip the remaining pixels against the cropping area. The VP8Io
// struct must have the following fields set correctly before calling put():
#define MACROBLOCK_VPOS(mb_y) ((mb_y) * 16) // vertical position of a MB
// Finalize and transmit a complete row. Return false in case of user-abort.
static int FinishRow(void* arg1, void* arg2) {
VP8Decoder* const dec = (VP8Decoder*)arg1;
VP8Io* const io = (VP8Io*)arg2;
int ok = 1;
const VP8ThreadContext* const ctx = &dec->thread_ctx_;
const int cache_id = ctx->id_;
const int extra_y_rows = kFilterExtraRows[dec->filter_type_];
const int ysize = extra_y_rows * dec->cache_y_stride_;
const int uvsize = (extra_y_rows / 2) * dec->cache_uv_stride_;
const int y_offset = cache_id * 16 * dec->cache_y_stride_;
const int uv_offset = cache_id * 8 * dec->cache_uv_stride_;
uint8_t* const ydst = dec->cache_y_ - ysize + y_offset;
uint8_t* const udst = dec->cache_u_ - uvsize + uv_offset;
uint8_t* const vdst = dec->cache_v_ - uvsize + uv_offset;
const int mb_y = ctx->mb_y_;
const int is_first_row = (mb_y == 0);
const int is_last_row = (mb_y >= dec->br_mb_y_ - 1);
if (dec->mt_method_ == 2) {
ReconstructRow(dec, ctx);
}
if (ctx->filter_row_) {
FilterRow(dec);
}
if (dec->dither_) {
DitherRow(dec);
}
if (io->put != NULL) {
int y_start = MACROBLOCK_VPOS(mb_y);
int y_end = MACROBLOCK_VPOS(mb_y + 1);
if (!is_first_row) {
y_start -= extra_y_rows;
io->y = ydst;
io->u = udst;
io->v = vdst;
} else {
io->y = dec->cache_y_ + y_offset;
io->u = dec->cache_u_ + uv_offset;
io->v = dec->cache_v_ + uv_offset;
}
if (!is_last_row) {
y_end -= extra_y_rows;
}
if (y_end > io->crop_bottom) {
y_end = io->crop_bottom; // make sure we don't overflow on last row.
}
// If dec->alpha_data_ is not NULL, we have some alpha plane present.
io->a = NULL;
if (dec->alpha_data_ != NULL && y_start < y_end) {
io->a = VP8DecompressAlphaRows(dec, io, y_start, y_end - y_start);
if (io->a == NULL) {
return VP8SetError(dec, VP8_STATUS_BITSTREAM_ERROR,
"Could not decode alpha data.");
}
}
if (y_start < io->crop_top) {
const int delta_y = io->crop_top - y_start;
y_start = io->crop_top;
assert(!(delta_y & 1));
io->y += dec->cache_y_stride_ * delta_y;
io->u += dec->cache_uv_stride_ * (delta_y >> 1);
io->v += dec->cache_uv_stride_ * (delta_y >> 1);
if (io->a != NULL) {
io->a += io->width * delta_y;
}
}
if (y_start < y_end) {
io->y += io->crop_left;
io->u += io->crop_left >> 1;
io->v += io->crop_left >> 1;
if (io->a != NULL) {
io->a += io->crop_left;
}
io->mb_y = y_start - io->crop_top;
io->mb_w = io->crop_right - io->crop_left;
io->mb_h = y_end - y_start;
ok = io->put(io);
}
}
// rotate top samples if needed
if (cache_id + 1 == dec->num_caches_) {
if (!is_last_row) {
memcpy(dec->cache_y_ - ysize, ydst + 16 * dec->cache_y_stride_, ysize);
memcpy(dec->cache_u_ - uvsize, udst + 8 * dec->cache_uv_stride_, uvsize);
memcpy(dec->cache_v_ - uvsize, vdst + 8 * dec->cache_uv_stride_, uvsize);
}
}
return ok;
}
#undef MACROBLOCK_VPOS
//------------------------------------------------------------------------------
int VP8ProcessRow(VP8Decoder* const dec, VP8Io* const io) {
int ok = 1;
VP8ThreadContext* const ctx = &dec->thread_ctx_;
const int filter_row =
(dec->filter_type_ > 0) &&
(dec->mb_y_ >= dec->tl_mb_y_) && (dec->mb_y_ <= dec->br_mb_y_);
if (dec->mt_method_ == 0) {
// ctx->id_ and ctx->f_info_ are already set
ctx->mb_y_ = dec->mb_y_;
ctx->filter_row_ = filter_row;
ReconstructRow(dec, ctx);
ok = FinishRow(dec, io);
} else {
WebPWorker* const worker = &dec->worker_;
// Finish previous job *before* updating context
ok &= WebPGetWorkerInterface()->Sync(worker);
assert(worker->status_ == OK);
if (ok) { // spawn a new deblocking/output job
ctx->io_ = *io;
ctx->id_ = dec->cache_id_;
ctx->mb_y_ = dec->mb_y_;
ctx->filter_row_ = filter_row;
if (dec->mt_method_ == 2) { // swap macroblock data
VP8MBData* const tmp = ctx->mb_data_;
ctx->mb_data_ = dec->mb_data_;
dec->mb_data_ = tmp;
} else {
// perform reconstruction directly in main thread
ReconstructRow(dec, ctx);
}
if (filter_row) { // swap filter info
VP8FInfo* const tmp = ctx->f_info_;
ctx->f_info_ = dec->f_info_;
dec->f_info_ = tmp;
}
// (reconstruct)+filter in parallel
WebPGetWorkerInterface()->Launch(worker);
if (++dec->cache_id_ == dec->num_caches_) {
dec->cache_id_ = 0;
}
}
}
return ok;
}
//------------------------------------------------------------------------------
// Finish setting up the decoding parameter once user's setup() is called.
VP8StatusCode VP8EnterCritical(VP8Decoder* const dec, VP8Io* const io) {
// Call setup() first. This may trigger additional decoding features on 'io'.
// Note: Afterward, we must call teardown() no matter what.
if (io->setup != NULL && !io->setup(io)) {
VP8SetError(dec, VP8_STATUS_USER_ABORT, "Frame setup failed");
return dec->status_;
}
// Disable filtering per user request
if (io->bypass_filtering) {
dec->filter_type_ = 0;
}
// Define the area where we can skip in-loop filtering, in case of cropping.
//
// 'Simple' filter reads two luma samples outside of the macroblock
// and filters one. It doesn't filter the chroma samples. Hence, we can
// avoid doing the in-loop filtering before crop_top/crop_left position.
// For the 'Complex' filter, 3 samples are read and up to 3 are filtered.
// Means: there's a dependency chain that goes all the way up to the
// top-left corner of the picture (MB #0). We must filter all the previous
// macroblocks.
{
const int extra_pixels = kFilterExtraRows[dec->filter_type_];
if (dec->filter_type_ == 2) {
// For complex filter, we need to preserve the dependency chain.
dec->tl_mb_x_ = 0;
dec->tl_mb_y_ = 0;
} else {
// For simple filter, we can filter only the cropped region.
// We include 'extra_pixels' on the other side of the boundary, since
// vertical or horizontal filtering of the previous macroblock can
// modify some abutting pixels.
dec->tl_mb_x_ = (io->crop_left - extra_pixels) >> 4;
dec->tl_mb_y_ = (io->crop_top - extra_pixels) >> 4;
if (dec->tl_mb_x_ < 0) dec->tl_mb_x_ = 0;
if (dec->tl_mb_y_ < 0) dec->tl_mb_y_ = 0;
}
// We need some 'extra' pixels on the right/bottom.
dec->br_mb_y_ = (io->crop_bottom + 15 + extra_pixels) >> 4;
dec->br_mb_x_ = (io->crop_right + 15 + extra_pixels) >> 4;
if (dec->br_mb_x_ > dec->mb_w_) {
dec->br_mb_x_ = dec->mb_w_;
}
if (dec->br_mb_y_ > dec->mb_h_) {
dec->br_mb_y_ = dec->mb_h_;
}
}
PrecomputeFilterStrengths(dec);
return VP8_STATUS_OK;
}
int VP8ExitCritical(VP8Decoder* const dec, VP8Io* const io) {
int ok = 1;
if (dec->mt_method_ > 0) {
ok = WebPGetWorkerInterface()->Sync(&dec->worker_);
}
if (io->teardown != NULL) {
io->teardown(io);
}
return ok;
}
//------------------------------------------------------------------------------
// For multi-threaded decoding we need to use 3 rows of 16 pixels as delay line.
//
// Reason is: the deblocking filter cannot deblock the bottom horizontal edges
// immediately, and needs to wait for first few rows of the next macroblock to
// be decoded. Hence, deblocking is lagging behind by 4 or 8 pixels (depending
// on strength).
// With two threads, the vertical positions of the rows being decoded are:
// Decode: [ 0..15][16..31][32..47][48..63][64..79][...
// Deblock: [ 0..11][12..27][28..43][44..59][...
// If we use two threads and two caches of 16 pixels, the sequence would be:
// Decode: [ 0..15][16..31][ 0..15!!][16..31][ 0..15][...
// Deblock: [ 0..11][12..27!!][-4..11][12..27][...
// The problem occurs during row [12..15!!] that both the decoding and
// deblocking threads are writing simultaneously.
// With 3 cache lines, one get a safe write pattern:
// Decode: [ 0..15][16..31][32..47][ 0..15][16..31][32..47][0..
// Deblock: [ 0..11][12..27][28..43][-4..11][12..27][28...
// Note that multi-threaded output _without_ deblocking can make use of two
// cache lines of 16 pixels only, since there's no lagging behind. The decoding
// and output process have non-concurrent writing:
// Decode: [ 0..15][16..31][ 0..15][16..31][...
// io->put: [ 0..15][16..31][ 0..15][...
#define MT_CACHE_LINES 3
#define ST_CACHE_LINES 1 // 1 cache row only for single-threaded case
// Initialize multi/single-thread worker
static int InitThreadContext(VP8Decoder* const dec) {
dec->cache_id_ = 0;
if (dec->mt_method_ > 0) {
WebPWorker* const worker = &dec->worker_;
if (!WebPGetWorkerInterface()->Reset(worker)) {
return VP8SetError(dec, VP8_STATUS_OUT_OF_MEMORY,
"thread initialization failed.");
}
worker->data1 = dec;
worker->data2 = (void*)&dec->thread_ctx_.io_;
worker->hook = FinishRow;
dec->num_caches_ =
(dec->filter_type_ > 0) ? MT_CACHE_LINES : MT_CACHE_LINES - 1;
} else {
dec->num_caches_ = ST_CACHE_LINES;
}
return 1;
}
int VP8GetThreadMethod(const WebPDecoderOptions* const options,
const WebPHeaderStructure* const headers,
int width, int height) {
if (options == NULL || options->use_threads == 0) {
return 0;
}
(void)headers;
(void)width;
(void)height;
assert(headers == NULL || !headers->is_lossless);
#if defined(WEBP_USE_THREAD)
if (width >= MIN_WIDTH_FOR_THREADS) return 2;
#endif
return 0;
}
#undef MT_CACHE_LINES
#undef ST_CACHE_LINES
//------------------------------------------------------------------------------
// Memory setup
static int AllocateMemory(VP8Decoder* const dec) {
const int num_caches = dec->num_caches_;
const int mb_w = dec->mb_w_;
// Note: we use 'size_t' when there's no overflow risk, uint64_t otherwise.
const size_t intra_pred_mode_size = 4 * mb_w * sizeof(uint8_t);
const size_t top_size = sizeof(VP8TopSamples) * mb_w;
const size_t mb_info_size = (mb_w + 1) * sizeof(VP8MB);
const size_t f_info_size =
(dec->filter_type_ > 0) ?
mb_w * (dec->mt_method_ > 0 ? 2 : 1) * sizeof(VP8FInfo)
: 0;
const size_t yuv_size = YUV_SIZE * sizeof(*dec->yuv_b_);
const size_t mb_data_size =
(dec->mt_method_ == 2 ? 2 : 1) * mb_w * sizeof(*dec->mb_data_);
const size_t cache_height = (16 * num_caches
+ kFilterExtraRows[dec->filter_type_]) * 3 / 2;
const size_t cache_size = top_size * cache_height;
// alpha_size is the only one that scales as width x height.
const uint64_t alpha_size = (dec->alpha_data_ != NULL) ?
(uint64_t)dec->pic_hdr_.width_ * dec->pic_hdr_.height_ : 0ULL;
const uint64_t needed = (uint64_t)intra_pred_mode_size
+ top_size + mb_info_size + f_info_size
+ yuv_size + mb_data_size
+ cache_size + alpha_size + WEBP_ALIGN_CST;
uint8_t* mem;
if (needed != (size_t)needed) return 0; // check for overflow
if (needed > dec->mem_size_) {
WebPSafeFree(dec->mem_);
dec->mem_size_ = 0;
dec->mem_ = WebPSafeMalloc(needed, sizeof(uint8_t));
if (dec->mem_ == NULL) {
return VP8SetError(dec, VP8_STATUS_OUT_OF_MEMORY,
"no memory during frame initialization.");
}
// down-cast is ok, thanks to WebPSafeMalloc() above.
dec->mem_size_ = (size_t)needed;
}
mem = (uint8_t*)dec->mem_;
dec->intra_t_ = mem;
mem += intra_pred_mode_size;
dec->yuv_t_ = (VP8TopSamples*)mem;
mem += top_size;
dec->mb_info_ = ((VP8MB*)mem) + 1;
mem += mb_info_size;
dec->f_info_ = f_info_size ? (VP8FInfo*)mem : NULL;
mem += f_info_size;
dec->thread_ctx_.id_ = 0;
dec->thread_ctx_.f_info_ = dec->f_info_;
if (dec->filter_type_ > 0 && dec->mt_method_ > 0) {
// secondary cache line. The deblocking process need to make use of the
// filtering strength from previous macroblock row, while the new ones
// are being decoded in parallel. We'll just swap the pointers.
dec->thread_ctx_.f_info_ += mb_w;
}
mem = (uint8_t*)WEBP_ALIGN(mem);
assert((yuv_size & WEBP_ALIGN_CST) == 0);
dec->yuv_b_ = mem;
mem += yuv_size;
dec->mb_data_ = (VP8MBData*)mem;
dec->thread_ctx_.mb_data_ = (VP8MBData*)mem;
if (dec->mt_method_ == 2) {
dec->thread_ctx_.mb_data_ += mb_w;
}
mem += mb_data_size;
dec->cache_y_stride_ = 16 * mb_w;
dec->cache_uv_stride_ = 8 * mb_w;
{
const int extra_rows = kFilterExtraRows[dec->filter_type_];
const int extra_y = extra_rows * dec->cache_y_stride_;
const int extra_uv = (extra_rows / 2) * dec->cache_uv_stride_;
dec->cache_y_ = mem + extra_y;
dec->cache_u_ = dec->cache_y_
+ 16 * num_caches * dec->cache_y_stride_ + extra_uv;
dec->cache_v_ = dec->cache_u_
+ 8 * num_caches * dec->cache_uv_stride_ + extra_uv;
dec->cache_id_ = 0;
}
mem += cache_size;
// alpha plane
dec->alpha_plane_ = alpha_size ? mem : NULL;
mem += alpha_size;
assert(mem <= (uint8_t*)dec->mem_ + dec->mem_size_);
// note: left/top-info is initialized once for all.
memset(dec->mb_info_ - 1, 0, mb_info_size);
VP8InitScanline(dec); // initialize left too.
// initialize top
memset(dec->intra_t_, B_DC_PRED, intra_pred_mode_size);
return 1;
}
static void InitIo(VP8Decoder* const dec, VP8Io* io) {
// prepare 'io'
io->mb_y = 0;
io->y = dec->cache_y_;
io->u = dec->cache_u_;
io->v = dec->cache_v_;
io->y_stride = dec->cache_y_stride_;
io->uv_stride = dec->cache_uv_stride_;
io->a = NULL;
}
int VP8InitFrame(VP8Decoder* const dec, VP8Io* const io) {
if (!InitThreadContext(dec)) return 0; // call first. Sets dec->num_caches_.
if (!AllocateMemory(dec)) return 0;
InitIo(dec, io);
VP8DspInit(); // Init critical function pointers and look-up tables.
return 1;
}
//------------------------------------------------------------------------------
| {
"pile_set_name": "Github"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.