prompt
large_stringlengths 70
991k
| completion
large_stringlengths 0
1.02k
|
---|---|
<|file_name|>vscode.d.ts<|end_file_name|><|fim▁begin|>/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
/**
* The version of the editor.
*/
export const version: string;
/**
* Represents a reference to a command. Provides a title which
* will be used to represent a command in the UI and, optionally,
* an array of arguments which will be passed to the command handler
* function when invoked.
*/
export interface Command {
/**
* Title of the command, like `save`.
*/
title: string;
/**
* The identifier of the actual command handler.
* @see [commands.registerCommand](#commands.registerCommand).
*/
command: string;
/**
* A tooltip for the command, when represented in the UI.
*/
tooltip?: string;
/**
* Arguments that the command handler should be
* invoked with.
*/
arguments?: any[];
}
/**
* Represents a line of text, such as a line of source code.
*
* TextLine objects are __immutable__. When a [document](#TextDocument) changes,
* previously retrieved lines will not represent the latest state.
*/
export interface TextLine {
/**
* The zero-based line number.
*/
readonly lineNumber: number;
/**
* The text of this line without the line separator characters.
*/
readonly text: string;
/**
* The range this line covers without the line separator characters.
*/
readonly range: Range;
/**
* The range this line covers with the line separator characters.
*/
readonly rangeIncludingLineBreak: Range;
/**
* The offset of the first character which is not a whitespace character as defined
* by `/\s/`. **Note** that if a line is all whitespaces the length of the line is returned.
*/
readonly firstNonWhitespaceCharacterIndex: number;
/**
* Whether this line is whitespace only, shorthand
* for [TextLine.firstNonWhitespaceCharacterIndex](#TextLine.firstNonWhitespaceCharacterIndex) === [TextLine.text.length](#TextLine.text).
*/
readonly isEmptyOrWhitespace: boolean;
}
/**
* Represents a text document, such as a source file. Text documents have
* [lines](#TextLine) and knowledge about an underlying resource like a file.
*/
export interface TextDocument {
/**
* The associated uri for this document.
*
* *Note* that most documents use the `file`-scheme, which means they are files on disk. However, **not** all documents are
* saved on disk and therefore the `scheme` must be checked before trying to access the underlying file or siblings on disk.
*
* @see [FileSystemProvider](#FileSystemProvider)
* @see [TextDocumentContentProvider](#TextDocumentContentProvider)
*/
readonly uri: Uri;
/**
* The file system path of the associated resource. Shorthand
* notation for [TextDocument.uri.fsPath](#TextDocument.uri). Independent of the uri scheme.
*/
readonly fileName: string;
/**
* Is this document representing an untitled file which has never been saved yet. *Note* that
* this does not mean the document will be saved to disk, use [`uri.scheme`](#Uri.scheme)
* to figure out where a document will be [saved](#FileSystemProvider), e.g. `file`, `ftp` etc.
*/
readonly isUntitled: boolean;
/**
* The identifier of the language associated with this document.
*/
readonly languageId: string;
/**
* The version number of this document (it will strictly increase after each
* change, including undo/redo).
*/
readonly version: number;
/**
* `true` if there are unpersisted changes.
*/
readonly isDirty: boolean;
/**
* `true` if the document have been closed. A closed document isn't synchronized anymore
* and won't be re-used when the same resource is opened again.
*/
readonly isClosed: boolean;
/**
* Save the underlying file.
*
* @return A promise that will resolve to true when the file
* has been saved. If the file was not dirty or the save failed,
* will return false.
*/
save(): Thenable<boolean>;
/**
* The [end of line](#EndOfLine) sequence that is predominately
* used in this document.
*/
readonly eol: EndOfLine;
/**
* The number of lines in this document.
*/
readonly lineCount: number;
/**
* Returns a text line denoted by the line number. Note
* that the returned object is *not* live and changes to the
* document are not reflected.
*
* @param line A line number in [0, lineCount).
* @return A [line](#TextLine).
*/
lineAt(line: number): TextLine;
/**
* Returns a text line denoted by the position. Note
* that the returned object is *not* live and changes to the
* document are not reflected.
*
* The position will be [adjusted](#TextDocument.validatePosition).
*
* @see [TextDocument.lineAt](#TextDocument.lineAt)
* @param position A position.
* @return A [line](#TextLine).
*/
lineAt(position: Position): TextLine;
/**
* Converts the position to a zero-based offset.
*
* The position will be [adjusted](#TextDocument.validatePosition).
*
* @param position A position.
* @return A valid zero-based offset.
*/
offsetAt(position: Position): number;
/**
* Converts a zero-based offset to a position.
*
* @param offset A zero-based offset.
* @return A valid [position](#Position).
*/
positionAt(offset: number): Position;
/**
* Get the text of this document. A substring can be retrieved by providing
* a range. The range will be [adjusted](#TextDocument.validateRange).
*
* @param range Include only the text included by the range.
* @return The text inside the provided range or the entire text.
*/
getText(range?: Range): string;
/**
* Get a word-range at the given position. By default words are defined by
* common separators, like space, -, _, etc. In addition, per language custom
* [word definitions](#LanguageConfiguration.wordPattern) can be defined. It
* is also possible to provide a custom regular expression.
*
* * *Note 1:* A custom regular expression must not match the empty string and
* if it does, it will be ignored.
* * *Note 2:* A custom regular expression will fail to match multiline strings
* and in the name of speed regular expressions should not match words with
* spaces. Use [`TextLine.text`](#TextLine.text) for more complex, non-wordy, scenarios.
*
* The position will be [adjusted](#TextDocument.validatePosition).
*
* @param position A position.
* @param regex Optional regular expression that describes what a word is.
* @return A range spanning a word, or `undefined`.
*/
getWordRangeAtPosition(position: Position, regex?: RegExp): Range | undefined;
/**
* Ensure a range is completely contained in this document.
*
* @param range A range.
* @return The given range or a new, adjusted range.
*/
validateRange(range: Range): Range;
/**
* Ensure a position is contained in the range of this document.
*
* @param position A position.
* @return The given position or a new, adjusted position.
*/
validatePosition(position: Position): Position;
}
/**
* Represents a line and character position, such as
* the position of the cursor.
*
* Position objects are __immutable__. Use the [with](#Position.with) or
* [translate](#Position.translate) methods to derive new positions
* from an existing position.
*/
export class Position {
/**
* The zero-based line value.
*/
readonly line: number;
/**
* The zero-based character value.
*/
readonly character: number;
/**
* @param line A zero-based line value.
* @param character A zero-based character value.
*/
constructor(line: number, character: number);
/**
* Check if this position is before `other`.
*
* @param other A position.
* @return `true` if position is on a smaller line
* or on the same line on a smaller character.
*/
isBefore(other: Position): boolean;
/**
* Check if this position is before or equal to `other`.
*
* @param other A position.
* @return `true` if position is on a smaller line
* or on the same line on a smaller or equal character.
*/
isBeforeOrEqual(other: Position): boolean;
/**
* Check if this position is after `other`.
*
* @param other A position.
* @return `true` if position is on a greater line
* or on the same line on a greater character.
*/
isAfter(other: Position): boolean;
/**
* Check if this position is after or equal to `other`.
*
* @param other A position.
* @return `true` if position is on a greater line
* or on the same line on a greater or equal character.
*/
isAfterOrEqual(other: Position): boolean;
/**
* Check if this position is equal to `other`.
*
* @param other A position.
* @return `true` if the line and character of the given position are equal to
* the line and character of this position.
*/
isEqual(other: Position): boolean;
/**
* Compare this to `other`.
*
* @param other A position.
* @return A number smaller than zero if this position is before the given position,
* a number greater than zero if this position is after the given position, or zero when
* this and the given position are equal.
*/
compareTo(other: Position): number;
/**
* Create a new position relative to this position.
*
* @param lineDelta Delta value for the line value, default is `0`.
* @param characterDelta Delta value for the character value, default is `0`.
* @return A position which line and character is the sum of the current line and
* character and the corresponding deltas.
*/
translate(lineDelta?: number, characterDelta?: number): Position;
/**
* Derived a new position relative to this position.
*
* @param change An object that describes a delta to this position.
* @return A position that reflects the given delta. Will return `this` position if the change
* is not changing anything.
*/
translate(change: { lineDelta?: number; characterDelta?: number; }): Position;
/**
* Create a new position derived from this position.
*
* @param line Value that should be used as line value, default is the [existing value](#Position.line)
* @param character Value that should be used as character value, default is the [existing value](#Position.character)
* @return A position where line and character are replaced by the given values.
*/
with(line?: number, character?: number): Position;
/**
* Derived a new position from this position.
*
* @param change An object that describes a change to this position.
* @return A position that reflects the given change. Will return `this` position if the change
* is not changing anything.
*/
with(change: { line?: number; character?: number; }): Position;
}
/**
* A range represents an ordered pair of two positions.
* It is guaranteed that [start](#Range.start).isBeforeOrEqual([end](#Range.end))
*
* Range objects are __immutable__. Use the [with](#Range.with),
* [intersection](#Range.intersection), or [union](#Range.union) methods
* to derive new ranges from an existing range.
*/
export class Range {
/**
* The start position. It is before or equal to [end](#Range.end).
*/
readonly start: Position;
/**
* The end position. It is after or equal to [start](#Range.start).
*/
readonly end: Position;
/**
* Create a new range from two positions. If `start` is not
* before or equal to `end`, the values will be swapped.
*
* @param start A position.
* @param end A position.
*/
constructor(start: Position, end: Position);
/**
* Create a new range from number coordinates. It is a shorter equivalent of
* using `new Range(new Position(startLine, startCharacter), new Position(endLine, endCharacter))`
*
* @param startLine A zero-based line value.
* @param startCharacter A zero-based character value.
* @param endLine A zero-based line value.
* @param endCharacter A zero-based character value.
*/
constructor(startLine: number, startCharacter: number, endLine: number, endCharacter: number);
/**
* `true` if `start` and `end` are equal.
*/
isEmpty: boolean;
/**
* `true` if `start.line` and `end.line` are equal.
*/
isSingleLine: boolean;
/**
* Check if a position or a range is contained in this range.
*
* @param positionOrRange A position or a range.
* @return `true` if the position or range is inside or equal
* to this range.
*/
contains(positionOrRange: Position | Range): boolean;
/**
* Check if `other` equals this range.
*
* @param other A range.
* @return `true` when start and end are [equal](#Position.isEqual) to
* start and end of this range.
*/
isEqual(other: Range): boolean;
/**
* Intersect `range` with this range and returns a new range or `undefined`
* if the ranges have no overlap.
*
* @param range A range.
* @return A range of the greater start and smaller end positions. Will
* return undefined when there is no overlap.
*/
intersection(range: Range): Range | undefined;
/**
* Compute the union of `other` with this range.
*
* @param other A range.
* @return A range of smaller start position and the greater end position.
*/
union(other: Range): Range;
/**
* Derived a new range from this range.
*
* @param start A position that should be used as start. The default value is the [current start](#Range.start).
* @param end A position that should be used as end. The default value is the [current end](#Range.end).
* @return A range derived from this range with the given start and end position.
* If start and end are not different `this` range will be returned.
*/
with(start?: Position, end?: Position): Range;
/**
* Derived a new range from this range.
*
* @param change An object that describes a change to this range.
* @return A range that reflects the given change. Will return `this` range if the change
* is not changing anything.
*/
with(change: { start?: Position, end?: Position }): Range;
}
/**
* Represents a text selection in an editor.
*/
export class Selection extends Range {
/**
* The position at which the selection starts.
* This position might be before or after [active](#Selection.active).
*/
anchor: Position;
/**
* The position of the cursor.
* This position might be before or after [anchor](#Selection.anchor).
*/
active: Position;
/**
* Create a selection from two positions.
*
* @param anchor A position.
* @param active A position.
*/
constructor(anchor: Position, active: Position);
/**
* Create a selection from four coordinates.
*
* @param anchorLine A zero-based line value.
* @param anchorCharacter A zero-based character value.
* @param activeLine A zero-based line value.
* @param activeCharacter A zero-based character value.
*/
constructor(anchorLine: number, anchorCharacter: number, activeLine: number, activeCharacter: number);
/**
* A selection is reversed if [active](#Selection.active).isBefore([anchor](#Selection.anchor)).
*/
isReversed: boolean;
}
/**
* Represents sources that can cause [selection change events](#window.onDidChangeTextEditorSelection).
*/
export enum TextEditorSelectionChangeKind {
/**
* Selection changed due to typing in the editor.
*/
Keyboard = 1,
/**
* Selection change due to clicking in the editor.
*/
Mouse = 2,
/**
* Selection changed because a command ran.
*/
Command = 3
}
/**
* Represents an event describing the change in a [text editor's selections](#TextEditor.selections).
*/
export interface TextEditorSelectionChangeEvent {
/**
* The [text editor](#TextEditor) for which the selections have changed.
*/
textEditor: TextEditor;
/**
* The new value for the [text editor's selections](#TextEditor.selections).
*/
selections: Selection[];
/**
* The [change kind](#TextEditorSelectionChangeKind) which has triggered this
* event. Can be `undefined`.
*/
kind?: TextEditorSelectionChangeKind;
}
/**
* Represents an event describing the change in a [text editor's visible ranges](#TextEditor.visibleRanges).
*/
export interface TextEditorVisibleRangesChangeEvent {
/**
* The [text editor](#TextEditor) for which the visible ranges have changed.
*/
textEditor: TextEditor;
/**
* The new value for the [text editor's visible ranges](#TextEditor.visibleRanges).
*/
visibleRanges: Range[];
}
/**
* Represents an event describing the change in a [text editor's options](#TextEditor.options).
*/
export interface TextEditorOptionsChangeEvent {
/**
* The [text editor](#TextEditor) for which the options have changed.
*/
textEditor: TextEditor;
/**
* The new value for the [text editor's options](#TextEditor.options).
*/
options: TextEditorOptions;
}
/**
* Represents an event describing the change of a [text editor's view column](#TextEditor.viewColumn).
*/
export interface TextEditorViewColumnChangeEvent {
/**
* The [text editor](#TextEditor) for which the view column has changed.
*/
textEditor: TextEditor;
/**
* The new value for the [text editor's view column](#TextEditor.viewColumn).
*/
viewColumn: ViewColumn;
}
/**
* Rendering style of the cursor.
*/
export enum TextEditorCursorStyle {
/**
* Render the cursor as a vertical thick line.
*/
Line = 1,
/**
* Render the cursor as a block filled.
*/
Block = 2,
/**
* Render the cursor as a thick horizontal line.
*/
Underline = 3,
/**
* Render the cursor as a vertical thin line.
*/
LineThin = 4,
/**
* Render the cursor as a block outlined.
*/
BlockOutline = 5,
/**
* Render the cursor as a thin horizontal line.
*/
UnderlineThin = 6
}
/**
* Rendering style of the line numbers.
*/
export enum TextEditorLineNumbersStyle {
/**
* Do not render the line numbers.
*/
Off = 0,
/**
* Render the line numbers.
*/
On = 1,
/**
* Render the line numbers with values relative to the primary cursor location.
*/
Relative = 2
}
/**
* Represents a [text editor](#TextEditor)'s [options](#TextEditor.options).
*/
export interface TextEditorOptions {
/**
* The size in spaces a tab takes. This is used for two purposes:
* - the rendering width of a tab character;
* - the number of spaces to insert when [insertSpaces](#TextEditorOptions.insertSpaces) is true.
*
* When getting a text editor's options, this property will always be a number (resolved).
* When setting a text editor's options, this property is optional and it can be a number or `"auto"`.
*/
tabSize?: number | string;
/**
* When pressing Tab insert [n](#TextEditorOptions.tabSize) spaces.
* When getting a text editor's options, this property will always be a boolean (resolved).
* When setting a text editor's options, this property is optional and it can be a boolean or `"auto"`.
*/
insertSpaces?: boolean | string;
/**
* The rendering style of the cursor in this editor.
* When getting a text editor's options, this property will always be present.
* When setting a text editor's options, this property is optional.
*/
cursorStyle?: TextEditorCursorStyle;
/**
* Render relative line numbers w.r.t. the current line number.
* When getting a text editor's options, this property will always be present.
* When setting a text editor's options, this property is optional.
*/
lineNumbers?: TextEditorLineNumbersStyle;
}
/**
* Represents a handle to a set of decorations
* sharing the same [styling options](#DecorationRenderOptions) in a [text editor](#TextEditor).
*
* To get an instance of a `TextEditorDecorationType` use
* [createTextEditorDecorationType](#window.createTextEditorDecorationType).
*/
export interface TextEditorDecorationType {
/**
* Internal representation of the handle.
*/
readonly key: string;
/**
* Remove this decoration type and all decorations on all text editors using it.
*/
dispose(): void;
}
/**
* Represents different [reveal](#TextEditor.revealRange) strategies in a text editor.
*/
export enum TextEditorRevealType {
/**
* The range will be revealed with as little scrolling as possible.
*/
Default = 0,
/**
* The range will always be revealed in the center of the viewport.
*/
InCenter = 1,
/**
* If the range is outside the viewport, it will be revealed in the center of the viewport.
* Otherwise, it will be revealed with as little scrolling as possible.
*/
InCenterIfOutsideViewport = 2,
/**
* The range will always be revealed at the top of the viewport.
*/
AtTop = 3
}
/**
* Represents different positions for rendering a decoration in an [overview ruler](#DecorationRenderOptions.overviewRulerLane).
* The overview ruler supports three lanes.
*/
export enum OverviewRulerLane {
Left = 1,
Center = 2,
Right = 4,
Full = 7
}
/**
* Describes the behavior of decorations when typing/editing at their edges.
*/
export enum DecorationRangeBehavior {
/**
* The decoration's range will widen when edits occur at the start or end.
*/
OpenOpen = 0,
/**
* The decoration's range will not widen when edits occur at the start of end.
*/
ClosedClosed = 1,
/**
* The decoration's range will widen when edits occur at the start, but not at the end.
*/
OpenClosed = 2,
/**
* The decoration's range will widen when edits occur at the end, but not at the start.
*/
ClosedOpen = 3
}
/**
* Represents options to configure the behavior of showing a [document](#TextDocument) in an [editor](#TextEditor).
*/
export interface TextDocumentShowOptions {
/**
* An optional view column in which the [editor](#TextEditor) should be shown.
* The default is the [active](#ViewColumn.Active), other values are adjusted to
* be `Min(column, columnCount + 1)`, the [active](#ViewColumn.Active)-column is
* not adjusted. Use [`ViewColumn.Beside`](#ViewColumn.Beside) to open the
* editor to the side of the currently active one.
*/
viewColumn?: ViewColumn;
/**
* An optional flag that when `true` will stop the [editor](#TextEditor) from taking focus.
*/
preserveFocus?: boolean;
/**
* An optional flag that controls if an [editor](#TextEditor)-tab will be replaced
* with the next editor or if it will be kept.
*/
preview?: boolean;
/**
* An optional selection to apply for the document in the [editor](#TextEditor).
*/
selection?: Range;
}
/**
* A reference to one of the workbench colors as defined in https://code.visualstudio.com/docs/getstarted/theme-color-reference.
* Using a theme color is preferred over a custom color as it gives theme authors and users the possibility to change the color.
*/
export class ThemeColor {
/**
* Creates a reference to a theme color.
* @param id of the color. The available colors are listed in https://code.visualstudio.com/docs/getstarted/theme-color-reference.
*/
constructor(id: string);
}
/**
* A reference to a named icon. Currently only [File](#ThemeIcon.File) and [Folder](#ThemeIcon.Folder) are supported.
* Using a theme icon is preferred over a custom icon as it gives theme authors the possibility to change the icons.
*/
export class ThemeIcon {
/**
* Reference to a icon representing a file. The icon is taken from the current file icon theme or a placeholder icon.
*/
static readonly File: ThemeIcon;
/**
* Reference to a icon representing a folder. The icon is taken from the current file icon theme or a placeholder icon.
*/
static readonly Folder: ThemeIcon;
private constructor(id: string);
}
/**
* Represents theme specific rendering styles for a [text editor decoration](#TextEditorDecorationType).
*/
export interface ThemableDecorationRenderOptions {
/**
* Background color of the decoration. Use rgba() and define transparent background colors to play well with other decorations.
* Alternatively a color from the color registry can be [referenced](#ThemeColor).
*/
backgroundColor?: string | ThemeColor;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
outline?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
* Better use 'outline' for setting one or more of the individual outline properties.
*/
outlineColor?: string | ThemeColor;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
* Better use 'outline' for setting one or more of the individual outline properties.
*/
outlineStyle?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
* Better use 'outline' for setting one or more of the individual outline properties.
*/
outlineWidth?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
border?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
* Better use 'border' for setting one or more of the individual border properties.
*/
borderColor?: string | ThemeColor;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
* Better use 'border' for setting one or more of the individual border properties.
*/
borderRadius?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
* Better use 'border' for setting one or more of the individual border properties.
*/
borderSpacing?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
* Better use 'border' for setting one or more of the individual border properties.
*/
borderStyle?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
* Better use 'border' for setting one or more of the individual border properties.
*/
borderWidth?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
fontStyle?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
fontWeight?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
textDecoration?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
cursor?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
color?: string | ThemeColor;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
opacity?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
letterSpacing?: string;
/**
* An **absolute path** or an URI to an image to be rendered in the gutter.
*/
gutterIconPath?: string | Uri;
/**
* Specifies the size of the gutter icon.
* Available values are 'auto', 'contain', 'cover' and any percentage value.
* For further information: https://msdn.microsoft.com/en-us/library/jj127316(v=vs.85).aspx
*/
gutterIconSize?: string;
/**
* The color of the decoration in the overview ruler. Use rgba() and define transparent colors to play well with other decorations.
*/
overviewRulerColor?: string | ThemeColor;
/**
* Defines the rendering options of the attachment that is inserted before the decorated text.
*/
before?: ThemableDecorationAttachmentRenderOptions;
/**
* Defines the rendering options of the attachment that is inserted after the decorated text.
*/
after?: ThemableDecorationAttachmentRenderOptions;
}
export interface ThemableDecorationAttachmentRenderOptions {
/**
* Defines a text content that is shown in the attachment. Either an icon or a text can be shown, but not both.
*/
contentText?: string;
/**
* An **absolute path** or an URI to an image to be rendered in the attachment. Either an icon
* or a text can be shown, but not both.
*/
contentIconPath?: string | Uri;
/**
* CSS styling property that will be applied to the decoration attachment.
*/
border?: string;
/**
* CSS styling property that will be applied to text enclosed by a decoration.
*/
borderColor?: string | ThemeColor;
/**
* CSS styling property that will be applied to the decoration attachment.
*/
fontStyle?: string;
/**
* CSS styling property that will be applied to the decoration attachment.
*/
fontWeight?: string;
/**
* CSS styling property that will be applied to the decoration attachment.
*/
textDecoration?: string;
/**
* CSS styling property that will be applied to the decoration attachment.
*/
color?: string | ThemeColor;
/**
* CSS styling property that will be applied to the decoration attachment.
*/
backgroundColor?: string | ThemeColor;
/**
* CSS styling property that will be applied to the decoration attachment.
*/
margin?: string;
/**
* CSS styling property that will be applied to the decoration attachment.
*/
width?: string;
/**
* CSS styling property that will be applied to the decoration attachment.
*/
height?: string;
}
/**
* Represents rendering styles for a [text editor decoration](#TextEditorDecorationType).
*/
export interface DecorationRenderOptions extends ThemableDecorationRenderOptions {
/**
* Should the decoration be rendered also on the whitespace after the line text.
* Defaults to `false`.
*/
isWholeLine?: boolean;
/**
* Customize the growing behavior of the decoration when edits occur at the edges of the decoration's range.
* Defaults to `DecorationRangeBehavior.OpenOpen`.
*/
rangeBehavior?: DecorationRangeBehavior;
/**
* The position in the overview ruler where the decoration should be rendered.
*/
overviewRulerLane?: OverviewRulerLane;
/**
* Overwrite options for light themes.
*/
light?: ThemableDecorationRenderOptions;
/**
* Overwrite options for dark themes.
*/
dark?: ThemableDecorationRenderOptions;
}
/**
* Represents options for a specific decoration in a [decoration set](#TextEditorDecorationType).
*/
export interface DecorationOptions {
/**
* Range to which this decoration is applied. The range must not be empty.
*/
range: Range;
/**
* A message that should be rendered when hovering over the decoration.
*/
hoverMessage?: MarkedString | MarkedString[];
/**
* Render options applied to the current decoration. For performance reasons, keep the
* number of decoration specific options small, and use decoration types wherever possible.
*/
renderOptions?: DecorationInstanceRenderOptions;
}
export interface ThemableDecorationInstanceRenderOptions {
/**
* Defines the rendering options of the attachment that is inserted before the decorated text.
*/
before?: ThemableDecorationAttachmentRenderOptions;
/**
* Defines the rendering options of the attachment that is inserted after the decorated text.
*/
after?: ThemableDecorationAttachmentRenderOptions;
}
export interface DecorationInstanceRenderOptions extends ThemableDecorationInstanceRenderOptions {
/**
* Overwrite options for light themes.
*/
light?: ThemableDecorationInstanceRenderOptions;
/**
* Overwrite options for dark themes.
*/
dark?: ThemableDecorationInstanceRenderOptions;
}
/**
* Represents an editor that is attached to a [document](#TextDocument).
*/
export interface TextEditor {
/**
* The document associated with this text editor. The document will be the same for the entire lifetime of this text editor.
*/
readonly document: TextDocument;
/**
* The primary selection on this text editor. Shorthand for `TextEditor.selections[0]`.
*/
selection: Selection;
/**
* The selections in this text editor. The primary selection is always at index 0.
*/
selections: Selection[];
/**
* The current visible ranges in the editor (vertically).
* This accounts only for vertical scrolling, and not for horizontal scrolling.
*/
readonly visibleRanges: Range[];
/**
* Text editor options.
*/
options: TextEditorOptions;
/**
* The column in which this editor shows. Will be `undefined` in case this
* isn't one of the main editors, e.g an embedded editor, or when the editor
* column is larger than three.
*/
viewColumn?: ViewColumn;
/**
* Perform an edit on the document associated with this text editor.
*
* The given callback-function is invoked with an [edit-builder](#TextEditorEdit) which must
* be used to make edits. Note that the edit-builder is only valid while the
* callback executes.
*
* @param callback A function which can create edits using an [edit-builder](#TextEditorEdit).
* @param options The undo/redo behavior around this edit. By default, undo stops will be created before and after this edit.
* @return A promise that resolves with a value indicating if the edits could be applied.
*/
edit(callback: (editBuilder: TextEditorEdit) => void, options?: { undoStopBefore: boolean; undoStopAfter: boolean; }): Thenable<boolean>;
/**
* Insert a [snippet](#SnippetString) and put the editor into snippet mode. "Snippet mode"
* means the editor adds placeholders and additional cursors so that the user can complete
* or accept the snippet.
*
* @param snippet The snippet to insert in this edit.
* @param location Position or range at which to insert the snippet, defaults to the current editor selection or selections.
* @param options The undo/redo behavior around this edit. By default, undo stops will be created before and after this edit.
* @return A promise that resolves with a value indicating if the snippet could be inserted. Note that the promise does not signal
* that the snippet is completely filled-in or accepted.
*/
insertSnippet(snippet: SnippetString, location?: Position | Range | Position[] | Range[], options?: { undoStopBefore: boolean; undoStopAfter: boolean; }): Thenable<boolean>;
/**
* Adds a set of decorations to the text editor. If a set of decorations already exists with
* the given [decoration type](#TextEditorDecorationType), they will be replaced.
*
* @see [createTextEditorDecorationType](#window.createTextEditorDecorationType).
*
* @param decorationType A decoration type.
* @param rangesOrOptions Either [ranges](#Range) or more detailed [options](#DecorationOptions).
*/
setDecorations(decorationType: TextEditorDecorationType, rangesOrOptions: Range[] | DecorationOptions[]): void;
/**
* Scroll as indicated by `revealType` in order to reveal the given range.
*
* @param range A range.
* @param revealType The scrolling strategy for revealing `range`.
*/
revealRange(range: Range, revealType?: TextEditorRevealType): void;
/**
* ~~Show the text editor.~~
*
* @deprecated Use [window.showTextDocument](#window.showTextDocument) instead.
*
* @param column The [column](#ViewColumn) in which to show this editor.
* This method shows unexpected behavior and will be removed in the next major update.
*/
show(column?: ViewColumn): void;
/**
* ~~Hide the text editor.~~
*
* @deprecated Use the command `workbench.action.closeActiveEditor` instead.
* This method shows unexpected behavior and will be removed in the next major update.
*/
hide(): void;
}
/**
* Represents an end of line character sequence in a [document](#TextDocument).
*/
export enum EndOfLine {
/**
* The line feed `\n` character.
*/
LF = 1,
/**
* The carriage return line feed `\r\n` sequence.
*/
CRLF = 2
}
/**
* A complex edit that will be applied in one transaction on a TextEditor.
* This holds a description of the edits and if the edits are valid (i.e. no overlapping regions, document was not changed in the meantime, etc.)
* they can be applied on a [document](#TextDocument) associated with a [text editor](#TextEditor).
*
*/
export interface TextEditorEdit {
/**
* Replace a certain text region with a new value.
* You can use \r\n or \n in `value` and they will be normalized to the current [document](#TextDocument).
*
* @param location The range this operation should remove.
* @param value The new text this operation should insert after removing `location`.
*/
replace(location: Position | Range | Selection, value: string): void;
/**
* Insert text at a location.
* You can use \r\n or \n in `value` and they will be normalized to the current [document](#TextDocument).
* Although the equivalent text edit can be made with [replace](#TextEditorEdit.replace), `insert` will produce a different resulting selection (it will get moved).
*
* @param location The position where the new text should be inserted.
* @param value The new text this operation should insert.
*/
insert(location: Position, value: string): void;
/**
* Delete a certain text region.
*
* @param location The range this operation should remove.
*/
delete(location: Range | Selection): void;
/**
* Set the end of line sequence.
*
* @param endOfLine The new end of line for the [document](#TextDocument).
*/
setEndOfLine(endOfLine: EndOfLine): void;
}
/**
* A universal resource identifier representing either a file on disk
* or another resource, like untitled resources.
*/
export class Uri {
/**
* Create an URI from a string, e.g. `http://www.msft.com/some/path`,
* `file:///usr/home`, or `scheme:with/path`.
*
* @see [Uri.toString](#Uri.toString)
* @param value The string value of an Uri.
* @return A new Uri instance.
*/
static parse(value: string): Uri;
/**
* Create an URI from a file system path. The [scheme](#Uri.scheme)
* will be `file`.
*
* The *difference* between `Uri#parse` and `Uri#file` is that the latter treats the argument
* as path, not as stringified-uri. E.g. `Uri.file(path)` is *not* the same as
* `Uri.parse('file://' + path)` because the path might contain characters that are
* interpreted (# and ?). See the following sample:
* ```ts
const good = URI.file('/coding/c#/project1');
good.scheme === 'file';
good.path === '/coding/c#/project1';
good.fragment === '';
const bad = URI.parse('file://' + '/coding/c#/project1');
bad.scheme === 'file';
bad.path === '/coding/c'; // path is now broken
bad.fragment === '/project1';
```
*
* @param path A file system or UNC path.
* @return A new Uri instance.
*/
static file(path: string): Uri;
/**
* Use the `file` and `parse` factory functions to create new `Uri` objects.
*/
private constructor(scheme: string, authority: string, path: string, query: string, fragment: string);
/**
* Scheme is the `http` part of `http://www.msft.com/some/path?query#fragment`.
* The part before the first colon.
*/
readonly scheme: string;
/**
* Authority is the `www.msft.com` part of `http://www.msft.com/some/path?query#fragment`.
* The part between the first double slashes and the next slash.
*/
readonly authority: string;
/**
* Path is the `/some/path` part of `http://www.msft.com/some/path?query#fragment`.
*/
readonly path: string;
/**
* Query is the `query` part of `http://www.msft.com/some/path?query#fragment`.
*/
readonly query: string;
/**
* Fragment is the `fragment` part of `http://www.msft.com/some/path?query#fragment`.
*/
readonly fragment: string;
/**
* The string representing the corresponding file system path of this Uri.
*
* Will handle UNC paths and normalize windows drive letters to lower-case. Also
* uses the platform specific path separator.
*
* * Will *not* validate the path for invalid characters and semantics.
* * Will *not* look at the scheme of this Uri.
* * The resulting string shall *not* be used for display purposes but
* for disk operations, like `readFile` et al.
*
* The *difference* to the [`path`](#Uri.path)-property is the use of the platform specific
* path separator and the handling of UNC paths. The sample below outlines the difference:
* ```ts
const u = URI.parse('file://server/c$/folder/file.txt')
u.authority === 'server'
u.path === '/shares/c$/file.txt'
u.fsPath === '\\server\c$\folder\file.txt'
```
*/
readonly fsPath: string;
/**
* Derive a new Uri from this Uri.
*
* ```ts
* let file = Uri.parse('before:some/file/path');
* let other = file.with({ scheme: 'after' });
* assert.ok(other.toString() === 'after:some/file/path');
* ```
*
* @param change An object that describes a change to this Uri. To unset components use `null` or
* the empty string.
* @return A new Uri that reflects the given change. Will return `this` Uri if the change
* is not changing anything.
*/
with(change: { scheme?: string; authority?: string; path?: string; query?: string; fragment?: string }): Uri;
/**
* Returns a string representation of this Uri. The representation and normalization
* of a URI depends on the scheme.
*
* * The resulting string can be safely used with [Uri.parse](#Uri.parse).
* * The resulting string shall *not* be used for display purposes.
*
* *Note* that the implementation will encode _aggressive_ which often leads to unexpected,
* but not incorrect, results. For instance, colons are encoded to `%3A` which might be unexpected
* in file-uri. Also `&` and `=` will be encoded which might be unexpected for http-uris. For stability
* reasons this cannot be changed anymore. If you suffer from too aggressive encoding you should use
* the `skipEncoding`-argument: `uri.toString(true)`.
*
* @param skipEncoding Do not percentage-encode the result, defaults to `false`. Note that
* the `#` and `?` characters occurring in the path will always be encoded.
* @returns A string representation of this Uri.
*/
toString(skipEncoding?: boolean): string;
/**
* Returns a JSON representation of this Uri.
*
* @return An object.
*/
toJSON(): any;
}
/**
* A cancellation token is passed to an asynchronous or long running
* operation to request cancellation, like cancelling a request
* for completion items because the user continued to type.
*
* To get an instance of a `CancellationToken` use a
* [CancellationTokenSource](#CancellationTokenSource).
*/
export interface CancellationToken {
/**
* Is `true` when the token has been cancelled, `false` otherwise.
*/
isCancellationRequested: boolean;
/**
* An [event](#Event) which fires upon cancellation.
*/
onCancellationRequested: Event<any>;
}
/**
* A cancellation source creates and controls a [cancellation token](#CancellationToken).
*/
export class CancellationTokenSource {
/**
* The cancellation token of this source.
*/
token: CancellationToken;
/**
* Signal cancellation on the token.
*/
cancel(): void;
/**
* Dispose object and free resources.
*/
dispose(): void;
}
/**
* Represents a type which can release resources, such
* as event listening or a timer.
*/
export class Disposable {
/**
* Combine many disposable-likes into one. Use this method
* when having objects with a dispose function which are not
* instances of Disposable.
*
* @param disposableLikes Objects that have at least a `dispose`-function member.
* @return Returns a new disposable which, upon dispose, will
* dispose all provided disposables.
*/
static from(...disposableLikes: { dispose: () => any }[]): Disposable;
/**
* Creates a new Disposable calling the provided function
* on dispose.
* @param callOnDispose Function that disposes something.
*/
constructor(callOnDispose: Function);
/**
* Dispose this object.
*/
dispose(): any;
}
/**
* Represents a typed event.
*
* A function that represents an event to which you subscribe by calling it with
* a listener function as argument.
*
* @sample `item.onDidChange(function(event) { console.log("Event happened: " + event); });`
*/
export interface Event<T> {
/**
* A function that represents an event to which you subscribe by calling it with
* a listener function as argument.
*
* @param listener The listener function will be called when the event happens.
* @param thisArgs The `this`-argument which will be used when calling the event listener.
* @param disposables An array to which a [disposable](#Disposable) will be added.
* @return A disposable which unsubscribes the event listener.
*/
(listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]): Disposable;
}
/**
* An event emitter can be used to create and manage an [event](#Event) for others
* to subscribe to. One emitter always owns one event.
*
* Use this class if you want to provide event from within your extension, for instance
* inside a [TextDocumentContentProvider](#TextDocumentContentProvider) or when providing
* API to other extensions.
*/
export class EventEmitter<T> {
/**
* The event listeners can subscribe to.
*/
event: Event<T>;
/**
* Notify all subscribers of the [event](#EventEmitter.event). Failure
* of one or more listener will not fail this function call.
*
* @param data The event object.
*/
fire(data?: T): void;
/**
* Dispose this object and free resources.
*/
dispose(): void;
}
/**
* A file system watcher notifies about changes to files and folders
* on disk.
*
* To get an instance of a `FileSystemWatcher` use
* [createFileSystemWatcher](#workspace.createFileSystemWatcher).
*/
export interface FileSystemWatcher extends Disposable {
/**
* true if this file system watcher has been created such that
* it ignores creation file system events.
*/
ignoreCreateEvents: boolean;
/**
* true if this file system watcher has been created such that
* it ignores change file system events.
*/
ignoreChangeEvents: boolean;
/**
* true if this file system watcher has been created such that
* it ignores delete file system events.
*/
ignoreDeleteEvents: boolean;
/**
* An event which fires on file/folder creation.
*/
onDidCreate: Event<Uri>;
/**
* An event which fires on file/folder change.
*/
onDidChange: Event<Uri>;
/**
* An event which fires on file/folder deletion.
*/
onDidDelete: Event<Uri>;
}
/**
* A text document content provider allows to add readonly documents
* to the editor, such as source from a dll or generated html from md.
*
* Content providers are [registered](#workspace.registerTextDocumentContentProvider)
* for a [uri-scheme](#Uri.scheme). When a uri with that scheme is to
* be [loaded](#workspace.openTextDocument) the content provider is
* asked.
*/
export interface TextDocumentContentProvider {
/**
* An event to signal a resource has changed.
*/
onDidChange?: Event<Uri>;
/**
* Provide textual content for a given uri.
*
* The editor will use the returned string-content to create a readonly
* [document](#TextDocument). Resources allocated should be released when
* the corresponding document has been [closed](#workspace.onDidCloseTextDocument).
*
* **Note**: The contents of the created [document](#TextDocument) might not be
* identical to the provided text due to end-of-line-sequence normalization.
*
* @param uri An uri which scheme matches the scheme this provider was [registered](#workspace.registerTextDocumentContentProvider) for.
* @param token A cancellation token.
* @return A string or a thenable that resolves to such.
*/
provideTextDocumentContent(uri: Uri, token: CancellationToken): ProviderResult<string>;
}
/**
* Represents an item that can be selected from
* a list of items.
*/
export interface QuickPickItem {
/**
* A human readable string which is rendered prominent.
*/
label: string;
/**
* A human readable string which is rendered less prominent.
*/
description?: string;
/**
* A human readable string which is rendered less prominent.
*/
detail?: string;
/**
* Optional flag indicating if this item is picked initially.
* (Only honored when the picker allows multiple selections.)
*
* @see [QuickPickOptions.canPickMany](#QuickPickOptions.canPickMany)
*/
picked?: boolean;
/**
* Always show this item.
*/
alwaysShow?: boolean;
}
/**
* Options to configure the behavior of the quick pick UI.
*/
export interface QuickPickOptions {
/**
* An optional flag to include the description when filtering the picks.
*/
matchOnDescription?: boolean;
/**
* An optional flag to include the detail when filtering the picks.
*/
matchOnDetail?: boolean;
/**
* An optional string to show as place holder in the input box to guide the user what to pick on.
*/
placeHolder?: string;
/**
* Set to `true` to keep the picker open when focus moves to another part of the editor or to another window.
*/
ignoreFocusOut?: boolean;
/**
* An optional flag to make the picker accept multiple selections, if true the result is an array of picks.
*/
canPickMany?: boolean;
/**
* An optional function that is invoked whenever an item is selected.
*/
onDidSelectItem?(item: QuickPickItem | string): any;
}
/**
* Options to configure the behaviour of the [workspace folder](#WorkspaceFolder) pick UI.
*/
export interface WorkspaceFolderPickOptions {
/**
* An optional string to show as place holder in the input box to guide the user what to pick on.
*/
placeHolder?: string;
/**
* Set to `true` to keep the picker open when focus moves to another part of the editor or to another window.
*/
ignoreFocusOut?: boolean;
}
/**
* Options to configure the behaviour of a file open dialog.
*
* * Note 1: A dialog can select files, folders, or both. This is not true for Windows
* which enforces to open either files or folder, but *not both*.
* * Note 2: Explicitly setting `canSelectFiles` and `canSelectFolders` to `false` is futile
* and the editor then silently adjusts the options to select files.
*/
export interface OpenDialogOptions {
/**
* The resource the dialog shows when opened.
*/
defaultUri?: Uri;
/**
* A human-readable string for the open button.
*/
openLabel?: string;
/**
* Allow to select files, defaults to `true`.
*/
canSelectFiles?: boolean;
/**
* Allow to select folders, defaults to `false`.
*/
canSelectFolders?: boolean;
/**
* Allow to select many files or folders.
*/
canSelectMany?: boolean;
/**
* A set of file filters that are used by the dialog. Each entry is a human readable label,
* like "TypeScript", and an array of extensions, e.g.
* ```ts
* {
* 'Images': ['png', 'jpg']
* 'TypeScript': ['ts', 'tsx']
* }
* ```
*/
filters?: { [name: string]: string[] };
}
/**
* Options to configure the behaviour of a file save dialog.
*/
export interface SaveDialogOptions {
/**
* The resource the dialog shows when opened.
*/
defaultUri?: Uri;
/**
* A human-readable string for the save button.
*/
saveLabel?: string;
/**
* A set of file filters that are used by the dialog. Each entry is a human readable label,
* like "TypeScript", and an array of extensions, e.g.
* ```ts
* {
* 'Images': ['png', 'jpg']
* 'TypeScript': ['ts', 'tsx']
* }
* ```
*/
filters?: { [name: string]: string[] };
}
/**
* Represents an action that is shown with an information, warning, or
* error message.
*
* @see [showInformationMessage](#window.showInformationMessage)
* @see [showWarningMessage](#window.showWarningMessage)
* @see [showErrorMessage](#window.showErrorMessage)
*/
export interface MessageItem {
/**
* A short title like 'Retry', 'Open Log' etc.
*/
title: string;
/**
* A hint for modal dialogs that the item should be triggered
* when the user cancels the dialog (e.g. by pressing the ESC
* key).
*
* Note: this option is ignored for non-modal messages.
*/
isCloseAffordance?: boolean;
}
/**
* Options to configure the behavior of the message.
*
* @see [showInformationMessage](#window.showInformationMessage)
* @see [showWarningMessage](#window.showWarningMessage)
* @see [showErrorMessage](#window.showErrorMessage)
*/
export interface MessageOptions {
/**
* Indicates that this message should be modal.
*/
modal?: boolean;
}
/**
* Options to configure the behavior of the input box UI.
*/
export interface InputBoxOptions {
/**
* The value to prefill in the input box.
*/
value?: string;
/**
* Selection of the prefilled [`value`](#InputBoxOptions.value). Defined as tuple of two number where the
* first is the inclusive start index and the second the exclusive end index. When `undefined` the whole
* word will be selected, when empty (start equals end) only the cursor will be set,
* otherwise the defined range will be selected.
*/
valueSelection?: [number, number];
/**
* The text to display underneath the input box.
*/
prompt?: string;
/**
* An optional string to show as place holder in the input box to guide the user what to type.
*/
placeHolder?: string;
/**
* Set to `true` to show a password prompt that will not show the typed value.
*/
password?: boolean;
/**
* Set to `true` to keep the input box open when focus moves to another part of the editor or to another window.
*/
ignoreFocusOut?: boolean;
/**
* An optional function that will be called to validate input and to give a hint
* to the user.
*
* @param value The current value of the input box.
* @return A human readable string which is presented as diagnostic message.
* Return `undefined`, `null`, or the empty string when 'value' is valid.
*/
validateInput?(value: string): string | undefined | null | Thenable<string | undefined | null>;
}
/**
* A relative pattern is a helper to construct glob patterns that are matched
* relatively to a base path. The base path can either be an absolute file path
* or a [workspace folder](#WorkspaceFolder).
*/
export class RelativePattern {
/**
* A base file path to which this pattern will be matched against relatively.
*/
base: string;
/**
* A file glob pattern like `*.{ts,js}` that will be matched on file paths
* relative to the base path.
*
* Example: Given a base of `/home/work/folder` and a file path of `/home/work/folder/index.js`,
* the file glob pattern will match on `index.js`.
*/
pattern: string;
/**
* Creates a new relative pattern object with a base path and pattern to match. This pattern
* will be matched on file paths relative to the base path.
*
* @param base A base file path to which this pattern will be matched against relatively.
* @param pattern A file glob pattern like `*.{ts,js}` that will be matched on file paths
* relative to the base path.
*/
constructor(base: WorkspaceFolder | string, pattern: string)
}
/**
* A file glob pattern to match file paths against. This can either be a glob pattern string
* (like `**/*.{ts,js}` or `*.{ts,js}`) or a [relative pattern](#RelativePattern).
*
* Glob patterns can have the following syntax:
* * `*` to match one or more characters in a path segment
* * `?` to match on one character in a path segment
* * `**` to match any number of path segments, including none
* * `{}` to group conditions (e.g. `**/*.{ts,js}` matches all TypeScript and JavaScript files)
* * `[]` to declare a range of characters to match in a path segment (e.g., `example.[0-9]` to match on `example.0`, `example.1`, …)
* * `[!...]` to negate a range of characters to match in a path segment (e.g., `example.[!0-9]` to match on `example.a`, `example.b`, but not `example.0`)
*/
export type GlobPattern = string | RelativePattern;
/**
* A document filter denotes a document by different properties like
* the [language](#TextDocument.languageId), the [scheme](#Uri.scheme) of
* its resource, or a glob-pattern that is applied to the [path](#TextDocument.fileName).
*
* @sample A language filter that applies to typescript files on disk: `{ language: 'typescript', scheme: 'file' }`
* @sample A language filter that applies to all package.json paths: `{ language: 'json', scheme: 'untitled', pattern: '**/package.json' }`
*/
export interface DocumentFilter {
/**
* A language id, like `typescript`.
*/
language?: string;
/**
* A Uri [scheme](#Uri.scheme), like `file` or `untitled`.
*/
scheme?: string;
/**
* A [glob pattern](#GlobPattern) that is matched on the absolute path of the document. Use a [relative pattern](#RelativePattern)
* to filter documents to a [workspace folder](#WorkspaceFolder).
*/
pattern?: GlobPattern;
}
/**
* A language selector is the combination of one or many language identifiers
* and [language filters](#DocumentFilter).
*
* *Note* that a document selector that is just a language identifier selects *all*
* documents, even those that are not saved on disk. Only use such selectors when
* a feature works without further context, e.g without the need to resolve related
* 'files'.
*
* @sample `let sel:DocumentSelector = { scheme: 'file', language: 'typescript' }`;
*/
export type DocumentSelector = DocumentFilter | string | Array<DocumentFilter | string>;
/**
* A provider result represents the values a provider, like the [`HoverProvider`](#HoverProvider),
* may return. For once this is the actual result type `T`, like `Hover`, or a thenable that resolves
* to that type `T`. In addition, `null` and `undefined` can be returned - either directly or from a
* thenable.
*
* The snippets below are all valid implementations of the [`HoverProvider`](#HoverProvider):
*
* ```ts
* let a: HoverProvider = {
* provideHover(doc, pos, token): ProviderResult<Hover> {
* return new Hover('Hello World');
* }
* }
*
* let b: HoverProvider = {
* provideHover(doc, pos, token): ProviderResult<Hover> {
* return new Promise(resolve => {
* resolve(new Hover('Hello World'));
* });
* }
* }
*
* let c: HoverProvider = {
* provideHover(doc, pos, token): ProviderResult<Hover> {
* return; // undefined
* }
* }
* ```
*/
export type ProviderResult<T> = T | undefined | null | Thenable<T | undefined | null>;
/**
* Kind of a code action.
*
* Kinds are a hierarchical list of identifiers separated by `.`, e.g. `"refactor.extract.function"`.
*
* Code action kinds are used by VS Code for UI elements such as the refactoring context menu. Users
* can also trigger code actions with a specific kind with the `editor.action.codeAction` command.
*/
export class CodeActionKind {
/**
* Empty kind.
*/
static readonly Empty: CodeActionKind;
/**
* Base kind for quickfix actions: `quickfix`.
*
* Quick fix actions address a problem in the code and are shown in the normal code action context menu.
*/
static readonly QuickFix: CodeActionKind;
/**
* Base kind for refactoring actions: `refactor`
*
* Refactoring actions are shown in the refactoring context menu.
*/
static readonly Refactor: CodeActionKind;
/**
* Base kind for refactoring extraction actions: `refactor.extract`
*
* Example extract actions:
*
* - Extract method
* - Extract function
* - Extract variable
* - Extract interface from class
* - ...
*/
static readonly RefactorExtract: CodeActionKind;
/**
* Base kind for refactoring inline actions: `refactor.inline`
*
* Example inline actions:
*
* - Inline function
* - Inline variable
* - Inline constant
* - ...
*/
static readonly RefactorInline: CodeActionKind;
/**
* Base kind for refactoring rewrite actions: `refactor.rewrite`
*
* Example rewrite actions:
*
* - Convert JavaScript function to class
* - Add or remove parameter
* - Encapsulate field
* - Make method static
* - Move method to base class
* - ...
*/
static readonly RefactorRewrite: CodeActionKind;
/**
* Base kind for source actions: `source`
*
* Source code actions apply to the entire file and can be run on save
* using `editor.codeActionsOnSave`. They also are shown in `source` context menu.
*/
static readonly Source: CodeActionKind;
/**
* Base kind for an organize imports source action: `source.organizeImports`.
*/
static readonly SourceOrganizeImports: CodeActionKind;
private constructor(value: string);
/**
* String value of the kind, e.g. `"refactor.extract.function"`.
*/
readonly value?: string;
/**
* Create a new kind by appending a more specific selector to the current kind.
*
* Does not modify the current kind.
*/
append(parts: string): CodeActionKind;
/**
* Does this kind contain `other`?
*
* The kind `"refactor"` for example contains `"refactor.extract"` and ``"refactor.extract.function"`, but not `"unicorn.refactor.extract"` or `"refactory.extract"`
*
* @param other Kind to check.
*/
contains(other: CodeActionKind): boolean;
}
/**
* Contains additional diagnostic information about the context in which
* a [code action](#CodeActionProvider.provideCodeActions) is run.
*/
export interface CodeActionContext {
/**
* An array of diagnostics.
*/
readonly diagnostics: Diagnostic[];
/**
* Requested kind of actions to return.
*
* Actions not of this kind are filtered out before being shown by the lightbulb.
*/
readonly only?: CodeActionKind;
}
/**
* A code action represents a change that can be performed in code, e.g. to fix a problem or
* to refactor code.
*
* A CodeAction must set either [`edit`](#CodeAction.edit) and/or a [`command`](#CodeAction.command). If both are supplied, the `edit` is applied first, then the command is executed.
*/
export class CodeAction {
/**
* A short, human-readable, title for this code action.
*/
title: string;
/**
* A [workspace edit](#WorkspaceEdit) this code action performs.
*/
edit?: WorkspaceEdit;
/**
* [Diagnostics](#Diagnostic) that this code action resolves.
*/
diagnostics?: Diagnostic[];
/**
* A [command](#Command) this code action executes.
*/
command?: Command;
/**
* [Kind](#CodeActionKind) of the code action.
*
* Used to filter code actions.
*/
kind?: CodeActionKind;
/**
* Creates a new code action.
*
* A code action must have at least a [title](#CodeAction.title) and [edits](#CodeAction.edit)
* and/or a [command](#CodeAction.command).
*
* @param title The title of the code action.
* @param kind The kind of the code action.
*/
constructor(title: string, kind?: CodeActionKind);
}
/**
* The code action interface defines the contract between extensions and
* the [light bulb](https://code.visualstudio.com/docs/editor/editingevolved#_code-action) feature.
*
* A code action can be any command that is [known](#commands.getCommands) to the system.
*/
export interface CodeActionProvider {
/**
* Provide commands for the given document and range.
*
* @param document The document in which the command was invoked.
* @param range The selector or range for which the command was invoked. This will always be a selection if
* there is a currently active editor.
* @param context Context carrying additional information.
* @param token A cancellation token.
* @return An array of commands, quick fixes, or refactorings or a thenable of such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideCodeActions(document: TextDocument, range: Range | Selection, context: CodeActionContext, token: CancellationToken): ProviderResult<(Command | CodeAction)[]>;
}
/**
* Metadata about the type of code actions that a [CodeActionProvider](#CodeActionProvider) providers
*/
export interface CodeActionProviderMetadata {
/**
* [CodeActionKinds](#CodeActionKind) that this provider may return.
*
* The list of kinds may be generic, such as `CodeActionKind.Refactor`, or the provider
* may list our every specific kind they provide, such as `CodeActionKind.Refactor.Extract.append('function`)`
*/
readonly providedCodeActionKinds?: ReadonlyArray<CodeActionKind>;
}
/**
* A code lens represents a [command](#Command) that should be shown along with
* source text, like the number of references, a way to run tests, etc.
*
* A code lens is _unresolved_ when no command is associated to it. For performance
* reasons the creation of a code lens and resolving should be done to two stages.
*
* @see [CodeLensProvider.provideCodeLenses](#CodeLensProvider.provideCodeLenses)
* @see [CodeLensProvider.resolveCodeLens](#CodeLensProvider.resolveCodeLens)
*/
export class CodeLens {
/**
* The range in which this code lens is valid. Should only span a single line.
*/
range: Range;
/**
* The command this code lens represents.
*/
command?: Command;
/**
* `true` when there is a command associated.
*/
readonly isResolved: boolean;
/**
* Creates a new code lens object.
*
* @param range The range to which this code lens applies.
* @param command The command associated to this code lens.
*/
constructor(range: Range, command?: Command);
}
/**
* A code lens provider adds [commands](#Command) to source text. The commands will be shown
* as dedicated horizontal lines in between the source text.
*/
export interface CodeLensProvider {
/**
* An optional event to signal that the code lenses from this provider have changed.
*/
onDidChangeCodeLenses?: Event<void>;
/**
* Compute a list of [lenses](#CodeLens). This call should return as fast as possible and if
* computing the commands is expensive implementors should only return code lens objects with the
* range set and implement [resolve](#CodeLensProvider.resolveCodeLens).
*
* @param document The document in which the command was invoked.
* @param token A cancellation token.
* @return An array of code lenses or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideCodeLenses(document: TextDocument, token: CancellationToken): ProviderResult<CodeLens[]>;
/**
* This function will be called for each visible code lens, usually when scrolling and after
* calls to [compute](#CodeLensProvider.provideCodeLenses)-lenses.
*
* @param codeLens code lens that must be resolved.
* @param token A cancellation token.
* @return The given, resolved code lens or thenable that resolves to such.
*/
resolveCodeLens?(codeLens: CodeLens, token: CancellationToken): ProviderResult<CodeLens>;
}
/**
* Information about where a symbol is defined.
*
* Provides additional metadata over normal [location](#Location) definitions, including the range of
* the defining symbol
*/
export type DefinitionLink = LocationLink;
/**
* The definition of a symbol represented as one or many [locations](#Location).
* For most programming languages there is only one location at which a symbol is
* defined.
*/
export type Definition = Location | Location[];
/**
* The definition provider interface defines the contract between extensions and
* the [go to definition](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-definition)
* and peek definition features.
*/
export interface DefinitionProvider {
/**
* Provide the definition of the symbol at the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return A definition or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideDefinition(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Definition | DefinitionLink[]>;
}
/**
* The implementation provider interface defines the contract between extensions and
* the go to implementation feature.
*/
export interface ImplementationProvider {
/**
* Provide the implementations of the symbol at the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return A definition or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideImplementation(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Definition | DefinitionLink[]>;
}
/**
* The type definition provider defines the contract between extensions and
* the go to type definition feature.
*/
export interface TypeDefinitionProvider {
/**
* Provide the type definition of the symbol at the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return A definition or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideTypeDefinition(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Definition | DefinitionLink[]>;
}
/**
* The declaration of a symbol representation as one or many [locations](#Location)
* or [location links][#LocationLink].
*/
export type Declaration = Location | Location[] | LocationLink[];
/**
* The declaration provider interface defines the contract between extensions and
* the go to declaration feature.
*/
export interface DeclarationProvider {
/**
* Provide the declaration of the symbol at the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return A declaration or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideDeclaration(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Declaration>;
}
/**
* The MarkdownString represents human readable text that supports formatting via the
* markdown syntax. Standard markdown is supported, also tables, but no embedded html.
*/
export class MarkdownString {
/**
* The markdown string.
*/
value: string;
/**
* Indicates that this markdown string is from a trusted source. Only *trusted*
* markdown supports links that execute commands, e.g. `[Run it](command:myCommandId)`.
*/
isTrusted?: boolean;
/**
* Creates a new markdown string with the given value.
*
* @param value Optional, initial value.
*/
constructor(value?: string);
/**
* Appends and escapes the given string to this markdown string.
* @param value Plain text.
*/
appendText(value: string): MarkdownString;
/**
* Appends the given string 'as is' to this markdown string.
* @param value Markdown string.
*/
appendMarkdown(value: string): MarkdownString;
/**
* Appends the given string as codeblock using the provided language.
* @param value A code snippet.
* @param language An optional [language identifier](#languages.getLanguages).
*/
appendCodeblock(value: string, language?: string): MarkdownString;
}
/**
* ~~MarkedString can be used to render human readable text. It is either a markdown string
* or a code-block that provides a language and a code snippet. Note that
* markdown strings will be sanitized - that means html will be escaped.~~
*
* @deprecated This type is deprecated, please use [`MarkdownString`](#MarkdownString) instead.
*/
export type MarkedString = MarkdownString | string | { language: string; value: string };
/**
* A hover represents additional information for a symbol or word. Hovers are
* rendered in a tooltip-like widget.
*/
export class Hover {
/**
* The contents of this hover.
*/
contents: MarkedString[];
/**
* The range to which this hover applies. When missing, the
* editor will use the range at the current position or the
* current position itself.
*/
range?: Range;
/**
* Creates a new hover object.
*
* @param contents The contents of the hover.
* @param range The range to which the hover applies.
*/
constructor(contents: MarkedString | MarkedString[], range?: Range);
}
/**
* The hover provider interface defines the contract between extensions and
* the [hover](https://code.visualstudio.com/docs/editor/intellisense)-feature.
*/
export interface HoverProvider {
/**
* Provide a hover for the given position and document. Multiple hovers at the same
* position will be merged by the editor. A hover can have a range which defaults
* to the word range at the position when omitted.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return A hover or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideHover(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Hover>;
}
/**
* A document highlight kind.
*/
export enum DocumentHighlightKind {
/**
* A textual occurrence.
*/
Text = 0,
/**
* Read-access of a symbol, like reading a variable.
*/
Read = 1,
/**
* Write-access of a symbol, like writing to a variable.
*/
Write = 2
}
/**
* A document highlight is a range inside a text document which deserves
* special attention. Usually a document highlight is visualized by changing
* the background color of its range.
*/
export class DocumentHighlight {
/**
* The range this highlight applies to.
*/
range: Range;
/**
* The highlight kind, default is [text](#DocumentHighlightKind.Text).
*/
kind?: DocumentHighlightKind;
/**
* Creates a new document highlight object.
*
* @param range The range the highlight applies to.
* @param kind The highlight kind, default is [text](#DocumentHighlightKind.Text).
*/
constructor(range: Range, kind?: DocumentHighlightKind);
}
/**
* The document highlight provider interface defines the contract between extensions and
* the word-highlight-feature.
*/
export interface DocumentHighlightProvider {
/**
* Provide a set of document highlights, like all occurrences of a variable or
* all exit-points of a function.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return An array of document highlights or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideDocumentHighlights(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<DocumentHighlight[]>;
}
/**
* A symbol kind.
*/
export enum SymbolKind {
File = 0,
Module = 1,
Namespace = 2,
Package = 3,
Class = 4,
Method = 5,
Property = 6,
Field = 7,
Constructor = 8,
Enum = 9,
Interface = 10,
Function = 11,
Variable = 12,
Constant = 13,
String = 14,
Number = 15,
Boolean = 16,
Array = 17,
Object = 18,
Key = 19,
Null = 20,
EnumMember = 21,
Struct = 22,
Event = 23,
Operator = 24,
TypeParameter = 25
}
/**
* Represents information about programming constructs like variables, classes,
* interfaces etc.
*/
export class SymbolInformation {
/**
* The name of this symbol.
*/
name: string;
/**
* The name of the symbol containing this symbol.
*/
containerName: string;
/**
* The kind of this symbol.
*/
kind: SymbolKind;
/**
* The location of this symbol.
*/
location: Location;
/**
* Creates a new symbol information object.
*
* @param name The name of the symbol.
* @param kind The kind of the symbol.
* @param containerName The name of the symbol containing the symbol.
* @param location The location of the symbol.
*/
constructor(name: string, kind: SymbolKind, containerName: string, location: Location);
/**
* ~~Creates a new symbol information object.~~
*
* @deprecated Please use the constructor taking a [location](#Location) object.
*
* @param name The name of the symbol.
* @param kind The kind of the symbol.
* @param range The range of the location of the symbol.
* @param uri The resource of the location of symbol, defaults to the current document.
* @param containerName The name of the symbol containing the symbol.
*/
constructor(name: string, kind: SymbolKind, range: Range, uri?: Uri, containerName?: string);
}
/**
* Represents programming constructs like variables, classes, interfaces etc. that appear in a document. Document
* symbols can be hierarchical and they have two ranges: one that encloses its definition and one that points to
* its most interesting range, e.g. the range of an identifier.
*/
export class DocumentSymbol {
/**
* The name of this symbol.
*/
name: string;
/**
* More detail for this symbol, e.g the signature of a function.
*/
detail: string;
/**
* The kind of this symbol.
*/
kind: SymbolKind;
/**
* The range enclosing this symbol not including leading/trailing whitespace but everything else, e.g comments and code.
*/
range: Range;
/**
* The range that should be selected and reveal when this symbol is being picked, e.g the name of a function.
* Must be contained by the [`range`](#DocumentSymbol.range).
*/
selectionRange: Range;
/**
* Children of this symbol, e.g. properties of a class.
*/
children: DocumentSymbol[];
/**
* Creates a new document symbol.
*
* @param name The name of the symbol.
* @param detail Details for the symbol.
* @param kind The kind of the symbol.
* @param range The full range of the symbol.
* @param selectionRange The range that should be reveal.
*/
constructor(name: string, detail: string, kind: SymbolKind, range: Range, selectionRange: Range);
}
/**
* The document symbol provider interface defines the contract between extensions and
* the [go to symbol](https://code.visualstudio.com/docs/editor/editingevolved#_go-to-symbol)-feature.
*/
export interface DocumentSymbolProvider {
/**
* Provide symbol information for the given document.
*
* @param document The document in which the command was invoked.
* @param token A cancellation token.
* @return An array of document highlights or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideDocumentSymbols(document: TextDocument, token: CancellationToken): ProviderResult<SymbolInformation[] | DocumentSymbol[]>;
}
/**
* Metadata about a document symbol provider.
*/
export interface DocumentSymbolProviderMetadata {
/**
* A human readable string that is shown when multiple outlines trees show for one document.
*/
label?: string;
}
/**
* The workspace symbol provider interface defines the contract between extensions and
* the [symbol search](https://code.visualstudio.com/docs/editor/editingevolved#_open-symbol-by-name)-feature.
*/
export interface WorkspaceSymbolProvider {
/**
* Project-wide search for a symbol matching the given query string.
*
* The `query`-parameter should be interpreted in a *relaxed way* as the editor will apply its own highlighting
* and scoring on the results. A good rule of thumb is to match case-insensitive and to simply check that the
* characters of *query* appear in their order in a candidate symbol. Don't use prefix, substring, or similar
* strict matching.
*
* To improve performance implementors can implement `resolveWorkspaceSymbol` and then provide symbols with partial
* [location](#SymbolInformation.location)-objects, without a `range` defined. The editor will then call
* `resolveWorkspaceSymbol` for selected symbols only, e.g. when opening a workspace symbol.
*
* @param query A non-empty query string.
* @param token A cancellation token.
* @return An array of document highlights or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideWorkspaceSymbols(query: string, token: CancellationToken): ProviderResult<SymbolInformation[]>;
/**
* Given a symbol fill in its [location](#SymbolInformation.location). This method is called whenever a symbol
* is selected in the UI. Providers can implement this method and return incomplete symbols from
* [`provideWorkspaceSymbols`](#WorkspaceSymbolProvider.provideWorkspaceSymbols) which often helps to improve
* performance.
*
* @param symbol The symbol that is to be resolved. Guaranteed to be an instance of an object returned from an
* earlier call to `provideWorkspaceSymbols`.
* @param token A cancellation token.
* @return The resolved symbol or a thenable that resolves to that. When no result is returned,
* the given `symbol` is used.
*/
resolveWorkspaceSymbol?(symbol: SymbolInformation, token: CancellationToken): ProviderResult<SymbolInformation>;
}
/**
* Value-object that contains additional information when
* requesting references.
*/
export interface ReferenceContext {
/**
* Include the declaration of the current symbol.
*/
includeDeclaration: boolean;
}
/**
* The reference provider interface defines the contract between extensions and
* the [find references](https://code.visualstudio.com/docs/editor/editingevolved#_peek)-feature.
*/
export interface ReferenceProvider {
/**
* Provide a set of project-wide references for the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param context
* @param token A cancellation token.
* @return An array of locations or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideReferences(document: TextDocument, position: Position, context: ReferenceContext, token: CancellationToken): ProviderResult<Location[]>;
}
/**
* A text edit represents edits that should be applied
* to a document.
*/
export class TextEdit {
/**
* Utility to create a replace edit.
*
* @param range A range.
* @param newText A string.
* @return A new text edit object.
*/
static replace(range: Range, newText: string): TextEdit;
/**
* Utility to create an insert edit.
*
* @param position A position, will become an empty range.
* @param newText A string.
* @return A new text edit object.
*/
static insert(position: Position, newText: string): TextEdit;
/**
* Utility to create a delete edit.
*
* @param range A range.
* @return A new text edit object.
*/
static delete(range: Range): TextEdit;
/**
* Utility to create an eol-edit.
*
* @param eol An eol-sequence
* @return A new text edit object.
*/
static setEndOfLine(eol: EndOfLine): TextEdit;
/**
* The range this edit applies to.
*/
range: Range;
/**
* The string this edit will insert.
*/
newText: string;
/**
* The eol-sequence used in the document.
*
* *Note* that the eol-sequence will be applied to the
* whole document.
*/
newEol: EndOfLine;
/**
* Create a new TextEdit.
*
* @param range A range.
* @param newText A string.
*/
constructor(range: Range, newText: string);
}
/**
* A workspace edit is a collection of textual and files changes for
* multiple resources and documents.
*
* Use the [applyEdit](#workspace.applyEdit)-function to apply a workspace edit.
*/
export class WorkspaceEdit {
/**
* The number of affected resources of textual or resource changes.
*/
readonly size: number;
/**
* Replace the given range with given text for the given resource.
*
* @param uri A resource identifier.
* @param range A range.
* @param newText A string.
*/
replace(uri: Uri, range: Range, newText: string): void;
/**
* Insert the given text at the given position.
*
* @param uri A resource identifier.
* @param position A position.
* @param newText A string.
*/
insert(uri: Uri, position: Position, newText: string): void;
/**
* Delete the text at the given range.
*
* @param uri A resource identifier.
* @param range A range.
*/
delete(uri: Uri, range: Range): void;
/**
* Check if a text edit for a resource exists.
*
* @param uri A resource identifier.
* @return `true` if the given resource will be touched by this edit.
*/
has(uri: Uri): boolean;
/**
* Set (and replace) text edits for a resource.
*
* @param uri A resource identifier.
* @param edits An array of text edits.
*/
set(uri: Uri, edits: TextEdit[]): void;
/**
* Get the text edits for a resource.
*
* @param uri A resource identifier.
* @return An array of text edits.
*/
get(uri: Uri): TextEdit[];
/**
* Create a regular file.
*
* @param uri Uri of the new file..
* @param options Defines if an existing file should be overwritten or be
* ignored. When overwrite and ignoreIfExists are both set overwrite wins.
*/
createFile(uri: Uri, options?: { overwrite?: boolean, ignoreIfExists?: boolean }): void;
/**
* Delete a file or folder.
*
* @param uri The uri of the file that is to be deleted.
*/
deleteFile(uri: Uri, options?: { recursive?: boolean, ignoreIfNotExists?: boolean }): void;
/**
* Rename a file or folder.
*
* @param oldUri The existing file.
* @param newUri The new location.
* @param options Defines if existing files should be overwritten or be
* ignored. When overwrite and ignoreIfExists are both set overwrite wins.
*/
renameFile(oldUri: Uri, newUri: Uri, options?: { overwrite?: boolean, ignoreIfExists?: boolean }): void;
/**
* Get all text edits grouped by resource.
*
* @return A shallow copy of `[Uri, TextEdit[]]`-tuples.
*/
entries(): [Uri, TextEdit[]][];
}
/**
* A snippet string is a template which allows to insert text
* and to control the editor cursor when insertion happens.
*
* A snippet can define tab stops and placeholders with `$1`, `$2`
* and `${3:foo}`. `$0` defines the final tab stop, it defaults to
* the end of the snippet. Variables are defined with `$name` and
* `${name:default value}`. The full snippet syntax is documented
* [here](http://code.visualstudio.com/docs/editor/userdefinedsnippets#_creating-your-own-snippets).
*/
export class SnippetString {
/**
* The snippet string.
*/
value: string;
constructor(value?: string);
/**
* Builder-function that appends the given string to
* the [`value`](#SnippetString.value) of this snippet string.
*
* @param string A value to append 'as given'. The string will be escaped.
* @return This snippet string.
*/
appendText(string: string): SnippetString;
/**
* Builder-function that appends a tabstop (`$1`, `$2` etc) to
* the [`value`](#SnippetString.value) of this snippet string.
*
* @param number The number of this tabstop, defaults to an auto-increment
* value starting at 1.
* @return This snippet string.
*/
appendTabstop(number?: number): SnippetString;
/**
* Builder-function that appends a placeholder (`${1:value}`) to
* the [`value`](#SnippetString.value) of this snippet string.
*
* @param value The value of this placeholder - either a string or a function
* with which a nested snippet can be created.
* @param number The number of this tabstop, defaults to an auto-increment
* value starting at 1.
* @return This snippet string.
*/
appendPlaceholder(value: string | ((snippet: SnippetString) => any), number?: number): SnippetString;
/**
* Builder-function that appends a variable (`${VAR}`) to
* the [`value`](#SnippetString.value) of this snippet string.
*
* @param name The name of the variable - excluding the `$`.
* @param defaultValue The default value which is used when the variable name cannot
* be resolved - either a string or a function with which a nested snippet can be created.
* @return This snippet string.
*/
appendVariable(name: string, defaultValue: string | ((snippet: SnippetString) => any)): SnippetString;
}
/**
* The rename provider interface defines the contract between extensions and
* the [rename](https://code.visualstudio.com/docs/editor/editingevolved#_rename-symbol)-feature.
*/
export interface RenameProvider {
/**
* Provide an edit that describes changes that have to be made to one
* or many resources to rename a symbol to a different name.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param newName The new name of the symbol. If the given name is not valid, the provider must return a rejected promise.
* @param token A cancellation token.
* @return A workspace edit or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideRenameEdits(document: TextDocument, position: Position, newName: string, token: CancellationToken): ProviderResult<WorkspaceEdit>;
/**
* Optional function for resolving and validating a position *before* running rename. The result can
* be a range or a range and a placeholder text. The placeholder text should be the identifier of the symbol
* which is being renamed - when omitted the text in the returned range is used.
*
* @param document The document in which rename will be invoked.
* @param position The position at which rename will be invoked.
* @param token A cancellation token.
* @return The range or range and placeholder text of the identifier that is to be renamed. The lack of a result can signaled by returning `undefined` or `null`.
*/
prepareRename?(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<Range | { range: Range, placeholder: string }>;
}
/**
* Value-object describing what options formatting should use.
*/
export interface FormattingOptions {
/**
* Size of a tab in spaces.
*/
tabSize: number;
/**
* Prefer spaces over tabs.
*/
insertSpaces: boolean;
/**
* Signature for further properties.
*/
[key: string]: boolean | number | string;
}
/**
* The document formatting provider interface defines the contract between extensions and
* the formatting-feature.
*/
export interface DocumentFormattingEditProvider {
/**
* Provide formatting edits for a whole document.
*
* @param document The document in which the command was invoked.
* @param options Options controlling formatting.
* @param token A cancellation token.
* @return A set of text edits or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideDocumentFormattingEdits(document: TextDocument, options: FormattingOptions, token: CancellationToken): ProviderResult<TextEdit[]>;
}
/**
* The document formatting provider interface defines the contract between extensions and
* the formatting-feature.
*/
export interface DocumentRangeFormattingEditProvider {
/**
* Provide formatting edits for a range in a document.
*
* The given range is a hint and providers can decide to format a smaller
* or larger range. Often this is done by adjusting the start and end
* of the range to full syntax nodes.
*
* @param document The document in which the command was invoked.
* @param range The range which should be formatted.
* @param options Options controlling formatting.
* @param token A cancellation token.
* @return A set of text edits or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideDocumentRangeFormattingEdits(document: TextDocument, range: Range, options: FormattingOptions, token: CancellationToken): ProviderResult<TextEdit[]>;
}
/**
* The document formatting provider interface defines the contract between extensions and
* the formatting-feature.
*/
export interface OnTypeFormattingEditProvider {
/**
* Provide formatting edits after a character has been typed.
*
* The given position and character should hint to the provider
* what range the position to expand to, like find the matching `{`
* when `}` has been entered.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param ch The character that has been typed.
* @param options Options controlling formatting.
* @param token A cancellation token.
* @return A set of text edits or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined`, `null`, or an empty array.
*/
provideOnTypeFormattingEdits(document: TextDocument, position: Position, ch: string, options: FormattingOptions, token: CancellationToken): ProviderResult<TextEdit[]>;
}
/**
* Represents a parameter of a callable-signature. A parameter can
* have a label and a doc-comment.
*/
export class ParameterInformation {
/**
* The label of this signature.
*
* Either a string or inclusive start and exclusive end offsets within its containing
* [signature label](#SignatureInformation.label). *Note*: A label of type string must be
* a substring of its containing signature information's [label](#SignatureInformation.label).
*/
label: string | [number, number];
/**
* The human-readable doc-comment of this signature. Will be shown
* in the UI but can be omitted.
*/
documentation?: string | MarkdownString;
/**
* Creates a new parameter information object.
*
* @param label A label string.
* @param documentation A doc string.
*/
constructor(label: string, documentation?: string | MarkdownString);
}
/**
* Represents the signature of something callable. A signature
* can have a label, like a function-name, a doc-comment, and
* a set of parameters.
*/
export class SignatureInformation {
/**
* The label of this signature. Will be shown in
* the UI.
*/
label: string;
/**
* The human-readable doc-comment of this signature. Will be shown
* in the UI but can be omitted.
*/
documentation?: string | MarkdownString;
/**
* The parameters of this signature.
*/
parameters: ParameterInformation[];
/**
* Creates a new signature information object.
*
* @param label A label string.
* @param documentation A doc string.
*/
constructor(label: string, documentation?: string | MarkdownString);
}
/**
* Signature help represents the signature of something
* callable. There can be multiple signatures but only one
* active and only one active parameter.
*/
export class SignatureHelp {
/**
* One or more signatures.
*/
signatures: SignatureInformation[];
/**
* The active signature.
*/
activeSignature: number;
/**
* The active parameter of the active signature.
*/
activeParameter: number;
}
/**
* The signature help provider interface defines the contract between extensions and
* the [parameter hints](https://code.visualstudio.com/docs/editor/intellisense)-feature.
*/
export interface SignatureHelpProvider {
/**
* Provide help for the signature at the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @return Signature help or a thenable that resolves to such. The lack of a result can be
* signaled by returning `undefined` or `null`.
*/
provideSignatureHelp(document: TextDocument, position: Position, token: CancellationToken): ProviderResult<SignatureHelp>;
}
/**
* Completion item kinds.
*/
export enum CompletionItemKind {
Text = 0,
Method = 1,
Function = 2,
Constructor = 3,
Field = 4,
Variable = 5,
Class = 6,
Interface = 7,
Module = 8,
Property = 9,
Unit = 10,
Value = 11,
Enum = 12,
Keyword = 13,
Snippet = 14,
Color = 15,
Reference = 17,
File = 16,
Folder = 18,
EnumMember = 19,
Constant = 20,
Struct = 21,
Event = 22,
Operator = 23,
TypeParameter = 24
}
/**
* A completion item represents a text snippet that is proposed to complete text that is being typed.
*
* It is sufficient to create a completion item from just a [label](#CompletionItem.label). In that
* case the completion item will replace the [word](#TextDocument.getWordRangeAtPosition)
* until the cursor with the given label or [insertText](#CompletionItem.insertText). Otherwise the
* given [edit](#CompletionItem.textEdit) is used.
*
* When selecting a completion item in the editor its defined or synthesized text edit will be applied
* to *all* cursors/selections whereas [additionalTextEdits](#CompletionItem.additionalTextEdits) will be
* applied as provided.
*
* @see [CompletionItemProvider.provideCompletionItems](#CompletionItemProvider.provideCompletionItems)
* @see [CompletionItemProvider.resolveCompletionItem](#CompletionItemProvider.resolveCompletionItem)
*/
export class CompletionItem {
/**
* The label of this completion item. By default
* this is also the text that is inserted when selecting
* this completion.
*/
label: string;
/**
* The kind of this completion item. Based on the kind
* an icon is chosen by the editor.
*/
kind?: CompletionItemKind;
/**
* A human-readable string with additional information
* about this item, like type or symbol information.
*/
detail?: string;
/**
* A human-readable string that represents a doc-comment.
*/
documentation?: string | MarkdownString;
/**
* A string that should be used when comparing this item
* with other items. When `falsy` the [label](#CompletionItem.label)
* is used.
*/
sortText?: string;
/**
* A string that should be used when filtering a set of
* completion items. When `falsy` the [label](#CompletionItem.label)
* is used.
*/
filterText?: string;
/**
* Select this item when showing. *Note* that only one completion item can be selected and
* that the editor decides which item that is. The rule is that the *first* item of those
* that match best is selected.
*/
preselect?: boolean;
/**
* A string or snippet that should be inserted in a document when selecting
* this completion. When `falsy` the [label](#CompletionItem.label)
* is used.
*/
insertText?: string | SnippetString;
/**
* A range of text that should be replaced by this completion item.
*
* Defaults to a range from the start of the [current word](#TextDocument.getWordRangeAtPosition) to the
* current position.
*
* *Note:* The range must be a [single line](#Range.isSingleLine) and it must
* [contain](#Range.contains) the position at which completion has been [requested](#CompletionItemProvider.provideCompletionItems).
*/
range?: Range;
/**
* An optional set of characters that when pressed while this completion is active will accept it first and
* then type that character. *Note* that all commit characters should have `length=1` and that superfluous
* characters will be ignored.
*/
commitCharacters?: string[];
/**
* Keep whitespace of the [insertText](#CompletionItem.insertText) as is. By default, the editor adjusts leading
* whitespace of new lines so that they match the indentation of the line for which the item is accepeted - setting
* this to `true` will prevent that.
*/
keepWhitespace?: boolean;
/**
* @deprecated Use `CompletionItem.insertText` and `CompletionItem.range` instead.
*
* ~~An [edit](#TextEdit) which is applied to a document when selecting
* this completion. When an edit is provided the value of
* [insertText](#CompletionItem.insertText) is ignored.~~
*
* ~~The [range](#Range) of the edit must be single-line and on the same
* line completions were [requested](#CompletionItemProvider.provideCompletionItems) at.~~
*/
textEdit?: TextEdit;
/**
* An optional array of additional [text edits](#TextEdit) that are applied when
* selecting this completion. Edits must not overlap with the main [edit](#CompletionItem.textEdit)
* nor with themselves.
*/
additionalTextEdits?: TextEdit[];
/**
* An optional [command](#Command) that is executed *after* inserting this completion. *Note* that
* additional modifications to the current document should be described with the
* [additionalTextEdits](#CompletionItem.additionalTextEdits)-property.
*/
command?: Command;
/**
* Creates a new completion item.
*
* Completion items must have at least a [label](#CompletionItem.label) which then
* will be used as insert text as well as for sorting and filtering.
*
* @param label The label of the completion.
* @param kind The [kind](#CompletionItemKind) of the completion.
*/
constructor(label: string, kind?: CompletionItemKind);
}
/**
* Represents a collection of [completion items](#CompletionItem) to be presented
* in the editor.
*/
export class CompletionList {
/**
* This list is not complete. Further typing should result in recomputing
* this list.
*/
isIncomplete?: boolean;
/**
* The completion items.
*/
items: CompletionItem[];
/**
* Creates a new completion list.
*
* @param items The completion items.
* @param isIncomplete The list is not complete.
*/
constructor(items?: CompletionItem[], isIncomplete?: boolean);
}
/**
* How a [completion provider](#CompletionItemProvider) was triggered
*/
export enum CompletionTriggerKind {
/**
* Completion was triggered normally.
*/
Invoke = 0,
/**
* Completion was triggered by a trigger character.
*/
TriggerCharacter = 1,
/**
* Completion was re-triggered as current completion list is incomplete
*/
TriggerForIncompleteCompletions = 2
}
/**
* Contains additional information about the context in which
* [completion provider](#CompletionItemProvider.provideCompletionItems) is triggered.
*/
export interface CompletionContext {
/**
* How the completion was triggered.
*/
readonly triggerKind: CompletionTriggerKind;
/**
* Character that triggered the completion item provider.
*
* `undefined` if provider was not triggered by a character.
*
* The trigger character is already in the document when the completion provider is triggered.
*/
readonly triggerCharacter?: string;
}
/**
* The completion item provider interface defines the contract between extensions and
* [IntelliSense](https://code.visualstudio.com/docs/editor/intellisense).
*
* Providers can delay the computation of the [`detail`](#CompletionItem.detail)
* and [`documentation`](#CompletionItem.documentation) properties by implementing the
* [`resolveCompletionItem`](#CompletionItemProvider.resolveCompletionItem)-function. However, properties that
* are needed for the initial sorting and filtering, like `sortText`, `filterText`, `insertText`, and `range`, must
* not be changed during resolve.
*
* Providers are asked for completions either explicitly by a user gesture or -depending on the configuration-
* implicitly when typing words or trigger characters.
*/
export interface CompletionItemProvider {
/**
* Provide completion items for the given position and document.
*
* @param document The document in which the command was invoked.
* @param position The position at which the command was invoked.
* @param token A cancellation token.
* @param context How the completion was triggered.
*
* @return An array of completions, a [completion list](#CompletionList), or a thenable that resolves to either.
* The lack of a result can be signaled by returning `undefined`, `null`, or an empty array.
*/
provideCompletionItems(document: TextDocument, position: Position, token: CancellationToken, context: CompletionContext): ProviderResult<CompletionItem[] | CompletionList>;
/**
* Given a completion item fill in more data, like [doc-comment](#CompletionItem.documentation)
* or [details](#CompletionItem.detail).
*
* The editor will only resolve a completion item once.
*
* @param item A completion item currently active in the UI.
* @param token A cancellation token.
* @return The resolved completion item or a thenable that resolves to of such. It is OK to return the given
* `item`. When no result is returned, the given `item` will be used.
*/
resolveCompletionItem?(item: CompletionItem, token: CancellationToken): ProviderResult<CompletionItem>;
}
/**
* A document link is a range in a text document that links to an internal or external resource, like another
* text document or a web site.
*/
export class DocumentLink {
/**
* The range this link applies to.
*/
range: Range;
/**
* The uri this link points to.
*/
target?: Uri;
/**
* Creates a new document link.
*
* @param range The range the document link applies to. Must not be empty.
* @param target The uri the document link points to.
*/
constructor(range: Range, target?: Uri);
}
/**
* The document link provider defines the contract between extensions and feature of showing
* links in the editor.
*/
export interface DocumentLinkProvider {
/**
* Provide links for the given document. Note that the editor ships with a default provider that detects
* `http(s)` and `file` links.
*
* @param document The document in which the command was invoked.
* @param token A cancellation token.
* @return An array of [document links](#DocumentLink) or a thenable that resolves to such. The lack of a result
* can be signaled by returning `undefined`, `null`, or an empty array.
*/
provideDocumentLinks(document: TextDocument, token: CancellationToken): ProviderResult<DocumentLink[]>;
/**
* Given a link fill in its [target](#DocumentLink.target). This method is called when an incomplete
* link is selected in the UI. Providers can implement this method and return incomplete links
* (without target) from the [`provideDocumentLinks`](#DocumentLinkProvider.provideDocumentLinks) method which
* often helps to improve performance.
*
* @param link The link that is to be resolved.
* @param token A cancellation token.
*/
resolveDocumentLink?(link: DocumentLink, token: CancellationToken): ProviderResult<DocumentLink>;
}
/**
* Represents a color in RGBA space.
*/
export class Color {
/**
* The red component of this color in the range [0-1].
*/
readonly red: number;
/**
* The green component of this color in the range [0-1].
*/
readonly green: number;
/**
* The blue component of this color in the range [0-1].
*/
readonly blue: number;
/**
* The alpha component of this color in the range [0-1].
*/
readonly alpha: number;
/**
* Creates a new color instance.
*
* @param red The red component.
* @param green The green component.
* @param blue The blue component.
* @param alpha The alpha component.
*/
constructor(red: number, green: number, blue: number, alpha: number);
}
/**
* Represents a color range from a document.
*/
export class ColorInformation {
/**
* The range in the document where this color appears.
*/
range: Range;
/**
* The actual color value for this color range.
*/
color: Color;
/**
* Creates a new color range.
*
* @param range The range the color appears in. Must not be empty.
* @param color The value of the color.
* @param format The format in which this color is currently formatted.
*/
constructor(range: Range, color: Color);
}
/**
* A color presentation object describes how a [`color`](#Color) should be represented as text and what
* edits are required to refer to it from source code.
*
* For some languages one color can have multiple presentations, e.g. css can represent the color red with
* the constant `Red`, the hex-value `#ff0000`, or in rgba and hsla forms. In csharp other representations
* apply, e.g `System.Drawing.Color.Red`.
*/
export class ColorPresentation {
/**
* The label of this color presentation. It will be shown on the color
* picker header. By default this is also the text that is inserted when selecting
* this color presentation.
*/
label: string;
/**
* An [edit](#TextEdit) which is applied to a document when selecting
* this presentation for the color. When `falsy` the [label](#ColorPresentation.label)
* is used.
*/
textEdit?: TextEdit;
/**
* An optional array of additional [text edits](#TextEdit) that are applied when
* selecting this color presentation. Edits must not overlap with the main [edit](#ColorPresentation.textEdit) nor with themselves.
*/
additionalTextEdits?: TextEdit[];
/**
* Creates a new color presentation.
*
* @param label The label of this color presentation.
*/
constructor(label: string);
}
/**
* The document color provider defines the contract between extensions and feature of
* picking and modifying colors in the editor.
*/
export interface DocumentColorProvider {
/**
* Provide colors for the given document.
*
* @param document The document in which the command was invoked.
* @param token A cancellation token.
* @return An array of [color information](#ColorInformation) or a thenable that resolves to such. The lack of a result
* can be signaled by returning `undefined`, `null`, or an empty array.
*/
provideDocumentColors(document: TextDocument, token: CancellationToken): ProviderResult<ColorInformation[]>;
/**
* Provide [representations](#ColorPresentation) for a color.
*
* @param color The color to show and insert.
* @param context A context object with additional information
* @param token A cancellation token.
* @return An array of color presentations or a thenable that resolves to such. The lack of a result
* can be signaled by returning `undefined`, `null`, or an empty array.
*/
provideColorPresentations(color: Color, context: { document: TextDocument, range: Range }, token: CancellationToken): ProviderResult<ColorPresentation[]>;
}
/**
* A line based folding range. To be valid, start and end line must a zero or larger and smaller than the number of lines in the document.
* Invalid ranges will be ignored.
*/
export class FoldingRange {
/**
* The zero-based start line of the range to fold. The folded area starts after the line's last character.
* To be valid, the end must be zero or larger and smaller than the number of lines in the document.
*/
start: number;
/**
* The zero-based end line of the range to fold. The folded area ends with the line's last character.
* To be valid, the end must be zero or larger and smaller than the number of lines in the document.
*/
end: number;
/**
* Describes the [Kind](#FoldingRangeKind) of the folding range such as [Comment](#FoldingRangeKind.Comment) or
* [Region](#FoldingRangeKind.Region). The kind is used to categorize folding ranges and used by commands
* like 'Fold all comments'. See
* [FoldingRangeKind](#FoldingRangeKind) for an enumeration of all kinds.
* If not set, the range is originated from a syntax element.
*/
kind?: FoldingRangeKind;
/**
* Creates a new folding range.
*
* @param start The start line of the folded range.
* @param end The end line of the folded range.
* @param kind The kind of the folding range.
*/
constructor(start: number, end: number, kind?: FoldingRangeKind);
}
/**
* An enumeration of specific folding range kinds. The kind is an optional field of a [FoldingRange](#FoldingRange)
* and is used to distinguish specific folding ranges such as ranges originated from comments. The kind is used by commands like
* `Fold all comments` or `Fold all regions`.
* If the kind is not set on the range, the range originated from a syntax element other than comments, imports or region markers.
*/
export enum FoldingRangeKind {
/**
* Kind for folding range representing a comment.
*/
Comment = 1,
/**
* Kind for folding range representing a import.
*/
Imports = 2,
/**
* Kind for folding range representing regions originating from folding markers like `#region` and `#endregion`.
*/
Region = 3
}
/**
* Folding context (for future use)
*/
export interface FoldingContext {
}
/**
* The folding range provider interface defines the contract between extensions and
* [Folding](https://code.visualstudio.com/docs/editor/codebasics#_folding) in the editor.
*/
export interface FoldingRangeProvider {
/**
* Returns a list of folding ranges or null and undefined if the provider
* does not want to participate or was cancelled.
* @param document The document in which the command was invoked.
* @param context Additional context information (for future use)
* @param token A cancellation token.
*/
provideFoldingRanges(document: TextDocument, context: FoldingContext, token: CancellationToken): ProviderResult<FoldingRange[]>;
}
/**
* A tuple of two characters, like a pair of
* opening and closing brackets.
*/
export type CharacterPair = [string, string];
/**
* Describes how comments for a language work.
*/
export interface CommentRule {
/**
* The line comment token, like `// this is a comment`
*/
lineComment?: string;
/**
* The block comment character pair, like `/* block comment */`
*/
blockComment?: CharacterPair;
}
/**
* Describes indentation rules for a language.
*/
export interface IndentationRule {
/**
* If a line matches this pattern, then all the lines after it should be unindented once (until another rule matches).
*/
decreaseIndentPattern: RegExp;
/**
* If a line matches this pattern, then all the lines after it should be indented once (until another rule matches).
*/
increaseIndentPattern: RegExp;
/**
* If a line matches this pattern, then **only the next line** after it should be indented once.
*/
indentNextLinePattern?: RegExp;
/**
* If a line matches this pattern, then its indentation should not be changed and it should not be evaluated against the other rules.
*/
unIndentedLinePattern?: RegExp;
}
/**
* Describes what to do with the indentation when pressing Enter.
*/
export enum IndentAction {
/**
* Insert new line and copy the previous line's indentation.
*/
None = 0,
/**
* Insert new line and indent once (relative to the previous line's indentation).
*/
Indent = 1,
/**
* Insert two new lines:
* - the first one indented which will hold the cursor
* - the second one at the same indentation level
*/
IndentOutdent = 2,
/**
* Insert new line and outdent once (relative to the previous line's indentation).
*/
Outdent = 3
}
/**
* Describes what to do when pressing Enter.
*/
export interface EnterAction {
/**
* Describe what to do with the indentation.
*/
indentAction: IndentAction;
/**
* Describes text to be appended after the new line and after the indentation.
*/
appendText?: string;
/**
* Describes the number of characters to remove from the new line's indentation.
*/
removeText?: number;
}
/**
* Describes a rule to be evaluated when pressing Enter.
*/
export interface OnEnterRule {
/**
* This rule will only execute if the text before the cursor matches this regular expression.
*/
beforeText: RegExp;
/**
* This rule will only execute if the text after the cursor matches this regular expression.
*/
afterText?: RegExp;
/**
* The action to execute.
*/
action: EnterAction;
}
/**
* The language configuration interfaces defines the contract between extensions
* and various editor features, like automatic bracket insertion, automatic indentation etc.
*/
export interface LanguageConfiguration {
/**
* The language's comment settings.
*/
comments?: CommentRule;
/**
* The language's brackets.
* This configuration implicitly affects pressing Enter around these brackets.
*/
brackets?: CharacterPair[];
/**
* The language's word definition.
* If the language supports Unicode identifiers (e.g. JavaScript), it is preferable
* to provide a word definition that uses exclusion of known separators.
* e.g.: A regex that matches anything except known separators (and dot is allowed to occur in a floating point number):
* /(-?\d*\.\d\w*)|([^\`\~\!\@\#\%\^\&\*\(\)\-\=\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g
*/
wordPattern?: RegExp;
/**
* The language's indentation settings.
*/
indentationRules?: IndentationRule;
/**
* The language's rules to be evaluated when pressing Enter.
*/
onEnterRules?: OnEnterRule[];
/**
* **Deprecated** Do not use.
*
* @deprecated Will be replaced by a better API soon.
*/
__electricCharacterSupport?: {
/**
* This property is deprecated and will be **ignored** from
* the editor.
* @deprecated
*/
brackets?: any;
/**
* This property is deprecated and not fully supported anymore by
* the editor (scope and lineStart are ignored).
* Use the autoClosingPairs property in the language configuration file instead.
* @deprecated
*/
docComment?: {
scope: string;
open: string;
lineStart: string;
close?: string;
};
};
/**
* **Deprecated** Do not use.
*
* @deprecated * Use the autoClosingPairs property in the language configuration file instead.
*/
__characterPairSupport?: {
autoClosingPairs: {
open: string;
close: string;
notIn?: string[];
}[];
};
}
/**
* The configuration target
*/
export enum ConfigurationTarget {
/**
* Global configuration
*/
Global = 1,
/**
* Workspace configuration
*/
Workspace = 2,
/**
* Workspace folder configuration
*/
WorkspaceFolder = 3
}
/**
* Represents the configuration. It is a merged view of
*
* - Default configuration
* - Global configuration
* - Workspace configuration (if available)
* - Workspace folder configuration of the requested resource (if available)
*
* *Global configuration* comes from User Settings and shadows Defaults.
*
* *Workspace configuration* comes from Workspace Settings and shadows Global configuration.
*
* *Workspace Folder configuration* comes from `.vscode` folder under one of the [workspace folders](#workspace.workspaceFolders).
*
* *Note:* Workspace and Workspace Folder configurations contains `launch` and `tasks` settings. Their basename will be
* part of the section identifier. The following snippets shows how to retrieve all configurations
* from `launch.json`:
*
* ```ts
* // launch.json configuration
* const config = workspace.getConfiguration('launch', vscode.window.activeTextEditor.document.uri);
*
* // retrieve values
* const values = config.get('configurations');
* ```
*
* Refer to [Settings](https://code.visualstudio.com/docs/getstarted/settings) for more information.
*/
export interface WorkspaceConfiguration {
/**
* Return a value from this configuration.
*
* @param section Configuration name, supports _dotted_ names.
* @return The value `section` denotes or `undefined`.
*/
get<T>(section: string): T | undefined;
/**
* Return a value from this configuration.
*
* @param section Configuration name, supports _dotted_ names.
* @param defaultValue A value should be returned when no value could be found, is `undefined`.
* @return The value `section` denotes or the default.
*/
get<T>(section: string, defaultValue: T): T;
/**
* Check if this configuration has a certain value.
*
* @param section Configuration name, supports _dotted_ names.
* @return `true` if the section doesn't resolve to `undefined`.
*/
has(section: string): boolean;
/**
* Retrieve all information about a configuration setting. A configuration value
* often consists of a *default* value, a global or installation-wide value,
* a workspace-specific value and a folder-specific value.
*
* The *effective* value (returned by [`get`](#WorkspaceConfiguration.get))
* is computed like this: `defaultValue` overwritten by `globalValue`,
* `globalValue` overwritten by `workspaceValue`. `workspaceValue` overwritten by `workspaceFolderValue`.
* Refer to [Settings Inheritance](https://code.visualstudio.com/docs/getstarted/settings)
* for more information.
*
* *Note:* The configuration name must denote a leaf in the configuration tree
* (`editor.fontSize` vs `editor`) otherwise no result is returned.
*
* @param section Configuration name, supports _dotted_ names.
* @return Information about a configuration setting or `undefined`.
*/
inspect<T>(section: string): { key: string; defaultValue?: T; globalValue?: T; workspaceValue?: T, workspaceFolderValue?: T } | undefined;
/**
* Update a configuration value. The updated configuration values are persisted.
*
* A value can be changed in
*
* - [Global configuration](#ConfigurationTarget.Global): Changes the value for all instances of the editor.
* - [Workspace configuration](#ConfigurationTarget.Workspace): Changes the value for current workspace, if available.
* - [Workspace folder configuration](#ConfigurationTarget.WorkspaceFolder): Changes the value for the
* [Workspace folder](#workspace.workspaceFolders) to which the current [configuration](#WorkspaceConfiguration) is scoped to.
*
* *Note 1:* Setting a global value in the presence of a more specific workspace value
* has no observable effect in that workspace, but in others. Setting a workspace value
* in the presence of a more specific folder value has no observable effect for the resources
* under respective [folder](#workspace.workspaceFolders), but in others. Refer to
* [Settings Inheritance](https://code.visualstudio.com/docs/getstarted/settings) for more information.
*
* *Note 2:* To remove a configuration value use `undefined`, like so: `config.update('somekey', undefined)`
*
* Will throw error when
* - Writing a configuration which is not registered.
* - Writing a configuration to workspace or folder target when no workspace is opened
* - Writing a configuration to folder target when there is no folder settings
* - Writing to folder target without passing a resource when getting the configuration (`workspace.getConfiguration(section, resource)`)
* - Writing a window configuration to folder target
*
* @param section Configuration name, supports _dotted_ names.
* @param value The new value.
* @param configurationTarget The [configuration target](#ConfigurationTarget) or a boolean value.
* - If `true` configuration target is `ConfigurationTarget.Global`.
* - If `false` configuration target is `ConfigurationTarget.Workspace`.
* - If `undefined` or `null` configuration target is
* `ConfigurationTarget.WorkspaceFolder` when configuration is resource specific
* `ConfigurationTarget.Workspace` otherwise.
*/
update(section: string, value: any, configurationTarget?: ConfigurationTarget | boolean): Thenable<void>;
/**
* Readable dictionary that backs this configuration.
*/
readonly [key: string]: any;
}
/**
* Represents a location inside a resource, such as a line
* inside a text file.
*/
export class Location {
/**
* The resource identifier of this location.
*/
uri: Uri;
/**
* The document range of this location.
*/
range: Range;
/**
* Creates a new location object.
*
* @param uri The resource identifier.
* @param rangeOrPosition The range or position. Positions will be converted to an empty range.
*/
constructor(uri: Uri, rangeOrPosition: Range | Position);
}
/**
* Represents the connection of two locations. Provides additional metadata over normal [locations](#Location),
* including an origin range.
*/
export interface LocationLink {
/**
* Span of the origin of this link.
*
* Used as the underlined span for mouse definition hover. Defaults to the word range at
* the definition position.
*/
originSelectionRange?: Range;
/**
* The target resource identifier of this link.
*/
targetUri: Uri;
/**
* The full target range of this link.
*/
targetRange: Range;
/**
* The span of this link.
*/
targetSelectionRange?: Range;
}
/**
* The event that is fired when diagnostics change.
*/
export interface DiagnosticChangeEvent {
/**
* An array of resources for which diagnostics have changed.
*/
readonly uris: Uri[];
}
/**
* Represents the severity of diagnostics.
*/
export enum DiagnosticSeverity {
/**
* Something not allowed by the rules of a language or other means.
*/
Error = 0,
/**
* Something suspicious but allowed.
*/
Warning = 1,
/**
* Something to inform about but not a problem.
*/
Information = 2,
/**
* Something to hint to a better way of doing it, like proposing
* a refactoring.
*/
Hint = 3
}
/**
* Represents a related message and source code location for a diagnostic. This should be
* used to point to code locations that cause or related to a diagnostics, e.g when duplicating
* a symbol in a scope.
*/
export class DiagnosticRelatedInformation {
/**
* The location of this related diagnostic information.
*/
location: Location;
/**
* The message of this related diagnostic information.
*/
message: string;
/**
* Creates a new related diagnostic information object.
*
* @param location The location.
* @param message The message.
*/
constructor(location: Location, message: string);
}
/**
* Additional metadata about the type of a diagnostic.
*/
export enum DiagnosticTag {
/**
* Unused or unnecessary code.
*
* Diagnostics with this tag are rendered faded out. The amount of fading
* is controlled by the `"editorUnnecessaryCode.opacity"` theme color. For
* example, `"editorUnnecessaryCode.opacity": "#000000c0"` will render the
* code with 75% opacity. For high contrast themes, use the
* `"editorUnnecessaryCode.border"` theme color to underline unnecessary code
* instead of fading it out.
*/
Unnecessary = 1,
}
/**
* Represents a diagnostic, such as a compiler error or warning. Diagnostic objects
* are only valid in the scope of a file.
*/
export class Diagnostic {
/**
* The range to which this diagnostic applies.
*/
range: Range;
/**
* The human-readable message.
*/
message: string;
/**
* The severity, default is [error](#DiagnosticSeverity.Error).
*/
severity: DiagnosticSeverity;
/**
* A human-readable string describing the source of this
* diagnostic, e.g. 'typescript' or 'super lint'.
*/
source?: string;
/**
* A code or identifier for this diagnostic.
* Should be used for later processing, e.g. when providing [code actions](#CodeActionContext).
*/
code?: string | number;
/**
* An array of related diagnostic information, e.g. when symbol-names within
* a scope collide all definitions can be marked via this property.
*/
relatedInformation?: DiagnosticRelatedInformation[];
/**
* Additional metadata about the diagnostic.
*/
tags?: DiagnosticTag[];
/**
* Creates a new diagnostic object.
*
* @param range The range to which this diagnostic applies.
* @param message The human-readable message.
* @param severity The severity, default is [error](#DiagnosticSeverity.Error).
*/
constructor(range: Range, message: string, severity?: DiagnosticSeverity);
}
/**
* A diagnostics collection is a container that manages a set of
* [diagnostics](#Diagnostic). Diagnostics are always scopes to a
* diagnostics collection and a resource.
*
* To get an instance of a `DiagnosticCollection` use
* [createDiagnosticCollection](#languages.createDiagnosticCollection).
*/
export interface DiagnosticCollection {
/**
* The name of this diagnostic collection, for instance `typescript`. Every diagnostic
* from this collection will be associated with this name. Also, the task framework uses this
* name when defining [problem matchers](https://code.visualstudio.com/docs/editor/tasks#_defining-a-problem-matcher).
*/
readonly name: string;
/**
* Assign diagnostics for given resource. Will replace
* existing diagnostics for that resource.
*
* @param uri A resource identifier.
* @param diagnostics Array of diagnostics or `undefined`
*/
set(uri: Uri, diagnostics: Diagnostic[] | undefined): void;
/**
* Replace all entries in this collection.
*
* Diagnostics of multiple tuples of the same uri will be merged, e.g
* `[[file1, [d1]], [file1, [d2]]]` is equivalent to `[[file1, [d1, d2]]]`.
* If a diagnostics item is `undefined` as in `[file1, undefined]`
* all previous but not subsequent diagnostics are removed.
*
* @param entries An array of tuples, like `[[file1, [d1, d2]], [file2, [d3, d4, d5]]]`, or `undefined`.
*/
set(entries: [Uri, Diagnostic[] | undefined][]): void;
/**
* Remove all diagnostics from this collection that belong
* to the provided `uri`. The same as `#set(uri, undefined)`.
*
* @param uri A resource identifier.
*/
delete(uri: Uri): void;
/**
* Remove all diagnostics from this collection. The same
* as calling `#set(undefined)`;
*/
clear(): void;
/**
* Iterate over each entry in this collection.
*
* @param callback Function to execute for each entry.
* @param thisArg The `this` context used when invoking the handler function.
*/
forEach(callback: (uri: Uri, diagnostics: Diagnostic[], collection: DiagnosticCollection) => any, thisArg?: any): void;
/**
* Get the diagnostics for a given resource. *Note* that you cannot
* modify the diagnostics-array returned from this call.
*
* @param uri A resource identifier.
* @returns An immutable array of [diagnostics](#Diagnostic) or `undefined`.
*/
get(uri: Uri): Diagnostic[] | undefined;
/**
* Check if this collection contains diagnostics for a
* given resource.
*
* @param uri A resource identifier.
* @returns `true` if this collection has diagnostic for the given resource.
*/
has(uri: Uri): boolean;
/**
* Dispose and free associated resources. Calls
* [clear](#DiagnosticCollection.clear).
*/
dispose(): void;
}
/**
* Denotes a location of an editor in the window. Editors can be arranged in a grid
* and each column represents one editor location in that grid by counting the editors
* in order of their appearance.
*/
export enum ViewColumn {
/**
* A *symbolic* editor column representing the currently active column. This value
* can be used when opening editors, but the *resolved* [viewColumn](#TextEditor.viewColumn)-value
* of editors will always be `One`, `Two`, `Three`,... or `undefined` but never `Active`.
*/
Active = -1,
/**
* A *symbolic* editor column representing the column to the side of the active one. This value
* can be used when opening editors, but the *resolved* [viewColumn](#TextEditor.viewColumn)-value
* of editors will always be `One`, `Two`, `Three`,... or `undefined` but never `Beside`.
*/
Beside = -2,
/**
* The first editor column.
*/
One = 1,
/**
* The second editor column.
*/
Two = 2,
/**
* The third editor column.
*/
Three = 3,
/**
* The fourth editor column.
*/
Four = 4,
/**
* The fifth editor column.
*/
Five = 5,
/**
* The sixth editor column.
*/
Six = 6,
/**
* The seventh editor column.
*/
Seven = 7,
/**
* The eighth editor column.
*/
Eight = 8,
/**
* The ninth editor column.
*/
Nine = 9
}
/**
* An output channel is a container for readonly textual information.
*
* To get an instance of an `OutputChannel` use
* [createOutputChannel](#window.createOutputChannel).
*/
export interface OutputChannel {
/**
* The human-readable name of this output channel.
*/
readonly name: string;
/**
* Append the given value to the channel.
*
* @param value A string, falsy values will not be printed.
*/
append(value: string): void;
/**
* Append the given value and a line feed character
* to the channel.
*
* @param value A string, falsy values will be printed.
*/
appendLine(value: string): void;
/**
* Removes all output from the channel.
*/
clear(): void;
/**
* Reveal this channel in the UI.
*
* @param preserveFocus When `true` the channel will not take focus.
*/
show(preserveFocus?: boolean): void;
/**
* ~~Reveal this channel in the UI.~~
*
* @deprecated Use the overload with just one parameter (`show(preserveFocus?: boolean): void`).
*
* @param column This argument is **deprecated** and will be ignored.
* @param preserveFocus When `true` the channel will not take focus.
*/
show(column?: ViewColumn, preserveFocus?: boolean): void;
/**
* Hide this channel from the UI.
*/
hide(): void;
/**
* Dispose and free associated resources.
*/
dispose(): void;
}
/**
* Represents the alignment of status bar items.
*/
export enum StatusBarAlignment {
/**
* Aligned to the left side.
*/
Left = 1,
/**
* Aligned to the right side.
*/
Right = 2
}
/**
* A status bar item is a status bar contribution that can
* show text and icons and run a command on click.
*/
export interface StatusBarItem {
/**
* The alignment of this item.
*/
readonly alignment: StatusBarAlignment;
/**
* The priority of this item. Higher value means the item should
* be shown more to the left.
*/
readonly priority: number;
/**
* The text to show for the entry. You can embed icons in the text by leveraging the syntax:
*
* `My text $(icon-name) contains icons like $(icon-name) this one.`
*
* Where the icon-name is taken from the [octicon](https://octicons.github.com) icon set, e.g.
* `light-bulb`, `thumbsup`, `zap` etc.
*/
text: string;
/**
* The tooltip text when you hover over this entry.
*/
tooltip: string | undefined;
/**
* The foreground color for this entry.
*/
color: string | ThemeColor | undefined;
/**
* The identifier of a command to run on click. The command must be
* [known](#commands.getCommands).
*/
command: string | undefined;
/**
* Shows the entry in the status bar.
*/
show(): void;
/**
* Hide the entry in the status bar.
*/
hide(): void;
/**
* Dispose and free associated resources. Call
* [hide](#StatusBarItem.hide).
*/
dispose(): void;
}
/**
* Defines a generalized way of reporting progress updates.
*/
export interface Progress<T> {
/**
* Report a progress update.
* @param value A progress item, like a message and/or an
* report on how much work finished
*/
report(value: T): void;
}
/**
* An individual terminal instance within the integrated terminal.
*/
export interface Terminal {
/**
* The name of the terminal.
*/
readonly name: string;
/**
* The process ID of the shell process.
*/
readonly processId: Thenable<number>;
/**
* Send text to the terminal. The text is written to the stdin of the underlying pty process
* (shell) of the terminal.
*
* @param text The text to send.
* @param addNewLine Whether to add a new line to the text being sent, this is normally
* required to run a command in the terminal. The character(s) added are \n or \r\n
* depending on the platform. This defaults to `true`.
*/
sendText(text: string, addNewLine?: boolean): void;
/**
* Show the terminal panel and reveal this terminal in the UI.
*
* @param preserveFocus When `true` the terminal will not take focus.
*/
show(preserveFocus?: boolean): void;
/**
* Hide the terminal panel if this terminal is currently showing.
*/
hide(): void;
/**
* Dispose and free associated resources.
*/
dispose(): void;
}
/**
* Represents an extension.
*
* To get an instance of an `Extension` use [getExtension](#extensions.getExtension).
*/
export interface Extension<T> {
/**
* The canonical extension identifier in the form of: `publisher.name`.
*/
readonly id: string;
/**
* The absolute file path of the directory containing this extension.
*/
readonly extensionPath: string;
/**
* `true` if the extension has been activated.
*/
readonly isActive: boolean;
/**
* The parsed contents of the extension's package.json.
*/
readonly packageJSON: any;
/**
* The public API exported by this extension. It is an invalid action
* to access this field before this extension has been activated.
*/
readonly exports: T;
/**
* Activates this extension and returns its public API.
*
* @return A promise that will resolve when this extension has been activated.
*/
activate(): Thenable<T>;
}
/**
* An extension context is a collection of utilities private to an
* extension.
*
* An instance of an `ExtensionContext` is provided as the first
* parameter to the `activate`-call of an extension.
*/
export interface ExtensionContext {
/**
* An array to which disposables can be added. When this
* extension is deactivated the disposables will be disposed.
*/
subscriptions: { dispose(): any }[];
/**
* A memento object that stores state in the context
* of the currently opened [workspace](#workspace.workspaceFolders).
*/
workspaceState: Memento;
/**
* A memento object that stores state independent
* of the current opened [workspace](#workspace.workspaceFolders).
*/
globalState: Memento;
/**
* The absolute file path of the directory containing the extension.
*/
extensionPath: string;
/**
* Get the absolute path of a resource contained in the extension.
*
* @param relativePath A relative path to a resource contained in the extension.
* @return The absolute path of the resource.
*/
asAbsolutePath(relativePath: string): string;
/**
* An absolute file path of a workspace specific directory in which the extension
* can store private state. The directory might not exist on disk and creation is
* up to the extension. However, the parent directory is guaranteed to be existent.
*
* Use [`workspaceState`](#ExtensionContext.workspaceState) or
* [`globalState`](#ExtensionContext.globalState) to store key value data.
*/
storagePath: string | undefined;
/**
* An absolute file path of a directory in which the extension can create log files.
* The directory might not exist on disk and creation is up to the extension. However,
* the parent directory is guaranteed to be existent.
*/
logPath: string;
}
/**
* A memento represents a storage utility. It can store and retrieve
* values.
*/
export interface Memento {
/**
* Return a value.
*
* @param key A string.
* @return The stored value or `undefined`.
*/
get<T>(key: string): T | undefined;
/**
* Return a value.
*
* @param key A string.
* @param defaultValue A value that should be returned when there is no
* value (`undefined`) with the given key.
* @return The stored value or the defaultValue.
*/
get<T>(key: string, defaultValue: T): T;
/**
* Store a value. The value must be JSON-stringifyable.
*
* @param key A string.
* @param value A value. MUST not contain cyclic references.
*/
update(key: string, value: any): Thenable<void>;
}
/**
* Controls the behaviour of the terminal's visibility.
*/
export enum TaskRevealKind {
/**
* Always brings the terminal to front if the task is executed.
*/
Always = 1,
/**
* Only brings the terminal to front if a problem is detected executing the task
* (e.g. the task couldn't be started because).
*/
Silent = 2,
/**
* The terminal never comes to front when the task is executed.
*/
Never = 3
}
/**
* Controls how the task channel is used between tasks
*/
export enum TaskPanelKind {
/**
* Shares a panel with other tasks. This is the default.
*/
Shared = 1,
/**
* Uses a dedicated panel for this tasks. The panel is not
* shared with other tasks.
*/
Dedicated = 2,
/**
* Creates a new panel whenever this task is executed.
*/
New = 3
}
/**
* Controls how the task is presented in the UI.
*/
export interface TaskPresentationOptions {
/**
* Controls whether the task output is reveal in the user interface.
* Defaults to `RevealKind.Always`.
*/
reveal?: TaskRevealKind;
/**
* Controls whether the command associated with the task is echoed
* in the user interface.
*/
echo?: boolean;
/**
* Controls whether the panel showing the task output is taking focus.
*/
focus?: boolean;
/**
* Controls if the task panel is used for this task only (dedicated),
* shared between tasks (shared) or if a new panel is created on
* every task execution (new). Defaults to `TaskInstanceKind.Shared`
*/
panel?: TaskPanelKind;
/**
* Controls whether to show the "Terminal will be reused by tasks, press any key to close it" message.
*/
showReuseMessage?: boolean;
/**
* Controls whether the terminal is cleared before executing the task.
*/
clear?: boolean;
}
/**
* A grouping for tasks. The editor by default supports the
* 'Clean', 'Build', 'RebuildAll' and 'Test' group.
*/
export class TaskGroup {
/**
* The clean task group;
*/
static Clean: TaskGroup;
/**
* The build task group;
*/
static Build: TaskGroup;
/**
* The rebuild all task group;
*/
static Rebuild: TaskGroup;
/**
* The test all task group;
*/
static Test: TaskGroup;
private constructor(id: string, label: string);
}
/**
* A structure that defines a task kind in the system.
* The value must be JSON-stringifyable.
*/
export interface TaskDefinition {
/**
* The task definition describing the task provided by an extension.
* Usually a task provider defines more properties to identify
* a task. They need to be defined in the package.json of the
* extension under the 'taskDefinitions' extension point. The npm
* task definition for example looks like this
* ```typescript
* interface NpmTaskDefinition extends TaskDefinition {
* script: string;
* }
* ```
*
* Note that type identifier starting with a '$' are reserved for internal
* usages and shouldn't be used by extensions.
*/
readonly type: string;
/**
* Additional attributes of a concrete task definition.
*/
[name: string]: any;
}
/**
* Options for a process execution
*/
export interface ProcessExecutionOptions {
/**
* The current working directory of the executed program or shell.
* If omitted the tools current workspace root is used.
*/
cwd?: string;
/**
* The additional environment of the executed program or shell. If omitted
* the parent process' environment is used. If provided it is merged with
* the parent process' environment.
*/
env?: { [key: string]: string };
}
/**
* The execution of a task happens as an external process
* without shell interaction.
*/
export class ProcessExecution {
/**
* Creates a process execution.
*
* @param process The process to start.
* @param options Optional options for the started process.
*/
constructor(process: string, options?: ProcessExecutionOptions);
/**
* Creates a process execution.
*
* @param process The process to start.
* @param args Arguments to be passed to the process.
* @param options Optional options for the started process.
*/
constructor(process: string, args: string[], options?: ProcessExecutionOptions);
/**
* The process to be executed.
*/
process: string;
/**
* The arguments passed to the process. Defaults to an empty array.
*/
args: string[];
/**
* The process options used when the process is executed.
* Defaults to undefined.
*/
options?: ProcessExecutionOptions;
}
/**
* The shell quoting options.
*/
export interface ShellQuotingOptions {
/**
* The character used to do character escaping. If a string is provided only spaces
* are escaped. If a `{ escapeChar, charsToEscape }` literal is provide all characters
* in `charsToEscape` are escaped using the `escapeChar`.
*/
escape?: string | {
/**
* The escape character.
*/
escapeChar: string;
/**
* The characters to escape.
*/
charsToEscape: string;
};
/**
* The character used for strong quoting. The string's length must be 1.
*/
strong?: string;
/**
* The character used for weak quoting. The string's length must be 1.
*/
weak?: string;
}
/**
* Options for a shell execution
*/
export interface ShellExecutionOptions {
/**
* The shell executable.
*/
executable?: string;
/**
* The arguments to be passed to the shell executable used to run the task. Most shells
* require special arguments to execute a command. For example `bash` requires the `-c`
* argument to execute a command, `PowerShell` requires `-Command` and `cmd` requires both
* `/d` and `/c`.
*/
shellArgs?: string[];
/**
* The shell quotes supported by this shell.
*/
shellQuoting?: ShellQuotingOptions;
/**
* The current working directory of the executed shell.
* If omitted the tools current workspace root is used.
*/
cwd?: string;
/**
* The additional environment of the executed shell. If omitted
* the parent process' environment is used. If provided it is merged with
* the parent process' environment.
*/
env?: { [key: string]: string };
}
/**
* Defines how an argument should be quoted if it contains
* spaces or unsupported characters.
*/
export enum ShellQuoting {
/**
* Character escaping should be used. This for example
* uses \ on bash and ` on PowerShell.
*/
Escape = 1,
/**
* Strong string quoting should be used. This for example
* uses " for Windows cmd and ' for bash and PowerShell.
* Strong quoting treats arguments as literal strings.
* Under PowerShell echo 'The value is $(2 * 3)' will
* print `The value is $(2 * 3)`
*/
Strong = 2,
/**
* Weak string quoting should be used. This for example
* uses " for Windows cmd, bash and PowerShell. Weak quoting
* still performs some kind of evaluation inside the quoted
* string. Under PowerShell echo "The value is $(2 * 3)"
* will print `The value is 6`
*/
Weak = 3
}
/**
* A string that will be quoted depending on the used shell.
*/
export interface ShellQuotedString {
/**
* The actual string value.
*/
value: string;
/**
* The quoting style to use.
*/
quoting: ShellQuoting;
}
export class ShellExecution {
/**
* Creates a shell execution with a full command line.
*
* @param commandLine The command line to execute.
* @param options Optional options for the started the shell.
*/
constructor(commandLine: string, options?: ShellExecutionOptions);
/**
* Creates a shell execution with a command and arguments. For the real execution VS Code will
* construct a command line from the command and the arguments. This is subject to interpretation
* especially when it comes to quoting. If full control over the command line is needed please
* use the constructor that creates a `ShellExecution` with the full command line.
*
* @param command The command to execute.
* @param args The command arguments.
* @param options Optional options for the started the shell.
*/
constructor(command: string | ShellQuotedString, args: (string | ShellQuotedString)[], options?: ShellExecutionOptions);
/**
* The shell command line. Is `undefined` if created with a command and arguments.
*/
commandLine: string;
/**
* The shell command. Is `undefined` if created with a full command line.
*/
command: string | ShellQuotedString;
/**
* The shell args. Is `undefined` if created with a full command line.
*/
args: (string | ShellQuotedString)[];
/**
* The shell options used when the command line is executed in a shell.
* Defaults to undefined.
*/
options?: ShellExecutionOptions;
}
/**
* The scope of a task.
*/
export enum TaskScope {
/**
* The task is a global task
*/
Global = 1,
/**
* The task is a workspace task
*/
Workspace = 2
}
/**
* A task to execute
*/
export class Task {
/**
* Creates a new task.
*
* @param definition The task definition as defined in the taskDefinitions extension point.
* @param scope Specifies the task's scope. It is either a global or a workspace task or a task for a specific workspace folder.
* @param name The task's name. Is presented in the user interface.
* @param source The task's source (e.g. 'gulp', 'npm', ...). Is presented in the user interface.
* @param execution The process or shell execution.
* @param problemMatchers the names of problem matchers to use, like '$tsc'
* or '$eslint'. Problem matchers can be contributed by an extension using
* the `problemMatchers` extension point.
*/
constructor(taskDefinition: TaskDefinition, scope: WorkspaceFolder | TaskScope.Global | TaskScope.Workspace, name: string, source: string, execution?: ProcessExecution | ShellExecution, problemMatchers?: string | string[]);
/**
* ~~Creates a new task.~~
*
* @deprecated Use the new constructors that allow specifying a scope for the task.
*
* @param definition The task definition as defined in the taskDefinitions extension point.
* @param name The task's name. Is presented in the user interface.
* @param source The task's source (e.g. 'gulp', 'npm', ...). Is presented in the user interface.
* @param execution The process or shell execution.
* @param problemMatchers the names of problem matchers to use, like '$tsc'
* or '$eslint'. Problem matchers can be contributed by an extension using
* the `problemMatchers` extension point.
*/
constructor(taskDefinition: TaskDefinition, name: string, source: string, execution?: ProcessExecution | ShellExecution, problemMatchers?: string | string[]);
/**
* The task's definition.
*/
definition: TaskDefinition;
/**
* The task's scope.
*/
readonly scope?: TaskScope.Global | TaskScope.Workspace | WorkspaceFolder;
/**
* The task's name
*/
name: string;
/**
* The task's execution engine
*/
execution?: ProcessExecution | ShellExecution;
/**
* Whether the task is a background task or not.
*/
isBackground: boolean;
/**
* A human-readable string describing the source of this
* shell task, e.g. 'gulp' or 'npm'.
*/
source: string;
/**
* The task group this tasks belongs to. See TaskGroup
* for a predefined set of available groups.
* Defaults to undefined meaning that the task doesn't
* belong to any special group.
*/
group?: TaskGroup;
/**
* The presentation options. Defaults to an empty literal.
*/
presentationOptions: TaskPresentationOptions;
/**
* The problem matchers attached to the task. Defaults to an empty
* array.
*/
problemMatchers: string[];
}
/**
* A task provider allows to add tasks to the task service.
* A task provider is registered via #tasks.registerTaskProvider.
*/
export interface TaskProvider {
/**
* Provides tasks.
* @param token A cancellation token.
* @return an array of tasks
*/
provideTasks(token?: CancellationToken): ProviderResult<Task[]>;
/**
* Resolves a task that has no [`execution`](#Task.execution) set. Tasks are
* often created from information found in the `tasks.json`-file. Such tasks miss
* the information on how to execute them and a task provider must fill in
* the missing information in the `resolveTask`-method. This method will not be
* called for tasks returned from the above `provideTasks` method since those
* tasks are always fully resolved. A valid default implementation for the
* `resolveTask` method is to return `undefined`.
*
* @param task The task to resolve.
* @param token A cancellation token.
* @return The resolved task
*/
resolveTask(task: Task, token?: CancellationToken): ProviderResult<Task>;
}
/**
* An object representing an executed Task. It can be used
* to terminate a task.
*
* This interface is not intended to be implemented.
*/
export interface TaskExecution {
/**
* The task that got started.
*/
task: Task;
/**
* Terminates the task execution.
*/
terminate(): void;
}
/**
* An event signaling the start of a task execution.
*
* This interface is not intended to be implemented.
*/
interface TaskStartEvent {
/**
* The task item representing the task that got started.
*/
execution: TaskExecution;
}
/**
* An event signaling the end of an executed task.
*
* This interface is not intended to be implemented.
*/
interface TaskEndEvent {
/**
* The task item representing the task that finished.
*/
execution: TaskExecution;
}
/**
* An event signaling the start of a process execution
* triggered through a task
*/
export interface TaskProcessStartEvent {
/**
* The task execution for which the process got started.
*/
execution: TaskExecution;
/**
* The underlying process id.
*/
processId: number;
}
/**
* An event signaling the end of a process execution
* triggered through a task
*/
export interface TaskProcessEndEvent {
/**
* The task execution for which the process got started.
*/
execution: TaskExecution;
/**
* The process's exit code.
*/
exitCode: number;
}
export interface TaskFilter {
/**
* The task version as used in the tasks.json file.
* The string support the package.json semver notation.
*/
version?: string;
/**
* The task type to return;
*/
type?: string;
}
/**
* Namespace for tasks functionality.
*/
export namespace tasks {
/**
* Register a task provider.
*
* @param type The task kind type this provider is registered for.
* @param provider A task provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerTaskProvider(type: string, provider: TaskProvider): Disposable;
/**
* Fetches all tasks available in the systems. This includes tasks
* from `tasks.json` files as well as tasks from task providers
* contributed through extensions.
*
* @param filter a filter to filter the return tasks.
*/
export function fetchTasks(filter?: TaskFilter): Thenable<Task[]>;
/**
* Executes a task that is managed by VS Code. The returned
* task execution can be used to terminate the task.
*
* @param task the task to execute
*/
export function executeTask(task: Task): Thenable<TaskExecution>;
/**
* The currently active task executions or an empty array.
*
* @readonly
*/
export let taskExecutions: ReadonlyArray<TaskExecution>;
/**
* Fires when a task starts.
*/
export const onDidStartTask: Event<TaskStartEvent>;
/**
* Fires when a task ends.
*/
export const onDidEndTask: Event<TaskEndEvent>;
/**
* Fires when the underlying process has been started.
* This event will not fire for tasks that don't
* execute an underlying process.
*/
export const onDidStartTaskProcess: Event<TaskProcessStartEvent>;
/**
* Fires when the underlying process has ended.
* This event will not fire for tasks that don't
* execute an underlying process.
*/
export const onDidEndTaskProcess: Event<TaskProcessEndEvent>;
}
/**
* Enumeration of file types. The types `File` and `Directory` can also be
* a symbolic links, in that use `FileType.File | FileType.SymbolicLink` and
* `FileType.Directory | FileType.SymbolicLink`.
*/
export enum FileType {
/**
* The file type is unknown.
*/
Unknown = 0,
/**
* A regular file.
*/
File = 1,
/**
* A directory.
*/
Directory = 2,
/**
* A symbolic link to a file.
*/
SymbolicLink = 64
}
/**
* The `FileStat`-type represents metadata about a file
*/
export interface FileStat {
/**
* The type of the file, e.g. is a regular file, a directory, or symbolic link
* to a file.
*/
type: FileType;
/**
* The creation timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC.
*/
ctime: number;
/**
* The modification timestamp in milliseconds elapsed since January 1, 1970 00:00:00 UTC.
*/
mtime: number;
/**
* The size in bytes.
*/
size: number;
}
/**
* A type that filesystem providers should use to signal errors.
*
* This class has factory methods for common error-cases, like `EntryNotFound` when
* a file or folder doesn't exist, use them like so: `throw vscode.FileSystemError.EntryNotFound(someUri);`
*/
export class FileSystemError extends Error {
/**
* Create an error to signal that a file or folder wasn't found.
* @param messageOrUri Message or uri.
*/
static FileNotFound(messageOrUri?: string | Uri): FileSystemError;
/**
* Create an error to signal that a file or folder already exists, e.g. when
* creating but not overwriting a file.
* @param messageOrUri Message or uri.
*/
static FileExists(messageOrUri?: string | Uri): FileSystemError;
/**
* Create an error to signal that a file is not a folder.
* @param messageOrUri Message or uri.
*/
static FileNotADirectory(messageOrUri?: string | Uri): FileSystemError;
/**
* Create an error to signal that a file is a folder.
* @param messageOrUri Message or uri.
*/
static FileIsADirectory(messageOrUri?: string | Uri): FileSystemError;
/**
* Create an error to signal that an operation lacks required permissions.
* @param messageOrUri Message or uri.
*/
static NoPermissions(messageOrUri?: string | Uri): FileSystemError;
/**
* Create an error to signal that the file system is unavailable or too busy to
* complete a request.
* @param messageOrUri Message or uri.
*/
static Unavailable(messageOrUri?: string | Uri): FileSystemError;
/**
* Creates a new filesystem error.
*
* @param messageOrUri Message or uri.
*/
constructor(messageOrUri?: string | Uri);
}
/**
* Enumeration of file change types.
*/
export enum FileChangeType {
/**
* The contents or metadata of a file have changed.
*/
Changed = 1,
/**
* A file has been created.
*/
Created = 2,
/**
* A file has been deleted.
*/
Deleted = 3,
}
/**
* The event filesystem providers must use to signal a file change.
*/
export interface FileChangeEvent {
/**
* The type of change.
*/
type: FileChangeType;
/**
* The uri of the file that has changed.
*/
uri: Uri;
}
/**
* The filesystem provider defines what the editor needs to read, write, discover,
* and to manage files and folders. It allows extensions to serve files from remote places,
* like ftp-servers, and to seamlessly integrate those into the editor.
*
* * *Note 1:* The filesystem provider API works with [uris](#Uri) and assumes hierarchical
* paths, e.g. `foo:/my/path` is a child of `foo:/my/` and a parent of `foo:/my/path/deeper`.
* * *Note 2:* There is an activation event `onFileSystem:<scheme>` that fires when a file
* or folder is being accessed.
* * *Note 3:* The word 'file' is often used to denote all [kinds](#FileType) of files, e.g.
* folders, symbolic links, and regular files.
*/
export interface FileSystemProvider {
/**
* An event to signal that a resource has been created, changed, or deleted. This
* event should fire for resources that are being [watched](#FileSystemProvider.watch)
* by clients of this provider.
*/
readonly onDidChangeFile: Event<FileChangeEvent[]>;
/**
* Subscribe to events in the file or folder denoted by `uri`.
*
* The editor will call this function for files and folders. In the latter case, the
* options differ from defaults, e.g. what files/folders to exclude from watching
* and if subfolders, sub-subfolder, etc. should be watched (`recursive`).
*
* @param uri The uri of the file to be watched.
* @param options Configures the watch.
* @returns A disposable that tells the provider to stop watching the `uri`.
*/
watch(uri: Uri, options: { recursive: boolean; excludes: string[] }): Disposable;
/**
* Retrieve metadata about a file.
*
* Note that the metadata for symbolic links should be the metadata of the file they refer to.
* Still, the [SymbolicLink](#FileType.SymbolicLink)-type must be used in addition to the actual type, e.g.
* `FileType.SymbolicLink | FileType.Directory`.
*
* @param uri The uri of the file to retrieve metadata about.
* @return The file metadata about the file.
* @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist.
*/
stat(uri: Uri): FileStat | Thenable<FileStat>;
/**
* Retrieve all entries of a [directory](#FileType.Directory).
*
* @param uri The uri of the folder.
* @return An array of name/type-tuples or a thenable that resolves to such.
* @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist.
*/
readDirectory(uri: Uri): [string, FileType][] | Thenable<[string, FileType][]>;
/**
* Create a new directory (Note, that new files are created via `write`-calls).
*
* @param uri The uri of the new folder.
* @throws [`FileNotFound`](#FileSystemError.FileNotFound) when the parent of `uri` doesn't exist, e.g. no mkdirp-logic required.
* @throws [`FileExists`](#FileSystemError.FileExists) when `uri` already exists.
* @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient.
*/
createDirectory(uri: Uri): void | Thenable<void>;
/**
* Read the entire contents of a file.
*
* @param uri The uri of the file.
* @return An array of bytes or a thenable that resolves to such.
* @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist.
*/
readFile(uri: Uri): Uint8Array | Thenable<Uint8Array>;
/**
* Write data to a file, replacing its entire contents.
*
* @param uri The uri of the file.
* @param content The new content of the file.
* @param options Defines if missing files should or must be created.
* @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist and `create` is not set.
* @throws [`FileNotFound`](#FileSystemError.FileNotFound) when the parent of `uri` doesn't exist and `create` is set, e.g. no mkdirp-logic required.
* @throws [`FileExists`](#FileSystemError.FileExists) when `uri` already exists, `create` is set but `overwrite` is not set.
* @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient.
*/
writeFile(uri: Uri, content: Uint8Array, options: { create: boolean, overwrite: boolean }): void | Thenable<void>;
/**
* Delete a file.
*
* @param uri The resource that is to be deleted.
* @param options Defines if deletion of folders is recursive.
* @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `uri` doesn't exist.
* @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient.
*/
delete(uri: Uri, options: { recursive: boolean }): void | Thenable<void>;
/**
* Rename a file or folder.
*
* @param oldUri The existing file.
* @param newUri The new location.
* @param options Defines if existing files should be overwritten.
* @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `oldUri` doesn't exist.
* @throws [`FileNotFound`](#FileSystemError.FileNotFound) when parent of `newUri` doesn't exist, e.g. no mkdirp-logic required.
* @throws [`FileExists`](#FileSystemError.FileExists) when `newUri` exists and when the `overwrite` option is not `true`.
* @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient.
*/
rename(oldUri: Uri, newUri: Uri, options: { overwrite: boolean }): void | Thenable<void>;
/**
* Copy files or folders. Implementing this function is optional but it will speedup
* the copy operation.
*
* @param source The existing file.
* @param destination The destination location.
* @param options Defines if existing files should be overwriten.
* @throws [`FileNotFound`](#FileSystemError.FileNotFound) when `source` doesn't exist.
* @throws [`FileNotFound`](#FileSystemError.FileNotFound) when parent of `destination` doesn't exist, e.g. no mkdirp-logic required.
* @throws [`FileExists`](#FileSystemError.FileExists) when `destination` exists and when the `overwrite` option is not `true`.
* @throws [`NoPermissions`](#FileSystemError.NoPermissions) when permissions aren't sufficient.
*/
copy?(source: Uri, destination: Uri, options: { overwrite: boolean }): void | Thenable<void>;
}
/**
* Content settings for a webview.
*/
export interface WebviewOptions {
/**
* Controls whether scripts are enabled in the webview content or not.
*
* Defaults to false (scripts-disabled).
*/
readonly enableScripts?: boolean;
/**
* Controls whether command uris are enabled in webview content or not.
*
* Defaults to false.
*/
readonly enableCommandUris?: boolean;
/**
* Root paths from which the webview can load local (filesystem) resources using the `vscode-resource:` scheme.
*
* Default to the root folders of the current workspace plus the extension's install directory.
*
* Pass in an empty array to disallow access to any local resources.
*/
readonly localResourceRoots?: ReadonlyArray<Uri>;
}
/**
* A webview displays html content, like an iframe.
*/
export interface Webview {
/**
* Content settings for the webview.
*/
options: WebviewOptions;
/**
* Contents of the webview.
*
* Should be a complete html document.
*/
html: string;
/**
* Fired when the webview content posts a message.<|fim▁hole|> * Post a message to the webview content.
*
* Messages are only delivered if the webview is visible.
*
* @param message Body of the message.
*/
postMessage(message: any): Thenable<boolean>;
}
/**
* Content settings for a webview panel.
*/
export interface WebviewPanelOptions {
/**
* Controls if the find widget is enabled in the panel.
*
* Defaults to false.
*/
readonly enableFindWidget?: boolean;
/**
* Controls if the webview panel's content (iframe) is kept around even when the panel
* is no longer visible.
*
* Normally the webview panel's html context is created when the panel becomes visible
* and destroyed when it is hidden. Extensions that have complex state
* or UI can set the `retainContextWhenHidden` to make VS Code keep the webview
* context around, even when the webview moves to a background tab. When a webview using
* `retainContextWhenHidden` becomes hidden, its scripts and other dynamic content are suspended.
* When the panel becomes visible again, the context is automatically restored
* in the exact same state it was in originally. You cannot send messages to a
* hidden webview, even with `retainContextWhenHidden` enabled.
*
* `retainContextWhenHidden` has a high memory overhead and should only be used if
* your panel's context cannot be quickly saved and restored.
*/
readonly retainContextWhenHidden?: boolean;
}
/**
* A panel that contains a webview.
*/
interface WebviewPanel {
/**
* Identifies the type of the webview panel, such as `'markdown.preview'`.
*/
readonly viewType: string;
/**
* Title of the panel shown in UI.
*/
title: string;
/**
* Icon for the panel shown in UI.
*/
iconPath?: Uri | { light: Uri; dark: Uri };
/**
* Webview belonging to the panel.
*/
readonly webview: Webview;
/**
* Content settings for the webview panel.
*/
readonly options: WebviewPanelOptions;
/**
* Editor position of the panel. This property is only set if the webview is in
* one of the editor view columns.
*/
readonly viewColumn?: ViewColumn;
/**
* Whether the panel is active (focused by the user).
*/
readonly active: boolean;
/**
* Whether the panel is visible.
*/
readonly visible: boolean;
/**
* Fired when the panel's view state changes.
*/
readonly onDidChangeViewState: Event<WebviewPanelOnDidChangeViewStateEvent>;
/**
* Fired when the panel is disposed.
*
* This may be because the user closed the panel or because `.dispose()` was
* called on it.
*
* Trying to use the panel after it has been disposed throws an exception.
*/
readonly onDidDispose: Event<void>;
/**
* Show the webview panel in a given column.
*
* A webview panel may only show in a single column at a time. If it is already showing, this
* method moves it to a new column.
*
* @param viewColumn View column to show the panel in. Shows in the current `viewColumn` if undefined.
* @param preserveFocus When `true`, the webview will not take focus.
*/
reveal(viewColumn?: ViewColumn, preserveFocus?: boolean): void;
/**
* Dispose of the webview panel.
*
* This closes the panel if it showing and disposes of the resources owned by the webview.
* Webview panels are also disposed when the user closes the webview panel. Both cases
* fire the `onDispose` event.
*/
dispose(): any;
}
/**
* Event fired when a webview panel's view state changes.
*/
export interface WebviewPanelOnDidChangeViewStateEvent {
/**
* Webview panel whose view state changed.
*/
readonly webviewPanel: WebviewPanel;
}
/**
* Restore webview panels that have been persisted when vscode shuts down.
*
* There are two types of webview persistence:
*
* - Persistence within a session.
* - Persistence across sessions (across restarts of VS Code).
*
* A `WebviewPanelSerializer` is only required for the second case: persisting a webview across sessions.
*
* Persistence within a session allows a webview to save its state when it becomes hidden
* and restore its content from this state when it becomes visible again. It is powered entirely
* by the webview content itself. To save off a persisted state, call `acquireVsCodeApi().setState()` with
* any json serializable object. To restore the state again, call `getState()`
*
* ```js
* // Within the webview
* const vscode = acquireVsCodeApi();
*
* // Get existing state
* const oldState = vscode.getState() || { value: 0 };
*
* // Update state
* setState({ value: oldState.value + 1 })
* ```
*
* A `WebviewPanelSerializer` extends this persistence across restarts of VS Code. When the editor is shutdown,
* VS Code will save off the state from `setState` of all webviews that have a serializer. When the
* webview first becomes visible after the restart, this state is passed to `deserializeWebviewPanel`.
* The extension can then restore the old `WebviewPanel` from this state.
*/
interface WebviewPanelSerializer {
/**
* Restore a webview panel from its seriailzed `state`.
*
* Called when a serialized webview first becomes visible.
*
* @param webviewPanel Webview panel to restore. The serializer should take ownership of this panel. The
* serializer must restore the webview's `.html` and hook up all webview events.
* @param state Persisted state from the webview content.
*
* @return Thanble indicating that the webview has been fully restored.
*/
deserializeWebviewPanel(webviewPanel: WebviewPanel, state: any): Thenable<void>;
}
/**
* The clipboard provides read and write access to the system's clipboard.
*/
export interface Clipboard {
/**
* Read the current clipboard contents as text.
* @returns A thenable that resolves to a string.
*/
readText(): Thenable<string>;
/**
* Writes text into the clipboard.
* @returns A thenable that resolves when writing happened.
*/
writeText(value: string): Thenable<void>;
}
/**
* Namespace describing the environment the editor runs in.
*/
export namespace env {
/**
* The application name of the editor, like 'VS Code'.
*
* @readonly
*/
export let appName: string;
/**
* The application root folder from which the editor is running.
*
* @readonly
*/
export let appRoot: string;
/**
* Represents the preferred user-language, like `de-CH`, `fr`, or `en-US`.
*
* @readonly
*/
export let language: string;
/**
* The system clipboard.
*/
export const clipboard: Clipboard;
/**
* A unique identifier for the computer.
*
* @readonly
*/
export let machineId: string;
/**
* A unique identifier for the current session.
* Changes each time the editor is started.
*
* @readonly
*/
export let sessionId: string;
}
/**
* Namespace for dealing with commands. In short, a command is a function with a
* unique identifier. The function is sometimes also called _command handler_.
*
* Commands can be added to the editor using the [registerCommand](#commands.registerCommand)
* and [registerTextEditorCommand](#commands.registerTextEditorCommand) functions. Commands
* can be executed [manually](#commands.executeCommand) or from a UI gesture. Those are:
*
* * palette - Use the `commands`-section in `package.json` to make a command show in
* the [command palette](https://code.visualstudio.com/docs/getstarted/userinterface#_command-palette).
* * keybinding - Use the `keybindings`-section in `package.json` to enable
* [keybindings](https://code.visualstudio.com/docs/getstarted/keybindings#_customizing-shortcuts)
* for your extension.
*
* Commands from other extensions and from the editor itself are accessible to an extension. However,
* when invoking an editor command not all argument types are supported.
*
* This is a sample that registers a command handler and adds an entry for that command to the palette. First
* register a command handler with the identifier `extension.sayHello`.
* ```javascript
* commands.registerCommand('extension.sayHello', () => {
* window.showInformationMessage('Hello World!');
* });
* ```
* Second, bind the command identifier to a title under which it will show in the palette (`package.json`).
* ```json
* {
* "contributes": {
* "commands": [{
* "command": "extension.sayHello",
* "title": "Hello World"
* }]
* }
* }
* ```
*/
export namespace commands {
/**
* Registers a command that can be invoked via a keyboard shortcut,
* a menu item, an action, or directly.
*
* Registering a command with an existing command identifier twice
* will cause an error.
*
* @param command A unique identifier for the command.
* @param callback A command handler function.
* @param thisArg The `this` context used when invoking the handler function.
* @return Disposable which unregisters this command on disposal.
*/
export function registerCommand(command: string, callback: (...args: any[]) => any, thisArg?: any): Disposable;
/**
* Registers a text editor command that can be invoked via a keyboard shortcut,
* a menu item, an action, or directly.
*
* Text editor commands are different from ordinary [commands](#commands.registerCommand) as
* they only execute when there is an active editor when the command is called. Also, the
* command handler of an editor command has access to the active editor and to an
* [edit](#TextEditorEdit)-builder.
*
* @param command A unique identifier for the command.
* @param callback A command handler function with access to an [editor](#TextEditor) and an [edit](#TextEditorEdit).
* @param thisArg The `this` context used when invoking the handler function.
* @return Disposable which unregisters this command on disposal.
*/
export function registerTextEditorCommand(command: string, callback: (textEditor: TextEditor, edit: TextEditorEdit, ...args: any[]) => void, thisArg?: any): Disposable;
/**
* Executes the command denoted by the given command identifier.
*
* * *Note 1:* When executing an editor command not all types are allowed to
* be passed as arguments. Allowed are the primitive types `string`, `boolean`,
* `number`, `undefined`, and `null`, as well as [`Position`](#Position), [`Range`](#Range), [`Uri`](#Uri) and [`Location`](#Location).
* * *Note 2:* There are no restrictions when executing commands that have been contributed
* by extensions.
*
* @param command Identifier of the command to execute.
* @param rest Parameters passed to the command function.
* @return A thenable that resolves to the returned value of the given command. `undefined` when
* the command handler function doesn't return anything.
*/
export function executeCommand<T>(command: string, ...rest: any[]): Thenable<T | undefined>;
export function executeCommand<T>(command: 'vscode.previewHtml', error: { '⚠️ The vscode.previewHtml command is deprecated and will be removed. Please switch to using the Webview Api': never }, ...rest: any[]): Thenable<T | undefined>;
/**
* Retrieve the list of all available commands. Commands starting an underscore are
* treated as internal commands.
*
* @param filterInternal Set `true` to not see internal commands (starting with an underscore)
* @return Thenable that resolves to a list of command ids.
*/
export function getCommands(filterInternal?: boolean): Thenable<string[]>;
}
/**
* Represents the state of a window.
*/
export interface WindowState {
/**
* Whether the current window is focused.
*/
readonly focused: boolean;
}
/**
* A uri handler is responsible for handling system-wide [uris](#Uri).
*
* @see [window.registerUriHandler](#window.registerUriHandler).
*/
export interface UriHandler {
/**
* Handle the provided system-wide [uri](#Uri).
*
* @see [window.registerUriHandler](#window.registerUriHandler).
*/
handleUri(uri: Uri): ProviderResult<void>;
}
/**
* Namespace for dealing with the current window of the editor. That is visible
* and active editors, as well as, UI elements to show messages, selections, and
* asking for user input.
*/
export namespace window {
/**
* The currently active editor or `undefined`. The active editor is the one
* that currently has focus or, when none has focus, the one that has changed
* input most recently.
*/
export let activeTextEditor: TextEditor | undefined;
/**
* The currently visible editors or an empty array.
*/
export let visibleTextEditors: TextEditor[];
/**
* An [event](#Event) which fires when the [active editor](#window.activeTextEditor)
* has changed. *Note* that the event also fires when the active editor changes
* to `undefined`.
*/
export const onDidChangeActiveTextEditor: Event<TextEditor | undefined>;
/**
* An [event](#Event) which fires when the array of [visible editors](#window.visibleTextEditors)
* has changed.
*/
export const onDidChangeVisibleTextEditors: Event<TextEditor[]>;
/**
* An [event](#Event) which fires when the selection in an editor has changed.
*/
export const onDidChangeTextEditorSelection: Event<TextEditorSelectionChangeEvent>;
/**
* An [event](#Event) which fires when the visible ranges of an editor has changed.
*/
export const onDidChangeTextEditorVisibleRanges: Event<TextEditorVisibleRangesChangeEvent>;
/**
* An [event](#Event) which fires when the options of an editor have changed.
*/
export const onDidChangeTextEditorOptions: Event<TextEditorOptionsChangeEvent>;
/**
* An [event](#Event) which fires when the view column of an editor has changed.
*/
export const onDidChangeTextEditorViewColumn: Event<TextEditorViewColumnChangeEvent>;
/**
* The currently opened terminals or an empty array.
*/
export const terminals: ReadonlyArray<Terminal>;
/**
* The currently active terminal or `undefined`. The active terminal is the one that
* currently has focus or most recently had focus.
*/
export const activeTerminal: Terminal | undefined;
/**
* An [event](#Event) which fires when the [active terminal](#window.activeTerminal)
* has changed. *Note* that the event also fires when the active terminal changes
* to `undefined`.
*/
export const onDidChangeActiveTerminal: Event<Terminal | undefined>;
/**
* An [event](#Event) which fires when a terminal has been created, either through the
* [createTerminal](#window.createTerminal) API or commands.
*/
export const onDidOpenTerminal: Event<Terminal>;
/**
* An [event](#Event) which fires when a terminal is disposed.
*/
export const onDidCloseTerminal: Event<Terminal>;
/**
* Represents the current window's state.
*
* @readonly
*/
export let state: WindowState;
/**
* An [event](#Event) which fires when the focus state of the current window
* changes. The value of the event represents whether the window is focused.
*/
export const onDidChangeWindowState: Event<WindowState>;
/**
* Show the given document in a text editor. A [column](#ViewColumn) can be provided
* to control where the editor is being shown. Might change the [active editor](#window.activeTextEditor).
*
* @param document A text document to be shown.
* @param column A view column in which the [editor](#TextEditor) should be shown. The default is the [active](#ViewColumn.Active), other values
* are adjusted to be `Min(column, columnCount + 1)`, the [active](#ViewColumn.Active)-column is not adjusted. Use [`ViewColumn.Beside`](#ViewColumn.Beside)
* to open the editor to the side of the currently active one.
* @param preserveFocus When `true` the editor will not take focus.
* @return A promise that resolves to an [editor](#TextEditor).
*/
export function showTextDocument(document: TextDocument, column?: ViewColumn, preserveFocus?: boolean): Thenable<TextEditor>;
/**
* Show the given document in a text editor. [Options](#TextDocumentShowOptions) can be provided
* to control options of the editor is being shown. Might change the [active editor](#window.activeTextEditor).
*
* @param document A text document to be shown.
* @param options [Editor options](#TextDocumentShowOptions) to configure the behavior of showing the [editor](#TextEditor).
* @return A promise that resolves to an [editor](#TextEditor).
*/
export function showTextDocument(document: TextDocument, options?: TextDocumentShowOptions): Thenable<TextEditor>;
/**
* A short-hand for `openTextDocument(uri).then(document => showTextDocument(document, options))`.
*
* @see [openTextDocument](#openTextDocument)
*
* @param uri A resource identifier.
* @param options [Editor options](#TextDocumentShowOptions) to configure the behavior of showing the [editor](#TextEditor).
* @return A promise that resolves to an [editor](#TextEditor).
*/
export function showTextDocument(uri: Uri, options?: TextDocumentShowOptions): Thenable<TextEditor>;
/**
* Create a TextEditorDecorationType that can be used to add decorations to text editors.
*
* @param options Rendering options for the decoration type.
* @return A new decoration type instance.
*/
export function createTextEditorDecorationType(options: DecorationRenderOptions): TextEditorDecorationType;
/**
* Show an information message to users. Optionally provide an array of items which will be presented as
* clickable buttons.
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showInformationMessage(message: string, ...items: string[]): Thenable<string | undefined>;
/**
* Show an information message to users. Optionally provide an array of items which will be presented as
* clickable buttons.
*
* @param message The message to show.
* @param options Configures the behaviour of the message.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showInformationMessage(message: string, options: MessageOptions, ...items: string[]): Thenable<string | undefined>;
/**
* Show an information message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showInformationMessage<T extends MessageItem>(message: string, ...items: T[]): Thenable<T | undefined>;
/**
* Show an information message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param options Configures the behaviour of the message.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showInformationMessage<T extends MessageItem>(message: string, options: MessageOptions, ...items: T[]): Thenable<T | undefined>;
/**
* Show a warning message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showWarningMessage(message: string, ...items: string[]): Thenable<string | undefined>;
/**
* Show a warning message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param options Configures the behaviour of the message.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showWarningMessage(message: string, options: MessageOptions, ...items: string[]): Thenable<string | undefined>;
/**
* Show a warning message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showWarningMessage<T extends MessageItem>(message: string, ...items: T[]): Thenable<T | undefined>;
/**
* Show a warning message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param options Configures the behaviour of the message.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showWarningMessage<T extends MessageItem>(message: string, options: MessageOptions, ...items: T[]): Thenable<T | undefined>;
/**
* Show an error message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showErrorMessage(message: string, ...items: string[]): Thenable<string | undefined>;
/**
* Show an error message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param options Configures the behaviour of the message.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showErrorMessage(message: string, options: MessageOptions, ...items: string[]): Thenable<string | undefined>;
/**
* Show an error message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showErrorMessage<T extends MessageItem>(message: string, ...items: T[]): Thenable<T | undefined>;
/**
* Show an error message.
*
* @see [showInformationMessage](#window.showInformationMessage)
*
* @param message The message to show.
* @param options Configures the behaviour of the message.
* @param items A set of items that will be rendered as actions in the message.
* @return A thenable that resolves to the selected item or `undefined` when being dismissed.
*/
export function showErrorMessage<T extends MessageItem>(message: string, options: MessageOptions, ...items: T[]): Thenable<T | undefined>;
/**
* Shows a selection list allowing multiple selections.
*
* @param items An array of strings, or a promise that resolves to an array of strings.
* @param options Configures the behavior of the selection list.
* @param token A token that can be used to signal cancellation.
* @return A promise that resolves to the selected items or `undefined`.
*/
export function showQuickPick(items: string[] | Thenable<string[]>, options: QuickPickOptions & { canPickMany: true; }, token?: CancellationToken): Thenable<string[] | undefined>;
/**
* Shows a selection list.
*
* @param items An array of strings, or a promise that resolves to an array of strings.
* @param options Configures the behavior of the selection list.
* @param token A token that can be used to signal cancellation.
* @return A promise that resolves to the selection or `undefined`.
*/
export function showQuickPick(items: string[] | Thenable<string[]>, options?: QuickPickOptions, token?: CancellationToken): Thenable<string | undefined>;
/**
* Shows a selection list allowing multiple selections.
*
* @param items An array of items, or a promise that resolves to an array of items.
* @param options Configures the behavior of the selection list.
* @param token A token that can be used to signal cancellation.
* @return A promise that resolves to the selected items or `undefined`.
*/
export function showQuickPick<T extends QuickPickItem>(items: T[] | Thenable<T[]>, options: QuickPickOptions & { canPickMany: true; }, token?: CancellationToken): Thenable<T[] | undefined>;
/**
* Shows a selection list.
*
* @param items An array of items, or a promise that resolves to an array of items.
* @param options Configures the behavior of the selection list.
* @param token A token that can be used to signal cancellation.
* @return A promise that resolves to the selected item or `undefined`.
*/
export function showQuickPick<T extends QuickPickItem>(items: T[] | Thenable<T[]>, options?: QuickPickOptions, token?: CancellationToken): Thenable<T | undefined>;
/**
* Shows a selection list of [workspace folders](#workspace.workspaceFolders) to pick from.
* Returns `undefined` if no folder is open.
*
* @param options Configures the behavior of the workspace folder list.
* @return A promise that resolves to the workspace folder or `undefined`.
*/
export function showWorkspaceFolderPick(options?: WorkspaceFolderPickOptions): Thenable<WorkspaceFolder | undefined>;
/**
* Shows a file open dialog to the user which allows to select a file
* for opening-purposes.
*
* @param options Options that control the dialog.
* @returns A promise that resolves to the selected resources or `undefined`.
*/
export function showOpenDialog(options: OpenDialogOptions): Thenable<Uri[] | undefined>;
/**
* Shows a file save dialog to the user which allows to select a file
* for saving-purposes.
*
* @param options Options that control the dialog.
* @returns A promise that resolves to the selected resource or `undefined`.
*/
export function showSaveDialog(options: SaveDialogOptions): Thenable<Uri | undefined>;
/**
* Opens an input box to ask the user for input.
*
* The returned value will be `undefined` if the input box was canceled (e.g. pressing ESC). Otherwise the
* returned value will be the string typed by the user or an empty string if the user did not type
* anything but dismissed the input box with OK.
*
* @param options Configures the behavior of the input box.
* @param token A token that can be used to signal cancellation.
* @return A promise that resolves to a string the user provided or to `undefined` in case of dismissal.
*/
export function showInputBox(options?: InputBoxOptions, token?: CancellationToken): Thenable<string | undefined>;
/**
* Creates a [QuickPick](#QuickPick) to let the user pick an item from a list
* of items of type T.
*
* Note that in many cases the more convenient [window.showQuickPick](#window.showQuickPick)
* is easier to use. [window.createQuickPick](#window.createQuickPick) should be used
* when [window.showQuickPick](#window.showQuickPick) does not offer the required flexibility.
*
* @return A new [QuickPick](#QuickPick).
*/
export function createQuickPick<T extends QuickPickItem>(): QuickPick<T>;
/**
* Creates a [InputBox](#InputBox) to let the user enter some text input.
*
* Note that in many cases the more convenient [window.showInputBox](#window.showInputBox)
* is easier to use. [window.createInputBox](#window.createInputBox) should be used
* when [window.showInputBox](#window.showInputBox) does not offer the required flexibility.
*
* @return A new [InputBox](#InputBox).
*/
export function createInputBox(): InputBox;
/**
* Creates a new [output channel](#OutputChannel) with the given name.
*
* @param name Human-readable string which will be used to represent the channel in the UI.
*/
export function createOutputChannel(name: string): OutputChannel;
/**
* Create and show a new webview panel.
*
* @param viewType Identifies the type of the webview panel.
* @param title Title of the panel.
* @param showOptions Where to show the webview in the editor. If preserveFocus is set, the new webview will not take focus.
* @param options Settings for the new panel.
*
* @return New webview panel.
*/
export function createWebviewPanel(viewType: string, title: string, showOptions: ViewColumn | { viewColumn: ViewColumn, preserveFocus?: boolean }, options?: WebviewPanelOptions & WebviewOptions): WebviewPanel;
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* @param text The message to show, supports icon substitution as in status bar [items](#StatusBarItem.text).
* @param hideAfterTimeout Timeout in milliseconds after which the message will be disposed.
* @return A disposable which hides the status bar message.
*/
export function setStatusBarMessage(text: string, hideAfterTimeout: number): Disposable;
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* @param text The message to show, supports icon substitution as in status bar [items](#StatusBarItem.text).
* @param hideWhenDone Thenable on which completion (resolve or reject) the message will be disposed.
* @return A disposable which hides the status bar message.
*/
export function setStatusBarMessage(text: string, hideWhenDone: Thenable<any>): Disposable;
/**
* Set a message to the status bar. This is a short hand for the more powerful
* status bar [items](#window.createStatusBarItem).
*
* *Note* that status bar messages stack and that they must be disposed when no
* longer used.
*
* @param text The message to show, supports icon substitution as in status bar [items](#StatusBarItem.text).
* @return A disposable which hides the status bar message.
*/
export function setStatusBarMessage(text: string): Disposable;
/**
* ~~Show progress in the Source Control viewlet while running the given callback and while
* its returned promise isn't resolve or rejected.~~
*
* @deprecated Use `withProgress` instead.
*
* @param task A callback returning a promise. Progress increments can be reported with
* the provided [progress](#Progress)-object.
* @return The thenable the task did return.
*/
export function withScmProgress<R>(task: (progress: Progress<number>) => Thenable<R>): Thenable<R>;
/**
* Show progress in the editor. Progress is shown while running the given callback
* and while the promise it returned isn't resolved nor rejected. The location at which
* progress should show (and other details) is defined via the passed [`ProgressOptions`](#ProgressOptions).
*
* @param task A callback returning a promise. Progress state can be reported with
* the provided [progress](#Progress)-object.
*
* To report discrete progress, use `increment` to indicate how much work has been completed. Each call with
* a `increment` value will be summed up and reflected as overall progress until 100% is reached (a value of
* e.g. `10` accounts for `10%` of work done).
* Note that currently only `ProgressLocation.Notification` is capable of showing discrete progress.
*
* To monitor if the operation has been cancelled by the user, use the provided [`CancellationToken`](#CancellationToken).
* Note that currently only `ProgressLocation.Notification` is supporting to show a cancel button to cancel the
* long running operation.
*
* @return The thenable the task-callback returned.
*/
export function withProgress<R>(options: ProgressOptions, task: (progress: Progress<{ message?: string; increment?: number }>, token: CancellationToken) => Thenable<R>): Thenable<R>;
/**
* Creates a status bar [item](#StatusBarItem).
*
* @param alignment The alignment of the item.
* @param priority The priority of the item. Higher values mean the item should be shown more to the left.
* @return A new status bar item.
*/
export function createStatusBarItem(alignment?: StatusBarAlignment, priority?: number): StatusBarItem;
/**
* Creates a [Terminal](#Terminal). The cwd of the terminal will be the workspace directory
* if it exists, regardless of whether an explicit customStartPath setting exists.
*
* @param name Optional human-readable string which will be used to represent the terminal in the UI.
* @param shellPath Optional path to a custom shell executable to be used in the terminal.
* @param shellArgs Optional args for the custom shell executable, this does not work on Windows (see #8429)
* @return A new Terminal.
*/
export function createTerminal(name?: string, shellPath?: string, shellArgs?: string[]): Terminal;
/**
* Creates a [Terminal](#Terminal). The cwd of the terminal will be the workspace directory
* if it exists, regardless of whether an explicit customStartPath setting exists.
*
* @param options A TerminalOptions object describing the characteristics of the new terminal.
* @return A new Terminal.
*/
export function createTerminal(options: TerminalOptions): Terminal;
/**
* Register a [TreeDataProvider](#TreeDataProvider) for the view contributed using the extension point `views`.
* This will allow you to contribute data to the [TreeView](#TreeView) and update if the data changes.
*
* **Note:** To get access to the [TreeView](#TreeView) and perform operations on it, use [createTreeView](#window.createTreeView).
*
* @param viewId Id of the view contributed using the extension point `views`.
* @param treeDataProvider A [TreeDataProvider](#TreeDataProvider) that provides tree data for the view
*/
export function registerTreeDataProvider<T>(viewId: string, treeDataProvider: TreeDataProvider<T>): Disposable;
/**
* Create a [TreeView](#TreeView) for the view contributed using the extension point `views`.
* @param viewId Id of the view contributed using the extension point `views`.
* @param options Options for creating the [TreeView](#TreeView)
* @returns a [TreeView](#TreeView).
*/
export function createTreeView<T>(viewId: string, options: TreeViewOptions<T>): TreeView<T>;
/**
* Registers a [uri handler](#UriHandler) capable of handling system-wide [uris](#Uri).
* In case there are multiple windows open, the topmost window will handle the uri.
* A uri handler is scoped to the extension it is contributed from; it will only
* be able to handle uris which are directed to the extension itself. A uri must respect
* the following rules:
*
* - The uri-scheme must be the product name;
* - The uri-authority must be the extension id (eg. `my.extension`);
* - The uri-path, -query and -fragment parts are arbitrary.
*
* For example, if the `my.extension` extension registers a uri handler, it will only
* be allowed to handle uris with the prefix `product-name://my.extension`.
*
* An extension can only register a single uri handler in its entire activation lifetime.
*
* * *Note:* There is an activation event `onUri` that fires when a uri directed for
* the current extension is about to be handled.
*
* @param handler The uri handler to register for this extension.
*/
export function registerUriHandler(handler: UriHandler): Disposable;
/**
* Registers a webview panel serializer.
*
* Extensions that support reviving should have an `"onWebviewPanel:viewType"` activation event and
* make sure that [registerWebviewPanelSerializer](#registerWebviewPanelSerializer) is called during activation.
*
* Only a single serializer may be registered at a time for a given `viewType`.
*
* @param viewType Type of the webview panel that can be serialized.
* @param serializer Webview serializer.
*/
export function registerWebviewPanelSerializer(viewType: string, serializer: WebviewPanelSerializer): Disposable;
}
/**
* Options for creating a [TreeView](#TreeView)
*/
export interface TreeViewOptions<T> {
/**
* A data provider that provides tree data.
*/
treeDataProvider: TreeDataProvider<T>;
/**
* Whether to show collapse all action or not.
*/
showCollapseAll?: boolean;
}
/**
* The event that is fired when an element in the [TreeView](#TreeView) is expanded or collapsed
*/
export interface TreeViewExpansionEvent<T> {
/**
* Element that is expanded or collapsed.
*/
readonly element: T;
}
/**
* The event that is fired when there is a change in [tree view's selection](#TreeView.selection)
*/
export interface TreeViewSelectionChangeEvent<T> {
/**
* Selected elements.
*/
readonly selection: T[];
}
/**
* The event that is fired when there is a change in [tree view's visibility](#TreeView.visible)
*/
export interface TreeViewVisibilityChangeEvent {
/**
* `true` if the [tree view](#TreeView) is visible otherwise `false`.
*/
readonly visible: boolean;
}
/**
* Represents a Tree view
*/
export interface TreeView<T> extends Disposable {
/**
* Event that is fired when an element is expanded
*/
readonly onDidExpandElement: Event<TreeViewExpansionEvent<T>>;
/**
* Event that is fired when an element is collapsed
*/
readonly onDidCollapseElement: Event<TreeViewExpansionEvent<T>>;
/**
* Currently selected elements.
*/
readonly selection: T[];
/**
* Event that is fired when the [selection](#TreeView.selection) has changed
*/
readonly onDidChangeSelection: Event<TreeViewSelectionChangeEvent<T>>;
/**
* `true` if the [tree view](#TreeView) is visible otherwise `false`.
*/
readonly visible: boolean;
/**
* Event that is fired when [visibility](#TreeView.visible) has changed
*/
readonly onDidChangeVisibility: Event<TreeViewVisibilityChangeEvent>;
/**
* Reveals the given element in the tree view.
* If the tree view is not visible then the tree view is shown and element is revealed.
*
* By default revealed element is selected.
* In order to not to select, set the option `select` to `false`.
* In order to focus, set the option `focus` to `true`.
* In order to expand the revealed element, set the option `expand` to `true`. To expand recursively set `expand` to the number of levels to expand.
* **NOTE:** You can expand only to 3 levels maximum.
*
* **NOTE:** [TreeDataProvider](#TreeDataProvider) is required to implement [getParent](#TreeDataProvider.getParent) method to access this API.
*/
reveal(element: T, options?: { select?: boolean, focus?: boolean, expand?: boolean | number }): Thenable<void>;
}
/**
* A data provider that provides tree data
*/
export interface TreeDataProvider<T> {
/**
* An optional event to signal that an element or root has changed.
* This will trigger the view to update the changed element/root and its children recursively (if shown).
* To signal that root has changed, do not pass any argument or pass `undefined` or `null`.
*/
onDidChangeTreeData?: Event<T | undefined | null>;
/**
* Get [TreeItem](#TreeItem) representation of the `element`
*
* @param element The element for which [TreeItem](#TreeItem) representation is asked for.
* @return [TreeItem](#TreeItem) representation of the element
*/
getTreeItem(element: T): TreeItem | Thenable<TreeItem>;
/**
* Get the children of `element` or root if no element is passed.
*
* @param element The element from which the provider gets children. Can be `undefined`.
* @return Children of `element` or root if no element is passed.
*/
getChildren(element?: T): ProviderResult<T[]>;
/**
* Optional method to return the parent of `element`.
* Return `null` or `undefined` if `element` is a child of root.
*
* **NOTE:** This method should be implemented in order to access [reveal](#TreeView.reveal) API.
*
* @param element The element for which the parent has to be returned.
* @return Parent of `element`.
*/
getParent?(element: T): ProviderResult<T>;
}
export class TreeItem {
/**
* A human-readable string describing this item. When `falsy`, it is derived from [resourceUri](#TreeItem.resourceUri).
*/
label?: string;
/**
* Optional id for the tree item that has to be unique across tree. The id is used to preserve the selection and expansion state of the tree item.
*
* If not provided, an id is generated using the tree item's label. **Note** that when labels change, ids will change and that selection and expansion state cannot be kept stable anymore.
*/
id?: string;
/**
* The icon path or [ThemeIcon](#ThemeIcon) for the tree item.
* When `falsy`, [Folder Theme Icon](#ThemeIcon.Folder) is assigned, if item is collapsible otherwise [File Theme Icon](#ThemeIcon.File).
* When a [ThemeIcon](#ThemeIcon) is specified, icon is derived from the current file icon theme for the specified theme icon using [resourceUri](#TreeItem.resourceUri) (if provided).
*/
iconPath?: string | Uri | { light: string | Uri; dark: string | Uri } | ThemeIcon;
/**
* A human readable string which is rendered less prominent.
* When `true`, it is derived from [resourceUri](#TreeItem.resourceUri) and when `falsy`, it is not shown.
*/
description?: string | boolean;
/**
* The [uri](#Uri) of the resource representing this item.
*
* Will be used to derive the [label](#TreeItem.label), when it is not provided.
* Will be used to derive the icon from current icon theme, when [iconPath](#TreeItem.iconPath) has [ThemeIcon](#ThemeIcon) value.
*/
resourceUri?: Uri;
/**
* The tooltip text when you hover over this item.
*/
tooltip?: string | undefined;
/**
* The [command](#Command) that should be executed when the tree item is selected.
*/
command?: Command;
/**
* [TreeItemCollapsibleState](#TreeItemCollapsibleState) of the tree item.
*/
collapsibleState?: TreeItemCollapsibleState;
/**
* Context value of the tree item. This can be used to contribute item specific actions in the tree.
* For example, a tree item is given a context value as `folder`. When contributing actions to `view/item/context`
* using `menus` extension point, you can specify context value for key `viewItem` in `when` expression like `viewItem == folder`.
* ```
* "contributes": {
* "menus": {
* "view/item/context": [
* {
* "command": "extension.deleteFolder",
* "when": "viewItem == folder"
* }
* ]
* }
* }
* ```
* This will show action `extension.deleteFolder` only for items with `contextValue` is `folder`.
*/
contextValue?: string;
/**
* @param label A human-readable string describing this item
* @param collapsibleState [TreeItemCollapsibleState](#TreeItemCollapsibleState) of the tree item. Default is [TreeItemCollapsibleState.None](#TreeItemCollapsibleState.None)
*/
constructor(label: string, collapsibleState?: TreeItemCollapsibleState);
/**
* @param resourceUri The [uri](#Uri) of the resource representing this item.
* @param collapsibleState [TreeItemCollapsibleState](#TreeItemCollapsibleState) of the tree item. Default is [TreeItemCollapsibleState.None](#TreeItemCollapsibleState.None)
*/
constructor(resourceUri: Uri, collapsibleState?: TreeItemCollapsibleState);
}
/**
* Collapsible state of the tree item
*/
export enum TreeItemCollapsibleState {
/**
* Determines an item can be neither collapsed nor expanded. Implies it has no children.
*/
None = 0,
/**
* Determines an item is collapsed
*/
Collapsed = 1,
/**
* Determines an item is expanded
*/
Expanded = 2
}
/**
* Value-object describing what options a terminal should use.
*/
export interface TerminalOptions {
/**
* A human-readable string which will be used to represent the terminal in the UI.
*/
name?: string;
/**
* A path to a custom shell executable to be used in the terminal.
*/
shellPath?: string;
/**
* Args for the custom shell executable, this does not work on Windows (see #8429)
*/
shellArgs?: string[];
/**
* A path for the current working directory to be used for the terminal.
*/
cwd?: string;
/**
* Object with environment variables that will be added to the VS Code process.
*/
env?: { [key: string]: string | null };
}
/**
* A location in the editor at which progress information can be shown. It depends on the
* location how progress is visually represented.
*/
export enum ProgressLocation {
/**
* Show progress for the source control viewlet, as overlay for the icon and as progress bar
* inside the viewlet (when visible). Neither supports cancellation nor discrete progress.
*/
SourceControl = 1,
/**
* Show progress in the status bar of the editor. Neither supports cancellation nor discrete progress.
*/
Window = 10,
/**
* Show progress as notification with an optional cancel button. Supports to show infinite and discrete progress.
*/
Notification = 15
}
/**
* Value-object describing where and how progress should show.
*/
export interface ProgressOptions {
/**
* The location at which progress should show.
*/
location: ProgressLocation;
/**
* A human-readable string which will be used to describe the
* operation.
*/
title?: string;
/**
* Controls if a cancel button should show to allow the user to
* cancel the long running operation. Note that currently only
* `ProgressLocation.Notification` is supporting to show a cancel
* button.
*/
cancellable?: boolean;
}
/**
* A light-weight user input UI that is intially not visible. After
* configuring it through its properties the extension can make it
* visible by calling [QuickInput.show](#QuickInput.show).
*
* There are several reasons why this UI might have to be hidden and
* the extension will be notified through [QuickInput.onDidHide](#QuickInput.onDidHide).
* (Examples include: an explict call to [QuickInput.hide](#QuickInput.hide),
* the user pressing Esc, some other input UI opening, etc.)
*
* A user pressing Enter or some other gesture implying acceptance
* of the current state does not automatically hide this UI component.
* It is up to the extension to decide whether to accept the user's input
* and if the UI should indeed be hidden through a call to [QuickInput.hide](#QuickInput.hide).
*
* When the extension no longer needs this input UI, it should
* [QuickInput.dispose](#QuickInput.dispose) it to allow for freeing up
* any resources associated with it.
*
* See [QuickPick](#QuickPick) and [InputBox](#InputBox) for concrete UIs.
*/
export interface QuickInput {
/**
* An optional title.
*/
title: string | undefined;
/**
* An optional current step count.
*/
step: number | undefined;
/**
* An optional total step count.
*/
totalSteps: number | undefined;
/**
* If the UI should allow for user input. Defaults to true.
*
* Change this to false, e.g., while validating user input or
* loading data for the next step in user input.
*/
enabled: boolean;
/**
* If the UI should show a progress indicator. Defaults to false.
*
* Change this to true, e.g., while loading more data or validating
* user input.
*/
busy: boolean;
/**
* If the UI should stay open even when loosing UI focus. Defaults to false.
*/
ignoreFocusOut: boolean;
/**
* Makes the input UI visible in its current configuration. Any other input
* UI will first fire an [QuickInput.onDidHide](#QuickInput.onDidHide) event.
*/
show(): void;
/**
* Hides this input UI. This will also fire an [QuickInput.onDidHide](#QuickInput.onDidHide)
* event.
*/
hide(): void;
/**
* An event signaling when this input UI is hidden.
*
* There are several reasons why this UI might have to be hidden and
* the extension will be notified through [QuickInput.onDidHide](#QuickInput.onDidHide).
* (Examples include: an explict call to [QuickInput.hide](#QuickInput.hide),
* the user pressing Esc, some other input UI opening, etc.)
*/
onDidHide: Event<void>;
/**
* Dispose of this input UI and any associated resources. If it is still
* visible, it is first hidden. After this call the input UI is no longer
* functional and no additional methods or properties on it should be
* accessed. Instead a new input UI should be created.
*/
dispose(): void;
}
/**
* A concrete [QuickInput](#QuickInput) to let the user pick an item from a
* list of items of type T. The items can be filtered through a filter text field and
* there is an option [canSelectMany](#QuickPick.canSelectMany) to allow for
* selecting multiple items.
*
* Note that in many cases the more convenient [window.showQuickPick](#window.showQuickPick)
* is easier to use. [window.createQuickPick](#window.createQuickPick) should be used
* when [window.showQuickPick](#window.showQuickPick) does not offer the required flexibility.
*/
export interface QuickPick<T extends QuickPickItem> extends QuickInput {
/**
* Current value of the filter text.
*/
value: string;
/**
* Optional placeholder in the filter text.
*/
placeholder: string | undefined;
/**
* An event signaling when the value of the filter text has changed.
*/
readonly onDidChangeValue: Event<string>;
/**
* An event signaling when the user indicated acceptance of the selected item(s).
*/
readonly onDidAccept: Event<void>;
/**
* Buttons for actions in the UI.
*/
buttons: ReadonlyArray<QuickInputButton>;
/**
* An event signaling when a button was triggered.
*/
readonly onDidTriggerButton: Event<QuickInputButton>;
/**
* Items to pick from.
*/
items: ReadonlyArray<T>;
/**
* If multiple items can be selected at the same time. Defaults to false.
*/
canSelectMany: boolean;
/**
* If the filter text should also be matched against the description of the items. Defaults to false.
*/
matchOnDescription: boolean;
/**
* If the filter text should also be matched against the detail of the items. Defaults to false.
*/
matchOnDetail: boolean;
/**
* Active items. This can be read and updated by the extension.
*/
activeItems: ReadonlyArray<T>;
/**
* An event signaling when the active items have changed.
*/
readonly onDidChangeActive: Event<T[]>;
/**
* Selected items. This can be read and updated by the extension.
*/
selectedItems: ReadonlyArray<T>;
/**
* An event signaling when the selected items have changed.
*/
readonly onDidChangeSelection: Event<T[]>;
}
/**
* A concrete [QuickInput](#QuickInput) to let the user input a text value.
*
* Note that in many cases the more convenient [window.showInputBox](#window.showInputBox)
* is easier to use. [window.createInputBox](#window.createInputBox) should be used
* when [window.showInputBox](#window.showInputBox) does not offer the required flexibility.
*/
export interface InputBox extends QuickInput {
/**
* Current input value.
*/
value: string;
/**
* Optional placeholder in the filter text.
*/
placeholder: string | undefined;
/**
* If the input value should be hidden. Defaults to false.
*/
password: boolean;
/**
* An event signaling when the value has changed.
*/
readonly onDidChangeValue: Event<string>;
/**
* An event signaling when the user indicated acceptance of the input value.
*/
readonly onDidAccept: Event<void>;
/**
* Buttons for actions in the UI.
*/
buttons: ReadonlyArray<QuickInputButton>;
/**
* An event signaling when a button was triggered.
*/
readonly onDidTriggerButton: Event<QuickInputButton>;
/**
* An optional prompt text providing some ask or explanation to the user.
*/
prompt: string | undefined;
/**
* An optional validation message indicating a problem with the current input value.
*/
validationMessage: string | undefined;
}
/**
* Button for an action in a [QuickPick](#QuickPick) or [InputBox](#InputBox).
*/
export interface QuickInputButton {
/**
* Icon for the button.
*/
readonly iconPath: Uri | { light: Uri; dark: Uri } | ThemeIcon;
/**
* An optional tooltip.
*/
readonly tooltip?: string | undefined;
}
/**
* Predefined buttons for [QuickPick](#QuickPick) and [InputBox](#InputBox).
*/
export class QuickInputButtons {
/**
* A back button for [QuickPick](#QuickPick) and [InputBox](#InputBox).
*
* When a navigation 'back' button is needed this one should be used for consistency.
* It comes with a predefined icon, tooltip and location.
*/
static readonly Back: QuickInputButton;
/**
* @hidden
*/
private constructor();
}
/**
* An event describing an individual change in the text of a [document](#TextDocument).
*/
export interface TextDocumentContentChangeEvent {
/**
* The range that got replaced.
*/
range: Range;
/**
* The offset of the range that got replaced.
*/
rangeOffset: number;
/**
* The length of the range that got replaced.
*/
rangeLength: number;
/**
* The new text for the range.
*/
text: string;
}
/**
* An event describing a transactional [document](#TextDocument) change.
*/
export interface TextDocumentChangeEvent {
/**
* The affected document.
*/
document: TextDocument;
/**
* An array of content changes.
*/
contentChanges: TextDocumentContentChangeEvent[];
}
/**
* Represents reasons why a text document is saved.
*/
export enum TextDocumentSaveReason {
/**
* Manually triggered, e.g. by the user pressing save, by starting debugging,
* or by an API call.
*/
Manual = 1,
/**
* Automatic after a delay.
*/
AfterDelay = 2,
/**
* When the editor lost focus.
*/
FocusOut = 3
}
/**
* An event that is fired when a [document](#TextDocument) will be saved.
*
* To make modifications to the document before it is being saved, call the
* [`waitUntil`](#TextDocumentWillSaveEvent.waitUntil)-function with a thenable
* that resolves to an array of [text edits](#TextEdit).
*/
export interface TextDocumentWillSaveEvent {
/**
* The document that will be saved.
*/
document: TextDocument;
/**
* The reason why save was triggered.
*/
reason: TextDocumentSaveReason;
/**
* Allows to pause the event loop and to apply [pre-save-edits](#TextEdit).
* Edits of subsequent calls to this function will be applied in order. The
* edits will be *ignored* if concurrent modifications of the document happened.
*
* *Note:* This function can only be called during event dispatch and not
* in an asynchronous manner:
*
* ```ts
* workspace.onWillSaveTextDocument(event => {
* // async, will *throw* an error
* setTimeout(() => event.waitUntil(promise));
*
* // sync, OK
* event.waitUntil(promise);
* })
* ```
*
* @param thenable A thenable that resolves to [pre-save-edits](#TextEdit).
*/
waitUntil(thenable: Thenable<TextEdit[]>): void;
/**
* Allows to pause the event loop until the provided thenable resolved.
*
* *Note:* This function can only be called during event dispatch.
*
* @param thenable A thenable that delays saving.
*/
waitUntil(thenable: Thenable<any>): void;
}
/**
* An event describing a change to the set of [workspace folders](#workspace.workspaceFolders).
*/
export interface WorkspaceFoldersChangeEvent {
/**
* Added workspace folders.
*/
readonly added: WorkspaceFolder[];
/**
* Removed workspace folders.
*/
readonly removed: WorkspaceFolder[];
}
/**
* A workspace folder is one of potentially many roots opened by the editor. All workspace folders
* are equal which means there is no notion of an active or master workspace folder.
*/
export interface WorkspaceFolder {
/**
* The associated uri for this workspace folder.
*
* *Note:* The [Uri](#Uri)-type was intentionally chosen such that future releases of the editor can support
* workspace folders that are not stored on the local disk, e.g. `ftp://server/workspaces/foo`.
*/
readonly uri: Uri;
/**
* The name of this workspace folder. Defaults to
* the basename of its [uri-path](#Uri.path)
*/
readonly name: string;
/**
* The ordinal number of this workspace folder.
*/
readonly index: number;
}
/**
* Namespace for dealing with the current workspace. A workspace is the representation
* of the folder that has been opened. There is no workspace when just a file but not a
* folder has been opened.
*
* The workspace offers support for [listening](#workspace.createFileSystemWatcher) to fs
* events and for [finding](#workspace.findFiles) files. Both perform well and run _outside_
* the editor-process so that they should be always used instead of nodejs-equivalents.
*/
export namespace workspace {
/**
* ~~The folder that is open in the editor. `undefined` when no folder
* has been opened.~~
*
* @deprecated Use [`workspaceFolders`](#workspace.workspaceFolders) instead.
*
* @readonly
*/
export let rootPath: string | undefined;
/**
* List of workspace folders or `undefined` when no folder is open.
* *Note* that the first entry corresponds to the value of `rootPath`.
*
* @readonly
*/
export let workspaceFolders: WorkspaceFolder[] | undefined;
/**
* The name of the workspace. `undefined` when no folder
* has been opened.
*
* @readonly
*/
export let name: string | undefined;
/**
* An event that is emitted when a workspace folder is added or removed.
*/
export const onDidChangeWorkspaceFolders: Event<WorkspaceFoldersChangeEvent>;
/**
* Returns the [workspace folder](#WorkspaceFolder) that contains a given uri.
* * returns `undefined` when the given uri doesn't match any workspace folder
* * returns the *input* when the given uri is a workspace folder itself
*
* @param uri An uri.
* @return A workspace folder or `undefined`
*/
export function getWorkspaceFolder(uri: Uri): WorkspaceFolder | undefined;
/**
* Returns a path that is relative to the workspace folder or folders.
*
* When there are no [workspace folders](#workspace.workspaceFolders) or when the path
* is not contained in them, the input is returned.
*
* @param pathOrUri A path or uri. When a uri is given its [fsPath](#Uri.fsPath) is used.
* @param includeWorkspaceFolder When `true` and when the given path is contained inside a
* workspace folder the name of the workspace is prepended. Defaults to `true` when there are
* multiple workspace folders and `false` otherwise.
* @return A path relative to the root or the input.
*/
export function asRelativePath(pathOrUri: string | Uri, includeWorkspaceFolder?: boolean): string;
/**
* This method replaces `deleteCount` [workspace folders](#workspace.workspaceFolders) starting at index `start`
* by an optional set of `workspaceFoldersToAdd` on the `vscode.workspace.workspaceFolders` array. This "splice"
* behavior can be used to add, remove and change workspace folders in a single operation.
*
* If the first workspace folder is added, removed or changed, the currently executing extensions (including the
* one that called this method) will be terminated and restarted so that the (deprecated) `rootPath` property is
* updated to point to the first workspace folder.
*
* Use the [`onDidChangeWorkspaceFolders()`](#onDidChangeWorkspaceFolders) event to get notified when the
* workspace folders have been updated.
*
* **Example:** adding a new workspace folder at the end of workspace folders
* ```typescript
* workspace.updateWorkspaceFolders(workspace.workspaceFolders ? workspace.workspaceFolders.length : 0, null, { uri: ...});
* ```
*
* **Example:** removing the first workspace folder
* ```typescript
* workspace.updateWorkspaceFolders(0, 1);
* ```
*
* **Example:** replacing an existing workspace folder with a new one
* ```typescript
* workspace.updateWorkspaceFolders(0, 1, { uri: ...});
* ```
*
* It is valid to remove an existing workspace folder and add it again with a different name
* to rename that folder.
*
* **Note:** it is not valid to call [updateWorkspaceFolders()](#updateWorkspaceFolders) multiple times
* without waiting for the [`onDidChangeWorkspaceFolders()`](#onDidChangeWorkspaceFolders) to fire.
*
* @param start the zero-based location in the list of currently opened [workspace folders](#WorkspaceFolder)
* from which to start deleting workspace folders.
* @param deleteCount the optional number of workspace folders to remove.
* @param workspaceFoldersToAdd the optional variable set of workspace folders to add in place of the deleted ones.
* Each workspace is identified with a mandatory URI and an optional name.
* @return true if the operation was successfully started and false otherwise if arguments were used that would result
* in invalid workspace folder state (e.g. 2 folders with the same URI).
*/
export function updateWorkspaceFolders(start: number, deleteCount: number | undefined | null, ...workspaceFoldersToAdd: { uri: Uri, name?: string }[]): boolean;
/**
* Creates a file system watcher.
*
* A glob pattern that filters the file events on their absolute path must be provided. Optionally,
* flags to ignore certain kinds of events can be provided. To stop listening to events the watcher must be disposed.
*
* *Note* that only files within the current [workspace folders](#workspace.workspaceFolders) can be watched.
*
* @param globPattern A [glob pattern](#GlobPattern) that is applied to the absolute paths of created, changed,
* and deleted files. Use a [relative pattern](#RelativePattern) to limit events to a certain [workspace folder](#WorkspaceFolder).
* @param ignoreCreateEvents Ignore when files have been created.
* @param ignoreChangeEvents Ignore when files have been changed.
* @param ignoreDeleteEvents Ignore when files have been deleted.
* @return A new file system watcher instance.
*/
export function createFileSystemWatcher(globPattern: GlobPattern, ignoreCreateEvents?: boolean, ignoreChangeEvents?: boolean, ignoreDeleteEvents?: boolean): FileSystemWatcher;
/**
* Find files across all [workspace folders](#workspace.workspaceFolders) in the workspace.
*
* @sample `findFiles('**/*.js', '**/node_modules/**', 10)`
* @param include A [glob pattern](#GlobPattern) that defines the files to search for. The glob pattern
* will be matched against the file paths of resulting matches relative to their workspace. Use a [relative pattern](#RelativePattern)
* to restrict the search results to a [workspace folder](#WorkspaceFolder).
* @param exclude A [glob pattern](#GlobPattern) that defines files and folders to exclude. The glob pattern
* will be matched against the file paths of resulting matches relative to their workspace. When `undefined` only default excludes will
* apply, when `null` no excludes will apply.
* @param maxResults An upper-bound for the result.
* @param token A token that can be used to signal cancellation to the underlying search engine.
* @return A thenable that resolves to an array of resource identifiers. Will return no results if no
* [workspace folders](#workspace.workspaceFolders) are opened.
*/
export function findFiles(include: GlobPattern, exclude?: GlobPattern | null, maxResults?: number, token?: CancellationToken): Thenable<Uri[]>;
/**
* Save all dirty files.
*
* @param includeUntitled Also save files that have been created during this session.
* @return A thenable that resolves when the files have been saved.
*/
export function saveAll(includeUntitled?: boolean): Thenable<boolean>;
/**
* Make changes to one or many resources or create, delete, and rename resources as defined by the given
* [workspace edit](#WorkspaceEdit).
*
* All changes of a workspace edit are applied in the same order in which they have been added. If
* multiple textual inserts are made at the same position, these strings appear in the resulting text
* in the order the 'inserts' were made. Invalid sequences like 'delete file a' -> 'insert text in file a'
* cause failure of the operation.
*
* When applying a workspace edit that consists only of text edits an 'all-or-nothing'-strategy is used.
* A workspace edit with resource creations or deletions aborts the operation, e.g. consective edits will
* not be attempted, when a single edit fails.
*
* @param edit A workspace edit.
* @return A thenable that resolves when the edit could be applied.
*/
export function applyEdit(edit: WorkspaceEdit): Thenable<boolean>;
/**
* All text documents currently known to the system.
*
* @readonly
*/
export let textDocuments: TextDocument[];
/**
* Opens a document. Will return early if this document is already open. Otherwise
* the document is loaded and the [didOpen](#workspace.onDidOpenTextDocument)-event fires.
*
* The document is denoted by an [uri](#Uri). Depending on the [scheme](#Uri.scheme) the
* following rules apply:
* * `file`-scheme: Open a file on disk, will be rejected if the file does not exist or cannot be loaded.
* * `untitled`-scheme: A new file that should be saved on disk, e.g. `untitled:c:\frodo\new.js`. The language
* will be derived from the file name.
* * For all other schemes the registered text document content [providers](#TextDocumentContentProvider) are consulted.
*
* *Note* that the lifecycle of the returned document is owned by the editor and not by the extension. That means an
* [`onDidClose`](#workspace.onDidCloseTextDocument)-event can occur at any time after opening it.
*
* @param uri Identifies the resource to open.
* @return A promise that resolves to a [document](#TextDocument).
*/
export function openTextDocument(uri: Uri): Thenable<TextDocument>;
/**
* A short-hand for `openTextDocument(Uri.file(fileName))`.
*
* @see [openTextDocument](#openTextDocument)
* @param fileName A name of a file on disk.
* @return A promise that resolves to a [document](#TextDocument).
*/
export function openTextDocument(fileName: string): Thenable<TextDocument>;
/**
* Opens an untitled text document. The editor will prompt the user for a file
* path when the document is to be saved. The `options` parameter allows to
* specify the *language* and/or the *content* of the document.
*
* @param options Options to control how the document will be created.
* @return A promise that resolves to a [document](#TextDocument).
*/
export function openTextDocument(options?: { language?: string; content?: string; }): Thenable<TextDocument>;
/**
* Register a text document content provider.
*
* Only one provider can be registered per scheme.
*
* @param scheme The uri-scheme to register for.
* @param provider A content provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerTextDocumentContentProvider(scheme: string, provider: TextDocumentContentProvider): Disposable;
/**
* An event that is emitted when a [text document](#TextDocument) is opened or when the language id
* of a text document [has been changed](#languages.setTextDocumentLanguage).
*
* To add an event listener when a visible text document is opened, use the [TextEditor](#TextEditor) events in the
* [window](#window) namespace. Note that:
*
* - The event is emitted before the [document](#TextDocument) is updated in the
* [active text editor](#window.activeTextEditor)
* - When a [text document](#TextDocument) is already open (e.g.: open in another [visible text editor](#window.visibleTextEditors)) this event is not emitted
*
*/
export const onDidOpenTextDocument: Event<TextDocument>;
/**
* An event that is emitted when a [text document](#TextDocument) is disposed or when the language id
* of a text document [has been changed](#languages.setTextDocumentLanguage).
*
* To add an event listener when a visible text document is closed, use the [TextEditor](#TextEditor) events in the
* [window](#window) namespace. Note that this event is not emitted when a [TextEditor](#TextEditor) is closed
* but the document remains open in another [visible text editor](#window.visibleTextEditors).
*/
export const onDidCloseTextDocument: Event<TextDocument>;
/**
* An event that is emitted when a [text document](#TextDocument) is changed. This usually happens
* when the [contents](#TextDocument.getText) changes but also when other things like the
* [dirty](#TextDocument.isDirty)-state changes.
*/
export const onDidChangeTextDocument: Event<TextDocumentChangeEvent>;
/**
* An event that is emitted when a [text document](#TextDocument) will be saved to disk.
*
* *Note 1:* Subscribers can delay saving by registering asynchronous work. For the sake of data integrity the editor
* might save without firing this event. For instance when shutting down with dirty files.
*
* *Note 2:* Subscribers are called sequentially and they can [delay](#TextDocumentWillSaveEvent.waitUntil) saving
* by registering asynchronous work. Protection against misbehaving listeners is implemented as such:
* * there is an overall time budget that all listeners share and if that is exhausted no further listener is called
* * listeners that take a long time or produce errors frequently will not be called anymore
*
* The current thresholds are 1.5 seconds as overall time budget and a listener can misbehave 3 times before being ignored.
*/
export const onWillSaveTextDocument: Event<TextDocumentWillSaveEvent>;
/**
* An event that is emitted when a [text document](#TextDocument) is saved to disk.
*/
export const onDidSaveTextDocument: Event<TextDocument>;
/**
* Get a workspace configuration object.
*
* When a section-identifier is provided only that part of the configuration
* is returned. Dots in the section-identifier are interpreted as child-access,
* like `{ myExt: { setting: { doIt: true }}}` and `getConfiguration('myExt.setting').get('doIt') === true`.
*
* When a resource is provided, configuration scoped to that resource is returned.
*
* @param section A dot-separated identifier.
* @param resource A resource for which the configuration is asked for
* @return The full configuration or a subset.
*/
export function getConfiguration(section?: string, resource?: Uri | null): WorkspaceConfiguration;
/**
* An event that is emitted when the [configuration](#WorkspaceConfiguration) changed.
*/
export const onDidChangeConfiguration: Event<ConfigurationChangeEvent>;
/**
* ~~Register a task provider.~~
*
* @deprecated Use the corresponding function on the `tasks` namespace instead
*
* @param type The task kind type this provider is registered for.
* @param provider A task provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerTaskProvider(type: string, provider: TaskProvider): Disposable;
/**
* Register a filesystem provider for a given scheme, e.g. `ftp`.
*
* There can only be one provider per scheme and an error is being thrown when a scheme
* has been claimed by another provider or when it is reserved.
*
* @param scheme The uri-[scheme](#Uri.scheme) the provider registers for.
* @param provider The filesystem provider.
* @param options Immutable metadata about the provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerFileSystemProvider(scheme: string, provider: FileSystemProvider, options?: { isCaseSensitive?: boolean, isReadonly?: boolean }): Disposable;
}
/**
* An event describing the change in Configuration
*/
export interface ConfigurationChangeEvent {
/**
* Returns `true` if the given section for the given resource (if provided) is affected.
*
* @param section Configuration name, supports _dotted_ names.
* @param resource A resource Uri.
* @return `true` if the given section for the given resource (if provided) is affected.
*/
affectsConfiguration(section: string, resource?: Uri): boolean;
}
/**
* Namespace for participating in language-specific editor [features](https://code.visualstudio.com/docs/editor/editingevolved),
* like IntelliSense, code actions, diagnostics etc.
*
* Many programming languages exist and there is huge variety in syntaxes, semantics, and paradigms. Despite that, features
* like automatic word-completion, code navigation, or code checking have become popular across different tools for different
* programming languages.
*
* The editor provides an API that makes it simple to provide such common features by having all UI and actions already in place and
* by allowing you to participate by providing data only. For instance, to contribute a hover all you have to do is provide a function
* that can be called with a [TextDocument](#TextDocument) and a [Position](#Position) returning hover info. The rest, like tracking the
* mouse, positioning the hover, keeping the hover stable etc. is taken care of by the editor.
*
* ```javascript
* languages.registerHoverProvider('javascript', {
* provideHover(document, position, token) {
* return new Hover('I am a hover!');
* }
* });
* ```
*
* Registration is done using a [document selector](#DocumentSelector) which is either a language id, like `javascript` or
* a more complex [filter](#DocumentFilter) like `{ language: 'typescript', scheme: 'file' }`. Matching a document against such
* a selector will result in a [score](#languages.match) that is used to determine if and how a provider shall be used. When
* scores are equal the provider that came last wins. For features that allow full arity, like [hover](#languages.registerHoverProvider),
* the score is only checked to be `>0`, for other features, like [IntelliSense](#languages.registerCompletionItemProvider) the
* score is used for determining the order in which providers are asked to participate.
*/
export namespace languages {
/**
* Return the identifiers of all known languages.
* @return Promise resolving to an array of identifier strings.
*/
export function getLanguages(): Thenable<string[]>;
/**
* Set (and change) the [language](#TextDocument.languageId) that is associated
* with the given document.
*
* *Note* that calling this function will trigger the [`onDidCloseTextDocument`](#workspace.onDidCloseTextDocument) event
* followed by the [`onDidOpenTextDocument`](#workspace.onDidOpenTextDocument) event.
*
* @param document The document which language is to be changed
* @param languageId The new language identifier.
* @returns A thenable that resolves with the updated document.
*/
export function setTextDocumentLanguage(document: TextDocument, languageId: string): Thenable<TextDocument>;
/**
* Compute the match between a document [selector](#DocumentSelector) and a document. Values
* greater than zero mean the selector matches the document.
*
* A match is computed according to these rules:
* 1. When [`DocumentSelector`](#DocumentSelector) is an array, compute the match for each contained `DocumentFilter` or language identifier and take the maximum value.
* 2. A string will be desugared to become the `language`-part of a [`DocumentFilter`](#DocumentFilter), so `"fooLang"` is like `{ language: "fooLang" }`.
* 3. A [`DocumentFilter`](#DocumentFilter) will be matched against the document by comparing its parts with the document. The following rules apply:
* 1. When the `DocumentFilter` is empty (`{}`) the result is `0`
* 2. When `scheme`, `language`, or `pattern` are defined but one doesn’t match, the result is `0`
* 3. Matching against `*` gives a score of `5`, matching via equality or via a glob-pattern gives a score of `10`
* 4. The result is the maximum value of each match
*
* Samples:
* ```js
* // default document from disk (file-scheme)
* doc.uri; //'file:///my/file.js'
* doc.languageId; // 'javascript'
* match('javascript', doc); // 10;
* match({language: 'javascript'}, doc); // 10;
* match({language: 'javascript', scheme: 'file'}, doc); // 10;
* match('*', doc); // 5
* match('fooLang', doc); // 0
* match(['fooLang', '*'], doc); // 5
*
* // virtual document, e.g. from git-index
* doc.uri; // 'git:/my/file.js'
* doc.languageId; // 'javascript'
* match('javascript', doc); // 10;
* match({language: 'javascript', scheme: 'git'}, doc); // 10;
* match('*', doc); // 5
* ```
*
* @param selector A document selector.
* @param document A text document.
* @return A number `>0` when the selector matches and `0` when the selector does not match.
*/
export function match(selector: DocumentSelector, document: TextDocument): number;
/**
* An [event](#Event) which fires when the global set of diagnostics changes. This is
* newly added and removed diagnostics.
*/
export const onDidChangeDiagnostics: Event<DiagnosticChangeEvent>;
/**
* Get all diagnostics for a given resource. *Note* that this includes diagnostics from
* all extensions but *not yet* from the task framework.
*
* @param resource A resource
* @returns An array of [diagnostics](#Diagnostic) objects or an empty array.
*/
export function getDiagnostics(resource: Uri): Diagnostic[];
/**
* Get all diagnostics. *Note* that this includes diagnostics from
* all extensions but *not yet* from the task framework.
*
* @returns An array of uri-diagnostics tuples or an empty array.
*/
export function getDiagnostics(): [Uri, Diagnostic[]][];
/**
* Create a diagnostics collection.
*
* @param name The [name](#DiagnosticCollection.name) of the collection.
* @return A new diagnostic collection.
*/
export function createDiagnosticCollection(name?: string): DiagnosticCollection;
/**
* Register a completion provider.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and groups of equal score are sequentially asked for
* completion items. The process stops when one or many providers of a group return a
* result. A failing provider (rejected promise or exception) will not fail the whole
* operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A completion provider.
* @param triggerCharacters Trigger completion when the user types one of the characters, like `.` or `:`.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerCompletionItemProvider(selector: DocumentSelector, provider: CompletionItemProvider, ...triggerCharacters: string[]): Disposable;
/**
* Register a code action provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A code action provider.
* @param metadata Metadata about the kind of code actions the provider providers.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerCodeActionsProvider(selector: DocumentSelector, provider: CodeActionProvider, metadata?: CodeActionProviderMetadata): Disposable;
/**
* Register a code lens provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A code lens provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerCodeLensProvider(selector: DocumentSelector, provider: CodeLensProvider): Disposable;
/**
* Register a definition provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A definition provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerDefinitionProvider(selector: DocumentSelector, provider: DefinitionProvider): Disposable;
/**
* Register an implementation provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider An implementation provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerImplementationProvider(selector: DocumentSelector, provider: ImplementationProvider): Disposable;
/**
* Register a type definition provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A type definition provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerTypeDefinitionProvider(selector: DocumentSelector, provider: TypeDefinitionProvider): Disposable;
/**
* Register a declaration provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A declaration provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerDeclarationProvider(selector: DocumentSelector, provider: DeclarationProvider): Disposable;
/**
* Register a hover provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A hover provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerHoverProvider(selector: DocumentSelector, provider: HoverProvider): Disposable;
/**
* Register a document highlight provider.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and groups sequentially asked for document highlights.
* The process stops when a provider returns a `non-falsy` or `non-failure` result.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A document highlight provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerDocumentHighlightProvider(selector: DocumentSelector, provider: DocumentHighlightProvider): Disposable;
/**
* Register a document symbol provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A document symbol provider.
* @param metaData metadata about the provider
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerDocumentSymbolProvider(selector: DocumentSelector, provider: DocumentSymbolProvider, metaData?: DocumentSymbolProviderMetadata): Disposable;
/**
* Register a workspace symbol provider.
*
* Multiple providers can be registered. In that case providers are asked in parallel and
* the results are merged. A failing provider (rejected promise or exception) will not cause
* a failure of the whole operation.
*
* @param provider A workspace symbol provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerWorkspaceSymbolProvider(provider: WorkspaceSymbolProvider): Disposable;
/**
* Register a reference provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A reference provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerReferenceProvider(selector: DocumentSelector, provider: ReferenceProvider): Disposable;
/**
* Register a reference provider.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and the best-matching provider is used. Failure
* of the selected provider will cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A rename provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerRenameProvider(selector: DocumentSelector, provider: RenameProvider): Disposable;
/**
* Register a formatting provider for a document.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and the best-matching provider is used. Failure
* of the selected provider will cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A document formatting edit provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerDocumentFormattingEditProvider(selector: DocumentSelector, provider: DocumentFormattingEditProvider): Disposable;
/**
* Register a formatting provider for a document range.
*
* *Note:* A document range provider is also a [document formatter](#DocumentFormattingEditProvider)
* which means there is no need to [register](#languages.registerDocumentFormattingEditProvider) a document
* formatter when also registering a range provider.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and the best-matching provider is used. Failure
* of the selected provider will cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A document range formatting edit provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerDocumentRangeFormattingEditProvider(selector: DocumentSelector, provider: DocumentRangeFormattingEditProvider): Disposable;
/**
* Register a formatting provider that works on type. The provider is active when the user enables the setting `editor.formatOnType`.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and the best-matching provider is used. Failure
* of the selected provider will cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider An on type formatting edit provider.
* @param firstTriggerCharacter A character on which formatting should be triggered, like `}`.
* @param moreTriggerCharacter More trigger characters.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerOnTypeFormattingEditProvider(selector: DocumentSelector, provider: OnTypeFormattingEditProvider, firstTriggerCharacter: string, ...moreTriggerCharacter: string[]): Disposable;
/**
* Register a signature help provider.
*
* Multiple providers can be registered for a language. In that case providers are sorted
* by their [score](#languages.match) and called sequentially until a provider returns a
* valid result.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A signature help provider.
* @param triggerCharacters Trigger signature help when the user types one of the characters, like `,` or `(`.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerSignatureHelpProvider(selector: DocumentSelector, provider: SignatureHelpProvider, ...triggerCharacters: string[]): Disposable;
/**
* Register a document link provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A document link provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerDocumentLinkProvider(selector: DocumentSelector, provider: DocumentLinkProvider): Disposable;
/**
* Register a color provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged. A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A color provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerColorProvider(selector: DocumentSelector, provider: DocumentColorProvider): Disposable;
/**
* Register a folding range provider.
*
* Multiple providers can be registered for a language. In that case providers are asked in
* parallel and the results are merged.
* If multiple folding ranges start at the same position, only the range of the first registered provider is used.
* If a folding range overlaps with an other range that has a smaller position, it is also ignored.
*
* A failing provider (rejected promise or exception) will
* not cause a failure of the whole operation.
*
* @param selector A selector that defines the documents this provider is applicable to.
* @param provider A folding range provider.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerFoldingRangeProvider(selector: DocumentSelector, provider: FoldingRangeProvider): Disposable;
/**
* Set a [language configuration](#LanguageConfiguration) for a language.
*
* @param language A language identifier like `typescript`.
* @param configuration Language configuration.
* @return A [disposable](#Disposable) that unsets this configuration.
*/
export function setLanguageConfiguration(language: string, configuration: LanguageConfiguration): Disposable;
}
/**
* Represents the input box in the Source Control viewlet.
*/
export interface SourceControlInputBox {
/**
* Setter and getter for the contents of the input box.
*/
value: string;
/**
* A string to show as place holder in the input box to guide the user.
*/
placeholder: string;
}
interface QuickDiffProvider {
/**
* Provide a [uri](#Uri) to the original resource of any given resource uri.
*
* @param uri The uri of the resource open in a text editor.
* @param token A cancellation token.
* @return A thenable that resolves to uri of the matching original resource.
*/
provideOriginalResource?(uri: Uri, token: CancellationToken): ProviderResult<Uri>;
}
/**
* The theme-aware decorations for a
* [source control resource state](#SourceControlResourceState).
*/
export interface SourceControlResourceThemableDecorations {
/**
* The icon path for a specific
* [source control resource state](#SourceControlResourceState).
*/
readonly iconPath?: string | Uri;
}
/**
* The decorations for a [source control resource state](#SourceControlResourceState).
* Can be independently specified for light and dark themes.
*/
export interface SourceControlResourceDecorations extends SourceControlResourceThemableDecorations {
/**
* Whether the [source control resource state](#SourceControlResourceState) should
* be striked-through in the UI.
*/
readonly strikeThrough?: boolean;
/**
* Whether the [source control resource state](#SourceControlResourceState) should
* be faded in the UI.
*/
readonly faded?: boolean;
/**
* The title for a specific
* [source control resource state](#SourceControlResourceState).
*/
readonly tooltip?: string;
/**
* The light theme decorations.
*/
readonly light?: SourceControlResourceThemableDecorations;
/**
* The dark theme decorations.
*/
readonly dark?: SourceControlResourceThemableDecorations;
}
/**
* An source control resource state represents the state of an underlying workspace
* resource within a certain [source control group](#SourceControlResourceGroup).
*/
export interface SourceControlResourceState {
/**
* The [uri](#Uri) of the underlying resource inside the workspace.
*/
readonly resourceUri: Uri;
/**
* The [command](#Command) which should be run when the resource
* state is open in the Source Control viewlet.
*/
readonly command?: Command;
/**
* The [decorations](#SourceControlResourceDecorations) for this source control
* resource state.
*/
readonly decorations?: SourceControlResourceDecorations;
}
/**
* A source control resource group is a collection of
* [source control resource states](#SourceControlResourceState).
*/
export interface SourceControlResourceGroup {
/**
* The id of this source control resource group.
*/
readonly id: string;
/**
* The label of this source control resource group.
*/
label: string;
/**
* Whether this source control resource group is hidden when it contains
* no [source control resource states](#SourceControlResourceState).
*/
hideWhenEmpty?: boolean;
/**
* This group's collection of
* [source control resource states](#SourceControlResourceState).
*/
resourceStates: SourceControlResourceState[];
/**
* Dispose this source control resource group.
*/
dispose(): void;
}
/**
* An source control is able to provide [resource states](#SourceControlResourceState)
* to the editor and interact with the editor in several source control related ways.
*/
export interface SourceControl {
/**
* The id of this source control.
*/
readonly id: string;
/**
* The human-readable label of this source control.
*/
readonly label: string;
/**
* The (optional) Uri of the root of this source control.
*/
readonly rootUri: Uri | undefined;
/**
* The [input box](#SourceControlInputBox) for this source control.
*/
readonly inputBox: SourceControlInputBox;
/**
* The UI-visible count of [resource states](#SourceControlResourceState) of
* this source control.
*
* Equals to the total number of [resource state](#SourceControlResourceState)
* of this source control, if undefined.
*/
count?: number;
/**
* An optional [quick diff provider](#QuickDiffProvider).
*/
quickDiffProvider?: QuickDiffProvider;
/**
* Optional commit template string.
*
* The Source Control viewlet will populate the Source Control
* input with this value when appropriate.
*/
commitTemplate?: string;
/**
* Optional accept input command.
*
* This command will be invoked when the user accepts the value
* in the Source Control input.
*/
acceptInputCommand?: Command;
/**
* Optional status bar commands.
*
* These commands will be displayed in the editor's status bar.
*/
statusBarCommands?: Command[];
/**
* Create a new [resource group](#SourceControlResourceGroup).
*/
createResourceGroup(id: string, label: string): SourceControlResourceGroup;
/**
* Dispose this source control.
*/
dispose(): void;
}
export namespace scm {
/**
* ~~The [input box](#SourceControlInputBox) for the last source control
* created by the extension.~~
*
* @deprecated Use SourceControl.inputBox instead
*/
export const inputBox: SourceControlInputBox;
/**
* Creates a new [source control](#SourceControl) instance.
*
* @param id An `id` for the source control. Something short, eg: `git`.
* @param label A human-readable string for the source control. Eg: `Git`.
* @param rootUri An optional Uri of the root of the source control. Eg: `Uri.parse(workspaceRoot)`.
* @return An instance of [source control](#SourceControl).
*/
export function createSourceControl(id: string, label: string, rootUri?: Uri): SourceControl;
}
/**
* Configuration for a debug session.
*/
export interface DebugConfiguration {
/**
* The type of the debug session.
*/
type: string;
/**
* The name of the debug session.
*/
name: string;
/**
* The request type of the debug session.
*/
request: string;
/**
* Additional debug type specific properties.
*/
[key: string]: any;
}
/**
* A debug session.
*/
export interface DebugSession {
/**
* The unique ID of this debug session.
*/
readonly id: string;
/**
* The debug session's type from the [debug configuration](#DebugConfiguration).
*/
readonly type: string;
/**
* The debug session's name from the [debug configuration](#DebugConfiguration).
*/
readonly name: string;
/**
* The workspace folder of this session or `undefined` for a folderless setup.
*/
readonly workspaceFolder: WorkspaceFolder | undefined;
/**
* The "resolved" [debug configuration](#DebugConfiguration) of this session.
* "Resolved" means that
* - all variables have been substituted and
* - platform specific attribute sections have been "flattened" for the matching platform and removed for non-matching platforms.
*/
readonly configuration: DebugConfiguration;
/**
* Send a custom request to the debug adapter.
*/
customRequest(command: string, args?: any): Thenable<any>;
}
/**
* A custom Debug Adapter Protocol event received from a [debug session](#DebugSession).
*/
export interface DebugSessionCustomEvent {
/**
* The [debug session](#DebugSession) for which the custom event was received.
*/
session: DebugSession;
/**
* Type of event.
*/
event: string;
/**
* Event specific information.
*/
body?: any;
}
/**
* A debug configuration provider allows to add the initial debug configurations to a newly created launch.json
* and to resolve a launch configuration before it is used to start a new debug session.
* A debug configuration provider is registered via #debug.registerDebugConfigurationProvider.
*/
export interface DebugConfigurationProvider {
/**
* Provides initial [debug configuration](#DebugConfiguration). If more than one debug configuration provider is
* registered for the same type, debug configurations are concatenated in arbitrary order.
*
* @param folder The workspace folder for which the configurations are used or `undefined` for a folderless setup.
* @param token A cancellation token.
* @return An array of [debug configurations](#DebugConfiguration).
*/
provideDebugConfigurations?(folder: WorkspaceFolder | undefined, token?: CancellationToken): ProviderResult<DebugConfiguration[]>;
/**
* Resolves a [debug configuration](#DebugConfiguration) by filling in missing values or by adding/changing/removing attributes.
* If more than one debug configuration provider is registered for the same type, the resolveDebugConfiguration calls are chained
* in arbitrary order and the initial debug configuration is piped through the chain.
* Returning the value 'undefined' prevents the debug session from starting.
* Returning the value 'null' prevents the debug session from starting and opens the underlying debug configuration instead.
*
* @param folder The workspace folder from which the configuration originates from or `undefined` for a folderless setup.
* @param debugConfiguration The [debug configuration](#DebugConfiguration) to resolve.
* @param token A cancellation token.
* @return The resolved debug configuration or undefined or null.
*/
resolveDebugConfiguration?(folder: WorkspaceFolder | undefined, debugConfiguration: DebugConfiguration, token?: CancellationToken): ProviderResult<DebugConfiguration>;
}
/**
* Represents a debug adapter executable and optional arguments and runtime options passed to it.
*/
export class DebugAdapterExecutable {
/**
* Creates a description for a debug adapter based on an executable program.
*
* @param command The command or executable path that implements the debug adapter.
* @param args Optional arguments to be passed to the command or executable.
* @param options Optional options to be used when starting the command or executable.
*/
constructor(command: string, args?: string[], options?: DebugAdapterExecutableOptions);
/**
* The command or path of the debug adapter executable.
* A command must be either an absolute path of an executable or the name of an command to be looked up via the PATH environment variable.
* The special value 'node' will be mapped to VS Code's built-in Node.js runtime.
*/
readonly command: string;
/**
* The arguments passed to the debug adapter executable. Defaults to an empty array.
*/
readonly args: string[];
/**
* Optional options to be used when the debug adapter is started.
* Defaults to undefined.
*/
readonly options?: DebugAdapterExecutableOptions;
}
/**
* Options for a debug adapter executable.
*/
export interface DebugAdapterExecutableOptions {
/**
* The additional environment of the executed program or shell. If omitted
* the parent process' environment is used. If provided it is merged with
* the parent process' environment.
*/
env?: { [key: string]: string };
/**
* The current working directory for the executed debug adapter.
*/
cwd?: string;
}
/**
* Represents a debug adapter running as a socket based server.
*/
export class DebugAdapterServer {
/**
* The port.
*/
readonly port: number;
/**
* The host.
*/
readonly host?: string;
/**
* Create a description for a debug adapter running as a socket based server.
*/
constructor(port: number, host?: string);
}
export type DebugAdapterDescriptor = DebugAdapterExecutable | DebugAdapterServer;
export interface DebugAdapterDescriptorFactory {
/**
* 'createDebugAdapterDescriptor' is called at the start of a debug session to provide details about the debug adapter to use.
* These details must be returned as objects of type [DebugAdapterDescriptor](#DebugAdapterDescriptor).
* Currently two types of debug adapters are supported:
* - a debug adapter executable is specified as a command path and arguments (see [DebugAdapterExecutable](#DebugAdapterExecutable)),
* - a debug adapter server reachable via a communication port (see [DebugAdapterServer](#DebugAdapterServer)).
* If the method is not implemented the default behavior is this:
* createDebugAdapter(session: DebugSession, executable: DebugAdapterExecutable) {
* if (typeof session.configuration.debugServer === 'number') {
* return new DebugAdapterServer(session.configuration.debugServer);
* }
* return executable;
* }
* @param session The [debug session](#DebugSession) for which the debug adapter will be used.
* @param executable The debug adapter's executable information as specified in the package.json (or undefined if no such information exists).
* @return a [debug adapter descriptor](#DebugAdapterDescriptor) or undefined.
*/
createDebugAdapterDescriptor(session: DebugSession, executable: DebugAdapterExecutable | undefined): ProviderResult<DebugAdapterDescriptor>;
}
/**
* Represents the debug console.
*/
export interface DebugConsole {
/**
* Append the given value to the debug console.
*
* @param value A string, falsy values will not be printed.
*/
append(value: string): void;
/**
* Append the given value and a line feed character
* to the debug console.
*
* @param value A string, falsy values will be printed.
*/
appendLine(value: string): void;
}
/**
* An event describing the changes to the set of [breakpoints](#Breakpoint).
*/
export interface BreakpointsChangeEvent {
/**
* Added breakpoints.
*/
readonly added: Breakpoint[];
/**
* Removed breakpoints.
*/
readonly removed: Breakpoint[];
/**
* Changed breakpoints.
*/
readonly changed: Breakpoint[];
}
/**
* The base class of all breakpoint types.
*/
export class Breakpoint {
/**
* The unique ID of the breakpoint.
*/
readonly id: string;
/**
* Is breakpoint enabled.
*/
readonly enabled: boolean;
/**
* An optional expression for conditional breakpoints.
*/
readonly condition?: string;
/**
* An optional expression that controls how many hits of the breakpoint are ignored.
*/
readonly hitCondition?: string;
/**
* An optional message that gets logged when this breakpoint is hit. Embedded expressions within {} are interpolated by the debug adapter.
*/
readonly logMessage?: string;
protected constructor(enabled?: boolean, condition?: string, hitCondition?: string, logMessage?: string);
}
/**
* A breakpoint specified by a source location.
*/
export class SourceBreakpoint extends Breakpoint {
/**
* The source and line position of this breakpoint.
*/
readonly location: Location;
/**
* Create a new breakpoint for a source location.
*/
constructor(location: Location, enabled?: boolean, condition?: string, hitCondition?: string, logMessage?: string);
}
/**
* A breakpoint specified by a function name.
*/
export class FunctionBreakpoint extends Breakpoint {
/**
* The name of the function to which this breakpoint is attached.
*/
readonly functionName: string;
/**
* Create a new function breakpoint.
*/
constructor(functionName: string, enabled?: boolean, condition?: string, hitCondition?: string, logMessage?: string);
}
/**
* Namespace for debug functionality.
*/
export namespace debug {
/**
* The currently active [debug session](#DebugSession) or `undefined`. The active debug session is the one
* represented by the debug action floating window or the one currently shown in the drop down menu of the debug action floating window.
* If no debug session is active, the value is `undefined`.
*/
export let activeDebugSession: DebugSession | undefined;
/**
* The currently active [debug console](#DebugConsole).
* If no debug session is active, output sent to the debug console is not shown.
*/
export let activeDebugConsole: DebugConsole;
/**
* List of breakpoints.
*/
export let breakpoints: Breakpoint[];
/**
* An [event](#Event) which fires when the [active debug session](#debug.activeDebugSession)
* has changed. *Note* that the event also fires when the active debug session changes
* to `undefined`.
*/
export const onDidChangeActiveDebugSession: Event<DebugSession | undefined>;
/**
* An [event](#Event) which fires when a new [debug session](#DebugSession) has been started.
*/
export const onDidStartDebugSession: Event<DebugSession>;
/**
* An [event](#Event) which fires when a custom DAP event is received from the [debug session](#DebugSession).
*/
export const onDidReceiveDebugSessionCustomEvent: Event<DebugSessionCustomEvent>;
/**
* An [event](#Event) which fires when a [debug session](#DebugSession) has terminated.
*/
export const onDidTerminateDebugSession: Event<DebugSession>;
/**
* An [event](#Event) that is emitted when the set of breakpoints is added, removed, or changed.
*/
export const onDidChangeBreakpoints: Event<BreakpointsChangeEvent>;
/**
* Register a [debug configuration provider](#DebugConfigurationProvider) for a specific debug type.
* More than one provider can be registered for the same type.
*
* @param type The debug type for which the provider is registered.
* @param provider The [debug configuration provider](#DebugConfigurationProvider) to register.
* @return A [disposable](#Disposable) that unregisters this provider when being disposed.
*/
export function registerDebugConfigurationProvider(debugType: string, provider: DebugConfigurationProvider): Disposable;
/**
* Register a [debug adapter descriptor factory](#DebugAdapterDescriptorFactory) for a specific debug type.
* An extension is only allowed to register a DebugAdapterDescriptorFactory for the debug type(s) defined by the extension. Otherwise an error is thrown.
* Registering more than one DebugAdapterDescriptorFactory for a debug type results in an error.
*
* @param debugType The debug type for which the factory is registered.
* @param factory The [debug adapter descriptor factory](#DebugAdapterDescriptorFactory) to register.
* @return A [disposable](#Disposable) that unregisters this factory when being disposed.
*/
export function registerDebugAdapterDescriptorFactory(debugType: string, factory: DebugAdapterDescriptorFactory): Disposable;
/**
* Start debugging by using either a named launch or named compound configuration,
* or by directly passing a [DebugConfiguration](#DebugConfiguration).
* The named configurations are looked up in '.vscode/launch.json' found in the given folder.
* Before debugging starts, all unsaved files are saved and the launch configurations are brought up-to-date.
* Folder specific variables used in the configuration (e.g. '${workspaceFolder}') are resolved against the given folder.
* @param folder The [workspace folder](#WorkspaceFolder) for looking up named configurations and resolving variables or `undefined` for a non-folder setup.
* @param nameOrConfiguration Either the name of a debug or compound configuration or a [DebugConfiguration](#DebugConfiguration) object.
* @return A thenable that resolves when debugging could be successfully started.
*/
export function startDebugging(folder: WorkspaceFolder | undefined, nameOrConfiguration: string | DebugConfiguration): Thenable<boolean>;
/**
* Add breakpoints.
* @param breakpoints The breakpoints to add.
*/
export function addBreakpoints(breakpoints: Breakpoint[]): void;
/**
* Remove breakpoints.
* @param breakpoints The breakpoints to remove.
*/
export function removeBreakpoints(breakpoints: Breakpoint[]): void;
}
/**
* Namespace for dealing with installed extensions. Extensions are represented
* by an [extension](#Extension)-interface which enables reflection on them.
*
* Extension writers can provide APIs to other extensions by returning their API public
* surface from the `activate`-call.
*
* ```javascript
* export function activate(context: vscode.ExtensionContext) {
* let api = {
* sum(a, b) {
* return a + b;
* },
* mul(a, b) {
* return a * b;
* }
* };
* // 'export' public api-surface
* return api;
* }
* ```
* When depending on the API of another extension add an `extensionDependency`-entry
* to `package.json`, and use the [getExtension](#extensions.getExtension)-function
* and the [exports](#Extension.exports)-property, like below:
*
* ```javascript
* let mathExt = extensions.getExtension('genius.math');
* let importedApi = mathExt.exports;
*
* console.log(importedApi.mul(42, 1));
* ```
*/
export namespace extensions {
/**
* Get an extension by its full identifier in the form of: `publisher.name`.
*
* @param extensionId An extension identifier.
* @return An extension or `undefined`.
*/
export function getExtension(extensionId: string): Extension<any> | undefined;
/**
* Get an extension its full identifier in the form of: `publisher.name`.
*
* @param extensionId An extension identifier.
* @return An extension or `undefined`.
*/
export function getExtension<T>(extensionId: string): Extension<T> | undefined;
/**
* All extensions currently known to the system.
*/
export let all: Extension<any>[];
}
}
/**
* Thenable is a common denominator between ES6 promises, Q, jquery.Deferred, WinJS.Promise,
* and others. This API makes no assumption about what promise library is being used which
* enables reusing existing code without migrating to a specific promise implementation. Still,
* we recommend the use of native promises which are available in this editor.
*/
interface Thenable<T> {
/**
* Attaches callbacks for the resolution and/or rejection of the Promise.
* @param onfulfilled The callback to execute when the Promise is resolved.
* @param onrejected The callback to execute when the Promise is rejected.
* @returns A Promise for the completion of which ever callback is executed.
*/
then<TResult>(onfulfilled?: (value: T) => TResult | Thenable<TResult>, onrejected?: (reason: any) => TResult | Thenable<TResult>): Thenable<TResult>;
then<TResult>(onfulfilled?: (value: T) => TResult | Thenable<TResult>, onrejected?: (reason: any) => void): Thenable<TResult>;
}<|fim▁end|> | */
readonly onDidReceiveMessage: Event<any>;
/** |
<|file_name|>game013.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import random
import sys
import pygame
import classes.board
import classes.extras as ex
import classes.game_driver as gd
import classes.level_controller as lc
class Board(gd.BoardGame):
def __init__(self, mainloop, speaker, config, screen_w, screen_h):
self.level = lc.Level(self, mainloop, 10, 8)
gd.BoardGame.__init__(self, mainloop, speaker, config, screen_w, screen_h, 15, 9)
def create_game_objects(self, level=1):
self.board.draw_grid = False
self.vis_buttons = [1, 1, 1, 1, 1, 1, 1, 0, 0]
self.mainloop.info.hide_buttonsa(self.vis_buttons)
# create non-movable objects
s = 100
v = 255
h = random.randrange(0, 225)
font_color = ex.hsv_to_rgb(h, 255, 140)
if self.mainloop.scheme is not None:
color0 = self.mainloop.scheme.u_color
else:
color0 = ex.hsv_to_rgb(h, 40, 230) # highlight 1
font_color = ex.hsv_to_rgb(h, 255, 140)
# data = [x_count, y_count, letter_count, top_limit, ordered]
if self.level.lvl == 1:
data = [15, 9, 15, 0, 1]
elif self.level.lvl == 2:
data = [15, 9, 15, 1, 1]
elif self.level.lvl == 3:
data = [15, 9, 15, 2, 1]
elif self.level.lvl == 4:
data = [15, 9, 15, 3, 1]
elif self.level.lvl == 5:
data = [15, 9, 30, 4, 2]
elif self.level.lvl == 6:
data = [15, 9, 30, 5, 2]
elif self.level.lvl == 7:
data = [15, 9, 30, 6, 3]
elif self.level.lvl == 8:
data = [15, 9, 30, 7, 3]
self.points = data[4]
letter_table = []
letter_table.extend(self.lang.alphabet_lc)
letter_table.extend(self.lang.alphabet_uc)
letter_table.extend(self.lang.accents_lc)
letter_table.extend(self.lang.accents_uc)
self.words = self.lang.di[data[3]]
self.data = data
self.board.set_animation_constraints(0, data[0], 2, data[1])
self.layout.update_layout(data[0], data[1])
self.board.level_start(data[0], data[1], self.layout.scale)
self.word = self.words[random.randrange(1, self.words[0])]
if sys.version_info < (3, 0):
self.wordu = unicode(self.word, "utf-8")
word_len = len(self.wordu)
self.word_l = []
# dirty way of replacing the word with letters from alphabet
for each in self.wordu:
for i in range(len(letter_table)):
if each == unicode(letter_table[i], "utf-8"):
self.word_l.append(letter_table[i])
else:
word_len = len(self.word)
self.word_l = self.word
self.num_list = []
choice_list = self.lang.alphabet_lc + self.lang.alphabet_uc
for i in range(data[2] - word_len): # adding noice letters
index = random.randrange(0, len(choice_list))
self.num_list.append(choice_list[index])
shuffled = self.num_list[:]
for i in range(word_len):
shuffled.append(self.word_l[i])
random.shuffle(shuffled)
color = ((255, 255, 255))
# create table to store 'binary' solution
self.solution_grid = [1 for x in range(data[0])]
x = 0
y = 4
for i in range(len(shuffled)):
if self.mainloop.scheme is not None:
number_color = self.mainloop.scheme.u_font_color
else:
h = random.randrange(0, 255, 5)
number_color = ex.hsv_to_rgb(h, s, v) # highlight 1
caption = shuffled[i]
self.board.add_unit(x, y, 1, 1, classes.board.Letter, caption, number_color, "", 1)
self.board.ships[-1].font_color = ex.hsv_to_rgb(h, 255, 140)
x += 1
if x >= data[0]:
x = 0
y += 1
# find position of first door square
x = (data[0] - word_len) // 2
# add objects to the board
for i in range(word_len):
self.board.add_door(x + i, 2, 1, 1, classes.board.Door, "", color, "")
self.board.units[i].door_outline = True<|fim▁hole|> self.board.add_unit(x + word_len, 2, data[0] - x - word_len, 1, classes.board.Obstacle, "", color0)
self.board.add_unit(0, 0, data[0], 1, classes.board.Letter,
self.d["Build the following word using the letters below."], color0, "", 3)
self.board.ships[-1].immobilize()
self.board.ships[-1].font_color = font_color
self.board.ships[-1].speaker_val = self.dp["Build the following word using the letters below."]
self.board.ships[-1].speaker_val_update = False
self.board.add_unit(0, 1, data[0], 1, classes.board.Letter, self.word, color0, "", 0)
self.board.ships[-1].immobilize()
self.board.ships[-1].font_color = font_color
self.outline_all(0, 1)
def handle(self, event):
gd.BoardGame.handle(self, event) # send event handling up
if event.type == pygame.MOUSEBUTTONUP:
for each in self.board.units:
if each.is_door is True:
self.board.all_sprites_list.move_to_front(each)
def update(self, game):
game.fill((255, 255, 255))
gd.BoardGame.update(self, game) # rest of painting done by parent
def check_result(self):
result = [" " for i in range(self.data[0])]
if self.board.grid[2] == self.solution_grid:
for i in range(len(self.board.ships)):
if self.board.ships[i].grid_y == 2:
result[self.board.ships[i].grid_x] = self.board.ships[i].value
result_s = ''.join(result).strip()
if self.word == result_s:
# self.update_score(self.points)
self.level.next_board()
else:
self.level.try_again()
else:
self.level.try_again()<|fim▁end|> | self.board.all_sprites_list.move_to_front(self.board.units[i])
self.board.add_unit(0, 2, x, 1, classes.board.Obstacle, "", color0) |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>"""Support for Roku API emulation."""
import voluptuous as vol
from homeassistant import config_entries, util
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
from .binding import EmulatedRoku
from .config_flow import configured_servers
from .const import (
CONF_ADVERTISE_IP, CONF_ADVERTISE_PORT, CONF_HOST_IP, CONF_LISTEN_PORT,
CONF_SERVERS, CONF_UPNP_BIND_MULTICAST, DOMAIN)
SERVER_CONFIG_SCHEMA = vol.Schema({
vol.Required(CONF_NAME): cv.string,
vol.Required(CONF_LISTEN_PORT): cv.port,
vol.Optional(CONF_HOST_IP): cv.string,
vol.Optional(CONF_ADVERTISE_IP): cv.string,
vol.Optional(CONF_ADVERTISE_PORT): cv.port,
vol.Optional(CONF_UPNP_BIND_MULTICAST): cv.boolean
})
CONFIG_SCHEMA = vol.Schema({
DOMAIN: vol.Schema({
vol.Required(CONF_SERVERS):
vol.All(cv.ensure_list, [SERVER_CONFIG_SCHEMA]),
}),<|fim▁hole|>async def async_setup(hass, config):
"""Set up the emulated roku component."""
conf = config.get(DOMAIN)
if conf is None:
return True
existing_servers = configured_servers(hass)
for entry in conf[CONF_SERVERS]:
if entry[CONF_NAME] not in existing_servers:
hass.async_create_task(hass.config_entries.flow.async_init(
DOMAIN,
context={'source': config_entries.SOURCE_IMPORT},
data=entry
))
return True
async def async_setup_entry(hass, config_entry):
"""Set up an emulated roku server from a config entry."""
config = config_entry.data
if DOMAIN not in hass.data:
hass.data[DOMAIN] = {}
name = config[CONF_NAME]
listen_port = config[CONF_LISTEN_PORT]
host_ip = config.get(CONF_HOST_IP) or util.get_local_ip()
advertise_ip = config.get(CONF_ADVERTISE_IP)
advertise_port = config.get(CONF_ADVERTISE_PORT)
upnp_bind_multicast = config.get(CONF_UPNP_BIND_MULTICAST)
server = EmulatedRoku(hass, name, host_ip, listen_port,
advertise_ip, advertise_port, upnp_bind_multicast)
hass.data[DOMAIN][name] = server
return await server.setup()
async def async_unload_entry(hass, entry):
"""Unload a config entry."""
name = entry.data[CONF_NAME]
server = hass.data[DOMAIN].pop(name)
return await server.unload()<|fim▁end|> | }, extra=vol.ALLOW_EXTRA)
|
<|file_name|>ConfirmSubscription.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
###############################################################################
#
# ConfirmSubscription
# Verifies that the endpoint owner wishes to receive messages by verifying the token sent during the Subscribe action.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#<|fim▁hole|># http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
#
#
###############################################################################
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class ConfirmSubscription(Choreography):
def __init__(self, temboo_session):
"""
Create a new instance of the ConfirmSubscription Choreo. A TembooSession object, containing a valid
set of Temboo credentials, must be supplied.
"""
super(ConfirmSubscription, self).__init__(temboo_session, '/Library/Amazon/SNS/ConfirmSubscription')
def new_input_set(self):
return ConfirmSubscriptionInputSet()
def _make_result_set(self, result, path):
return ConfirmSubscriptionResultSet(result, path)
def _make_execution(self, session, exec_id, path):
return ConfirmSubscriptionChoreographyExecution(session, exec_id, path)
class ConfirmSubscriptionInputSet(InputSet):
"""
An InputSet with methods appropriate for specifying the inputs to the ConfirmSubscription
Choreo. The InputSet object is used to specify input parameters when executing this Choreo.
"""
def set_AWSAccessKeyId(self, value):
"""
Set the value of the AWSAccessKeyId input for this Choreo. ((required, string) The Access Key ID provided by Amazon Web Services.)
"""
super(ConfirmSubscriptionInputSet, self)._set_input('AWSAccessKeyId', value)
def set_AWSSecretKeyId(self, value):
"""
Set the value of the AWSSecretKeyId input for this Choreo. ((required, string) The Secret Key ID provided by Amazon Web Services.)
"""
super(ConfirmSubscriptionInputSet, self)._set_input('AWSSecretKeyId', value)
def set_AuthenticateOnUnsubscribed(self, value):
"""
Set the value of the AuthenticateOnUnsubscribed input for this Choreo. ((optional, boolean) Indicates that you want to disable the ability to unsubscribe from the subscription without authenticating. Specify 1 to enable this flag.)
"""
super(ConfirmSubscriptionInputSet, self)._set_input('AuthenticateOnUnsubscribed', value)
def set_Token(self, value):
"""
Set the value of the Token input for this Choreo. ((required, string) The short-lived token sent to an endpoint during the Subscribe action.)
"""
super(ConfirmSubscriptionInputSet, self)._set_input('Token', value)
def set_TopicArn(self, value):
"""
Set the value of the TopicArn input for this Choreo. ((required, string) The ARN of the topic you want to confirm a subscription for.)
"""
super(ConfirmSubscriptionInputSet, self)._set_input('TopicArn', value)
def set_UserRegion(self, value):
"""
Set the value of the UserRegion input for this Choreo. ((optional, string) The AWS region that corresponds to the SNS endpoint you wish to access. The default region is "us-east-1". See description below for valid values.)
"""
super(ConfirmSubscriptionInputSet, self)._set_input('UserRegion', value)
class ConfirmSubscriptionResultSet(ResultSet):
"""
A ResultSet with methods tailored to the values returned by the ConfirmSubscription Choreo.
The ResultSet object is used to retrieve the results of a Choreo execution.
"""
def getJSONFromString(self, str):
return json.loads(str)
def get_Response(self):
"""
Retrieve the value for the "Response" output from this Choreo execution. ((xml) The response from Amazon.)
"""
return self._output.get('Response', None)
class ConfirmSubscriptionChoreographyExecution(ChoreographyExecution):
def _make_result_set(self, response, path):
return ConfirmSubscriptionResultSet(response, path)<|fim▁end|> | # 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
# |
<|file_name|>DeferredVectorBuilder.java<|end_file_name|><|fim▁begin|>package org.renjin.invoke.codegen;
import com.google.common.collect.Lists;
import com.sun.codemodel.*;
import org.apache.commons.math.complex.Complex;
import org.renjin.invoke.annotations.PreserveAttributeStyle;
import org.renjin.invoke.model.JvmMethod;
import org.renjin.invoke.model.PrimitiveModel;
import org.renjin.primitives.vector.DeferredComputation;
import org.renjin.sexp.*;
import java.util.List;
import static com.sun.codemodel.JExpr.lit;
public class DeferredVectorBuilder {
public static final int LENGTH_THRESHOLD = 100;
private final JExpression contextArgument;
private JCodeModel codeModel;
private PrimitiveModel primitive;
private JvmMethod overload;
private int arity;
private JDefinedClass vectorClass;
private VectorType type;
private List<DeferredArgument> arguments = Lists.newArrayList();
private JFieldVar lengthField;
public DeferredVectorBuilder(JCodeModel codeModel, JExpression contextArgument, PrimitiveModel primitive, JvmMethod overload) {
this.codeModel = codeModel;
this.primitive = primitive;
this.overload = overload;
this.arity = overload.getPositionalFormals().size();
this.contextArgument = contextArgument;
if(overload.getReturnType().equals(double.class)) {
type = VectorType.DOUBLE;
} else if(overload.getReturnType().equals(boolean.class)) {
type = VectorType.LOGICAL;
} else if(overload.getReturnType().equals(Logical.class)) {
type = VectorType.LOGICAL;
} else if(overload.getReturnType().equals(int.class)) {
type = VectorType.INTEGER;
} else if(overload.getReturnType().equals(Complex.class)) {
type = VectorType.COMPLEX;
} else if(overload.getReturnType().equals(byte.class)) {
type = VectorType.RAW;
} else {
throw new UnsupportedOperationException(overload.getReturnType().toString());
}
}
public void buildClass() {
try {
vectorClass = codeModel._class( WrapperGenerator2.toFullJavaName(primitive.getName()) + "$deferred_" + typeSuffix() );
} catch (JClassAlreadyExistsException e) {
throw new RuntimeException(e);
}
vectorClass._extends(type.baseClass);
vectorClass._implements(DeferredComputation.class);
for(int i=0;i!=arity;++i) {
arguments.add(new DeferredArgument(overload.getPositionalFormals().get(i), i));
}
this.lengthField = vectorClass.field(JMod.PRIVATE, codeModel._ref(int.class), "length");
writeConstructor();
implementAccessor();
implementLength();
implementAttributeSetter();
implementGetOperands();
implementGetComputationName();
implementStaticApply();
implementIsConstantAccess();
implementGetComputationDepth();
if(overload.isPassNA() && overload.getReturnType().equals(boolean.class)) {
overrideIsNaWithConstantValue();
}
}
private void implementIsConstantAccess() {
JMethod method = vectorClass.method(JMod.PUBLIC, boolean.class, "isConstantAccessTime");
JExpression condition = null;
for(DeferredArgument arg : arguments) {
JExpression operandIsConstant = arg.valueField.invoke("isConstantAccessTime");
if(condition == null) {
condition = operandIsConstant;
} else {
condition = condition.cand(operandIsConstant);
}
}
method.body()._return(condition);
}
private void implementGetComputationDepth() {
JMethod method = vectorClass.method(JMod.PUBLIC, int.class, "getComputationDepth");
JVar depth = method.body().decl(codeModel._ref(int.class), "depth",
arguments.get(0).valueField.invoke("getComputationDepth"));
for(int i=1;i<arguments.size();++i) {
method.body().assign(depth, codeModel.ref(Math.class).staticInvoke("max")
.arg(depth)
.arg(arguments.get(1).valueField.invoke("getComputationDepth")));
}
method.body()._return(depth.plus(JExpr.lit(1)));
}
private void implementGetOperands() {
JMethod method = vectorClass.method(JMod.PUBLIC, Vector[].class, "getOperands");
JArray array = JExpr.newArray(codeModel.ref(Vector.class));
for(DeferredArgument arg : arguments) {
array.add(arg.valueField);
}
method.body()._return(array);
}
private void implementGetComputationName() {
JMethod method = vectorClass.method(JMod.PUBLIC, String.class, "getComputationName");
method.body()._return(lit(primitive.getName()));
}
private String typeSuffix() {
StringBuilder suffix = new StringBuilder();
for(JvmMethod.Argument formal : overload.getPositionalFormals()) {
suffix.append(abbrev(formal.getClazz()));
}
return suffix.toString();
}
private String abbrev(Class clazz) {
if(clazz.equals(double.class)) {
return "d";
} else if(clazz.equals(boolean.class)) {
return "b";
} else if(clazz.equals(String.class)) {
return "s";
} else if(clazz.equals(int.class)) {
return "i";
} else if(clazz.equals(Complex.class)) {
return "z";
} else if(clazz.equals(byte.class)) {
return "r";
} else {
throw new UnsupportedOperationException(clazz.toString());
}
}
public void maybeReturn(JBlock parent, JExpression cycleCount, List<JExpression> arguments) {
JExpression condition = cycleCount.gt(lit(LENGTH_THRESHOLD));
for(JExpression arg : arguments) {
condition = condition.cor(arg._instanceof(codeModel.ref(DeferredComputation.class)));
}
JBlock ifBig = parent._if(condition)._then();
JExpression attributes = copyAttributes(arguments);
JInvocation newInvocation = JExpr._new(vectorClass);
for(JExpression arg : arguments) {
newInvocation.arg(arg);
}
newInvocation.arg(attributes);
ifBig._return(contextArgument.invoke("simplify").arg(newInvocation));
}
private JExpression copyAttributes(List<JExpression> arguments) {
if(overload.getPreserveAttributesStyle() == PreserveAttributeStyle.NONE) {
return codeModel.ref(AttributeMap.class).staticRef("EMPTY");
} else {
if(arity == 1) {
return copyAttributes(arguments.get(0));
} else if(arity == 2) {
return copyAttributes(arguments.get(0), arguments.get(1));
} else {
throw new UnsupportedOperationException("arity = " + arity);
}
}
}
private JExpression copyAttributes(JExpression arg0, JExpression arg1) {
String combineMethod;
switch(overload.getPreserveAttributesStyle()) {
case ALL:
combineMethod = "combineAttributes";
break;
case SPECIAL:
combineMethod = "combineStructuralAttributes";
break;
default:
throw new UnsupportedOperationException();
}
return codeModel.ref(AttributeMap.class).staticInvoke(combineMethod)
.arg(arg0)
.arg(arg1);
}
private JExpression copyAttributes(JExpression arg) {
if(overload.getPreserveAttributesStyle() == PreserveAttributeStyle.ALL) {
return arg.invoke("getAttributes");
} else if(overload.getPreserveAttributesStyle() == PreserveAttributeStyle.SPECIAL) {
return arg.invoke("getAttributes").invoke("copyStructural");
} else {
throw new UnsupportedOperationException();
}
}
private void writeConstructor() {
// public DoubleBinaryFnVector(Vector arg0, Vector arg1, AttributeMap attributes) {
// super(attributes);
// this.x = x;
// this.y = y;
// this.fn = fn;
// this.xLength = x.length();
// this.yLength = y.length();
// this.length = Math.max(xLength, yLength);
// }
JMethod ctor = vectorClass.constructor(JMod.PUBLIC);
List<JVar> argParams = Lists.newArrayList();
for(int i=0;i!=arity;++i) {
argParams.add(ctor.param(Vector.class, "arg" + i));
}
ctor.param(AttributeMap.class, "attributes");
ctor.body().directStatement("super(attributes);");
ctor.body().assign(lengthField, lit(0));
for(int i=0;i!=arity;++i) {
ctor.body().assign(JExpr._this().ref(arg(i).valueField), argParams.get(i));
ctor.body().assign(arg(i).lengthField, arg(i).valueField.invoke("length"));
}
if(arity == 1) {
ctor.body().assign(lengthField, arg(0).lengthField);
} else if(arity == 2) {
ctor.body().assign(lengthField, codeModel.ref(Math.class).staticInvoke("max")
.arg(arg(0).lengthField)
.arg(arg(1).lengthField));
}
}
private DeferredArgument arg(int i) {
return arguments.get(i);
}
private void implementLength() {
JMethod method = vectorClass.method(JMod.PUBLIC, int.class, "length");
method.body()._return(lengthField);
}
private void implementStaticApply() {
JMethod method = vectorClass.method(JMod.PUBLIC | JMod.STATIC, type.accessorType, "compute");
List<JExpression> params = Lists.newArrayList();
for(DeferredArgument argument : arguments) {
JVar param = method.param(argument.accessorType(), "p" + argument.index);
params.add(argument.convert(param));
}
returnValue(method.body(), buildInvocation(params));
}
private void implementAccessor() {
JMethod method = vectorClass.method(JMod.PUBLIC, type.accessorType, type.accessorName);
JVar index = method.param(int.class, "index");
// extract the arguments to the function from the given vectors
List<JExpression> argValues = Lists.newArrayList();
for(DeferredArgument arg : arguments) {
JExpression elementIndex;
if(arity == 1) {
elementIndex = index;
} else {
// avoid using modulus if we can
JVar indexVar = method.body().decl(codeModel._ref(int.class), "i" + arg.index);
JConditional ifLessThan = method.body()._if(index.lt(arg.lengthField));
ifLessThan._then().assign(indexVar, index);
ifLessThan._else().assign(indexVar, index.mod(arg.lengthField));
elementIndex = indexVar;
}
JVar argValue = method.body().decl(arg.accessorType(), "arg" + arg.index + "_i", arg.invokeAccessor(elementIndex));
argValues.add(arg.convert(argValue));
if(!overload.isPassNA() && arg.type != ArgumentType.BYTE) {
method.body()._if(arg.isNA(argValue))._then()._return(na());
}
}
// invoke the underlying function
returnValue(method.body(), buildInvocation(argValues));
}
private JInvocation buildInvocation(List<JExpression> argValues) {
JInvocation invocation = codeModel
.ref(overload.getDeclaringClass())
.staticInvoke(overload.getName());
for(JExpression argValue : argValues) {
invocation.arg(argValue);
}
return invocation;
}
private JExpression na() {
switch (type) {
case DOUBLE:
return codeModel.ref(DoubleVector.class).staticRef("NA");
case LOGICAL:
case INTEGER:
return codeModel.ref(IntVector.class).staticRef("NA");
case COMPLEX:
return codeModel.ref(ComplexArrayVector.class).staticRef("NA");
}
throw new UnsupportedOperationException(type.toString());
}
private void returnValue(JBlock parent, JExpression retVal) {
if(overload.getReturnType().equals(boolean.class)) {
JConditional ifTrue = parent._if(retVal);<|fim▁hole|> ifTrue._then()._return(lit(1));
ifTrue._else()._return(lit(0));
} else if(overload.getReturnType().equals(Logical.class)) {
parent._return(retVal.invoke("getInternalValue"));
} else {
parent._return(retVal);
}
}
public void overrideIsNaWithConstantValue() {
JMethod method = vectorClass.method(JMod.PUBLIC, boolean.class, "isElementNA");
method.param(int.class, "index");
method.body()._return(JExpr.FALSE);
}
private void implementAttributeSetter() {
// @Override
// protected SEXP cloneWithNewAttributes(AttributeMap attributes) {
// return new DoubleBinaryFnVector(fn, x, y, attributes);
// }
JMethod method = vectorClass.method(JMod.PUBLIC, SEXP.class, "cloneWithNewAttributes");
JVar attributes = method.param(AttributeMap.class, "attributes");
JInvocation newInvocation = JExpr._new(vectorClass);
for(DeferredArgument arg : arguments) {
newInvocation.arg(arg.valueField);
}
newInvocation.arg(attributes);
method.body()._return(newInvocation);
}
private class DeferredArgument {
private JvmMethod.Argument model;
private int index;
private JFieldVar valueField;
private JFieldVar lengthField;
private ArgumentType type;
private DeferredArgument(JvmMethod.Argument model, int index) {
this.model = model;
this.index = index;
this.valueField = vectorClass.field(JMod.PRIVATE | JMod.FINAL, Vector.class, "arg" + index);
this.lengthField = vectorClass.field(JMod.PRIVATE | JMod.FINAL, int.class, "argLength" + index);
if(model.getClazz().equals(double.class)) {
this.type = ArgumentType.DOUBLE;
} else if(model.getClazz().equals(boolean.class)) {
this.type = ArgumentType.BOOLEAN;
} else if(model.getClazz().equals(int.class)) {
this.type = ArgumentType.INTEGER;
} else if(model.getClazz().equals(String.class)) {
this.type = ArgumentType.STRING;
} else if(model.getClazz().equals(Complex.class)) {
this.type = ArgumentType.COMPLEX;
} else if(model.getClazz().equals(byte.class)) {
this.type = ArgumentType.BYTE;
} else {
throw new UnsupportedOperationException(model.getClazz().toString());
}
}
public JType type() {
return codeModel._ref(model.getClazz());
}
public JExpression invokeAccessor(JExpression elementIndex) {
return valueField.invoke(type.accessorName).arg(elementIndex);
}
public JType accessorType() {
return codeModel._ref(type.accessorType());
}
public JExpression isNA(JExpression expr) {
return type.isNa(codeModel, expr);
}
public JExpression convert(JExpression argValue) {
return type.convertToArg(argValue);
}
}
private enum VectorType {
DOUBLE(DoubleVector.class, "getElementAsDouble", double.class),
LOGICAL(LogicalVector.class, "getElementAsRawLogical", int.class),
INTEGER(IntVector.class, "getElementAsInt", int.class),
COMPLEX(ComplexVector.class, "getElementAsComplex", Complex.class),
RAW(RawVector.class, "getElementAsByte", byte.class);
private Class baseClass;
private String accessorName;
private Class accessorType;
private VectorType(Class baseClass, String accessorName, Class accessorType) {
this.baseClass = baseClass;
this.accessorName = accessorName;
this.accessorType = accessorType;
}
}
private enum ArgumentType {
DOUBLE(double.class, "getElementAsDouble") {
@Override
public JExpression isNa(JCodeModel codeModel, JExpression expr) {
return codeModel.ref(DoubleVector.class).staticInvoke("isNA").arg(expr);
}
},
INTEGER(int.class, "getElementAsInt") {
@Override
public JExpression isNa(JCodeModel codeModel, JExpression expr) {
return codeModel.ref(IntVector.class).staticInvoke("isNA").arg(expr);
}
},
BOOLEAN(boolean.class, "getElementAsRawLogical") {
@Override
public JExpression convertToArg(JExpression expr) {
return expr.ne(lit(0));
}
@Override
public Class accessorType() {
return int.class;
}
@Override
public JExpression isNa(JCodeModel codeModel, JExpression expr) {
return codeModel.ref(IntVector.class).staticInvoke("isNA").arg(expr);
}
},
STRING(String.class, "getElementAsString") {
@Override
public JExpression isNa(JCodeModel codeModel, JExpression expr) {
return codeModel.ref(StringVector.class).staticInvoke("isNA").arg(expr);
}
},
COMPLEX(Complex.class, "getElementAsComplex" ) {
@Override
public JExpression isNa(JCodeModel codeModel, JExpression expr) {
return codeModel.ref(ComplexVector.class).staticInvoke("isNA").arg(expr);
}
}, BYTE(byte.class, "getElementAsByte" ) {
@Override
public JExpression isNa(JCodeModel codeModel, JExpression expr) {
return JExpr.lit(false);
}
};
private Class clazz;
private String accessorName;
private ArgumentType(Class clazz, String accessorName) {
this.clazz = clazz;
this.accessorName = accessorName;
}
public JExpression convertToArg(JExpression expr) {
return expr;
}
public Class accessorType() {
return clazz;
}
public abstract JExpression isNa(JCodeModel codeModel, JExpression expr);
}
}<|fim▁end|> | |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin<|fim▁hole|>class AccountFilterAdmin(admin.ModelAdmin):
list_display = ('location', 'include_users', 'exclude_users')
ordering = ('location',)
admin.site.register(AccountFilter, AccountFilterAdmin)<|fim▁end|> |
from panoptes.tracking.models import AccountFilter
|
<|file_name|>new-entity.component.ts<|end_file_name|><|fim▁begin|>import { Component, HostListener, Inject } from '@angular/core';
import { MdlDialogReference } from '@angular-mdl/core';
import * as _ from 'lodash';
@Component({
selector: 'app-new-entity',
templateUrl: './new-entity.component.html',
styleUrls: ['./new-entity.component.scss']
})
export class NewEntityComponent {
actions: any;
pluginFormats = [<|fim▁hole|> { label: 'XQuery', value: 'XQUERY' },
];
dataFormats = [
{ label: 'JSON', value: 'JSON' },
{ label: 'XML', value: 'XML' },
];
DEFAULTENTITY: any = {
info: {
title: null
}
};
entity: any = _.clone(this.DEFAULTENTITY);
constructor(
private dialog: MdlDialogReference,
@Inject('actions') actions: any
) {
this.entity = _.clone(this.DEFAULTENTITY);
this.actions = actions;
}
hide() {
this.dialog.hide();
}
create() {
if (this.entity.info.title && this.entity.info.title.length > 0) {
this.hide();
if (this.actions && this.actions.save) {
this.actions.save(this.entity);
}
}
}
cancel() {
this.hide();
}
}<|fim▁end|> | { label: 'Javascript', value: 'JAVASCRIPT' }, |
<|file_name|>resource.rs<|end_file_name|><|fim▁begin|>use alloc::boxed::Box;
use system::error::{Error, Result, EBADF};
use system::syscall::Stat;
/// Resource seek
#[derive(Copy, Clone, Debug)]
pub enum ResourceSeek {
/// Start point
Start(usize),
/// Current point
Current(isize),<|fim▁hole|>/// A system resource
#[allow(unused_variables)]
pub trait Resource {
/// Duplicate the resource
fn dup(&self) -> Result<Box<Resource>> {
Err(Error::new(EBADF))
}
/// Return the path of this resource
fn path(&self, buf: &mut [u8]) -> Result<usize> {
Err(Error::new(EBADF))
}
/// Read data to buffer
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
Err(Error::new(EBADF))
}
/// Write to resource
fn write(&mut self, buf: &[u8]) -> Result<usize> {
Err(Error::new(EBADF))
}
/// Seek to the given offset
fn seek(&mut self, pos: ResourceSeek) -> Result<usize> {
Err(Error::new(EBADF))
}
fn stat(&self, stat: &mut Stat) -> Result<usize> {
Err(Error::new(EBADF))
}
/// Sync all buffers
fn sync(&mut self) -> Result<()> {
Err(Error::new(EBADF))
}
/// Truncate to the given length
fn truncate(&mut self, len: usize) -> Result<()> {
Err(Error::new(EBADF))
}
}<|fim▁end|> | /// End point
End(isize),
}
|
<|file_name|>test_constructions.py<|end_file_name|><|fim▁begin|>from collections import OrderedDict
import pytest
from ucca import textutil
from ucca.constructions import CATEGORIES_NAME, DEFAULT, CONSTRUCTIONS, extract_candidates
from .conftest import PASSAGES, loaded, loaded_valid, multi_sent, crossing, discontiguous, l1_passage, empty
"""Tests the constructions module functions and classes."""
def assert_spacy_not_loaded(*args, **kwargs):
del args, kwargs
assert False, "Should not load spaCy when passage is pre-annotated"
def extract_and_check(p, constructions=None, expected=None):
d = OrderedDict((construction, [candidate.edge for candidate in candidates]) for construction, candidates in
extract_candidates(p, constructions=constructions).items() if candidates)
if expected is not None:<|fim▁hole|> hist = {c.name: len(e) for c, e in d.items()}
assert hist == expected, " != ".join(",".join(sorted(h)) for h in (hist, expected))
@pytest.mark.parametrize("create, expected", (
(loaded, {'P': 1, 'remote': 1, 'E': 3, 'primary': 15, 'U': 2, 'F': 1, 'C': 3, 'A': 1, 'D': 1, 'L': 2, 'mwe': 2,
'H': 5, 'implicit': 1, 'main_rel': 1}),
(loaded_valid, {'P': 1, 'remote': 1, 'E': 3, 'primary': 15, 'U': 2, 'F': 1, 'C': 3, 'A': 1, 'D': 1, 'L': 2,
'mwe': 2, 'H': 5, 'implicit': 1, 'main_rel': 1}),
(multi_sent, {'U': 4, 'P': 3, 'mwe': 2, 'H': 3, 'primary': 6, 'main_rel': 2}),
(crossing, {'U': 3, 'P': 2, 'remote': 1, 'mwe': 1, 'H': 2, 'primary': 3, 'main_rel': 2}),
(discontiguous, {'G': 1, 'U': 2, 'E': 2, 'primary': 13, 'P': 3, 'F': 1, 'C': 1, 'A': 3, 'D': 2,
'mwe': 6, 'H': 3, 'implicit':3, 'main_rel': 2}),
(l1_passage, {'P': 2, 'mwe': 4, 'H': 3, 'primary': 11, 'U': 2, 'A': 5, 'D': 1, 'L': 2, 'remote': 2, 'S': 1,
'implicit':1, 'main_rel': 3}),
(empty, {}),
))
def test_extract_all(create, expected):
extract_and_check(create(), constructions=CONSTRUCTIONS, expected=expected)
@pytest.mark.parametrize("create", PASSAGES)
@pytest.mark.parametrize("constructions", (DEFAULT, [CATEGORIES_NAME]), ids=("default", CATEGORIES_NAME))
def test_extract(create, constructions, monkeypatch):
monkeypatch.setattr(textutil, "get_nlp", assert_spacy_not_loaded)
extract_and_check(create(), constructions=constructions)<|fim▁end|> | |
<|file_name|>issue-4252.rs<|end_file_name|><|fim▁begin|>// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
<|fim▁hole|>
trait X {
fn call(&self);
}
struct Y;
struct Z<T> {
x: T
}
impl X for Y {
fn call(&self) {
}
}
impl<T: X> Drop for Z<T> {
fn drop(&mut self) {
self.x.call(); // Adding this statement causes an ICE.
}
}
fn main() {
let y = Y;
let _z = Z{x: y};
}<|fim▁end|> | // xfail-test |
<|file_name|>jimp.ts<|end_file_name|><|fim▁begin|>import * as jimp from "jimp"
type ResizeProps = {
width: number
mime: "image/jpeg" | "image/png" | "image/webp" | "image/avif"
options: {
background?: string
rotate: number
quality: number
progressive?: boolean
}
}
class JimpAdapter {
readImage: Promise<jimp>
constructor(imagePath: string) {
this.readImage = jimp.read(imagePath)
}
metadata(): Promise<{ height: number; width: number }> {
return this.readImage.then((image) => ({
width: image.bitmap.width,
height: image.bitmap.height,
}))
}
resize({
width,
mime,
options,
}: ResizeProps): Promise<{
width: number
height: number
data: Buffer
}> {
return new Promise((resolve, reject) => {
this.readImage.then((image) => {
image<|fim▁hole|> .resize(width, jimp.AUTO)
.quality(options.quality)
.background(parseInt(options.background + "", 16) || 0xffffffff)
.getBuffer(mime, function (err, data) {
// eslint-disable-line func-names
if (err) {
reject(err)
} else {
resolve({
data,
width,
height: this.bitmap.height,
})
}
})
})
})
}
}
module.exports = (imagePath: string): JimpAdapter => {
return new JimpAdapter(imagePath)
}<|fim▁end|> | .clone() |
<|file_name|>ruby_requirements.py<|end_file_name|><|fim▁begin|># Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#<|fim▁hole|># 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.
"""Requirements for Ruby codegen."""
from artman.tasks.requirements import task_requirement_base
class RubyFormatRequirements(task_requirement_base.TaskRequirementBase):
@classmethod
def require(cls):
return ['rubocop']
@classmethod
def install(cls):
# Intentionally do nothing
pass
class RakeRequirements(task_requirement_base.TaskRequirementBase):
@classmethod
def require(cls):
return ['rake']
@classmethod
def install(cls):
# Intentionally do nothing
pass<|fim▁end|> | # http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software |
<|file_name|>tarfile_getmember.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2009 Doug Hellmann All rights reserved.
#
"""
"""
__version__ = "$Id$"
#end_pymotw_header<|fim▁hole|>t = tarfile.open('example.tar', 'r')
for filename in [ 'README.txt', 'notthere.txt' ]:
try:
info = t.getmember(filename)
except KeyError:
print 'ERROR: Did not find %s in tar archive' % filename
else:
print '%s is %d bytes' % (info.name, info.size)<|fim▁end|> |
import tarfile
import time
|
<|file_name|>oxm_fields.py<|end_file_name|><|fim▁begin|># Copyright (C) 2013-2015 Nippon Telegraph and Telephone Corporation.
# Copyright (C) 2013-2015 YAMAMOTO Takashi <yamamoto at valinux co jp>
#
# 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.
# there are two representations of value and mask this module deal with.
#
# "user"
# (value, mask) or value. the latter means no mask.
# value and mask are strings.
#
# "internal"
# value and mask are on-wire bytes.
# mask is None if no mask.
# There are two types of OXM/NXM headers.
#
# 32-bit OXM/NXM header
# +-------------------------------+-------------+-+---------------+
# | class | field |m| length |
# +-------------------------------+-------------+-+---------------+
#
# 64-bit experimenter OXM header
# +-------------------------------+-------------+-+---------------+
# | class (OFPXMC_EXPERIMENTER) | field |m| length |
# +-------------------------------+-------------+-+---------------+
# | experimenter ID |
# +---------------------------------------------------------------+
# NOTE: EXT-256 had a variation of experimenter OXM header.
# It has been rectified since then. Currently this implementation
# supports only the old version.
#
# ONF EXT-256 (old, exp_type = 2560)
# +-------------------------------+-------------+-+---------------+
# | class (OFPXMC_EXPERIMENTER) | ????? |m| length |
# +-------------------------------+-------------+-+---------------+
# | experimenter ID (ONF_EXPERIMENTER_ID) |
# +-------------------------------+---------------+---------------+
# | exp_type (PBB_UCA=2560) | pbb_uca |
# +-------------------------------+---------------+
#
# ONF EXT-256 (new, oxm_field = 41)
# +-------------------------------+-------------+-+---------------+
# | class (OFPXMC_EXPERIMENTER) | PBB_UCA=41 |m| length |
# +-------------------------------+-------------+-+---------------+
# | experimenter ID (ONF_EXPERIMENTER_ID) |
# +-------------------------------+---------------+---------------+
# | reserved, should be zero | pbb_uca |
# +-------------------------------+---------------+
import itertools
import struct
from ryu.ofproto import ofproto_common
from ryu.lib.pack_utils import msg_pack_into
from ryu.lib import type_desc
OFPXMC_NXM_0 = 0 # Nicira Extended Match (NXM_OF_)
OFPXMC_NXM_1 = 1 # Nicira Extended Match (NXM_NX_)
OFPXMC_OPENFLOW_BASIC = 0x8000
OFPXMC_PACKET_REGS = 0x8001
OFPXMC_EXPERIMENTER = 0xffff
class _OxmClass(object):
def __init__(self, name, num, type_):
self.name = name
self.oxm_type = num | (self._class << 7)
# TODO(yamamoto): Clean this up later.
# Probably when we drop EXT-256 style experimenter OXMs.
self.num = self.oxm_type
self.type = type_
class OpenFlowBasic(_OxmClass):
_class = OFPXMC_OPENFLOW_BASIC
class PacketRegs(_OxmClass):
_class = OFPXMC_PACKET_REGS
class _Experimenter(_OxmClass):
_class = OFPXMC_EXPERIMENTER
def __init__(self, name, num, type_):
super(_Experimenter, self).__init__(name, num, type_)
self.num = (self.experimenter_id, self.oxm_type)
class ONFExperimenter(_Experimenter):
experimenter_id = ofproto_common.ONF_EXPERIMENTER_ID
class OldONFExperimenter(_Experimenter):
# This class is for the old version of EXT-256
experimenter_id = ofproto_common.ONF_EXPERIMENTER_ID
def __init__(self, name, num, type_):
super(OldONFExperimenter, self).__init__(name, 0, type_)
self.num = (self.experimenter_id, num)
self.exp_type = num
class OpenStateExperimenter(_Experimenter):
experimenter_id = ofproto_common.OPENSTATE_EXPERIMENTER_ID
class NiciraExperimenter(_Experimenter):
experimenter_id = ofproto_common.NX_EXPERIMENTER_ID
class NiciraExtended0(_OxmClass):
"""Nicira Extended Match (NXM_0)
NXM header format is same as 32-bit (non-experimenter) OXMs.
"""
_class = OFPXMC_NXM_0
class NiciraExtended1(_OxmClass):
"""Nicira Extended Match (NXM_1)
NXM header format is same as 32-bit (non-experimenter) OXMs.
"""
_class = OFPXMC_NXM_1
def generate(modname):
import sys
import functools
mod = sys.modules[modname]
def add_attr(k, v):
setattr(mod, k, v)
for i in mod.oxm_types:
uk = i.name.upper()
if isinstance(i.num, tuple):
continue
oxm_class = i.num >> 7
if oxm_class != OFPXMC_OPENFLOW_BASIC:
continue
ofpxmt = i.num & 0x3f
td = i.type
add_attr('OFPXMT_OFB_' + uk, ofpxmt)
add_attr('OXM_OF_' + uk, mod.oxm_tlv_header(ofpxmt, td.size))
add_attr('OXM_OF_' + uk + '_W', mod.oxm_tlv_header_w(ofpxmt, td.size))
name_to_field = dict((f.name, f) for f in mod.oxm_types)
num_to_field = dict((f.num, f) for f in mod.oxm_types)
add_attr('oxm_from_user', functools.partial(_from_user, name_to_field))
add_attr('oxm_from_user_header',
functools.partial(_from_user_header, name_to_field))
add_attr('oxm_to_user', functools.partial(_to_user, num_to_field))
add_attr('oxm_to_user_header',
functools.partial(_to_user_header, num_to_field))
add_attr('_oxm_field_desc', functools.partial(_field_desc, num_to_field))
add_attr('oxm_normalize_user', functools.partial(_normalize_user, mod))
add_attr('oxm_parse', functools.partial(_parse, mod))
add_attr('oxm_parse_header', functools.partial(_parse_header, mod))
add_attr('oxm_serialize', functools.partial(_serialize, mod))
add_attr('oxm_serialize_header', functools.partial(_serialize_header, mod))
add_attr('oxm_to_jsondict', _to_jsondict)
add_attr('oxm_from_jsondict', _from_jsondict)
def _get_field_info_by_name(name_to_field, name):
try:
f = name_to_field[name]
t = f.type
num = f.num
except KeyError:
t = type_desc.UnknownType
if name.startswith('field_'):
num = int(name.split('_')[1])
else:
raise KeyError('unknown match field ' + name)
return num, t
def _from_user_header(name_to_field, name):
(num, t) = _get_field_info_by_name(name_to_field, name)
return num
def _from_user(name_to_field, name, user_value):
(num, t) = _get_field_info_by_name(name_to_field, name)
# the 'list' case below is a bit hack; json.dumps silently maps
# python tuples into json lists.
if isinstance(user_value, (tuple, list)):
(value, mask) = user_value
else:
value = user_value
mask = None
if value is not None:
value = t.from_user(value)
if mask is not None:
mask = t.from_user(mask)
return num, value, mask
def _get_field_info_by_number(num_to_field, n):
try:
f = num_to_field[n]
t = f.type
name = f.name
except KeyError:
t = type_desc.UnknownType
name = 'field_%d' % (n,)
return name, t
def _to_user_header(num_to_field, n):
(name, t) = _get_field_info_by_number(num_to_field, n)
return name
def _to_user(num_to_field, n, v, m):
(name, t) = _get_field_info_by_number(num_to_field, n)
if v is not None:
if hasattr(t, 'size') and t.size != len(v):
raise Exception(
'Unexpected OXM payload length %d for %s (expected %d)'
% (len(v), name, t.size))
value = t.to_user(v)
else:
value = None
if m is None:
user_value = value
else:
user_value = (value, t.to_user(m))
return name, user_value
def _field_desc(num_to_field, n):
return num_to_field[n]
def _normalize_user(mod, k, uv):
(n, v, m) = mod.oxm_from_user(k, uv)
# apply mask
if m is not None:
v = ''.join(chr(ord(x) & ord(y)) for (x, y) in itertools.izip(v, m))
(k2, uv2) = mod.oxm_to_user(n, v, m)
assert k2 == k
return (k2, uv2)
def _parse_header_impl(mod, buf, offset):
hdr_pack_str = '!I'
(header, ) = struct.unpack_from(hdr_pack_str, buf, offset)
hdr_len = struct.calcsize(hdr_pack_str)
oxm_type = header >> 9 # class|field
oxm_hasmask = mod.oxm_tlv_header_extract_hasmask(header)
oxm_class = oxm_type >> 7
oxm_length = header & 0xff
if oxm_class == OFPXMC_EXPERIMENTER:
# Experimenter OXMs have 64-bit header. (vs 32-bit for other OXMs)
exp_hdr_pack_str = '!I' # experimenter_id
(exp_id, ) = struct.unpack_from(exp_hdr_pack_str, buf,
offset + hdr_len)
exp_hdr_len = struct.calcsize(exp_hdr_pack_str)
assert exp_hdr_len == 4
oxm_field = oxm_type & 0x7f
if exp_id == ofproto_common.ONF_EXPERIMENTER_ID and oxm_field == 0:
# XXX
# This block implements EXT-256 style experimenter OXM.
onf_exp_type_pack_str = '!H'
(exp_type, ) = struct.unpack_from(onf_exp_type_pack_str, buf,
offset + hdr_len + exp_hdr_len)
exp_hdr_len += struct.calcsize(onf_exp_type_pack_str)
assert exp_hdr_len == 4 + 2
num = (exp_id, exp_type)
elif exp_id == ofproto_common.OPENSTATE_EXPERIMENTER_ID:
num = oxm_type
else:
num = (exp_id, oxm_type)
else:
num = oxm_type
exp_hdr_len = 0
value_len = oxm_length - exp_hdr_len
if oxm_hasmask:
value_len //= 2
assert value_len > 0
field_len = hdr_len + oxm_length
total_hdr_len = hdr_len + exp_hdr_len
return num, total_hdr_len, oxm_hasmask, value_len, field_len
def _parse_header(mod, buf, offset):
(oxm_type_num, total_hdr_len, hasmask, value_len,
field_len) = _parse_header_impl(mod, buf, offset)
return oxm_type_num, field_len - value_len
def _parse(mod, buf, offset):
(oxm_type_num, total_hdr_len, hasmask, value_len,
field_len) = _parse_header_impl(mod, buf, offset)
# Note: OXM payload length (oxm_len) includes Experimenter ID (exp_hdr_len)
# for experimenter OXMs.
value_offset = offset + total_hdr_len
value_pack_str = '!%ds' % value_len
assert struct.calcsize(value_pack_str) == value_len
(value, ) = struct.unpack_from(value_pack_str, buf, value_offset)
if hasmask:
(mask, ) = struct.unpack_from(value_pack_str, buf,
value_offset + value_len)
else:
mask = None
return oxm_type_num, value, mask, field_len
<|fim▁hole|>
def _make_exp_hdr(mod, n):
exp_hdr = bytearray()
try:
desc = mod._oxm_field_desc(n)
except KeyError:
return n, exp_hdr
if isinstance(desc, _Experimenter): # XXX
(exp_id, exp_type) = n
assert desc.experimenter_id == exp_id
if isinstance(desc, OldONFExperimenter): # XXX
# XXX
# This block implements EXT-256 style experimenter OXM.
exp_hdr_pack_str = '!IH' # experimenter_id, exp_type
msg_pack_into(exp_hdr_pack_str, exp_hdr, 0,
desc.experimenter_id, desc.exp_type)
else:
assert desc.oxm_type == exp_type
exp_hdr_pack_str = '!I' # experimenter_id
msg_pack_into(exp_hdr_pack_str, exp_hdr, 0,
desc.experimenter_id)
assert len(exp_hdr) == struct.calcsize(exp_hdr_pack_str)
n = desc.oxm_type
assert (n >> 7) == OFPXMC_EXPERIMENTER
return n, exp_hdr
def _serialize_header(mod, n, buf, offset):
try:
desc = mod._oxm_field_desc(n)
value_len = desc.type.size
except KeyError:
value_len = 0
n, exp_hdr = _make_exp_hdr(mod, n)
exp_hdr_len = len(exp_hdr)
pack_str = "!I%ds" % (exp_hdr_len,)
msg_pack_into(pack_str, buf, offset,
(n << 9) | (0 << 8) | (exp_hdr_len + value_len),
bytes(exp_hdr))
return struct.calcsize(pack_str)
def _serialize(mod, n, value, mask, buf, offset):
n, exp_hdr = _make_exp_hdr(mod, n)
exp_hdr_len = len(exp_hdr)
value_len = len(value)
if mask:
assert value_len == len(mask)
pack_str = "!I%ds%ds%ds" % (exp_hdr_len, value_len, len(mask))
msg_pack_into(pack_str, buf, offset,
(n << 9) | (1 << 8) | (exp_hdr_len + value_len * 2),
bytes(exp_hdr), value, mask)
else:
pack_str = "!I%ds%ds" % (exp_hdr_len, value_len,)
msg_pack_into(pack_str, buf, offset,
(n << 9) | (0 << 8) | (exp_hdr_len + value_len),
bytes(exp_hdr), value)
return struct.calcsize(pack_str)
def _to_jsondict(k, uv):
if isinstance(uv, tuple):
(value, mask) = uv
else:
value = uv
mask = None
return {"OXMTlv": {"field": k, "value": value, "mask": mask}}
def _from_jsondict(j):
tlv = j['OXMTlv']
field = tlv['field']
value = tlv['value']
mask = tlv.get('mask')
if mask is None:
uv = value
else:
uv = (value, mask)
return (field, uv)<|fim▁end|> | |
<|file_name|>04_methodDecorators.ts<|end_file_name|><|fim▁begin|>// Method Decorator (WORK IN PROGRESS)
function editable(value: boolean) {
return function (target: any, propName: string, descriptor: PropertyDescriptor) {
descriptor.writable = value;
}
}
class CoffeeBean {
name: string;
constructor(name: string) {
this.name = name;
}
@editable(false)
calcPrice() {
console.log(1000);
}
/*
@editable(true)
calcYourBudget() {
console.log(2000);
}
*/
}
const coffee = new CoffeeBean('Kenyan');
coffee.calcPrice();
coffee.calcPrice = function() {
console.log(111);
}
/*
coffee.calcYourBudget = function() {
console.log(111);
}<|fim▁hole|>
// Property Decorator<|fim▁end|> | */ |
<|file_name|>demo.py<|end_file_name|><|fim▁begin|>"""
Demo platform for the cover component.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/demo/
"""
from homeassistant.components.cover import CoverDevice
from homeassistant.helpers.event import track_utc_time_change
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the Demo covers."""
add_devices([
DemoCover(hass, 'Kitchen Window'),
DemoCover(hass, 'Hall Window', 10),
DemoCover(hass, 'Living Room Window', 70, 50),
])
class DemoCover(CoverDevice):
"""Representation of a demo cover."""
# pylint: disable=no-self-use, too-many-instance-attributes
def __init__(self, hass, name, position=None, tilt_position=None):
"""Initialize the cover."""
self.hass = hass
self._name = name
self._position = position
self._set_position = None
self._set_tilt_position = None
self._tilt_position = tilt_position
self._closing = True
self._closing_tilt = True
self._unsub_listener_cover = None
self._unsub_listener_cover_tilt = None
@property
def name(self):
"""Return the name of the cover."""
return self._name
@property
def should_poll(self):
"""No polling needed for a demo cover."""
return False
@property
def current_cover_position(self):
"""Return the current position of the cover."""
return self._position
@property
def current_cover_tilt_position(self):
"""Return the current tilt position of the cover."""
return self._tilt_position
@property
def is_closed(self):
"""Return if the cover is closed."""
if self._position is not None:
if self.current_cover_position > 0:
return False
else:
return True
else:
return None
def close_cover(self, **kwargs):
"""Close the cover."""
if self._position in (0, None):
return
self._listen_cover()
self._closing = True
def close_cover_tilt(self, **kwargs):
"""Close the cover tilt."""
if self._tilt_position in (0, None):
return
self._listen_cover_tilt()
self._closing_tilt = True
def open_cover(self, **kwargs):
"""Open the cover."""
if self._position in (100, None):
return
self._listen_cover()
self._closing = False
def open_cover_tilt(self, **kwargs):
"""Open the cover tilt."""
if self._tilt_position in (100, None):
return
self._listen_cover_tilt()
self._closing_tilt = False
def set_cover_position(self, position, **kwargs):
"""Move the cover to a specific position."""
self._set_position = round(position, -1)
if self._position == position:
return
<|fim▁hole|> self._closing = position < self._position
def set_cover_tilt_position(self, tilt_position, **kwargs):
"""Move the cover til to a specific position."""
self._set_tilt_position = round(tilt_position, -1)
if self._tilt_position == tilt_position:
return
self._listen_cover_tilt()
self._closing_tilt = tilt_position < self._tilt_position
def stop_cover(self, **kwargs):
"""Stop the cover."""
if self._position is None:
return
if self._unsub_listener_cover is not None:
self._unsub_listener_cover()
self._unsub_listener_cover = None
self._set_position = None
def stop_cover_tilt(self, **kwargs):
"""Stop the cover tilt."""
if self._tilt_position is None:
return
if self._unsub_listener_cover_tilt is not None:
self._unsub_listener_cover_tilt()
self._unsub_listener_cover_tilt = None
self._set_tilt_position = None
def _listen_cover(self):
"""Listen for changes in cover."""
if self._unsub_listener_cover is None:
self._unsub_listener_cover = track_utc_time_change(
self.hass, self._time_changed_cover)
def _time_changed_cover(self, now):
"""Track time changes."""
if self._closing:
self._position -= 10
else:
self._position += 10
if self._position in (100, 0, self._set_position):
self.stop_cover()
self.update_ha_state()
def _listen_cover_tilt(self):
"""Listen for changes in cover tilt."""
if self._unsub_listener_cover_tilt is None:
self._unsub_listener_cover_tilt = track_utc_time_change(
self.hass, self._time_changed_cover_tilt)
def _time_changed_cover_tilt(self, now):
"""Track time changes."""
if self._closing_tilt:
self._tilt_position -= 10
else:
self._tilt_position += 10
if self._tilt_position in (100, 0, self._set_tilt_position):
self.stop_cover_tilt()
self.update_ha_state()<|fim▁end|> | self._listen_cover() |
<|file_name|>lu.cc<|end_file_name|><|fim▁begin|>#include "math/lu.hh"
#include <cassert>
#include <cmath>
#include "math/vlist.hh"
LU::lu_t LU::lu(const Matrix& a)
{
assert(a.rows() == a.cols());
std::size_t n = a.rows();
auto l = Matrix::id(n);
auto u = a;
for (std::size_t j = 0; j < n; ++j)
for (std::size_t i = j + 1; i < n; ++i)
{
double pivot = !u.at(i, j) && !u.at(j, j) ? 0
: u.at(i, j) / u.at(j, j);
l.at(i, j) = pivot;
auto ui = VList::row_to_vec(u, i);
auto uj = VList::row_to_vec(u, j);
VList::row_set(u, i, ui - pivot * uj);
}
return {l, u};
}
/**
* Compute the PLU Decomposition PA = LU
* A square matrix of size n
* P permutation matrix of size n
* L unit lower triangular matrix of size n
* U upper triangular matrix of size n
* if parity != nullptr, pointed value set to numbers of permutations
* returns (P, L, U)
*
* Method:
* parity = 0
* for j = 0 -> n - 1:
* let imax = max(|A[j][j : n - 1]|)
* if imax != j:
* ++parity
* swap(tr(P)[j], tr(P)[imax])
* swap(tr(L)[j], tr(L)[imax])
* swap(tr(A)[j], tr(A)[imax])
* for i = j + 1 -> n - 1:
* let pivot = a_ij / a_jj, or 0 if a_ij = a_jj = 0
* l_ij = pivot
* tr(A)[i] -= pivot * tr(A)[j]
* return (P, L, A)
*/
LU::plu_t LU::plu(const Matrix& a, int* parity)
{
assert(a.rows() == a.cols());
std::size_t n = a.rows();
auto p = Matrix::id(n);
auto l = Matrix::id(n);
auto u = a;
int par = 0;
for (std::size_t j = 0; j < n; ++j)
{
std::size_t imax = j;
for (std::size_t i = j + 1; i < n; ++i)<|fim▁hole|>
if (imax != j)
{
++par;
VList::swap_row(p, j, imax);
//VList::swap_row(l, j, imax);
VList::swap_row(u, j, imax);
}
for (std::size_t i = j + 1; i < n; ++i)
{
double pivot = !u.at(i, j) && !u.at(j, j) ? 0
: u.at(i, j) / u.at(j, j);
/*
u.at(i, j) = 0;
for (std::size_t k = j + 1; k < n; ++k)
u.at(i, k) -= pivot * u.at(j, k);
l.at(i, j) = pivot;
*/
l.at(i, j) = pivot;
auto ui = VList::row_to_vec(u, i);
auto uj = VList::row_to_vec(u, j);
VList::row_set(u, i, ui - pivot * uj);
}
}
if (parity)
*parity = par;
return {p, l, u};
}<|fim▁end|> | if (std::abs(u.at(i, j)) > std::abs(u.at(imax, j)))
imax = i; |
<|file_name|>creatureDB.py<|end_file_name|><|fim▁begin|>'''A module containing a class for storing Creature objects in a
SQLite database.'''
import csv
import sqlite3
__all__ = ['CreatureDB']
class CreatureDB(object):
'''Class for storing Creature objects in a SQLite database.'''
def __init__(self, name='creature.db', use_nominal_cr=False):
self.min_cr = 0.0
self.max_cr = float('inf')
# set flags
self.using_nominal_cr = use_nominal_cr
# initialize database
self.connection = sqlite3.connect(name)
self.connection.text_factory = str
self._create_table()
def _construct_table_columns(self):
'''Constructs a tuple that defines the columns in
the "creatures" table
:returns tuple that defines the columns in "creatures" table
'''
columns = ('id integer primary key autoincrement',
'name varchar(45)')
# set type of CR column depending on flag
if self.using_nominal_cr:
columns = columns + ('CR varchar(10)',)
else:
columns = columns + ('CR real',)
# add the remaining database fields to column tuple
main_entry_columns = (
'hp integer', 'HD integer',
'ac integer', 'touch_ac integer', 'flatfooted_ac integer',
'Fort integer', 'Ref integer', 'Will integer',
'Str integer', 'Dex integer', 'Con integer',
'Int integer', 'Wis integer', 'Cha integer',
'BAB integer', 'CMB integer', 'CMD integer'
)
columns = columns + main_entry_columns
return columns
def _construct_tuple_insert_values(self, creature):
'''Constructs a tuple of Creature values for insertion into
the "creatures" table
:returns tuple of values for insertion into "creatures" table
'''
values = (creature.name,)
# set value of CR column depending on flag
if self.using_nominal_cr:
values = values + ('CR ' + creature.cr,)
else:
values = values + (creature.cr,)
# add the remaining database fields to values tuple
main_entry_values = (
creature.hp,
creature.hd,
creature.ac['AC'],
creature.ac['touch'],
creature.ac['flat-footed'],
creature.saves['Fort'],
creature.saves['Ref'],
creature.saves['Will'],
creature.ability_scores['Str'],
creature.ability_scores['Dex'],
creature.ability_scores['Con'],
creature.ability_scores['Int'],
creature.ability_scores['Wis'],
creature.ability_scores['Cha'],
creature.bab,
creature.cmb,
creature.cmd
)
values = values + main_entry_values
return values
def _create_table(self):
'''Creates a SQLite table with the given name for storing
Creature objects if it does not already exist
:param name: a string value for the name of the table
'''
# create table
columns = self._construct_table_columns()
query = '''create table if not exists creatures
(
%s,%s,
%s,%s,
%s,%s,%s,
%s,%s,%s,
%s,%s,%s,%s,%s,%s,%s,
%s, %s, %s
)''' % columns
self.connection.execute(query)
def add_creature(self, creature):
'''Adds a Creature object as a row in the appropriate table
of the SQLite database
:param creature: a Creature object to be added to the database
'''
# check that creature CR is within desired range
creature_cr = float(creature.cr)
if creature_cr < self.min_cr or creature_cr > self.max_cr:
return
# ignore duplicate creatures<|fim▁hole|> # insert creature into database
values = self._construct_tuple_insert_values(creature)
query = '''insert into creatures
(
name,CR,
hp,HD,
ac,touch_ac,flatfooted_ac,
Fort, Ref, Will,
Str,Dex,Con,Int,Wis,Cha,
BAB,CMB,CMD
)
values
(
?,?,
?,?,
?,?,?,
?,?,?,
?,?,?,?,?,?,
?,?,?
)'''
self.connection.execute(query, values)
def commit_and_close(self):
'''Commits any uncommitted changes to the SQLite database and
closes the connection
'''
self.connection.commit()
self.connection.close()
def export_as_csv(self, file_name='creature.csv'):
'''Exports the data in this object as a .csv file.
:param file_name: the name of the output csv file
'''
cursor = self.connection.cursor()
data = cursor.execute('select * from creatures')
# write data to output file
csv_file = open(file_name, 'w')
writer = csv.writer(csv_file)
writer.writerow([
'id',
'name', 'CR',
'hp', 'HD',
'ac', 'touch_ac', 'flatfooted_ac',
'Fort', 'Ref', 'Will',
'Str', 'Dex', 'Con', 'Int', 'Wis', 'Cha',
'BAB', 'CMB', 'CMD'
])
writer.writerows(data)
csv_file.close()
def is_creature_in_db(self, creature):
''' Determines whether or not a datbase entry exists for a
given creature
:returns True if entry exists, False otherwise
'''
# set value of CR column depending on flag
creature_cr = creature.cr
if self.using_nominal_cr:
creature_cr = 'CR ' + creature.cr
# query database for creature
values = (creature.name, creature_cr)
query = '''select * from creatures where name=? and cr=?'''
cursor = self.connection.cursor()
cursor.execute(query, values)
return cursor.fetchone() is not None<|fim▁end|> | if self.is_creature_in_db(creature):
return |
<|file_name|>editor_plugin.js<|end_file_name|><|fim▁begin|>(function() {
var preview = true;
var themeShortcuts = {
insert: function(where) {
switch(where) {
case 'st_button_more':
var href = jQuery("#btn_more_src").val();
var what = '[st_button_more href="'+href+'"]';
break;
case 'st_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'"]'+text+'[/st_button]';
break;
case 'st_hover_fill_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var hover_bg = jQuery("#hover_bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var hover_direction = jQuery("#hover_direction").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_fill_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" hover_background="'+hover_bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" hover_direction="'+hover_direction+'"]'+text+'[/st_hover_fill_button]';
break;
case 'st_hover_fancy_icon_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var icon_color = jQuery("#icon_color").val();
var icon_bg = jQuery("#icon_bg").val();
var target = jQuery("#target").val();
var icon_position = jQuery("#icon_pos").val();
var icon_separator = jQuery("#icon_sep").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_fancy_icon_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" icon_color="'+icon_color+'" icon_background="'+icon_bg+'" icon_position="'+icon_position+'" icon_separator="'+icon_separator+'" border_radius="'+border_radius+'"]'+text+'[/st_hover_fancy_icon_button]';
break;
case 'st_hover_arrows_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var arrow_direction = jQuery("#arrow_direction").val();
var what = '[st_hover_arrows_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" arrow_direction="'+arrow_direction+'"]'+text+'[/st_hover_arrows_button]';
break;
case 'st_hover_icon_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_radius = jQuery("#border_radius").val();
var icon_direction = jQuery("#icon_direction").val();
var what = '[st_hover_icon_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" icon_direction="'+icon_direction+'" border_radius="'+border_radius+'"]'+text+'[/st_hover_icon_button]';
break;
case 'st_hover_bordered_button':
var text = jQuery("#text").val();
var text_color = jQuery("#color").val();
var link = jQuery("#link").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var icon = jQuery("#name").val();
var target = jQuery("#target").val();
var border_type = jQuery("#border_type").val();
var border_radius = jQuery("#border_radius").val();
var what = '[st_hover_bordered_button text_color="'+text_color+'" link="'+link+'" background="'+bg+'" size="'+size+'" target="'+target+'" icon="'+icon+'" border_radius="'+border_radius+'" border_type="'+border_type+'"]'+text+'[/st_hover_bordered_button]';
break;
case 'st_unordered':
var list = '<li>First list item</li>';
var listicon = jQuery("#listicon").val();
var what = '[st_unordered listicon="'+listicon+'"]'+list+'[/st_unordered]';
break;
case 'st_box':
var title = jQuery("#box_title").val();
var text = jQuery("#text").val();
var type = jQuery("#box_type").val();
var what = '[st_box title="'+title+'" type="'+type+'"]'+text+'[/st_box]';
break;
case 'st_callout':
var title = jQuery("#callout_title").val();
var text = jQuery("#text").val();
var btn_text = jQuery("#btn_text").val();
var btn_link = jQuery("#btn_link").val();
var text_color = jQuery("#color").val();
var bg = jQuery("#bg").val();
var what = '[st_callout title="'+title+'" button_text="'+btn_text+'" link="'+btn_link+'" text_color="'+text_color+'" background="'+bg+'"]'+text+'[/st_callout]';
break;
case 'st_tooltip':
var text = jQuery("#text").val();
var tooltip_text = jQuery("#tooltip_text").val();
var type = jQuery("#tooltip_type").val();
var what = '[st_tooltip type="'+type+'" tooltip_text="'+tooltip_text+'"]'+text+'[/st_tooltip]';
break;
case 'st_popover':
var content = 'Your text here';
var title = jQuery("#popover_title").val();
var text = jQuery("#popover_text").val();
var type = jQuery("#popover_type").val();
var what = '[st_popover type="'+type+'" popover_title="'+title+'" text="'+text+'"]'+content+'[/st_popover]';
break;
case 'st_modal':
var title = jQuery("#modal_title").val();
var content = jQuery("#modal_text").val();
var modal_link = jQuery("#modal_link").val();
var primary_text = jQuery("#primary").val();
var primary_link = jQuery("#primary_link").val();
var what = '[st_modal modal_link="'+modal_link+'" primary_text="'+primary_text+'" primary_link="'+primary_link+'" modal_title="'+title+'"]'+content+'[/st_modal]';
break;
case 'st_tables':
var colsEl = jQuery("#cols");
var rowsEl = jQuery("#rows");
var cols = new Array();
var rows = new Array();
for(var i=0; i<jQuery(rowsEl).val(); i++) {
for(var j=0; j<jQuery(colsEl).val(); j++) {
if(i == 0) {
cols.push(jQuery('#input_'+i+''+j).val());
} else if (i == 1) {
rows.push(jQuery('#input_'+i+''+j).val());
j = jQuery(colsEl).val();
} else {
rows.push(jQuery('#input_'+i+''+j).val());
}
}
}
var what = '[st_table cols="'+cols.join('||')+'" data="'+rows.join('||')+'"]';
break;
case 'st_tabs':
var tabs = '';
var boxes = jQuery(".box");
boxes.splice(0,1);
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
tabs += '[st_tab title="'+title+'"]'+text+'[/st_tab]';
});
var what = '[st_tabs]'+tabs+'[/st_tabs]';
break;
case 'st_toggle':
var accs = '';
var boxes = jQuery(".box");
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
var state = jQuery(this).find('select').val();
accs += '[st_panel title="'+title+'" state="'+state+'"]'+text+'[/st_panel]<br />';
});
var what = '[st_toggle]<br />'+accs+'[/st_toggle]';
break;
case 'st_accordion':
var accs = '';
var boxes = jQuery(".box");
jQuery(boxes).each(function() {
var title = jQuery(this).find('input').val();
var text = jQuery(this).find('textarea').val();
var state = jQuery(this).find('select').val();
accs += '[st_acc_panel title="'+title+'" state="'+state+'"]'+text+'[/st_acc_panel]<br />';
});
var what = '[st_accordion]<br />'+accs+'[/st_accordion]';
break;
case 'st_progress_bar':
var width = jQuery("#width").val();
var style = jQuery("#style").val();
var striped = jQuery("#striped").val();
var active = jQuery("#active").val();
var what = '[st_progress_bar width="'+width+'" style="'+style+'" striped="'+striped+'" active="'+active+'"]';
break;
case 'st_related_posts':
var limit = jQuery("#limit").val();
var what = '[st_related_posts limit="'+limit+'"]';
break;
case 'st_highlight':
var background_color = jQuery("#background_color").val();
var text_color = jQuery("#text_color").val();
var what = '[st_highlight background_color="'+background_color+'" text_color="'+text_color+'"]Highlighted text[/st_highlight]';
break;
case 'st_loginout':
var text_col = jQuery("#color").val();
var bg = jQuery("#bg").val();
var size = jQuery("#size").val();
var type = jQuery("#login_type").val();
var target = jQuery("#target").val();
var login_msg = jQuery("#login_msg").val();
var logout_msg = jQuery("#logout_msg").val();
var what = '[st_loginout text_col="'+text_col+'" background="'+bg+'" size="'+size+'" login_msg="'+login_msg+'" logout_msg="'+logout_msg+'"]';
break;
case 'st_quote':
var author = jQuery("#author-name").val();
var content = jQuery("#text").val();
var what = '[st_quote author="'+author+'"]' +content+ '[/st_quote]';
break;
case 'st_abbreviation':
var text = jQuery("#text").val();
var abbreviation = jQuery("#abbreviation").val();
var what = '[st_abbr title="'+abbreviation+'"]' + text + '[/st_abbr]';
break;
case 'st_twitter':
var style = jQuery("#style").val();
var url = jQuery("#url").val();
var sourceVal = jQuery("#source").val();
var related = jQuery("#related").val();
var text = jQuery("#text").val();
var lang = jQuery("#lang").val();
var what = '[st_twitter style="'+style+'" url="'+url+'" source="'+sourceVal+'" related="'+related+'" text="'+text+'" lang="'+lang+'"]';
break;
case 'st_digg':
var style = jQuery("#style").val();
var link = jQuery("#link").val();
var title = jQuery("#digg_title").val();
var what = '[st_digg style="'+style+'" title="'+title+'" link="'+link+'"]';
break;
case 'st_fblike':
var style = jQuery("#style").val();
var url = jQuery("#url").val();
var show_faces = jQuery("#show_faces").val();
var width = jQuery("#width").val();
var verb = jQuery("#verb_to_display").val();
var font = jQuery("#font").val();
var what = '[st_fblike url="'+url+'" style="'+style+'" showfaces="'+show_faces+'" width="'+width+'" verb="'+verb+'" font="'+font+'"]';
break;
case 'st_fbshare':
var url = jQuery("#link").val();
var what = '[st_fbshare url="'+url+'"]';
break;
case 'st_lishare':
var style = jQuery("#style").val();
var url = jQuery("#link").val();
var sourceVal = jQuery("#source").val();
var related = jQuery("#related").val();
var text = jQuery("#text").val();
var lang = jQuery("#lang").val();
var what = '[st_linkedin_share url="'+url+'" style="'+style+'"]';
break;
case 'st_gplus':
var style = jQuery("#style").val();
var size = jQuery("#size").val();
var what = '[st_gplus style="'+style+'" size="'+size+'"]';
break;
case 'st_pinterest_pin':
var style = jQuery("#style").val();
var what = '[st_pinterest_pin style="'+style+'"]';
break;
case 'st_tumblr':
var style = jQuery("#style").val();
var what = '[st_tumblr style="'+style+'"]';
break;
case 'st_pricingTable':
var content = '';
var columns = jQuery("#columns").val();
var highlighted = jQuery("#highlighted").val();
for(x=0;x<columns;x++) {
var highlight = ((x+1) == highlighted) ? " highlight='true'" : '';
content += "\n[st_pricing_column title='Column " + (x+1) + "'" + highlight + "]\n[st_price_info cost='$14.99/month'][/st_price_info]<ul><li>Item description and details...</li>\n<li>Item description and details...</li>\n<li>Some more info...</li>\n<li>[st_button text_color='#444444' link='#' background='#E6E6E6' size='small']Button text[/st_button]</li></ul>\n[/st_pricing_column]\n";
}
var what = "[st_pricing_table columns='"+columns+"']\n" + content + "\n[/st_pricing_table]";
break;
case 'st_gmap':
var additional = '';
additional = (jQuery("#latitude").val() != '') ? additional + ' latitude="'+ jQuery("#latitude").val() +'"' : additional;
additional = (jQuery("#longitute").val() != '') ? additional + ' longitute="'+ jQuery("#longitute").val() +'"' : additional;
additional = (jQuery("#html").val() != '') ? additional + ' html="'+ jQuery("#html").val() +'"' : additional;
additional = (jQuery("#zoom").val() != '') ? additional + ' zoom="'+ jQuery("#zoom").val() +'"' : additional;
additional = (jQuery("#gheight").val() != '') ? additional + ' height="'+ jQuery("#gheight").val() +'"' : additional;
additional = (jQuery("#gwidth").val() != '') ? additional + ' width="'+ jQuery("#gwidth").val() +'"' : additional;
additional = (jQuery("#maptype").val() != '') ? additional + ' maptype="'+ jQuery("#maptype").val() +'"' : additional;
additional = (jQuery("#color").val() != '') ? additional + ' color="'+ jQuery("#color").val() +'"' : additional;
var what = '[st_gmap '+additional+']';
break;
case 'st_trends':
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var query = jQuery("#query").val();
var geo = jQuery("#geo").val();
var what = '[st_trends width="'+width+'" height="'+height+'" query="'+query+'" geo="'+geo+'"]';
break;
case 'st_gchart':
var data = jQuery("#data").val();
var title = jQuery("#g_title").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var series_type = jQuery("#series_type").val();
var vAxis = jQuery("#vAxis").val();
var hAxis = jQuery("#hAxis").val();
var type = jQuery("#gchart_type").val();
var red_from = jQuery("#red_from").val();
var red_to = jQuery("#red_to").val();
var yellow_from = jQuery("#yellow_from").val();
var yellow_to = jQuery("#yellow_to").val();
var gauge_minor_ticks = jQuery("#gauge_minor_ticks").val();
var what = '[st_chart title="'+title+'" data="'+data+'" width="'+width+'" height="'+height+'" type="'+type+'" series_type="'+series_type+'" vAxis="'+vAxis+'" hAxis="'+hAxis+'" red_from="'+red_from+'" red_to="'+red_to+'" yellow_from="'+yellow_from+'" yellow_to="'+yellow_to+'" gauge_minor_ticks="'+gauge_minor_ticks+'"]';
break;
case 'st_chart_pie':
var data = jQuery("#data").val();
var title = jQuery("#pie_title").val();
var what = '[st_chart_pie title="'+title+'" data="'+data+'"]';
break;
case 'st_chart_bar':
var data = jQuery("#data").val();
var title = jQuery("#bar_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var what = '[st_chart_bar title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'"]';
break;
case 'st_chart_area':
var data = jQuery("#data").val();
var title = jQuery("#area_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var what = '[st_chart_area title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'"]';
break;
case 'st_chart_geo':
var data = jQuery("#data").val();
var title = jQuery("#geo_title").val();
var primary = jQuery("#primary").val();
var secondary = jQuery("#secondary").val();
var what = '[st_chart_geo title="'+title+'" data="'+data+'" primary="'+primary+'" secondary="'+secondary+'"]';
break;
case 'st_chart_combo':
var data = jQuery("#data").val();
var title = jQuery("#combo_title").val();
var vaxis = jQuery("#vaxis_title").val();
var haxis = jQuery("#haxis_title").val();
var series = jQuery("#series").val();
var what = '[st_chart_combo title="'+title+'" data="'+data+'" vaxis="'+vaxis+'" haxis="'+haxis+'" series="'+series+'"]';
break;
case 'st_chart_org':
var data = jQuery("#data").val();
var what = '[st_chart_org data="'+data+'"]';
break;
case 'st_chart_bubble':
var data = jQuery("#data").val();
var title = jQuery("#bubble_title").val();
var primary = jQuery("#primary").val();
var secondary = jQuery("#secondary").val();
var what = '[st_chart_bubble title="'+title+'" data="'+data+'" primary="'+primary+'" secondary="'+secondary+'"]';
break;
case 'st_gdocs':
var url = jQuery("#url").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var what = "[st_gdocs width='"+width+"' height='"+height+"' url='"+ url +"']";
break;
case 'st_children':
var parent = jQuery("#page").val();
var what = "[st_children of='"+ parent +"']";
break;
case 'st_contact_form_dark':
var email_d = jQuery("#email_d").val();
var what = "[st_contact_form_dark email='"+ email_d +"']";
break;
case 'st_contact_form_light':
var email_l = jQuery("#email_l").val();
var what = "[st_contact_form_light email='"+ email_l +"']";
break;
case 'st_fancyboxImages':
var href = jQuery("#href").val();
var thumb = jQuery("#thumb").val();
var thumb_width = jQuery("#thumb_width").val();
var group = jQuery("#group").val();
var title = jQuery("#title_lb").val();
var what = "[st_fancyboxImages href='"+ href +"' thumb='"+thumb+"' thumb_width='"+thumb_width+"' group='"+group+"' title='"+title+"']";
break;
case 'st_fancyboxInline':
var title = jQuery("#in_title").val();
var content_title = jQuery("#content_title").val();
var content = jQuery("#in_content").val();
var what = "[st_fancyboxInline title='"+title+"' content_title='"+content_title+"' content='"+content+"']";
break;
case 'st_fancyboxIframe':
var title = jQuery("#iframe_title").val();
var href = jQuery("#iframe_href").val();
var what = "[st_fancyboxIframe title='"+title+"' href='"+ href +"']";
break;
case 'st_fancyboxPage':
var title = jQuery("#ipage_title").val();
var href = jQuery("#ipage").val();
var what = "[st_fancyboxPage title='"+title+"' href='"+ href +"']";
break;
case 'st_fancyboxSwf':
var title = jQuery("#swf_title").val();
var href = jQuery("#swf").val();
var what = "[st_fancyboxSwf title='"+title+"' href='"+href+"']";
break;
case 'st_video':
var title = jQuery("#video_title").val();
var display = jQuery("#display").val();
var width = jQuery("#width").val();
var height = jQuery("#height").val();
var type = jQuery("#video_type").val();
if (type == 'flash') {
var src = jQuery("#src").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' src='"+src+"']";
} else if (type == 'html5') {
var poster = jQuery("#poster").val();
var mp4 = jQuery("#mp4").val();
var webm = jQuery("#webm").val();
var ogg = jQuery("#ogg").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' poster='"+poster+"' mp4='"+mp4+"' webm='"+webm+"' ogg='"+ogg+"']";
} else {
var src = jQuery("#clip_id").val();
var what = "[st_video title='"+title+"' type='"+ type +"' width='"+width+"' height='"+height+"' src='"+src+"']";
}
var group = jQuery("#group").val();
var title = jQuery("#title_lb").val();
break;
case 'st_audio':
var title = jQuery("#audio_title").val();
var src = jQuery("#audio_src").val();
var what = "[st_audio title='"+title+"' src='"+src+"']";
break;
case 'st_soundcloud':
var src = jQuery("#sound_src").val();
var color = jQuery("#sound_color").val();
var what = "[st_soundcloud color='"+color+"' src='"+src+"']";
break;
case 'st_mixcloud':
var src = jQuery("#mix_src").val();
var width = jQuery("#mix_width").val();
var height = jQuery("#mix_height").val();
var what = "[st_mixcloud width='"+width+"' height='"+height+"' src='"+src+"']";
break;
case 'st_section_image':
var image_id = jQuery("#imageid").val();
var bg_color = jQuery("#bg_color").val();
var type = jQuery("#section_image_type").val();
var bg_position = jQuery("#bg_position").val();
var bg_size = jQuery("#bg_size").val();
var repeat = jQuery("#repeat").val();
var padding = jQuery("#img_padding").val();
var what = "[st_section_image image_id='"+image_id+"' bg_color='"+bg_color+"' type='"+type+"' position='"+bg_position+"' bg_size='"+bg_size+"' repeat='"+repeat+"' padding='"+padding+"']Section content goes here[/st_section_image]";
break;
case 'st_section_color':
var color = jQuery("#color").val();
var padding = jQuery("#col_padding").val();
var what = "[st_section_color color='"+color+"' padding='"+padding+"']Section content goes here[/st_section_color]";
break;
case 'st_text_color':
var color = jQuery("#color").val();
var what = "[st_text_color color='"+color+"']Text goes here[/st_text_color]";
break;
case 'st_posts_carousel':
var posts = jQuery("#posts").val();
var number = jQuery("#number").val();
var cat = jQuery("#cat").val();
var display_title = jQuery("#display_title").val();
var what = "[st_posts_carousel posts='"+posts+"' number='"+number+"' cat='"+cat+"' display_title='"+display_title+"']";
break;
case 'st_swiper':
var posts = jQuery("#swiper_posts").val();
var number = jQuery("#swiper_number").val();
var category = jQuery("#category").val();
var display_title = jQuery("#display_title").val();
var what = "[st_swiper posts='"+posts+"' number='"+number+"' category='"+category+"' display_title='"+display_title+"']";
break;
case 'st_animated':
var type = jQuery("#animated_type").val();
var trigger = jQuery("#trigger").val();
var precent = jQuery("#precent").val();
var what = "[st_animated type='"+type+"' trigger='"+trigger+"' precent='"+precent+"']Animated element goes here[/st_animated]";
break;
case 'st_svg_drawing':
var type = jQuery("#drawing_type").val();
var image_id = jQuery("#image_id").val();
var color = jQuery("#drawing_color").val();
var what = "[st_svg_drawing type='"+type+"' image_id='"+image_id+"' color='"+color+"']";
break;
case 'st_animated_boxes':
var posts = jQuery("#posts").val();
var what = "[st_animated_boxes posts='"+posts+"']";
break;
case 'st_icon':
var name = jQuery("#name").val();
var size = jQuery("#size").val();
var type = jQuery("#icon_type").val();
var color = jQuery("#icon_color").val();
var bg_color = jQuery("#icon_bg_color").val();
var border_color = jQuery("#icon_border_color").val();
var align = jQuery("#align").val();
var what = "[st_icon name='"+name+"' size='"+size+"' color='"+color+"' type='"+type+"' background='"+bg_color+"' border_color='"+border_color+"' align='"+align+"']";
break;
case 'st_icon_melon':
var name = jQuery("#name").val();
var size = jQuery("#size").val();
var type = jQuery("#icon_type").val();
var color = jQuery("#icon_color").val();
var bg_color = jQuery("#icon_bg_color").val();
var border_color = jQuery("#icon_border_color").val();
var align = jQuery("#align").val();
var what = "[st_icon_melon name='"+name+"' size='"+size+"' color='"+color+"' type='"+type+"' background='"+bg_color+"' border_color='"+border_color+"' align='"+align+"']";
break;
case 'st_social_icon':
var name = jQuery("#name").val();
var href = jQuery("#href").val();
var target = jQuery("#target").val();
var align = jQuery("#align").val();
var what = "[st_social_icon name='"+name+"' href='"+href+"' target='"+target+"' align='"+align+"']";
break;
case 'st_divider_text':
var type = jQuery("#divider_type").val();
var text = jQuery("#text").val();
var what = "[st_divider_text position='"+type+"' text='"+text+"']";
break;
case 'st_countdown':
var id = jQuery("#event_id").val();
var align = jQuery("#countdown_align").val();
var what = "[st_countdown id='"+id+"' align='"+align+"']";
break;
case 'st_testimonials':
var color = jQuery("#color").val();
var number = jQuery("#number").val();
var what = "[st_testimonials color='"+color+"' number='"+number+"']";
break;
}
if(this.validate()) {
if(preview === true) {
var values = {
'data': what
};
jQuery.ajax({
url: stPluginUrl + '/ajaxPlugin.php?act=preview',
type: 'POST',
data: values,
loading: function() {
jQuery("#previewDiv").empty().html('<div class="loading"> </div>')
},
success: function(response) {
jQuery("#previewDiv").empty().html(response);
}
});
} else {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, what);
}
}
},
validate: function() {
ret = true;
jQuery('.req').each(function() {
if(jQuery(this).find('input').val() == '') {
ret = false;
jQuery(this).find('input').addClass('errorInput');
} else {
jQuery(this).find('input').removeClass('errorInput');
}
if(jQuery(this).find('textarea').val() == '') {
ret = false;
jQuery(this).find('textarea').addClass('errorInput');
} else {
jQuery(this).find('textarea').removeClass('errorInput');
}
});
return ret;
},
readMore: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=readMore&preview');
what = 'st_button_more';
},
breakLine: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_break_line]");
},
horizontalLine: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_horizontal_line]");
},
divClear: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_clear]");
},
createDividerDotted: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_dotted]");
},
createDividerDashed: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_dashed]");
},
createDividerTop: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_top]");
},
createDividerShadow: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_divider_shadow]");
},
insertButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertButton&preview');
what = 'st_button';
},
insertHoverFillButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverFillButton&preview');
what = 'st_hover_fill_button';
},
insertHoverFancyIconButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverFancyIconButton&preview');
what = 'st_hover_fancy_icon_button';
},
insertHoverArrowsButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverArrowsButton&preview');
what = 'st_hover_arrows_button';
},
insertHoverIconOnHoverButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverIconOnHoverButton&preview');
what = 'st_hover_icon_button';
},
insertHoverBorderedButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertHoverBorderedButton&preview');
what = 'st_hover_bordered_button';
},
insertBox: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertBox&preview');
what = 'st_box';
},
dividerText: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=dividerText&preview');
what = 'st_divider_text';
},
eventCountdown: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=eventCountdown');
what = 'st_countdown';
},
createTestimonials: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=testimonials');
what = 'st_testimonials';
},
insertCallout: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertCallout&preview');
what = 'st_callout';
},
insertTooltip: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertTooltip&preview=remove');
what = 'st_tooltip';
},
insertPopover: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertPopover&preview=remove');
what = 'st_popover';
},
insertModal: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=insertModal&preview=remove');
what = 'st_modal';
},
createTabs: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createTabs&preview=remove');
what = 'st_tabs';
},
createUnorderedList: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createUnorderedList&preview');
what = 'st_unordered';
},
createOrderedList: function() {
var content = (tinyMCE.activeEditor.selection.getContent() != '') ? tinyMCE.activeEditor.selection.getContent() : '<ol><li>First list item</li></ol>';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_ordered]"+ content +"[/st_ordered]");
},
createToggle: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=toggle&preview');
what = 'st_toggle';
},
createAccordion: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createAccordion&preview');
what = 'st_accordion';
},
createProgressBar: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=progress_bar&preview');
what = 'st_progress_bar';
},
createTables: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=createTable&preview');
what = 'st_tables';
},
relatedPosts: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=related&preview=remove');
what = 'st_related_posts';
},
logInOut: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=logInOut&preview');
what = 'st_loginout';
},
dropCap: function(type) {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_dropcap type='"+type+"']"+ tinyMCE.activeEditor.selection.getContent() +"[/st_dropcap]");
},
highlight: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=highlight&preview');
what = 'st_highlight';
},
labels: function(type) {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_label type='"+type+"']"+ tinyMCE.activeEditor.selection.getContent() +"[/st_label]");
},
quote: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=quote&preview');
what = 'st_quote';
},
abbreviation: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=abbreviation&preview');
what = 'st_abbreviation';
},
createTwitterButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=twitter&preview');
what = 'st_twitter';
},
createDiggButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=digg&preview');
what = 'st_digg';
},
createFBlikeButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fblike&preview');
what = 'st_fblike';
},
createFBShareButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fbshare&preview');
what = 'st_fbshare';
},
createLIShareButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=lishare&preview');
what = 'st_lishare';
},
createGplusButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gplus&preview');
what = 'st_gplus';
},
createPinButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=pinterest_pin&preview');
what = 'st_pinterest_pin';
},
createTumblrButton: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=tumblr&preview');
what = 'st_tumblr';
},
createSocialIcon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=social_icon&preview');
what = 'st_social_icon';
},
createPricingTables: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=pricingTable&preview');
what = 'st_pricingTable';
},
createFancyboxImages: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxImages&preview=remove');
what = 'st_fancyboxImages';
},
createFancyboxInline: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxInline&preview=remove');
what = 'st_fancyboxInline';
},
createFancyboxIframe: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxIframe&preview=remove');
what = 'st_fancyboxIframe';
},
createFancyboxPage: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxPage&preview=remove');
what = 'st_fancyboxPage';
},
createFancyboxSwf: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=fancyboxSwf&preview=remove');
what = 'st_fancyboxSwf';
},
createVideo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=video&preview');
what = 'st_video';
},
createAudio: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=audio&preview');
what = 'st_audio';
},
createSoundcloud: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=soundcloud&preview');
what = 'st_soundcloud';
},
createMixcloud: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=mixcloud&preview');
what = 'st_mixcloud';
},
createSectionImage: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=section_image&preview=remove');
what = 'st_section_image';
},
createSectionColor: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=section_color&preview=remove');
what = 'st_section_color';
},
createContainer: function(){
var currentVal = 'Put your content here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_container]"+ currentVal +"[/st_container]");
},
createTextColor: function(){
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=text_color&preview=remove');
what = 'st_text_color';
},
createRow: function(){
var currentVal = 'Put your columns here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_row]"+ currentVal +"[/st_row]");
},
createColumnLayout: function(n) {
var col = '';
var values = {
'st_column1': 'st_column1',
'st_column2': 'st_column2',
'st_column3': 'st_column3',
'st_column4': 'st_column4',
'st_column5': 'st_column5',
'st_column6': 'st_column6',
'st_column7': 'st_column7',
'st_column8': 'st_column8',
'st_column9': 'st_column9',
'st_column10': 'st_column10',
'st_column11': 'st_column11',
'st_column12': 'st_column12',
}
col = values[n];
var currentVal = 'Your content goes here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "["+col+"]"+ currentVal +"[/"+col+"]");
},
createGoogleMaps: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gmap&preview=remove');
what = 'st_gmap';
},
createGoogleTrends: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=trends&preview=remove');
what = 'st_trends';
},
createChartPie: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_pie&preview=remove');
what = 'st_chart_pie';
},
createChartBar: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_bar&preview=remove');
what = 'st_chart_bar';
},
createChartArea: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_area&preview=remove');
what = 'st_chart_area';
},
createChartGeo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_geo&preview=remove');
what = 'st_chart_geo';
},
createChartCombo: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_combo&preview=remove');
what = 'st_chart_combo';
},
createChartOrg: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_org&preview=remove');
what = 'st_chart_org';
},
createChartBubble: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=chart_bubble&preview=remove');
what = 'st_chart_bubble';
},
createGoogleDocs: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=gdocs&preview=remove');
what = 'st_gdocs';
},
pageSiblings: function() {
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_siblings]");
},
children: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=children&preview');
what = 'st_children';
},
contactFormDark: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=contact_form_dark&preview');
what = 'st_contact_form_dark';
},
contactFormLight: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=contact_form_light&preview');
what = 'st_contact_form_light';
},
createCarousel: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=posts_carousel&preview=remove');
what = 'st_posts_carousel';
},
createSwiper: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=swiper&preview=remove');
what = 'st_swiper';
},
insertAnimated: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=animated&preview=remove');
what = 'st_animated';
},
insertDrawing: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=svg_drawing&preview=remove');
what = 'st_svg_drawing';
},
createIcon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=icon&preview');
what = 'st_icon';
},
createIconMelon: function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=melonIcon&preview');
what = 'st_icon_melon';
},
createCode: function() {
var currentVal = 'Put your code here';
tinyMCE.activeEditor.execCommand('mceInsertContent', 0, "[st_code]"+ currentVal +"[/st_code]");
}
};
var what = '';
jQuery('#insert').live('click', function(e) {
preview = false;
e.preventDefault();
themeShortcuts.insert(what);
tb_remove();
return false;
});
jQuery('#preview').live('click', function(e) {
preview = true;
e.preventDefault();
themeShortcuts.insert(what);
return false;
});
jQuery('#SupremeSocialTheme_preview input').live('blur', function() {
preview = true;
setTimeout(function() {
themeShortcuts.insert(what);
}, 300);
});
jQuery('#SupremeSocialTheme_preview select').live('change', function() {
preview = true;
setTimeout(function() {
themeShortcuts.insert(what);
}, 300);
});
jQuery('#cancel').live('click', function(e) {
tb_remove();
return false;
});
///////////////////////////////////////
// CHECK THE VERSION OF TINYMCE !!
///////////////////////////////////////
if (tinymce.majorVersion < 4) {
//////////////////////////////
// IF IS TINYMCE VERSION 3
//////////////////////////////
tinymce.create('tinymce.plugins.themeShortcuts', {
init: function(ed, url) {
},
createControl: function(n, cm) {
switch (n) {
case 'themeShortcuts':
var c = cm.createSplitButton('themeShortcuts', {
title : 'Theme shortcuts',
image : stPluginUrl + '/images/supremetheme-logo-19x19.png',
onclick : function() {
c.showMenu();
}
});
c.onRenderMenu.add(function(c,m) {
e = m.addMenu({title : 'Lines'});
e.add({title : 'Break Line', onclick : themeShortcuts.breakLine});
e.add({title : 'Horizontal Line', onclick : themeShortcuts.horizontalLine});
e.add({title : 'Clear', onclick : themeShortcuts.divClear});
var ea = e.addMenu({title : 'Dividers'});
ea.add({title : 'Dotted', onclick : themeShortcuts.createDividerDotted});
ea.add({title : 'Dashed', onclick : themeShortcuts.createDividerDashed});
ea.add({title : 'To Top', onclick : themeShortcuts.createDividerTop});
ea.add({title : 'Shadow', onclick : themeShortcuts.createDividerShadow});
ea.add({title : 'Text', onclick : themeShortcuts.dividerText});
b = m.addMenu({title : 'Buttons'});
b.add({title : 'Button', onclick : function() { themeShortcuts.insertButton() }});
var ba = b.addMenu({title : 'Hover Buttons'});
ba.add({title: 'Fill In', onclick : themeShortcuts.insertHoverFillButton});
ba.add({title: 'Fancy Icon', onclick : themeShortcuts.insertHoverFancyIconButton});
ba.add({title: 'Arrows', onclick : themeShortcuts.insertHoverArrowsButton});
ba.add({title: 'Icon on hover', onclick : themeShortcuts.insertHoverIconOnHoverButton});
ba.add({title: 'Bordered', onclick : themeShortcuts.insertHoverBorderedButton});
b.add({title : 'Read More', onclick : themeShortcuts.readMore});
var be = b.addMenu({title : 'Share Buttons'});
be.add({title: 'Twitter', onclick : themeShortcuts.createTwitterButton});
be.add({title: 'Digg', onclick : themeShortcuts.createDiggButton});
be.add({title: 'Facebook Like', onclick : themeShortcuts.createFBlikeButton});
be.add({title: 'Facebook Share', onclick : themeShortcuts.createFBShareButton});
be.add({title: 'LinkedIn', onclick : themeShortcuts.createLIShareButton});
be.add({title: 'Google+', onclick : themeShortcuts.createGplusButton});
be.add({title: 'Pinterest', onclick : themeShortcuts.createPinButton});
be.add({title: 'Tumbler', onclick : themeShortcuts.createTumblrButton});
b.add({title : 'Log in / out button', onclick : themeShortcuts.logInOut});
i = m.addMenu({title : 'Boxes'});
i.add({title : 'Box', onclick : themeShortcuts.insertBox});
i.add({title : 'Callout', onclick : themeShortcuts.insertCallout});
p = m.addMenu({title : 'Icons'});
p.add({title : 'Font Awesome', onclick : themeShortcuts.createIcon});
p.add({title : 'Icon Melon', onclick : themeShortcuts.createIconMelon});
p.add({title : 'Social Icons', onclick : themeShortcuts.createSocialIcon});
m.add({title : 'Animated', onclick : themeShortcuts.insertAnimated});
m.add({title : 'SVG Drawing', onclick : themeShortcuts.insertDrawing});
s = m.addMenu({title : 'Elements'});
s.add({title : 'Tooltip', onclick : themeShortcuts.insertTooltip});
s.add({title : 'Popover', onclick : themeShortcuts.insertPopover});
s.add({title : 'Modal', onclick : themeShortcuts.insertModal});
s.add({title : 'Tabs', onclick : themeShortcuts.createTabs});
s.add({title : 'Toggle', onclick : themeShortcuts.createToggle});
s.add({title : 'Accordion', onclick : themeShortcuts.createAccordion});
s.add({title : 'Progress Bar', onclick : themeShortcuts.createProgressBar});
r = m.addMenu({title : 'Section'});
r.add({title : 'Image', onclick : themeShortcuts.createSectionImage});
r.add({title : 'Color', onclick : themeShortcuts.createSectionColor});
m.add({title : 'Container', onclick : themeShortcuts.createContainer});
h = m.addMenu({title : 'Responsive'});
h.add({title : 'Row', onclick : themeShortcuts.createRow});
h.add({title: '1 column', onclick : function() { themeShortcuts.createColumnLayout('st_column1') }});
h.add({title: '2 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column2') }});
h.add({title: '3 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column3') }});
h.add({title: '4 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column4') }});
h.add({title: '5 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column5') }});
h.add({title: '6 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column6') }});
h.add({title: '7 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column7') }});
h.add({title: '8 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column8') }});
h.add({title: '9 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column9') }});
h.add({title: '10 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column10') }});
h.add({title: '11 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column11') }});
h.add({title: '12 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column12') }});
d = m.addMenu({title : 'Google'});
d.add({title : 'Google Maps', onclick : themeShortcuts.createGoogleMaps});
d.add({title : 'Google Trends', onclick : themeShortcuts.createGoogleTrends});
d.add({title : 'Google Docs', onclick : themeShortcuts.createGoogleDocs});
var da = d.addMenu({title : 'Google Charts'});
da.add({title : 'Pie', onclick : themeShortcuts.createChartPie});
da.add({title : 'Bar', onclick : themeShortcuts.createChartBar});
da.add({title : 'Area', onclick : themeShortcuts.createChartArea});
da.add({title : 'Geo', onclick : themeShortcuts.createChartGeo});
da.add({title : 'Combo', onclick : themeShortcuts.createChartCombo});
da.add({title : 'Org', onclick : themeShortcuts.createChartOrg});
da.add({title : 'Bubble', onclick : themeShortcuts.createChartBubble});
f = m.addMenu({title: 'Lists'});
f.add({title : 'Unordered list', onclick : themeShortcuts.createUnorderedList});
f.add({title : 'Ordered list', onclick : themeShortcuts.createOrderedList});
o = m.addMenu({title: 'Tables'});
o.add({title : 'Styled table', onclick : themeShortcuts.createTables});
o.add({title : 'Pricing table', onclick : themeShortcuts.createPricingTables});
l = m.addMenu({title : 'Media'});
l.add({title : 'Video', onclick : themeShortcuts.createVideo});
var la = l.addMenu({title : 'Audio'});
la.add({title : 'Soundcloud', onclick : themeShortcuts.createSoundcloud});
la.add({title : 'Mixcloud', onclick : themeShortcuts.createMixcloud});
la.add({title : 'Other', onclick : themeShortcuts.createAudio});
d = m.addMenu({title: 'Typography'});
var dc = d.addMenu({title : 'Dropcap'});
dc.add({title : 'Light', onclick : function() { themeShortcuts.dropCap('light') }});
dc.add({title : 'Light Circled', onclick : function() {themeShortcuts.dropCap('light_circled')}});
dc.add({title : 'Dark', onclick : function() {themeShortcuts.dropCap('dark')}});
dc.add({title : 'Dark Circled', onclick : function() {themeShortcuts.dropCap('dark_circled')}});
d.add({title : 'Quote', onclick : themeShortcuts.quote});
d.add({title : 'Highlight', onclick : themeShortcuts.highlight});
var df = d.addMenu({title: 'Label'});
df.add({title : 'Default', onclick : function() { themeShortcuts.labels('default') }});
df.add({title : 'New', onclick : function() {themeShortcuts.labels('success')}});
df.add({title : 'Warning', onclick : function() {themeShortcuts.labels('warning')}});
df.add({title : 'Important', onclick : function() {themeShortcuts.labels('important')}});
df.add({title : 'Notice', onclick : function() {themeShortcuts.labels('notice')}});
d.add({title : 'Colored Text', onclick : themeShortcuts.createTextColor});
d.add({title : 'Abbreviation', onclick : themeShortcuts.abbreviation});
p = m.addMenu({title : 'Related'});
p.add({title : 'Related posts', onclick : themeShortcuts.relatedPosts});
p.add({title : 'Siblings', onclick : themeShortcuts.pageSiblings});
p.add({title : 'Children', onclick : themeShortcuts.children});
k = m.addMenu({title : 'Fancybox'});
k.add({title : 'Images', onclick : themeShortcuts.createFancyboxImages});
k.add({title : 'Inline', onclick : themeShortcuts.createFancyboxInline});
k.add({title : 'iFrame', onclick : themeShortcuts.createFancyboxIframe});
k.add({title : 'Page', onclick : themeShortcuts.createFancyboxPage});
k.add({title : 'Swf', onclick : themeShortcuts.createFancyboxSwf});
j = m.addMenu({title : 'Contact form'});
j.add({title : 'Light', onclick : themeShortcuts.contactFormLight});
j.add({title : 'Dark', onclick : themeShortcuts.contactFormDark});
t = m.addMenu({title : 'Carousel'});
t.add({title : 'Post Carousel', onclick : themeShortcuts.createCarousel});
t.add({title : 'Swiper', onclick : themeShortcuts.createSwiper});
//t.add({title : 'Testimonial', onclick : themeShortcuts.createTestimonials});
//m.add({title : 'Countdown', onclick : themeShortcuts.eventCountdown});
m.add({title : 'Code', onclick : themeShortcuts.createCode});
});
return c;
}
return null;
},
});
}else{
//////////////////////////////
// IF IS TINYMCE VERSION 4+
//////////////////////////////
tinymce.create('tinymce.plugins.themeShortcuts', {
init : function(ed, url) {
ed.addButton( 'themeShortcuts', {
type: 'listbox',
text: 'Supreme',
icon: 'supreme',
classes: 'mce-btn supreme-class',
tooltip: 'Supreme Shortcodes',
onselect: function(e) {
},
values: [
{
type: 'listbox',
text: 'Lines',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Break Line', onclick : themeShortcuts.breakLine},
{ text: 'Horizontal Line', onclick : themeShortcuts.horizontalLine},
{ text: 'Clear', onclick : themeShortcuts.divClear},
{
type: 'listbox',
text: 'Dividers',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Dotted', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_dotted]');
}},
{ text: 'Dashed', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_dashed]');
}},
{ text: 'To Top', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_top]');
}},
{ text: 'Shadow', onclick : function() {
tinymce.execCommand('mceInsertContent', false, '[st_divider_shadow]');
}},
{text: 'Text', onclick : function() {
tb_show('', stPluginUrl + '/ajaxPlugin.php?act=dividerText&preview');
what = 'st_divider_text';
}},
]
},
]
},
{
type: 'listbox',
text: 'Buttons',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Button', onclick : function() { themeShortcuts.insertButton() }},
{
type: 'listbox',
text: 'Hover Button',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Fill In', onclick : function() { themeShortcuts.insertHoverFillButton() }},
{text: 'Fancy Icon', onclick : function() { themeShortcuts.insertHoverFancyIconButton() }},
{text: 'Arrows', onclick : function() { themeShortcuts.insertHoverArrowsButton() }},
{text: 'Icon on hover', onclick : function() { themeShortcuts.insertHoverIconOnHoverButton() }},
{text: 'Bordered', onclick : function() { themeShortcuts.insertHoverBorderedButton() }},
]
},
{text: 'Read more', onclick : themeShortcuts.readMore},
{
type: 'listbox',
text: 'Share buttons',
icon: false,
classes: 'has-dropdown',
values: [
{ text: 'Twitter', onclick : themeShortcuts.createTwitterButton},
{ text: 'Digg', onclick : themeShortcuts.createDiggButton},
{ text: 'Facebook Like', onclick : themeShortcuts.createFBlikeButton},
{ text: 'Facebook Share', onclick : themeShortcuts.createFBShareButton},
{ text: 'LinkedIn', onclick : themeShortcuts.createLIShareButton},
{ text: 'Google+', onclick : themeShortcuts.createGplusButton},
{ text: 'Pinterest', onclick : themeShortcuts.createPinButton},
{ text: 'Tumbler', onclick : themeShortcuts.createTumblrButton},
]
},
{text: 'Log in / out button', onclick : themeShortcuts.logInOut},
]
},
{
type: 'listbox',
text: 'Boxes',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Info Box', onclick : themeShortcuts.insertBox},
{text: 'Callout', onclick : themeShortcuts.insertCallout},
]
},
{
type: 'listbox',
text: 'Icons',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Font Awesome', onclick : themeShortcuts.createIcon},
{text: 'Icon Melon', onclick : themeShortcuts.createIconMelon},
{text: 'Social Icons', onclick : themeShortcuts.createSocialIcon},
]
},
{classes: 'no-dropdown', text: 'Animated', onclick : themeShortcuts.insertAnimated},
{classes: 'no-dropdown', text: 'SVG Drawing', onclick : themeShortcuts.insertDrawing},
{
type: 'listbox',
text: 'Elements',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Tooltip', onclick : themeShortcuts.insertTooltip},
{text: 'Popover', onclick : themeShortcuts.insertPopover},
{text: 'Modal', onclick : themeShortcuts.insertModal},
{text: 'Tabs', onclick : themeShortcuts.createTabs},
{text: 'Toggle', onclick : themeShortcuts.createToggle},
{text: 'Accordion', onclick : themeShortcuts.createAccordion},
{text: 'Progress Bar', onclick : themeShortcuts.createProgressBar},
]
},
{
type: 'listbox',
text: 'Section',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Image', onclick : themeShortcuts.createSectionImage},
{text: 'Color', onclick : themeShortcuts.createSectionColor},
]
},
{classes: 'no-dropdown', text: 'Container', onclick : themeShortcuts.createContainer},
{
type: 'listbox',
text: 'Responsive',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Row', onclick : themeShortcuts.createRow},
{text: '1 column', onclick : function() { themeShortcuts.createColumnLayout('st_column1') }},
{text: '2 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column2') }},
{text: '3 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column3') }},
{text: '4 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column4') }},
{text: '5 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column5') }},
{text: '6 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column6') }},
{text: '7 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column7') }},
{text: '8 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column8') }},
{text: '9 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column9') }},
{text: '10 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column10') }},
{text: '11 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column11') }},
{text: '12 columns', onclick : function() { themeShortcuts.createColumnLayout('st_column12') }},
]
},
{
type: 'listbox',
text: 'Google',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Google Maps', onclick : themeShortcuts.createGoogleMaps},
{text: 'Google Trends', onclick : themeShortcuts.createGoogleTrends},
{text: 'Google Docs', onclick : themeShortcuts.createGoogleDocs},
{
type: 'listbox',
text: 'Google Charts',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Pie', onclick : themeShortcuts.createChartPie},
{text: 'Bar', onclick : themeShortcuts.createChartBar},
{text: 'Area', onclick : themeShortcuts.createChartArea},
{text: 'Geo', onclick : themeShortcuts.createChartGeo},
{text: 'Combo', onclick : themeShortcuts.createChartCombo},
{text: 'Org', onclick : themeShortcuts.createChartOrg},
{text: 'Bubble', onclick : themeShortcuts.createChartBubble},
]
},
]
},
{
type: 'listbox',
text: 'Lists',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Unordered list', onclick : themeShortcuts.createUnorderedList},
{text: 'Ordered list', onclick : themeShortcuts.createOrderedList},
]
},
{
type: 'listbox',
text: 'Tables',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Styled table', onclick : themeShortcuts.createTables},
{text: 'Pricing table', onclick : themeShortcuts.createPricingTables},
]
},
{
type: 'listbox',
text: 'Media',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Video', onclick : themeShortcuts.createVideo},
{
type: 'listbox',
text: 'Audio',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Soundcloud', onclick : themeShortcuts.createSoundcloud},
{text: 'Mixcloud', onclick : themeShortcuts.createMixcloud},
{text: 'Other', onclick : themeShortcuts.createAudio},
]
},
]
},
{
type: 'listbox',
text: 'Typography',
icon: false,
classes: 'has-dropdown',
values: [
{
type: 'listbox',
text: 'Dropcap',
icon: false,
values: [
{text: 'Light', onclick : function() {themeShortcuts.dropCap('light')}},
{text: 'Light Circled', onclick : function() {themeShortcuts.dropCap('light_circled')}},
{text: 'Dark', onclick : function() {themeShortcuts.dropCap('dark')}},
{text: 'Dark Circled', onclick : function() {themeShortcuts.dropCap('dark_circled')}},
]
},
{text: 'Quote', onclick : themeShortcuts.quote},
{text: 'Highlight', onclick : themeShortcuts.highlight},
{
type: 'listbox',
text: 'Label',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Default', onclick : function() { themeShortcuts.labels('default') }},
{text: 'New', onclick : function() { themeShortcuts.labels('success') }},
{text: 'Warning', onclick : function() { themeShortcuts.labels('warning') }},
{text: 'Important', onclick : function() { themeShortcuts.labels('important') }},
{text: 'Notice', onclick : function() { themeShortcuts.labels('notice') }},
]
},
{text: 'Colored Text', onclick : themeShortcuts.createTextColor},
{text: 'Abbreviation', onclick : themeShortcuts.abbreviation},
]
},
{
type: 'listbox',
text: 'Related',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Related posts', onclick : themeShortcuts.relatedPosts},
{text: 'Siblings', onclick : themeShortcuts.pageSiblings},
{text: 'Children', onclick : themeShortcuts.children},
]
},
{
type: 'listbox',
text: 'Fancybox',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Images', onclick : themeShortcuts.createFancyboxImages},
{text: 'Inline', onclick : themeShortcuts.createFancyboxInline},
{text: 'iFrame', onclick : themeShortcuts.createFancyboxIframe},
{text: 'Page', onclick : themeShortcuts.createFancyboxPage},
{text: 'Swf', onclick : themeShortcuts.createFancyboxSwf},
]
<|fim▁hole|> {
type: 'listbox',
text: 'Contact form',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Light', onclick : themeShortcuts.contactFormLight},
{text: 'Dark', onclick : themeShortcuts.contactFormDark},
]
},
{
type: 'listbox',
text: 'Carousel',
icon: false,
classes: 'has-dropdown',
values: [
{text: 'Post Carousel', onclick : themeShortcuts.createCarousel},
{text: 'Swiper', onclick : themeShortcuts.createSwiper},
//{text: 'Testimonial', onclick : themeShortcuts.createTestimonials},
]
},
//{classes: 'no-dropdown', text: 'Countdown', onclick : themeShortcuts.eventCountdown},
{classes: 'no-dropdown', text: 'Code', onclick : themeShortcuts.createCode},
]
});
},
});
};//end else
tinymce.PluginManager.add('themeShortcuts', tinymce.plugins.themeShortcuts);
})()<|fim▁end|> | },
|
<|file_name|>d1_sbl_recon.py<|end_file_name|><|fim▁begin|>import re
import sqlite3
import csv
import ast
import os
import sys
import fnmatch
import datetime
import xlrd
import win32com.client
def question_marks(st):
question_marks = '?'
for i in range(0, len(st.split(','))-1):
question_marks = question_marks + ",?"<|fim▁hole|> wb = xlrd.open_workbook(xlsx_file)
ws = wb.sheet_by_index(worksheet)
row_end = ws.nrows if row_end == -1 else row_end
col_end = ws.ncols if col_end == -1 else col_end
arr = [ws.row_values(row, start_colx=col_start, end_colx=col_end-1) for row in range(row_start, row_end)]
header = ','.join(arr[0])
return re.sub(r"[\*\.#/\$%\"\(\)&\- ]", "", header), arr[1:]
def csv_to_arr(csv_file, start=0, end=0, has_header=True, delim=',', ignore_col=""):
arr = []
with open(csv_file, 'rU') as f:
reader = csv.reader(f, delimiter=delim)
arr = list(reader)
header = ""
if has_header:
header = ','.join(arr[start])
if end == 0:
arr = arr[start+1:]
else:
arr = arr[start+1:end]
return re.sub(r"[\*\.#/\$%\d\" ]", "", header), arr
else:
return arr[start:]
return
def arr_to_csv(file_name, header, data_arr):
csv_file = open(file_name, 'wb')
wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL)
wr.writerow(header.split(','))
for data_row in data_arr:
line = []
for ele in data_row:
line.append(str(ele))
wr.writerow(line)
csv_file.close()
return
def arrs_to_xlsx(filename, header=[], arr=[]):
i = 1
xl = win32com.client.Dispatch('Excel.Application')
wb = xl.Workbooks.Add()
for x in range(0, len(header)):
ws = wb.Worksheets(x+1)
for i, cell in enumerate(header[x].split(',')):
ws.Cells(1,i+1).Value = cell
for i, row in enumerate(arr[x]):
for j, cell in enumerate(row):
ws.Cells(i+2,j+1).Value = str(cell)
wb.Worksheets(1).Columns.AutoFit()
wb.Worksheets(1).UsedRange.FormatConditions.Add(win32com.client.constants.xlExpression, "", '=OR(AND(ISNUMBER($C1),$C1<>$D1),AND(ISNUMBER($E1),$E1<>$F1))')
wb.Worksheets(1).UsedRange.FormatConditions(1).Interior.ColorIndex = 6
wb.Worksheets(1).UsedRange.FormatConditions(1).StopIfTrue = False
wb.Worksheets(1).Columns("C:F").NumberFormat = "#,##0_);[Red](#,##0);0;@"
xl.DisplayAlerts = False
wb.SaveAs(filename)
xl.DisplayAlerts = True
wb.Close(True)
return
def db_cur(source = ":memory:"):
conn = sqlite3.connect(source, detect_types=sqlite3.PARSE_DECLTYPES)
# conn.row_factory = sqlite3.Row
cur = conn.cursor()
return conn, cur
def create_tbl(cur, tbl_name, header, arr = [], index_arr = []):
cur.execute("""select count(*) FROM sqlite_master WHERE type='table' AND name = '%s' """ % (tbl_name))
tbl_exists = cur.fetchone()
if tbl_exists[0] == 0:
cur.execute("CREATE TABLE " + tbl_name + " (" + header.replace("id,", "id PRIMARY KEY,") + " );")
for index in index_arr:
cur.execute("CREATE INDEX " + tbl_name + "_" + index + " ON " + tbl_name + " (" + index + ");")
if arr != []:
cur.executemany("INSERT INTO " + tbl_name + " VALUES ("+question_marks(header)+")", arr)
return
def files_lookup(tgt_dir, pattern, recur_list=False, sub_folder=False, most_recent=True):
filepath_arr = []
for fi in os.listdir(tgt_dir):
full_path = os.path.join(tgt_dir, fi)
if sub_folder and os.path.isdir(full_path):
filepath_arr += files_lookup(full_path, pattern, recur_list, sub_folder, most_recent)
if fnmatch.fnmatch(fi, pattern):
filepath_arr.append(full_path)
filepath_arr.sort(reverse=most_recent)
if recur_list:
return filepath_arr
else:
return filepath_arr[0]
def recon_sbl(cur):
sbl_header = "Contract,CPCode,Client,StockCode,G1 O/S,FA O/S,G1 Pending,FA Pending"
create_tbl(cur, "g1_inv", "SBLCODE,CPTY,STOCK,OS,PD")
create_tbl(cur, "fa_inv", "EXT,DESK,STOCK,OS,PD")
cur.execute("""
insert into fa_inv
select ExternalReference, ClientCode, StockCode, sum(case when date('now') > ValueDate then Qty else 0 end), sum(case when date('now') <= ValueDate then Qty else 0 end)
from fasbl
group by ExternalReference, ClientCode, StockCode
""")
cur.execute("""
insert into g1_inv
select SBLCODE, business, STOCK||' HK Equity', sum(case when source = 'os' then QTY else 0 end), sum(case when source = 'pd' then QTY else 0 end)
from (
select sblmap.SBLCode as SBLCODE, sblmap.Name as business, cast(STOCK as int) as STOCK, case when PTYPE = 'B' then -QTY else QTY end as QTY, 'os' as source
from os join sblmap on os.CPTY = sblmap.SBLCode
where cast(STOCK as int) <> 0
UNION ALL
select sblmap.SBLCode as SBLCODE, sblmap.Name as business, cast(STOCK as int) as STOCK, case when (BL = 'L' and STATUS = 'R') or (BL = 'B' and STATUS = 'L') then -QTY else QTY end as QTY, 'pd' as source
from pd join sblmap on pd.CPTY = sblmap.SBLCode
where cast(STOCK as int) <> 0
) aggrg
where STOCK <> ''
group by business, STOCK
""")
cur.execute("""
select EXT, SBLCode, CPTY, STOCK, sbl_os, fa_os, sbl_pd, fa_pd
from (
select EXT, SBLCODE, g1_inv.CPTY as CPTY, g1_inv.STOCK as STOCK, g1_inv.OS as sbl_os, ifnull(fa_inv.OS, 0) as fa_os, g1_inv.PD as sbl_pd, ifnull(fa_inv.PD, 0) as fa_pd
from g1_inv left join fa_inv
on g1_inv.CPTY = fa_inv.DESK
and g1_inv.STOCK = fa_inv.STOCK
union
select EXT, SBLCODE, fa_inv.DESK as CPTY, fa_inv.STOCK as STOCK, ifnull(g1_inv.OS, 0) as sbl_os, fa_inv.OS as fa_os, ifnull(g1_inv.PD, 0) as sbl_pd, fa_inv.PD as fa_pd
from fa_inv left join g1_inv
on g1_inv.CPTY = fa_inv.DESK
and g1_inv.STOCK = fa_inv.STOCK
) consol
where sbl_os <> 0 or fa_os <> 0 or sbl_pd <> 0 or fa_pd <> 0
""")
sbl_arr = cur.fetchall()
# for row in sbl_arr:
# print row
return sbl_header, sbl_arr
def conv_xl_dt(xl_dt):
dt = datetime.datetime.fromordinal(datetime.datetime(1900, 1, 1).toordinal() + int(xl_dt) - 2).date().strftime("%Y-%m-%d")
# tt = dt.timetuple()
return dt
def conv_xl_dt_arr(arr, cols):
return [ [ conv_xl_dt(ele) if idx in cols else ele for idx, ele in enumerate(row) ] for row in arr ]
def main():
conn, cur = db_cur()
pb_dir = os.path.dirname(os.path.abspath(__file__))
# pb_dir = "\\\\p7fs0003\\nd\\3033-Horizon-FA-Share\\PB_DeltaOne\\Daily_Data"
sbl_dir = os.path.dirname(os.path.abspath(__file__))
# sbl_dir = "\\\\P7FS0001\\ED\\SBL\\Reports\\Daily SBL Report\\ReportData"
output_dir = "\\\\p7fs0003\\nd\\3033-Horizon-FA-Share\\PB_DeltaOne\\SBL FA Deltaone Recon"
sblmap_file = files_lookup(pb_dir, "ClientDetails_????????.xlsx")
fasbl_file = files_lookup(pb_dir, "RepoSBLTrade_????????.xlsx")
os_file = files_lookup(sbl_dir, "OS_Trades_Extract_*.CSV")
pd_file = files_lookup(sbl_dir, "Pending_Trades_Extract_*.CSV")
print (sblmap_file)
print (fasbl_file)
print (os_file)
print (pd_file)
trd_date = sblmap_file[-13:-5]
inv_file = os.path.join(output_dir, "FA_G1_SBL_recon_"+trd_date+".xlsx")
sblmap_header, sblmap_arr = xlsx_to_arr(sblmap_file, row_start=1)
sblmap_header = sblmap_header.replace("ClientId", "ClientId1", 1)
fasbl_header, fasbl_arr = xlsx_to_arr(fasbl_file, row_start=1)
fasbl_arr = conv_xl_dt_arr(fasbl_arr, [3, 4])
os_header, os_arr = csv_to_arr(os_file, 1, -1, True, '\t')
pd_header, pd_arr = csv_to_arr(pd_file, 1, -1, True, '\t')
pd_header = pd_header.replace("BL","B_L",1)
create_tbl(cur, "sblmap", sblmap_header, sblmap_arr)
create_tbl(cur, "os", os_header, os_arr)
create_tbl(cur, "pd", pd_header, pd_arr)
create_tbl(cur, "fasbl", fasbl_header, fasbl_arr)
sbl_header, sbl_arr = recon_sbl(cur)
arrs_to_xlsx(inv_file, [sbl_header], [sbl_arr])
return
if __name__ == "__main__":
print ("D1 G1 SBL Recon")
try:
main()
except KeyboardInterrupt:
print ("Ctrl+C pressed. Stopping...")<|fim▁end|> | return question_marks
def xlsx_to_arr(xlsx_file, worksheet=0, row_start=0, col_start=0, row_end=-1, col_end=-1):
arr = [] |
<|file_name|>cursor.js<|end_file_name|><|fim▁begin|>"use strict";
var inherits = require('util').inherits
, f = require('util').format
, formattedOrderClause = require('./utils').formattedOrderClause
, handleCallback = require('./utils').handleCallback
, ReadPreference = require('./read_preference')
, MongoError = require('mongodb-core').MongoError
, Readable = require('stream').Readable || require('readable-stream').Readable
, Define = require('./metadata')
, CoreCursor = require('mongodb-core').Cursor
, Map = require('mongodb-core').BSON.Map
, Query = require('mongodb-core').Query
, CoreReadPreference = require('mongodb-core').ReadPreference;
/**
* @fileOverview The **Cursor** class is an internal class that embodies a cursor on MongoDB
* allowing for iteration over the results returned from the underlying query. It supports
* one by one document iteration, conversion to an array or can be iterated as a Node 0.10.X
* or higher stream
*
* **CURSORS Cannot directly be instantiated**
* @example
* var MongoClient = require('mongodb').MongoClient,
* test = require('assert');
* // Connection url
* var url = 'mongodb://localhost:27017/test';
* // Connect using MongoClient
* MongoClient.connect(url, function(err, db) {
* // Create a collection we want to drop later
* var col = db.collection('createIndexExample1');
* // Insert a bunch of documents
* col.insert([{a:1, b:1}
* , {a:2, b:2}, {a:3, b:3}
* , {a:4, b:4}], {w:1}, function(err, result) {
* test.equal(null, err);
*
* // Show that duplicate records got dropped
* col.find({}).toArray(function(err, items) {
* test.equal(null, err);
* test.equal(4, items.length);
* db.close();
* });
* });
* });
*/
/**
* Namespace provided by the mongodb-core and node.js
* @external CoreCursor
* @external Readable
*/
// Flags allowed for cursor
var flags = ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'exhaust', 'partial'];
var fields = ['numberOfRetries', 'tailableRetryInterval'];
var push = Array.prototype.push;
/**
* Creates a new Cursor instance (INTERNAL TYPE, do not instantiate directly)
* @class Cursor
* @extends external:CoreCursor
* @extends external:Readable
* @property {string} sortValue Cursor query sort setting.
* @property {boolean} timeout Is Cursor able to time out.
* @property {ReadPreference} readPreference Get cursor ReadPreference.
* @fires Cursor#data
* @fires Cursor#end
* @fires Cursor#close
* @fires Cursor#readable
* @return {Cursor} a Cursor instance.
* @example
* Cursor cursor options.
*
* collection.find({}).project({a:1}) // Create a projection of field a
* collection.find({}).skip(1).limit(10) // Skip 1 and limit 10
* collection.find({}).batchSize(5) // Set batchSize on cursor to 5
* collection.find({}).filter({a:1}) // Set query on the cursor
* collection.find({}).comment('add a comment') // Add a comment to the query, allowing to correlate queries
* collection.find({}).addCursorFlag('tailable', true) // Set cursor as tailable
* collection.find({}).addCursorFlag('oplogReplay', true) // Set cursor as oplogReplay
* collection.find({}).addCursorFlag('noCursorTimeout', true) // Set cursor as noCursorTimeout
* collection.find({}).addCursorFlag('awaitData', true) // Set cursor as awaitData
* collection.find({}).addCursorFlag('partial', true) // Set cursor as partial
* collection.find({}).addQueryModifier('$orderby', {a:1}) // Set $orderby {a:1}
* collection.find({}).max(10) // Set the cursor maxScan
* collection.find({}).maxScan(10) // Set the cursor maxScan
* collection.find({}).maxTimeMS(1000) // Set the cursor maxTimeMS
* collection.find({}).min(100) // Set the cursor min
* collection.find({}).returnKey(10) // Set the cursor returnKey
* collection.find({}).setReadPreference(ReadPreference.PRIMARY) // Set the cursor readPreference
* collection.find({}).showRecordId(true) // Set the cursor showRecordId
* collection.find({}).snapshot(true) // Set the cursor snapshot
* collection.find({}).sort([['a', 1]]) // Sets the sort order of the cursor query
* collection.find({}).hint('a_1') // Set the cursor hint
*
* All options are chainable, so one can do the following.
*
* collection.find({}).maxTimeMS(1000).maxScan(100).skip(1).toArray(..)
*/
var Cursor = function(bson, ns, cmd, options, topology, topologyOptions) {
CoreCursor.apply(this, Array.prototype.slice.call(arguments, 0));
var self = this;
var state = Cursor.INIT;
var streamOptions = {};
// Tailable cursor options
var numberOfRetries = options.numberOfRetries || 5;
var tailableRetryInterval = options.tailableRetryInterval || 500;
var currentNumberOfRetries = numberOfRetries;
// Get the promiseLibrary
var promiseLibrary = options.promiseLibrary;
// No promise library selected fall back
if(!promiseLibrary) {
promiseLibrary = typeof global.Promise == 'function' ?
global.Promise : require('es6-promise').Promise;
}
// Set up
Readable.call(this, {objectMode: true});
// Internal cursor state
this.s = {
// Tailable cursor options
numberOfRetries: numberOfRetries
, tailableRetryInterval: tailableRetryInterval
, currentNumberOfRetries: currentNumberOfRetries
// State
, state: state
// Stream options
, streamOptions: streamOptions
// BSON
, bson: bson
// Namespace
, ns: ns
// Command
, cmd: cmd
// Options
, options: options
// Topology
, topology: topology
// Topology options
, topologyOptions: topologyOptions
// Promise library
, promiseLibrary: promiseLibrary
// Current doc
, currentDoc: null
}
// Translate correctly
if(self.s.options.noCursorTimeout == true) {
self.addCursorFlag('noCursorTimeout', true);
}
// Set the sort value
this.sortValue = self.s.cmd.sort;
}
/**
* Cursor stream data event, fired for each document in the cursor.
*
* @event Cursor#data
* @type {object}
*/
/**
* Cursor stream end event
*
* @event Cursor#end
* @type {null}
*/
/**
* Cursor stream close event
*
* @event Cursor#close
* @type {null}
*/
/**
* Cursor stream readable event
*
* @event Cursor#readable
* @type {null}
*/
// Inherit from Readable
inherits(Cursor, Readable);
// Map core cursor _next method so we can apply mapping
CoreCursor.prototype._next = CoreCursor.prototype.next;
for(var name in CoreCursor.prototype) {
Cursor.prototype[name] = CoreCursor.prototype[name];
}
var define = Cursor.define = new Define('Cursor', Cursor, true);
/**
* Check if there is any document still available in the cursor
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.hasNext = function(callback) {
var self = this;
// Execute using callback
if(typeof callback == 'function') {
if(self.s.currentDoc){
return callback(null, true);
} else {
return nextObject(self, function(err, doc) {
if(!doc) return callback(null, false);
self.s.currentDoc = doc;
callback(null, true);
});
}
}
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
if(self.s.currentDoc){
resolve(true);
} else {
nextObject(self, function(err, doc) {
if(self.s.state == Cursor.CLOSED || self.isDead()) return resolve(false);
if(err) return reject(err);
if(!doc) return resolve(false);
self.s.currentDoc = doc;
resolve(true);
});
}
});
}
define.classMethod('hasNext', {callback: true, promise:true});
/**
* Get the next available document from the cursor, returns null if no more documents are available.
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.next = function(callback) {
var self = this;
// Execute using callback
if(typeof callback == 'function') {
// Return the currentDoc if someone called hasNext first
if(self.s.currentDoc) {
var doc = self.s.currentDoc;
self.s.currentDoc = null;
return callback(null, doc);
}
// Return the next object
return nextObject(self, callback)
};
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
// Return the currentDoc if someone called hasNext first
if(self.s.currentDoc) {
var doc = self.s.currentDoc;
self.s.currentDoc = null;
return resolve(doc);
}
nextObject(self, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
}
define.classMethod('next', {callback: true, promise:true});
/**
* Set the cursor query
* @method
* @param {object} filter The filter object used for the cursor.
* @return {Cursor}
*/
Cursor.prototype.filter = function(filter) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.query = filter;
return this;
}
define.classMethod('filter', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor maxScan
* @method
* @param {object} maxScan Constrains the query to only scan the specified number of documents when fulfilling the query
* @return {Cursor}
*/
Cursor.prototype.maxScan = function(maxScan) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.maxScan = maxScan;
return this;
}
define.classMethod('maxScan', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor hint
* @method
* @param {object} hint If specified, then the query system will only consider plans using the hinted index.
* @return {Cursor}
*/
Cursor.prototype.hint = function(hint) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.hint = hint;
return this;
}
define.classMethod('hint', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor min
* @method
* @param {object} min Specify a $min value to specify the inclusive lower bound for a specific index in order to constrain the results of find(). The $min specifies the lower bound for all keys of a specific index in order.
* @return {Cursor}
*/
Cursor.prototype.min = function(min) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.min = min;
return this;
}
define.classMethod('min', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor max
* @method
* @param {object} max Specify a $max value to specify the exclusive upper bound for a specific index in order to constrain the results of find(). The $max specifies the upper bound for all keys of a specific index in order.
* @return {Cursor}
*/
Cursor.prototype.max = function(max) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.max = max;
return this;
}
define.classMethod('max', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor returnKey
* @method
* @param {object} returnKey Only return the index field or fields for the results of the query. If $returnKey is set to true and the query does not use an index to perform the read operation, the returned documents will not contain any fields. Use one of the following forms:
* @return {Cursor}
*/
Cursor.prototype.returnKey = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.returnKey = value;
return this;
}
define.classMethod('returnKey', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor showRecordId
* @method
* @param {object} showRecordId The $showDiskLoc option has now been deprecated and replaced with the showRecordId field. $showDiskLoc will still be accepted for OP_QUERY stye find.
* @return {Cursor}
*/
Cursor.prototype.showRecordId = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.showDiskLoc = value;
return this;
}
define.classMethod('showRecordId', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the cursor snapshot
* @method
* @param {object} snapshot The $snapshot operator prevents the cursor from returning a document more than once because an intervening write operation results in a move of the document.
* @return {Cursor}
*/
Cursor.prototype.snapshot = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.snapshot = value;
return this;
}
define.classMethod('snapshot', {callback: false, promise:false, returns: [Cursor]});
/**
* Set a node.js specific cursor option
* @method
* @param {string} field The cursor option to set ['numberOfRetries', 'tailableRetryInterval'].
* @param {object} value The field value.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.setCursorOption = function(field, value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(fields.indexOf(field) == -1) throw MongoError.create({message: f("option %s not a supported option %s", field, fields), driver:true });
this.s[field] = value;
if(field == 'numberOfRetries')
this.s.currentNumberOfRetries = value;
return this;
}
define.classMethod('setCursorOption', {callback: false, promise:false, returns: [Cursor]});
/**
* Add a cursor flag to the cursor
* @method
* @param {string} flag The flag to set, must be one of following ['tailable', 'oplogReplay', 'noCursorTimeout', 'awaitData', 'partial'].
* @param {boolean} value The flag boolean value.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.addCursorFlag = function(flag, value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(flags.indexOf(flag) == -1) throw MongoError.create({message: f("flag %s not a supported flag %s", flag, flags), driver:true });
if(typeof value != 'boolean') throw MongoError.create({message: f("flag %s must be a boolean value", flag), driver:true});
this.s.cmd[flag] = value;
return this;<|fim▁hole|>}
define.classMethod('addCursorFlag', {callback: false, promise:false, returns: [Cursor]});
/**
* Add a query modifier to the cursor query
* @method
* @param {string} name The query modifier (must start with $, such as $orderby etc)
* @param {boolean} value The flag boolean value.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.addQueryModifier = function(name, value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(name[0] != '$') throw MongoError.create({message: f("%s is not a valid query modifier"), driver:true});
// Strip of the $
var field = name.substr(1);
// Set on the command
this.s.cmd[field] = value;
// Deal with the special case for sort
if(field == 'orderby') this.s.cmd.sort = this.s.cmd[field];
return this;
}
define.classMethod('addQueryModifier', {callback: false, promise:false, returns: [Cursor]});
/**
* Add a comment to the cursor query allowing for tracking the comment in the log.
* @method
* @param {string} value The comment attached to this query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.comment = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.comment = value;
return this;
}
define.classMethod('comment', {callback: false, promise:false, returns: [Cursor]});
/**
* Set a maxAwaitTimeMS on a tailing cursor query to allow to customize the timeout value for the option awaitData (Only supported on MongoDB 3.2 or higher, ignored otherwise)
* @method
* @param {number} value Number of milliseconds to wait before aborting the tailed query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.maxAwaitTimeMS = function(value) {
if(typeof value != 'number') throw MongoError.create({message: "maxAwaitTimeMS must be a number", driver:true});
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.maxAwaitTimeMS = value;
return this;
}
define.classMethod('maxAwaitTimeMS', {callback: false, promise:false, returns: [Cursor]});
/**
* Set a maxTimeMS on the cursor query, allowing for hard timeout limits on queries (Only supported on MongoDB 2.6 or higher)
* @method
* @param {number} value Number of milliseconds to wait before aborting the query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.maxTimeMS = function(value) {
if(typeof value != 'number') throw MongoError.create({message: "maxTimeMS must be a number", driver:true});
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.maxTimeMS = value;
return this;
}
define.classMethod('maxTimeMS', {callback: false, promise:false, returns: [Cursor]});
Cursor.prototype.maxTimeMs = Cursor.prototype.maxTimeMS;
define.classMethod('maxTimeMs', {callback: false, promise:false, returns: [Cursor]});
/**
* Sets a field projection for the query.
* @method
* @param {object} value The field projection object.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.project = function(value) {
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
this.s.cmd.fields = value;
return this;
}
define.classMethod('project', {callback: false, promise:false, returns: [Cursor]});
/**
* Sets the sort order of the cursor query.
* @method
* @param {(string|array|object)} keyOrList The key or keys set for the sort.
* @param {number} [direction] The direction of the sorting (1 or -1).
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.sort = function(keyOrList, direction) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support sorting", driver:true});
if(this.s.state == Cursor.CLOSED || this.s.state == Cursor.OPEN || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
var order = keyOrList;
// We have an array of arrays, we need to preserve the order of the sort
// so we will us a Map
if(Array.isArray(order) && Array.isArray(order[0])) {
order = new Map(order.map(function(x) {
var value = [x[0], null];
if(x[1] == 'asc') {
value[1] = 1;
} else if(x[1] == 'desc') {
value[1] = -1;
} else if(x[1] == 1 || x[1] == -1) {
value[1] = x[1];
} else {
throw new MongoError("Illegal sort clause, must be of the form [['field1', '(ascending|descending)'], ['field2', '(ascending|descending)']]");
}
return value;
}));
}
if(direction != null) {
order = [[keyOrList, direction]];
}
this.s.cmd.sort = order;
this.sortValue = order;
return this;
}
define.classMethod('sort', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the batch size for the cursor.
* @method
* @param {number} value The batchSize for the cursor.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.batchSize = function(value) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support batchSize", driver:true});
if(this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(typeof value != 'number') throw MongoError.create({message: "batchSize requires an integer", driver:true});
this.s.cmd.batchSize = value;
this.setCursorBatchSize(value);
return this;
}
define.classMethod('batchSize', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the limit for the cursor.
* @method
* @param {number} value The limit for the cursor query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.limit = function(value) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support limit", driver:true});
if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(typeof value != 'number') throw MongoError.create({message: "limit requires an integer", driver:true});
this.s.cmd.limit = value;
// this.cursorLimit = value;
this.setCursorLimit(value);
return this;
}
define.classMethod('limit', {callback: false, promise:false, returns: [Cursor]});
/**
* Set the skip for the cursor.
* @method
* @param {number} value The skip for the cursor query.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.skip = function(value) {
if(this.s.options.tailable) throw MongoError.create({message: "Tailable cursor doesn't support skip", driver:true});
if(this.s.state == Cursor.OPEN || this.s.state == Cursor.CLOSED || this.isDead()) throw MongoError.create({message: "Cursor is closed", driver:true});
if(typeof value != 'number') throw MongoError.create({message: "skip requires an integer", driver:true});
this.s.cmd.skip = value;
this.setCursorSkip(value);
return this;
}
define.classMethod('skip', {callback: false, promise:false, returns: [Cursor]});
/**
* The callback format for results
* @callback Cursor~resultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {(object|null|boolean)} result The result object if the command was executed successfully.
*/
/**
* Clone the cursor
* @function external:CoreCursor#clone
* @return {Cursor}
*/
/**
* Resets the cursor
* @function external:CoreCursor#rewind
* @return {null}
*/
/**
* Get the next available document from the cursor, returns null if no more documents are available.
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @throws {MongoError}
* @deprecated
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.nextObject = Cursor.prototype.next;
var nextObject = function(self, callback) {
// console.log("cursor:: nextObject")
if(self.s.state == Cursor.CLOSED || self.isDead && self.isDead()) return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true}));
if(self.s.state == Cursor.INIT && self.s.cmd.sort) {
try {
self.s.cmd.sort = formattedOrderClause(self.s.cmd.sort);
} catch(err) {
return handleCallback(callback, err);
}
}
// Get the next object
self._next(function(err, doc) {
self.s.state = Cursor.OPEN;
if(err) return handleCallback(callback, err);
handleCallback(callback, null, doc);
});
}
define.classMethod('nextObject', {callback: true, promise:true});
// Trampoline emptying the number of retrieved items
// without incurring a nextTick operation
var loop = function(self, callback) {
// No more items we are done
if(self.bufferedCount() == 0) return;
// Get the next document
self._next(callback);
// Loop
return loop;
}
Cursor.prototype.next = Cursor.prototype.nextObject;
define.classMethod('next', {callback: true, promise:true});
/**
* Iterates over all the documents for this cursor. As with **{cursor.toArray}**,
* not all of the elements will be iterated if this cursor had been previouly accessed.
* In that case, **{cursor.rewind}** can be used to reset the cursor. However, unlike
* **{cursor.toArray}**, the cursor will only hold a maximum of batch size elements
* at any given time if batch size is specified. Otherwise, the caller is responsible
* for making sure that the entire result can fit the memory.
* @method
* @deprecated
* @param {Cursor~resultCallback} callback The result callback.
* @throws {MongoError}
* @return {null}
*/
Cursor.prototype.each = function(callback) {
// Rewind cursor state
this.rewind();
// Set current cursor to INIT
this.s.state = Cursor.INIT;
// Run the query
_each(this, callback);
};
define.classMethod('each', {callback: true, promise:false});
// Run the each loop
var _each = function(self, callback) {
if(!callback) throw MongoError.create({message: 'callback is mandatory', driver:true});
if(self.isNotified()) return;
if(self.s.state == Cursor.CLOSED || self.isDead()) {
return handleCallback(callback, MongoError.create({message: "Cursor is closed", driver:true}));
}
if(self.s.state == Cursor.INIT) self.s.state = Cursor.OPEN;
// Define function to avoid global scope escape
var fn = null;
// Trampoline all the entries
if(self.bufferedCount() > 0) {
while(fn = loop(self, callback)) fn(self, callback);
_each(self, callback);
} else {
self.next(function(err, item) {
if(err) return handleCallback(callback, err);
if(item == null) {
self.s.state = Cursor.CLOSED;
return handleCallback(callback, null, null);
}
if(handleCallback(callback, null, item) == false) return;
_each(self, callback);
})
}
}
/**
* The callback format for the forEach iterator method
* @callback Cursor~iteratorCallback
* @param {Object} doc An emitted document for the iterator
*/
/**
* The callback error format for the forEach iterator method
* @callback Cursor~endCallback
* @param {MongoError} error An error instance representing the error during the execution.
*/
/**
* Iterates over all the documents for this cursor using the iterator, callback pattern.
* @method
* @param {Cursor~iteratorCallback} iterator The iteration callback.
* @param {Cursor~endCallback} callback The end callback.
* @throws {MongoError}
* @return {null}
*/
Cursor.prototype.forEach = function(iterator, callback) {
this.each(function(err, doc){
if(err) { callback(err); return false; }
if(doc != null) { iterator(doc); return true; }
if(doc == null && callback) {
var internalCallback = callback;
callback = null;
internalCallback(null);
return false;
}
});
}
define.classMethod('forEach', {callback: true, promise:false});
/**
* Set the ReadPreference for the cursor.
* @method
* @param {(string|ReadPreference)} readPreference The new read preference for the cursor.
* @throws {MongoError}
* @return {Cursor}
*/
Cursor.prototype.setReadPreference = function(r) {
if(this.s.state != Cursor.INIT) throw MongoError.create({message: 'cannot change cursor readPreference after cursor has been accessed', driver:true});
if(r instanceof ReadPreference) {
this.s.options.readPreference = new CoreReadPreference(r.mode, r.tags);
} else if(typeof r == 'string'){
this.s.options.readPreference = new CoreReadPreference(r);
} else if(r instanceof CoreReadPreference) {
this.s.options.readPreference = r;
}
return this;
}
define.classMethod('setReadPreference', {callback: false, promise:false, returns: [Cursor]});
/**
* The callback format for results
* @callback Cursor~toArrayResultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {object[]} documents All the documents the satisfy the cursor.
*/
/**
* Returns an array of documents. The caller is responsible for making sure that there
* is enough memory to store the results. Note that the array only contain partial
* results when this cursor had been previouly accessed. In that case,
* cursor.rewind() can be used to reset the cursor.
* @method
* @param {Cursor~toArrayResultCallback} [callback] The result callback.
* @throws {MongoError}
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.toArray = function(callback) {
var self = this;
if(self.s.options.tailable) throw MongoError.create({message: 'Tailable cursor cannot be converted to array', driver:true});
// Execute using callback
if(typeof callback == 'function') return toArray(self, callback);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
toArray(self, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
}
var toArray = function(self, callback) {
var items = [];
// console.log("!!!!!!!!!!!!! toArray :: 0")
// Reset cursor
self.rewind();
self.s.state = Cursor.INIT;
// console.log("!!!!!!!!!!!!! toArray :: 1")
// Fetch all the documents
var fetchDocs = function() {
// console.log("!!!!!!!!!!!!! toArray :: 2")
self._next(function(err, doc) {
// console.log("!!!!!!!!!!!!! toArray :: 3")
if(err) return handleCallback(callback, err);
if(doc == null) {
self.s.state = Cursor.CLOSED;
return handleCallback(callback, null, items);
}
// Add doc to items
items.push(doc)
// Get all buffered objects
if(self.bufferedCount() > 0) {
var docs = self.readBufferedDocuments(self.bufferedCount())
// Transform the doc if transform method added
if(self.s.transforms && typeof self.s.transforms.doc == 'function') {
docs = docs.map(self.s.transforms.doc);
}
push.apply(items, docs);
}
// Attempt a fetch
fetchDocs();
})
}
fetchDocs();
}
define.classMethod('toArray', {callback: true, promise:true});
/**
* The callback format for results
* @callback Cursor~countResultCallback
* @param {MongoError} error An error instance representing the error during the execution.
* @param {number} count The count of documents.
*/
/**
* Get the count of documents for this cursor
* @method
* @param {boolean} applySkipLimit Should the count command apply limit and skip settings on the cursor or in the passed in options.
* @param {object} [options=null] Optional settings.
* @param {number} [options.skip=null] The number of documents to skip.
* @param {number} [options.limit=null] The maximum amounts to count before aborting.
* @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
* @param {string} [options.hint=null] An index name hint for the query.
* @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
* @param {Cursor~countResultCallback} [callback] The result callback.
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.count = function(applySkipLimit, opts, callback) {
var self = this;
if(self.s.cmd.query == null) throw MongoError.create({message: "count can only be used with find command", driver:true});
if(typeof opts == 'function') callback = opts, opts = {};
opts = opts || {};
// Execute using callback
if(typeof callback == 'function') return count(self, applySkipLimit, opts, callback);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
count(self, applySkipLimit, opts, function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
};
var count = function(self, applySkipLimit, opts, callback) {
if(typeof applySkipLimit == 'function') {
callback = applySkipLimit;
applySkipLimit = true;
}
if(applySkipLimit) {
if(typeof self.cursorSkip() == 'number') opts.skip = self.cursorSkip();
if(typeof self.cursorLimit() == 'number') opts.limit = self.cursorLimit();
}
// Command
var delimiter = self.s.ns.indexOf('.');
var command = {
'count': self.s.ns.substr(delimiter+1), 'query': self.s.cmd.query
}
if(typeof opts.maxTimeMS == 'number') {
command.maxTimeMS = opts.maxTimeMS;
} else if(self.s.cmd && typeof self.s.cmd.maxTimeMS == 'number') {
command.maxTimeMS = self.s.cmd.maxTimeMS;
}
// Merge in any options
if(opts.skip) command.skip = opts.skip;
if(opts.limit) command.limit = opts.limit;
if(self.s.options.hint) command.hint = self.s.options.hint;
// Execute the command
self.topology.command(f("%s.$cmd", self.s.ns.substr(0, delimiter))
, command, function(err, result) {
callback(err, result ? result.result.n : null)
});
}
define.classMethod('count', {callback: true, promise:true});
/**
* Close the cursor, sending a KillCursor command and emitting close.
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.close = function(callback) {
this.s.state = Cursor.CLOSED;
// Kill the cursor
this.kill();
// Emit the close event for the cursor
this.emit('close');
// Callback if provided
if(typeof callback == 'function') return handleCallback(callback, null, this);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
resolve();
});
}
define.classMethod('close', {callback: true, promise:true});
/**
* Map all documents using the provided function
* @method
* @param {function} [transform] The mapping transformation method.
* @return {null}
*/
Cursor.prototype.map = function(transform) {
this.cursorState.transforms = { doc: transform };
return this;
}
define.classMethod('map', {callback: false, promise:false, returns: [Cursor]});
/**
* Is the cursor closed
* @method
* @return {boolean}
*/
Cursor.prototype.isClosed = function() {
return this.isDead();
}
define.classMethod('isClosed', {callback: false, promise:false, returns: [Boolean]});
Cursor.prototype.destroy = function(err) {
if(err) this.emit('error', err);
this.pause();
this.close();
}
define.classMethod('destroy', {callback: false, promise:false});
/**
* Return a modified Readable stream including a possible transform method.
* @method
* @param {object} [options=null] Optional settings.
* @param {function} [options.transform=null] A transformation method applied to each document emitted by the stream.
* @return {Cursor}
*/
Cursor.prototype.stream = function(options) {
this.s.streamOptions = options || {};
return this;
}
define.classMethod('stream', {callback: false, promise:false, returns: [Cursor]});
/**
* Execute the explain for the cursor
* @method
* @param {Cursor~resultCallback} [callback] The result callback.
* @return {Promise} returns Promise if no callback passed
*/
Cursor.prototype.explain = function(callback) {
var self = this;
this.s.cmd.explain = true;
// Do we have a readConcern
if(this.s.cmd.readConcern) {
delete this.s.cmd['readConcern'];
}
// Execute using callback
if(typeof callback == 'function') return this._next(callback);
// Return a Promise
return new this.s.promiseLibrary(function(resolve, reject) {
self._next(function(err, r) {
if(err) return reject(err);
resolve(r);
});
});
}
define.classMethod('explain', {callback: true, promise:true});
Cursor.prototype._read = function(n) {
// console.log("=== _read")
var self = this;
if(self.s.state == Cursor.CLOSED || self.isDead()) {
return self.push(null);
}
// Get the next item
self.nextObject(function(err, result) {
// console.log("=== _read 1")
// console.dir(err)
if(err) {
if(self.listeners('error') && self.listeners('error').length > 0) {
self.emit('error', err);
}
if(!self.isDead()) self.close();
// Emit end event
self.emit('end');
return self.emit('finish');
}
// If we provided a transformation method
if(typeof self.s.streamOptions.transform == 'function' && result != null) {
return self.push(self.s.streamOptions.transform(result));
}
// If we provided a map function
if(self.cursorState.transforms && typeof self.cursorState.transforms.doc == 'function' && result != null) {
return self.push(self.cursorState.transforms.doc(result));
}
// Return the result
self.push(result);
});
}
Object.defineProperty(Cursor.prototype, 'readPreference', {
enumerable:true,
get: function() {
if (!this || !this.s) {
return null;
}
return this.s.options.readPreference;
}
});
Object.defineProperty(Cursor.prototype, 'namespace', {
enumerable: true,
get: function() {
if (!this || !this.s) {
return null;
}
// TODO: refactor this logic into core
var ns = this.s.ns || '';
var firstDot = ns.indexOf('.');
if (firstDot < 0) {
return {
database: this.s.ns,
collection: ''
};
}
return {
database: ns.substr(0, firstDot),
collection: ns.substr(firstDot + 1)
};
}
});
/**
* The read() method pulls some data out of the internal buffer and returns it. If there is no data available, then it will return null.
* @function external:Readable#read
* @param {number} size Optional argument to specify how much data to read.
* @return {(String | Buffer | null)}
*/
/**
* Call this function to cause the stream to return strings of the specified encoding instead of Buffer objects.
* @function external:Readable#setEncoding
* @param {string} encoding The encoding to use.
* @return {null}
*/
/**
* This method will cause the readable stream to resume emitting data events.
* @function external:Readable#resume
* @return {null}
*/
/**
* This method will cause a stream in flowing-mode to stop emitting data events. Any data that becomes available will remain in the internal buffer.
* @function external:Readable#pause
* @return {null}
*/
/**
* This method pulls all the data out of a readable stream, and writes it to the supplied destination, automatically managing the flow so that the destination is not overwhelmed by a fast readable stream.
* @function external:Readable#pipe
* @param {Writable} destination The destination for writing data
* @param {object} [options] Pipe options
* @return {null}
*/
/**
* This method will remove the hooks set up for a previous pipe() call.
* @function external:Readable#unpipe
* @param {Writable} [destination] The destination for writing data
* @return {null}
*/
/**
* This is useful in certain cases where a stream is being consumed by a parser, which needs to "un-consume" some data that it has optimistically pulled out of the source, so that the stream can be passed on to some other party.
* @function external:Readable#unshift
* @param {(Buffer|string)} chunk Chunk of data to unshift onto the read queue.
* @return {null}
*/
/**
* Versions of Node prior to v0.10 had streams that did not implement the entire Streams API as it is today. (See "Compatibility" below for more information.)
* @function external:Readable#wrap
* @param {Stream} stream An "old style" readable stream.
* @return {null}
*/
Cursor.INIT = 0;
Cursor.OPEN = 1;
Cursor.CLOSED = 2;
Cursor.GET_MORE = 3;
module.exports = Cursor;<|fim▁end|> | |
<|file_name|>InfoBar.py<|end_file_name|><|fim▁begin|>from Tools.Profile import profile
from Tools.BoundFunction import boundFunction
# workaround for required config entry dependencies.
import Screens.MovieSelection
from Components.PluginComponent import plugins
from Plugins.Plugin import PluginDescriptor
from Screens.Screen import Screen
from Screens.MessageBox import MessageBox
from Components.Label import Label
from Components.Pixmap import MultiPixmap
from Tools.Directories import fileExists
profile("LOAD:enigma")
import enigma
import os
from boxbranding import getBoxType, getMachineBrand, getBrandOEM, getMachineBuild, getMachineName
boxtype = getBoxType()
profile("LOAD:InfoBarGenerics")
from Screens.InfoBarGenerics import InfoBarShowHide, \
InfoBarNumberZap, InfoBarChannelSelection, InfoBarMenu, InfoBarRdsDecoder, InfoBarRedButton, InfoBarTimerButton, InfoBarVmodeButton, \
InfoBarEPG, InfoBarSeek, InfoBarInstantRecord, InfoBarResolutionSelection, InfoBarAspectSelection, \
InfoBarAudioSelection, InfoBarAdditionalInfo, InfoBarNotifications, InfoBarDish, InfoBarUnhandledKey, InfoBarLongKeyDetection, \
InfoBarSubserviceSelection, InfoBarShowMovies, \
InfoBarServiceNotifications, InfoBarPVRState, InfoBarCueSheetSupport, InfoBarSimpleEventView, InfoBarBuffer, \
InfoBarSummarySupport, InfoBarMoviePlayerSummarySupport, InfoBarTimeshiftState, InfoBarTeletextPlugin, InfoBarExtensions, \
InfoBarSubtitleSupport, InfoBarPiP, InfoBarPlugins, InfoBarServiceErrorPopupSupport, InfoBarJobman, InfoBarZoom, InfoBarSleepTimer, InfoBarOpenOnTopHelper, \
InfoBarHdmi, setResumePoint, delResumePoint
from Screens.ButtonSetup import InfoBarButtonSetup
profile("LOAD:InitBar_Components")
from Components.ActionMap import HelpableActionMap
from Components.Timeshift import InfoBarTimeshift
from Components.config import config
from Components.ServiceEventTracker import ServiceEventTracker, InfoBarBase
profile("LOAD:HelpableScreen")
from Screens.HelpMenu import HelpableScreen
class InfoBar(InfoBarBase, InfoBarShowHide,
InfoBarNumberZap, InfoBarChannelSelection, InfoBarMenu, InfoBarEPG, InfoBarRdsDecoder,
InfoBarInstantRecord, InfoBarAudioSelection, InfoBarRedButton, InfoBarTimerButton, InfoBarResolutionSelection, InfoBarAspectSelection, InfoBarVmodeButton,
HelpableScreen, InfoBarAdditionalInfo, InfoBarNotifications, InfoBarDish, InfoBarUnhandledKey, InfoBarLongKeyDetection,
InfoBarSubserviceSelection, InfoBarTimeshift, InfoBarSeek, InfoBarCueSheetSupport, InfoBarBuffer,
InfoBarSummarySupport, InfoBarTimeshiftState, InfoBarTeletextPlugin, InfoBarExtensions,
InfoBarPiP, InfoBarPlugins, InfoBarSubtitleSupport, InfoBarServiceErrorPopupSupport, InfoBarJobman, InfoBarZoom, InfoBarSleepTimer, InfoBarOpenOnTopHelper,
InfoBarHdmi, Screen, InfoBarButtonSetup):
ALLOW_SUSPEND = True
instance = None
def __init__(self, session):
Screen.__init__(self, session)
if config.usage.show_infobar_lite.value and (config.skin.primary_skin.value == "OPD-Blue-Line/skin.xml" or config.skin.primary_skin.value.startswith('oDreamy-FHD/skin.xml/')):
self.skinName = "OPD-Blue-Line/skin.xml"
self["actions"] = HelpableActionMap(self, "InfobarActions",
{
"showMovies": (self.showMovies, _("Play recorded movies...")),
"showRadio": (self.showRadioButton, _("Show the radio player...")),
"showTv": (self.showTvButton, _("Show the tv player...")),
"toogleTvRadio": (self.toogleTvRadio, _("Toggels between tv and radio...")),
"openBouquetList": (self.openBouquetList, _("Open bouquetlist...")),
"showMediaPlayer": (self.showMediaPlayer, _("Show the media player...")),
"openBouquetList": (self.openBouquetList, _("open bouquetlist")),
"openWeather": (self.openWeather, _("Open Weather...")),
"openTimerList": (self.openTimerList, _("Open Timerlist...")),
"openAutoTimerList": (self.openAutoTimerList, _("Open AutoTimerlist...")),
"openEPGSearch": (self.openEPGSearch, _("Open EPGSearch...")),
"openIMDB": (self.openIMDB, _("Open IMDB...")),
"showMC": (self.showMediaCenter, _("Show the media center...")),
"openSleepTimer": (self.openPowerTimerList, _("Show the Sleep Timer...")),
'ZoomInOut': (self.ZoomInOut, _('Zoom In/Out TV...')),
'ZoomOff': (self.ZoomOff, _('Zoom Off...')),
'HarddiskSetup': (self.HarddiskSetup, _('Select HDD')),
"showWWW": (self.showPORTAL, _("Open MediaPortal...")),
"showSetup": (self.showSetup, _("Show setup...")),
"showFormat": (self.showFormat, _("Show Format Setup...")),
"showPluginBrowser": (self.showPluginBrowser, _("Show the plugins...")),
"showBoxPortal": (self.showBoxPortal, _("Show Box Portal...")),
}, prio=2)
self["key_red"] = Label()
self["key_yellow"] = Label()
self["key_blue"] = Label()
self["key_green"] = Label()
self.allowPiP = True
self.radioTV = 0
for x in HelpableScreen, \
InfoBarBase, InfoBarShowHide, \
InfoBarNumberZap, InfoBarChannelSelection, InfoBarMenu, InfoBarEPG, InfoBarRdsDecoder, \
InfoBarInstantRecord, InfoBarAudioSelection, InfoBarRedButton, InfoBarTimerButton, InfoBarUnhandledKey, InfoBarLongKeyDetection, InfoBarResolutionSelection, InfoBarVmodeButton, \
InfoBarAdditionalInfo, InfoBarNotifications, InfoBarDish, InfoBarSubserviceSelection, InfoBarAspectSelection, InfoBarBuffer, \
InfoBarTimeshift, InfoBarSeek, InfoBarCueSheetSupport, InfoBarSummarySupport, InfoBarTimeshiftState, \
InfoBarTeletextPlugin, InfoBarExtensions, InfoBarPiP, InfoBarSubtitleSupport, InfoBarJobman, InfoBarZoom, InfoBarSleepTimer, InfoBarOpenOnTopHelper, \
InfoBarHdmi, InfoBarPlugins, InfoBarServiceErrorPopupSupport, InfoBarButtonSetup:
x.__init__(self)
self.helpList.append((self["actions"], "InfobarActions", [("showMovies", _("Watch recordings..."))]))
self.helpList.append((self["actions"], "InfobarActions", [("showRadio", _("Listen to the radio..."))]))
self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
{
enigma.iPlayableService.evUpdatedEventInfo: self.__eventInfoChanged
})
self.current_begin_time=0
assert InfoBar.instance is None, "class InfoBar is a singleton class and just one instance of this class is allowed!"
InfoBar.instance = self
if config.misc.initialchannelselection.value:
self.onShown.append(self.showMenu)
self.zoomrate = 0
self.zoomin = 1
self.onShow.append(self.doButtonsCheck)
def showMenu(self):
self.onShown.remove(self.showMenu)
config.misc.initialchannelselection.value = False
config.misc.initialchannelselection.save()
self.mainMenu()
def doButtonsCheck(self):
if config.plisettings.ColouredButtons.value:
self["key_yellow"].setText(_("Extensions"))
if config.usage.defaultEPGType.value == "Graphical EPG..." or config.usage.defaultEPGType.value == "None":
self["key_red"].setText(_("Single EPG"))
else:
self["key_red"].setText(_("ViX EPG"))
if not config.plisettings.Subservice.value:
self["key_green"].setText(_("Timers"))
else:
self["key_green"].setText(_("Green Panel"))
self["key_blue"].setText(_("Blue Panel"))
def __onClose(self):
InfoBar.instance = None
def __eventInfoChanged(self):
if self.execing:
service = self.session.nav.getCurrentService()
old_begin_time = self.current_begin_time
info = service and service.info()
ptr = info and info.getEvent(0)
self.current_begin_time = ptr and ptr.getBeginTime() or 0
if config.usage.show_infobar_on_event_change.value:
if old_begin_time and old_begin_time != self.current_begin_time:
self.doShow()
def __checkServiceStarted(self):
self.__serviceStarted(True)
self.onExecBegin.remove(self.__checkServiceStarted)
def serviceStarted(self): #override from InfoBarShowHide
new = self.servicelist.newServicePlayed()
if self.execing:
InfoBarShowHide.serviceStarted(self)
self.current_begin_time=0
elif not self.__checkServiceStarted in self.onShown and new:
self.onShown.append(self.__checkServiceStarted)
def __checkServiceStarted(self):
self.serviceStarted()
self.onShown.remove(self.__checkServiceStarted)
def openBouquetList(self):
if config.usage.tvradiobutton_mode.value == "MovieList":
self.showTvChannelList(True)
self.showMovies()
elif config.usage.tvradiobutton_mode.value == "ChannelList":
self.showTvChannelList(True)
elif config.usage.tvradiobutton_mode.value == "BouquetList":
self.showTvChannelList(True)
self.servicelist.showFavourites()
def showTvButton(self):
if boxtype.startswith('gb') or boxtype in ('classm', 'genius', 'evo', 'galaxym6'):
self.toogleTvRadio()
elif boxtype in ('uniboxhd1', 'uniboxhd2', 'uniboxhd3', 'sezam5000hd', 'mbtwin'):
self.showMovies()
else:
self.showTv()
def showTv(self):
if config.usage.tvradiobutton_mode.value == "MovieList":
self.showTvChannelList(True)
self.showMovies()
elif config.usage.tvradiobutton_mode.value == "BouquetList":
self.showTvChannelList(True)
if config.usage.show_servicelist.value:
self.servicelist.showFavourites()
else:
self.showTvChannelList(True)
def showRadioButton(self):
if boxtype.startswith('gb') or boxtype.startswith('azbox') or boxtype in ('classm', 'genius', 'evo', 'galaxym6', 'uniboxhd1', 'uniboxhd2', 'uniboxhd3', 'sezam5000hd', 'mbtwin', 'beyonwizt3'):
self.toogleTvRadio()
else:
self.showRadio()
def showRadio(self):
if config.usage.e1like_radio_mode.value:
if config.usage.tvradiobutton_mode.value == "BouquetList":
self.showRadioChannelList(True)
if config.usage.show_servicelist.value:
self.servicelist.showFavourites()
else:
self.showRadioChannelList(True)
else:
self.rds_display.hide() # in InfoBarRdsDecoder
from Screens.ChannelSelection import ChannelSelectionRadio
self.session.openWithCallback(self.ChannelSelectionRadioClosed, ChannelSelectionRadio, self)
def toogleTvRadio(self):
if self.radioTV == 1:
self.radioTV = 0
self.showTv()
else:
self.radioTV = 1
self.showRadio()
def ChannelSelectionRadioClosed(self, *arg):
self.rds_display.show() # in InfoBarRdsDecoder
self.radioTV = 0
self.doShow()
def showMovies(self, defaultRef=None):
if getMachineBrand() == 'GI' or boxtype.startswith('azbox') or boxtype.startswith('ini') or boxtype.startswith('venton'):
from Screens.BoxPortal import BoxPortal
self.session.open(BoxPortal)
else:
self.showMoviePlayer(defaultRef)
def showMoviePlayer(self, defaultRef=None): #for using with hotkeys (ButtonSetup.py) regardless of plugins which overwrite the showMovies function
self.lastservice = self.session.nav.getCurrentlyPlayingServiceOrGroup()
if self.lastservice and ':0:/' in self.lastservice.toString():
self.lastservice = enigma.eServiceReference(config.movielist.curentlyplayingservice.value)
self.session.openWithCallback(self.movieSelected, Screens.MovieSelection.MovieSelection, defaultRef, timeshiftEnabled = self.timeshiftEnabled())
def movieSelected(self, service):
ref = self.lastservice
del self.lastservice
if service is None:
if ref and not self.session.nav.getCurrentlyPlayingServiceOrGroup():
self.session.nav.playService(ref)
else:
self.session.open(MoviePlayer, service, slist = self.servicelist, lastservice = ref)
def showMediaPlayer(self):
try:
from Plugins.Extensions.MediaPlayer.plugin import MediaPlayer
self.session.open(MediaPlayer)
no_plugin = False
except Exception, e:
self.session.open(MessageBox, _("The MediaPlayer plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
def showMediaCenter(self):
try:
from Plugins.Extensions.BMediaCenter.plugin import DMC_MainMenu
self.session.open(DMC_MainMenu)
no_plugin = False
except Exception, e:
self.session.open(MessageBox, _("The MediaCenter plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
def openSleepTimer(self):
from Screens.SleepTimerEdit import SleepTimerEdit
self.session.open(SleepTimerEdit)
def openTimerList(self):
from Screens.TimerEdit import TimerEditList
self.session.open(TimerEditList)
def openPowerTimerList(self):
from Screens.PowerTimerEdit import PowerTimerEditList
self.session.open(PowerTimerEditList)
def openAutoTimerList(self):
try:
for plugin in plugins.getPlugins([PluginDescriptor.WHERE_PLUGINMENU ,PluginDescriptor.WHERE_EXTENSIONSMENU, PluginDescriptor.WHERE_EVENTINFO]):
if plugin.name == _("AutoTimer"):
self.runPlugin(plugin)
break
except Exception, e:
self.session.open(MessageBox, _("The AutoTimer plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
def openWeather(self):
try:
for plugin in plugins.getPlugins([PluginDescriptor.WHERE_PLUGINMENU ,PluginDescriptor.WHERE_EXTENSIONSMENU, PluginDescriptor.WHERE_EVENTINFO]):
if plugin.name == _("Weather Details"):
self.runPlugin(plugin)
break
except Exception, e:
self.session.open(MessageBox, _("The Weather plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
def openEPGSearch(self):
try:
for plugin in plugins.getPlugins([PluginDescriptor.WHERE_PLUGINMENU ,PluginDescriptor.WHERE_EXTENSIONSMENU, PluginDescriptor.WHERE_EVENTINFO]):
if plugin.name == _("EPGSearch") or plugin.name == _("search EPG...") or plugin.name == "Durchsuche EPG...":
self.runPlugin(plugin)
break
except Exception, e:
self.session.open(MessageBox, _("The EPGSearch plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
def openIMDB(self):
try:
for plugin in plugins.getPlugins([PluginDescriptor.WHERE_PLUGINMENU ,PluginDescriptor.WHERE_EXTENSIONSMENU, PluginDescriptor.WHERE_EVENTINFO]):
if plugin.name == _("IMDb Details"):
self.runPlugin(plugin)
break
except Exception, e:
self.session.open(MessageBox, _("The IMDb plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
def ZoomInOut(self):
zoomval = 0
if self.zoomrate > 3:
self.zoomin = 0
elif self.zoomrate < -9:
self.zoomin = 1
if self.zoomin == 1:
self.zoomrate += 1
else:
self.zoomrate -= 1
if self.zoomrate < 0:
zoomval = abs(self.zoomrate) + 10
else:
zoomval = self.zoomrate
print 'zoomRate:', self.zoomrate
print 'zoomval:', zoomval
if fileExists("/proc/stb/vmpeg/0/zoomrate"):
file = open('/proc/stb/vmpeg/0/zoomrate', 'w')
file.write('%d' % int(zoomval))
file.close()
def ZoomOff(self):
self.zoomrate = 0
self.zoomin = 1
if fileExists("/proc/stb/vmpeg/0/zoomrate"):
file = open('/proc/stb/vmpeg/0/zoomrate', 'w')
file.write(str(0))
file.close()
def HarddiskSetup(self):
from Screens.HarddiskSetup import HarddiskSelection
self.session.open(HarddiskSelection)
def showPORTAL(self):
try:
from Plugins.Extensions.MediaPortal.plugin import MPmain as MediaPortal
MediaPortal(self.session)
no_plugin = False
except Exception, e:
self.session.open(MessageBox, _("The MediaPortal plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
def showSetup(self):
from Screens.Menu import MainMenu, mdom
root = mdom.getroot()
for x in root.findall("menu"):
y = x.find("id")
if y is not None:
id = y.get("val")
if id and id == "setup":
self.session.infobar = self
self.session.open(MainMenu, x)
return
def showFormat(self):
try:
from Plugins.SystemPlugins.Videomode.plugin import videoSetupMain
self.session.instantiateDialog(videoSetupMain)
no_plugin = False
except Exception, e:
self.session.open(MessageBox, _("The VideoMode plugin is not installed!\nPlease install it."), type = MessageBox.TYPE_INFO,timeout = 10 )
def showPluginBrowser(self):
from OPENDROID.GreenPanel import GreenPanel
self.session.open(GreenPanel)
def showBoxPortal(self):
if getMachineBrand() == 'GI' or boxtype.startswith('azbox') or boxtype.startswith('ini') or boxtype.startswith('venton'):
from Screens.BoxPortal import BoxPortal
self.session.open(BoxPortal)
else:
self.showMovies()
def setAudioTrack(service):
try:
from Tools.ISO639 import LanguageCodes as langC
tracks = service and service.audioTracks()
nTracks = tracks and tracks.getNumberOfTracks() or 0
if not nTracks: return
idx = 0
trackList = []
for i in xrange(nTracks):
audioInfo = tracks.getTrackInfo(i)
lang = audioInfo.getLanguage()
if langC.has_key(lang):
lang = langC[lang][0]
desc = audioInfo.getDescription()
track = idx, lang, desc
idx += 1
trackList += [track]
seltrack = tracks.getCurrentTrack()
# we need default selected language from image
# to set the audiotrack if "config.autolanguage.audio_autoselect...values" are not set
from Components.Language import language
syslang = language.getLanguage()[:2]
syslang = langC[syslang][0]
if (config.autolanguage.audio_autoselect1.value or config.autolanguage.audio_autoselect2.value or config.autolanguage.audio_autoselect3.value or config.autolanguage.audio_autoselect4.value) != "---":
audiolang = [config.autolanguage.audio_autoselect1.value, config.autolanguage.audio_autoselect2.value, config.autolanguage.audio_autoselect3.value, config.autolanguage.audio_autoselect4.value]
caudiolang = True
else:
audiolang = syslang
caudiolang = False
useAc3 = config.autolanguage.audio_defaultac3.value
if useAc3:
matchedAc3 = tryAudioTrack(tracks, audiolang, caudiolang, trackList, seltrack, useAc3)
if matchedAc3: return
matchedMpeg = tryAudioTrack(tracks, audiolang, caudiolang, trackList, seltrack, False)
if matchedMpeg: return
tracks.selectTrack(0) # fallback to track 1(0)
return
else:
matchedMpeg = tryAudioTrack(tracks, audiolang, caudiolang, trackList, seltrack, False)
if matchedMpeg: return
matchedAc3 = tryAudioTrack(tracks, audiolang, caudiolang, trackList, seltrack, useAc3)
if matchedAc3: return
tracks.selectTrack(0) # fallback to track 1(0)
except Exception, e:
print("[MoviePlayer] audioTrack exception:\n" + str(e))
def tryAudioTrack(tracks, audiolang, caudiolang, trackList, seltrack, useAc3):
for entry in audiolang:
if caudiolang:
# we need here more replacing for other language, or new configs with another list !!!
# choice gives only the value, never the description
# so we can also make some changes in "config.py" to get the description too, then we dont need replacing here !
entry = entry.replace('eng qaa Englisch', 'English').replace('deu ger', 'German')
for x in trackList:
if entry == x[1] and seltrack == x[0]:
if useAc3:
if x[2].startswith('AC'):
print("[MoviePlayer] audio track is current selected track: " + str(x))<|fim▁hole|> return True
elif entry == x[1] and seltrack != x[0]:
if useAc3:
if x[2].startswith('AC'):
print("[MoviePlayer] audio track match: " + str(x))
tracks.selectTrack(x[0])
return True
else:
print("[MoviePlayer] audio track match: " + str(x))
tracks.selectTrack(x[0])
return True
return False
class MoviePlayer(InfoBarAspectSelection, InfoBarSimpleEventView, InfoBarBase, InfoBarShowHide, InfoBarLongKeyDetection, InfoBarMenu, InfoBarEPG, \
InfoBarSeek, InfoBarShowMovies, InfoBarInstantRecord, InfoBarAudioSelection, HelpableScreen, InfoBarNotifications,
InfoBarServiceNotifications, InfoBarPVRState, InfoBarCueSheetSupport,
InfoBarMoviePlayerSummarySupport, InfoBarSubtitleSupport, Screen, InfoBarTeletextPlugin,
InfoBarServiceErrorPopupSupport, InfoBarExtensions, InfoBarPlugins, InfoBarPiP, InfoBarZoom, InfoBarHdmi, InfoBarButtonSetup):
ENABLE_RESUME_SUPPORT = True
ALLOW_SUSPEND = True
instance = None
def __init__(self, session, service, slist = None, lastservice = None):
Screen.__init__(self, session)
InfoBarAspectSelection.__init__(self)
InfoBarAudioSelection.__init__(self)
InfoBarSimpleEventView.__init__(self)
self.pts_pvrStateDialog = ""
self["key_yellow"] = Label()
self["key_blue"] = Label()
self["key_green"] = Label()
self["eventname"] = Label()
self["state"] = Label()
self["speed"] = Label()
self["statusicon"] = MultiPixmap()
self["actions"] = HelpableActionMap(self, "MoviePlayerActions",
{
"leavePlayer": (self.leavePlayer, _("leave movie player...")),
"leavePlayerOnExit": (self.leavePlayerOnExit, _("leave movie player..."))
})
self.allowPiP = True
for x in HelpableScreen, InfoBarShowHide, InfoBarLongKeyDetection, InfoBarMenu, InfoBarEPG, \
InfoBarBase, InfoBarSeek, InfoBarShowMovies, InfoBarInstantRecord, \
InfoBarAudioSelection, InfoBarNotifications, InfoBarSimpleEventView, \
InfoBarServiceNotifications, InfoBarPVRState, InfoBarCueSheetSupport, \
InfoBarMoviePlayerSummarySupport, InfoBarSubtitleSupport, \
InfoBarTeletextPlugin, InfoBarServiceErrorPopupSupport, InfoBarExtensions, \
InfoBarPlugins, InfoBarPiP, InfoBarZoom, InfoBarButtonSetup:
x.__init__(self)
self.onChangedEntry = [ ]
self.servicelist = slist
self.lastservice = lastservice or session.nav.getCurrentlyPlayingServiceOrGroup()
session.nav.playService(service)
self.cur_service = service
self.returning = False
self.onClose.append(self.__onClose)
self.onShow.append(self.doButtonsCheck)
self.__event_tracker = ServiceEventTracker(screen=self, eventmap=
{
enigma.iPlayableService.evStart: self.__evStart
})
assert MoviePlayer.instance is None, "class InfoBar is a singleton class and just one instance of this class is allowed!"
MoviePlayer.instance = self
# is needed for every first call of MoviePlayer
self.__evStart()
def __evStart(self):
self.switchAudioTimer = enigma.eTimer()
self.switchAudioTimer.callback.append(self.switchAudio)
self.switchAudioTimer.start(750, True) # 750 is a safe-value
def switchAudio(self):
service = self.session.nav.getCurrentlyPlayingServiceOrGroup()
if service:
# we go this way for other extensions as own records(they switch over pmt)
path = service.getPath()
import os
ext = os.path.splitext(path)[1].lower()
exts = [".mkv", ".avi", ".divx", ".mp4"] # we need more extensions here ?
if ext.lower() in exts:
service = self.session.nav.getCurrentService()
if service:
setAudioTrack(service)
def doButtonsCheck(self):
if config.plisettings.ColouredButtons.value:
self["key_yellow"].setText(_("Extensions"))
self["key_green"].setText(_("Green Panel"))
self["key_blue"].setText(_("Blue Panel"))
def __onClose(self):
MoviePlayer.instance = None
from Screens.MovieSelection import playlist
del playlist[:]
Screens.InfoBar.InfoBar.instance.callServiceStarted()
self.session.nav.playService(self.lastservice)
config.usage.last_movie_played.value = self.cur_service.toString()
config.usage.last_movie_played.save()
def handleLeave(self, how):
self.is_closing = True
if how == "ask":
if config.usage.setup_level.index < 2: # -expert
list = (
(_("Yes"), "quit"),
(_("No"), "continue")
)
else:
list = (
(_("Yes"), "quit"),
(_("Yes, returning to movie list"), "movielist"),
(_("Yes, and delete this movie"), "quitanddelete"),
(_("Yes, delete this movie and return to movie list"), "deleteandmovielist"),
(_("No"), "continue"),
(_("No, but restart from begin"), "restart")
)
from Screens.ChoiceBox import ChoiceBox
self.session.openWithCallback(self.leavePlayerConfirmed, ChoiceBox, title=_("Stop playing this movie?"), list = list)
else:
self.leavePlayerConfirmed([True, how])
def leavePlayer(self):
setResumePoint(self.session)
self.handleLeave(config.usage.on_movie_stop.value)
def leavePlayerOnExit(self):
if self.shown:
self.hide()
elif self.session.pipshown and "popup" in config.usage.pip_hideOnExit.value:
if config.usage.pip_hideOnExit.value == "popup":
self.session.openWithCallback(self.hidePipOnExitCallback, MessageBox, _("Disable Picture in Picture"), simple=True)
else:
self.hidePipOnExitCallback(True)
elif config.usage.leave_movieplayer_onExit.value == "popup":
self.session.openWithCallback(self.leavePlayerOnExitCallback, MessageBox, _("Exit movie player?"), simple=True)
elif config.usage.leave_movieplayer_onExit.value == "without popup":
self.leavePlayerOnExitCallback(True)
elif config.usage.leave_movieplayer_onExit.value == "stop":
self.leavePlayer()
def leavePlayerOnExitCallback(self, answer):
if answer:
setResumePoint(self.session)
self.handleLeave("quit")
def hidePipOnExitCallback(self, answer):
if answer:
self.showPiP()
def deleteConfirmed(self, answer):
if answer:
self.leavePlayerConfirmed((True, "quitanddeleteconfirmed"))
def deleteAndMovielistConfirmed(self, answer):
if answer:
self.leavePlayerConfirmed((True, "deleteandmovielistconfirmed"))
def movielistAgain(self):
from Screens.MovieSelection import playlist
del playlist[:]
self.session.nav.playService(self.lastservice)
self.leavePlayerConfirmed((True, "movielist"))
def leavePlayerConfirmed(self, answer):
answer = answer and answer[1]
if answer is None:
return
if answer in ("quitanddelete", "quitanddeleteconfirmed", "deleteandmovielist", "deleteandmovielistconfirmed"):
ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
serviceHandler = enigma.eServiceCenter.getInstance()
if answer in ("quitanddelete", "deleteandmovielist"):
msg = ''
if config.usage.movielist_trashcan.value:
import Tools.Trashcan
try:
trash = Tools.Trashcan.createTrashFolder(ref.getPath())
Screens.MovieSelection.moveServiceFiles(ref, trash)
# Moved to trash, okay
if answer == "quitanddelete":
self.close()
else:
self.movielistAgain()
return
except Exception, e:
print "[InfoBar] Failed to move to .Trash folder:", e
msg = _("Cannot move to trash can") + "\n" + str(e) + "\n"
info = serviceHandler.info(ref)
name = info and info.getName(ref) or _("this recording")
msg += _("Do you really want to delete %s?") % name
if answer == "quitanddelete":
self.session.openWithCallback(self.deleteConfirmed, MessageBox, msg)
elif answer == "deleteandmovielist":
self.session.openWithCallback(self.deleteAndMovielistConfirmed, MessageBox, msg)
return
elif answer in ("quitanddeleteconfirmed", "deleteandmovielistconfirmed"):
offline = serviceHandler.offlineOperations(ref)
if offline.deleteFromDisk(0):
self.session.openWithCallback(self.close, MessageBox, _("You cannot delete this!"), MessageBox.TYPE_ERROR)
if answer == "deleteandmovielistconfirmed":
self.movielistAgain()
return
if answer in ("quit", "quitanddeleteconfirmed"):
self.close()
elif answer in ("movielist", "deleteandmovielistconfirmed"):
if config.movielist.stop_service.value:
ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
else:
ref = self.lastservice
self.returning = True
self.session.openWithCallback(self.movieSelected, Screens.MovieSelection.MovieSelection, ref)
self.session.nav.stopService()
if not config.movielist.stop_service.value:
self.session.nav.playService(self.lastservice)
elif answer == "restart":
self.doSeek(0)
self.setSeekState(self.SEEK_STATE_PLAY)
elif answer in ("playlist","playlistquit","loop"):
( next_service, item , length ) = self.getPlaylistServiceInfo(self.cur_service)
if next_service is not None:
if config.usage.next_movie_msg.value:
self.displayPlayedName(next_service, item, length)
self.session.nav.playService(next_service)
self.cur_service = next_service
else:
if answer == "playlist":
self.leavePlayerConfirmed([True,"movielist"])
elif answer == "loop" and length > 0:
self.leavePlayerConfirmed([True,"loop"])
else:
self.leavePlayerConfirmed([True,"quit"])
elif answer in "repeatcurrent":
if config.usage.next_movie_msg.value:
(item, length) = self.getPlaylistServiceInfo(self.cur_service)
self.displayPlayedName(self.cur_service, item, length)
self.session.nav.stopService()
self.session.nav.playService(self.cur_service)
def doEofInternal(self, playing):
if not self.execing:
return
if not playing :
return
ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
if ref:
delResumePoint(ref)
self.handleLeave(config.usage.on_movie_eof.value)
def up(self):
slist = self.servicelist
if slist and slist.dopipzap:
if "keep" not in config.usage.servicelist_cursor_behavior.value:
slist.moveUp()
self.session.execDialog(slist)
else:
self.showMovies()
def down(self):
slist = self.servicelist
if slist and slist.dopipzap:
if "keep" not in config.usage.servicelist_cursor_behavior.value:
slist.moveDown()
self.session.execDialog(slist)
else:
self.showMovies()
def right(self):
# XXX: gross hack, we do not really seek if changing channel in pip :-)
slist = self.servicelist
if slist and slist.dopipzap:
# XXX: We replicate InfoBarChannelSelection.zapDown here - we shouldn't do that
if slist.inBouquet():
prev = slist.getCurrentSelection()
if prev:
prev = prev.toString()
while True:
if config.usage.quickzap_bouquet_change.value and slist.atEnd():
slist.nextBouquet()
else:
slist.moveDown()
cur = slist.getCurrentSelection()
if not cur or (not (cur.flags & 64)) or cur.toString() == prev:
break
else:
slist.moveDown()
slist.zap(enable_pipzap = True)
else:
InfoBarSeek.seekFwd(self)
def left(self):
slist = self.servicelist
if slist and slist.dopipzap:
# XXX: We replicate InfoBarChannelSelection.zapUp here - we shouldn't do that
if slist.inBouquet():
prev = slist.getCurrentSelection()
if prev:
prev = prev.toString()
while True:
if config.usage.quickzap_bouquet_change.value:
if slist.atBegin():
slist.prevBouquet()
slist.moveUp()
cur = slist.getCurrentSelection()
if not cur or (not (cur.flags & 64)) or cur.toString() == prev:
break
else:
slist.moveUp()
slist.zap(enable_pipzap = True)
else:
InfoBarSeek.seekBack(self)
def showPiP(self):
slist = self.servicelist
if self.session.pipshown:
if slist and slist.dopipzap:
slist.togglePipzap()
if self.session.pipshown:
del self.session.pip
self.session.pipshown = False
else:
service = self.session.nav.getCurrentService()
info = service and service.info()
xres = str(info.getInfo(enigma.iServiceInformation.sVideoWidth))
if int(xres) <= 720 or not getMachineBuild() == 'blackbox7405':
from Screens.PictureInPicture import PictureInPicture
self.session.pip = self.session.instantiateDialog(PictureInPicture)
self.session.pip.show()
if self.session.pip.playService(slist.getCurrentSelection()):
self.session.pipshown = True
self.session.pip.servicePath = slist.getCurrentServicePath()
else:
self.session.pipshown = False
del self.session.pip
else:
self.session.open(MessageBox, _("Your %s %s does not support PiP HD") % (getMachineBrand(), getMachineName()), type = MessageBox.TYPE_INFO,timeout = 5 )
def movePiP(self):
if self.session.pipshown:
InfoBarPiP.movePiP(self)
def swapPiP(self):
pass
def showMovies(self):
ref = self.session.nav.getCurrentlyPlayingServiceOrGroup()
if ref and ':0:/' not in ref.toString():
self.playingservice = ref # movie list may change the currently playing
else:
self.playingservice = enigma.eServiceReference(config.movielist.curentlyplayingservice.value)
self.session.openWithCallback(self.movieSelected, Screens.MovieSelection.MovieSelection, ref)
def movieSelected(self, service):
if service is not None:
self.cur_service = service
self.is_closing = False
self.session.nav.playService(service)
self.returning = False
elif self.returning:
self.close()
else:
self.is_closing = False
try:
ref = self.playingservice
del self.playingservice
# no selection? Continue where we left off
if ref and not self.session.nav.getCurrentlyPlayingServiceOrGroup():
self.session.nav.playService(ref)
except:
pass
def getPlaylistServiceInfo(self, service):
from MovieSelection import playlist
for i, item in enumerate(playlist):
if item == service:
if config.usage.on_movie_eof.value == "repeatcurrent":
return i+1, len(playlist)
i += 1
if i < len(playlist):
return playlist[i], i+1, len(playlist)
elif config.usage.on_movie_eof.value == "loop":
return playlist[0], 1, len(playlist)
return None, 0, 0
def displayPlayedName(self, ref, index, n):
from Tools import Notifications
Notifications.AddPopup(text = _("%s/%s: %s") % (index, n, self.ref2HumanName(ref)), type = MessageBox.TYPE_INFO, timeout = 5)
def ref2HumanName(self, ref):
return enigma.eServiceCenter.getInstance().info(ref).getName(ref)<|fim▁end|> | return True
else:
print("[MoviePlayer] audio track is current selected track: " + str(x)) |
<|file_name|>OpenXML4JRuntimeException.java<|end_file_name|><|fim▁begin|>/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
package org.apache.poi.openxml4j.exceptions;
/**
* Global exception throws when a critical error occurs (this exception is
* set as Runtime in order not to force the user to manage the exception in a
* try/catch).
*
* @author Julien Chable
* @version 1.0
*/
@SuppressWarnings("serial")
public class OpenXML4JRuntimeException extends RuntimeException {
public OpenXML4JRuntimeException(String msg) {
super(msg);
}<|fim▁hole|><|fim▁end|> | } |
<|file_name|>RedisProtocol.java<|end_file_name|><|fim▁begin|>package com.ctrip.xpipe.redis.core.protocal;
/**
* @author wenchao.meng
*<|fim▁hole|> int REDIS_PORT_DEFAULT = 6379;
int KEEPER_PORT_DEFAULT = 6380;
int RUN_ID_LENGTH = 40;
String CRLF = "\r\n";
String OK = "OK";
String KEEPER_ROLE_PREFIX = "keeperrole";
static String booleanToString(boolean yes){
if(yes){
return "yes";
}
return "no";
}
}<|fim▁end|> | * 2016年3月24日 下午6:27:48
*/
public interface RedisProtocol {
|
<|file_name|>codelab_template.go<|end_file_name|><|fim▁begin|>package main
import (
"html/template"
"io/ioutil"
"os"
"path"
"sort"
"strconv"
"strings"
"time"
"github.com/peterebden/go-cli-init/v5/flags"
)
// TODO(jpoole): maybe we should just have an order field in the MD?
var categoryOrder = map[string]int{
"beginner": 0,
"intermediate": 1,
"advanced": 2,
}
type codelabList []codelabMD
func (c codelabList) Len() int {
return len(c)
}
// Sort by difficulty (based on the category) and then lexicographically on the title
func (c codelabList) Less(i, j int) bool {
lhs := c[i]
rhs := c[j]
lhsOrder, ok := categoryOrder[lhs.Category]
if !ok {
panic("Unknown categories order: %" + lhs.Category)
}
rhsOrder, ok := categoryOrder[rhs.Category]
if !ok {
panic("Unknown categories order: %" + rhs.Category)
}
if lhsOrder == rhsOrder {
return strings.Compare(lhs.Title, rhs.Title) < 0
}
return lhsOrder < rhsOrder
}
func (c codelabList) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}
type codelabMD struct {
ID string
Title string
Description string
Author string
Duration int
LastUpdated string
Category string
Status string
}
var opts = struct {
Template string `long:"template" required:"true"`
Args struct {
Codelabs []string `positional-arg-name:"codelabs" description:"A list of codelabs to generate"`
} `positional-args:"true"`
}{}
func main() {
flags.ParseFlagsOrDie("Codelab template", &opts, nil)
tmplName := path.Base(opts.Template)
tmp := template.Must(template.New(tmplName).ParseFiles(opts.Template))
if err := tmp.ExecuteTemplate(os.Stdout, tmplName, getMetadata()); err != nil {
panic(err)
}
}
func getMetadata() codelabList {
var mds codelabList
for _, codelab := range opts.Args.Codelabs {
md := codelabMD{}
info, err := os.Stat(codelab)
if err != nil {
panic(err)
}
md.LastUpdated = info.ModTime().UTC().Format(time.RFC822)
b, err := ioutil.ReadFile(codelab)
if err != nil {
panic(err)
}
lines := strings.Split(string(b), "\n")
for _, line := range lines {
if line == "" {
break
}
<|fim▁hole|>
switch key {
case "summary":
md.Title = value
case "description":
md.Description = value
case "authors":
md.Author = value
case "id":
md.ID = value
case "categories":
md.Category = value
case "status":
md.Status = value
}
}
for _, line := range lines {
if strings.HasPrefix(line, "Duration: ") {
d, err := strconv.Atoi(strings.TrimSpace(strings.TrimPrefix(line, "Duration: ")))
if err != nil {
panic(err)
}
md.Duration += d
}
}
if md.Status == "Published" {
mds = append(mds, md)
}
}
sort.Sort(mds)
return mds
}<|fim▁end|> | s := strings.Split(line, ": ")
key, value := strings.TrimSpace(s[0]), strings.TrimSpace(s[1]) |
<|file_name|>abi.rs<|end_file_name|><|fim▁begin|>// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
pub static box_field_refcnt: uint = 0u;
pub static box_field_drop_glue: uint = 1u;
pub static box_field_body: uint = 4u;
pub static tydesc_field_visit_glue: uint = 3u;
// The two halves of a closure: code and environment.
pub static fn_field_code: uint = 0u;
pub static fn_field_box: uint = 1u;
// The two fields of a trait object/trait instance: vtable and box.
// The vtable contains the type descriptor as first element.
pub static trt_field_box: uint = 0u;
pub static trt_field_vtable: uint = 1u;<|fim▁hole|><|fim▁end|> |
pub static slice_elt_base: uint = 0u;
pub static slice_elt_len: uint = 1u; |
<|file_name|>pyoptic.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import csv, gzip, os
from pyqtgraph import Point
class GlassDB:
"""
Database of dispersion coefficients for Schott glasses
+ Corning 7980
"""
def __init__(self, fileName='schott_glasses.csv'):
path = os.path.dirname(__file__)
fh = gzip.open(os.path.join(path, 'schott_glasses.csv.gz'), 'rb')
r = csv.reader(map(str, fh.readlines()))
lines = [x for x in r]
self.data = {}
header = lines[0]
for l in lines[1:]:
info = {}
for i in range(1, len(l)):
info[header[i]] = l[i]
self.data[l[0]] = info
self.data['Corning7980'] = { ## Thorlabs UV fused silica--not in schott catalog.
'B1': 0.68374049400,
'B2': 0.42032361300,
'B3': 0.58502748000,
'C1': 0.00460352869,
'C2': 0.01339688560,
'C3': 64.49327320000,
'TAUI25/250': 0.95, ## transmission data is fabricated, but close.
'TAUI25/1400': 0.98,
}
for k in self.data:
self.data[k]['ior_cache'] = {}
def ior(self, glass, wl):
"""
Return the index of refraction for *glass* at wavelength *wl*.
The *glass* argument must be a key in self.data.
"""
info = self.data[glass]
cache = info['ior_cache']
if wl not in cache:
B = list(map(float, [info['B1'], info['B2'], info['B3']]))
C = list(map(float, [info['C1'], info['C2'], info['C3']]))
w2 = (wl/1000.)**2
n = np.sqrt(1.0 + (B[0]*w2 / (w2-C[0])) + (B[1]*w2 / (w2-C[1])) + (B[2]*w2 / (w2-C[2])))
cache[wl] = n
return cache[wl]
def transmissionCurve(self, glass):
data = self.data[glass]
keys = [int(x[7:]) for x in data.keys() if 'TAUI25' in x]
keys.sort()
curve = np.empty((2,len(keys)))
for i in range(len(keys)):
curve[0][i] = keys[i]
key = 'TAUI25/%d' % keys[i]
val = data[key]
if val == '':
val = 0
else:
val = float(val)
curve[1][i] = val
return curve
GLASSDB = GlassDB()
def wlPen(wl):
"""Return a pen representing the given wavelength"""
l1 = 400
l2 = 700
hue = np.clip(((l2-l1) - (wl-l1)) * 0.8 / (l2-l1), 0, 0.8)
val = 1.0
if wl > 700:
val = 1.0 * (((700-wl)/700.) + 1)
elif wl < 400:
val = wl * 1.0/400.
#print hue, val
color = pg.hsvColor(hue, 1.0, val)
pen = pg.mkPen(color)
return pen
class ParamObj(object):
# Just a helper for tracking parameters and responding to changes
def __init__(self):
self.__params = {}
def __setitem__(self, item, val):
self.setParam(item, val)
def setParam(self, param, val):
self.setParams(**{param:val})
def setParams(self, **params):
"""Set parameters for this optic. This is a good function to override for subclasses."""
self.__params.update(params)
self.paramStateChanged()
def paramStateChanged(self):
pass
def __getitem__(self, item):
# bug in pyside 1.2.2 causes getitem to be called inside QGraphicsObject.parentItem:
return self.getParam(item) # PySide bug: https://bugreports.qt.io/browse/PYSIDE-441
def getParam(self, param):
return self.__params[param]
class Optic(pg.GraphicsObject, ParamObj):
sigStateChanged = QtCore.Signal()
def __init__(self, gitem, **params):
ParamObj.__init__(self)
pg.GraphicsObject.__init__(self) #, [0,0], [1,1])
self.gitem = gitem
self.surfaces = gitem.surfaces
gitem.setParentItem(self)
self.roi = pg.ROI([0,0], [1,1])
self.roi.addRotateHandle([1, 1], [0.5, 0.5])
self.roi.setParentItem(self)
defaults = {
'pos': Point(0,0),
'angle': 0,
}
defaults.update(params)
self._ior_cache = {}
self.roi.sigRegionChanged.connect(self.roiChanged)
self.setParams(**defaults)
def updateTransform(self):
self.resetTransform()
self.setPos(0, 0)
self.translate(Point(self['pos']))
self.rotate(self['angle'])
def setParam(self, param, val):
ParamObj.setParam(self, param, val)
def paramStateChanged(self):
"""Some parameters of the optic have changed."""
# Move graphics item
self.gitem.setPos(Point(self['pos']))
self.gitem.resetTransform()
self.gitem.rotate(self['angle'])
# Move ROI to match
try:
self.roi.sigRegionChanged.disconnect(self.roiChanged)
br = self.gitem.boundingRect()
o = self.gitem.mapToParent(br.topLeft())
self.roi.setAngle(self['angle'])
self.roi.setPos(o)
self.roi.setSize([br.width(), br.height()])
finally:
self.roi.sigRegionChanged.connect(self.roiChanged)
self.sigStateChanged.emit()
def roiChanged(self, *args):
pos = self.roi.pos()
# rotate gitem temporarily so we can decide where it will need to move
self.gitem.resetTransform()
self.gitem.rotate(self.roi.angle())
br = self.gitem.boundingRect()
o1 = self.gitem.mapToParent(br.topLeft())
self.setParams(angle=self.roi.angle(), pos=pos + (self.gitem.pos() - o1))
def boundingRect(self):
return QtCore.QRectF()
def paint(self, p, *args):
pass
def ior(self, wavelength):
return GLASSDB.ior(self['glass'], wavelength)
class Lens(Optic):
def __init__(self, **params):
defaults = {
'dia': 25.4, ## diameter of lens
'r1': 50., ## positive means convex, use 0 for planar
'r2': 0, ## negative means convex
'd': 4.0,
'glass': 'N-BK7',
'reflect': False,
}
defaults.update(params)
d = defaults.pop('d')
defaults['x1'] = -d/2.
defaults['x2'] = d/2.
gitem = CircularSolid(brush=(100, 100, 130, 100), **defaults)
Optic.__init__(self, gitem, **defaults)
def propagateRay(self, ray):
"""Refract, reflect, absorb, and/or scatter ray. This function may create and return new rays"""
"""
NOTE:: We can probably use this to compute refractions faster: (from GLSL 120 docs)
For the incident vector I and surface normal N, and the
ratio of indices of refraction eta, return the refraction
vector. The result is computed by
k = 1.0 - eta * eta * (1.0 - dot(N, I) * dot(N, I))
if (k < 0.0)
return genType(0.0)
else
return eta * I - (eta * dot(N, I) + sqrt(k)) * N
The input parameters for the incident vector I and the
surface normal N must already be normalized to get the
desired results. eta == ratio of IORs
For reflection:
For the incident vector I and surface orientation N,
returns the reflection direction:
I – 2 ∗ dot(N, I) ∗ N
N must already be normalized in order to achieve the
desired result.
"""
iors = [self.ior(ray['wl']), 1.0]
for i in [0,1]:
surface = self.surfaces[i]
ior = iors[i]
p1, ai = surface.intersectRay(ray)
#print "surface intersection:", p1, ai*180/3.14159
#trans = self.sceneTransform().inverted()[0] * surface.sceneTransform()
#p1 = trans.map(p1)
if p1 is None:
ray.setEnd(None)
break
p1 = surface.mapToItem(ray, p1)
#print "adjusted position:", p1
#ior = self.ior(ray['wl'])
rd = ray['dir']
a1 = np.arctan2(rd[1], rd[0])
ar = a1 - ai + np.arcsin((np.sin(ai) * ray['ior'] / ior))
#print [x for x in [a1, ai, (np.sin(ai) * ray['ior'] / ior), ar]]
#print ai, np.sin(ai), ray['ior'], ior
ray.setEnd(p1)
dp = Point(np.cos(ar), np.sin(ar))
#p2 = p1+dp
#p1p = self.mapToScene(p1)
#p2p = self.mapToScene(p2)
#dpp = Point(p2p-p1p)
ray = Ray(parent=ray, ior=ior, dir=dp)
return [ray]
class Mirror(Optic):
def __init__(self, **params):
defaults = {
'r1': 0,
'r2': 0,
'd': 0.01,
}
defaults.update(params)
d = defaults.pop('d')
defaults['x1'] = -d/2.
defaults['x2'] = d/2.
gitem = CircularSolid(brush=(100,100,100,255), **defaults)
Optic.__init__(self, gitem, **defaults)
def propagateRay(self, ray):
"""Refract, reflect, absorb, and/or scatter ray. This function may create and return new rays"""
surface = self.surfaces[0]
p1, ai = surface.intersectRay(ray)
if p1 is not None:
p1 = surface.mapToItem(ray, p1)
rd = ray['dir']
a1 = np.arctan2(rd[1], rd[0])
ar = a1 + np.pi - 2*ai
ray.setEnd(p1)
dp = Point(np.cos(ar), np.sin(ar))
ray = Ray(parent=ray, dir=dp)
else:
ray.setEnd(None)
return [ray]
class CircularSolid(pg.GraphicsObject, ParamObj):
"""GraphicsObject with two circular or flat surfaces."""
def __init__(self, pen=None, brush=None, **opts):
"""
Arguments for each surface are:
x1,x2 - position of center of _physical surface_
r1,r2 - radius of curvature
d1,d2 - diameter of optic
"""
defaults = dict(x1=-2, r1=100, d1=25.4, x2=2, r2=100, d2=25.4)
defaults.update(opts)
ParamObj.__init__(self)
self.surfaces = [CircleSurface(defaults['r1'], defaults['d1']), CircleSurface(-defaults['r2'], defaults['d2'])]
pg.GraphicsObject.__init__(self)
for s in self.surfaces:
s.setParentItem(self)
if pen is None:
self.pen = pg.mkPen((220,220,255,200), width=1, cosmetic=True)
else:
self.pen = pg.mkPen(pen)
if brush is None:
self.brush = pg.mkBrush((230, 230, 255, 30))
else:
self.brush = pg.mkBrush(brush)
self.setParams(**defaults)
def paramStateChanged(self):
self.updateSurfaces()
def updateSurfaces(self):
self.surfaces[0].setParams(self['r1'], self['d1'])
self.surfaces[1].setParams(-self['r2'], self['d2'])
self.surfaces[0].setPos(self['x1'], 0)
self.surfaces[1].setPos(self['x2'], 0)
self.path = QtGui.QPainterPath()
self.path.connectPath(self.surfaces[0].path.translated(self.surfaces[0].pos()))
self.path.connectPath(self.surfaces[1].path.translated(self.surfaces[1].pos()).toReversed())
self.path.closeSubpath()
def boundingRect(self):
return self.path.boundingRect()
def shape(self):
return self.path
def paint(self, p, *args):
p.setRenderHints(p.renderHints() | p.Antialiasing)
p.setPen(self.pen)
p.fillPath(self.path, self.brush)
p.drawPath(self.path)
class CircleSurface(pg.GraphicsObject):
def __init__(self, radius=None, diameter=None):
"""center of physical surface is at 0,0
radius is the radius of the surface. If radius is None, the surface is flat.
diameter is of the optic's edge."""
pg.GraphicsObject.__init__(self)
self.r = radius
self.d = diameter
self.mkPath()
def setParams(self, r, d):
self.r = r
self.d = d
self.mkPath()
def mkPath(self):
self.prepareGeometryChange()
r = self.r
d = self.d
h2 = d/2.
self.path = QtGui.QPainterPath()
if r == 0: ## flat surface
self.path.moveTo(0, h2)
self.path.lineTo(0, -h2)
else:
## half-height of surface can't be larger than radius
h2 = min(h2, abs(r))
#dx = abs(r) - (abs(r)**2 - abs(h2)**2)**0.5
#p.moveTo(-d*w/2.+ d*dx, d*h2)
arc = QtCore.QRectF(0, -r, r*2, r*2)
#self.surfaces.append((arc.center(), r, h2))
a1 = np.arcsin(h2/r) * 180. / np.pi
a2 = -2*a1
a1 += 180.
self.path.arcMoveTo(arc, a1)
self.path.arcTo(arc, a1, a2)
#if d == -1:
#p1 = QtGui.QPainterPath()
#p1.addRect(arc)
#self.paths.append(p1)
self.h2 = h2
def boundingRect(self):
return self.path.boundingRect()
def paint(self, p, *args):
return ## usually we let the optic draw.
#p.setPen(pg.mkPen('r'))
#p.drawPath(self.path)
def intersectRay(self, ray):
## return the point of intersection and the angle of incidence
#print "intersect ray"
h = self.h2
r = self.r
p, dir = ray.currentState(relativeTo=self) # position and angle of ray in local coords.
#print " ray: ", p, dir
p = p - Point(r, 0) ## move position so center of circle is at 0,0
#print " adj: ", p, r
if r == 0:
#print " flat"
if dir[0] == 0:
y = 0
else:
y = p[1] - p[0] * dir[1]/dir[0]
if abs(y) > h:
return None, None
else:
return (Point(0, y), np.arctan2(dir[1], dir[0]))
else:
#print " curve"
## find intersection of circle and line (quadratic formula)
dx = dir[0]
dy = dir[1]
dr = (dx**2 + dy**2) ** 0.5
D = p[0] * (p[1]+dy) - (p[0]+dx) * p[1]
idr2 = 1.0 / dr**2
disc = r**2 * dr**2 - D**2
if disc < 0:
return None, None
disc2 = disc**0.5
if dy < 0:
sgn = -1
else:
sgn = 1
br = self.path.boundingRect()
x1 = (D*dy + sgn*dx*disc2) * idr2
y1 = (-D*dx + abs(dy)*disc2) * idr2
if br.contains(x1+r, y1):
pt = Point(x1, y1)
else:
x2 = (D*dy - sgn*dx*disc2) * idr2
y2 = (-D*dx - abs(dy)*disc2) * idr2
pt = Point(x2, y2)
if not br.contains(x2+r, y2):
return None, None
raise Exception("No intersection!")
norm = np.arctan2(pt[1], pt[0])
if r < 0:
norm += np.pi
#print " norm:", norm*180/3.1415
dp = p - pt
#print " dp:", dp
ang = np.arctan2(dp[1], dp[0])
#print " ang:", ang*180/3.1415
#print " ai:", (ang-norm)*180/3.1415
#print " intersection:", pt
return pt + Point(r, 0), ang-norm
class Ray(pg.GraphicsObject, ParamObj):<|fim▁hole|> def __init__(self, **params):
ParamObj.__init__(self)
defaults = {
'ior': 1.0,
'wl': 500,
'end': None,
'dir': Point(1,0),
}
self.params = {}
pg.GraphicsObject.__init__(self)
self.children = []
parent = params.get('parent', None)
if parent is not None:
defaults['start'] = parent['end']
defaults['wl'] = parent['wl']
self['ior'] = parent['ior']
self['dir'] = parent['dir']
parent.addChild(self)
defaults.update(params)
defaults['dir'] = Point(defaults['dir'])
self.setParams(**defaults)
self.mkPath()
def clearChildren(self):
for c in self.children:
c.clearChildren()
c.setParentItem(None)
self.scene().removeItem(c)
self.children = []
def paramStateChanged(self):
pass
def addChild(self, ch):
self.children.append(ch)
ch.setParentItem(self)
def currentState(self, relativeTo=None):
pos = self['start']
dir = self['dir']
if relativeTo is None:
return pos, dir
else:
trans = self.itemTransform(relativeTo)[0]
p1 = trans.map(pos)
p2 = trans.map(pos + dir)
return Point(p1), Point(p2-p1)
def setEnd(self, end):
self['end'] = end
self.mkPath()
def boundingRect(self):
return self.path.boundingRect()
def paint(self, p, *args):
#p.setPen(pg.mkPen((255,0,0, 150)))
p.setRenderHints(p.renderHints() | p.Antialiasing)
p.setCompositionMode(p.CompositionMode_Plus)
p.setPen(wlPen(self['wl']))
p.drawPath(self.path)
def mkPath(self):
self.prepareGeometryChange()
self.path = QtGui.QPainterPath()
self.path.moveTo(self['start'])
if self['end'] is not None:
self.path.lineTo(self['end'])
else:
self.path.lineTo(self['start']+500*self['dir'])
def trace(rays, optics):
if len(optics) < 1 or len(rays) < 1:
return
for r in rays:
r.clearChildren()
o = optics[0]
r2 = o.propagateRay(r)
trace(r2, optics[1:])
class Tracer(QtCore.QObject):
"""
Simple ray tracer.
Initialize with a list of rays and optics;
calling trace() will cause rays to be extended by propagating them through
each optic in sequence.
"""
def __init__(self, rays, optics):
QtCore.QObject.__init__(self)
self.optics = optics
self.rays = rays
for o in self.optics:
o.sigStateChanged.connect(self.trace)
self.trace()
def trace(self):
trace(self.rays, self.optics)<|fim▁end|> | """Represents a single straight segment of a ray"""
sigStateChanged = QtCore.Signal()
|
<|file_name|>api.py<|end_file_name|><|fim▁begin|>##
# api.py
#
# This file is the workhorse for the the entire web application.
# It implements and provides the API required for the iOS portion
# of the project as well as interacting with Google's datastore
# for persistent storage of our models.
##
# for sending mail
from google.appengine.api import mail
# Used in conjunction with the geomodel library for doing
# proximity based searches
from google.appengine.ext.db import GeoPt
from geo import geotypes
# HttpResponse is what all Django-based views must return
# to render the output. In our web application the
# _json* methods build and return HttpResponse objects
# for rendering JSON dat
from django.http import HttpResponse
# For encoding Python objects into JSON strings
from django.utils import simplejson
# Our datastore models
from model import *
# For handling user sessions
from appengine_utilities.sessions import Session
# Provides the sha1 module we use for hashing passwords
import hashlib
# The Python loggin module. We use the basicConfig method
# to setup to log to the console (or GoogleAppEngineLauncher
# logs screen)
import logging
logging.basicConfig(level=logging.DEBUG)
##
# CONSTANTS
##
"""
The email address to send from. See the Notes section of the README
for more information on what to set this to.
"""
SENDER_EMAIL_ADDRESS = "VALID@APPENGINE_ADDRESS.COM"
<|fim▁hole|>##
def _hash_password(password):
"""
Returns a sha1-hashed version of the given plaintext password.
"""
return hashlib.sha1(password).hexdigest()
def _json_response(success=True, msg="OK", **kwargs):
"""
Helper method to build an HTTPResponse with a stock
JSON object.
@param success=True: indicates success or failure of the API method
@param msg: string with details on success or failure
@kwargs: any number of key/value pairs to be sent with the JSON object
"""
# build up the response data and convert it to a string using the
# simplejson module
response_data = dict(success=success, msg=msg)
response_data.update(kwargs)
response_string = simplejson.dumps(response_data)
# All views must return a valid HttpResponse object so build it and
# set the JSON string and mimetype indicating that the result is
# JSON
return HttpResponse(response_string, mimetype="application/json")
def _json_unauthorized_response(**kwargs):
"""
Helper method to build an HTTPResponse with a stock JSON object
that represents unauthorized access to an API method.
NOTE: Always returns success=false and msg="Unauthorized"
@kwargs: any number of key/value pairs to be sent with the JSON object
"""
# Same process as _json_response method, accept always return false and
# an Unauthorized message with a status code of 401
response_data = dict(success=False, msg="Unauthorized")
response_data.update(kwargs)
response_string = simplejson.dumps(response_data)
return HttpResponse(response_string, status=401, mimetype="application/json")
##
# DECORATORS
#
# For more information about decorators in Python see:
#
# http://www.python.org/dev/peps/pep-0318/
# http://wiki.python.org/moin/PythonDecorators
# http://www.ibm.com/developerworks/linux/library/l-cpdecor.html
# Google...
##
# Usage: @validate_request(method, p1, p2, ...)
def validate_request(method, *params):
"""
Decorator for validating the required request method for an API call as
well as enforcing any required parameters in the request. If either the
method or parameter checks fail a stock failure JSON object is returned
with the exact issue in the msg field. If all checks pass then the
API call proceeds.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# check the required method
if request.method == method:
# check that each parameter exists and has a value
for param in params:
value = request.REQUEST.get(param, "")
if not value:
# failed parameter check
return _json_response(success=False,
msg="'%s' is required." % param)
# return the original API call through
return view_func(request, *args, **kwargs)
else:
# failed method check
return _json_response(success=False,
msg="%s requests are not allowed." % request.method)
return _view
return _dec
# Usage: @validate_session()
def validate_session():
"""
Decorator for validating that a user is authenticated by checking the
session for a user object. If this fails the stock json_unauthorized_response
is returned or else the API call is allowed to proceed.
"""
def _dec(view_func):
def _view(request, *args, **kwargs):
# get the session and check for a user, fail if it doesn't exist
if Session().get("user") is None:
# failed request
return _json_unauthorized_response()
# return the original API call through
return view_func(request, *args, **kwargs)
return _view
return _dec
##
# API METHODS
##
@validate_session()
@validate_request("POST", "question", "latitude", "longitude", "pay_key")
def ask(request):
"""
API Method - /ask
Creates a new Question and adds it to the datastore
@method POST
@param question: the text of the question
@param latitude: latitude of the location
@param longitude: longitude of the location
@param pay_key: the pay key from a successful PayPal purchase
@returns stock success or failure JSON response along with
the question and user objects.
"""
# authenticated user
user = Session().get("user")
# required parameters
question = request.REQUEST.get("question")
latitude = float(request.REQUEST.get("latitude"))
longitude = float(request.REQUEST.get("longitude"))
pay_key = request.REQUEST.get("pay_key")
# Using the PayKey you could validate it using PayPal APIs
# to confirm that a user paid and the transaction is complete.
# This is left up to the curious coder to implement :)
# Create the question with the required fields and tie it
# to the authenticated user
q = Question(question=question,
location=GeoPt(latitude, longitude),
user=user)
q.update_location()
q.put()
# return stock JSON with the Question object details
return _json_response(question=q.to_json(), user=user.to_json())
@validate_session()
@validate_request("POST", "question_id", "answer")
def answer(request):
"""
API Method - /answer
Creates a new Answer object and adds it to the datastore. Validates
that the question exists and does not have an accepted answer before
accepting the answer.
This method also takes care of sending the owner of the question
an email saying a new answer has been given with the answer in the
body of the message.
@method POST
@param question_id: id of an existing question
@param answer: the text for the answer to a question
@returns one answer object
"""
# session and authenticated user
user = Session().get("user")
# required parameters
question_id = int(request.REQUEST.get("question_id"))
answer = request.REQUEST.get("answer")
# find the question associated with the question_id parameter
question = Question.get_by_id(question_id)
# no question with the given id
if question is None:
return _json_response(success=False, msg="Question does not exist.")
# question has already been answered
if question.closed:
return _json_response(success=False, msg="Question has an accepted answer and is now closed.")
# create a new answer and save it to the datastore
a = Answer(user=user,
question=question,
answer=answer)
a.put()
# send an email to the owner of the question
question_owner_email = question.user.email
mail.send_mail(sender=SENDER_EMAIL_ADDRESS,
to=question_owner_email,
subject="Your question has a new answer!",
body="""
This is to inform you that one of your questions has
received a new answer.
Your question:
%s
The answer:
%s
Regards,
Inquire Application
""" % (question.question, answer))
# return stock JSON with details of the answer object
return _json_response(answer=a.to_json())
@validate_session()
@validate_request("POST", "answer_id")
def accept(request):
"""
API Method - /accept
Accepts an answer for a question. The question must be owned by the
current authenticated user accepting the question and not already
have an accepted answer.
This method also takes care of sending the owner of the answer
an email saying their answer was accepted. The accepted answer
owner will also be given one karma point.
@method POST
@param answer_id: id of the answer being accepted
@returns stock JSON object
"""
# session and authenticated user
user = Session().get("user")
# required parameters
answer_id = int(request.REQUEST.get("answer_id"))
# find the answer associated with the answer_id
answer = Answer.get_by_id(answer_id)
# no answer with the given id
if answer is None:
return _json_response(success=False, msg="Answer does not exist.")
# associated question
question = answer.question
# make sure the question for this answer is owned by this user
question = answer.question
if question.user.key().id() != user.key().id():
return _json_response(success=False, msg="You must be the owner of the question to accept an answer.")
# also make sure the question is not already answered
if question.closed:
return _json_response(success=False, msg="Question already has an accepted answer.")
# change the accepted flag of the answer and save it.
answer.accepted_answer = True
answer.put()
# close the question and save it
question.closed = True
question.put()
# update the answer owner's karma points
answer.user.karma += 1
answer.user.put()
# send an email to the address assigned to the answer
answer_owner_email = answer.user.email
mail.send_mail(sender=SENDER_EMAIL_ADDRESS,
to=answer_owner_email,
subject="Your answer was accepted!",
body="""
This is to inform you that one of your answers has
been accepted! You have been given one karma point.
The question you answered:
%s
Your answer:
%s
Regards,
Inquire Application
""" % (question.question, answer.answer))
# return stock success JSON
return _json_response()
@validate_session()
@validate_request("GET", "question_id")
def answers(request):
"""
API Method - /answers
Returns a list of answers for a given question id.
@method GET
@param question_id: The question id to retrieve answers for
@returns list of answer objects
"""
# required parameters
question_id = int(request.GET.get("question_id"))
# retrieve the matching question
question = Question.get_by_id(question_id)
if question is None:
return _json_response(success=False,
msg="Question does not exist!")
return _json_response(answers=[a.to_json() for a in question.answer_set])
@validate_session()
@validate_request("GET", "latitude", "longitude")
def questions(request):
"""
API Method - /questions
Returns a list of questions that are within geographical proximity
to the passed in latitude/longitude.
@method GET
@param latitude: latitude of the location
@param longitude longitude of the location
@optional max_results: max number of questions to return, default=25
@optional max_distance: max distance to search in miles
@returns list of question objects
"""
# required parameters
latitude = float(request.GET.get("latitude"))
longitude = float(request.GET.get("longitude"))
# defines the center of our proximity search
# geotypes.Point provided by geomodel project
center = geotypes.Point(latitude, longitude)
# default
max_results = int(request.GET.get("max_results", 25)) # 25 results default
max_distance = int(request.GET.get("max_distance", 50)) # 50 mile default
# convert miles to kilometers
max_distance = 1000*max_distance/0.621371192
# Get all unclosed questions within the proximity max_distance and
# limit to max_results
base_query = Question.all().filter("closed =", False)
questions = Question.proximity_fetch(base_query,
center,
max_results=max_results,
max_distance=max_distance)
return _json_response(questions=[q.to_json() for q in questions])
@validate_request("POST", "email", "password")
def register(request):
"""
API Method - /register
Creates a new user and adds it to the datastore. If a user already
exists with the given email address the request fails and an
appropriate JSON response is returned.
@method POST
@param email: email address for the user
@param password: password for the user
@returns newly created user object or failure JSON
"""
# required parameters
email = request.POST.get("email")
password = request.POST.get("password")
#
users = User.all()
users.filter("email =", email)
if users.count() != 0:
return _json_response(success=False,
msg="Email address already exists.", users=users.count())
password = _hash_password(password)
new_user = User(email=email, password=password)
new_user.put()
return _json_response()
def logout(request):
"""
API Method - /logout
Destroys the active user's session object. Any further use of
protected API methods will require a new session via the auth
API.
@method GET
@returns stock JSON response
"""
# delete session and return stock JSON response with a msg
# indicating the user has logged out
session = Session()
session.delete()
return _json_response(msg="User has been logged out.")
@validate_request("POST", "email", "password")
def auth(request):
"""
API Method - /auth
If credentials are correct a new session is created for this
user which authorizes them to use protected API methods.
@method POST
@param email: user's email address
@param password: user's password
@returns stock JSON response
"""
# required parameters
email = request.POST.get("email")
password = request.POST.get("password")
# hash the password
password = _hash_password(password)
# Look up a User object that matches the email/password
users = User.all()
users \
.filter("email =", email) \
.filter("password =", password)
# No user found, return a failure message
if users.count() == 0:
return _json_response(success=False,
msg="Email or password is invalid.")
# Somehow more than one client with the same user/password have
# been created, which should never happen. Error out here.
if users.count() > 1:
return _json_response(details=None,
success=False,
msg="Internal security error. Contact an administrator")
# Pull the User from the datastore
user = users.get()
# Build a new session object and store the user
session = Session()
session["user"] = user
# return stock JSON with user details
return _json_response(user=user.to_json())
# Utility method for generating random questions around a
# given point. The point is currently Apple's headquarters
# so this works well with testing with the simulator.
def randomize(request):
import random
# location to generate questions around
near_lat, near_lon = 37.331693, -122.030457
# ~50 miles
dx = 50.0/69.0
# Number of questions to generate
num_questions = 10
# Possible users to assign questions to. These
# users will be looked up by the email addresses
# supply in this list and they must exist
email_accounts = ["[email protected]", "[email protected]"]
# no more editing
# look up the user objects associated with the
# given email addresses
users = []
for email in email_accounts:
user = User.all().filter("email =", email).get()
if user is not None:
users.append(user)
# return false if there were no user objects found
if not users:
return _json_response(success=False, msg="No users found")
# generate num_questions random questions around the given
# point (near_lat, near_lon) within some distance dx and
# assigning a random user to the question
for i in range(num_questions):
lat = random.uniform(near_lat-dx, near_lat+dx)
lon = random.uniform(near_lon-dx, near_lon+dx)
user = random.sample(users, 1)[0]
q = Question(user=user,
question="Question %d" % i,
location=db.GeoPt(lat, lon))
q.update_location()
q.put()
# return true
return _json_response()<|fim▁end|> | ##
# UTILITY METHODS |
<|file_name|>Number.isInteger.js<|end_file_name|><|fim▁begin|><|fim▁hole|>if (!Number.isInteger) {
Number.isInteger = function(value) {
return typeof value === 'number'
&& isFinite(value)
&& Math.floor(value) === value;
};
}<|fim▁end|> | |
<|file_name|>cloudstack.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) 2015, René Moser <[email protected]>
#
# This file is part of Ansible,
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
######################################################################
"""
Ansible CloudStack external inventory script.
=============================================
Generates Ansible inventory from CloudStack. Configuration is read from
'cloudstack.ini'. If you need to pass the project, write a simple wrapper
script, e.g. project_cloudstack.sh:
#!/bin/bash
cloudstack.py --project <your_project> $@
When run against a specific host, this script returns the following attributes
based on the data obtained from CloudStack API:
"web01": {
"cpu_number": 2,
"nic": [
{
"ip": "10.102.76.98",
"mac": "02:00:50:99:00:01",
"type": "Isolated",
"netmask": "255.255.255.0",
"gateway": "10.102.76.1"
},
{
"ip": "10.102.138.63",
"mac": "06:b7:5a:00:14:84",
"type": "Shared",
"netmask": "255.255.255.0",
"gateway": "10.102.138.1"
}
],
"default_ip": "10.102.76.98",
"zone": "ZUERICH",
"created": "2014-07-02T07:53:50+0200",
"hypervisor": "VMware",
"memory": 2048,
"state": "Running",
"tags": [],
"cpu_speed": 1800,
"affinity_group": [],
"service_offering": "Small",
"cpu_used": "62%"
}
usage: cloudstack.py [--list] [--host HOST] [--project PROJECT] [--domain DOMAIN]
"""
from __future__ import print_function
import os
import sys
import argparse
try:
import json
except:
import simplejson as json
try:
from cs import CloudStack, CloudStackException, read_config<|fim▁hole|>
class CloudStackInventory(object):
def __init__(self):
parser = argparse.ArgumentParser()
parser.add_argument('--host')
parser.add_argument('--list', action='store_true')
parser.add_argument('--project')
parser.add_argument('--domain')
options = parser.parse_args()
try:
self.cs = CloudStack(**read_config())
except CloudStackException as e:
print("Error: Could not connect to CloudStack API", file=sys.stderr)
sys.exit(1)
domain_id = None
if options.domain:
domain_id = self.get_domain_id(options.domain)
project_id = None
if options.project:
project_id = self.get_project_id(options.project, domain_id)
if options.host:
data = self.get_host(options.host, project_id, domain_id)
print(json.dumps(data, indent=2))
elif options.list:
data = self.get_list(project_id, domain_id)
print(json.dumps(data, indent=2))
else:
print("usage: --list | --host <hostname> [--project <project>] [--domain <domain_path>]",
file=sys.stderr)
sys.exit(1)
def get_domain_id(self, domain):
domains = self.cs.listDomains(listall=True)
if domains:
for d in domains['domain']:
if d['path'].lower() == domain.lower():
return d['id']
print("Error: Domain %s not found." % domain, file=sys.stderr)
sys.exit(1)
def get_project_id(self, project, domain_id=None):
projects = self.cs.listProjects(domainid=domain_id)
if projects:
for p in projects['project']:
if p['name'] == project or p['id'] == project:
return p['id']
print("Error: Project %s not found." % project, file=sys.stderr)
sys.exit(1)
def get_host(self, name, project_id=None, domain_id=None):
hosts = self.cs.listVirtualMachines(projectid=project_id, domainid=domain_id)
data = {}
if not hosts:
return data
for host in hosts['virtualmachine']:
host_name = host['displayname']
if name == host_name:
data['zone'] = host['zonename']
if 'group' in host:
data['group'] = host['group']
data['state'] = host['state']
data['service_offering'] = host['serviceofferingname']
data['affinity_group'] = host['affinitygroup']
data['security_group'] = host['securitygroup']
data['cpu_number'] = host['cpunumber']
data['cpu_speed'] = host['cpuspeed']
if 'cpuused' in host:
data['cpu_used'] = host['cpuused']
data['memory'] = host['memory']
data['tags'] = host['tags']
data['hypervisor'] = host['hypervisor']
data['created'] = host['created']
data['nic'] = []
for nic in host['nic']:
data['nic'].append({
'ip': nic['ipaddress'],
'mac': nic['macaddress'],
'netmask': nic['netmask'],
'gateway': nic['gateway'],
'type': nic['type'],
})
if nic['isdefault']:
data['default_ip'] = nic['ipaddress']
break;
return data
def get_list(self, project_id=None, domain_id=None):
data = {
'all': {
'hosts': [],
},
'_meta': {
'hostvars': {},
},
}
groups = self.cs.listInstanceGroups(projectid=project_id, domainid=domain_id)
if groups:
for group in groups['instancegroup']:
group_name = group['name']
if group_name and not group_name in data:
data[group_name] = {
'hosts': []
}
hosts = self.cs.listVirtualMachines(projectid=project_id, domainid=domain_id)
if not hosts:
return data
for host in hosts['virtualmachine']:
host_name = host['displayname']
data['all']['hosts'].append(host_name)
data['_meta']['hostvars'][host_name] = {}
# Make a group per zone
data['_meta']['hostvars'][host_name]['zone'] = host['zonename']
group_name = host['zonename']
if group_name not in data:
data[group_name] = {
'hosts': []
}
data[group_name]['hosts'].append(host_name)
if 'group' in host:
data['_meta']['hostvars'][host_name]['group'] = host['group']
data['_meta']['hostvars'][host_name]['state'] = host['state']
data['_meta']['hostvars'][host_name]['service_offering'] = host['serviceofferingname']
data['_meta']['hostvars'][host_name]['affinity_group'] = host['affinitygroup']
data['_meta']['hostvars'][host_name]['security_group'] = host['securitygroup']
data['_meta']['hostvars'][host_name]['cpu_number'] = host['cpunumber']
data['_meta']['hostvars'][host_name]['cpu_speed'] = host['cpuspeed']
if 'cpuused' in host:
data['_meta']['hostvars'][host_name]['cpu_used'] = host['cpuused']
data['_meta']['hostvars'][host_name]['created'] = host['created']
data['_meta']['hostvars'][host_name]['memory'] = host['memory']
data['_meta']['hostvars'][host_name]['tags'] = host['tags']
data['_meta']['hostvars'][host_name]['hypervisor'] = host['hypervisor']
data['_meta']['hostvars'][host_name]['created'] = host['created']
data['_meta']['hostvars'][host_name]['nic'] = []
for nic in host['nic']:
data['_meta']['hostvars'][host_name]['nic'].append({
'ip': nic['ipaddress'],
'mac': nic['macaddress'],
'netmask': nic['netmask'],
'gateway': nic['gateway'],
'type': nic['type'],
})
if nic['isdefault']:
data['_meta']['hostvars'][host_name]['default_ip'] = nic['ipaddress']
group_name = ''
if 'group' in host:
group_name = host['group']
if group_name and group_name in data:
data[group_name]['hosts'].append(host_name)
return data
if __name__ == '__main__':
CloudStackInventory()<|fim▁end|> | except ImportError:
print("Error: CloudStack library must be installed: pip install cs.",
file=sys.stderr)
sys.exit(1) |
<|file_name|>views.py<|end_file_name|><|fim▁begin|>from django.shortcuts import render,HttpResponse
from .models import Employee
from .models import Record
import datetime
import calendar
def wage_list(request):
return render(request,'app/wage_list.html',{})
def get_data(request):
date_from_user = str(request.POST.get('datepicker'))
date_from_user = date_from_user.split(' ')# 1st month 2nd is year
print(date_from_user)<|fim▁hole|>
filtered_record = Record.objects.filter(date__year=date_from_user[1],date__month=date_from_user[0])
employees_list = list(filtered_record)
print(type(employees_list))
temp=[]
employees = Employee.objects.all()
e = Employee.objects.all()
# To find no of working days
full_date = datetime.datetime.now()
no_of_sundays = sum( [ 1 for i in calendar.monthcalendar( full_date.year, full_date.month ) if i[6]!=0 ] )
no_of_saturdays = sum( [ 1 for i in calendar.monthcalendar( full_date.year, full_date.month ) if i[5]!=0 ] )
tupl = calendar.monthrange(full_date.year,full_date.month)
total_days_in_month = int(tupl[1])
total_working_days = int(total_days_in_month - ( no_of_sundays + no_of_saturdays))
# End to find no of working days
# To find net payable slary
no_of_employees = filtered_record.count()
salary_payable=[]
salary=[]
net_payable = []
no_of_holiday = []
salary_deducted = []
net_final_payable = []
total_ot_hrs = []
Ot_Salary = []
salary_per_day=[]
days_attended = []
esi_cutting = []
esi = 1.75
i=0
int_array=[]
name_of_employee=[]
for counter in range(no_of_employees):
int_array.append(int(counter))
emp_data = []
while i<no_of_employees:
salary.append( int(filtered_record[i].Employee.pay_per_month) ) # Salary per month
salary_per_day.append(( round(int(filtered_record[i].Employee.pay_per_month)/total_working_days,2) ))
# name_of_employee.append(filtered_record[i].Employee.first_name)
temp.append(employees_list[i].Employee)
m=filtered_record[i].Employee.record_set.all()
no_of_holiday.append(str(int(m[0].no_of_holidays) + float(float(m[0].no_of_hours_absent)/8) ))
days_attended.append(float(total_working_days) - float(no_of_holiday[i]))
salary_payable.append( round(salary_per_day[i] * days_attended[i],2))
esi_cutting.append( round(salary_payable[i]*0.0175,2) )
net_salary = round(salary_payable[i] - salary_payable[i]*0.0175,2)
net_payable.append(net_salary)
# salary_deducted.append( round((int(m[0].no_of_holidays) + int(int(m[0].no_of_hours_absent)/8))*salary_per_day[i],2 ))
salary_deducted.append( round((int(int(m[0].no_of_hours_absent)/8))*salary_per_day[i],2 ))
total_ot_hrs.append(int(m[0].no_of_ot_hours))
Ot_Salary.append( round((int(m[0].no_of_ot_hours)/8)*salary_per_day[i],2) )
net_final_payable.append( round(Ot_Salary[i] + net_payable[i] -salary_deducted[i],2) )
emp_data.append({
'name_of_employee':temp[-1],
'salary':salary[-1],
'salary_payable' : salary_payable[-1],
'no_of_holiday' : no_of_holiday[-1],
'esi_cutting' : esi_cutting[-1],
'net_payable' : net_payable[-1],
'salary_deducted' : salary_deducted[-1],
'total_ot_hrs' : total_ot_hrs[-1],
'Ot_Salary' : Ot_Salary[-1],
'net_final_payable' : net_final_payable[-1],
})
# print(no_of_holiday)
i+=1
# End to find net payable slary
return render(request,'app/wage_list.html',{'employees': employees_list,'twd':total_working_days,'no_of_employees':no_of_employees,'salary':salary,
'salary_payable':salary_payable,'net_payable':net_payable,'no_of_holiday':no_of_holiday,'salary_deducted':salary_deducted,
'total_ot_hrs':total_ot_hrs,'Ot_Salary':Ot_Salary,'net_final_payable':net_final_payable,'esi':esi,
'esi_cutting':esi_cutting,'filtered_record':filtered_record,'int_array':int_array,'emp_data':emp_data})
# Make ESI new variable
def index_data(request):
return render(request,'app/wage_list.html',{})<|fim▁end|> | |
<|file_name|>FormLoader.java<|end_file_name|><|fim▁begin|>import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class FormLoader {
public static String connectionString = "jdbc:hsqldb:file:db-data/teamsandplayers";
static Connection con;
public static void main(String[] args) throws Exception {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
} catch (ClassNotFoundException e) {
throw e;
}
<|fim▁hole|>
MainTeamForm form = new MainTeamForm();
form.setVisible(true);
try {
// will create DB if does not exist
// "SA" is default user with hypersql
con = DriverManager.getConnection(connectionString, "SA", "");
} catch (SQLException e) {
throw e;
} finally {
con.close();
System.out.println("Program complete");
}
}
}<|fim▁end|> | |
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>pub fn abbreviate(text: &str) -> String {
let mut acronym = text.chars().nth(0).unwrap().to_string();
let mut prev = text.chars().nth(0).unwrap();
for c in text.chars().skip(1) {
if c.is_uppercase() && !prev.is_uppercase() ||
prev.is_whitespace() ||
!prev.is_alphanumeric()
&& !c.is_whitespace() {
acronym.push(c);
}
prev = c;
}<|fim▁hole|><|fim▁end|> | acronym.to_uppercase()
} |
<|file_name|>bitcoin_zh_TW.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="zh_TW" version="2.0">
<context>
<name>AboutDialog</name>
<message>
<location filename="../forms/aboutdialog.ui" line="+14"/>
<source>About Bitcoin</source>
<translation>關於位元幣</translation>
</message>
<message>
<location line="+39"/>
<source><b>Bitcoin</b> version</source>
<translation><b>位元幣</b>版本</translation>
</message>
<message>
<location line="+57"/>
<source>
This is experimental software.
Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php.
This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source>
<translation>
這是一套實驗性的軟體.
此軟體是依據 MIT/X11 軟體授權條款散布, 詳情請見附帶的 COPYING 檔案, 或是以下網站: http://www.opensource.org/licenses/mit-license.php.
此產品也包含了由 OpenSSL Project 所開發的 OpenSSL Toolkit (http://www.openssl.org/) 軟體, 由 Eric Young ([email protected]) 撰寫的加解密軟體, 以及由 Thomas Bernard 所撰寫的 UPnP 軟體.</translation>
</message>
<message>
<location filename="../aboutdialog.cpp" line="+14"/>
<source>Copyright</source>
<translation>版權</translation>
</message>
<message>
<location line="+0"/>
<source>The Bitcoin developers</source>
<translation>位元幣開發人員</translation>
</message>
</context>
<context>
<name>AddressBookPage</name>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>Address Book</source>
<translation>位址簿</translation>
</message>
<message>
<location line="+19"/>
<source>Double-click to edit address or label</source>
<translation>點兩下來修改位址或標記</translation>
</message>
<message>
<location line="+27"/>
<source>Create a new address</source>
<translation>產生新位址</translation>
</message>
<message>
<location line="+14"/>
<source>Copy the currently selected address to the system clipboard</source>
<translation>複製目前選取的位址到系統剪貼簿</translation>
</message>
<message>
<location line="-11"/>
<source>&New Address</source>
<translation>新增位址</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="+63"/>
<source>These are your Bitcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source>
<translation>這些是你用來收款的位元幣位址. 你可以提供不同的位址給不同的付款人, 來追蹤是誰支付給你.</translation>
</message>
<message>
<location filename="../forms/addressbookpage.ui" line="+14"/>
<source>&Copy Address</source>
<translation>複製位址</translation>
</message>
<message>
<location line="+11"/>
<source>Show &QR Code</source>
<translation>顯示 &QR 條碼</translation>
</message>
<message>
<location line="+11"/>
<source>Sign a message to prove you own a Bitcoin address</source>
<translation>簽署訊息是用來證明位元幣位址是你的</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>訊息簽署</translation>
</message>
<message>
<location line="+25"/>
<source>Delete the currently selected address from the list</source>
<translation>從列表中刪除目前選取的位址</translation>
</message>
<message>
<location line="+27"/>
<source>Export the data in the current tab to a file</source>
<translation>將目前分頁的資料匯出存成檔案</translation>
</message>
<message>
<location line="+3"/>
<source>&Export</source>
<translation>匯出</translation>
</message>
<message>
<location line="-44"/>
<source>Verify a message to ensure it was signed with a specified Bitcoin address</source>
<translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation>
</message>
<message>
<location line="+3"/>
<source>&Verify Message</source>
<translation>訊息驗證</translation>
</message>
<message>
<location line="+14"/>
<source>&Delete</source>
<translation>刪除</translation>
</message>
<message>
<location filename="../addressbookpage.cpp" line="-5"/>
<source>These are your Bitcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>這是你用來付款的位元幣位址. 在付錢之前, 務必要檢查金額和收款位址是否正確.</translation>
</message>
<message>
<location line="+13"/>
<source>Copy &Label</source>
<translation>複製標記</translation>
</message>
<message>
<location line="+1"/>
<source>&Edit</source>
<translation>編輯</translation>
</message>
<message>
<location line="+1"/>
<source>Send &Coins</source>
<translation>付錢</translation>
</message>
<message>
<location line="+265"/>
<source>Export Address Book Data</source>
<translation>匯出位址簿資料</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>逗號區隔資料檔 (*.csv)</translation>
</message>
<message>
<location line="+13"/>
<source>Error exporting</source>
<translation>匯出失敗</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>無法寫入檔案 %1.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<location filename="../addresstablemodel.cpp" line="+144"/>
<source>Label</source>
<translation>標記</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>位址</translation>
</message>
<message>
<location line="+36"/>
<source>(no label)</source>
<translation>(沒有標記)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<location filename="../forms/askpassphrasedialog.ui" line="+26"/>
<source>Passphrase Dialog</source>
<translation>密碼對話視窗</translation>
</message>
<message>
<location line="+21"/>
<source>Enter passphrase</source>
<translation>輸入密碼</translation>
</message>
<message>
<location line="+14"/>
<source>New passphrase</source>
<translation>新的密碼</translation>
</message>
<message>
<location line="+14"/>
<source>Repeat new passphrase</source>
<translation>重複新密碼</translation>
</message>
<message>
<location filename="../askpassphrasedialog.cpp" line="+33"/>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>輸入錢包的新密碼.<br/>請用<b>10個以上的字元</b>, 或是<b>8個以上的單字</b>.</translation>
</message>
<message>
<location line="+1"/>
<source>Encrypt wallet</source>
<translation>錢包加密</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>這個動作需要用你的錢包密碼來解鎖</translation>
</message>
<message>
<location line="+5"/>
<source>Unlock wallet</source>
<translation>錢包解鎖</translation>
</message>
<message>
<location line="+3"/>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>這個動作需要用你的錢包密碼來解密</translation>
</message>
<message>
<location line="+5"/>
<source>Decrypt wallet</source>
<translation>錢包解密</translation>
</message>
<message>
<location line="+3"/>
<source>Change passphrase</source>
<translation>變更密碼</translation>
</message>
<message>
<location line="+1"/>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>輸入錢包的新舊密碼.</translation>
</message>
<message>
<location line="+46"/>
<source>Confirm wallet encryption</source>
<translation>錢包加密確認</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR BITCOINS</b>!</source>
<translation>警告: 如果將錢包加密後忘記密碼, 你會<b>失去其中所有的位元幣</b>!</translation>
</message>
<message>
<location line="+0"/>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>你確定要將錢包加密嗎?</translation>
</message>
<message>
<location line="+15"/>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>重要: 請改用新產生有加密的錢包檔, 來取代之前錢包檔的備份. 為了安全性的理由, 當你開始使用新的有加密的錢包時, 舊錢包的備份就不能再使用了.</translation>
</message>
<message>
<location line="+100"/>
<location line="+24"/>
<source>Warning: The Caps Lock key is on!</source>
<translation>警告: 大寫字母鎖定作用中!</translation>
</message>
<message>
<location line="-130"/>
<location line="+58"/>
<source>Wallet encrypted</source>
<translation>錢包已加密</translation>
</message>
<message>
<location line="-56"/>
<source>Bitcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your bitcoins from being stolen by malware infecting your computer.</source>
<translation>位元幣現在要關閉以完成加密程序. 請記住, 加密錢包無法完全防止入侵電腦的惡意程式偷取你的位元幣.</translation>
</message>
<message>
<location line="+13"/>
<location line="+7"/>
<location line="+42"/>
<location line="+6"/>
<source>Wallet encryption failed</source>
<translation>錢包加密失敗</translation>
</message>
<message>
<location line="-54"/>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>錢包加密因程式內部錯誤而失敗. 你的錢包還是沒有加密.</translation>
</message>
<message>
<location line="+7"/>
<location line="+48"/>
<source>The supplied passphrases do not match.</source>
<translation>提供的密碼不符.</translation>
</message>
<message>
<location line="-37"/>
<source>Wallet unlock failed</source>
<translation>錢包解鎖失敗</translation>
</message>
<message>
<location line="+1"/>
<location line="+11"/>
<location line="+19"/>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>用來解密錢包的密碼輸入錯誤.</translation>
</message>
<message>
<location line="-20"/>
<source>Wallet decryption failed</source>
<translation>錢包解密失敗</translation>
</message>
<message>
<location line="+14"/>
<source>Wallet passphrase was successfully changed.</source>
<translation>錢包密碼變更成功.</translation>
</message>
</context>
<context>
<name>BitcoinGUI</name>
<message>
<location filename="../bitcoingui.cpp" line="+254"/>
<source>Sign &message...</source>
<translation>訊息簽署...</translation>
</message>
<message>
<location line="+246"/>
<source>Synchronizing with network...</source>
<translation>網路同步中...</translation>
</message>
<message>
<location line="-321"/>
<source>&Overview</source>
<translation>總覽</translation>
</message>
<message>
<location line="+1"/>
<source>Show general overview of wallet</source>
<translation>顯示錢包一般總覽</translation>
</message>
<message>
<location line="+20"/>
<source>&Transactions</source>
<translation>交易</translation>
</message>
<message>
<location line="+1"/>
<source>Browse transaction history</source>
<translation>瀏覽交易紀錄</translation>
</message>
<message>
<location line="+7"/>
<source>Edit the list of stored addresses and labels</source>
<translation>編輯位址與標記的儲存列表</translation>
</message>
<message>
<location line="-14"/>
<source>Show the list of addresses for receiving payments</source>
<translation>顯示收款位址的列表</translation>
</message>
<message>
<location line="+31"/>
<source>E&xit</source>
<translation>結束</translation>
</message>
<message>
<location line="+1"/>
<source>Quit application</source>
<translation>結束應用程式</translation>
</message>
<message>
<location line="+7"/>
<source>Show information about Bitcoin</source>
<translation>顯示位元幣相關資訊</translation>
</message>
<message>
<location line="+2"/>
<source>About &Qt</source>
<translation>關於 &Qt</translation>
</message>
<message>
<location line="+1"/>
<source>Show information about Qt</source>
<translation>顯示有關於 Qt 的資訊</translation>
</message>
<message>
<location line="+2"/>
<source>&Options...</source>
<translation>選項...</translation>
</message>
<message>
<location line="+9"/>
<source>&Encrypt Wallet...</source>
<translation>錢包加密...</translation>
</message>
<message>
<location line="+3"/>
<source>&Backup Wallet...</source>
<translation>錢包備份...</translation>
</message>
<message>
<location line="+2"/>
<source>&Change Passphrase...</source>
<translation>密碼變更...</translation>
</message>
<message>
<location line="+251"/>
<source>Importing blocks from disk...</source>
<translation>從磁碟匯入區塊中...</translation>
</message>
<message>
<location line="+3"/>
<source>Reindexing blocks on disk...</source>
<translation>重建磁碟區塊索引中...</translation>
</message>
<message>
<location line="-319"/>
<source>Send coins to a Bitcoin address</source>
<translation>付錢到位元幣位址</translation>
</message>
<message>
<location line="+52"/>
<source>Modify configuration options for Bitcoin</source>
<translation>修改位元幣的設定選項</translation>
</message>
<message>
<location line="+12"/>
<source>Backup wallet to another location</source>
<translation>將錢包備份到其它地方</translation>
</message>
<message>
<location line="+2"/>
<source>Change the passphrase used for wallet encryption</source>
<translation>變更錢包加密用的密碼</translation>
</message>
<message>
<location line="+6"/>
<source>&Debug window</source>
<translation>除錯視窗</translation>
</message>
<message>
<location line="+1"/>
<source>Open debugging and diagnostic console</source>
<translation>開啓除錯與診斷主控台</translation>
</message>
<message>
<location line="-4"/>
<source>&Verify message...</source>
<translation>驗證訊息...</translation>
</message>
<message>
<location line="-183"/>
<location line="+6"/>
<location line="+508"/>
<source>Bitcoin</source>
<translation>位元幣</translation>
</message>
<message>
<location line="-514"/>
<location line="+6"/>
<source>Wallet</source>
<translation>錢包</translation>
</message>
<message>
<location line="+107"/>
<source>&Send</source>
<translation>付出</translation>
</message>
<message>
<location line="+7"/>
<source>&Receive</source>
<translation>收受</translation>
</message>
<message>
<location line="+14"/>
<source>&Addresses</source>
<translation>位址</translation>
</message>
<message>
<location line="+23"/>
<location line="+2"/>
<source>&About Bitcoin</source>
<translation>關於位元幣</translation>
</message>
<message>
<location line="+10"/>
<location line="+2"/>
<source>&Show / Hide</source>
<translation>顯示或隱藏</translation>
</message>
<message>
<location line="+1"/>
<source>Show or hide the main Window</source>
<translation>顯示或隱藏主視窗</translation>
</message>
<message>
<location line="+3"/>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>將屬於你的錢包的密鑰加密</translation>
</message>
<message>
<location line="+7"/>
<source>Sign messages with your Bitcoin addresses to prove you own them</source>
<translation>用位元幣位址簽署訊息來證明那是你的</translation>
</message>
<message>
<location line="+2"/>
<source>Verify messages to ensure they were signed with specified Bitcoin addresses</source>
<translation>驗證訊息來確認是用指定的位元幣位址簽署的</translation>
</message>
<message>
<location line="+28"/>
<source>&File</source>
<translation>檔案</translation>
</message>
<message>
<location line="+7"/>
<source>&Settings</source>
<translation>設定</translation>
</message>
<message>
<location line="+6"/>
<source>&Help</source>
<translation>求助</translation>
</message>
<message>
<location line="+9"/>
<source>Tabs toolbar</source>
<translation>分頁工具列</translation>
</message>
<message>
<location line="-228"/>
<location line="+288"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
<message>
<location line="-5"/>
<location line="+5"/>
<source>Bitcoin client</source>
<translation>位元幣客戶端軟體</translation>
</message>
<message numerus="yes">
<location line="+121"/>
<source>%n active connection(s) to Bitcoin network</source>
<translation><numerusform>與位元幣網路有 %n 個連線在使用中</numerusform></translation>
</message>
<message>
<location line="+22"/>
<source>No block source available...</source>
<translation>目前沒有區塊來源...</translation>
</message>
<message>
<location line="+12"/>
<source>Processed %1 of %2 (estimated) blocks of transaction history.</source>
<translation>已處理了估計全部 %2 個中的 %1 個區塊的交易紀錄.</translation>
</message>
<message>
<location line="+4"/>
<source>Processed %1 blocks of transaction history.</source>
<translation>已處理了 %1 個區塊的交易紀錄.</translation>
</message>
<message numerus="yes">
<location line="+20"/>
<source>%n hour(s)</source>
<translation><numerusform>%n 個小時</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n day(s)</source>
<translation><numerusform>%n 天</numerusform></translation>
</message>
<message numerus="yes">
<location line="+4"/>
<source>%n week(s)</source>
<translation><numerusform>%n 個星期</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>%1 behind</source>
<translation>落後 %1</translation>
</message>
<message>
<location line="+14"/>
<source>Last received block was generated %1 ago.</source>
<translation>最近收到的區塊是在 %1 之前生產出來.</translation>
</message>
<message>
<location line="+2"/>
<source>Transactions after this will not yet be visible.</source>
<translation>會看不見在這之後的交易.</translation>
</message>
<message>
<location line="+22"/>
<source>Error</source>
<translation>錯誤</translation>
</message>
<message>
<location line="+3"/>
<source>Warning</source>
<translation>警告</translation>
</message>
<message>
<location line="+3"/>
<source>Information</source>
<translation>資訊</translation>
</message>
<message>
<location line="+70"/>
<source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source>
<translation>這筆交易的資料大小超過限制了. 你還是可以付出 %1 的費用來傳送, 這筆費用會付給處理你的交易的節點, 並幫助維持整個網路. 你願意支付這項費用嗎?</translation>
</message>
<message>
<location line="-140"/>
<source>Up to date</source>
<translation>最新狀態</translation>
</message>
<message>
<location line="+31"/>
<source>Catching up...</source>
<translation>進度追趕中...</translation>
</message>
<message>
<location line="+113"/>
<source>Confirm transaction fee</source>
<translation>確認交易手續費</translation>
</message>
<message>
<location line="+8"/>
<source>Sent transaction</source>
<translation>付款交易</translation>
</message>
<message>
<location line="+0"/>
<source>Incoming transaction</source>
<translation>收款交易</translation>
</message>
<message>
<location line="+1"/>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>日期: %1
金額: %2
類別: %3
位址: %4</translation>
</message>
<message>
<location line="+33"/>
<location line="+23"/>
<source>URI handling</source>
<translation>URI 處理</translation>
</message>
<message>
<location line="-23"/>
<location line="+23"/>
<source>URI can not be parsed! This can be caused by an invalid Bitcoin address or malformed URI parameters.</source>
<translation>無法解析 URI! 也許位元幣位址無效或 URI 參數有誤.</translation>
</message>
<message>
<location line="+17"/>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>錢包<b>已加密</b>並且正<b>解鎖中</b></translation>
</message>
<message>
<location line="+8"/>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>錢包<b>已加密</b>並且正<b>上鎖中</b></translation>
</message>
<message>
<location filename="../bitcoin.cpp" line="+110"/>
<source>A fatal error occurred. Bitcoin can no longer continue safely and will quit.</source>
<translation>發生了致命的錯誤. 位元幣程式無法再繼續安全執行, 只好結束.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<location filename="../clientmodel.cpp" line="+105"/>
<source>Network Alert</source>
<translation>網路警報</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<location filename="../forms/editaddressdialog.ui" line="+14"/>
<source>Edit Address</source>
<translation>編輯位址</translation>
</message>
<message>
<location line="+11"/>
<source>&Label</source>
<translation>標記</translation>
</message>
<message>
<location line="+10"/>
<source>The label associated with this address book entry</source>
<translation>與這個位址簿項目關聯的標記</translation>
</message>
<message>
<location line="+7"/>
<source>&Address</source>
<translation>位址</translation>
</message>
<message>
<location line="+10"/>
<source>The address associated with this address book entry. This can only be modified for sending addresses.</source>
<translation>與這個位址簿項目關聯的位址. 付款位址才能被更改.</translation>
</message>
<message>
<location filename="../editaddressdialog.cpp" line="+21"/>
<source>New receiving address</source>
<translation>新收款位址</translation>
</message>
<message>
<location line="+4"/>
<source>New sending address</source>
<translation>新增付款位址</translation>
</message>
<message>
<location line="+3"/>
<source>Edit receiving address</source>
<translation>編輯收款位址</translation>
</message>
<message>
<location line="+4"/>
<source>Edit sending address</source>
<translation>編輯付款位址</translation>
</message>
<message>
<location line="+76"/>
<source>The entered address "%1" is already in the address book.</source>
<translation>輸入的位址"%1"已存在於位址簿中.</translation>
</message>
<message>
<location line="-5"/>
<source>The entered address "%1" is not a valid Bitcoin address.</source>
<translation>輸入的位址 "%1" 並不是有效的位元幣位址.</translation>
</message>
<message>
<location line="+10"/>
<source>Could not unlock wallet.</source>
<translation>無法將錢包解鎖.</translation>
</message>
<message>
<location line="+5"/>
<source>New key generation failed.</source>
<translation>新密鑰產生失敗.</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<location filename="../intro.cpp" line="+61"/>
<source>A new data directory will be created.</source>
<translation>將會建立新的資料目錄.</translation>
</message>
<message>
<location line="+22"/>
<source>name</source>
<translation>名稱</translation>
</message>
<message>
<location line="+2"/>
<source>Directory already exists. Add %1 if you intend to create a new directory here.</source>
<translation>目錄已經存在了. 如果你要在裡面建立新目錄的話, 請加上 %1.</translation>
</message>
<message>
<location line="+3"/>
<source>Path already exists, and is not a directory.</source>
<translation>已經存在該路徑了, 並且不是一個目錄.</translation>
</message>
<message>
<location line="+7"/>
<source>Cannot create data directory here.</source>
<translation>無法在這裡新增資料目錄</translation>
</message>
</context>
<context>
<name>GUIUtil::HelpMessageBox</name>
<message>
<location filename="../guiutil.cpp" line="+517"/>
<location line="+13"/>
<source>Bitcoin-Qt</source>
<translation>位元幣-Qt</translation>
</message>
<message>
<location line="-13"/>
<source>version</source>
<translation>版本</translation>
</message>
<message>
<location line="+2"/>
<source>Usage:</source>
<translation>用法:</translation>
</message>
<message>
<location line="+1"/>
<source>command-line options</source>
<translation>命令列選項</translation>
</message>
<message>
<location line="+4"/>
<source>UI options</source>
<translation>使用界面選項</translation>
</message>
<message>
<location line="+1"/>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>設定語言, 比如說 "de_DE" (預設: 系統語系)</translation>
</message>
<message>
<location line="+1"/>
<source>Start minimized</source>
<translation>啓動時最小化
</translation>
</message>
<message>
<location line="+1"/>
<source>Show splash screen on startup (default: 1)</source>
<translation>顯示啓動畫面 (預設: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Choose data directory on startup (default: 0)</source>
<translation>啓動時選擇資料目錄 (預設值: 0)</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<location filename="../forms/intro.ui" line="+14"/>
<source>Welcome</source>
<translation>歡迎</translation>
</message>
<message>
<location line="+9"/>
<source>Welcome to Bitcoin-Qt.</source>
<translation>歡迎使用"位元幣-Qt"</translation>
</message>
<message>
<location line="+26"/>
<source>As this is the first time the program is launched, you can choose where Bitcoin-Qt will store its data.</source>
<translation>由於這是程式第一次啓動, 你可以選擇"位元幣-Qt"儲存資料的地方.</translation>
</message>
<message>
<location line="+10"/>
<source>Bitcoin-Qt will download and store a copy of the Bitcoin block chain. At least %1GB of data will be stored in this directory, and it will grow over time. The wallet will also be stored in this directory.</source>
<translation>位元幣-Qt 會下載並儲存一份位元幣區塊鏈結的拷貝. 至少有 %1GB 的資料會儲存到這個目錄中, 並且還會持續增長. 另外錢包資料也會儲存在這個目錄.</translation>
</message>
<message>
<location line="+10"/>
<source>Use the default data directory</source>
<translation>用預設的資料目錄</translation>
</message>
<message>
<location line="+7"/>
<source>Use a custom data directory:</source>
<translation>用自定的資料目錄:</translation>
</message>
<message>
<location filename="../intro.cpp" line="+100"/>
<source>Error</source>
<translation>錯誤</translation>
</message>
<message>
<location line="+9"/>
<source>GB of free space available</source>
<translation>GB 可用空間</translation>
</message>
<message>
<location line="+3"/>
<source>(of %1GB needed)</source>
<translation>(需要 %1GB)</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<location filename="../forms/optionsdialog.ui" line="+14"/>
<source>Options</source>
<translation>選項</translation>
</message>
<message>
<location line="+16"/>
<source>&Main</source>
<translation>主要</translation>
</message>
<message>
<location line="+6"/>
<source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source>
<translation>非必要的交易手續費, 以 kB 為計費單位, 且有助於縮短你的交易處理時間. 大部份交易資料的大小是 1 kB.</translation>
</message>
<message>
<location line="+15"/>
<source>Pay transaction &fee</source>
<translation>付交易手續費</translation>
</message>
<message>
<location line="+31"/>
<source>Automatically start Bitcoin after logging in to the system.</source>
<translation>在登入系統後自動啓動位元幣.</translation>
</message>
<message>
<location line="+3"/>
<source>&Start Bitcoin on system login</source>
<translation>系統登入時啟動位元幣</translation>
</message>
<message>
<location line="+35"/>
<source>Reset all client options to default.</source>
<translation>回復所有客戶端軟體選項成預設值.</translation>
</message>
<message>
<location line="+3"/>
<source>&Reset Options</source>
<translation>選項回復</translation>
</message>
<message>
<location line="+13"/>
<source>&Network</source>
<translation>網路</translation>
</message>
<message>
<location line="+6"/>
<source>Automatically open the Bitcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>自動在路由器上開啟 Bitcoin 的客戶端通訊埠. 只有在你的路由器支援 UPnP 且開啟時才有作用.</translation>
</message>
<message>
<location line="+3"/>
<source>Map port using &UPnP</source>
<translation>用 &UPnP 設定通訊埠對應</translation>
</message>
<message>
<location line="+7"/>
<source>Connect to the Bitcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source>
<translation>透過 SOCKS 代理伺服器連線至位元幣網路 (比如說要透過 Tor 連線).</translation>
</message>
<message>
<location line="+3"/>
<source>&Connect through SOCKS proxy:</source>
<translation>透過 SOCKS 代理伺服器連線:</translation>
</message>
<message>
<location line="+9"/>
<source>Proxy &IP:</source>
<translation>代理伺服器位址:</translation>
</message>
<message>
<location line="+19"/>
<source>IP address of the proxy (e.g. 127.0.0.1)</source>
<translation>代理伺服器的網際網路位址 (比如說 127.0.0.1)</translation>
</message>
<message>
<location line="+7"/>
<source>&Port:</source>
<translation>通訊埠:</translation>
</message>
<message>
<location line="+19"/>
<source>Port of the proxy (e.g. 9050)</source>
<translation>代理伺服器的通訊埠 (比如說 9050)</translation>
</message>
<message>
<location line="+7"/>
<source>SOCKS &Version:</source>
<translation>SOCKS 協定版本:</translation>
</message>
<message>
<location line="+13"/>
<source>SOCKS version of the proxy (e.g. 5)</source>
<translation>代理伺服器的 SOCKS 協定版本 (比如說 5)</translation>
</message>
<message>
<location line="+36"/>
<source>&Window</source>
<translation>視窗</translation>
</message>
<message>
<location line="+6"/>
<source>Show only a tray icon after minimizing the window.</source>
<translation>最小化視窗後只在通知區域顯示圖示</translation>
</message>
<message>
<location line="+3"/>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>最小化至通知區域而非工作列</translation>
</message>
<message>
<location line="+7"/>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>當視窗關閉時將其最小化, 而非結束應用程式. 當勾選這個選項時, 應用程式只能用選單中的結束來停止執行.</translation>
</message>
<message>
<location line="+3"/>
<source>M&inimize on close</source>
<translation>關閉時最小化</translation>
</message>
<message>
<location line="+21"/>
<source>&Display</source>
<translation>顯示</translation>
</message>
<message>
<location line="+8"/>
<source>User Interface &language:</source>
<translation>使用界面語言</translation>
</message>
<message>
<location line="+13"/>
<source>The user interface language can be set here. This setting will take effect after restarting Bitcoin.</source>
<translation>可以在這裡設定使用者介面的語言. 這個設定在位元幣程式重啓後才會生效.</translation>
</message>
<message>
<location line="+11"/>
<source>&Unit to show amounts in:</source>
<translation>金額顯示單位:</translation>
</message>
<message>
<location line="+13"/>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>選擇操作界面與付錢時預設顯示的細分單位.</translation>
</message>
<message>
<location line="+9"/>
<source>Whether to show Bitcoin addresses in the transaction list or not.</source>
<translation>是否要在交易列表中顯示位元幣位址.</translation>
</message>
<message>
<location line="+3"/>
<source>&Display addresses in transaction list</source>
<translation>在交易列表顯示位址</translation>
</message>
<message>
<location line="+71"/>
<source>&OK</source>
<translation>好</translation>
</message>
<message>
<location line="+7"/>
<source>&Cancel</source>
<translation>取消</translation>
</message>
<message>
<location line="+10"/>
<source>&Apply</source>
<translation>套用</translation>
</message>
<message>
<location filename="../optionsdialog.cpp" line="+54"/>
<source>default</source>
<translation>預設</translation>
</message>
<message>
<location line="+130"/>
<source>Confirm options reset</source>
<translation>確認回復選項</translation>
</message>
<message>
<location line="+1"/>
<source>Some settings may require a client restart to take effect.</source>
<translation>有些設定可能需要重新啓動客戶端軟體才會生效.</translation>
</message>
<message>
<location line="+0"/>
<source>Do you want to proceed?</source>
<translation>你想要就做下去嗎?</translation>
</message>
<message>
<location line="+42"/>
<location line="+9"/>
<source>Warning</source>
<translation>警告</translation>
</message>
<message>
<location line="-9"/>
<location line="+9"/>
<source>This setting will take effect after restarting Bitcoin.</source>
<translation>這個設定會在位元幣程式重啓後生效.</translation>
</message>
<message>
<location line="+29"/>
<source>The supplied proxy address is invalid.</source>
<translation>提供的代理伺服器位址無效</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<location filename="../forms/overviewpage.ui" line="+14"/>
<source>Form</source>
<translation>表單</translation>
</message>
<message>
<location line="+50"/>
<location line="+202"/>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Bitcoin network after a connection is established, but this process has not completed yet.</source>
<translation>顯示的資訊可能是過期的. 與位元幣網路的連線建立後, 你的錢包會自動和網路同步, 但這個步驟還沒完成.</translation>
</message>
<message>
<location line="-131"/>
<source>Unconfirmed:</source>
<translation>未確認金額:</translation>
</message>
<message>
<location line="-78"/>
<source>Wallet</source>
<translation>錢包</translation>
</message>
<message>
<location line="+49"/>
<source>Confirmed:</source>
<translation>已確認金額:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current spendable balance</source>
<translation>目前可用餘額</translation>
</message>
<message>
<location line="+29"/>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation>尚未確認的交易的總金額, 可用餘額不包含此金額</translation>
</message>
<message>
<location line="+13"/>
<source>Immature:</source>
<translation>未熟成</translation>
</message>
<message>
<location line="+13"/>
<source>Mined balance that has not yet matured</source>
<translation>尚未熟成的開採金額</translation>
</message>
<message>
<location line="+13"/>
<source>Total:</source>
<translation>總金額:</translation>
</message>
<message>
<location line="+16"/>
<source>Your current total balance</source>
<translation>目前全部餘額</translation>
</message>
<message>
<location line="+53"/>
<source><b>Recent transactions</b></source>
<translation><b>最近交易</b></translation>
</message>
<message>
<location filename="../overviewpage.cpp" line="+116"/>
<location line="+1"/>
<source>out of sync</source>
<translation>沒同步</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<location filename="../paymentserver.cpp" line="+108"/>
<source>Cannot start bitcoin: click-to-pay handler</source>
<translation>無法啟動 bitcoin 隨按隨付處理器</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<location filename="../bitcoin.cpp" line="+92"/>
<location filename="../intro.cpp" line="-32"/>
<source>Bitcoin</source>
<translation>位元幣</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Specified data directory "%1" does not exist.</source>
<translation>錯誤: 不存在指定的資料目錄 "%1".</translation>
</message>
<message>
<location filename="../intro.cpp" line="+1"/>
<source>Error: Specified data directory "%1" can not be created.</source>
<translation>錯誤: 無法新增指定的資料目錄 "%1".</translation>
</message>
</context>
<context>
<name>QRCodeDialog</name>
<message>
<location filename="../forms/qrcodedialog.ui" line="+14"/>
<source>QR Code Dialog</source>
<translation>QR 條碼對話視窗</translation>
</message>
<message>
<location line="+59"/>
<source>Request Payment</source>
<translation>付款單</translation>
</message>
<message>
<location line="+56"/>
<source>Amount:</source>
<translation>金額:</translation>
</message>
<message>
<location line="-44"/>
<source>Label:</source>
<translation>標記:</translation>
</message>
<message>
<location line="+19"/>
<source>Message:</source>
<translation>訊息:</translation>
</message>
<message>
<location line="+71"/>
<source>&Save As...</source>
<translation>儲存為...</translation>
</message>
<message>
<location filename="../qrcodedialog.cpp" line="+64"/>
<source>Error encoding URI into QR Code.</source>
<translation>將 URI 編碼成 QR 條碼失敗</translation>
</message>
<message>
<location line="+40"/>
<source>The entered amount is invalid, please check.</source>
<translation>輸入的金額無效, 請檢查看看.</translation>
</message>
<message>
<location line="+23"/>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>造出的網址太長了,請把標籤或訊息的文字縮短再試看看.</translation>
</message>
<message>
<location line="+25"/>
<source>Save QR Code</source>
<translation>儲存 QR 條碼</translation>
</message>
<message>
<location line="+0"/>
<source>PNG Images (*.png)</source>
<translation>PNG 圖檔 (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<location filename="../forms/rpcconsole.ui" line="+46"/>
<source>Client name</source>
<translation>客戶端軟體名稱</translation>
</message>
<message>
<location line="+10"/>
<location line="+23"/>
<location line="+26"/>
<location line="+23"/>
<location line="+23"/>
<location line="+36"/>
<location line="+53"/>
<location line="+23"/>
<location line="+23"/>
<location filename="../rpcconsole.cpp" line="+345"/>
<source>N/A</source>
<translation>無</translation>
</message>
<message>
<location line="-217"/>
<source>Client version</source>
<translation>客戶端軟體版本</translation>
</message>
<message>
<location line="-45"/>
<source>&Information</source>
<translation>資訊</translation>
</message>
<message>
<location line="+68"/>
<source>Using OpenSSL version</source>
<translation>使用 OpenSSL 版本</translation>
</message>
<message>
<location line="+49"/>
<source>Startup time</source>
<translation>啓動時間</translation>
</message>
<message>
<location line="+29"/>
<source>Network</source>
<translation>網路</translation>
</message>
<message>
<location line="+7"/>
<source>Number of connections</source>
<translation>連線數</translation>
</message>
<message>
<location line="+23"/>
<source>On testnet</source>
<translation>位於測試網路</translation>
</message>
<message>
<location line="+23"/>
<source>Block chain</source>
<translation>區塊鎖鏈</translation>
</message>
<message>
<location line="+7"/>
<source>Current number of blocks</source>
<translation>目前區塊數</translation>
</message>
<message>
<location line="+23"/>
<source>Estimated total blocks</source>
<translation>估算總區塊數</translation>
</message>
<message>
<location line="+23"/>
<source>Last block time</source>
<translation>最近區塊時間</translation>
</message>
<message>
<location line="+52"/>
<source>&Open</source>
<translation>開啓</translation>
</message>
<message>
<location line="+16"/>
<source>Command-line options</source>
<translation>命令列選項</translation>
</message>
<message>
<location line="+7"/>
<source>Show the Bitcoin-Qt help message to get a list with possible Bitcoin command-line options.</source>
<translation>顯示"位元幣-Qt"的求助訊息, 來取得可用的命令列選項列表.</translation>
</message>
<message>
<location line="+3"/>
<source>&Show</source>
<translation>顯示</translation>
</message>
<message>
<location line="+24"/>
<source>&Console</source>
<translation>主控台</translation>
</message>
<message>
<location line="-260"/>
<source>Build date</source>
<translation>建置日期</translation>
</message>
<message>
<location line="-104"/>
<source>Bitcoin - Debug window</source>
<translation>位元幣 - 除錯視窗</translation>
</message>
<message>
<location line="+25"/>
<source>Bitcoin Core</source>
<translation>位元幣核心</translation>
</message>
<message>
<location line="+279"/>
<source>Debug log file</source>
<translation>除錯紀錄檔</translation>
</message>
<message>
<location line="+7"/>
<source>Open the Bitcoin debug log file from the current data directory. This can take a few seconds for large log files.</source>
<translation>從目前的資料目錄下開啓位元幣的除錯紀錄檔. 當紀錄檔很大時可能要花好幾秒的時間.</translation>
</message>
<message>
<location line="+102"/>
<source>Clear console</source>
<translation>清主控台</translation>
</message>
<message>
<location filename="../rpcconsole.cpp" line="-30"/>
<source>Welcome to the Bitcoin RPC console.</source>
<translation>歡迎使用位元幣 RPC 主控台.</translation>
</message>
<message>
<location line="+1"/>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>請用上下游標鍵來瀏覽歷史指令, 且可用 <b>Ctrl-L</b> 來清理畫面.</translation>
</message>
<message>
<location line="+1"/>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>請打 <b>help</b> 來看可用指令的簡介.</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<location filename="../forms/sendcoinsdialog.ui" line="+14"/>
<location filename="../sendcoinsdialog.cpp" line="+128"/>
<location line="+5"/>
<location line="+5"/>
<location line="+5"/>
<location line="+6"/>
<location line="+5"/>
<location line="+5"/>
<source>Send Coins</source>
<translation>付錢</translation>
</message>
<message>
<location line="+50"/>
<source>Send to multiple recipients at once</source>
<translation>一次付給多個人</translation>
</message>
<message>
<location line="+3"/>
<source>Add &Recipient</source>
<translation>加收款人</translation>
</message>
<message>
<location line="+20"/>
<source>Remove all transaction fields</source>
<translation>移除所有交易欄位</translation>
</message>
<message>
<location line="+3"/>
<source>Clear &All</source>
<translation>全部清掉</translation>
</message>
<message>
<location line="+22"/>
<source>Balance:</source>
<translation>餘額:</translation>
</message>
<message>
<location line="+10"/>
<source>123.456 BTC</source>
<translation>123.456 BTC</translation>
</message>
<message>
<location line="+31"/>
<source>Confirm the send action</source>
<translation>確認付款動作</translation>
</message>
<message>
<location line="+3"/>
<source>S&end</source>
<translation>付出</translation>
</message>
<message>
<location filename="../sendcoinsdialog.cpp" line="-62"/>
<location line="+2"/>
<source><b>%1</b> to %2 (%3)</source>
<translation><b>%1</b> 給 %2 (%3)</translation>
</message>
<message>
<location line="+6"/>
<source>Confirm send coins</source>
<translation>確認要付錢</translation>
</message>
<message>
<location line="+1"/>
<source>Are you sure you want to send %1?</source>
<translation>確定要付出 %1 嗎?</translation>
</message>
<message>
<location line="+0"/>
<source> and </source>
<translation>和</translation>
</message>
<message>
<location line="+23"/>
<source>The recipient address is not valid, please recheck.</source>
<translation>無效的收款位址, 請再檢查看看.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount to pay must be larger than 0.</source>
<translation>付款金額必須大於 0.</translation>
</message>
<message>
<location line="+5"/>
<source>The amount exceeds your balance.</source>
<translation>金額超過餘額了.</translation>
</message>
<message>
<location line="+5"/>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>包含 %1 的交易手續費後, 總金額超過你的餘額了.</translation>
</message>
<message>
<location line="+6"/>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>發現有重複的位址. 每個付款動作中, 只能付給個別的位址一次.</translation>
</message>
<message>
<location line="+5"/>
<source>Error: Transaction creation failed!</source>
<translation>錯誤: 交易產生失敗!</translation>
</message>
<message>
<location line="+5"/>
<source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>錯誤: 交易被拒絕. 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<location filename="../forms/sendcoinsentry.ui" line="+14"/>
<source>Form</source>
<translation>表單</translation>
</message>
<message>
<location line="+15"/>
<source>A&mount:</source>
<translation>金額:</translation>
</message>
<message>
<location line="+13"/>
<source>Pay &To:</source>
<translation>付給:</translation>
</message>
<message>
<location line="+34"/>
<source>The address to send the payment to (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>付款的目標位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+60"/>
<location filename="../sendcoinsentry.cpp" line="+26"/>
<source>Enter a label for this address to add it to your address book</source>
<translation>輸入一個標記給這個位址, 並加到位址簿中</translation>
</message>
<message>
<location line="-78"/>
<source>&Label:</source>
<translation>標記:</translation>
</message>
<message>
<location line="+28"/>
<source>Choose address from address book</source>
<translation>從位址簿中選一個位址</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="+7"/>
<source>Paste address from clipboard</source>
<translation>從剪貼簿貼上位址</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+7"/>
<source>Remove this recipient</source>
<translation>去掉這個收款人</translation>
</message>
<message>
<location filename="../sendcoinsentry.cpp" line="+1"/>
<source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<location filename="../forms/signverifymessagedialog.ui" line="+14"/>
<source>Signatures - Sign / Verify a Message</source>
<translation>簽章 - 簽署或驗證訊息</translation>
</message>
<message>
<location line="+13"/>
<source>&Sign Message</source>
<translation>訊息簽署</translation>
</message>
<message>
<location line="+6"/>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>你可以用自己的位址來簽署訊息, 以證明你對它的所有權. 但是請小心, 不要簽署語意含糊不清的內容, 因為釣魚式詐騙可能會用騙你簽署的手法來冒充是你. 只有在語句中的細節你都同意時才簽署.</translation>
</message>
<message>
<location line="+18"/>
<source>The address to sign the message with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>用來簽署訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+10"/>
<location line="+213"/>
<source>Choose an address from the address book</source>
<translation>從位址簿選一個位址</translation>
</message>
<message>
<location line="-203"/>
<location line="+213"/>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<location line="-203"/>
<source>Paste address from clipboard</source>
<translation>從剪貼簿貼上位址</translation>
</message>
<message>
<location line="+10"/>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<location line="+12"/>
<source>Enter the message you want to sign here</source>
<translation>在這裡輸入你想簽署的訊息</translation>
</message>
<message>
<location line="+7"/>
<source>Signature</source>
<translation>簽章</translation>
</message>
<message>
<location line="+27"/>
<source>Copy the current signature to the system clipboard</source>
<translation>複製目前的簽章到系統剪貼簿</translation>
</message>
<message>
<location line="+21"/>
<source>Sign the message to prove you own this Bitcoin address</source>
<translation>簽署訊息是用來證明這個位元幣位址是你的</translation>
</message>
<message>
<location line="+3"/>
<source>Sign &Message</source>
<translation>訊息簽署</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all sign message fields</source>
<translation>重置所有訊息簽署欄位</translation>
</message>
<message>
<location line="+3"/>
<location line="+146"/>
<source>Clear &All</source>
<translation>全部清掉</translation>
</message>
<message>
<location line="-87"/>
<source>&Verify Message</source>
<translation>訊息驗證</translation>
</message>
<message>
<location line="+6"/>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>請在下面輸入簽署的位址, 訊息(請確認完整複製了所包含的換行, 空格, 跳位符號等等), 與簽章, 以驗證該訊息. 請小心, 除了訊息內容外, 不要對簽章本身過度解讀, 以避免被用"中間人攻擊法"詐騙.</translation>
</message>
<message>
<location line="+21"/>
<source>The address the message was signed with (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>簽署該訊息的位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="+40"/>
<source>Verify the message to ensure it was signed with the specified Bitcoin address</source>
<translation>驗證訊息是用來確認訊息是用指定的位元幣位址簽署的</translation>
</message>
<message>
<location line="+3"/>
<source>Verify &Message</source>
<translation>訊息驗證</translation>
</message>
<message>
<location line="+14"/>
<source>Reset all verify message fields</source>
<translation>重置所有訊息驗證欄位</translation>
</message>
<message>
<location filename="../signverifymessagedialog.cpp" line="+27"/>
<location line="+3"/>
<source>Enter a Bitcoin address (e.g. 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</source>
<translation>輸入位元幣位址 (比如說 1NS17iag9jJgTHD1VXjvLCEnZuQ3rJDE9L)</translation>
</message>
<message>
<location line="-2"/>
<source>Click "Sign Message" to generate signature</source>
<translation>按"訊息簽署"來產生簽章</translation>
</message>
<message>
<location line="+3"/>
<source>Enter Bitcoin signature</source>
<translation>輸入位元幣簽章</translation>
</message>
<message>
<location line="+82"/>
<location line="+81"/>
<source>The entered address is invalid.</source>
<translation>輸入的位址無效.</translation>
</message>
<message>
<location line="-81"/>
<location line="+8"/>
<location line="+73"/>
<location line="+8"/>
<source>Please check the address and try again.</source>
<translation>請檢查位址是否正確後再試一次.</translation>
</message>
<message>
<location line="-81"/>
<location line="+81"/>
<source>The entered address does not refer to a key.</source>
<translation>輸入的位址沒有指到任何密鑰.</translation>
</message>
<message>
<location line="-73"/>
<source>Wallet unlock was cancelled.</source>
<translation>錢包解鎖已取消.</translation>
</message>
<message>
<location line="+8"/>
<source>Private key for the entered address is not available.</source>
<translation>沒有所輸入位址的密鑰.</translation>
</message>
<message>
<location line="+12"/>
<source>Message signing failed.</source>
<translation>訊息簽署失敗.</translation>
</message>
<message>
<location line="+5"/>
<source>Message signed.</source>
<translation>訊息已簽署.</translation>
</message>
<message>
<location line="+59"/>
<source>The signature could not be decoded.</source>
<translation>無法將這個簽章解碼.</translation>
</message>
<message>
<location line="+0"/>
<location line="+13"/>
<source>Please check the signature and try again.</source>
<translation>請檢查簽章是否正確後再試一次.</translation>
</message>
<message>
<location line="+0"/>
<source>The signature did not match the message digest.</source>
<translation>這個簽章與訊息的數位摘要不符.</translation>
</message>
<message>
<location line="+7"/>
<source>Message verification failed.</source>
<translation>訊息驗證失敗.</translation>
</message>
<message>
<location line="+5"/>
<source>Message verified.</source>
<translation>訊息已驗證.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<location filename="../splashscreen.cpp" line="+22"/>
<source>The Bitcoin developers</source>
<translation>位元幣開發人員</translation>
</message>
<message>
<location line="+1"/>
<source>[testnet]</source>
<translation>[testnet]</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<location filename="../transactiondesc.cpp" line="+20"/>
<source>Open until %1</source>
<translation>在 %1 前未定</translation>
</message>
<message>
<location line="+6"/>
<source>%1/offline</source>
<translation>%1/離線中</translation>
</message>
<message>
<location line="+2"/>
<source>%1/unconfirmed</source>
<translation>%1/未確認</translation>
</message>
<message>
<location line="+2"/>
<source>%1 confirmations</source>
<translation>經確認 %1 次</translation>
</message>
<message>
<location line="+18"/>
<source>Status</source>
<translation>狀態</translation>
</message>
<message numerus="yes">
<location line="+7"/>
<source>, broadcast through %n node(s)</source>
<translation><numerusform>, 已公告至 %n 個節點</numerusform></translation>
</message>
<message>
<location line="+4"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location line="+7"/>
<source>Source</source>
<translation>來源</translation>
</message>
<message>
<location line="+0"/>
<source>Generated</source>
<translation>生產出</translation>
</message>
<message>
<location line="+5"/>
<location line="+17"/>
<source>From</source>
<translation>來處</translation>
</message>
<message>
<location line="+1"/>
<location line="+22"/>
<location line="+58"/>
<source>To</source>
<translation>目的</translation>
</message>
<message>
<location line="-77"/>
<location line="+2"/>
<source>own address</source>
<translation>自己的位址</translation>
</message>
<message>
<location line="-2"/>
<source>label</source>
<translation>標籤</translation>
</message>
<message>
<location line="+37"/>
<location line="+12"/>
<location line="+45"/>
<location line="+17"/>
<location line="+30"/>
<source>Credit</source>
<translation>入帳</translation>
</message>
<message numerus="yes">
<location line="-102"/>
<source>matures in %n more block(s)</source>
<translation><numerusform>將在 %n 個區塊產出後熟成</numerusform></translation>
</message>
<message>
<location line="+2"/>
<source>not accepted</source>
<translation>不被接受</translation>
</message>
<message>
<location line="+44"/>
<location line="+8"/>
<location line="+15"/>
<location line="+30"/>
<source>Debit</source>
<translation>出帳</translation>
</message>
<message>
<location line="-39"/>
<source>Transaction fee</source>
<translation>交易手續費</translation>
</message>
<message>
<location line="+16"/>
<source>Net amount</source>
<translation>淨額</translation>
</message>
<message>
<location line="+6"/>
<source>Message</source>
<translation>訊息</translation>
</message>
<message>
<location line="+2"/>
<source>Comment</source>
<translation>附註</translation>
</message>
<message>
<location line="+2"/>
<source>Transaction ID</source>
<translation>交易識別碼</translation>
</message>
<message>
<location line="+3"/>
<source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to "not accepted" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source>
<translation>生產出來的錢要再等 120 個區塊熟成之後, 才能夠花用. 當你產出區塊時, 它會被公布到網路上, 以被串連至區塊鎖鏈. 如果串連失敗了, 它的狀態就會變成"不被接受", 且不能被花用. 當你產出區塊的幾秒鐘內, 也有其他節點產出區塊的話, 有時候就會發生這種情形.</translation>
</message>
<message>
<location line="+7"/>
<source>Debug information</source>
<translation>除錯資訊</translation>
</message>
<message>
<location line="+8"/>
<source>Transaction</source>
<translation>交易</translation>
</message>
<message>
<location line="+3"/>
<source>Inputs</source>
<translation>輸入</translation>
</message>
<message>
<location line="+23"/>
<source>Amount</source>
<translation>金額</translation>
</message>
<message>
<location line="+1"/>
<source>true</source>
<translation>是</translation>
</message>
<message>
<location line="+0"/>
<source>false</source>
<translation>否</translation>
</message>
<message>
<location line="-209"/>
<source>, has not been successfully broadcast yet</source>
<translation>, 尚未成功公告出去</translation>
</message>
<message numerus="yes">
<location line="-35"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation>
</message>
<message>
<location line="+70"/>
<source>unknown</source>
<translation>未知</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<location filename="../forms/transactiondescdialog.ui" line="+14"/>
<source>Transaction details</source>
<translation>交易明細</translation>
</message>
<message>
<location line="+6"/>
<source>This pane shows a detailed description of the transaction</source>
<translation>此版面顯示交易的詳細說明</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<location filename="../transactiontablemodel.cpp" line="+225"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location line="+0"/>
<source>Type</source>
<translation>種類</translation>
</message>
<message>
<location line="+0"/>
<source>Address</source>
<translation>位址</translation>
</message>
<message>
<location line="+0"/>
<source>Amount</source>
<translation>金額</translation>
</message>
<message numerus="yes">
<location line="+57"/>
<source>Open for %n more block(s)</source>
<translation><numerusform>在接下來 %n 個區塊產出前未定</numerusform></translation>
</message>
<message>
<location line="+3"/>
<source>Open until %1</source>
<translation>在 %1 前未定</translation>
</message>
<message>
<location line="+3"/>
<source>Offline (%1 confirmations)</source>
<translation>離線中 (經確認 %1 次)</translation>
</message>
<message>
<location line="+3"/>
<source>Unconfirmed (%1 of %2 confirmations)</source>
<translation>未確認 (經確認 %1 次, 應確認 %2 次)</translation>
</message>
<message>
<location line="+3"/>
<source>Confirmed (%1 confirmations)</source>
<translation>已確認 (經確認 %1 次)</translation>
</message>
<message numerus="yes">
<location line="+8"/>
<source>Mined balance will be available when it matures in %n more block(s)</source>
<translation><numerusform>開採金額將可在 %n 個區塊熟成後可用</numerusform></translation>
</message>
<message>
<location line="+5"/>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>沒有其他節點收到這個區塊, 也許它不被接受!</translation>
</message>
<message>
<location line="+3"/>
<source>Generated but not accepted</source>
<translation>生產出但不被接受</translation>
</message>
<message>
<location line="+43"/>
<source>Received with</source>
<translation>收受於</translation>
</message>
<message>
<location line="+2"/>
<source>Received from</source>
<translation>收受自</translation>
</message>
<message>
<location line="+3"/>
<source>Sent to</source>
<translation>付出至</translation>
</message>
<message>
<location line="+2"/>
<source>Payment to yourself</source>
<translation>付給自己</translation>
</message>
<message>
<location line="+2"/>
<source>Mined</source>
<translation>開採所得</translation>
</message>
<message>
<location line="+38"/>
<source>(n/a)</source>
<translation>(不適用)</translation>
</message>
<message>
<location line="+199"/>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>交易狀態. 移動游標至欄位上方來顯示確認次數.</translation>
</message>
<message>
<location line="+2"/>
<source>Date and time that the transaction was received.</source>
<translation>收到交易的日期與時間.</translation>
</message>
<message>
<location line="+2"/>
<source>Type of transaction.</source>
<translation>交易的種類.</translation>
</message>
<message>
<location line="+2"/>
<source>Destination address of transaction.</source>
<translation>交易的目標位址.</translation>
</message>
<message>
<location line="+2"/>
<source>Amount removed from or added to balance.</source>
<translation>減去或加入至餘額的金額</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<location filename="../transactionview.cpp" line="+52"/>
<location line="+16"/>
<source>All</source>
<translation>全部</translation>
</message>
<message>
<location line="-15"/>
<source>Today</source>
<translation>今天</translation>
</message>
<message>
<location line="+1"/>
<source>This week</source>
<translation>這週</translation>
</message>
<message>
<location line="+1"/>
<source>This month</source>
<translation>這個月</translation>
</message>
<message>
<location line="+1"/>
<source>Last month</source>
<translation>上個月</translation>
</message>
<message>
<location line="+1"/>
<source>This year</source>
<translation>今年</translation>
</message>
<message>
<location line="+1"/>
<source>Range...</source>
<translation>指定範圍...</translation>
</message>
<message>
<location line="+11"/>
<source>Received with</source>
<translation>收受於</translation>
</message>
<message>
<location line="+2"/>
<source>Sent to</source>
<translation>付出至</translation>
</message>
<message>
<location line="+2"/>
<source>To yourself</source>
<translation>給自己</translation>
</message>
<message>
<location line="+1"/>
<source>Mined</source>
<translation>開採所得</translation>
</message>
<message>
<location line="+1"/>
<source>Other</source>
<translation>其他</translation>
</message>
<message>
<location line="+7"/>
<source>Enter address or label to search</source>
<translation>輸入位址或標記來搜尋</translation>
</message>
<message>
<location line="+7"/>
<source>Min amount</source>
<translation>最小金額</translation>
</message>
<message>
<location line="+34"/>
<source>Copy address</source>
<translation>複製位址</translation>
</message>
<message>
<location line="+1"/>
<source>Copy label</source>
<translation>複製標記</translation>
</message>
<message>
<location line="+1"/>
<source>Copy amount</source>
<translation>複製金額</translation>
</message>
<message>
<location line="+1"/>
<source>Copy transaction ID</source>
<translation>複製交易識別碼</translation>
</message>
<message>
<location line="+1"/>
<source>Edit label</source>
<translation>編輯標記</translation>
</message>
<message>
<location line="+1"/>
<source>Show transaction details</source>
<translation>顯示交易明細</translation>
</message>
<message>
<location line="+143"/>
<source>Export Transaction Data</source>
<translation>匯出交易資料</translation>
</message>
<message>
<location line="+1"/>
<source>Comma separated file (*.csv)</source>
<translation>逗號分隔資料檔 (*.csv)</translation>
</message>
<message>
<location line="+8"/>
<source>Confirmed</source>
<translation>已確認</translation>
</message>
<message>
<location line="+1"/>
<source>Date</source>
<translation>日期</translation>
</message>
<message>
<location line="+1"/>
<source>Type</source>
<translation>種類</translation>
</message>
<message>
<location line="+1"/>
<source>Label</source>
<translation>標記</translation>
</message>
<message>
<location line="+1"/>
<source>Address</source>
<translation>位址</translation>
</message>
<message>
<location line="+1"/>
<source>Amount</source>
<translation>金額</translation>
</message>
<message>
<location line="+1"/>
<source>ID</source>
<translation>識別碼</translation>
</message>
<message>
<location line="+4"/>
<source>Error exporting</source>
<translation>匯出失敗</translation>
</message>
<message>
<location line="+0"/>
<source>Could not write to file %1.</source>
<translation>無法寫入至 %1 檔案.</translation>
</message>
<message>
<location line="+100"/>
<source>Range:</source>
<translation>範圍:</translation>
</message>
<message>
<location line="+8"/>
<source>to</source>
<translation>至</translation>
</message>
</context>
<context>
<name>WalletModel</name>
<message>
<location filename="../walletmodel.cpp" line="+193"/>
<source>Send Coins</source>
<translation>付錢</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<location filename="../walletview.cpp" line="+46"/>
<source>&Export</source>
<translation>匯出</translation>
</message>
<message>
<location line="+1"/>
<source>Export the data in the current tab to a file</source>
<translation>將目前分頁的資料匯出存成檔案</translation>
</message>
<message>
<location line="+197"/>
<source>Backup Wallet</source>
<translation>錢包備份</translation>
</message>
<message>
<location line="+0"/>
<source>Wallet Data (*.dat)</source>
<translation>錢包資料檔 (*.dat)</translation>
</message>
<message>
<location line="+3"/>
<source>Backup Failed</source>
<translation>備份失敗</translation>
</message>
<message>
<location line="+0"/>
<source>There was an error trying to save the wallet data to the new location.</source>
<translation>儲存錢包資料到新的地方失敗</translation>
</message>
<message>
<location line="+4"/>
<source>Backup Successful</source>
<translation>備份成功</translation>
</message>
<message>
<location line="+0"/>
<source>The wallet data was successfully saved to the new location.</source>
<translation>錢包的資料已經成功儲存到新的地方了.</translation>
</message>
</context>
<context>
<name>bitcoin-core</name>
<message>
<location filename="../bitcoinstrings.cpp" line="+98"/>
<source>Bitcoin version</source>
<translation>位元幣版本</translation>
</message>
<message>
<location line="+104"/>
<source>Usage:</source>
<translation>用法:</translation>
</message>
<message>
<location line="-30"/>
<source>Send command to -server or bitcoind</source>
<translation>送指令給 -server 或 bitcoind
</translation>
</message>
<message>
<location line="-23"/>
<source>List commands</source>
<translation>列出指令
</translation>
</message>
<message>
<location line="-13"/>
<source>Get help for a command</source>
<translation>取得指令說明
</translation>
</message>
<message>
<location line="+25"/>
<source>Options:</source>
<translation>選項:
</translation>
</message>
<message>
<location line="+24"/>
<source>Specify configuration file (default: bitcoin.conf)</source>
<translation>指定設定檔 (預設: bitcoin.conf)
</translation>
</message>
<message>
<location line="+3"/>
<source>Specify pid file (default: bitcoind.pid)</source>
<translation>指定行程識別碼檔案 (預設: bitcoind.pid)
</translation>
</message>
<message>
<location line="-1"/>
<source>Specify data directory</source>
<translation>指定資料目錄
</translation><|fim▁hole|> </message>
<message>
<location line="-9"/>
<source>Set database cache size in megabytes (default: 25)</source>
<translation>設定資料庫快取大小為多少百萬位元組(MB, 預設: 25)</translation>
</message>
<message>
<location line="-28"/>
<source>Listen for connections on <port> (default: 8333 or testnet: 18333)</source>
<translation>在通訊埠 <port> 聽候連線 (預設: 8333, 或若為測試網路: 18333)</translation>
</message>
<message>
<location line="+5"/>
<source>Maintain at most <n> connections to peers (default: 125)</source>
<translation>維持與節點連線數的上限為 <n> 個 (預設: 125)</translation>
</message>
<message>
<location line="-49"/>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>連線到某個節點以取得其它節點的位址, 然後斷線</translation>
</message>
<message>
<location line="+84"/>
<source>Specify your own public address</source>
<translation>指定自己公開的位址</translation>
</message>
<message>
<location line="+3"/>
<source>Threshold for disconnecting misbehaving peers (default: 100)</source>
<translation>與亂搞的節點斷線的臨界值 (預設: 100)</translation>
</message>
<message>
<location line="-136"/>
<source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source>
<translation>避免與亂搞的節點連線的秒數 (預設: 86400)</translation>
</message>
<message>
<location line="-33"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source>
<translation>在 IPv4 網路上以通訊埠 %u 聽取 RPC 連線時發生錯誤: %s</translation>
</message>
<message>
<location line="+31"/>
<source>Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)</source>
<translation>在通訊埠 <port> 聽候 JSON-RPC 連線 (預設: 8332, 或若為測試網路: 18332)</translation>
</message>
<message>
<location line="+37"/>
<source>Accept command line and JSON-RPC commands</source>
<translation>接受命令列與 JSON-RPC 指令
</translation>
</message>
<message>
<location line="+77"/>
<source>Run in the background as a daemon and accept commands</source>
<translation>以背景程式執行並接受指令</translation>
</message>
<message>
<location line="+38"/>
<source>Use the test network</source>
<translation>使用測試網路
</translation>
</message>
<message>
<location line="-114"/>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>是否接受外來連線 (預設: 當沒有 -proxy 或 -connect 時預設為 1)</translation>
</message>
<message>
<location line="-84"/>
<source>%s, you must set a rpcpassword in the configuration file:
%s
It is recommended you use the following random password:
rpcuser=bitcoinrpc
rpcpassword=%s
(you do not need to remember this password)
The username and password MUST NOT be the same.
If the file does not exist, create it with owner-readable-only file permissions.
It is also recommended to set alertnotify so you are notified of problems;
for example: alertnotify=echo %%s | mail -s "Bitcoin Alert" [email protected]
</source>
<translation>%s, 你必須要在以下設定檔中設定 RPC 密碼(rpcpassword):
%s
建議你使用以下隨機產生的密碼:
rpcuser=bitcoinrpc
rpcpassword=%s
(你不用記住這個密碼)
使用者名稱(rpcuser)和密碼(rpcpassword)不可以相同!
如果設定檔還不存在, 請在新增時, 設定檔案權限為"只有主人才能讀取".
也建議你設定警示通知, 發生問題時你才會被通知到;
比如說設定為:
alertnotify=echo %%s | mail -s "Bitcoin Alert" [email protected]
</translation>
</message>
<message>
<location line="+17"/>
<source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source>
<translation>設定在 IPv6 網路的通訊埠 %u 上聽候 RPC 連線失敗, 退而改用 IPv4 網路: %s</translation>
</message>
<message>
<location line="+3"/>
<source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source>
<translation>和指定的位址繫結, 並總是在該位址聽候連線. IPv6 請用 "[主機]:通訊埠" 這種格式</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot obtain a lock on data directory %s. Bitcoin is probably already running.</source>
<translation>無法鎖定資料目錄 %s. 也許位元幣已經在執行了.</translation>
</message>
<message>
<location line="+3"/>
<source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source>
<translation>進入回歸測試模式, 特別的區塊鎖鏈使用中, 可以立即解出區塊. 目的是用來做回歸測試, 以及配合應用程式的開發.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source>
<translation>錯誤: 交易被拒絕了! 有時候會發生這種錯誤, 是因為你錢包中的一些錢已經被花掉了. 比如說你複製了錢包檔 wallet.dat, 然後用複製的錢包花掉了錢, 你現在所用的原來的錢包中卻沒有該筆交易紀錄.</translation>
</message>
<message>
<location line="+4"/>
<source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source>
<translation>錯誤: 這筆交易需要至少 %s 的手續費! 因為它的金額太大, 或複雜度太高, 或是使用了最近才剛收到的款項.</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source>
<translation>當收到相關警示時所要執行的指令 (指令中的 %s 會被取代為警示訊息)</translation>
</message>
<message>
<location line="+3"/>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>當錢包有交易改變時所要執行的指令 (指令中的 %s 會被取代為交易識別碼)</translation>
</message>
<message>
<location line="+11"/>
<source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source>
<translation>設定高優先權或低手續費的交易資料大小上限為多少位元組 (預設: 27000)</translation>
</message>
<message>
<location line="+6"/>
<source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source>
<translation>這是尚未發表的測試版本 - 使用請自負風險 - 請不要用於開採或商業應用</translation>
</message>
<message>
<location line="+5"/>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>警告: -paytxfee 設定了很高的金額! 這可是你交易付款所要付的手續費.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source>
<translation>警告: 顯示的交易可能不正確! 你可能需要升級, 或者需要等其它的節點升級.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: Please check that your computer's date and time are correct! If your clock is wrong Bitcoin will not work properly.</source>
<translation>警告: 請檢查電腦時間與日期是否正確! 位元幣無法在時鐘不準的情況下正常運作.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source>
<translation>警告: 讀取錢包檔 wallet.dat 失敗了! 所有的密鑰都正確讀取了, 但是交易資料或位址簿資料可能會缺少或不正確.</translation>
</message>
<message>
<location line="+3"/>
<source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source>
<translation>警告: 錢包檔 wallet.dat 壞掉, 但資料被拯救回來了! 原來的 wallet.dat 會改儲存在 %s, 檔名為 wallet.{timestamp}.bak. 如果餘額或交易資料有誤, 你應該要用備份資料復原回來.</translation>
</message>
<message>
<location line="+14"/>
<source>Attempt to recover private keys from a corrupt wallet.dat</source>
<translation>嘗試從壞掉的錢包檔 wallet.dat 復原密鑰</translation>
</message>
<message>
<location line="+2"/>
<source>Block creation options:</source>
<translation>區塊產生選項:</translation>
</message>
<message>
<location line="+5"/>
<source>Connect only to the specified node(s)</source>
<translation>只連線至指定節點(可多個)</translation>
</message>
<message>
<location line="+3"/>
<source>Corrupted block database detected</source>
<translation>發現區塊資料庫壞掉了</translation>
</message>
<message>
<location line="+1"/>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>找出自己的網際網路位址 (預設: 當有聽候連線且沒有 -externalip 時為 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Do you want to rebuild the block database now?</source>
<translation>你要現在重建區塊資料庫嗎?</translation>
</message>
<message>
<location line="+2"/>
<source>Error initializing block database</source>
<translation>初始化區塊資料庫失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Error initializing wallet database environment %s!</source>
<translation>錢包資料庫環境 %s 初始化錯誤!</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading block database</source>
<translation>載入區塊資料庫失敗</translation>
</message>
<message>
<location line="+4"/>
<source>Error opening block database</source>
<translation>打開區塊資料庫檔案失敗</translation>
</message>
<message>
<location line="+2"/>
<source>Error: Disk space is low!</source>
<translation>錯誤: 磁碟空間很少!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: Wallet locked, unable to create transaction!</source>
<translation>錯誤: 錢包被上鎖了, 無法產生新的交易!</translation>
</message>
<message>
<location line="+1"/>
<source>Error: system error: </source>
<translation>錯誤: 系統錯誤:</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>在任意的通訊埠聽候失敗. 如果你想的話可以用 -listen=0.</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block info</source>
<translation>讀取區塊資訊失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to read block</source>
<translation>讀取區塊失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to sync block index</source>
<translation>同步區塊索引失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block index</source>
<translation>寫入區塊索引失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block info</source>
<translation>寫入區塊資訊失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write block</source>
<translation>寫入區塊失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write file info</source>
<translation>寫入檔案資訊失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write to coin database</source>
<translation>寫入位元幣資料庫失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write transaction index</source>
<translation>寫入交易索引失敗</translation>
</message>
<message>
<location line="+1"/>
<source>Failed to write undo data</source>
<translation>寫入回復資料失敗</translation>
</message>
<message>
<location line="+2"/>
<source>Find peers using DNS lookup (default: 1 unless -connect)</source>
<translation>是否允許在找節點時使用域名查詢 (預設: 當沒用 -connect 時為 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Generate coins (default: 0)</source>
<translation>生產位元幣 (預設值: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>How many blocks to check at startup (default: 288, 0 = all)</source>
<translation>啓動時檢查的區塊數 (預設: 288, 指定 0 表示全部)</translation>
</message>
<message>
<location line="+1"/>
<source>How thorough the block verification is (0-4, default: 3)</source>
<translation>區塊檢查的仔細程度 (0 至 4, 預設: 3)</translation>
</message>
<message>
<location line="+2"/>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation>創世區塊不正確或找不到. 資料目錄錯了嗎?</translation>
</message>
<message>
<location line="+18"/>
<source>Not enough file descriptors available.</source>
<translation>檔案描述器不足.</translation>
</message>
<message>
<location line="+8"/>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>從目前的區塊檔 blk000??.dat 重建鎖鏈索引</translation>
</message>
<message>
<location line="+16"/>
<source>Set the number of threads to service RPC calls (default: 4)</source>
<translation>設定處理 RPC 服務請求的執行緒數目 (預設為 4)</translation>
</message>
<message>
<location line="+7"/>
<source>Specify wallet file (within data directory)</source>
<translation>指定錢包檔(會在資料目錄中)</translation>
</message>
<message>
<location line="+20"/>
<source>Verifying blocks...</source>
<translation>驗證區塊資料中...</translation>
</message>
<message>
<location line="+1"/>
<source>Verifying wallet...</source>
<translation>驗證錢包資料中...</translation>
</message>
<message>
<location line="+1"/>
<source>Wallet %s resides outside data directory %s</source>
<translation>錢包檔 %s 沒有在資料目錄 %s 裡面</translation>
</message>
<message>
<location line="+4"/>
<source>You need to rebuild the database using -reindex to change -txindex</source>
<translation>改變 -txindex 參數後, 必須要用 -reindex 參數來重建資料庫</translation>
</message>
<message>
<location line="-76"/>
<source>Imports blocks from external blk000??.dat file</source>
<translation>從其它來源的 blk000??.dat 檔匯入區塊</translation>
</message>
<message>
<location line="-76"/>
<source>Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)</source>
<translation>設定指令碼驗證的執行緒數目 (最多為 16, 若為 0 表示程式自動決定, 小於 0 表示保留不用的處理器核心數目, 預設為 0)</translation>
</message>
<message>
<location line="+78"/>
<source>Information</source>
<translation>資訊</translation>
</message>
<message>
<location line="+3"/>
<source>Invalid -tor address: '%s'</source>
<translation>無效的 -tor 位址: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>設定 -minrelaytxfee=<金額> 的金額無效: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>設定 -mintxfee=<amount> 的金額無效: '%s'</translation>
</message>
<message>
<location line="+8"/>
<source>Maintain a full transaction index (default: 0)</source>
<translation>維護全部交易的索引 (預設為 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)</source>
<translation>每個連線的接收緩衝區大小上限為 <n>*1000 個位元組 (預設: 5000)</translation>
</message>
<message>
<location line="+1"/>
<source>Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)</source>
<translation>每個連線的傳送緩衝區大小上限為 <n>*1000 位元組 (預設: 1000)</translation>
</message>
<message>
<location line="+2"/>
<source>Only accept block chain matching built-in checkpoints (default: 1)</source>
<translation>只接受與內建的檢查段點吻合的區塊鎖鏈 (預設: 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Only connect to nodes in network <net> (IPv4, IPv6 or Tor)</source>
<translation>只和 <net> 網路上的節點連線 (IPv4, IPv6, 或 Tor)</translation>
</message>
<message>
<location line="+2"/>
<source>Output extra debugging information. Implies all other -debug* options</source>
<translation>輸出額外的除錯資訊. 包含了其它所有的 -debug* 選項</translation>
</message>
<message>
<location line="+1"/>
<source>Output extra network debugging information</source>
<translation>輸出額外的網路除錯資訊</translation>
</message>
<message>
<location line="+2"/>
<source>Prepend debug output with timestamp</source>
<translation>在除錯輸出內容前附加時間</translation>
</message>
<message>
<location line="+5"/>
<source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source>
<translation>SSL 選項: (SSL 設定程序請見 Bitcoin Wiki)</translation>
</message>
<message>
<location line="+1"/>
<source>Select the version of socks proxy to use (4-5, default: 5)</source>
<translation>選擇 SOCKS 代理伺服器的協定版本(4 或 5, 預設: 5)</translation>
</message>
<message>
<location line="+3"/>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>在終端機顯示追蹤或除錯資訊, 而非寫到 debug.log 檔</translation>
</message>
<message>
<location line="+1"/>
<source>Send trace/debug info to debugger</source>
<translation>輸出追蹤或除錯資訊給除錯器</translation>
</message>
<message>
<location line="+5"/>
<source>Set maximum block size in bytes (default: 250000)</source>
<translation>設定區塊大小上限為多少位元組 (預設: 250000)</translation>
</message>
<message>
<location line="+1"/>
<source>Set minimum block size in bytes (default: 0)</source>
<translation>設定區塊大小下限為多少位元組 (預設: 0)</translation>
</message>
<message>
<location line="+2"/>
<source>Shrink debug.log file on client startup (default: 1 when no -debug)</source>
<translation>客戶端軟體啓動時將 debug.log 檔縮小 (預設: 當沒有 -debug 時為 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Signing transaction failed</source>
<translation>簽署交易失敗</translation>
</message>
<message>
<location line="+2"/>
<source>Specify connection timeout in milliseconds (default: 5000)</source>
<translation>指定連線在幾毫秒後逾時 (預設: 5000)</translation>
</message>
<message>
<location line="+5"/>
<source>System error: </source>
<translation>系統錯誤:</translation>
</message>
<message>
<location line="+4"/>
<source>Transaction amount too small</source>
<translation>交易金額太小</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction amounts must be positive</source>
<translation>交易金額必須是正的</translation>
</message>
<message>
<location line="+1"/>
<source>Transaction too large</source>
<translation>交易位元量太大</translation>
</message>
<message>
<location line="+7"/>
<source>Use UPnP to map the listening port (default: 0)</source>
<translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 0)</translation>
</message>
<message>
<location line="+1"/>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>是否使用通用即插即用(UPnP)協定來設定聽候連線的通訊埠 (預設: 當有聽候連線為 1)</translation>
</message>
<message>
<location line="+1"/>
<source>Use proxy to reach tor hidden services (default: same as -proxy)</source>
<translation>透過代理伺服器來使用 Tor 隱藏服務 (預設: 同 -proxy)</translation>
</message>
<message>
<location line="+2"/>
<source>Username for JSON-RPC connections</source>
<translation>JSON-RPC 連線使用者名稱</translation>
</message>
<message>
<location line="+5"/>
<source>Warning</source>
<translation>警告</translation>
</message>
<message>
<location line="+1"/>
<source>Warning: This version is obsolete, upgrade required!</source>
<translation>警告: 這個版本已經被淘汰掉了, 必須要升級!</translation>
</message>
<message>
<location line="+2"/>
<source>wallet.dat corrupt, salvage failed</source>
<translation>錢包檔 weallet.dat 壞掉了, 拯救失敗</translation>
</message>
<message>
<location line="-52"/>
<source>Password for JSON-RPC connections</source>
<translation>JSON-RPC 連線密碼</translation>
</message>
<message>
<location line="-68"/>
<source>Allow JSON-RPC connections from specified IP address</source>
<translation>只允許從指定網路位址來的 JSON-RPC 連線</translation>
</message>
<message>
<location line="+77"/>
<source>Send commands to node running on <ip> (default: 127.0.0.1)</source>
<translation>送指令給在 <ip> 的節點 (預設: 127.0.0.1)
</translation>
</message>
<message>
<location line="-121"/>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>當最新區塊改變時所要執行的指令 (指令中的 %s 會被取代為區塊的雜湊值)</translation>
</message>
<message>
<location line="+149"/>
<source>Upgrade wallet to latest format</source>
<translation>將錢包升級成最新的格式</translation>
</message>
<message>
<location line="-22"/>
<source>Set key pool size to <n> (default: 100)</source>
<translation>設定密鑰池大小為 <n> (預設: 100)
</translation>
</message>
<message>
<location line="-12"/>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>重新掃描區塊鎖鏈, 以尋找錢包所遺漏的交易.</translation>
</message>
<message>
<location line="+36"/>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>於 JSON-RPC 連線使用 OpenSSL (https)
</translation>
</message>
<message>
<location line="-27"/>
<source>Server certificate file (default: server.cert)</source>
<translation>伺服器憑證檔 (預設: server.cert)
</translation>
</message>
<message>
<location line="+1"/>
<source>Server private key (default: server.pem)</source>
<translation>伺服器密鑰檔 (預設: server.pem)
</translation>
</message>
<message>
<location line="-156"/>
<source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source>
<translation>可以接受的加密法 (預設: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)
</translation>
</message>
<message>
<location line="+171"/>
<source>This help message</source>
<translation>此協助訊息
</translation>
</message>
<message>
<location line="+6"/>
<source>Unable to bind to %s on this computer (bind returned error %d, %s)</source>
<translation>無法和這台電腦上的 %s 繫結 (繫結回傳錯誤 %d, %s)</translation>
</message>
<message>
<location line="-93"/>
<source>Connect through socks proxy</source>
<translation>透過 SOCKS 代理伺服器連線</translation>
</message>
<message>
<location line="-10"/>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>允許對 -addnode, -seednode, -connect 的參數使用域名查詢 </translation>
</message>
<message>
<location line="+56"/>
<source>Loading addresses...</source>
<translation>載入位址中...</translation>
</message>
<message>
<location line="-36"/>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>載入檔案 wallet.dat 失敗: 錢包壞掉了</translation>
</message>
<message>
<location line="+1"/>
<source>Error loading wallet.dat: Wallet requires newer version of Bitcoin</source>
<translation>載入檔案 wallet.dat 失敗: 此錢包需要新版的 Bitcoin</translation>
</message>
<message>
<location line="+96"/>
<source>Wallet needed to be rewritten: restart Bitcoin to complete</source>
<translation>錢包需要重寫: 請重啟位元幣來完成</translation>
</message>
<message>
<location line="-98"/>
<source>Error loading wallet.dat</source>
<translation>載入檔案 wallet.dat 失敗</translation>
</message>
<message>
<location line="+29"/>
<source>Invalid -proxy address: '%s'</source>
<translation>無效的 -proxy 位址: '%s'</translation>
</message>
<message>
<location line="+57"/>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>在 -onlynet 指定了不明的網路別: '%s'</translation>
</message>
<message>
<location line="-1"/>
<source>Unknown -socks proxy version requested: %i</source>
<translation>在 -socks 指定了不明的代理協定版本: %i</translation>
</message>
<message>
<location line="-98"/>
<source>Cannot resolve -bind address: '%s'</source>
<translation>無法解析 -bind 位址: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>無法解析 -externalip 位址: '%s'</translation>
</message>
<message>
<location line="+45"/>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>設定 -paytxfee=<金額> 的金額無效: '%s'</translation>
</message>
<message>
<location line="+1"/>
<source>Invalid amount</source>
<translation>無效的金額</translation>
</message>
<message>
<location line="-6"/>
<source>Insufficient funds</source>
<translation>累積金額不足</translation>
</message>
<message>
<location line="+10"/>
<source>Loading block index...</source>
<translation>載入區塊索引中...</translation>
</message>
<message>
<location line="-58"/>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>加入一個要連線的節線, 並試著保持對它的連線暢通</translation>
</message>
<message>
<location line="-25"/>
<source>Unable to bind to %s on this computer. Bitcoin is probably already running.</source>
<translation>無法和這台電腦上的 %s 繫結. 也許位元幣已經在執行了.</translation>
</message>
<message>
<location line="+64"/>
<source>Fee per KB to add to transactions you send</source>
<translation>交易付款時每 KB 的交易手續費</translation>
</message>
<message>
<location line="+20"/>
<source>Loading wallet...</source>
<translation>載入錢包中...</translation>
</message>
<message>
<location line="-53"/>
<source>Cannot downgrade wallet</source>
<translation>無法將錢包格式降級</translation>
</message>
<message>
<location line="+3"/>
<source>Cannot write default address</source>
<translation>無法寫入預設位址</translation>
</message>
<message>
<location line="+65"/>
<source>Rescanning...</source>
<translation>重新掃描中...</translation>
</message>
<message>
<location line="-58"/>
<source>Done loading</source>
<translation>載入完成</translation>
</message>
<message>
<location line="+84"/>
<source>To use the %s option</source>
<translation>為了要使用 %s 選項</translation>
</message>
<message>
<location line="-76"/>
<source>Error</source>
<translation>錯誤</translation>
</message>
<message>
<location line="-31"/>
<source>You must set rpcpassword=<password> in the configuration file:
%s
If the file does not exist, create it with owner-readable-only file permissions.</source>
<translation>你必須在下列設定檔中設定 RPC 密碼(rpcpassword=<password>):
%s
如果這個檔案還不存在, 請在新增時, 設定檔案權限為"只有主人才能讀取".</translation>
</message>
</context>
</TS><|fim▁end|> | |
<|file_name|>pde.rs<|end_file_name|><|fim▁begin|>use ndarray::*;
use ndarray_linalg::*;
use std::f64::consts::PI;
use std::iter::FromIterator;
use eom::pde::*;
#[test]
fn pair_r2c2r() {
let n = 128;
let a: Array1<f64> = random(n);
let mut p = Pair::new(n);
p.r.copy_from_slice(&a.as_slice().unwrap());
p.r2c();
p.c2r();
let b: Array1<f64> = Array::from_iter(p.r.iter().cloned());
assert_close_l2!(&a, &b, 1e-7);
}
#[test]
fn pair_c2r() {
let n = 128;<|fim▁hole|> let a = Array::from_shape_fn(n, |i| 2.0 * (i as f64 * k0).cos());
let mut p = Pair::new(n);
p.c[1] = c64::new(1.0, 0.0);
p.c2r();
let b = Array::from_iter(p.r.iter().cloned());
assert_close_l2!(&a, &b, 1e-7);
}<|fim▁end|> | let k0 = 2.0 * PI / n as f64; |
<|file_name|>start.js<|end_file_name|><|fim▁begin|>//repl read eval print loop<|fim▁hole|><|fim▁end|> | console.log('start'); |
<|file_name|>issue-16256.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license<|fim▁hole|>// pretty-expanded FIXME #23616
fn main() {
let mut buf = Vec::new();
|c: u8| buf.push(c);
}<|fim▁end|> | // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
|
<|file_name|>test_volume_backup.py<|end_file_name|><|fim▁begin|># -*- coding:utf-8 -*-
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
volume = test_lib.lib_get_specific_stub('e2e_mini/volume', 'volume')
volume_ops = None
vm_ops = None
volume_name = 'volume-' + volume.get_time_postfix()
backup_name = 'backup-' + volume.get_time_postfix()
def test():
global volume_ops
volume_ops = volume.VOLUME()
vm = test_lib.lib_get_specific_stub(suite_name='e2e_mini/vm', specific_name='vm')
vm_ops = vm.VM(uri=volume_ops.uri, initialized=True)
vm_ops.create_vm()
volume_ops.create_volume(volume_name)
volume_ops.volume_attach_to_vm(vm_ops.vm_name)
volume_ops.create_backup(volume_name, 'volume', backup_name)
vm_ops.vm_ops(vm_ops.vm_name, action='stop')
volume_ops.restore_backup(volume_name, 'volume', backup_name)
volume_ops.delete_backup(volume_name, 'volume', backup_name)
volume_ops.check_browser_console_log()
test_util.test_pass('Test Volume Create, Restore and Delete Backups Successful')
def env_recover():
global volume_ops
vm_ops.expunge_vm()
volume_ops.expunge_volume(volume_name)
volume_ops.close()
#Will be called only if exception happens in test().
def error_cleanup():
global volume_ops
try:<|fim▁hole|> vm_ops.expunge_vm()
volume_ops.expunge_volume(volume_name)
volume_ops.close()
except:
pass<|fim▁end|> | |
<|file_name|>all_a.js<|end_file_name|><|fim▁begin|>var searchData=
[
['database',['Database',['../namespace_pontikis_1_1_database.html',1,'Pontikis']]],<|fim▁hole|> ['prepared_5fstatements_5fquestion_5fmark',['PREPARED_STATEMENTS_QUESTION_MARK',['../class_pontikis_1_1_database_1_1_dacapo.html#a63dd2d4d612585c42c7e53e9b66caf24',1,'Pontikis::Database::Dacapo']]]
];<|fim▁end|> | ['pg_5fsequence_5fname_5fauto',['PG_SEQUENCE_NAME_AUTO',['../class_pontikis_1_1_database_1_1_dacapo.html#aef46219ed4c7133e99979e0d3aa5cd86',1,'Pontikis::Database::Dacapo']]],
['pontikis',['Pontikis',['../namespace_pontikis.html',1,'']]],
['prepared_5fstatements_5fnumbered',['PREPARED_STATEMENTS_NUMBERED',['../class_pontikis_1_1_database_1_1_dacapo.html#a963df8efcdd80ba37064e3cde0c8809a',1,'Pontikis::Database::Dacapo']]], |
<|file_name|>trello.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python
''' Interact with Trello API as a CLI or Sopel IRC bot module '''
import argparse
from datetime import date
from email.mime.text import MIMEText
import json
import os
import re
import smtplib
import sys
# sopel is only for IRC bot installation. Not required for CLI
try:
import sopel.module # pylint: disable=import-error
except ImportError:
pass
try:
from urllib import urlencode
from urllib2 import HTTPError, Request, urlopen
except ImportError:
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
# constants
DEFAULT_LIST = "Active"
DEFAULT_SNOWFLAKE_LIST = "Snowflakes"
DEFAULT_RESOLVED_LIST = "Resolved"
BASE_URL = "https://api.trello.com/1"
EMAIL_SERVER = 'smtp.redhat.com'
EMAIL_FROM = '[email protected]'
EMAIL_REPLYTO = '[email protected]'
class Trello(object):
"""Trello object"""
def __init__(self):
"""Set object params"""
self.args = None
self.api_key = os.environ.get("trello_consumer_key", None)
self.oauth_token = os.environ.get("trello_oauth_token", None)
self.board_id = os.environ.get("trello_board_id", None)
self.board_id_long = os.environ.get("trello_board_id_long", None)
self.email_addresses = os.environ.get("trello_report_email_addresses", None)
@staticmethod
def parse_args():
"""Parse CLI arguments"""
parser = argparse.ArgumentParser(
description='Create, comment, move Trello cards, also reporting.')
subparsers = parser.add_subparsers(help='sub-command help')
parser_get = subparsers.add_parser('get',
help="""Get board information:
card list, user list or
card details""")
parser_get.add_argument(
'card',
nargs='?',
metavar='CARD_URL',
help='Card short URL to get details for')
parser_get.add_argument(
'--list', '-l',
metavar='TRELLO_LIST',
default=DEFAULT_LIST,
help='List to display cards from, e.g. "Resolved" or "Snowflakes"')
parser_get.add_argument(
'--users', '-u',
action='store_true',
help='Display board users')
parser_get.set_defaults(action='get')
parser_create = subparsers.add_parser('create',
help='Create a new card')
parser_create.set_defaults(action='create')
parser_create.add_argument(
'title', metavar='TITLE',
help='Card title')
parser_update = subparsers.add_parser('update',
help='Update an existing card')
parser_update.set_defaults(action='update')
parser_update.add_argument(
'card', metavar='CARD', help='Existing card URL')
parser_update.add_argument(
'--comment', '-c',
help='Add a comment')
parser_update.add_argument(
'--move', '-m',
metavar='LIST_NAME',
help='Move card to another list, e.g. "Resolved" or "Snowflakes"')
parser_update.add_argument(
'--assign', '-a',
metavar='USER',
help='Attach Trello user to card')
parser_update.add_argument(
'--unassign', '-u',
metavar='USER',
help='Remove Trello user from card')
parser_report = subparsers.add_parser('report',
help="Generate reports")
parser_report.set_defaults(action='report')
parser_report.add_argument(
'--email', '-e',
metavar='ADDRESS[,ADDRESS]',
help="""Comma-separated (no spaces) list of email addresses to
send report to. Overrides env var 'trello_report_email_addresses'""")
parser_report.add_argument(
'--move', '-m',
action='store_true',
help='Move cards to end-of-week list')
return parser.parse_args()
def create(self, title=None):
"""Create card"""
if not title:
title = self.args.title
card = self.trello_create(title)
return card['shortUrl']
def update(self):
"""Update card"""
if self.trello_update(self.card_id(self.args.card)):
print("Updated")
else:
sys.exit("No updates applied")
def get(self):
"""Get card details or list of cards"""
cards = None
if self.args.card:
return json.dumps(self.trello_get(self.card_id()), indent=4)
cards = self.trello_get()
results = ''
for card in cards:
members = ''
if self.args.users:
results += '{} {}\n'.format(str(card['username']),
str(card['fullName']))
else:
for member in card['idMembers']:
if member:
members += str(self.member_username(member)) + ' '
results += '{} {} ({})\n'.format(str(card['shortUrl']),
str(card['name']),
members)
return results
def report(self, email=None, move=False):
"""Generate reports"""
payload = self.report_payload()
print(payload)
_env_email = os.environ.get("trello_report_email_addresses", None)
if _env_email:
email = _env_email
if self.args:
if self.args.email:
email = self.args.email
if self.args.move:
move = self.args.move
week_number = date.today().isocalendar()[1]
if email:
subj = "OpenShift SRE Report for Week #{} (ending {})".format(
week_number, date.today().strftime("%d-%m-%Y"))
_board_url = "https://trello.com/b/{}".format(
os.environ.get("trello_board_id", None))
payload = "For more information visit the SRE 24x7 board {}\n\n{}".format(
_board_url, payload)
self.email_report(email, subj, payload)
print("Report emailed to {}".format(email))
if move:
list_name = "Week #{}".format(week_number)
if self.move_cards(to_list=list_name):
print("Cards moved to list '{}'".format(list_name))
def report_payload(self):
"""Return report payload
:return: formatted report"""
data = ""
resolved_cards = self.get_list_cards(DEFAULT_RESOLVED_LIST)
data += "{}: {}\n".format(DEFAULT_LIST,
len(self.get_list_cards(DEFAULT_LIST)))
data += "{}: {}\n".format(DEFAULT_SNOWFLAKE_LIST,
len(self.get_list_cards(DEFAULT_SNOWFLAKE_LIST)))
data += "{}: {}\n".format(DEFAULT_RESOLVED_LIST,
len(resolved_cards))
data += "\n---\nResolved issues:\n---\n"
for card in resolved_cards:
data += "{} {}\n".format(card['shortUrl'], card['name'])
return data
def move_cards(self, to_list, from_list=None):
"""Move cards from one list to another
:param to_list (required): name of list to move cards to
:param from_list (optional, use default): name of list to move card from
:return: None"""
params = {}
if not to_list:
print("Cannot move: no destination list provided")
return False
if not from_list:
from_list = DEFAULT_RESOLVED_LIST
to_list_id = self.create_list(to_list)
path = "/lists/" + self.get_list_id(from_list) + "/moveAllCards"
params['idBoard'] = self.board_id_long
params['idList'] = to_list_id
return self.make_request(path, 'POST', params)
def create_list(self, name=None):
"""Create new list
:param name: name of list
:return: list ID"""
params = {}
params['name'] = name
params['idBoard'] = self.board_id_long
params['pos'] = "bottom"
newlist = self.make_request('/lists', 'POST', params)
return newlist['id']
@staticmethod
def email_report(email, subj, body):
"""Email report
:param email: email address
:param subj: email subject
:param body: email body
:return: None"""
msg = MIMEText(body)
msg['Subject'] = subj
msg['From'] = EMAIL_FROM
msg['To'] = email
msg['Reply-to'] = EMAIL_REPLYTO
smtpcxn = smtplib.SMTP(host=EMAIL_SERVER, port='25')
smtpcxn.sendmail(email, email, msg.as_string())
smtpcxn.quit()
def get_list_cards(self, trello_list=DEFAULT_LIST):
"""Return card total for given list
:param trello_list: list name
:return: cards array"""
path = "/lists/%s/cards" % self.get_list_id(trello_list)
return self.make_request(path)
def trello_update(self, card_id, **kwargs):
"""Call trello update API
:param card_id: card ID
:return: success boolean"""
params = {}
path = None
updated = False
# handle being called via CLI or bot
if self.args:
if self.args.comment:
kwargs['comment'] = self.args.comment
if self.args.move:
kwargs['move'] = self.args.move
if self.args.assign:
kwargs['assign'] = self.args.assign
if self.args.unassign:
kwargs['unassign'] = self.args.unassign
# Since the trello API is different calls/methods for different data
# we call multiple times
if 'comment' in kwargs:
params['text'] = kwargs['comment']
path = '/cards/' + card_id + '/actions/comments'
updated = self.make_request(path, "POST", params)
if 'resolve' in kwargs:
params['idList'] = self.get_list_id(DEFAULT_RESOLVED_LIST)
path = '/cards/' + card_id
updated = self.make_request(path, "PUT", params)
if 'move' in kwargs:
params['idList'] = self.get_list_id(kwargs['move'])
path = '/cards/' + card_id
updated = self.make_request(path, "PUT", params)
if 'assign' in kwargs:
params['value'] = self.member_id(kwargs['assign'])
path = '/cards/' + card_id + '/idMembers'
updated = self.make_request(path, "POST", params)
if 'unassign' in kwargs:
path = '/cards/' + card_id + '/idMembers/' + self.member_id(kwargs['unassign'])
updated = self.make_request(path, "DELETE", params)
return updated
def trello_create(self, title):
"""Call trello create API
:param title: name/title of card
:return: card"""
params = {}
params['idList'] = self.get_list_id()
params['name'] = title
path = '/cards'
return self.make_request(path, "POST", params)
def member_username(self, memberid):
"""Get member username from member ID"""
member = self.make_request('/members/' + memberid)
return member['username']
def member_id(self, username):
"""Get member id from username"""
members = self.make_request('/boards/' + self.board_id + '/members/')
for member in members:
if username == member['username']:
return member['id']
def card_id(self, url=None):
"""Return parsed card ID from URL
example: https://trello.com/c/PZlOHgGm
returns: PZlOHgGm
:param url: trello short URL
:return: trello card ID"""
if not url:
url = self.args.card
parsed_uri = url.split("/")
return parsed_uri[-1]
def get_list_id(self, list_id=None):
"""Return the list ID
:param list_id: list ID if not default
:return: list_id"""
default = DEFAULT_LIST
if list_id:
default = list_id
path = '/boards/' + self.board_id + '/lists/'
lists = self.make_request(path)
# match board name regardless of case
pattern = re.compile(default, re.I)
for board_list in lists:
if re.match(pattern, board_list['name']):
return board_list['id']
sys.exit("List '%s' not found" % list_id)
def trello_get(self, card_id=None):
"""Get trello cards
:param card_id: trello card ID
:return: trello json"""
path = None
if card_id:
path = '/cards/' + card_id
elif self.args.users:
path = '/boards/' + self.board_id + '/members'
else:
path = '/lists/' + self.get_list_id(self.args.list) + '/cards'
results = self.make_request(path)
return results
def make_request(self, path, method="GET", params=None):
"""Trello API call
:param path: trello API path
:param method: rest call method
:param params: API params
:return: trello json"""
if not params:
params = {}
params['key'] = self.api_key
params['token'] = self.oauth_token
url = BASE_URL + path
data = None
if method == "GET":
url += '?' + urlencode(params)
elif method in ['DELETE', 'POST', 'PUT']:
data = urlencode(params).encode('utf-8')
request = Request(url)
if method in ['DELETE', 'PUT']:
request.get_method = lambda: method
try:
if data:
response = urlopen(request, data=data)
else:
response = urlopen(request)
except HTTPError as err:
print(err)<|fim▁hole|>
return result
def get_trello_id(ircnick):
"""Return trello ID for a given IRC nick"""
key = 'IRCNICK_' + ircnick
try:
return os.environ[key]
except KeyError:
print("%s, you need to map your IRC nick with Trello username" % ircnick)
return None
@sopel.module.commands('issue')
def issue(bot, trigger):
"""Record a new issue in Trello, e.g. '.issue Some issue text'"""
trellobot = Trello()
card = trellobot.trello_create(trigger.group(2))
bot.say(card['shortUrl'])
if not trellobot.trello_update(trellobot.card_id(card['shortUrl']),
assign=get_trello_id(trigger.nick)):
bot.reply(
"you need to map your IRC nick with Trello username." +
"See https://github.com/openshift/openshift-ansible-ops/tree/prod/playbooks/adhoc/ircbot")
@sopel.module.commands('comment')
def comment(bot, trigger):
"""Add comment to a trello card, e.g. '.comment <trelloShortUrl> My comment'"""
trellobot = Trello()
msg = trigger.group(2).partition(' ')
trellobot.trello_update(trellobot.card_id(msg[0]), comment=msg[2])
bot.say('Comment added')
@sopel.module.commands('resolve', 'resolved')
def resolve(bot, trigger):
"""Resolve a trello card, e.g. '.resolve <trelloShortUrl>'"""
trellobot = Trello()
if trellobot.trello_update(trellobot.card_id(trigger.group(2)), resolve=True):
card = trellobot.trello_get(trellobot.card_id(trigger.group(2)))
bot.say('Resolved {}: {}'.format(trigger.group(2), card['name']))
else:
bot.say('Could not resolve %s' % trigger.group(2))
def main():
"""
main() function
:return:
"""
trello = Trello()
trello.args = Trello.parse_args()
if trello.args.action is 'create':
print(trello.create())
elif trello.args.action is 'get':
print(trello.get())
elif trello.args.action is 'update':
trello.update()
elif trello.args.action is 'report':
trello.report()
if __name__ == "__main__":
main()<|fim▁end|> | print(err.read())
result = None
else:
result = json.loads(response.read().decode('utf-8')) |
<|file_name|>func_net_basic_test.py<|end_file_name|><|fim▁begin|>#
# Copyright 2016-2017 Red Hat, Inc.
#
# 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
#
# Refer to the README and COPYING files for full details of the license
#
from __future__ import absolute_import
import os
import six
from nose.plugins.attrib import attr
from vdsm.network import errors as ne
from vdsm.network.link import iface as link_iface
from .netfunctestlib import NetFuncTestCase, NOCHK, SetupNetworksError
from .nettestlib import dummy_device, dummy_devices
from .nmnettestlib import iface_name, nm_connections, is_networkmanager_running
NETWORK_NAME = 'test-network'
NET_1 = NETWORK_NAME + '1'
NET_2 = NETWORK_NAME + '2'
VLANID = 100
class NetworkBasicTemplate(NetFuncTestCase):
__test__ = False
def test_add_net_based_on_nic(self):
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic, 'switch': self.switch}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.assertNetwork(NETWORK_NAME, NETCREATE[NETWORK_NAME])
def test_remove_net_based_on_nic(self):
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic, 'switch': self.switch}}
NETREMOVE = {NETWORK_NAME: {'remove': True}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.setupNetworks(NETREMOVE, {}, NOCHK)
self.assertNoNetwork(NETWORK_NAME)
def test_add_bridged_net_twice(self):
self._test_add_net_twice(bridged=True)
def test_add_bridgeless_net_twice(self):
self._test_add_net_twice(bridged=False)
def test_add_bridgeless_net_missing_nic_fails(self):
self._test_add_net_missing_nic_fails(bridged=False)
def test_add_bridged_net_missing_nic_fails(self):
self._test_add_net_missing_nic_fails(bridged=True)
def test_remove_missing_net_fails(self):
NETREMOVE = {NETWORK_NAME: {'remove': True}}
with self.assertRaises(SetupNetworksError) as cm:
with self.setupNetworks(NETREMOVE, {}, NOCHK):
pass
self.assertEqual(cm.exception.status, ne.ERR_BAD_BRIDGE)
def test_add_net_based_on_vlan(self):
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic, 'vlan': VLANID,
'switch': self.switch}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.assertNetwork(NETWORK_NAME, NETCREATE[NETWORK_NAME])
def test_remove_net_based_on_vlan(self):
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic, 'vlan': VLANID,
'switch': self.switch}}
NETREMOVE = {NETWORK_NAME: {'remove': True}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.setupNetworks(NETREMOVE, {}, NOCHK)
self.assertNoNetwork(NETWORK_NAME)
self.assertNoVlan(nic, VLANID)
def test_add_bridged_net_with_multiple_vlans_over_a_nic(self):
self._test_add_net_with_multiple_vlans_over_a_nic(bridged=True)
def test_add_bridgeless_net_with_multiple_vlans_over_a_nic(self):
self._test_add_net_with_multiple_vlans_over_a_nic(bridged=False)
def test_add_bridged_vlaned_and_non_vlaned_nets_same_nic(self):
self._test_add_vlaned_and_non_vlaned_nets_same_nic(bridged=True)
def test_add_bridgeless_vlaned_and_non_vlaned_nets_same_nic(self):
self._test_add_vlaned_and_non_vlaned_nets_same_nic(bridged=False)
def test_add_multiple_bridged_nets_on_the_same_nic_fails(self):
self._test_add_multiple_nets_fails(bridged=True)
def test_add_multiple_bridgeless_nets_on_the_same_nic_fails(self):
self._test_add_multiple_nets_fails(bridged=False)
def test_add_identical_vlan_id_bridged_nets_same_nic_fails(self):
self._test_add_multiple_nets_fails(bridged=True, vlan_id=VLANID)
def test_add_identical_vlan_id_bridgeless_nets_same_nic_fails(self):
self._test_add_multiple_nets_fails(bridged=False, vlan_id=VLANID)
def test_add_identical_vlan_id_bridged_nets_with_two_nics(self):
self._test_add_identical_vlan_id_nets_with_two_nics(bridged=True)
def test_add_identical_vlan_id_bridgeless_nets_with_two_nics(self):
self._test_add_identical_vlan_id_nets_with_two_nics(bridged=False)
def _test_add_net_with_multiple_vlans_over_a_nic(self, bridged):
VLAN_COUNT = 3
with dummy_device() as nic:
netsetup = {}
for tag in range(VLAN_COUNT):
netname = '{}{}'.format(NETWORK_NAME, tag)
netsetup[netname] = {'vlan': tag,
'nic': nic,
'switch': self.switch,
'bridged': bridged}
with self.setupNetworks(netsetup, {}, NOCHK):
for netname, netattrs in six.viewitems(netsetup):
self.assertNetwork(netname, netattrs)
def _test_add_vlaned_and_non_vlaned_nets_same_nic(self, bridged):
with dummy_device() as nic:
net_1_attrs = self._create_net_attrs(nic, bridged)
net_2_attrs = self._create_net_attrs(nic, bridged, VLANID)
self._assert_nets(net_1_attrs, net_2_attrs)
def _test_add_multiple_nets_fails(self, bridged, vlan_id=None):
with dummy_device() as nic:
net_1_attrs = net_2_attrs = self._create_net_attrs(
nic, bridged, vlan_id)
with self.setupNetworks({NET_1: net_1_attrs}, {}, NOCHK):
with self.assertRaises(SetupNetworksError) as cm:
with self.setupNetworks({NET_2: net_2_attrs}, {}, NOCHK):
pass
self.assertEqual(cm.exception.status, ne.ERR_BAD_PARAMS)
def _test_add_identical_vlan_id_nets_with_two_nics(self, bridged):
with dummy_devices(2) as (nic_1, nic_2):
net_1_attrs = self._create_net_attrs(nic_1, bridged, VLANID)
net_2_attrs = self._create_net_attrs(nic_2, bridged, VLANID)
self._assert_nets(net_1_attrs, net_2_attrs)
def _test_add_net_twice(self, bridged):
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic,
'bridged': bridged,
'switch': self.switch}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.setupNetworks(NETCREATE, {}, NOCHK)
self.assertNetwork(NETWORK_NAME, NETCREATE[NETWORK_NAME])
def _test_add_net_missing_nic_fails(self, bridged):
NETCREATE = {NETWORK_NAME: {'nic': 'missing_nic',
'bridged': bridged,
'switch': self.switch}}
with self.assertRaises(SetupNetworksError) as cm:
with self.setupNetworks(NETCREATE, {}, NOCHK):
pass
self.assertEqual(cm.exception.status, ne.ERR_BAD_NIC)
def _assert_nets(self, net_1_attrs, net_2_attrs):
with self.setupNetworks({NET_1: net_1_attrs}, {}, NOCHK):
with self.setupNetworks({NET_2: net_2_attrs}, {}, NOCHK):
self.assertNetwork(NET_1, net_1_attrs)
self.assertNetwork(NET_2, net_2_attrs)
def _create_net_attrs(self, nic, bridged, vlan_id=None):
attrs = {'nic': nic,
'bridged': bridged,
'switch': self.switch}
if vlan_id is not None:
attrs['vlan'] = vlan_id
return attrs<|fim▁hole|> __test__ = True
switch = 'legacy'
NET_CONF_DIR = '/etc/sysconfig/network-scripts/'
NET_CONF_PREF = NET_CONF_DIR + 'ifcfg-'
def test_add_net_based_on_device_with_non_standard_ifcfg_file(self):
if is_networkmanager_running():
self.skipTest('NetworkManager is running.')
with dummy_device() as nic:
NETCREATE = {NETWORK_NAME: {'nic': nic, 'switch': self.switch}}
NETREMOVE = {NETWORK_NAME: {'remove': True}}
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.setupNetworks(NETREMOVE, {}, NOCHK)
self.assertNoNetwork(NETWORK_NAME)
nic_ifcfg_file = self.NET_CONF_PREF + nic
self.assertTrue(os.path.exists(nic_ifcfg_file))
nic_ifcfg_badname_file = nic_ifcfg_file + 'tail123'
os.rename(nic_ifcfg_file, nic_ifcfg_badname_file)
# Up until now, we have set the test setup, now start the test.
with self.setupNetworks(NETCREATE, {}, NOCHK):
self.assertNetwork(NETWORK_NAME, NETCREATE[NETWORK_NAME])
self.assertTrue(os.path.exists(nic_ifcfg_file))
self.assertFalse(os.path.exists(nic_ifcfg_badname_file))
@attr(type='functional', switch='ovs')
class NetworkBasicOvsTest(NetworkBasicTemplate):
__test__ = True
switch = 'ovs'
@attr(type='functional', switch='legacy')
class NetworkManagerLegacyTest(NetFuncTestCase):
switch = 'legacy'
def setUp(self):
if not is_networkmanager_running():
self.skipTest('NetworkManager is not running.')
self.iface = iface_name()
def tearDown(self):
# The bond was acquired, therefore VDSM needs to clean it.
BONDREMOVE = {self.iface: {'remove': True}}
self.setupNetworks({}, BONDREMOVE, NOCHK)
def test_add_net_based_on_device_with_multiple_nm_connections(self):
IPv4_ADDRESS = '192.0.2.1'
NET = {NETWORK_NAME: {'bonding': self.iface, 'switch': self.switch}}
with dummy_devices(1) as nics:
with nm_connections(
self.iface, IPv4_ADDRESS, con_count=3, slaves=nics):
with self.setupNetworks(NET, {}, NOCHK):
self.assertNetwork(NETWORK_NAME, NET[NETWORK_NAME])
def test_add_net_based_on_existing_vlan_bond_nm_setup(self):
vlan_id = '101'
NET = {NETWORK_NAME: {'bonding': self.iface, 'vlan': int(vlan_id),
'switch': self.switch}}
with dummy_devices(1) as nics:
with nm_connections(
self.iface, ipv4addr=None, vlan=vlan_id, slaves=nics):
bond_hwaddress = link_iface.mac_address(self.iface)
vlan_iface = '.'.join([self.iface, vlan_id])
vlan_hwaddress = link_iface.mac_address(vlan_iface)
self.assertEqual(vlan_hwaddress, bond_hwaddress)
with self.setupNetworks(NET, {}, NOCHK):
self.assertNetwork(NETWORK_NAME, NET[NETWORK_NAME])
# Check if the mac has been preserved.
bridge_hwaddress = link_iface.mac_address(NETWORK_NAME)
self.assertEqual(vlan_hwaddress, bridge_hwaddress)<|fim▁end|> |
@attr(type='functional', switch='legacy')
class NetworkBasicLegacyTest(NetworkBasicTemplate): |
<|file_name|>TestRandIndex.java<|end_file_name|><|fim▁begin|>package personifiler.cluster;
import static org.junit.Assert.*;<|fim▁hole|>
/**
* Tests for {@link RandIndex}
*
* @author Allen Cheng
*/
public class TestRandIndex
{
/**
* Tests that the rand index of a cluster is between 0.0 and 1.0
*/
@Test
public void testRandIndex()
{
ClusterPeople cluster = new ClusterPeople(TestUtils.getSampleFeatureMatrix());
double randIndex = cluster.randIndex(TestUtils.getSampleGroundTruth());
assertTrue(randIndex >= 0.0 && randIndex <= 1.0);
}
}<|fim▁end|> |
import org.junit.Test;
import personifiler.util.TestUtils; |
<|file_name|>viewzodb.py<|end_file_name|><|fim▁begin|>##########################################################
# view the person ZODB database in PyForm's FormGui;
# FileDB maps indexing to db root, close does commit;
# caveat 1: FormGui doesn't yet allow mixed class types;
# caveat 2: FormGui has no way to call class methods;
# caveat 3: Persistent subclasses don't allow __class__
# to be set: must have defaults for all __init__ args;
# Person here works only if always defined in __main__;
##########################################################
import sys
filename = 'data/people-simple.fs'
from zodbtools import FileDB
from PP3E.Dbase.TableBrowser.formgui import FormGui
from PP3E.Dbase.TableBrowser.formtable import Table, InstanceRecord
class Person: pass
initrecs = {'bob': dict(name='bob', job='devel', pay=30),
'sue': dict(name='sue', job='music', pay=40)}
<|fim▁hole|>if len(sys.argv) > 1:
for key in dbtable.keys():
del dbtable[key] # "viewzodb.py -" inits db
dbtable.storeItems(initrecs) # "viewzodb.py" browses db
FormGui(dbtable).mainloop()
dbtable.printItems()
dbtable.close()<|fim▁end|> | dbtable = Table(FileDB(filename), InstanceRecord(Person))
|
<|file_name|>TransitionExampleGroupExplorer.js<|end_file_name|><|fim▁begin|>import React, { Component } from 'react'
import { Form, Grid, Image, Transition } from 'shengnian-ui-react'
const transitions = [
'scale',
'fade', 'fade up', 'fade down', 'fade left', 'fade right',
'horizontal flip', 'vertical flip',
'drop',
'fly left', 'fly right', 'fly up', 'fly down',
'swing left', 'swing right', 'swing up', 'swing down',
'browse', 'browse right',
'slide down', 'slide up', 'slide right',
]
const options = transitions.map(name => ({ key: name, text: name, value: name }))
export default class TransitionExampleSingleExplorer extends Component {
state = { animation: transitions[0], duration: 500, visible: true }
handleChange = (e, { name, value }) => this.setState({ [name]: value })
handleVisibility = () => this.setState({ visible: !this.state.visible })
render() {
const { animation, duration, visible } = this.state
return (
<Grid columns={2}>
<Grid.Column as={Form}>
<Form.Select
label='Choose transition'
name='animation'
onChange={this.handleChange}
options={options}
value={animation}
/>
<Form.Input
label={`Duration: ${duration}ms `}
min={100}
max={2000}
name='duration'
onChange={this.handleChange}
step={100}
type='range'
value={duration}
/><|fim▁hole|>
<Grid.Column>
<Transition.Group animation={animation} duration={duration}>
{visible && <Image centered size='small' src='/assets/images/leaves/4.png' />}
</Transition.Group>
</Grid.Column>
</Grid>
)
}
}<|fim▁end|> | <Form.Button content={visible ? 'Unmount' : 'Mount'} onClick={this.handleVisibility} />
</Grid.Column> |
<|file_name|>custom.js<|end_file_name|><|fim▁begin|>// Can also be used with $(document).ready()
jQuery(window).load(function() {<|fim▁hole|>});<|fim▁end|> | jQuery('.flexslider').flexslider({
animation: "slide"
}); |
<|file_name|>Partition.java<|end_file_name|><|fim▁begin|>/**
* Copyright (C) 2001-2016 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* 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 com.rapidminer.example.set;
import com.rapidminer.tools.LogService;
import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
/**
* Implements a partition. A partition is used to divide an example set into different parts of
* arbitrary sizes without actually make a copy of the data. Partitions are used by
* {@link SplittedExampleSet}s. Partition numbering starts at 0.
*
* @author Simon Fischer, Ingo Mierswa
*/
public class Partition implements Cloneable, Serializable {
private static final long serialVersionUID = 6126334515107973287L;
/** Mask for the selected partitions. */
private boolean[] mask;
/** Size of the individual partitions. */
private int[] partitionSizes;
/** Maps every example to its partition index. */
private int[] elements;
/** Indicates the position of the last element for each partition. */
<|fim▁hole|> */
private int[] tableIndexMap = null;
/**
* Creates a new partition of a given size consisting of <tt>ratio.length</tt> sets. The set
* <i>i</i> will be of size of <i>size x ratio[i]</i>, i.e. the sum of all <i>ratio[i]</i> must
* be 1. Initially all partitions are selected.
*/
public Partition(double ratio[], int size, PartitionBuilder builder) {
init(ratio, size, builder);
}
/**
* Creates a new partition of a given size consisting of <i>noPartitions</i> equally sized sets.
* Initially all partitions are selected.
*/
public Partition(int noPartitions, int size, PartitionBuilder builder) {
double[] ratio = new double[noPartitions];
for (int i = 0; i < ratio.length; i++) {
ratio[i] = 1 / (double) noPartitions;
}
init(ratio, size, builder);
}
/** Creates a partition from the given one. Partition numbering starts at 0. */
public Partition(int[] elements, int numberOfPartitions) {
init(elements, numberOfPartitions);
}
/** Clone constructor. */
private Partition(Partition p) {
this.partitionSizes = new int[p.partitionSizes.length];
System.arraycopy(p.partitionSizes, 0, this.partitionSizes, 0, p.partitionSizes.length);
this.mask = new boolean[p.mask.length];
System.arraycopy(p.mask, 0, this.mask, 0, p.mask.length);
this.elements = new int[p.elements.length];
System.arraycopy(p.elements, 0, this.elements, 0, p.elements.length);
this.lastElementIndex = new int[p.lastElementIndex.length];
System.arraycopy(p.lastElementIndex, 0, this.lastElementIndex, 0, p.lastElementIndex.length);
recalculateTableIndices();
}
/**
* Creates a partition from the given ratios. The partition builder is used for creation.
*/
private void init(double[] ratio, int size, PartitionBuilder builder) {
// LogService.getGlobal().log("Create new partition using a '" +
// builder.getClass().getName() + "'.", LogService.STATUS);
LogService.getRoot().log(Level.FINE, "com.rapidminer.example.set.Partition.creating_new_partition_using",
builder.getClass().getName());
elements = builder.createPartition(ratio, size);
init(elements, ratio.length);
}
/** Private initialization method used by constructors. */
private void init(int[] newElements, int noOfPartitions) {
// LogService.getGlobal().log("Create new partition with " + newElements.length +
// " elements and " + noOfPartitions + " partitions.",
// LogService.STATUS);
LogService.getRoot().log(Level.FINE, "com.rapidminer.example.set.Partition.creating_new_partition_with",
new Object[] { newElements.length, noOfPartitions });
partitionSizes = new int[noOfPartitions];
lastElementIndex = new int[noOfPartitions];
elements = newElements;
for (int i = 0; i < elements.length; i++) {
if (elements[i] >= 0) {
partitionSizes[elements[i]]++;
lastElementIndex[elements[i]] = i;
}
}
// select all partitions
mask = new boolean[noOfPartitions];
for (int i = 0; i < mask.length; i++) {
mask[i] = true;
}
recalculateTableIndices();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Partition)) {
return false;
}
Partition other = (Partition) o;
for (int i = 0; i < mask.length; i++) {
if (this.mask[i] != other.mask[i]) {
return false;
}
}
for (int i = 0; i < elements.length; i++) {
if (this.elements[i] != other.elements[i]) {
return false;
}
}
return true;
}
@Override
public int hashCode() {
int hc = 17;
int hashMultiplier = 59;
hc = hc * hashMultiplier + this.mask.length;
for (int i = 1; i < mask.length; i <<= 1) {
hc = hc * hashMultiplier + Boolean.valueOf(this.mask[i]).hashCode();
}
hc = hc * hashMultiplier + this.elements.length;
for (int i = 1; i < elements.length; i <<= 1) {
hc = hc * hashMultiplier + Integer.valueOf(this.elements[i]).hashCode();
}
return hc;
}
/**
* Returns true if the last possible index stored in lastElementIndex for all currently selected
* partitions is not yet reached. Might be used to prune iterations (especially useful for
* linear partitions).
*/
public boolean hasNext(int index) {
for (int p = 0; p < mask.length; p++) {
if (mask[p]) {
if (index <= lastElementIndex[p]) {
return true;
}
}
}
return false;
}
/** Clears the selection, i.e. deselects all subsets. */
public void clearSelection() {
this.mask = new boolean[mask.length];
recalculateTableIndices();
}
public void invertSelection() {
for (int i = 0; i < mask.length; i++) {
mask[i] = !mask[i];
}
recalculateTableIndices();
};
/** Marks the given subset as selected. */
public void selectSubset(int i) {
this.mask[i] = true;
recalculateTableIndices();
}
/** Marks the given subset as deselected. */
public void deselectSubset(int i) {
this.mask[i] = false;
recalculateTableIndices();
}
/** Returns the number of subsets. */
public int getNumberOfSubsets() {
return partitionSizes.length;
}
/** Returns the number of selected elements. */
public int getSelectionSize() {
int s = 0;
for (int i = 0; i < partitionSizes.length; i++) {
if (mask[i]) {
s += partitionSizes[i];
}
}
return s;
}
/** Returns the total number of examples. */
public int getTotalSize() {
return elements.length;
}
/**
* Returns true iff the example with the given index is selected according to the current
* selection mask.
*/
public boolean isSelected(int index) {
return mask[elements[index]];
}
/**
* Recalculates the example table indices of the currently selected examples.
*/
private void recalculateTableIndices() {
List<Integer> indices = new LinkedList<Integer>();
for (int i = 0; i < elements.length; i++) {
if (mask[elements[i]]) {
indices.add(i);
}
}
tableIndexMap = new int[indices.size()];
Iterator<Integer> i = indices.iterator();
int counter = 0;
while (i.hasNext()) {
tableIndexMap[counter++] = i.next();
}
}
/**
* Returns the actual example table index of the i-th example of the currently selected subset.
*/
public int mapIndex(int index) {
return tableIndexMap[index];
}
@Override
public String toString() {
StringBuffer str = new StringBuffer("(");
for (int i = 0; i < partitionSizes.length; i++) {
str.append((i != 0 ? "/" : "") + partitionSizes[i]);
}
str.append(")");
return str.toString();
}
@Override
public Object clone() {
return new Partition(this);
}
}<|fim▁end|> | private int[] lastElementIndex;
/**
* Maps every example index to the true index of the data row in the example table.
|
<|file_name|>index.js<|end_file_name|><|fim▁begin|>'use strict';
<|fim▁hole|> // forget to provide E1, that nobody is consuming
return {
// E1: function() {},
E2: function() {}
};
}<|fim▁end|> | module.exports = function setup(options, imports) { |
<|file_name|>at2om.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import argparse
import pydot
import os
__author__ = 'Shamal Faily'
def dotToObstacleModel(graph,contextName,originatorName):
goals = []
goalNames = set([])
obstacles = []
acs = {}
for node in graph.get_nodes():
nodeShape = node.get_shape()
nodeStyle = str(node.get_style())
if nodeShape == 'box' and nodeStyle == 'rounded':
obstacles.append(node.get_name())
elif nodeShape == 'box' and nodeStyle == 'None':
nodeName = node.get_name()
if (nodeName != 'node' and nodeName != 'edge'):
goals.append(node.get_name())
goalNames.add(node.get_name())
elif nodeShape == 'triangle':
acs[node.get_name()] = node.get_label()
xmlBuf = '<?xml version="1.0"?>\n<!DOCTYPE cairis_model PUBLIC "-//CAIRIS//DTD MODEL 1.0//EN" "http://cairis.org/dtd/cairis_model.dtd">\n\n<cairis_model>\n\n'
xmlBuf += '<cairis>\n <project_settings name="' + contextName + '">\n <contributors>\n <contributor first_name="None" surname="None" affiliation="' + originatorName + '" role="Scribe" />\n </contributors>\n </project_settings>\n <environment name="' + contextName + '" short_code="' + contextName + '">\n <definition>' + contextName + '</definition>\n <asset_values>\n <none>TBC</none>\n <low>TBC</low>\n <medium>TBC</medium>\n <high>TBC</high>\n </asset_values>\n </environment>\n</cairis>\n\n<goals>\n'
for g in goals:
xmlBuf += ' <goal name=' + g + ' originator="' + originatorName + '">\n <goal_environment name="' + contextName + '" category="Maintain" priority="Medium">\n <definition>' + g + '</definition>\n <fit_criterion>TBC</fit_criterion>\n <issue>None</issue>\n </goal_environment>\n </goal>\n'
for o in obstacles:
xmlBuf += ' <obstacle name=' + o + ' originator="' + originatorName + '">\n <obstacle_environment name="' + contextName + '" category="Threat">\n <definition>' + o + '</definition>\n </obstacle_environment>\n </obstacle>\n'
xmlBuf += '</goals>\n\n'
fromAssocs = []
toAssocs = {}
assocs = []
for e in graph.get_edge_list():<|fim▁hole|> fromName = e.get_source()
toName = e.get_destination()
if fromName in acs:
if fromName not in toAssocs:
toAssocs[fromName] = [toName]
else:
toAssocs[fromName].append(toName)
elif toName in acs:
fromAssocs.append((fromName,toName))
else:
if fromName in goalNames:
assocs.append(' <goal_association environment="' + contextName + '" goal_name=' + fromName + ' goal_dim="goal" ref_type="obstruct" subgoal_name=' + toName + ' subgoal_dim="obstacle" alternative_id="0">\n <rationale>None</rationale>\n </goal_association>\n')
else:
assocs.append(' <goal_association environment="' + contextName + '" goal_name=' + fromName + ' goal_dim="obstacle" ref_type="resolve" subgoal_name=' + toName + ' subgoal_dim="goal" alternative_id="0">\n <rationale>None</rationale>\n </goal_association>\n')
for fromName,toName in fromAssocs:
for subGoalName in toAssocs[toName]:
assocs.append(' <goal_association environment="' + contextName + '" goal_name=' + fromName + ' goal_dim="obstacle" ref_type=' + acs[toName] + ' subgoal_name=' + subGoalName + ' subgoal_dim="obstacle" alternative_id="0">\n <rationale>None</rationale>\n </goal_association>\n')
xmlBuf += '<associations>\n'
for assoc in assocs:
xmlBuf += assoc
xmlBuf += '</associations>\n\n</cairis_model>'
return xmlBuf
def main(args=None):
parser = argparse.ArgumentParser(description='Attack Tree to CAIRIS Model converter')
parser.add_argument('dotFile',help='attack tree model to import (Dot format)')
parser.add_argument('--context',dest='contextName',help='attack context')
parser.add_argument('--author',dest='originatorName',help='author/s')
parser.add_argument('--out',dest='outFile',help='output file (CAIRIS format)')
args = parser.parse_args()
dotInstance = pydot.graph_from_dot_file(args.dotFile)
xmlBuf = dotToObstacleModel(dotInstance[0],args.contextName,args.originatorName)
f = open(args.outFile,'w')
f.write(xmlBuf)
f.close()
if __name__ == '__main__':
main()<|fim▁end|> | |
<|file_name|>msvst_starlet.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# References:
# [1] Jean-Luc Starck, Fionn Murtagh & Jalal M. Fadili
# Sparse Image and Signal Processing: Wavelets, Curvelets, Morphological Diversity
# Section 3.5, 6.6
#
# Credits:
# [1] https://github.com/abrazhe/image-funcut/blob/master/imfun/atrous.py
#
# Aaron LI
# Created: 2016-03-17
# Updated: 2016-04-22
#
# ChangeLog:
# 2016-04-22:
# * Add argument "end-scale" to specifiy the end denoising scale
# * Check outfile existence first
# * Add argument "start-scale" to specifiy the start denoising scale
# * Fix a bug about "p_cutoff" when "comp" contains ALL False's
# * Show more verbose information/details
# 2016-04-20:
# * Add argparse and main() for scripting
#
"""
Starlet wavelet transform, i.e., isotropic undecimated wavelet transform
(IUWT), or à trous wavelet transform.
And multi-scale variance stabling transform (MS-VST), which can be used
to effectively remove the Poisson noises.
"""
__version__ = "0.2.5"
__date__ = "2016-04-22"
import sys
import os
import argparse
from datetime import datetime
import numpy as np
import scipy as sp
from scipy import signal
from astropy.io import fits
class B3Spline: # {{{
"""
B3-spline wavelet.
"""
# scaling function (phi)
dec_lo = np.array([1.0, 4.0, 6.0, 4.0, 1.0]) / 16
dec_hi = np.array([-1.0, -4.0, 10.0, -4.0, -1.0]) / 16
rec_lo = np.array([0.0, 0.0, 1.0, 0.0, 0.0])
rec_hi = np.array([0.0, 0.0, 1.0, 0.0, 0.0])
# B3Spline }}}
class IUWT: # {{{
"""
Isotropic undecimated wavelet transform.
"""
## Decomposition filters list:
# a_{scale} = convole(a_0, filters[scale])
# Note: the zero-th scale filter (i.e., delta function) is the first
# element, thus the array index is the same as the decomposition scale.
filters = []
phi = None # wavelet scaling function (2D)
level = 0 # number of transform level
decomposition = None # decomposed coefficients/images
reconstruction = None # reconstructed image
# convolution boundary condition
boundary = "symm"
def __init__(self, phi=B3Spline.dec_lo, level=None, boundary="symm",
data=None):
self.set_wavelet(phi=phi)
self.level = level
self.boundary = boundary
self.data = np.array(data)
def reset(self):
"""
Reset the object attributes.
"""
self.data = None
self.phi = None
self.decomposition = None
self.reconstruction = None
self.level = 0
self.filters = []
self.boundary = "symm"
def load_data(self, data):
self.reset()
self.data = np.array(data)
def set_wavelet(self, phi):
self.reset()
phi = np.array(phi)
if phi.ndim == 1:
phi_ = phi.reshape(1, -1)
self.phi = np.dot(phi_.T, phi_)
elif phi.ndim == 2:
self.phi = phi
else:
raise ValueError("Invalid phi dimension")
def calc_filters(self):
"""
Calculate the convolution filters of each scale.
Note: the zero-th scale filter (i.e., delta function) is the first
element, thus the array index is the same as the decomposition scale.
"""
self.filters = []
# scale 0: delta function
h = np.array([[1]]) # NOTE: 2D
self.filters.append(h)
# scale 1
h = self.phi[::-1, ::-1]
self.filters.append(h)
for scale in range(2, self.level+1):
h_up = self.zupsample(self.phi, order=scale-1)
h2 = signal.convolve2d(h_up[::-1, ::-1], h, mode="same",
boundary=self.boundary)
self.filters.append(h2)
def transform(self, data, scale, boundary="symm"):
"""
Perform only one scale wavelet transform for the given data.
return:
[ approx, detail ]
"""
self.decomposition = []
approx = signal.convolve2d(data, self.filters[scale],
mode="same", boundary=self.boundary)
detail = data - approx
return [approx, detail]
def decompose(self, level, boundary="symm"):
"""
Perform IUWT decomposition in the plain loop way.
The filters of each scale/level are calculated first, then the
approximations of each scale/level are calculated by convolving the
raw/finest image with these filters.
return:
[ W_1, W_2, ..., W_n, A_n ]
n = level
W: wavelet details
A: approximation<|fim▁hole|> if self.level != level or self.filters == []:
self.level = level
self.calc_filters()
self.decomposition = []
approx = self.data
for scale in range(1, level+1):
# approximation:
approx2 = signal.convolve2d(self.data, self.filters[scale],
mode="same", boundary=self.boundary)
# wavelet details:
w = approx - approx2
self.decomposition.append(w)
if scale == level:
self.decomposition.append(approx2)
approx = approx2
return self.decomposition
def decompose_recursive(self, level, boundary="symm"):
"""
Perform the IUWT decomposition in the recursive way.
return:
[ W_1, W_2, ..., W_n, A_n ]
n = level
W: wavelet details
A: approximation
"""
self.level = level
self.boundary = boundary
self.decomposition = self.__decompose(self.data, self.phi, level=level)
return self.decomposition
def __decompose(self, data, phi, level):
"""
2D IUWT decomposition (or stationary wavelet transform).
This is a convolution version, where kernel is zero-upsampled
explicitly. Not fast.
Parameters:
- level : level of decomposition
- phi : low-pass filter kernel
- boundary : boundary conditions (passed to scipy.signal.convolve2d,
'symm' by default)
Returns:
list of wavelet details + last approximation. Each element in
the list is an image of the same size as the input image.
"""
if level <= 0:
return data
shapecheck = map(lambda a,b:a>b, data.shape, phi.shape)
assert np.all(shapecheck)
# approximation:
approx = signal.convolve2d(data, phi[::-1, ::-1], mode="same",
boundary=self.boundary)
# wavelet details:
w = data - approx
phi_up = self.zupsample(phi, order=1)
shapecheck = map(lambda a,b:a>b, data.shape, phi_up.shape)
if level == 1:
return [w, approx]
elif not np.all(shapecheck):
print("Maximum allowed decomposition level reached",
file=sys.stderr)
return [w, approx]
else:
return [w] + self.__decompose(approx, phi_up, level-1)
@staticmethod
def zupsample(data, order=1):
"""
Upsample data array by interleaving it with zero's.
h{up_order: n}[l] = (1) h[l], if l % 2^n == 0;
(2) 0, otherwise
"""
shape = data.shape
new_shape = [ (2**order * (n-1) + 1) for n in shape ]
output = np.zeros(new_shape, dtype=data.dtype)
output[[ slice(None, None, 2**order) for d in shape ]] = data
return output
def reconstruct(self, decomposition=None):
if decomposition is not None:
reconstruction = np.sum(decomposition, axis=0)
return reconstruction
else:
self.reconstruction = np.sum(self.decomposition, axis=0)
def get_detail(self, scale):
"""
Get the wavelet detail coefficients of given scale.
Note: 1 <= scale <= level
"""
if scale < 1 or scale > self.level:
raise ValueError("Invalid scale")
return self.decomposition[scale-1]
def get_approx(self):
"""
Get the approximation coefficients of the largest scale.
"""
return self.decomposition[-1]
# IUWT }}}
class IUWT_VST(IUWT): # {{{
"""
IUWT with Multi-scale variance stabling transform.
Refernce:
[1] Bo Zhang, Jalal M. Fadili & Jean-Luc Starck,
IEEE Trans. Image Processing, 17, 17, 2008
"""
# VST coefficients and the corresponding asymptotic standard deviation
# of each scale.
vst_coef = []
def reset(self):
super(self.__class__, self).reset()
vst_coef = []
def __decompose(self):
raise AttributeError("No '__decompose' attribute")
@staticmethod
def soft_threshold(data, threshold):
if isinstance(data, np.ndarray):
data_th = data.copy()
data_th[np.abs(data) <= threshold] = 0.0
data_th[data > threshold] -= threshold
data_th[data < -threshold] += threshold
else:
data_th = data
if np.abs(data) <= threshold:
data_th = 0.0
elif data > threshold:
data_th -= threshold
else:
data_th += threshold
return data_th
def tau(self, k, scale):
"""
Helper function used in VST coefficients calculation.
"""
return np.sum(np.power(self.filters[scale], k))
def filters_product(self, scale1, scale2):
"""
Calculate the scalar product of the filters of two scales,
considering only the overlapped part.
Helper function used in VST coefficients calculation.
"""
if scale1 > scale2:
filter_big = self.filters[scale1]
filter_small = self.filters[scale2]
else:
filter_big = self.filters[scale2]
filter_small = self.filters[scale1]
# crop the big filter to match the size of the small filter
size_big = filter_big.shape
size_small = filter_small.shape
size_diff2 = list(map(lambda a,b: (a-b)//2, size_big, size_small))
filter_big_crop = filter_big[
size_diff2[0]:(size_big[0]-size_diff2[0]),
size_diff2[1]:(size_big[1]-size_diff2[1])]
assert(np.all(list(map(lambda a,b: a==b,
size_small, filter_big_crop.shape))))
product = np.sum(filter_small * filter_big_crop)
return product
def calc_vst_coef(self):
"""
Calculate the VST coefficients and the corresponding
asymptotic standard deviation of each scale, according to the
calculated filters of each scale/level.
"""
self.vst_coef = []
for scale in range(self.level+1):
b = 2 * np.sqrt(np.abs(self.tau(1, scale)) / self.tau(2, scale))
c = 7.0*self.tau(2, scale) / (8.0*self.tau(1, scale)) - \
self.tau(3, scale) / (2.0*self.tau(2, scale))
if scale == 0:
std = -1.0
else:
std = np.sqrt((self.tau(2, scale-1) / \
(4 * self.tau(1, scale-1)**2)) + \
(self.tau(2, scale) / (4 * self.tau(1, scale)**2)) - \
(self.filters_product(scale-1, scale) / \
(2 * self.tau(1, scale-1) * self.tau(1, scale))))
self.vst_coef.append({ "b": b, "c": c, "std": std })
def vst(self, data, scale, coupled=True):
"""
Perform variance stabling transform
XXX: parameter `coupled' why??
Credit: MSVST-V1.0/src/libmsvst/B3VSTAtrous.h
"""
self.vst_coupled = coupled
if self.vst_coef == []:
self.calc_vst_coef()
if coupled:
b = 1.0
else:
b = self.vst_coef[scale]["b"]
data_vst = b * np.sqrt(np.abs(data + self.vst_coef[scale]["c"]))
return data_vst
def ivst(self, data, scale, cbias=True):
"""
Inverse variance stabling transform
NOTE: assuming that `a_{j} + c^{j}' are all positive.
XXX: parameter `cbias' why??
`bias correction' is recommended while reconstruct the data
after estimation
Credit: MSVST-V1.0/src/libmsvst/B3VSTAtrous.h
"""
self.vst_cbias = cbias
if cbias:
cb = 1.0 / (self.vst_coef[scale]["b"] ** 2)
else:
cb = 0.0
data_ivst = data ** 2 + cb - self.vst_coef[scale]["c"]
return data_ivst
def is_significant(self, scale, fdr=0.1, independent=False, verbose=False):
"""
Multiple hypothesis testing with false discovery rate (FDR) control.
`independent': whether the test statistics of all the null
hypotheses are independent.
If `independent=True': FDR <= (m0/m) * q
otherwise: FDR <= (m0/m) * q * (1 + 1/2 + 1/3 + ... + 1/m)
References:
[1] False discovery rate - Wikipedia
https://en.wikipedia.org/wiki/False_discovery_rate
"""
coef = self.get_detail(scale)
std = self.vst_coef[scale]["std"]
pvalues = 2.0 * (1.0 - sp.stats.norm.cdf(np.abs(coef) / std))
p_sorted = pvalues.flatten()
p_sorted.sort()
N = len(p_sorted)
if independent:
cn = 1.0
else:
cn = np.sum(1.0 / np.arange(1, N+1))
p_comp = fdr * np.arange(N) / (N * cn)
comp = (p_sorted < p_comp)
if np.sum(comp) == 0:
# `comp' contains ALL False
p_cutoff = 0.0
else:
# cutoff p-value after FDR control/correction
p_cutoff = np.max(p_sorted[comp])
sig = (pvalues <= p_cutoff)
if verbose:
print("std/sigma: %g, p_cutoff: %g" % (std, p_cutoff),
flush=True, file=sys.stderr)
return (sig, p_cutoff)
def denoise(self, fdr=0.1, fdr_independent=False, start_scale=1,
end_scale=None, verbose=False):
"""
Denoise the wavelet coefficients by controlling FDR.
"""
self.fdr = fdr
self.fdr_indepent = fdr_independent
self.denoised = []
# supports of significant coefficients of each scale
self.sig_supports = [None] # make index match the scale
self.p_cutoff = [None]
if verbose:
print("MSVST denosing ...", flush=True, file=sys.stderr)
for scale in range(1, self.level+1):
coef = self.get_detail(scale)
if verbose:
print("\tScale %d: " % scale, end="",
flush=True, file=sys.stderr)
if (scale < start_scale) or \
((end_scale is not None) and scale > end_scale):
if verbose:
print("skipped", flush=True, file=sys.stderr)
sig, p_cutoff = None, None
else:
sig, p_cutoff = self.is_significant(scale, fdr=fdr,
independent=fdr_independent, verbose=verbose)
coef[np.logical_not(sig)] = 0.0
#
self.denoised.append(coef)
self.sig_supports.append(sig)
self.p_cutoff.append(p_cutoff)
# append the last approximation
self.denoised.append(self.get_approx())
def decompose(self, level=5, boundary="symm", verbose=False):
"""
2D IUWT decomposition with VST.
"""
self.boundary = boundary
if self.level != level or self.filters == []:
self.level = level
self.calc_filters()
self.calc_vst_coef()
self.decomposition = []
approx = self.data
if verbose:
print("IUWT decomposing (%d levels): " % level,
end="", flush=True, file=sys.stderr)
for scale in range(1, level+1):
if verbose:
print("%d..." % scale, end="", flush=True, file=sys.stderr)
# approximation:
approx2 = signal.convolve2d(self.data, self.filters[scale],
mode="same", boundary=self.boundary)
# wavelet details:
w = self.vst(approx, scale=scale-1) - self.vst(approx2, scale=scale)
self.decomposition.append(w)
if scale == level:
self.decomposition.append(approx2)
approx = approx2
if verbose:
print("DONE!", flush=True, file=sys.stderr)
return self.decomposition
def reconstruct_ivst(self, denoised=True, positive_project=True):
"""
Reconstruct the original image from the *un-denoised* decomposition
by applying the inverse VST.
This reconstruction result is also used as the `initial condition'
for the below `iterative reconstruction' algorithm.
arguments:
* denoised: whether use th denoised data or the direct decomposition
* positive_project: whether replace negative values with zeros
"""
if denoised:
decomposition = self.denoised
else:
decomposition = self.decomposition
self.positive_project = positive_project
details = np.sum(decomposition[:-1], axis=0)
approx = self.vst(decomposition[-1], scale=self.level)
reconstruction = self.ivst(approx+details, scale=0)
if positive_project:
reconstruction[reconstruction < 0.0] = 0.0
self.reconstruction = reconstruction
return reconstruction
def reconstruct(self, denoised=True, niter=10, verbose=False):
"""
Reconstruct the original image using iterative method with
L1 regularization, because the denoising violates the exact inverse
procedure.
arguments:
* denoised: whether use the denoised coefficients
* niter: number of iterations
"""
if denoised:
decomposition = self.denoised
else:
decomposition = self.decomposition
# L1 regularization
lbd = 1.0
delta = lbd / (niter - 1)
# initial solution
solution = self.reconstruct_ivst(denoised=denoised,
positive_project=True)
#
iuwt = IUWT(level=self.level)
iuwt.calc_filters()
# iterative reconstruction
if verbose:
print("Iteratively reconstructing (%d times): " % niter,
end="", flush=True, file=sys.stderr)
for i in range(niter):
if verbose:
print("%d..." % i, end="", flush=True, file=sys.stderr)
tempd = self.data.copy()
solution_decomp = []
for scale in range(1, self.level+1):
approx, detail = iuwt.transform(tempd, scale)
approx_sol, detail_sol = iuwt.transform(solution, scale)
# Update coefficients according to the significant supports,
# which are acquired during the denosing precodure with FDR.
sig = self.sig_supports[scale]
detail_sol[sig] = detail[sig]
detail_sol = self.soft_threshold(detail_sol, threshold=lbd)
#
solution_decomp.append(detail_sol)
tempd = approx.copy()
solution = approx_sol.copy()
# last approximation (the two are the same)
solution_decomp.append(approx)
# reconstruct
solution = iuwt.reconstruct(decomposition=solution_decomp)
# discard all negative values
solution[solution < 0] = 0.0
#
lbd -= delta
if verbose:
print("DONE!", flush=True, file=sys.stderr)
#
self.reconstruction = solution
return self.reconstruction
# IUWT_VST }}}
def main():
# commandline arguments parser
parser = argparse.ArgumentParser(
description="Poisson Noise Removal with Multi-scale Variance " + \
"Stabling Transform and Wavelet Transform",
epilog="Version: %s (%s)" % (__version__, __date__))
parser.add_argument("-l", "--level", dest="level",
type=int, default=5,
help="level of the IUWT decomposition")
parser.add_argument("-r", "--fdr", dest="fdr",
type=float, default=0.1,
help="false discovery rate")
parser.add_argument("-I", "--fdr-independent", dest="fdr_independent",
action="store_true", default=False,
help="whether the FDR null hypotheses are independent")
parser.add_argument("-s", "--start-scale", dest="start_scale",
type=int, default=1,
help="which scale to start the denoising (inclusive)")
parser.add_argument("-e", "--end-scale", dest="end_scale",
type=int, default=0,
help="which scale to end the denoising (inclusive)")
parser.add_argument("-n", "--niter", dest="niter",
type=int, default=10,
help="number of iterations for reconstruction")
parser.add_argument("-v", "--verbose", dest="verbose",
action="store_true", default=False,
help="show verbose progress")
parser.add_argument("-C", "--clobber", dest="clobber",
action="store_true", default=False,
help="overwrite output file if exists")
parser.add_argument("infile", help="input image with Poisson noises")
parser.add_argument("outfile", help="output denoised image")
args = parser.parse_args()
if args.end_scale == 0:
args.end_scale = args.level
if args.verbose:
print("infile: '%s'" % args.infile, file=sys.stderr)
print("outfile: '%s'" % args.outfile, file=sys.stderr)
print("level: %d" % args.level, file=sys.stderr)
print("fdr: %.2f" % args.fdr, file=sys.stderr)
print("fdr_independent: %s" % args.fdr_independent, file=sys.stderr)
print("start_scale: %d" % args.start_scale, file=sys.stderr)
print("end_scale: %d" % args.end_scale, file=sys.stderr)
print("niter: %d\n" % args.niter, flush=True, file=sys.stderr)
if not args.clobber and os.path.exists(args.outfile):
raise OSError("outfile '%s' already exists" % args.outfile)
imgfits = fits.open(args.infile)
img = imgfits[0].data
# Remove Poisson noises
msvst = IUWT_VST(data=img)
msvst.decompose(level=args.level, verbose=args.verbose)
msvst.denoise(fdr=args.fdr, fdr_independent=args.fdr_independent,
start_scale=args.start_scale, end_scale=args.end_scale,
verbose=args.verbose)
msvst.reconstruct(denoised=True, niter=args.niter, verbose=args.verbose)
img_denoised = msvst.reconstruction
# Output
imgfits[0].data = img_denoised
imgfits[0].header.add_history("%s: Removed Poisson Noises @ %s" % (
os.path.basename(sys.argv[0]), datetime.utcnow().isoformat()))
imgfits[0].header.add_history(" TOOL: %s (v%s, %s)" % (
os.path.basename(sys.argv[0]), __version__, __date__))
imgfits[0].header.add_history(" PARAM: %s" % " ".join(sys.argv[1:]))
imgfits.writeto(args.outfile, checksum=True, clobber=args.clobber)
if __name__ == "__main__":
main()<|fim▁end|> | """
self.boundary = boundary |
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>use std::env;
use std::fs::File;
use std::io::Read;
use std::path::Path;
enum Lang {
Python,
Unknown,
}
struct CommentDelimiters {
begin: &'static str,
end: &'static str,
}
fn main() {
let fname = env::args().nth(1).unwrap();
let lang = lang_guess(&fname);
let delims = comment_delims(lang);
let path = Path::new(&fname);
let f = File::open(path);
match f {
Ok(mut fr) => {
let mut s = String::new();
fr.read_to_string(&mut s);
let v = reduce_to_comments(s, delims);
println!("_");
},
Err(_) => { },
}
}
fn lang_guess(s: &String) -> Lang {
let path = Path::new(&s);
let ext = path.extension();
match ext {
Some(x) => {
let y = x.to_str().unwrap();
match y {
"py" => Lang::Python,
_ => Lang::Unknown,
}
},
None => Lang::Unknown,
}
}
fn comment_delims(lang: Lang) -> CommentDelimiters {
match lang {
Lang::Python => CommentDelimiters { begin: "#", end: "\n" },
_ => CommentDelimiters { begin: "", end: "" },
}
}
<|fim▁hole|><|fim▁end|> | fn reduce_to_comments(s: String, ds: CommentDelimiters) -> Vec<String> {
vec![]
} |
<|file_name|>get_pushrule_enabled.rs<|end_file_name|><|fim▁begin|>//! [GET /_matrix/client/r0/pushrules/{scope}/{kind}/{ruleId}/enabled](https://matrix.org/docs/spec/client_server/r0.6.0#get-matrix-client-r0-pushrules-scope-kind-ruleid-enabled)
use ruma_api::ruma_api;
use super::RuleKind;
ruma_api! {
metadata {
description: "This endpoint gets whether the specified push rule is enabled.",
method: GET,
name: "get_pushrule_enabled",
path: "/_matrix/client/r0/pushrules/:scope/:kind/:rule_id/enabled",
rate_limited: false,
requires_authentication: true,
}
request {
/// The scope to fetch a rule from. 'global' to specify global rules.
#[ruma_api(path)]
pub scope: String,
/// The kind of rule
#[ruma_api(path)]
pub kind: RuleKind,
/// The identifier for the rule.
#[ruma_api(path)]
pub rule_id: String,
}<|fim▁hole|> }
error: crate::Error
}<|fim▁end|> |
response {
/// Whether the push rule is enabled or not.
pub enabled: bool |
<|file_name|>domtokenlist.rs<|end_file_name|><|fim▁begin|>/* 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 https://mozilla.org/MPL/2.0/. */
use crate::dom::attr::Attr;
use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding;
use crate::dom::bindings::codegen::Bindings::DOMTokenListBinding::DOMTokenListMethods;
use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::{Dom, DomRoot};
use crate::dom::bindings::str::DOMString;
use crate::dom::element::Element;
use crate::dom::node::window_from_node;
use dom_struct::dom_struct;
use html5ever::LocalName;
use servo_atoms::Atom;
use style::str::HTML_SPACE_CHARACTERS;
#[dom_struct]
pub struct DOMTokenList {
reflector_: Reflector,
element: Dom<Element>,
local_name: LocalName,
}
impl DOMTokenList {
pub fn new_inherited(element: &Element, local_name: LocalName) -> DOMTokenList {
DOMTokenList {
reflector_: Reflector::new(),
element: Dom::from_ref(element),
local_name: local_name,
}
}
pub fn new(element: &Element, local_name: &LocalName) -> DomRoot<DOMTokenList> {
let window = window_from_node(element);
reflect_dom_object(
Box::new(DOMTokenList::new_inherited(element, local_name.clone())),
&*window,
DOMTokenListBinding::Wrap,
)
}
fn attribute(&self) -> Option<DomRoot<Attr>> {
self.element.get_attribute(&ns!(), &self.local_name)
}
fn check_token_exceptions(&self, token: &str) -> Fallible<Atom> {
match token {
"" => Err(Error::Syntax),
slice if slice.find(HTML_SPACE_CHARACTERS).is_some() => Err(Error::InvalidCharacter),
slice => Ok(Atom::from(slice)),
}
}
}
// https://dom.spec.whatwg.org/#domtokenlist<|fim▁hole|>impl DOMTokenListMethods for DOMTokenList {
// https://dom.spec.whatwg.org/#dom-domtokenlist-length
fn Length(&self) -> u32 {
self.attribute()
.map_or(0, |attr| attr.value().as_tokens().len()) as u32
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-item
fn Item(&self, index: u32) -> Option<DOMString> {
self.attribute().and_then(|attr| {
// FIXME(ajeffrey): Convert directly from Atom to DOMString
attr.value()
.as_tokens()
.get(index as usize)
.map(|token| DOMString::from(&**token))
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-contains
fn Contains(&self, token: DOMString) -> bool {
let token = Atom::from(token);
self.attribute().map_or(false, |attr| {
attr.value()
.as_tokens()
.iter()
.any(|atom: &Atom| *atom == token)
})
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-add
fn Add(&self, tokens: Vec<DOMString>) -> ErrorResult {
let mut atoms = self.element.get_tokenlist_attribute(&self.local_name);
for token in &tokens {
let token = self.check_token_exceptions(&token)?;
if !atoms.iter().any(|atom| *atom == token) {
atoms.push(token);
}
}
self.element
.set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-remove
fn Remove(&self, tokens: Vec<DOMString>) -> ErrorResult {
let mut atoms = self.element.get_tokenlist_attribute(&self.local_name);
for token in &tokens {
let token = self.check_token_exceptions(&token)?;
atoms
.iter()
.position(|atom| *atom == token)
.map(|index| atoms.remove(index));
}
self.element
.set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(())
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-toggle
fn Toggle(&self, token: DOMString, force: Option<bool>) -> Fallible<bool> {
let mut atoms = self.element.get_tokenlist_attribute(&self.local_name);
let token = self.check_token_exceptions(&token)?;
match atoms.iter().position(|atom| *atom == token) {
Some(index) => match force {
Some(true) => Ok(true),
_ => {
atoms.remove(index);
self.element
.set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(false)
},
},
None => match force {
Some(false) => Ok(false),
_ => {
atoms.push(token);
self.element
.set_atomic_tokenlist_attribute(&self.local_name, atoms);
Ok(true)
},
},
}
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-value
fn Value(&self) -> DOMString {
self.element.get_string_attribute(&self.local_name)
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-value
fn SetValue(&self, value: DOMString) {
self.element
.set_tokenlist_attribute(&self.local_name, value);
}
// https://dom.spec.whatwg.org/#dom-domtokenlist-replace
fn Replace(&self, token: DOMString, new_token: DOMString) -> ErrorResult {
if token.is_empty() || new_token.is_empty() {
// Step 1.
return Err(Error::Syntax);
}
if token.contains(HTML_SPACE_CHARACTERS) || new_token.contains(HTML_SPACE_CHARACTERS) {
// Step 2.
return Err(Error::InvalidCharacter);
}
// Steps 3-4.
let token = Atom::from(token);
let new_token = Atom::from(new_token);
let mut atoms = self.element.get_tokenlist_attribute(&self.local_name);
if let Some(pos) = atoms.iter().position(|atom| *atom == token) {
if !atoms.contains(&new_token) {
atoms[pos] = new_token;
} else {
atoms.remove(pos);
}
// Step 5.
self.element
.set_atomic_tokenlist_attribute(&self.local_name, atoms);
}
Ok(())
}
// https://dom.spec.whatwg.org/#concept-dtl-serialize
fn Stringifier(&self) -> DOMString {
self.element.get_string_attribute(&self.local_name)
}
// check-tidy: no specs after this line
fn IndexedGetter(&self, index: u32) -> Option<DOMString> {
self.Item(index)
}
}<|fim▁end|> | |
<|file_name|>directiondictionaries.py<|end_file_name|><|fim▁begin|>from direction import Direction, Pivot
XMovement = {
Direction.left: -1,
Direction.up: 0,
Direction.right: 1,
Direction.down: 0,
Direction.up_left: -1,
Direction.up_right: 1,
Direction.down_left: -1,
Direction.down_right: 1
}
YMovement = {
Direction.left: 0,
Direction.up: -1,
Direction.right: 0,
Direction.down: 1,
Direction.up_left: -1,
Direction.up_right: -1,
Direction.down_left: 1,
Direction.down_right: 1
}
NewlineDirection = {
Direction.left: Direction.up,
Direction.up: Direction.right,
Direction.right: Direction.down,
Direction.down: Direction.left,
Direction.up_left: Direction.up_right,
Direction.up_right: Direction.down_right,
Direction.down_left: Direction.up_left,
Direction.down_right: Direction.down_left
}
NextDirection = {
Direction.left: Direction.up_left,
Direction.up: Direction.up_right,
Direction.right: Direction.down_right,
Direction.down: Direction.down_left,
Direction.up_left: Direction.up,
Direction.up_right: Direction.right,
Direction.down_left: Direction.left,
Direction.down_right: Direction.down
}
DirectionCharacters = {
Direction.left: "-",
Direction.up: "|",
Direction.right: "-",
Direction.down: "|",
Direction.up_left: "\\",
Direction.up_right: "/",
Direction.down_left: "/",
Direction.down_right: "\\"
}
PivotLookup = {
Pivot.left: {
Direction.left: Direction.down_left,
Direction.up: Direction.up_left,
Direction.right: Direction.up_right,
Direction.down: Direction.down_right,
Direction.up_left: Direction.left,
Direction.up_right: Direction.up,
Direction.down_left: Direction.down,
Direction.down_right: Direction.right
},
Pivot.right: {
Direction.left: Direction.up_left,
Direction.up: Direction.up_right,
Direction.right: Direction.down_right,
Direction.down: Direction.down_left,<|fim▁hole|> }
}
DirectionFromXYSigns = {
-1: {-1: Direction.up_left, 0: Direction.left, 1: Direction.down_left},
0: {-1: Direction.up, 0: Direction.right, 1: Direction.down},
1: {-1: Direction.up_right, 0: Direction.right, 1: Direction.down_right}
}<|fim▁end|> | Direction.up_left: Direction.up,
Direction.up_right: Direction.right,
Direction.down_left: Direction.left,
Direction.down_right: Direction.down |
<|file_name|>xmlhttprequesteventtarget.rs<|end_file_name|><|fim▁begin|>/* This Source Code Form is subject to the terms of the Mozilla Public<|fim▁hole|> * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::EventHandlerBinding::EventHandlerNonNull;
use dom::bindings::codegen::Bindings::XMLHttpRequestEventTargetBinding::XMLHttpRequestEventTargetMethods;
use dom::bindings::codegen::InheritTypes::EventTargetCast;
use dom::bindings::codegen::InheritTypes::XMLHttpRequestEventTargetDerived;
use dom::bindings::js::JSRef;
use dom::eventtarget::{EventTarget, EventTargetHelpers, EventTargetTypeId};
#[deriving(Copy, PartialEq)]
#[jstraceable]
pub enum XMLHttpRequestEventTargetTypeId {
XMLHttpRequest,
XMLHttpRequestUpload,
}
#[dom_struct]
pub struct XMLHttpRequestEventTarget {
eventtarget: EventTarget,
}
impl XMLHttpRequestEventTarget {
pub fn new_inherited(type_id: XMLHttpRequestEventTargetTypeId) -> XMLHttpRequestEventTarget {
XMLHttpRequestEventTarget {
eventtarget: EventTarget::new_inherited(EventTargetTypeId::XMLHttpRequestEventTarget(type_id))
}
}
#[inline]
pub fn eventtarget<'a>(&'a self) -> &'a EventTarget {
&self.eventtarget
}
}
impl XMLHttpRequestEventTargetDerived for EventTarget {
fn is_xmlhttprequesteventtarget(&self) -> bool {
match *self.type_id() {
EventTargetTypeId::XMLHttpRequestEventTarget(_) => true,
_ => false
}
}
}
impl<'a> XMLHttpRequestEventTargetMethods for JSRef<'a, XMLHttpRequestEventTarget> {
event_handler!(loadstart,GetOnloadstart, SetOnloadstart)
event_handler!(progress, GetOnprogress, SetOnprogress)
event_handler!(abort, GetOnabort, SetOnabort)
event_handler!(error, GetOnerror, SetOnerror)
event_handler!(load, GetOnload, SetOnload)
event_handler!(timeout, GetOntimeout, SetOntimeout)
event_handler!(loadend, GetOnloadend, SetOnloadend)
}<|fim▁end|> | * License, v. 2.0. If a copy of the MPL was not distributed with this |
<|file_name|>triangulation.rs<|end_file_name|><|fim▁begin|>//! Methods for converting shapes into triangles.
use ImageSize;
use interpolation::lerp;
use types::{
Line,
SourceRectangle,
Polygon,
Polygons,
Radius,
Rectangle,
Resolution,
};
use math::{
multiply,
orient,
translate,
Matrix2d,
Scalar,
Vec2d,
};
use radians::Radians;
/// Transformed x coordinate as f32.
#[inline(always)]
pub fn tx(m: Matrix2d, x: Scalar, y: Scalar) -> f32 {
(m[0][0] * x + m[0][1] * y + m[0][2]) as f32
}
/// Transformed y coordinate as f32.
#[inline(always)]
pub fn ty(m: Matrix2d, x: Scalar, y: Scalar) -> f32 {
(m[1][0] * x + m[1][1] * y + m[1][2]) as f32
}
/// Streams tweened polygons using linear interpolation.
#[inline(always)]
pub fn with_lerp_polygons_tri_list<F>(
m: Matrix2d,
polygons: Polygons,
tween_factor: Scalar,
f: F
)
where
F: FnMut(&[f32])
{
let poly_len = polygons.len() as Scalar;
// Map to interval between 0 and 1.
let tw = tween_factor % 1.0;
// Map negative values to positive.
let tw = if tw < 0.0 { tw + 1.0 } else { tw };
// Map to frame.
let tw = tw * poly_len;
// Get the current frame.
let frame = tw as usize;
// Get the next frame.
let next_frame = (frame + 1) % polygons.len();
let p0 = polygons[frame];
let p1 = polygons[next_frame];
// Get factor between frames.
let tw = tw - frame as Scalar;
let n = polygons[0].len();
let mut i: usize = 0;
stream_polygon_tri_list(m, || {
if i >= n { return None; }
let j = i;
i += 1;
Some(lerp(&p0[j], &p1[j], &tw))
}, f);
}
/// Streams an ellipse specified by a resolution.
#[inline(always)]
pub fn with_ellipse_tri_list<F>(
resolution: Resolution,
m: Matrix2d,
rect: Rectangle,
f: F
)
where
F: FnMut(&[f32])
{
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let (cw, ch) = (0.5 * w, 0.5 * h);
let (cx, cy) = (x + cw, y + ch);
let n = resolution;
let mut i = 0;
stream_polygon_tri_list(m, || {
if i >= n { return None; }
let angle = i as Scalar / n as Scalar * <Scalar as Radians>::_360();
i += 1;
Some([cx + angle.cos() * cw, cy + angle.sin() * ch])
}, f);
}
/// Streams a round border line.
#[inline(always)]
pub fn with_round_border_line_tri_list<F>(
resolution_cap: Resolution,
m: Matrix2d,
line: Line,
round_border_radius: Radius,
f: F
)
where
F: FnMut(&[f32])
{
let radius = round_border_radius;
let (x1, y1, x2, y2) = (line[0], line[1], line[2], line[3]);
let (dx, dy) = (x2 - x1, y2 - y1);
let w = (dx * dx + dy * dy).sqrt();
let m = multiply(m, translate([x1, y1]));
let m = multiply(m, orient(dx, dy));
let n = resolution_cap * 2;
let mut i = 0;
stream_polygon_tri_list(m, || {
if i >= n { return None; }
let j = i;
i += 1;
// Detect the half circle from index.
// There is one half circle at each end of the line.
// Together they form a full circle if
// the length of the line is zero.
match j {
j if j >= resolution_cap => {
// Compute the angle to match start and end
// point of half circle.
// This requires an angle offset since
// the other end of line is the first half circle.
let angle = (j - resolution_cap) as Scalar
/ (resolution_cap - 1) as Scalar * <Scalar as Radians>::_180()
+ <Scalar as Radians>::_180();
// Rotate 90 degrees since the line is horizontal.
let angle = angle + <Scalar as Radians>::_90();
Some([w + angle.cos() * radius, angle.sin() * radius])
},
j => {
// Compute the angle to match start and end
// point of half circle.
let angle = j as Scalar
/ (resolution_cap - 1) as Scalar
* <Scalar as Radians>::_180();
// Rotate 90 degrees since the line is horizontal.
let angle = angle + <Scalar as Radians>::_90();
Some([angle.cos() * radius, angle.sin() * radius])
},
}
}, f);
}
/// Streams a round rectangle.
#[inline(always)]
pub fn with_round_rectangle_tri_list<F>(
resolution_corner: Resolution,
m: Matrix2d,
rect: Rectangle,
round_radius: Radius,
f: F
)
where
F: FnMut(&[f32])
{
use vecmath::traits::{ FromPrimitive, Trig };
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let radius = round_radius;
let n = resolution_corner * 4;
let mut i = 0;
stream_polygon_tri_list(m, || {
if i >= n { return None; }
let j = i;
i += 1;
// Detect quarter circle from index.
// There is one quarter circle at each corner.
// Together they form a full circle if
// each side of rectangle is 2 times the radius.
match j {
j if j >= resolution_corner * 3 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since this
// is the last quarter.
let angle: Scalar = (j - resolution_corner * 3) as Scalar
/ (resolution_corner - 1) as Scalar
* <Scalar as Radians>::_90()
+ <Scalar as FromPrimitive>::from_f64(3.0)
* <Scalar as Radians>::_90();
// Set center of the circle to the last corner.
let (cx, cy) = (x + w - radius, y + radius);
Some([cx + angle.cos() * radius, cy + angle.sin() * radius])
},
j if j >= resolution_corner * 2 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since
// this is the second last quarter.
let angle = (j - resolution_corner * 2) as Scalar
/ (resolution_corner - 1) as Scalar
* <Scalar as Radians>::_90()
+ <Scalar as Radians>::_180();
// Set center of the circle to the second last corner.
let (cx, cy) = (x + radius, y + radius);
Some([cx + angle.cos() * radius, cy + angle.sin() * radius])
},
j if j >= resolution_corner * 1 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since
// this is the second quarter.
let angle = (j - resolution_corner) as Scalar
/ (resolution_corner - 1) as Scalar
* <Scalar as Radians>::_90()
+ <Scalar as Radians>::_90();
// Set center of the circle to the second corner.
let (cx, cy) = (x + radius, y + h - radius);
Some([cx + angle.cos() * radius, cy + angle.sin() * radius])
},
j => {
// Compute the angle to match start and end
// point of quarter circle.
let angle = j as Scalar
/ (resolution_corner - 1) as Scalar
* <Scalar as Radians>::_90();
// Set center of the circle to the first corner.
let (cx, cy) = (x + w - radius, y + h - radius);
Some([cx + angle.cos() * radius, cy + angle.sin() * radius])
},
}
}, f);
}
/// Streams a polygon into tri list.
/// Uses buffers that fit inside L1 cache.
///
/// `polygon` is a function that provides the vertices that comprise the polygon. Each
/// call to E will return a new vertex until there are none left.
///
/// `f` is a function that consumes the tri list constructed by the output of `polygon`,
/// one chunk (buffer) at a time.
///
/// Each chunk (buffer) is a fixed size array) of the format:
///
/// ```
/// // [x0, y0, x1, y1, x2, y2, x3, y3, ... y5, ...]
/// // ^--------------------^ ^------------^
/// // 3 Points of triangle 3 points of second triangle,
/// ```
///
/// Together all the chunks comprise the full tri list. Each time the buffer size is
/// reached, that chunk is fed to `f`, then this function proceeds using a new buffer
/// until a call to `polygon` returns `None`, indicating there are no points left in
/// the polygon. (in which case the last partially filled buffer is sent to `f`)
pub fn stream_polygon_tri_list<E, F>(
m: Matrix2d,
mut polygon: E,
mut f: F
)
where
E: FnMut() -> Option<Vec2d>,
F: FnMut(&[f32])
{
let mut vertices: [f32; 720] = [0.0; 720];
// Get the first point which will be used a lot.
let fp = match polygon() { None => return, Some(val) => val };
let (fx, fy) = (tx(m, fp[0], fp[1]), ty(m, fp[0], fp[1]));
let gp = match polygon() { None => return, Some(val) => val };
let (gx, gy) = (tx(m, gp[0], gp[1]), ty(m, gp[0], gp[1]));
let mut gx = gx;
let mut gy = gy;
let mut i = 0;
let vertices_per_triangle = 3;
let position_components_per_vertex = 2;
let align_vertices =
vertices_per_triangle
* position_components_per_vertex;
'read_vertices: loop {
let ind_out = i * align_vertices;
vertices[ind_out + 0] = fx;
vertices[ind_out + 1] = fy;
// Copy vertex.
let ind_out = i * align_vertices + 2;
let p =
match polygon() {
None => break 'read_vertices,
Some(val) => val,
};
let x = tx(m, p[0], p[1]);
let y = ty(m, p[0], p[1]);
vertices[ind_out + 0] = gx;
vertices[ind_out + 1] = gy;
vertices[ind_out + 2] = x;
vertices[ind_out + 3] = y;
gx = x;
gy = y;
i += 1;
// Buffer is full.
if i * align_vertices + 2 >= vertices.len() {
// Send chunk and start over.
f(&vertices[0..i * align_vertices]);
i = 0;
}
}
if i > 0 {
f(&vertices[0..i * align_vertices]);
}
}
/// Streams an ellipse border specified by a resolution.
#[inline(always)]
pub fn with_ellipse_border_tri_list<F>(
resolution: Resolution,
m: Matrix2d,
rect: Rectangle,
border_radius: Radius,
f: F
)
where
F: FnMut(&[f32])
{
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let (cw, ch) = (0.5 * w, 0.5 * h);
let (cw1, ch1) = (cw + border_radius, ch + border_radius);
let (cw2, ch2) = (cw - border_radius, ch - border_radius);
let (cx, cy) = (x + cw, y + ch);
let n = resolution;
let mut i = 0;
stream_quad_tri_list(m, || {
if i > n { return None; }
let angle = i as Scalar / n as Scalar * <Scalar as Radians>::_360();
let cos = angle.cos();
let sin = angle.sin();
i += 1;
Some(([cx + cos * cw1, cy + sin * ch1],
[cx + cos * cw2, cy + sin * ch2]))
}, f);
}
/// Streams an arc between the two radian boundaries.
#[inline(always)]
pub fn with_arc_tri_list<F>(
start_radians: Scalar,
end_radians: Scalar,
resolution: Resolution,
m: Matrix2d,
rect: Rectangle,
border_radius: Radius,
f: F
)
where
F: FnMut(&[f32])
{
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let (cw, ch) = (0.5 * w, 0.5 * h);
let (cw1, ch1) = (cw + border_radius, ch + border_radius);
let (cw2, ch2) = (cw - border_radius, ch - border_radius);
let (cx, cy) = (x + cw, y + ch);
let n = resolution;
let mut i = 0;
let (nearest_start_radians, nearest_end_radians) = if start_radians < end_radians {
(start_radians, start_radians + (end_radians - start_radians))
} else {
(end_radians, end_radians + (start_radians - end_radians))
};
stream_quad_tri_list(m, || {
if i > n { return None; }
let angle = nearest_start_radians
+ i as Scalar / n as Scalar * <Scalar as Radians>::_360();
if angle > nearest_end_radians {
return None;
}
let cos = angle.cos();
let sin = angle.sin();
i += 1;
Some(([cx + cos * cw1, cy + sin * ch1],
[cx + cos * cw2, cy + sin * ch2]))
}, f);
}
/// Streams a round rectangle border.
#[inline(always)]
pub fn with_round_rectangle_border_tri_list<F>(
resolution_corner: Resolution,
m: Matrix2d,
rect: Rectangle,
round_radius: Radius,
border_radius: Radius,
f: F
)
where
F: FnMut(&[f32])
{
use vecmath::traits::{ FromPrimitive, Trig };
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let radius = round_radius;
let radius1 = round_radius + border_radius;
let radius2 = round_radius - border_radius;
let n = resolution_corner * 4;
let mut i = 0;
stream_quad_tri_list(m, || {
if i > n { return None; }
let j = i;
i += 1;
// Detect quarter circle from index.
// There is one quarter circle at each corner.
// Together they form a full circle if
// each side of rectangle is 2 times the radius.
match j {
j if j == n => {
let (cx, cy) = (x + w - radius, y + h - radius);
Some(([cx + radius1, cy],
[cx + radius2, cy]))
},
j if j >= resolution_corner * 3 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since this
// is the last quarter.
let angle: Scalar = (j - resolution_corner * 3) as Scalar
/ (resolution_corner - 1) as Scalar
* <Scalar as Radians>::_90()
+ <Scalar as FromPrimitive>::from_f64(3.0)
* <Scalar as Radians>::_90();
// Set center of the circle to the last corner.
let (cx, cy) = (x + w - radius, y + radius);
let cos = angle.cos();
let sin = angle.sin();
Some(([cx + cos * radius1, cy + sin * radius1],
[cx + cos * radius2, cy + sin * radius2]))
},
j if j >= resolution_corner * 2 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since
// this is the second last quarter.
let angle = (j - resolution_corner * 2) as Scalar
/ (resolution_corner - 1) as Scalar
* <Scalar as Radians>::_90()
+ <Scalar as Radians>::_180();
// Set center of the circle to the second last corner.
let (cx, cy) = (x + radius, y + radius);
let cos = angle.cos();
let sin = angle.sin();
Some(([cx + cos * radius1, cy + sin * radius1],
[cx + cos * radius2, cy + sin * radius2]))
},
j if j >= resolution_corner * 1 => {
// Compute the angle to match start and end
// point of quarter circle.
// This requires an angle offset since
// this is the second quarter.
let angle = (j - resolution_corner) as Scalar
/ (resolution_corner - 1) as Scalar
* <Scalar as Radians>::_90()
+ <Scalar as Radians>::_90();
// Set center of the circle to the second corner.
let (cx, cy) = (x + radius, y + h - radius);
let cos = angle.cos();
let sin = angle.sin();
Some(([cx + cos * radius1, cy + sin * radius1],
[cx + cos * radius2, cy + sin * radius2]))
},
j => {
// Compute the angle to match start and end
// point of quarter circle.
let angle = j as Scalar
/ (resolution_corner - 1) as Scalar
* <Scalar as Radians>::_90();
// Set center of the circle to the first corner.
let (cx, cy) = (x + w - radius, y + h - radius);
let cos = angle.cos();
let sin = angle.sin();
Some(([cx + cos * radius1, cy + sin * radius1],
[cx + cos * radius2, cy + sin * radius2]))
},
}
}, f);
}
/// Streams a quad into tri list.
///
/// Uses buffers that fit inside L1 cache.
/// The 'quad_edge' stream returns two points
/// defining the next edge.
///
/// `quad_edge` is a function that returns two vertices, which together comprise
/// one edge of a quad
///
///
/// `f` is a function that consumes the tri list constructed by the output of
/// `quad_edge`, one chunk (buffer) at a time
///
/// The tri list is series of buffers (fixed size array) of the format:
///
/// ```
/// // [x0, y0, x1, y1, x2, y2, x3, y3, ... y5, ...]
/// // ^--------------------^ ^------------^
/// // 3 Points of triangle 3 points of second triangle,
/// // ^------------------------------------^ __
/// // Two triangles together form a single quad |\\ 2|
/// // |1\\ |
/// // |__\\|
/// ```
/// Together all the chunks comprise the full tri list. Each time the buffer size is
/// reached, that chunk is fed to `f`, then this function proceeds using a new buffer
/// until a call to `quad_edge` returns `None`, indicating there are no more edges left.
/// (in which case the last partially filled buffer is sent to `f`)
pub fn stream_quad_tri_list<E, F>(
m: Matrix2d,
mut quad_edge: E,
mut f: F
)
where
E: FnMut() -> Option<(Vec2d, Vec2d)>,
F: FnMut(&[f32])
{
let mut vertices: [f32; 720] = [0.0; 720];
// Get the two points .
let (fp1, fp2) = match quad_edge() {
None => return,
Some((val1, val2)) => (val1, val2)
};
// Transform the points using the matrix.
let (mut fx1, mut fy1) = (
tx(m, fp1[0], fp1[1]),
ty(m, fp1[0], fp1[1])
);
let (mut fx2, mut fy2) = (
tx(m, fp2[0], fp2[1]),
ty(m, fp2[0], fp2[1])
);
// Counts the quads.
let mut i = 0;
let triangles_per_quad = 2;
let vertices_per_triangle = 3;
let position_components_per_vertex = 2;
let align_vertices =
triangles_per_quad
* vertices_per_triangle
* position_components_per_vertex;
loop {
// Read two more points.
let (gp1, gp2) = match quad_edge() {
None => break,
Some((val1, val2)) => (val1, val2)
};
// Transform the points using the matrix.
let (gx1, gy1) = (
tx(m, gp1[0], gp1[1]),
ty(m, gp1[0], gp1[1])
);
let (gx2, gy2) = (
tx(m, gp2[0], gp2[1]),
ty(m, gp2[0], gp2[1])
);
let ind_out = i * align_vertices;
// First triangle.
vertices[ind_out + 0] = fx1;
vertices[ind_out + 1] = fy1;
vertices[ind_out + 2] = fx2;
vertices[ind_out + 3] = fy2;
vertices[ind_out + 4] = gx1;
vertices[ind_out + 5] = gy1;
// Second triangle.
vertices[ind_out + 6] = fx2;
vertices[ind_out + 7] = fy2;
vertices[ind_out + 8] = gx1;
vertices[ind_out + 9] = gy1;
vertices[ind_out + 10] = gx2;
vertices[ind_out + 11] = gy2;
// Next quad.<|fim▁hole|> fx1 = gx1;
fy1 = gy1;
fx2 = gx2;
fy2 = gy2;
// Buffer is full.
if i * align_vertices >= vertices.len() {
// Send chunk and start over.
f(&vertices[0..i * align_vertices]);
i = 0;
}
}
if i > 0 {
f(&vertices[0..i * align_vertices]);
}
}
/// Splits polygon into convex segments.
/// Create a buffer that fits into L1 cache with 1KB overhead.
///
/// See stream_polygon_tri_list docs for detailed explanation.
pub fn with_polygon_tri_list<F>(
m: Matrix2d,
polygon: Polygon,
f: F
)
where
F: FnMut(&[f32])
{
let n = polygon.len();
let mut i = 0;
stream_polygon_tri_list(
m, || {
if i >= n { return None; }
let j = i;
i += 1;
Some(polygon[j])
}, f
);
}
/// Creates triangle list vertices from rectangle.
#[inline(always)]
pub fn rect_tri_list_xy(
m: Matrix2d,
rect: Rectangle
) -> [f32; 12] {
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let (x2, y2) = (x + w, y + h);
[
tx(m,x,y), ty(m,x,y),
tx(m,x2,y), ty(m,x2,y),
tx(m,x,y2), ty(m,x,y2),
tx(m,x2,y), ty(m,x2,y),
tx(m,x2,y2), ty(m,x2,y2),
tx(m,x,y2), ty(m,x,y2)
]
}
/// Creates triangle list vertices from rectangle.
#[inline(always)]
pub fn rect_border_tri_list_xy(
m: Matrix2d,
rect: Rectangle,
border_radius: Radius,
) -> [f32; 48] {
let (x, y, w, h) = (rect[0], rect[1], rect[2], rect[3]);
let (w1, h1) = (w + border_radius, h + border_radius);
let (w2, h2) = (w - border_radius, h - border_radius);
let (x11, y11) = (x - border_radius, y - border_radius);
let (x21, y21) = (x + border_radius, y + border_radius);
let (x12, y12) = (x + w1, y + h1);
let (x22, y22) = (x + w2, y + h2);
[
tx(m, x11, y11), ty(m, x11, y11),
tx(m, x12, y11), ty(m, x12, y11),
tx(m, x21, y21), ty(m, x21, y21),
tx(m, x21, y21), ty(m, x21, y21),
tx(m, x12, y11), ty(m, x12, y11),
tx(m, x22, y21), ty(m, x22, y21),
tx(m, x22, y21), ty(m, x22, y21),
tx(m, x12, y11), ty(m, x12, y11),
tx(m, x12, y12), ty(m, x12, y12),
tx(m, x22, y21), ty(m, x22, y21),
tx(m, x12, y12), ty(m, x12, y12),
tx(m, x22, y22), ty(m, x22, y22),
tx(m, x12, y12), ty(m, x12, y12),
tx(m, x22, y22), ty(m, x22, y22),
tx(m, x11, y12), ty(m, x11, y12),
tx(m, x22, y22), ty(m, x22, y22),
tx(m, x11, y12), ty(m, x11, y12),
tx(m, x21, y22), ty(m, x21, y22),
tx(m, x11, y12), ty(m, x11, y12),
tx(m, x21, y21), ty(m, x21, y21),
tx(m, x21, y22), ty(m, x21, y22),
tx(m, x11, y12), ty(m, x11, y12),
tx(m, x11, y11), ty(m, x11, y11),
tx(m, x21, y21), ty(m, x21, y21),
]
}
/// Creates triangle list texture coords from image.
#[inline(always)]
pub fn rect_tri_list_uv<I: ImageSize>(
image: &I, source_rect: SourceRectangle
) -> [f32; 12] {
let (w, h) = image.get_size();
let (src_x, src_y, src_w, src_h) =
(source_rect[0], source_rect[1], source_rect[2], source_rect[3]);
let x1 = src_x as f32 / w as f32;
let y1 = src_y as f32 / h as f32;
let x2 = (src_w + src_x) as f32 / w as f32;
let y2 = (src_h + src_y) as f32 / h as f32;
[
x1, y1, x2, y1, x1, y2,
x2, y1, x2, y2, x1, y2
]
}<|fim▁end|> | i += 1;
// Set next current edge. |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='fcit',
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='1.2.0',
<|fim▁hole|> url = 'https://github.com/kjchalup/fcit',
# Author details
author = 'Krzysztof Chalupka',
author_email = '[email protected]',
# Choose your license
license='MIT',
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 3 - Alpha',
# Indicate who your project is intended for
'Intended Audience :: Science/Research',
'Topic :: Scientific/Engineering :: Artificial Intelligence',
# Pick your license as you wish (should match "license" above)
'License :: OSI Approved :: MIT License',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
# What does your project relate to?
keywords='machine learning statistics decision trees',
# You can just specify the packages manually here if your project is
# simple. Or you can use find_packages().
packages=find_packages(exclude=['contrib', 'docs', 'tests']),
# Alternatively, if you want to distribute just a my_module.py, uncomment
# this:
# py_modules=["my_module"],
# List run-time dependencies here. These will be installed by pip when
# your project is installed. For an analysis of "install_requires" vs pip's
# requirements files see:
# https://packaging.python.org/en/latest/requirements.html
install_requires=['numpy', 'sklearn', 'scipy', 'joblib'],
)<|fim▁end|> | description='A decision-tree based conditional independence test',
long_description=long_description,
# The project's main homepage. |
<|file_name|>rpi_io.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
import RPi.GPIO as GPIO
from models import session
from models import Device
from models import Module
from models import Event_Log
from time import sleep
from sys import stdout
# Modules pins and description
M1A = session.query(Module).filter(Module.name == 'M1A').first()
M1B = session.query(Module).filter(Module.name == 'M1B').first()
M1C = session.query(Module).filter(Module.name == 'M1C').first()
M2A = session.query(Module).filter(Module.name == 'M2A').first()
M2B = session.query(Module).filter(Module.name == 'M2B').first()
M2C = session.query(Module).filter(Module.name == 'M2C').first()
M3A = session.query(Module).filter(Module.name == 'M3A').first()
M3B = session.query(Module).filter(Module.name == 'M3B').first()
M3C = session.query(Module).filter(Module.name == 'M3C').first()
M4A = session.query(Module).filter(Module.name == 'M4A').first()
M4B = session.query(Module).filter(Module.name == 'M4B').first()
M4C = session.query(Module).filter(Module.name == 'M4C').first()
M5A = session.query(Module).filter(Module.name == 'M5A').first()
M5B = session.query(Module).filter(Module.name == 'M5B').first()
M5C = session.query(Module).filter(Module.name == 'M5C').first()
M6A = session.query(Module).filter(Module.name == 'M6A').first()
M6B = session.query(Module).filter(Module.name == 'M6B').first()
M6C = session.query(Module).filter(Module.name == 'M6C').first()
M7A = session.query(Module).filter(Module.name == 'M7A').first()
M7B = session.query(Module).filter(Module.name == 'M7B').first()
M7C = session.query(Module).filter(Module.name == 'M7C').first()
# Statup inputs BCM pin
input_pins = [0, 1, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25]
# Statup outputs BCM pin
output_pins = [26, 27]
def main():
# Set up GPIO using BCM numbering
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(26, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(27, GPIO.OUT, initial=GPIO.LOW)
def modo0():
for pin in input_pins:<|fim▁hole|> except:
print u"Erro de ativação do Pino BCM %s", pin
stdout.flush()
for pin in output_pins:
try:
GPIO.setup(pin, GPIO.OUT, initial=GPIO.LOW)
except:
print u"Erro na ativação do Pino BCM %s", pin
stdout.flush()
return(True)
def modo1():
global M1A, M1B, M1C
global M2A, M2B, M2C
global M3A, M3B, M3C
global M4A, M4B, M4C
global M5A, M5B, M5C
global M6A, M6B, M6C
global M7A, M7B, M7C
try:
GPIO.output(26, GPIO.HIGH)
except:
print u'Erro ao setar o nível do pino BCM pin 26'
try:
GPIO.output(27, GPIO.LOW)
except:
print u'Erro ao setar o nível do pino BCM pin 27'
sleep(5)
discovery_mods(M1A, M1B, M1C)
discovery_mods(M2A, M2B, M2C)
discovery_mods(M3A, M3B, M3C)
discovery_mods(M4A, M4B, M4C)
discovery_mods(M5A, M5B, M5C)
discovery_mods(M6A, M6B, M6C)
discovery_mods(M7A, M7B, M7C)
def modo3():
try:
GPIO.output(26, GPIO.HIGH)
except:
print u'Erro ao setar o nível do pino BCM pin 26'
try:
GPIO.output(27, GPIO.HIGH)
except:
print u'Erro ao setar o nível do pino BCM pin 27'
return True
def switch_on(_M):
import RPi.GPIO as GPIO
from models import session
from models import Device
from models import Module
from models import Event_Log
from time import sleep
from sys import stdout
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
if GPIO.gpio_function(_M.gpio) == 0:
GPIO.setup(_M.gpio, GPIO.OUT, initial=GPIO.LOW)
GPIO.output(_M.gpio, GPIO.HIGH)
_M.status = True
session.commit()
else:
print 'ERROR! This pin is set as a input'
def switch_off(_M):
import RPi.GPIO as GPIO
from models import session
from models import Device
from models import Module
from models import Event_Log
from time import sleep
from sys import stdout
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
if GPIO.gpio_function(_M.gpio) == 0:
GPIO.setup(_M.gpio, GPIO.OUT, initial=GPIO.HIGH)
GPIO.output(_M.gpio, GPIO.LOW)
_M.status = False
session.commit()
else:
print 'ERROR! This pin is set as a input'
def reset_pin(_M, _time):
import RPi.GPIO as GPIO
from models import session
from models import Device
from models import Module
from models import Event_Log
from time import sleep
from sys import stdout
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
if GPIO.gpio_function(_M.gpio) == 0:
switch_on(_M)
sleep(_time)
switch_off(_M)
else:
print 'ERROR! This pin is set as a input'
def softreset(_host):
from subprocess import call
call(["net", "rpc", "shutdown", "-r", "-I", "192.168.1.21", "-U", "Administrador%SemParar"])
def discovery_mods(_MA, _MB, _MC):
import RPi.GPIO as GPIO
from models import session
from models import Device
from models import Module
from models import Event_Log
from time import sleep
from sys import stdout
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
if GPIO.input(_MA.gpio) == 0 and GPIO.input(_MB.gpio) == 1:
GPIO.setup(_MA.gpio, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(_MB.gpio, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(_MC.gpio, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
_MA.io_type = 'input'
_MA.rpull = False
_MB.io_type = 'input'
_MB.rpull = False
_MC.io_type = 'input'
_MC.rpull = False
session.commit()
elif GPIO.input(_MA.gpio) == 1 and GPIO.input(_MB.gpio) == 0:
GPIO.setup(_MA.gpio, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(_MB.gpio, GPIO.OUT, initial=GPIO.LOW)
GPIO.setup(_MC.gpio, GPIO.OUT, initial=GPIO.LOW)
_MA.io_type = 'output'
_MA.status = False
_MB.io_type = 'output'
_MB.status = False
_MC.io_type = 'output'
_MC.status = False
session.commit()
else:
GPIO.setup(_MA.gpio, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(_MB.gpio, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setup(_MC.gpio, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
_MA.io_type = 'empty'
_MA.rpull = False
_MB.io_type = 'empty'
_MB.rpull = False
_MC.io_type = 'empty'
_MC.rpull = False
session.commit()
def cleanup_pins():
import RPi.GPIO as GPIO
from models import session
from models import Device
from models import Module
from models import Event_Log
from time import sleep
from sys import stdout
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.cleanup()
if __name__ == "__main__":
main()<|fim▁end|> | try:
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) |
<|file_name|>arg-is-one.js<|end_file_name|><|fim▁begin|>// Copyright 2015 Microsoft Corporation. All rights reserved.
// This code is governed by the license found in the LICENSE file.
/*---
description: Math.acosh(1) returns +0
es6id: 20.2.2.3
info: |
Math.acosh ( x )
- If x is 1, the result is +0.
---*/
<|fim▁hole|>assert.sameValue(Math.acosh(+1), 0, "Math.acosh should produce 0 for +1");<|fim▁end|> | |
<|file_name|>url-domains.go<|end_file_name|><|fim▁begin|>package kiwitaxi
type UrlDomain struct {
Id int `csv:"id" json:"id" bson:"id"`
Locale string `csv:"locale" json:"locale" bson:"locale"`<|fim▁hole|>}
func (a *KiwitaxiApi) UrlDomains() (urlDomains []*UrlDomain, err error) {
err = a.getCsv("services/data/csv/url_domains", &urlDomains)
return
}<|fim▁end|> | Value string `csv:"value" json:"value" bson:"value"` |
<|file_name|>order_leg.py<|end_file_name|><|fim▁begin|>from kaleidoscope.globals import SecType
class OrderLeg(object):
def __init__(self, quantity, contract):
"""
This class is an abstraction of an order leg of an option strategy. It holds the information
for a single order leg as part of an entire option strategy.
"""
self.quantity = quantity
self.contract = contract
<|fim▁hole|> """ reverse the the position by negating the quantity """
self.quantity *= -1
class OptionLeg(OrderLeg):
""" Holds information of an option leg """
def __init__(self, option, quantity):
self.sec_type = SecType.OPT
super().__init__(quantity, option)
class StockLeg(OrderLeg):
""" Holds information of an stock leg """
def __init__(self, symbol, quantity):
self.sec_type = SecType.STK
super().__init__(quantity, symbol)<|fim▁end|> | def reverse(self): |
<|file_name|>GotoLineCol.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*-
"""
Script: GotoLineCol.py
Utility: 1. Moves the cursor position to the specified line and column for a file in Notepad++.
Especially useful for inspecting data files in fixed-width record formats.
2. Also, displays the character code (SBCS & LTR) in decimal and hex at the specified position.
Requires: Python Script plugin in Notepad++
Customizable parameters for the goToLineCol function call in main():
bRepeatPrompt: Whether to repeat prompting when the specified number value is out of range
iEdgeBuffer: Ensures that the caret will be that many characters inside the left and right edges of the editor viewing area, when possible
iCaretHiliteDuration: Caret will be in Block mode for specified seconds
bCallTipAutoHide: Whether to hide the call tip automatically in sync when caret highlighting is turned off
bBraceHilite: Whether to use brace highlighting style for the character at the specified position. Automatically turns off when current line changes.
Known Issues: 1. Character code display in the call tip is functional with SBCS (Single-Byte Character Sets) and LTR (left-to-right) direction.
With MBCS (Bulti-Bytes Character Sets) or RTL (right-to-left) direction, results will not be reliable.
2. If iCaretHiliteDuration is set to a high value (>3 seconds), and the user tries to rerun the script
while the previous execution is still running, the Python Script plugin will display an error message:
"Another script is still running..." So set this parameter to 3 seconds or lower.
Author: Shridhar Kumar
Date: 2019-08-15
"""
def main():
goToLineCol(bRepeatPrompt = True,
iEdgeBuffer = 5,
iCaretHiliteDuration = 5,
bCallTipAutoHide = False,
bBraceHilite = True)
def getDisplayLineCol():
iCurrLine = editor.lineFromPosition(editor.getCurrentPos())
iCurrCol = editor.getCurrentPos() - editor.positionFromLine(iCurrLine)
return str(iCurrLine + 1), str(iCurrCol + 1)
def promptValue(sInfoText, sTitleText, sDefaultVal, iMinVal, iMaxVal, sRangeError, bRepeatPrompt):
while True:
sNewVal = notepad.prompt(sInfoText, sTitleText, sDefaultVal)
if sNewVal == None:
return None
try:
iNewVal = int(sNewVal)
if iMinVal <= iNewVal <= iMaxVal:
return iNewVal
else:
raise
except:
notepad.messageBox(sRangeError + '.\n\nYou specified: ' + sNewVal +
'\n\nPlease specify a number between ' + str(iMinVal) + ' and ' + str(iMaxVal) + '.',
'Specified value is out of range')
if not bRepeatPrompt:
return None
def goToLineCol(bRepeatPrompt, iEdgeBuffer, iCaretHiliteDuration, bCallTipAutoHide, bBraceHilite):
import time
sCurrLine, sCurrCol = getDisplayLineCol()
iMaxLines = editor.getLineCount()
iNewLine = promptValue(sInfoText = 'Line number (between 1 and ' + str(iMaxLines) + '):',
sTitleText = 'Specify line number',
sDefaultVal = sCurrLine,
iMinVal = 1,
iMaxVal = iMaxLines,
sRangeError = 'File line count is only ' + str(iMaxLines),
bRepeatPrompt = bRepeatPrompt)
if iNewLine == None:
return
# Get the character count plus 1 for the specified line
# Plus 1 is to account for the caret position at the end of the line, past all characters but before EOL/EOF
# Since lineLength already includes EOL, we just need to subtract 1 only when EOL is 2 chars. i.e., CRLF
# For the last line in file, there is no 2-character CRLF EOL; only a single character EOF.
iMaxCols = max(1, editor.lineLength(iNewLine - 1))
if (editor.getEOLMode() == ENDOFLINE.CRLF) and (iNewLine < iMaxLines):
iMaxCols -= 1
iNewCol = promptValue(sInfoText = 'Column position (between 1 and ' + str(iMaxCols) + ') for line ' + str(iNewLine) + ':',
sTitleText = 'Specify column position',
sDefaultVal = sCurrCol,
iMinVal = 1,
iMaxVal = iMaxCols,
sRangeError = 'There are only ' + str(iMaxCols) + ' characters in line ' + str(iNewLine),
bRepeatPrompt = bRepeatPrompt)
# Navigate to the specified position in the document
iLineStartPos = editor.positionFromLine(iNewLine - 1)
iNewPos = iLineStartPos + iNewCol - 1
editor.ensureVisible(iNewLine - 1)
editor.gotoPos( min(iLineStartPos + iMaxCols, iNewPos + iEdgeBuffer) ) # Ensure that caret is 'iEdgeBuffer' characters inside right edge when possible
editor.gotoPos( max(iLineStartPos, iNewPos - iEdgeBuffer) ) # Ensure that caret is 'iEdgeBuffer' characters inside left edge when possible
editor.gotoPos(iNewPos) # Finally, move caret to the specified position
<|fim▁hole|>
# Set the caret to block style to highlight the new position
editor.setCaretStyle(CARETSTYLE.BLOCK)
# Display a call tip with the new line and column numbers with verification
# Also display the character code in decimal and hex
sCurrLine, sCurrCol = getDisplayLineCol()
editor.callTipShow(iNewPos, ' Line: ' + sCurrLine +
'\n Column: ' + sCurrCol +
'\nChar Code: ' + str(editor.getCharAt(iNewPos)) + ' [' + hex(editor.getCharAt(iNewPos)) + ']')
if iCaretHiliteDuration > 0:
time.sleep(iCaretHiliteDuration)
# Reset the caret style
editor.setCaretStyle(currCS)
if bCallTipAutoHide:
editor.callTipCancel()
if bBraceHilite:
editor.braceHighlight(iNewPos, iNewPos)
main()<|fim▁end|> | # Obtain current caret style to restore it later on
currCS = editor.getCaretStyle() |
<|file_name|>beer.service.ts<|end_file_name|><|fim▁begin|>import { Injectable } from 'angular2/core'
import { Http, Response } from 'angular2/http';
import { Beer } from './beer'
import 'rxjs/Rx';
@Injectable()
export class BeerService {
private _breweryDbKey = '2d18b2531035b441a50dddc3aed32a1b';
private _beerUrl = "http://localhost:1337/api.brewerydb.com/v2/beers?availableId=1&withBreweries=Y&key=" + this._breweryDbKey;
private _searchUrl = "http://localhost:1337/api.brewerydb.com/v2/search?type=beer&withBreweries=Y&key=" + this._breweryDbKey + '&q=';
constructor(private http: Http) {}
getBeer() {
return this.http.get(this._beerUrl)
.map((response: Response) => {
return response.json().data.map(item => {
return new Beer({
name: item.nameDisplay,
brewery: item.breweries[0].nameShortDisplay,
description: item.description,
abv: item.abv,
ibu: item.ibu,
type: item.style.shortName
});
});<|fim▁hole|> }
search(term: string) {
return this.http.get(this._searchUrl + term)
.map((response: Response) => {
return response.json().data.map(item => {
return new Beer({
name: item.nameDisplay,
brewery: item.breweries[0].nameShortDisplay,
description: item.description,
abv: item.abv,
ibu: item.ibu,
type: item.style.shortName
});
})
})
.catch((err: Response) => console.log(err));
}
}<|fim▁end|> | })
.catch((err: Response) => console.log(err)); |
<|file_name|>setup.py<|end_file_name|><|fim▁begin|># -*- coding=utf-8 -*-<|fim▁hole|>
version = get_version()
setup(name='edem.content.logo',
version=version,
description="Logos for forums.e-democracy.org",
long_description=open("README.txt").read() + "\n" +
open(os.path.join("docs", "HISTORY.txt")).read(),
# See https://pypi.python.org/pypi?%3Aaction=list_classifiers for values
classifiers=[
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Zope2",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
"Natural Language :: English",
"Operating System :: POSIX :: Linux"
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='',
author='Bill Bushey',
author_email='[email protected]',
url='http://www.e-democracy.org/',
license='GPL 3',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['edem', 'edem.content'],
include_package_data=True,
zip_safe=True,
install_requires=[
'setuptools',
'edem.skin',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",)<|fim▁end|> | import os
from setuptools import setup, find_packages
from version import get_version |
<|file_name|>MainActivity.java<|end_file_name|><|fim▁begin|>package com.reactnativeexample;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "ReactNativeExample";
}
/**
* Returns whether dev mode should be enabled.
* This enables e.g. the dev menu.
*/
@Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
/**
* A list of packages used by the app. If the app uses additional views
* or modules besides the default ones, add more packages here.
*/
@Override
protected List<ReactPackage> getPackages() {<|fim▁hole|> );
}
}<|fim▁end|> | return Arrays.<ReactPackage>asList(
new MainReactPackage() |
<|file_name|>fund.go<|end_file_name|><|fim▁begin|>package main
import (
"context"
"fmt"
"log"
"net/http"
"strconv"
"strings"
"time"
"github.com/PuerkitoBio/goquery"
)
const (
userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36"
timeLayout = "02/01/2006"
storagePath = ".local/share"
baseURL = "https://www.tefas.gov.tr/FonAnaliz.aspx?FonKod=%v"
)
var (
ErrDisabled = fmt.Errorf("disabled on weekends")
)
func GetFunds(ctx context.Context, codes ...string) ([]Fund, error) {
c := &http.Client{Timeout: time.Minute}
today := time.Now()
switch today.Weekday() {
case 6, 0: // saturday and sunday
return nil, ErrDisabled
}
var funds []Fund
for _, code := range codes {
code = strings.ToUpper(code)
u := fmt.Sprintf(baseURL, code)
req, _ := http.NewRequest("GET", u, nil)
req = req.WithContext(ctx)
req.Header.Set("User-Agent", userAgent)
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
resp, err := c.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
log.Printf("unexpected status code: %v", resp.StatusCode)
continue
}
doc, err := goquery.NewDocumentFromReader(resp.Body)
if err != nil {
return nil, err
}
fundName := strings.TrimSpace(doc.Find(".main-indicators h2").Text())<|fim▁hole|> }
fund.Price = atof(doc.Find(".top-list > li:nth-child(1) span").Text())
fund.Daily = atof(doc.Find(".top-list > li:nth-child(2) span").Text())
doc.Find(".price-indicators li span").Each(func(i int, sel *goquery.Selection) {
changePercent := atof(sel.Text())
switch i {
case 0:
fund.Monthly = changePercent
case 1:
fund.Quarterly = changePercent
case 2:
fund.Biannual = changePercent
case 3:
fund.Annual = changePercent
}
})
funds = append(funds, fund)
}
return funds, nil
}
type Fund struct {
Type FundType
Code string
Name string
Price float64
Daily float64
Monthly float64
Quarterly float64
Biannual float64
Annual float64
}
type FundType uint8
const (
CommodityFunds FundType = 3
FixedIncomeFunds FundType = 6
ForeignEquityFunds FundType = 111
)
func atof(s string) float64 {
s = strings.TrimPrefix(s, "%")
s = strings.ReplaceAll(s, ",", ".")
f, _ := strconv.ParseFloat(s, 64)
return f
}<|fim▁end|> | fund := Fund{
Code: code,
Name: fundName, |
<|file_name|>ToolConstants.java<|end_file_name|><|fim▁begin|>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.tools.common;
import javax.xml.namespace.QName;
public final class ToolConstants {
//public static final String TOOLSPECS_BASE = "/org/apache/cxf/tools/common/toolspec/toolspecs/";
public static final String TOOLSPECS_BASE = "/org/apache/cxf/tools/";
public static final String SCHEMA_URI = "http://www.w3.org/2001/XMLSchema";
public static final String XML_NAMESPACE_URI = "http://www.w3.org/XML/1998/namespace";
public static final String WSDL_NAMESPACE_URI = "http://schemas.xmlsoap.org/wsdl/";
public static final String WSA_NAMESPACE_URI = "http://www.w3.org/2005/08/addressing";
/**
* Tools permit caller to pass in additional bean definitions.
*/
public static final String CFG_BEAN_CONFIG = "beans";
public static final String DEFAULT_TEMP_DIR = "gen_tmp";
public static final String CFG_OUTPUTDIR = "outputdir";
public static final String CFG_OUTPUTFILE = "outputfile";
public static final String CFG_WSDLURL = "wsdlurl";
public static final String CFG_WSDLLOCATION = "wsdlLocation";
public static final String CFG_WSDLLIST = "wsdlList";
public static final String CFG_NAMESPACE = "namespace";
public static final String CFG_VERBOSE = "verbose";
public static final String CFG_PORT = "port";
public static final String CFG_BINDING = "binding";
public static final String CFG_AUTORESOLVE = "autoNameResolution";
public static final String CFG_WEBSERVICE = "webservice";
public static final String CFG_SERVER = "server";
public static final String CFG_CLIENT = "client";
public static final String CFG_ALL = "all";
public static final String CFG_IMPL = "impl";
public static final String CFG_PACKAGENAME = "packagename";
public static final String CFG_JSPACKAGEPREFIX = "jspackageprefix";
public static final String CFG_NINCLUDE = "ninclude";
public static final String CFG_NEXCLUDE = "nexclude";
public static final String CFG_CMD_ARG = "args";
public static final String CFG_INSTALL_DIR = "install.dir";
public static final String CFG_PLATFORM_VERSION = "platform.version";
public static final String CFG_COMPILE = "compile";
public static final String CFG_CLASSDIR = "classdir";
public static final String CFG_EXTRA_SOAPHEADER = "exsoapheader";
public static final String CFG_DEFAULT_NS = "defaultns";
public static final String CFG_DEFAULT_EX = "defaultex";
public static final String CFG_NO_TYPES = "notypes";
public static final String CFG_XJC_ARGS = "xjc";
public static final String CFG_CATALOG = "catalog";
public static final String CFG_BAREMETHODS = "bareMethods";
public static final String CFG_ASYNCMETHODS = "asyncMethods";
public static final String CFG_MIMEMETHODS = "mimeMethods";
public static final String CFG_DEFAULT_VALUES = "defaultValues";
public static final String CFG_JAVASCRIPT_UTILS = "javascriptUtils";
public static final String CFG_VALIDATE_WSDL = "validate";
public static final String CFG_CREATE_XSD_IMPORTS = "createxsdimports";
/**
* Front-end selection command-line option to java2ws.
*/
public static final String CFG_FRONTEND = "frontend";
public static final String CFG_DATABINDING = "databinding";
public static final String DEFAULT_ADDRESS = "http://localhost:9090";
// WSDL2Java Constants
public static final String CFG_TYPES = "types";
public static final String CFG_INTERFACE = "interface";
public static final String CFG_NIGNOREEXCLUDE = "nignoreexclude";
public static final String CFG_ANT = "ant";
public static final String CFG_LIB_REF = "library.references";
public static final String CFG_ANT_PROP = "ant.prop";
public static final String CFG_NO_ADDRESS_BINDING = "noAddressBinding";
public static final String CFG_ALLOW_ELEMENT_REFS = "allowElementReferences";
public static final String CFG_RESERVE_NAME = "reserveClass";
public static final String CFG_FAULT_SERIAL_VERSION_UID = "faultSerialVersionUID";
public static final String CFG_EXCEPTION_SUPER = "exceptionSuper";
public static final String CFG_MARK_GENERATED = "mark-generated";
//Internal Flag to generate
public static final String CFG_IMPL_CLASS = "implClass";
public static final String CFG_GEN_CLIENT = "genClient";
public static final String CFG_GEN_SERVER = "genServer";
public static final String CFG_GEN_IMPL = "genImpl";
public static final String CFG_GEN_TYPES = "genTypes";
public static final String CFG_GEN_SEI = "genSEI";
public static final String CFG_GEN_ANT = "genAnt";
public static final String CFG_GEN_SERVICE = "genService";
public static final String CFG_GEN_OVERWRITE = "overwrite";
public static final String CFG_GEN_FAULT = "genFault";
public static final String CFG_GEN_NEW_ONLY = "newonly";
// Java2WSDL Constants
public static final String CFG_CLASSPATH = "classpath";
public static final String CFG_TNS = "tns";
public static final String CFG_SERVICENAME = "servicename";
public static final String CFG_SCHEMANS = "schemans";
public static final String CFG_USETYPES = "usetypes";
public static final String CFG_CLASSNAME = "classname";
public static final String CFG_PORTTYPE = "porttype";
public static final String CFG_SOURCEDIR = "sourcedir";
public static final String CFG_WSDL = "wsdl";
public static final String CFG_WRAPPERBEAN = "wrapperbean";
// WSDL2Service Constants
public static final String CFG_ADDRESS = "address";
public static final String CFG_TRANSPORT = "transport";
public static final String CFG_SERVICE = "service";
public static final String CFG_BINDING_ATTR = "attrbinding";
public static final String CFG_SOAP12 = "soap12";
// WSDL2Soap Constants
public static final String CFG_STYLE = "style";
public static final String CFG_USE = "use";
// XSD2WSDL Constants
public static final String CFG_XSDURL = "xsdurl";
public static final String CFG_NAME = "name";
// WsdlValidator
public static final String CFG_DEEP = "deep";
public static final String CFG_SCHEMA_DIR = "schemaDir";
public static final String CFG_SCHEMA_URL = "schemaURL";
public static final String CXF_SCHEMA_DIR = "cxf_schema_dir";
public static final String CXF_SCHEMAS_DIR_INJAR = "schemas/wsdl/";
public static final String CFG_SUPPRESS_WARNINGS = "suppressWarnings";
// WSDL2Java Processor Constants
public static final String SEI_GENERATOR = "sei.generator";
public static final String FAULT_GENERATOR = "fault.generator";
public static final String TYPE_GENERATOR = "type.generator";
public static final String IMPL_GENERATOR = "impl.generator";
public static final String SVR_GENERATOR = "svr.generator";
public static final String CLT_GENERATOR = "clt.generator";
public static final String SERVICE_GENERATOR = "service.generator";
public static final String ANT_GENERATOR = "ant.generator";
public static final String HANDLER_GENERATOR = "handler.generator";
// Binding namespace
public static final String NS_JAXWS_BINDINGS = "http://java.sun.com/xml/ns/jaxws";
public static final String NS_JAXB_BINDINGS = "http://java.sun.com/xml/ns/jaxb";
public static final QName JAXWS_BINDINGS = new QName(NS_JAXWS_BINDINGS, "bindings");
public static final QName JAXB_BINDINGS = new QName(NS_JAXB_BINDINGS, "bindings");<|fim▁hole|> public static final String JAXWS_BINDINGS_WSDL_LOCATION = "wsdlLocation";
public static final String JAXWS_BINDING_NODE = "node";
public static final String JAXWS_BINDING_VERSION = "version";
public static final String ASYNC_METHOD_SUFFIX = "Async";
public static final String HANDLER_CHAINS_URI = "http://java.sun.com/xml/ns/javaee";
public static final String HANDLER_CHAIN = "handler-chain";
public static final String HANDLER_CHAINS = "handler-chains";
//public static final String RAW_JAXB_MODEL = "rawjaxbmodel";
// JMS address
public static final String NS_JMS_ADDRESS = "http://cxf.apache.org/transports/jms";
public static final QName JMS_ADDRESS = new QName(NS_JMS_ADDRESS, "address");
public static final String JMS_ADDR_DEST_STYLE = "destinationStyle";
public static final String JMS_ADDR_JNDI_URL = "jndiProviderURL";
public static final String JMS_ADDR_JNDI_FAC = "jndiConnectionFactoryName";
public static final String JMS_ADDR_JNDI_DEST = "jndiDestinationName";
public static final String JMS_ADDR_MSG_TYPE = "messageType";
public static final String JMS_ADDR_INIT_CTX = "initialContextFactory";
public static final String JMS_ADDR_SUBSCRIBER_NAME = "durableSubscriberName";
public static final String JMS_ADDR_MSGID_TO_CORRID = "useMessageIDAsCorrelationID";
// XML Binding
public static final String XMLBINDING_ROOTNODE = "rootNode";
public static final String XMLBINDING_HTTP_LOCATION = "location";
public static final String NS_XML_FORMAT = "http://cxf.apache.org/bindings/xformat";
public static final String XML_FORMAT_PREFIX = "xformat";
public static final String NS_XML_HTTP = "http://schemas.xmlsoap.org/wsdl/http/";
public static final String XML_HTTP_PREFIX = "http";
public static final QName XML_HTTP_ADDRESS = new QName(NS_XML_HTTP, "address");
public static final QName XML_FORMAT = new QName(NS_XML_FORMAT, "body");
public static final QName XML_BINDING_FORMAT = new QName(NS_XML_FORMAT, "binding");
public static final String XML_SCHEMA_COLLECTION = "xmlSchemaCollection";
public static final String PORTTYPE_MAP = "portTypeMap";
public static final String SCHEMA_TARGET_NAMESPACES = "schemaTargetNameSpaces";
public static final String WSDL_DEFINITION = "wsdlDefinition";
public static final String IMPORTED_DEFINITION = "importedDefinition";
public static final String IMPORTED_PORTTYPE = "importedPortType";
public static final String IMPORTED_SERVICE = "importedService";
public static final String BINDING_GENERATOR = "BindingGenerator";
// Tools framework
public static final String FRONTEND_PLUGIN = "frontend";
public static final String DATABINDING_PLUGIN = "databinding";
public static final String RUNTIME_DATABINDING_CLASS = "databinding-class";
public static final String CFG_WSDL_VERSION = "wsdlversion";
// Suppress the code generation, in this case you can just get the generated code model
public static final String CFG_SUPPRESS_GEN = "suppress";
public static final String DEFAULT_PACKAGE_NAME = "defaultnamespace";
//For java2ws tool
public static final String SERVICE_LIST = "serviceList";
public static final String GEN_FROM_SEI = "genFromSEI";
public static final String JAXWS_FRONTEND = "jaxws";
public static final String SIMPLE_FRONTEND = "simple";
public static final String JAXB_DATABINDING = "jaxb";
public static final String AEGIS_DATABINDING = "aegis";
//For Simple FrontEnd
public static final String SEI_CLASS = "seiClass";
public static final String IMPL_CLASS = "implClass";
public static final String SERVICE_NAME = "serviceName";
public static final String PORT_NAME = "portName";
public static final String DEFAULT_DATA_BINDING_NAME = "jaxb";
public static final String DATABIND_BEAN_NAME_SUFFIX = "DatabindingBean";
public static final String CLIENT_CLASS = "clientClass";
public static final String SERVER_CLASS = "serverClass";
public static final String CFG_JSPREFIXMAP = "javascriptPrefixMap";
private ToolConstants() {
//utility class
}
}<|fim▁end|> | |
<|file_name|>tasks.py<|end_file_name|><|fim▁begin|>#-*- coding: UTF-8 -*-
from django.db.models import F
from celery.task import *
from datetime import timedelta, datetime
from app.models import CustomUser
from django.utils.translation import activate,deactivate
"""
Note: the api of twitter retards 1 minute (more or less) the update of the update_date
"""
@task
def forensic():
logger = forensic.get_logger(logfile='tasks.log')
users = CustomUser.objects.filter(next_check__lt=datetime.utcnow(),half_dead=False,dead=False,configured=True,posts__gt=0)
<|fim▁hole|> if user.update_date():
logger.info("User %s, update her date update (on twitter) - [%s]" % (user.username, datetime.utcnow()))
#Which is bigger? login or update date?
date_substract = user.bigger_date()
nowdate = datetime.utcnow()
#time from last update or login on foowill
t = nowdate - date_substract
#Check if the user is half-dead
if t.seconds >= user.activity_interval:
user.half_dead = True
user.save()
False
logger.info("User %s, is HALF-DEAD (on twitter) - [%s]" % (user.username, datetime.utcnow()))
activate(user.language)
user.send_email_halfdead()
deactivate()
@task
def killer_saver():
logger = killer_saver.get_logger(logfile='tasks.log')
users = CustomUser.objects.filter(half_dead=True, dead=False, configured=True, posts__gt=0)
for user in users:
logger.info("User %s, act: %d, mail: %d, lu: %s - [%s]" % (user.username, user.activity_interval, user.mail_interval, user.last_update, datetime.now()))
#Get the last update date for the user
if user.update_date():
logger.info("User %s, update the last date update (on twitter) - [%s]" % (user.username, datetime.utcnow()))
#Which is bigger? login or update date?
date_substract = user.bigger_date()
nowdate = datetime.utcnow()
#time from last update or login on foowill
if nowdate > date_substract: #Correction for a date_substract in future (synchronization problems)
t = nowdate - date_substract
else:
t = timedelta(seconds=0)
#Check if the user status
if t.seconds < user.activity_interval:
#Is not still half_dead -> save it
user.half_dead = False
user.last_update = nowdate
user.next_check = nowdate + timedelta(seconds=user.activity_interval)
user.save()
logger.info("User %s, is SAVED (on twitter) - [%s]" % (user.username, datetime.utcnow()))
activate(user.language)
user.send_email_still_alive()
deactivate()
#user.update_twitter_status("Sigo vivo, no os preocupeis. http://foowill.com %s" % datetime.now() )
elif t.seconds >= user.activity_interval + user.mail_interval:
user.dead = True
user.save()
logger.info("User %s, is DEAD (on twitter) - [%s]" % (user.username, datetime.utcnow()))
activate(user.language)
user.send_email_hope_to_read()
if user.mail_interval == 0:
user.deliver_all_to_twitter()
else:
user.posts_sended = user.posts
user.deliver_one_to_twitter()
deactivate()
else:
logger.info("User %s, is STILL HALF-DEAD (on twitter) - [%s]" % (user.username, datetime.utcnow()))
#TODO: if email: Send email for another reminder.
@task
def tweet_sender():
logger = killer_saver.get_logger(logfile='tasks.log')
users = CustomUser.objects.filter(half_dead=True, dead=True, configured=True, posts_sended__gt=0, next_check_mail__lt=datetime.utcnow())
for user in users:
user.deliver_one_to_twitter()<|fim▁end|> | for user in users:
logger.info("User %s, act: %d, mail: %d, lu: %s - [%s]" % (user.username, user.activity_interval, user.mail_interval, user.last_update, datetime.now()))
#Get the last update date for the user |
<|file_name|>pconvert.cpp<|end_file_name|><|fim▁begin|>/******************************************************************************
*
* MantaFlow fluid solver framework
* Copyright 2011 Tobias Pfaff, Nils Thuerey
*
* This program is free software, distributed under the terms of the
* GNU General Public License (GPL)
* http://www.gnu.org/licenses
*
* Python argument wrappers and conversion tools
*
******************************************************************************/
#include "pythonInclude.h"
#include <sstream>
#include <algorithm>
#include "vectorbase.h"
#include "manta.h"
using namespace std;
//******************************************************************************
// Explicit definition and instantiation of python object converters
namespace Manta {
extern PyTypeObject PbVec3Type;
extern PyTypeObject PbVec4Type;
struct PbVec3 {
PyObject_HEAD
float data[3];
};
struct PbVec4 {
PyObject_HEAD
float data[4];
};
PyObject* getPyNone() {
Py_INCREF(Py_None);
return Py_None;
}
PyObject* incref(PyObject* obj) {
Py_INCREF(obj);
return obj;
}
/*template<> PyObject* toPy<PyObject*>(PyObject* obj) {
return obj;
}*/
template<> PyObject* toPy<int>( const int& v) {
return PyLong_FromLong(v);
}
/*template<> PyObject* toPy<char*>(const (char*) & val) {
return PyUnicode_DecodeLatin1(val,strlen(val),"replace");
}*/
template<> PyObject* toPy<string>( const string& val) {
return PyUnicode_DecodeLatin1(val.c_str(),val.length(),"replace");
}
template<> PyObject* toPy<float>( const float& v) {
return PyFloat_FromDouble(v);
}
template<> PyObject* toPy<double>( const double& v) {
return PyFloat_FromDouble(v);
}
template<> PyObject* toPy<bool>( const bool& v) {
return PyBool_FromLong(v);
}
template<> PyObject* toPy<Vec3i>(const Vec3i& v) {
float x=(float)v.x, y=(float)v.y, z=(float)v.z;
return PyObject_CallFunction((PyObject*)&PbVec3Type, (char*)"fff", x, y, z);
}
template<> PyObject* toPy<Vec3>(const Vec3& v) {
float x=(float)v.x, y=(float)v.y, z=(float)v.z;
return PyObject_CallFunction((PyObject*)&PbVec3Type, (char*)"fff", x, y, z);
}
template<> PyObject* toPy<Vec4i>(const Vec4i& v) {
float x=(float)v.x, y=(float)v.y, z=(float)v.z;
return PyObject_CallFunction((PyObject*)&PbVec4Type, (char*)"ffff", x, y, z);
}
template<> PyObject* toPy<Vec4>(const Vec4& v) {
float x=(float)v.x, y=(float)v.y, z=(float)v.z;
return PyObject_CallFunction((PyObject*)&PbVec4Type, (char*)"ffff", x, y, z);
}
template<> PyObject* toPy<PbClass*>(const PbClass_Ptr& obj) {
return obj->getPyObject();
}
template<> float fromPy<float>(PyObject* obj) {
#if PY_MAJOR_VERSION <= 2
if (PyInt_Check(obj)) return PyInt_AsLong(obj);
#endif
if (PyFloat_Check(obj)) return PyFloat_AsDouble(obj);
if (PyLong_Check(obj)) return PyLong_AsDouble(obj);
errMsg("argument is not a float");
}
template<> double fromPy<double>(PyObject* obj) {
#if PY_MAJOR_VERSION <= 2
if (PyInt_Check(obj)) return PyInt_AsLong(obj);
#endif
if (PyFloat_Check(obj)) return PyFloat_AsDouble(obj);
if (PyLong_Check(obj)) return PyLong_AsDouble(obj);<|fim▁hole|>}
template<> PyObject* fromPy<PyObject*>(PyObject *obj) {
return obj;
}
template<> int fromPy<int>(PyObject *obj) {
#if PY_MAJOR_VERSION <= 2
if (PyInt_Check(obj)) return PyInt_AsLong(obj);
#endif
if (PyLong_Check(obj)) return PyLong_AsDouble(obj);
if (PyFloat_Check(obj)) {
double a = PyFloat_AsDouble(obj);
if (fabs(a-floor(a+0.5)) > 1e-5)
errMsg("argument is not an int");
return (int) (a+0.5);
}
errMsg("argument is not an int");
}
template<> string fromPy<string>(PyObject *obj) {
if (PyUnicode_Check(obj))
return PyBytes_AsString(PyUnicode_AsLatin1String(obj));
#if PY_MAJOR_VERSION <= 2
else if (PyString_Check(obj))
return PyString_AsString(obj);
#endif
else
errMsg("argument is not a string");
}
template<> const char* fromPy<const char*>(PyObject *obj) {
if (PyUnicode_Check(obj))
return PyBytes_AsString(PyUnicode_AsLatin1String(obj));
#if PY_MAJOR_VERSION <= 2
else if (PyString_Check(obj))
return PyString_AsString(obj);
#endif
else errMsg("argument is not a string");
}
template<> bool fromPy<bool>(PyObject *obj) {
if (!PyBool_Check(obj)) errMsg("argument is not a boolean");
return PyLong_AsLong(obj) != 0;
}
template<> Vec3 fromPy<Vec3>(PyObject* obj) {
if (PyObject_IsInstance(obj, (PyObject*)&PbVec3Type)) {
return Vec3(((PbVec3*)obj)->data);
}
else if (PyTuple_Check(obj) && PyTuple_Size(obj) == 3) {
return Vec3(fromPy<Real>(PyTuple_GetItem(obj,0)),
fromPy<Real>(PyTuple_GetItem(obj,1)),
fromPy<Real>(PyTuple_GetItem(obj,2)));
}
errMsg("argument is not a Vec3");
}
template<> Vec3i fromPy<Vec3i>(PyObject* obj) {
if (PyObject_IsInstance(obj, (PyObject*)&PbVec3Type)) {
return toVec3iChecked(((PbVec3*)obj)->data);
}
else if (PyTuple_Check(obj) && PyTuple_Size(obj) == 3) {
return Vec3i(fromPy<int>(PyTuple_GetItem(obj,0)),
fromPy<int>(PyTuple_GetItem(obj,1)),
fromPy<int>(PyTuple_GetItem(obj,2)));
}
errMsg("argument is not a Vec3i");
}
template<> Vec4 fromPy<Vec4>(PyObject* obj) {
if (PyObject_IsInstance(obj, (PyObject*)&PbVec4Type)) {
return Vec4(((PbVec4*)obj)->data);
}
else if (PyTuple_Check(obj) && PyTuple_Size(obj) == 4) {
return Vec4(fromPy<Real>(PyTuple_GetItem(obj,0)),
fromPy<Real>(PyTuple_GetItem(obj,1)),
fromPy<Real>(PyTuple_GetItem(obj,2)),
fromPy<Real>(PyTuple_GetItem(obj,3)));
}
errMsg("argument is not a Vec4");
}
template<> Vec4i fromPy<Vec4i>(PyObject* obj) {
if (PyObject_IsInstance(obj, (PyObject*)&PbVec4Type)) {
return toVec4i(((PbVec4*)obj)->data);
}
else if (PyTuple_Check(obj) && PyTuple_Size(obj) == 4) {
return Vec4i(fromPy<int>(PyTuple_GetItem(obj,0)),
fromPy<int>(PyTuple_GetItem(obj,1)),
fromPy<int>(PyTuple_GetItem(obj,2)),
fromPy<int>(PyTuple_GetItem(obj,3)));
}
errMsg("argument is not a Vec4i");
}
template<> PbType fromPy<PbType>(PyObject* obj) {
PbType pb = {""};
if (!PyType_Check(obj))
return pb;
const char* tname = ((PyTypeObject*)obj)->tp_name;
pb.S = tname;
return pb;
}
template<> PbTypeVec fromPy<PbTypeVec>(PyObject* obj) {
PbTypeVec vec;
if (PyType_Check(obj)) {
vec.T.push_back(fromPy<PbType>(obj));
} else if (PyTuple_Check(obj)) {
int sz = PyTuple_Size(obj);
for (int i=0; i< sz; i++)
vec.T.push_back(fromPy<PbType>(PyTuple_GetItem(obj,i)));
}
else
errMsg("argument is not a type tuple");
return vec;
}
template<class T> T* tmpAlloc(PyObject* obj,std::vector<void*>* tmp) {
if (!tmp) throw Error("dynamic de-ref not supported for this type");
void* ptr = malloc(sizeof(T));
tmp->push_back(ptr);
*((T*)ptr) = fromPy<T>(obj);
return (T*)ptr;
}
template<> float* fromPyPtr<float>(PyObject* obj, std::vector<void*>* tmp) { return tmpAlloc<float>(obj,tmp); }
template<> double* fromPyPtr<double>(PyObject* obj, std::vector<void*>* tmp) { return tmpAlloc<double>(obj,tmp); }
template<> int* fromPyPtr<int>(PyObject* obj, std::vector<void*>* tmp) { return tmpAlloc<int>(obj,tmp); }
template<> std::string* fromPyPtr<std::string>(PyObject* obj, std::vector<void*>* tmp) { return tmpAlloc<std::string>(obj,tmp); }
template<> bool* fromPyPtr<bool>(PyObject* obj, std::vector<void*>* tmp) { return tmpAlloc<bool>(obj,tmp); }
template<> Vec3* fromPyPtr<Vec3>(PyObject* obj, std::vector<void*>* tmp) { return tmpAlloc<Vec3>(obj,tmp); }
template<> Vec3i* fromPyPtr<Vec3i>(PyObject* obj, std::vector<void*>* tmp) { return tmpAlloc<Vec3i>(obj,tmp); }
template<> Vec4* fromPyPtr<Vec4>(PyObject* obj, std::vector<void*>* tmp) { return tmpAlloc<Vec4>(obj,tmp); }
template<> Vec4i* fromPyPtr<Vec4i>(PyObject* obj, std::vector<void*>* tmp) { return tmpAlloc<Vec4i>(obj,tmp); }
template<> bool isPy<float>(PyObject* obj) {
#if PY_MAJOR_VERSION <= 2
if (PyInt_Check(obj)) return true;
#endif
return PyFloat_Check(obj) || PyLong_Check(obj);
}
template<> bool isPy<double>(PyObject* obj) {
#if PY_MAJOR_VERSION <= 2
if (PyInt_Check(obj)) return true;
#endif
return PyFloat_Check(obj) || PyLong_Check(obj);
}
template<> bool isPy<PyObject*>(PyObject *obj) {
return true;
}
template<> bool isPy<int>(PyObject *obj) {
#if PY_MAJOR_VERSION <= 2
if (PyInt_Check(obj)) return true;
#endif
if (PyLong_Check(obj)) return true;
if (PyFloat_Check(obj)) {
double a = PyFloat_AsDouble(obj);
return fabs(a-floor(a+0.5)) < 1e-5;
}
return false;
}
template<> bool isPy<string>(PyObject *obj) {
if (PyUnicode_Check(obj)) return true;
#if PY_MAJOR_VERSION <= 2
if (PyString_Check(obj)) return true;
#endif
return false;
}
template<> bool isPy<const char*>(PyObject *obj) {
if (PyUnicode_Check(obj)) return true;
#if PY_MAJOR_VERSION <= 2
if (PyString_Check(obj)) return true;
#endif
return false;
}
template<> bool isPy<bool>(PyObject *obj) {
return PyBool_Check(obj);
}
template<> bool isPy<Vec3>(PyObject* obj) {
if (PyObject_IsInstance(obj, (PyObject*)&PbVec3Type)) return true;
if (PyTuple_Check(obj) && PyTuple_Size(obj) == 3) {
return isPy<Real>(PyTuple_GetItem(obj,0)) &&
isPy<Real>(PyTuple_GetItem(obj,1)) &&
isPy<Real>(PyTuple_GetItem(obj,2));
}
return false;
}
template<> bool isPy<Vec3i>(PyObject* obj) {
if (PyObject_IsInstance(obj, (PyObject*)&PbVec3Type)) return true;
if (PyTuple_Check(obj) && PyTuple_Size(obj) == 3) {
return isPy<int>(PyTuple_GetItem(obj,0)) &&
isPy<int>(PyTuple_GetItem(obj,1)) &&
isPy<int>(PyTuple_GetItem(obj,2));
}
return false;
}
template<> bool isPy<Vec4>(PyObject* obj) {
if (PyObject_IsInstance(obj, (PyObject*)&PbVec4Type)) return true;
if (PyTuple_Check(obj) && PyTuple_Size(obj) == 4) {
return isPy<Real>(PyTuple_GetItem(obj,0)) &&
isPy<Real>(PyTuple_GetItem(obj,1)) &&
isPy<Real>(PyTuple_GetItem(obj,2)) &&
isPy<Real>(PyTuple_GetItem(obj,3));
}
return false;
}
template<> bool isPy<Vec4i>(PyObject* obj) {
if (PyObject_IsInstance(obj, (PyObject*)&PbVec4Type)) return true;
if (PyTuple_Check(obj) && PyTuple_Size(obj) == 4) {
return isPy<int>(PyTuple_GetItem(obj,0)) &&
isPy<int>(PyTuple_GetItem(obj,1)) &&
isPy<int>(PyTuple_GetItem(obj,2)) &&
isPy<int>(PyTuple_GetItem(obj,3));
}
return false;
}
template<> bool isPy<PbType>(PyObject* obj) {
return PyType_Check(obj);
}
//******************************************************************************
// PbArgs class defs
PbArgs PbArgs::EMPTY(NULL,NULL);
PbArgs::PbArgs(PyObject* linarg, PyObject* dict) : mLinArgs(0), mKwds(0) {
setup(linarg, dict);
}
PbArgs::~PbArgs() {
for(int i=0; i<(int)mTmpStorage.size(); i++)
free(mTmpStorage[i]);
mTmpStorage.clear();
}
void PbArgs::copy(PbArgs& a) {
mKwds = a.mKwds;
mData = a.mData;
mLinData = a.mLinData;
mLinArgs = a.mLinArgs;
}
void PbArgs::clear() {
mLinArgs = 0;
mKwds = 0;
mData.clear();
mLinData.clear();
}
PbArgs& PbArgs::operator=(const PbArgs& a) {
// mLinArgs = 0;
// mKwds = 0;
return *this;
}
void PbArgs::setup(PyObject* linarg, PyObject* dict) {
if (dict) {
PyObject *key, *value;
Py_ssize_t pos = 0;
while (PyDict_Next(dict, &pos, &key, &value)) {
DataElement el;
el.obj = value;
el.visited = false;
mData[fromPy<string>(key)] = el;
}
mKwds = dict;
}
if (linarg) {
size_t len = PyTuple_Size(linarg);
for (size_t i=0; i<len; i++) {
DataElement el;
el.obj = PyTuple_GetItem(linarg, i);
el.visited = false;
mLinData.push_back(el);
}
mLinArgs = linarg;
}
}
void PbArgs::addLinArg(PyObject* obj) {
DataElement el = { obj, false };
mLinData.push_back(el);
}
void PbArgs::check() {
if (has("nocheck")) return;
for(map<string, DataElement>::iterator it = mData.begin(); it != mData.end(); it++) {
if (!it->second.visited)
errMsg("Argument '" + it->first + "' unknown");
}
for(size_t i=0; i<mLinData.size(); i++) {
if (!mLinData[i].visited) {
stringstream s;
s << "Function does not read argument number #" << i;
errMsg(s.str());
}
}
}
FluidSolver* PbArgs::obtainParent() {
FluidSolver* solver = getPtrOpt<FluidSolver>("solver",-1,NULL);
if (solver != 0) return solver;
for(map<string, DataElement>::iterator it = mData.begin(); it != mData.end(); it++) {
PbClass* obj = Pb::objFromPy(it->second.obj);
if (obj) {
if (solver == NULL)
solver = obj->getParent();
}
}
for(vector<DataElement>::iterator it = mLinData.begin(); it != mLinData.end(); it++) {
PbClass* obj = Pb::objFromPy(it->obj);
if (obj) {
if (solver == NULL)
solver = obj->getParent();
}
}
return solver;
}
void PbArgs::visit(int number, const string& key) {
if (number >= 0 && number < (int)mLinData.size())
mLinData[number].visited = true;
map<string, DataElement>::iterator lu = mData.find(key);
if (lu != mData.end())
lu->second.visited = true;
}
PyObject* PbArgs::getItem(const std::string& key, bool strict, ArgLocker* lk) {
map<string, DataElement>::iterator lu = mData.find(key);
if (lu == mData.end()) {
if (strict)
errMsg ("Argument '" + key + "' is not defined.");
return NULL;
}
PbClass* pbo = Pb::objFromPy(lu->second.obj);
// try to lock
if (pbo && lk) lk->add(pbo);
return lu->second.obj;
}
PyObject* PbArgs::getItem(size_t number, bool strict, ArgLocker* lk) {
if (number >= mLinData.size()) {
if (!strict)
return NULL;
stringstream s;
s << "Argument number #" << number << " not specified.";
errMsg(s.str());
}
PbClass* pbo = Pb::objFromPy(mLinData[number].obj);
// try to lock
if (pbo && lk) lk->add(pbo);
return mLinData[number].obj;
}
//******************************************************************************
// ArgLocker class defs
void ArgLocker::add(PbClass* p) {
if (find(locks.begin(), locks.end(), p) == locks.end()) {
locks.push_back(p);
p->lock();
}
}
ArgLocker::~ArgLocker() {
for (size_t i=0; i<locks.size(); i++)
locks[i]->unlock();
locks.clear();
}
} // namespace<|fim▁end|> | errMsg("argument is not a double"); |
<|file_name|>admin.py<|end_file_name|><|fim▁begin|>from django.contrib import admin
from puzzle_captcha.models import Puzzle, PuzzlePiece
class PuzzlePieceInline(admin.StackedInline):
model = PuzzlePiece
readonly_fields = ('key', 'image', 'order')
can_delete = False
extra = 0
class PuzzleAdmin(admin.ModelAdmin):
list_display = ('key', 'rows', 'cols')
readonly_fields = ('key', 'rows', 'cols')
class Meta:<|fim▁hole|>
admin.site.register(Puzzle, PuzzleAdmin)<|fim▁end|> | model = Puzzle
inlines = [
PuzzlePieceInline,
] |
<|file_name|>optimized.py<|end_file_name|><|fim▁begin|>from feature import *
from pymongo import MongoClient
from bson.binary import Binary as BsonBinary
import pickle
import os
from operator import itemgetter
import time
import sys
imagelocation = "" #Input Image path
indir = "" #Directory Path
client = MongoClient('mongodb://localhost:27017')
db = client.coil #Insert your database in place of coil
col = db.images #Insert your collection in place of images
class Image(object):
"""docstring for Image"""
def __init__(self, path):
self.path = path
img = cv2.imread(self.path,0)
imgm = preprocess(img)
segm = segment(imgm)
self.glfeature = globalfeature(imgm,16)
self.llfeature = localfeature(segm)
self.numberofones = self.glfeature.sum(dtype=int)
start_time = time.time()
count = 0
for root, dirs, filenames in os.walk(indir):
for f in filenames:
i1 = Image(f)
count = count+1
perc = (count/360) * 100
sys.stdout.write("\r%d%%" % perc)
sys.stdout.flush()
new_posts = [{'path': i1.path,
'llfeature': BsonBinary(pickle.dumps(i1.llfeature,protocol=2)),
'glfeature': BsonBinary(pickle.dumps(i1.glfeature,protocol=2)),
'numberofones' : int(i1.numberofones)}]
post_id = col.insert(new_posts)
# print(post_id)
img = Image(imagelocation)
count = 0
maxglosim = 0
maxlocsim = 0
maximum = 0
gridmax=0
vectormax=0
for f in col.find():
llfeature = pickle.loads(f['llfeature'])
glfeature = pickle.loads(f['glfeature'])
count = count+1
perc = (count/360) * 100
sys.stdout.write("\r%d%%" % perc)
sys.stdout.flush()
locsim = np.absolute((llfeature-img.llfeature).sum())
glosim = np.logical_xor(glfeature,img.glfeature).sum()
distance = locsim+glosim
if(glosim>maxglosim):
gridmax = glfeature
maxglosim=glosim
if(locsim>maxlocsim):
maxlocsim=locsim
vectormax = llfeature
if(distance>maximum):
vectmostdif= llfeature
gridmostdif = glfeature
maximum = distance
<|fim▁hole|>print("\nTotal Processing Time : {0:.2f} seconds".format(processed_time-start_time))
def gloDist(gridA,gridB):
glosim = np.logical_xor(gridA,gridB).sum()
return glosim/maxiglosim
def locDist(vectorA,vectorB):
locsim = np.absolute((vectorA-vectorB).sum())
return locsim/maxilocsim
ranking = []
count = 0
print("\nSearching:")
for f in col.find():
llfeature = pickle.loads(f['llfeature'])
glfeature = pickle.loads(f['glfeature'])
count = count+1
perc = (count/360) * 100
sys.stdout.write("\r%d%%" % perc)
sys.stdout.flush()
g1 = gloDist(glfeature,img.glfeature)
l1 = locDist(llfeature,img.llfeature)
sim = ((2-(g1+l1))/2)*100
ranking.append([sim,f['path']])
search_time = time.time()
print("\nTotal Searching Time : {0:.2f} seconds".format(search_time-processed_time))
print("\nTotal Time : {0:.2f} seconds".format(search_time-start_time))
ranking = sorted(ranking, key=itemgetter(0),reverse=True)
#Ranking : Results in a list<|fim▁end|> | maxilocsim = np.absolute((vectormax-img.llfeature).sum())
maxiglosim = np.logical_xor(gridmax,img.glfeature).sum()
processed_time = time.time()
|
<|file_name|>speedway.py<|end_file_name|><|fim▁begin|># Copyright 2011 Google Inc. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License");<|fim▁hole|># 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.
#
"""Speedway iptables generator. This is a subclass of Iptables lib."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
__author__ = '[email protected] (Tony Watson)'
from string import Template
from lib import iptables
class Error(Exception):
pass
class Term(iptables.Term):
"""Generate Iptables policy terms."""
_PLATFORM = 'speedway'
_PREJUMP_FORMAT = None
_POSTJUMP_FORMAT = Template('-A $filter -j $term')
class Speedway(iptables.Iptables):
"""Generates filters and terms from provided policy object."""
_PLATFORM = 'speedway'
_DEFAULT_PROTOCOL = 'all'
SUFFIX = '.ipt'
_RENDER_PREFIX = '*filter'
_RENDER_SUFFIX = 'COMMIT'
_DEFAULTACTION_FORMAT = ':%s %s'
_TERM = Term<|fim▁end|> | # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# |
<|file_name|>testLauncher.js<|end_file_name|><|fim▁begin|>/**
* Macchiato : Mobile and Web application offloading Copyright (C) 2013 Nicolas
* Petitprez
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
// include FutureJS
require('../../../src/main/javascript/websocket-node-adapter.js');
require('../../main/javascript/futuresjs/future.js');
require('../../main/javascript/futuresjs/sequence.js');
require('../../main/javascript/futuresjs/chainify.js');
require('../../main/javascript/futuresjs/join.js');
// macchiato EB libraries
require('../../main/javascript/macchiato-commons.js');<|fim▁hole|>// test
require('./qunit-server.js');
require('../javascript/eventbus.js');
run();<|fim▁end|> | require('../../main/javascript/macchiato-eb.js');
|
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! This pass type-checks the MIR to ensure it is not broken.
#![allow(unreachable_code)]
use borrow_check::borrow_set::BorrowSet;
use borrow_check::location::LocationTable;
use borrow_check::nll::constraints::{ConstraintSet, OutlivesConstraint};
use borrow_check::nll::facts::AllFacts;
use borrow_check::nll::region_infer::values::LivenessValues;
use borrow_check::nll::region_infer::values::PlaceholderIndex;
use borrow_check::nll::region_infer::values::PlaceholderIndices;
use borrow_check::nll::region_infer::values::RegionValueElements;
use borrow_check::nll::region_infer::{ClosureRegionRequirementsExt, TypeTest};
use borrow_check::nll::renumber;
use borrow_check::nll::type_check::free_region_relations::{
CreateResult, UniversalRegionRelations,
};
use borrow_check::nll::universal_regions::{DefiningTy, UniversalRegions};
use borrow_check::nll::ToRegionVid;
use dataflow::move_paths::MoveData;
use dataflow::FlowAtLocation;
use dataflow::MaybeInitializedPlaces;
use either::Either;
use rustc::hir;
use rustc::hir::def_id::DefId;
use rustc::infer::canonical::QueryRegionConstraint;
use rustc::infer::outlives::env::RegionBoundPairs;
use rustc::infer::{InferCtxt, InferOk, LateBoundRegionConversionTime, NLLRegionVariableOrigin};
use rustc::mir::interpret::EvalErrorKind::BoundsCheck;
use rustc::mir::tcx::PlaceTy;
use rustc::mir::visit::{PlaceContext, Visitor, MutatingUseContext, NonMutatingUseContext};
use rustc::mir::*;
use rustc::traits::query::type_op;
use rustc::traits::query::type_op::custom::CustomTypeOp;
use rustc::traits::query::{Fallible, NoSolution};
use rustc::traits::{ObligationCause, PredicateObligations};
use rustc::ty::fold::TypeFoldable;
use rustc::ty::subst::{Subst, Substs, UnpackedKind};<|fim▁hole|>use rustc::ty::{self, RegionVid, ToPolyTraitRef, Ty, TyCtxt, TyKind};
use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_data_structures::indexed_vec::{IndexVec, Idx};
use rustc::ty::layout::VariantIdx;
use std::rc::Rc;
use std::{fmt, iter};
use syntax_pos::{Span, DUMMY_SP};
use transform::{MirPass, MirSource};
macro_rules! span_mirbug {
($context:expr, $elem:expr, $($message:tt)*) => ({
$crate::borrow_check::nll::type_check::mirbug(
$context.tcx(),
$context.last_span,
&format!(
"broken MIR in {:?} ({:?}): {}",
$context.mir_def_id,
$elem,
format_args!($($message)*),
),
)
})
}
macro_rules! span_mirbug_and_err {
($context:expr, $elem:expr, $($message:tt)*) => ({
{
span_mirbug!($context, $elem, $($message)*);
$context.error()
}
})
}
mod constraint_conversion;
pub mod free_region_relations;
mod input_output;
crate mod liveness;
mod relate_tys;
/// Type checks the given `mir` in the context of the inference
/// context `infcx`. Returns any region constraints that have yet to
/// be proven. This result is includes liveness constraints that
/// ensure that regions appearing in the types of all local variables
/// are live at all points where that local variable may later be
/// used.
///
/// This phase of type-check ought to be infallible -- this is because
/// the original, HIR-based type-check succeeded. So if any errors
/// occur here, we will get a `bug!` reported.
///
/// # Parameters
///
/// - `infcx` -- inference context to use
/// - `param_env` -- parameter environment to use for trait solving
/// - `mir` -- MIR to type-check
/// - `mir_def_id` -- DefId from which the MIR is derived (must be local)
/// - `region_bound_pairs` -- the implied outlives obligations between type parameters
/// and lifetimes (e.g., `&'a T` implies `T: 'a`)
/// - `implicit_region_bound` -- a region which all generic parameters are assumed
/// to outlive; should represent the fn body
/// - `input_tys` -- fully liberated, but **not** normalized, expected types of the arguments;
/// the types of the input parameters found in the MIR itself will be equated with these
/// - `output_ty` -- fully liberated, but **not** normalized, expected return type;
/// the type for the RETURN_PLACE will be equated with this
/// - `liveness` -- results of a liveness computation on the MIR; used to create liveness
/// constraints for the regions in the types of variables
/// - `flow_inits` -- results of a maybe-init dataflow analysis
/// - `move_data` -- move-data constructed when performing the maybe-init dataflow analysis
pub(crate) fn type_check<'gcx, 'tcx>(
infcx: &InferCtxt<'_, 'gcx, 'tcx>,
param_env: ty::ParamEnv<'gcx>,
mir: &Mir<'tcx>,
mir_def_id: DefId,
universal_regions: &Rc<UniversalRegions<'tcx>>,
location_table: &LocationTable,
borrow_set: &BorrowSet<'tcx>,
all_facts: &mut Option<AllFacts>,
flow_inits: &mut FlowAtLocation<MaybeInitializedPlaces<'_, 'gcx, 'tcx>>,
move_data: &MoveData<'tcx>,
elements: &Rc<RegionValueElements>,
) -> MirTypeckResults<'tcx> {
let implicit_region_bound = infcx.tcx.mk_region(ty::ReVar(universal_regions.fr_fn_body));
let mut constraints = MirTypeckRegionConstraints {
placeholder_indices: PlaceholderIndices::default(),
placeholder_index_to_region: IndexVec::default(),
liveness_constraints: LivenessValues::new(elements),
outlives_constraints: ConstraintSet::default(),
closure_bounds_mapping: Default::default(),
type_tests: Vec::default(),
};
let CreateResult {
universal_region_relations,
region_bound_pairs,
normalized_inputs_and_output,
} = free_region_relations::create(
infcx,
param_env,
Some(implicit_region_bound),
universal_regions,
&mut constraints,
);
let mut borrowck_context = BorrowCheckContext {
universal_regions,
location_table,
borrow_set,
all_facts,
constraints: &mut constraints,
};
type_check_internal(
infcx,
mir_def_id,
param_env,
mir,
®ion_bound_pairs,
Some(implicit_region_bound),
Some(&mut borrowck_context),
Some(&universal_region_relations),
|cx| {
cx.equate_inputs_and_outputs(mir, universal_regions, &normalized_inputs_and_output);
liveness::generate(cx, mir, elements, flow_inits, move_data, location_table);
cx.borrowck_context
.as_mut()
.map(|bcx| translate_outlives_facts(bcx));
},
);
MirTypeckResults {
constraints,
universal_region_relations,
}
}
fn type_check_internal<'a, 'gcx, 'tcx, R>(
infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
mir_def_id: DefId,
param_env: ty::ParamEnv<'gcx>,
mir: &'a Mir<'tcx>,
region_bound_pairs: &'a RegionBoundPairs<'tcx>,
implicit_region_bound: Option<ty::Region<'tcx>>,
borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
mut extra: impl FnMut(&mut TypeChecker<'a, 'gcx, 'tcx>) -> R,
) -> R where {
let mut checker = TypeChecker::new(
infcx,
mir,
mir_def_id,
param_env,
region_bound_pairs,
implicit_region_bound,
borrowck_context,
universal_region_relations,
);
let errors_reported = {
let mut verifier = TypeVerifier::new(&mut checker, mir);
verifier.visit_mir(mir);
verifier.errors_reported
};
if !errors_reported {
// if verifier failed, don't do further checks to avoid ICEs
checker.typeck_mir(mir);
}
extra(&mut checker)
}
fn translate_outlives_facts(cx: &mut BorrowCheckContext) {
if let Some(facts) = cx.all_facts {
let location_table = cx.location_table;
facts
.outlives
.extend(cx.constraints.outlives_constraints.iter().flat_map(
|constraint: &OutlivesConstraint| {
if let Some(from_location) = constraint.locations.from_location() {
Either::Left(iter::once((
constraint.sup,
constraint.sub,
location_table.mid_index(from_location),
)))
} else {
Either::Right(
location_table
.all_points()
.map(move |location| (constraint.sup, constraint.sub, location)),
)
}
},
));
}
}
fn mirbug(tcx: TyCtxt, span: Span, msg: &str) {
// We sometimes see MIR failures (notably predicate failures) due to
// the fact that we check rvalue sized predicates here. So use `delay_span_bug`
// to avoid reporting bugs in those cases.
tcx.sess.diagnostic().delay_span_bug(span, msg);
}
enum FieldAccessError {
OutOfRange { field_count: usize },
}
/// Verifies that MIR types are sane to not crash further checks.
///
/// The sanitize_XYZ methods here take an MIR object and compute its
/// type, calling `span_mirbug` and returning an error type if there
/// is a problem.
struct TypeVerifier<'a, 'b: 'a, 'gcx: 'tcx, 'tcx: 'b> {
cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>,
mir: &'a Mir<'tcx>,
last_span: Span,
mir_def_id: DefId,
errors_reported: bool,
}
impl<'a, 'b, 'gcx, 'tcx> Visitor<'tcx> for TypeVerifier<'a, 'b, 'gcx, 'tcx> {
fn visit_span(&mut self, span: &Span) {
if !span.is_dummy() {
self.last_span = *span;
}
}
fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
self.sanitize_place(place, location, context);
}
fn visit_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
self.super_constant(constant, location);
self.sanitize_constant(constant, location);
self.sanitize_type(constant, constant.ty);
if let Some(user_ty) = constant.user_ty {
if let Err(terr) = self.cx.relate_type_and_user_type(
constant.ty,
ty::Variance::Invariant,
&UserTypeProjection { base: user_ty, projs: vec![], },
location.to_locations(),
ConstraintCategory::Boring,
) {
span_mirbug!(
self,
constant,
"bad constant user type {:?} vs {:?}: {:?}",
user_ty,
constant.ty,
terr,
);
}
}
}
fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
self.super_rvalue(rvalue, location);
let rval_ty = rvalue.ty(self.mir, self.tcx());
self.sanitize_type(rvalue, rval_ty);
}
fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
self.super_local_decl(local, local_decl);
self.sanitize_type(local_decl, local_decl.ty);
for (user_ty, span) in local_decl.user_ty.projections_and_spans() {
if let Err(terr) = self.cx.relate_type_and_user_type(
local_decl.ty,
ty::Variance::Invariant,
user_ty,
Locations::All(*span),
ConstraintCategory::TypeAnnotation,
) {
span_mirbug!(
self,
local,
"bad user type on variable {:?}: {:?} != {:?} ({:?})",
local,
local_decl.ty,
local_decl.user_ty,
terr,
);
}
}
}
fn visit_mir(&mut self, mir: &Mir<'tcx>) {
self.sanitize_type(&"return type", mir.return_ty());
for local_decl in &mir.local_decls {
self.sanitize_type(local_decl, local_decl.ty);
}
if self.errors_reported {
return;
}
self.super_mir(mir);
}
}
impl<'a, 'b, 'gcx, 'tcx> TypeVerifier<'a, 'b, 'gcx, 'tcx> {
fn new(cx: &'a mut TypeChecker<'b, 'gcx, 'tcx>, mir: &'a Mir<'tcx>) -> Self {
TypeVerifier {
mir,
mir_def_id: cx.mir_def_id,
cx,
last_span: mir.span,
errors_reported: false,
}
}
fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
self.cx.infcx.tcx
}
fn sanitize_type(&mut self, parent: &dyn fmt::Debug, ty: Ty<'tcx>) -> Ty<'tcx> {
if ty.has_escaping_bound_vars() || ty.references_error() {
span_mirbug_and_err!(self, parent, "bad type {:?}", ty)
} else {
ty
}
}
/// Checks that the constant's `ty` field matches up with what
/// would be expected from its literal.
fn sanitize_constant(&mut self, constant: &Constant<'tcx>, location: Location) {
debug!(
"sanitize_constant(constant={:?}, location={:?})",
constant, location
);
// FIXME(#46702) -- We need some way to get the predicates
// associated with the "pre-evaluated" form of the
// constant. For example, consider that the constant
// may have associated constant projections (`<Foo as
// Trait<'a, 'b>>::SOME_CONST`) that impose
// constraints on `'a` and `'b`. These constraints
// would be lost if we just look at the normalized
// value.
if let ty::FnDef(def_id, substs) = constant.literal.ty.sty {
let tcx = self.tcx();
let type_checker = &mut self.cx;
// FIXME -- For now, use the substitutions from
// `value.ty` rather than `value.val`. The
// renumberer will rewrite them to independent
// sets of regions; in principle, we ought to
// derive the type of the `value.val` from "first
// principles" and equate with value.ty, but as we
// are transitioning to the miri-based system, we
// don't have a handy function for that, so for
// now we just ignore `value.val` regions.
let instantiated_predicates = tcx.predicates_of(def_id).instantiate(tcx, substs);
type_checker.normalize_and_prove_instantiated_predicates(
instantiated_predicates,
location.to_locations(),
);
}
debug!("sanitize_constant: expected_ty={:?}", constant.literal.ty);
if let Err(terr) = self.cx.eq_types(
constant.literal.ty,
constant.ty,
location.to_locations(),
ConstraintCategory::Boring,
) {
span_mirbug!(
self,
constant,
"constant {:?} should have type {:?} but has {:?} ({:?})",
constant,
constant.literal.ty,
constant.ty,
terr,
);
}
}
/// Checks that the types internal to the `place` match up with
/// what would be expected.
fn sanitize_place(
&mut self,
place: &Place<'tcx>,
location: Location,
context: PlaceContext,
) -> PlaceTy<'tcx> {
debug!("sanitize_place: {:?}", place);
let place_ty = match *place {
Place::Local(index) => PlaceTy::Ty {
ty: self.mir.local_decls[index].ty,
},
Place::Promoted(box (_index, sty)) => {
let sty = self.sanitize_type(place, sty);
// FIXME -- promoted MIR return types reference
// various "free regions" (e.g., scopes and things)
// that they ought not to do. We have to figure out
// how best to handle that -- probably we want treat
// promoted MIR much like closures, renumbering all
// their free regions and propagating constraints
// upwards. We have the same acyclic guarantees, so
// that should be possible. But for now, ignore them.
//
// let promoted_mir = &self.mir.promoted[index];
// promoted_mir.return_ty()
PlaceTy::Ty { ty: sty }
}
Place::Static(box Static { def_id, ty: sty }) => {
let sty = self.sanitize_type(place, sty);
let ty = self.tcx().type_of(def_id);
let ty = self.cx.normalize(ty, location);
if let Err(terr) =
self.cx
.eq_types(ty, sty, location.to_locations(), ConstraintCategory::Boring)
{
span_mirbug!(
self,
place,
"bad static type ({:?}: {:?}): {:?}",
ty,
sty,
terr
);
}
PlaceTy::Ty { ty: sty }
}
Place::Projection(ref proj) => {
let base_context = if context.is_mutating_use() {
PlaceContext::MutatingUse(MutatingUseContext::Projection)
} else {
PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
};
let base_ty = self.sanitize_place(&proj.base, location, base_context);
if let PlaceTy::Ty { ty } = base_ty {
if ty.references_error() {
assert!(self.errors_reported);
return PlaceTy::Ty {
ty: self.tcx().types.err,
};
}
}
self.sanitize_projection(base_ty, &proj.elem, place, location)
}
};
if let PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy) = context {
let tcx = self.tcx();
let trait_ref = ty::TraitRef {
def_id: tcx.lang_items().copy_trait().unwrap(),
substs: tcx.mk_substs_trait(place_ty.to_ty(tcx), &[]),
};
// In order to have a Copy operand, the type T of the value must be Copy. Note that we
// prove that T: Copy, rather than using the type_moves_by_default test. This is
// important because type_moves_by_default ignores the resulting region obligations and
// assumes they pass. This can result in bounds from Copy impls being unsoundly ignored
// (e.g., #29149). Note that we decide to use Copy before knowing whether the bounds
// fully apply: in effect, the rule is that if a value of some type could implement
// Copy, then it must.
self.cx.prove_trait_ref(
trait_ref,
location.to_locations(),
ConstraintCategory::CopyBound,
);
}
place_ty
}
fn sanitize_projection(
&mut self,
base: PlaceTy<'tcx>,
pi: &PlaceElem<'tcx>,
place: &Place<'tcx>,
location: Location,
) -> PlaceTy<'tcx> {
debug!("sanitize_projection: {:?} {:?} {:?}", base, pi, place);
let tcx = self.tcx();
let base_ty = base.to_ty(tcx);
match *pi {
ProjectionElem::Deref => {
let deref_ty = base_ty.builtin_deref(true);
PlaceTy::Ty {
ty: deref_ty.map(|t| t.ty).unwrap_or_else(|| {
span_mirbug_and_err!(self, place, "deref of non-pointer {:?}", base_ty)
}),
}
}
ProjectionElem::Index(i) => {
let index_ty = Place::Local(i).ty(self.mir, tcx).to_ty(tcx);
if index_ty != tcx.types.usize {
PlaceTy::Ty {
ty: span_mirbug_and_err!(self, i, "index by non-usize {:?}", i),
}
} else {
PlaceTy::Ty {
ty: base_ty.builtin_index().unwrap_or_else(|| {
span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
}),
}
}
}
ProjectionElem::ConstantIndex { .. } => {
// consider verifying in-bounds
PlaceTy::Ty {
ty: base_ty.builtin_index().unwrap_or_else(|| {
span_mirbug_and_err!(self, place, "index of non-array {:?}", base_ty)
}),
}
}
ProjectionElem::Subslice { from, to } => PlaceTy::Ty {
ty: match base_ty.sty {
ty::Array(inner, size) => {
let size = size.unwrap_usize(tcx);
let min_size = (from as u64) + (to as u64);
if let Some(rest_size) = size.checked_sub(min_size) {
tcx.mk_array(inner, rest_size)
} else {
span_mirbug_and_err!(
self,
place,
"taking too-small slice of {:?}",
base_ty
)
}
}
ty::Slice(..) => base_ty,
_ => span_mirbug_and_err!(self, place, "slice of non-array {:?}", base_ty),
},
},
ProjectionElem::Downcast(adt_def1, index) => match base_ty.sty {
ty::Adt(adt_def, substs) if adt_def.is_enum() && adt_def == adt_def1 => {
if index.as_usize() >= adt_def.variants.len() {
PlaceTy::Ty {
ty: span_mirbug_and_err!(
self,
place,
"cast to variant #{:?} but enum only has {:?}",
index,
adt_def.variants.len()
),
}
} else {
PlaceTy::Downcast {
adt_def,
substs,
variant_index: index,
}
}
}
_ => PlaceTy::Ty {
ty: span_mirbug_and_err!(
self,
place,
"can't downcast {:?} as {:?}",
base_ty,
adt_def1
),
},
},
ProjectionElem::Field(field, fty) => {
let fty = self.sanitize_type(place, fty);
match self.field_ty(place, base, field, location) {
Ok(ty) => if let Err(terr) = self.cx.eq_types(
ty,
fty,
location.to_locations(),
ConstraintCategory::Boring,
) {
span_mirbug!(
self,
place,
"bad field access ({:?}: {:?}): {:?}",
ty,
fty,
terr
);
},
Err(FieldAccessError::OutOfRange { field_count }) => span_mirbug!(
self,
place,
"accessed field #{} but variant only has {}",
field.index(),
field_count
),
}
PlaceTy::Ty { ty: fty }
}
}
}
fn error(&mut self) -> Ty<'tcx> {
self.errors_reported = true;
self.tcx().types.err
}
fn field_ty(
&mut self,
parent: &dyn fmt::Debug,
base_ty: PlaceTy<'tcx>,
field: Field,
location: Location,
) -> Result<Ty<'tcx>, FieldAccessError> {
let tcx = self.tcx();
let (variant, substs) = match base_ty {
PlaceTy::Downcast {
adt_def,
substs,
variant_index,
} => (&adt_def.variants[variant_index], substs),
PlaceTy::Ty { ty } => match ty.sty {
ty::Adt(adt_def, substs) if !adt_def.is_enum() =>
(&adt_def.variants[VariantIdx::new(0)], substs),
ty::Closure(def_id, substs) => {
return match substs.upvar_tys(def_id, tcx).nth(field.index()) {
Some(ty) => Ok(ty),
None => Err(FieldAccessError::OutOfRange {
field_count: substs.upvar_tys(def_id, tcx).count(),
}),
}
}
ty::Generator(def_id, substs, _) => {
// Try pre-transform fields first (upvars and current state)
if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field.index()) {
return Ok(ty);
}
// Then try `field_tys` which contains all the fields, but it
// requires the final optimized MIR.
return match substs.field_tys(def_id, tcx).nth(field.index()) {
Some(ty) => Ok(ty),
None => Err(FieldAccessError::OutOfRange {
field_count: substs.field_tys(def_id, tcx).count(),
}),
};
}
ty::Tuple(tys) => {
return match tys.get(field.index()) {
Some(&ty) => Ok(ty),
None => Err(FieldAccessError::OutOfRange {
field_count: tys.len(),
}),
}
}
_ => {
return Ok(span_mirbug_and_err!(
self,
parent,
"can't project out of {:?}",
base_ty
))
}
},
};
if let Some(field) = variant.fields.get(field.index()) {
Ok(self.cx.normalize(&field.ty(tcx, substs), location))
} else {
Err(FieldAccessError::OutOfRange {
field_count: variant.fields.len(),
})
}
}
}
/// The MIR type checker. Visits the MIR and enforces all the
/// constraints needed for it to be valid and well-typed. Along the
/// way, it accrues region constraints -- these can later be used by
/// NLL region checking.
struct TypeChecker<'a, 'gcx: 'tcx, 'tcx: 'a> {
infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
param_env: ty::ParamEnv<'gcx>,
last_span: Span,
mir: &'a Mir<'tcx>,
mir_def_id: DefId,
region_bound_pairs: &'a RegionBoundPairs<'tcx>,
implicit_region_bound: Option<ty::Region<'tcx>>,
reported_errors: FxHashSet<(Ty<'tcx>, Span)>,
borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
}
struct BorrowCheckContext<'a, 'tcx: 'a> {
universal_regions: &'a UniversalRegions<'tcx>,
location_table: &'a LocationTable,
all_facts: &'a mut Option<AllFacts>,
borrow_set: &'a BorrowSet<'tcx>,
constraints: &'a mut MirTypeckRegionConstraints<'tcx>,
}
crate struct MirTypeckResults<'tcx> {
crate constraints: MirTypeckRegionConstraints<'tcx>,
crate universal_region_relations: Rc<UniversalRegionRelations<'tcx>>,
}
/// A collection of region constraints that must be satisfied for the
/// program to be considered well-typed.
crate struct MirTypeckRegionConstraints<'tcx> {
/// Maps from a `ty::Placeholder` to the corresponding
/// `PlaceholderIndex` bit that we will use for it.
///
/// To keep everything in sync, do not insert this set
/// directly. Instead, use the `placeholder_region` helper.
crate placeholder_indices: PlaceholderIndices,
/// Each time we add a placeholder to `placeholder_indices`, we
/// also create a corresponding "representative" region vid for
/// that wraps it. This vector tracks those. This way, when we
/// convert the same `ty::RePlaceholder(p)` twice, we can map to
/// the same underlying `RegionVid`.
crate placeholder_index_to_region: IndexVec<PlaceholderIndex, ty::Region<'tcx>>,
/// In general, the type-checker is not responsible for enforcing
/// liveness constraints; this job falls to the region inferencer,
/// which performs a liveness analysis. However, in some limited
/// cases, the MIR type-checker creates temporary regions that do
/// not otherwise appear in the MIR -- in particular, the
/// late-bound regions that it instantiates at call-sites -- and
/// hence it must report on their liveness constraints.
crate liveness_constraints: LivenessValues<RegionVid>,
crate outlives_constraints: ConstraintSet,
crate closure_bounds_mapping:
FxHashMap<Location, FxHashMap<(RegionVid, RegionVid), (ConstraintCategory, Span)>>,
crate type_tests: Vec<TypeTest<'tcx>>,
}
impl MirTypeckRegionConstraints<'tcx> {
fn placeholder_region(
&mut self,
infcx: &InferCtxt<'_, '_, 'tcx>,
placeholder: ty::PlaceholderRegion,
) -> ty::Region<'tcx> {
let placeholder_index = self.placeholder_indices.insert(placeholder);
match self.placeholder_index_to_region.get(placeholder_index) {
Some(&v) => v,
None => {
let origin = NLLRegionVariableOrigin::Placeholder(placeholder);
let region = infcx.next_nll_region_var_in_universe(origin, placeholder.universe);
self.placeholder_index_to_region.push(region);
region
}
}
}
}
/// The `Locations` type summarizes *where* region constraints are
/// required to hold. Normally, this is at a particular point which
/// created the obligation, but for constraints that the user gave, we
/// want the constraint to hold at all points.
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub enum Locations {
/// Indicates that a type constraint should always be true. This
/// is particularly important in the new borrowck analysis for
/// things like the type of the return slot. Consider this
/// example:
///
/// ```
/// fn foo<'a>(x: &'a u32) -> &'a u32 {
/// let y = 22;
/// return &y; // error
/// }
/// ```
///
/// Here, we wind up with the signature from the return type being
/// something like `&'1 u32` where `'1` is a universal region. But
/// the type of the return slot `_0` is something like `&'2 u32`
/// where `'2` is an existential region variable. The type checker
/// requires that `&'2 u32 = &'1 u32` -- but at what point? In the
/// older NLL analysis, we required this only at the entry point
/// to the function. By the nature of the constraints, this wound
/// up propagating to all points reachable from start (because
/// `'1` -- as a universal region -- is live everywhere). In the
/// newer analysis, though, this doesn't work: `_0` is considered
/// dead at the start (it has no usable value) and hence this type
/// equality is basically a no-op. Then, later on, when we do `_0
/// = &'3 y`, that region `'3` never winds up related to the
/// universal region `'1` and hence no error occurs. Therefore, we
/// use Locations::All instead, which ensures that the `'1` and
/// `'2` are equal everything. We also use this for other
/// user-given type annotations; e.g., if the user wrote `let mut
/// x: &'static u32 = ...`, we would ensure that all values
/// assigned to `x` are of `'static` lifetime.
///
/// The span points to the place the constraint arose. For example,
/// it points to the type in a user-given type annotation. If
/// there's no sensible span then it's DUMMY_SP.
All(Span),
/// An outlives constraint that only has to hold at a single location,
/// usually it represents a point where references flow from one spot to
/// another (e.g., `x = y`)
Single(Location),
}
impl Locations {
pub fn from_location(&self) -> Option<Location> {
match self {
Locations::All(_) => None,
Locations::Single(from_location) => Some(*from_location),
}
}
/// Gets a span representing the location.
pub fn span(&self, mir: &Mir<'_>) -> Span {
match self {
Locations::All(span) => *span,
Locations::Single(l) => mir.source_info(*l).span,
}
}
}
impl<'a, 'gcx, 'tcx> TypeChecker<'a, 'gcx, 'tcx> {
fn new(
infcx: &'a InferCtxt<'a, 'gcx, 'tcx>,
mir: &'a Mir<'tcx>,
mir_def_id: DefId,
param_env: ty::ParamEnv<'gcx>,
region_bound_pairs: &'a RegionBoundPairs<'tcx>,
implicit_region_bound: Option<ty::Region<'tcx>>,
borrowck_context: Option<&'a mut BorrowCheckContext<'a, 'tcx>>,
universal_region_relations: Option<&'a UniversalRegionRelations<'tcx>>,
) -> Self {
TypeChecker {
infcx,
last_span: DUMMY_SP,
mir,
mir_def_id,
param_env,
region_bound_pairs,
implicit_region_bound,
borrowck_context,
reported_errors: Default::default(),
universal_region_relations,
}
}
/// Given some operation `op` that manipulates types, proves
/// predicates, or otherwise uses the inference context, executes
/// `op` and then executes all the further obligations that `op`
/// returns. This will yield a set of outlives constraints amongst
/// regions which are extracted and stored as having occurred at
/// `locations`.
///
/// **Any `rustc::infer` operations that might generate region
/// constraints should occur within this method so that those
/// constraints can be properly localized!**
fn fully_perform_op<R>(
&mut self,
locations: Locations,
category: ConstraintCategory,
op: impl type_op::TypeOp<'gcx, 'tcx, Output = R>,
) -> Fallible<R> {
let (r, opt_data) = op.fully_perform(self.infcx)?;
if let Some(data) = &opt_data {
self.push_region_constraints(locations, category, data);
}
Ok(r)
}
fn push_region_constraints(
&mut self,
locations: Locations,
category: ConstraintCategory,
data: &[QueryRegionConstraint<'tcx>],
) {
debug!(
"push_region_constraints: constraints generated at {:?} are {:#?}",
locations, data
);
if let Some(ref mut borrowck_context) = self.borrowck_context {
constraint_conversion::ConstraintConversion::new(
self.infcx,
borrowck_context.universal_regions,
self.region_bound_pairs,
self.implicit_region_bound,
self.param_env,
locations,
category,
&mut borrowck_context.constraints,
).convert_all(&data);
}
}
/// Convenient wrapper around `relate_tys::relate_types` -- see
/// that fn for docs.
fn relate_types(
&mut self,
a: Ty<'tcx>,
v: ty::Variance,
b: Ty<'tcx>,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
relate_tys::relate_types(
self.infcx,
a,
v,
b,
locations,
category,
self.borrowck_context.as_mut().map(|x| &mut **x),
)
}
fn sub_types(
&mut self,
sub: Ty<'tcx>,
sup: Ty<'tcx>,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
self.relate_types(sub, ty::Variance::Covariant, sup, locations, category)
}
/// Try to relate `sub <: sup`; if this fails, instantiate opaque
/// variables in `sub` with their inferred definitions and try
/// again. This is used for opaque types in places (e.g., `let x:
/// impl Foo = ..`).
fn sub_types_or_anon(
&mut self,
sub: Ty<'tcx>,
sup: Ty<'tcx>,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
if let Err(terr) = self.sub_types(sub, sup, locations, category) {
if let TyKind::Opaque(..) = sup.sty {
// When you have `let x: impl Foo = ...` in a closure,
// the resulting inferend values are stored with the
// def-id of the base function.
let parent_def_id = self.tcx().closure_base_def_id(self.mir_def_id);
return self.eq_opaque_type_and_type(sub, sup, parent_def_id, locations, category);
} else {
return Err(terr);
}
}
Ok(())
}
fn eq_types(
&mut self,
a: Ty<'tcx>,
b: Ty<'tcx>,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
self.relate_types(a, ty::Variance::Invariant, b, locations, category)
}
fn relate_type_and_user_type(
&mut self,
a: Ty<'tcx>,
v: ty::Variance,
user_ty: &UserTypeProjection<'tcx>,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
debug!(
"relate_type_and_user_type(a={:?}, v={:?}, user_ty={:?}, locations={:?})",
a, v, user_ty, locations,
);
match user_ty.base {
UserTypeAnnotation::Ty(canonical_ty) => {
let (ty, _) = self.infcx
.instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_ty);
// The `TypeRelating` code assumes that "unresolved inference
// variables" appear in the "a" side, so flip `Contravariant`
// ambient variance to get the right relationship.
let v1 = ty::Contravariant.xform(v);
let tcx = self.infcx.tcx;
let ty = self.normalize(ty, locations);
// We need to follow any provided projetions into the type.
//
// if we hit a ty var as we descend, then just skip the
// attempt to relate the mir local with any type.
#[derive(Debug)] struct HitTyVar;
let mut curr_projected_ty: Result<PlaceTy, HitTyVar>;
curr_projected_ty = Ok(PlaceTy::from_ty(ty));
for proj in &user_ty.projs {
let projected_ty = if let Ok(projected_ty) = curr_projected_ty {
projected_ty
} else {
break;
};
curr_projected_ty = projected_ty.projection_ty_core(
tcx, proj, |this, field, &()| {
if this.to_ty(tcx).is_ty_var() {
Err(HitTyVar)
} else {
let ty = this.field_ty(tcx, field);
Ok(self.normalize(ty, locations))
}
});
}
debug!("user_ty base: {:?} freshened: {:?} projs: {:?} yields: {:?}",
user_ty.base, ty, user_ty.projs, curr_projected_ty);
if let Ok(projected_ty) = curr_projected_ty {
let ty = projected_ty.to_ty(tcx);
self.relate_types(ty, v1, a, locations, category)?;
}
}
UserTypeAnnotation::TypeOf(def_id, canonical_substs) => {
let (
user_substs,
_,
) = self.infcx
.instantiate_canonical_with_fresh_inference_vars(DUMMY_SP, &canonical_substs);
let projs = self.infcx.tcx.intern_projs(&user_ty.projs);
self.fully_perform_op(
locations,
category,
self.param_env.and(type_op::ascribe_user_type::AscribeUserType::new(
a, v, def_id, user_substs, projs,
)),
)?;
}
}
Ok(())
}
fn eq_opaque_type_and_type(
&mut self,
revealed_ty: Ty<'tcx>,
anon_ty: Ty<'tcx>,
anon_owner_def_id: DefId,
locations: Locations,
category: ConstraintCategory,
) -> Fallible<()> {
debug!(
"eq_opaque_type_and_type( \
revealed_ty={:?}, \
anon_ty={:?})",
revealed_ty, anon_ty
);
let infcx = self.infcx;
let tcx = infcx.tcx;
let param_env = self.param_env;
debug!("eq_opaque_type_and_type: mir_def_id={:?}", self.mir_def_id);
let opaque_type_map = self.fully_perform_op(
locations,
category,
CustomTypeOp::new(
|infcx| {
let mut obligations = ObligationAccumulator::default();
let dummy_body_id = ObligationCause::dummy().body_id;
let (output_ty, opaque_type_map) =
obligations.add(infcx.instantiate_opaque_types(
anon_owner_def_id,
dummy_body_id,
param_env,
&anon_ty,
));
debug!(
"eq_opaque_type_and_type: \
instantiated output_ty={:?} \
opaque_type_map={:#?} \
revealed_ty={:?}",
output_ty, opaque_type_map, revealed_ty
);
obligations.add(infcx
.at(&ObligationCause::dummy(), param_env)
.eq(output_ty, revealed_ty)?);
for (&opaque_def_id, opaque_decl) in &opaque_type_map {
let opaque_defn_ty = tcx.type_of(opaque_def_id);
let opaque_defn_ty = opaque_defn_ty.subst(tcx, opaque_decl.substs);
let opaque_defn_ty = renumber::renumber_regions(infcx, &opaque_defn_ty);
debug!(
"eq_opaque_type_and_type: concrete_ty={:?}={:?} opaque_defn_ty={:?}",
opaque_decl.concrete_ty,
infcx.resolve_type_vars_if_possible(&opaque_decl.concrete_ty),
opaque_defn_ty
);
obligations.add(infcx
.at(&ObligationCause::dummy(), param_env)
.eq(opaque_decl.concrete_ty, opaque_defn_ty)?);
}
debug!("eq_opaque_type_and_type: equated");
Ok(InferOk {
value: Some(opaque_type_map),
obligations: obligations.into_vec(),
})
},
|| "input_output".to_string(),
),
)?;
let universal_region_relations = match self.universal_region_relations {
Some(rel) => rel,
None => return Ok(()),
};
// Finally, if we instantiated the anon types successfully, we
// have to solve any bounds (e.g., `-> impl Iterator` needs to
// prove that `T: Iterator` where `T` is the type we
// instantiated it with).
if let Some(opaque_type_map) = opaque_type_map {
for (opaque_def_id, opaque_decl) in opaque_type_map {
self.fully_perform_op(
locations,
ConstraintCategory::OpaqueType,
CustomTypeOp::new(
|_cx| {
infcx.constrain_opaque_type(
opaque_def_id,
&opaque_decl,
universal_region_relations,
);
Ok(InferOk {
value: (),
obligations: vec![],
})
},
|| "opaque_type_map".to_string(),
),
)?;
}
}
Ok(())
}
fn tcx(&self) -> TyCtxt<'a, 'gcx, 'tcx> {
self.infcx.tcx
}
fn check_stmt(&mut self, mir: &Mir<'tcx>, stmt: &Statement<'tcx>, location: Location) {
debug!("check_stmt: {:?}", stmt);
let tcx = self.tcx();
match stmt.kind {
StatementKind::Assign(ref place, ref rv) => {
// Assignments to temporaries are not "interesting";
// they are not caused by the user, but rather artifacts
// of lowering. Assignments to other sorts of places *are* interesting
// though.
let category = match *place {
Place::Local(RETURN_PLACE) => if let Some(BorrowCheckContext {
universal_regions:
UniversalRegions {
defining_ty: DefiningTy::Const(def_id, _),
..
},
..
}) = self.borrowck_context
{
if tcx.is_static(*def_id).is_some() {
ConstraintCategory::UseAsStatic
} else {
ConstraintCategory::UseAsConst
}
} else {
ConstraintCategory::Return
},
Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
ConstraintCategory::Boring
}
_ => ConstraintCategory::Assignment,
};
let place_ty = place.ty(mir, tcx).to_ty(tcx);
let rv_ty = rv.ty(mir, tcx);
if let Err(terr) =
self.sub_types_or_anon(rv_ty, place_ty, location.to_locations(), category)
{
span_mirbug!(
self,
stmt,
"bad assignment ({:?} = {:?}): {:?}",
place_ty,
rv_ty,
terr
);
}
if let Some(user_ty) = self.rvalue_user_ty(rv) {
if let Err(terr) = self.relate_type_and_user_type(
rv_ty,
ty::Variance::Invariant,
&UserTypeProjection { base: user_ty, projs: vec![], },
location.to_locations(),
ConstraintCategory::Boring,
) {
span_mirbug!(
self,
stmt,
"bad user type on rvalue ({:?} = {:?}): {:?}",
user_ty,
rv_ty,
terr
);
}
}
self.check_rvalue(mir, rv, location);
if !self.tcx().features().unsized_locals {
let trait_ref = ty::TraitRef {
def_id: tcx.lang_items().sized_trait().unwrap(),
substs: tcx.mk_substs_trait(place_ty, &[]),
};
self.prove_trait_ref(
trait_ref,
location.to_locations(),
ConstraintCategory::SizedBound,
);
}
}
StatementKind::SetDiscriminant {
ref place,
variant_index,
} => {
let place_type = place.ty(mir, tcx).to_ty(tcx);
let adt = match place_type.sty {
TyKind::Adt(adt, _) if adt.is_enum() => adt,
_ => {
span_bug!(
stmt.source_info.span,
"bad set discriminant ({:?} = {:?}): lhs is not an enum",
place,
variant_index
);
}
};
if variant_index.as_usize() >= adt.variants.len() {
span_bug!(
stmt.source_info.span,
"bad set discriminant ({:?} = {:?}): value of of range",
place,
variant_index
);
};
}
StatementKind::AscribeUserType(ref place, variance, box ref c_ty) => {
let place_ty = place.ty(mir, tcx).to_ty(tcx);
if let Err(terr) = self.relate_type_and_user_type(
place_ty,
variance,
c_ty,
Locations::All(stmt.source_info.span),
ConstraintCategory::TypeAnnotation,
) {
span_mirbug!(
self,
stmt,
"bad type assert ({:?} <: {:?}): {:?}",
place_ty,
c_ty,
terr
);
}
}
StatementKind::FakeRead(..)
| StatementKind::StorageLive(..)
| StatementKind::StorageDead(..)
| StatementKind::InlineAsm { .. }
| StatementKind::Retag { .. }
| StatementKind::EscapeToRaw { .. }
| StatementKind::Nop => {}
}
}
fn check_terminator(
&mut self,
mir: &Mir<'tcx>,
term: &Terminator<'tcx>,
term_location: Location,
) {
debug!("check_terminator: {:?}", term);
let tcx = self.tcx();
match term.kind {
TerminatorKind::Goto { .. }
| TerminatorKind::Resume
| TerminatorKind::Abort
| TerminatorKind::Return
| TerminatorKind::GeneratorDrop
| TerminatorKind::Unreachable
| TerminatorKind::Drop { .. }
| TerminatorKind::FalseEdges { .. }
| TerminatorKind::FalseUnwind { .. } => {
// no checks needed for these
}
TerminatorKind::DropAndReplace {
ref location,
ref value,
target: _,
unwind: _,
} => {
let place_ty = location.ty(mir, tcx).to_ty(tcx);
let rv_ty = value.ty(mir, tcx);
let locations = term_location.to_locations();
if let Err(terr) =
self.sub_types(rv_ty, place_ty, locations, ConstraintCategory::Assignment)
{
span_mirbug!(
self,
term,
"bad DropAndReplace ({:?} = {:?}): {:?}",
place_ty,
rv_ty,
terr
);
}
}
TerminatorKind::SwitchInt {
ref discr,
switch_ty,
..
} => {
let discr_ty = discr.ty(mir, tcx);
if let Err(terr) = self.sub_types(
discr_ty,
switch_ty,
term_location.to_locations(),
ConstraintCategory::Assignment,
) {
span_mirbug!(
self,
term,
"bad SwitchInt ({:?} on {:?}): {:?}",
switch_ty,
discr_ty,
terr
);
}
if !switch_ty.is_integral() && !switch_ty.is_char() && !switch_ty.is_bool() {
span_mirbug!(self, term, "bad SwitchInt discr ty {:?}", switch_ty);
}
// FIXME: check the values
}
TerminatorKind::Call {
ref func,
ref args,
ref destination,
from_hir_call,
..
} => {
let func_ty = func.ty(mir, tcx);
debug!("check_terminator: call, func_ty={:?}", func_ty);
let sig = match func_ty.sty {
ty::FnDef(..) | ty::FnPtr(_) => func_ty.fn_sig(tcx),
_ => {
span_mirbug!(self, term, "call to non-function {:?}", func_ty);
return;
}
};
let (sig, map) = self.infcx.replace_bound_vars_with_fresh_vars(
term.source_info.span,
LateBoundRegionConversionTime::FnCall,
&sig,
);
let sig = self.normalize(sig, term_location);
self.check_call_dest(mir, term, &sig, destination, term_location);
self.prove_predicates(
sig.inputs().iter().map(|ty| ty::Predicate::WellFormed(ty)),
term_location.to_locations(),
ConstraintCategory::Boring,
);
// The ordinary liveness rules will ensure that all
// regions in the type of the callee are live here. We
// then further constrain the late-bound regions that
// were instantiated at the call site to be live as
// well. The resulting is that all the input (and
// output) types in the signature must be live, since
// all the inputs that fed into it were live.
for &late_bound_region in map.values() {
if let Some(ref mut borrowck_context) = self.borrowck_context {
let region_vid = borrowck_context
.universal_regions
.to_region_vid(late_bound_region);
borrowck_context
.constraints
.liveness_constraints
.add_element(region_vid, term_location);
}
}
self.check_call_inputs(mir, term, &sig, args, term_location, from_hir_call);
}
TerminatorKind::Assert {
ref cond, ref msg, ..
} => {
let cond_ty = cond.ty(mir, tcx);
if cond_ty != tcx.types.bool {
span_mirbug!(self, term, "bad Assert ({:?}, not bool", cond_ty);
}
if let BoundsCheck { ref len, ref index } = *msg {
if len.ty(mir, tcx) != tcx.types.usize {
span_mirbug!(self, len, "bounds-check length non-usize {:?}", len)
}
if index.ty(mir, tcx) != tcx.types.usize {
span_mirbug!(self, index, "bounds-check index non-usize {:?}", index)
}
}
}
TerminatorKind::Yield { ref value, .. } => {
let value_ty = value.ty(mir, tcx);
match mir.yield_ty {
None => span_mirbug!(self, term, "yield in non-generator"),
Some(ty) => {
if let Err(terr) = self.sub_types(
value_ty,
ty,
term_location.to_locations(),
ConstraintCategory::Yield,
) {
span_mirbug!(
self,
term,
"type of yield value is {:?}, but the yield type is {:?}: {:?}",
value_ty,
ty,
terr
);
}
}
}
}
}
}
fn check_call_dest(
&mut self,
mir: &Mir<'tcx>,
term: &Terminator<'tcx>,
sig: &ty::FnSig<'tcx>,
destination: &Option<(Place<'tcx>, BasicBlock)>,
term_location: Location,
) {
let tcx = self.tcx();
match *destination {
Some((ref dest, _target_block)) => {
let dest_ty = dest.ty(mir, tcx).to_ty(tcx);
let category = match *dest {
Place::Local(RETURN_PLACE) => {
if let Some(BorrowCheckContext {
universal_regions:
UniversalRegions {
defining_ty: DefiningTy::Const(def_id, _),
..
},
..
}) = self.borrowck_context
{
if tcx.is_static(*def_id).is_some() {
ConstraintCategory::UseAsStatic
} else {
ConstraintCategory::UseAsConst
}
} else {
ConstraintCategory::Return
}
}
Place::Local(l) if !mir.local_decls[l].is_user_variable.is_some() => {
ConstraintCategory::Boring
}
_ => ConstraintCategory::Assignment,
};
let locations = term_location.to_locations();
if let Err(terr) =
self.sub_types_or_anon(sig.output(), dest_ty, locations, category)
{
span_mirbug!(
self,
term,
"call dest mismatch ({:?} <- {:?}): {:?}",
dest_ty,
sig.output(),
terr
);
}
// When `#![feature(unsized_locals)]` is not enabled,
// this check is done at `check_local`.
if self.tcx().features().unsized_locals {
let span = term.source_info.span;
self.ensure_place_sized(dest_ty, span);
}
}
None => {
// FIXME(canndrew): This is_never should probably be an is_uninhabited
if !sig.output().is_never() {
span_mirbug!(self, term, "call to converging function {:?} w/o dest", sig);
}
}
}
}
fn check_call_inputs(
&mut self,
mir: &Mir<'tcx>,
term: &Terminator<'tcx>,
sig: &ty::FnSig<'tcx>,
args: &[Operand<'tcx>],
term_location: Location,
from_hir_call: bool,
) {
debug!("check_call_inputs({:?}, {:?})", sig, args);
if args.len() < sig.inputs().len() || (args.len() > sig.inputs().len() && !sig.variadic) {
span_mirbug!(self, term, "call to {:?} with wrong # of args", sig);
}
for (n, (fn_arg, op_arg)) in sig.inputs().iter().zip(args).enumerate() {
let op_arg_ty = op_arg.ty(mir, self.tcx());
let category = if from_hir_call {
ConstraintCategory::CallArgument
} else {
ConstraintCategory::Boring
};
if let Err(terr) =
self.sub_types(op_arg_ty, fn_arg, term_location.to_locations(), category)
{
span_mirbug!(
self,
term,
"bad arg #{:?} ({:?} <- {:?}): {:?}",
n,
fn_arg,
op_arg_ty,
terr
);
}
}
}
fn check_iscleanup(&mut self, mir: &Mir<'tcx>, block_data: &BasicBlockData<'tcx>) {
let is_cleanup = block_data.is_cleanup;
self.last_span = block_data.terminator().source_info.span;
match block_data.terminator().kind {
TerminatorKind::Goto { target } => {
self.assert_iscleanup(mir, block_data, target, is_cleanup)
}
TerminatorKind::SwitchInt { ref targets, .. } => for target in targets {
self.assert_iscleanup(mir, block_data, *target, is_cleanup);
},
TerminatorKind::Resume => if !is_cleanup {
span_mirbug!(self, block_data, "resume on non-cleanup block!")
},
TerminatorKind::Abort => if !is_cleanup {
span_mirbug!(self, block_data, "abort on non-cleanup block!")
},
TerminatorKind::Return => if is_cleanup {
span_mirbug!(self, block_data, "return on cleanup block")
},
TerminatorKind::GeneratorDrop { .. } => if is_cleanup {
span_mirbug!(self, block_data, "generator_drop in cleanup block")
},
TerminatorKind::Yield { resume, drop, .. } => {
if is_cleanup {
span_mirbug!(self, block_data, "yield in cleanup block")
}
self.assert_iscleanup(mir, block_data, resume, is_cleanup);
if let Some(drop) = drop {
self.assert_iscleanup(mir, block_data, drop, is_cleanup);
}
}
TerminatorKind::Unreachable => {}
TerminatorKind::Drop { target, unwind, .. }
| TerminatorKind::DropAndReplace { target, unwind, .. }
| TerminatorKind::Assert {
target,
cleanup: unwind,
..
} => {
self.assert_iscleanup(mir, block_data, target, is_cleanup);
if let Some(unwind) = unwind {
if is_cleanup {
span_mirbug!(self, block_data, "unwind on cleanup block")
}
self.assert_iscleanup(mir, block_data, unwind, true);
}
}
TerminatorKind::Call {
ref destination,
cleanup,
..
} => {
if let &Some((_, target)) = destination {
self.assert_iscleanup(mir, block_data, target, is_cleanup);
}
if let Some(cleanup) = cleanup {
if is_cleanup {
span_mirbug!(self, block_data, "cleanup on cleanup block")
}
self.assert_iscleanup(mir, block_data, cleanup, true);
}
}
TerminatorKind::FalseEdges {
real_target,
ref imaginary_targets,
} => {
self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
for target in imaginary_targets {
self.assert_iscleanup(mir, block_data, *target, is_cleanup);
}
}
TerminatorKind::FalseUnwind {
real_target,
unwind,
} => {
self.assert_iscleanup(mir, block_data, real_target, is_cleanup);
if let Some(unwind) = unwind {
if is_cleanup {
span_mirbug!(
self,
block_data,
"cleanup in cleanup block via false unwind"
);
}
self.assert_iscleanup(mir, block_data, unwind, true);
}
}
}
}
fn assert_iscleanup(
&mut self,
mir: &Mir<'tcx>,
ctxt: &dyn fmt::Debug,
bb: BasicBlock,
iscleanuppad: bool,
) {
if mir[bb].is_cleanup != iscleanuppad {
span_mirbug!(
self,
ctxt,
"cleanuppad mismatch: {:?} should be {:?}",
bb,
iscleanuppad
);
}
}
fn check_local(&mut self, mir: &Mir<'tcx>, local: Local, local_decl: &LocalDecl<'tcx>) {
match mir.local_kind(local) {
LocalKind::ReturnPointer | LocalKind::Arg => {
// return values of normal functions are required to be
// sized by typeck, but return values of ADT constructors are
// not because we don't include a `Self: Sized` bounds on them.
//
// Unbound parts of arguments were never required to be Sized
// - maybe we should make that a warning.
return;
}
LocalKind::Var | LocalKind::Temp => {}
}
// When `#![feature(unsized_locals)]` is enabled, only function calls
// and nullary ops are checked in `check_call_dest`.
if !self.tcx().features().unsized_locals {
let span = local_decl.source_info.span;
let ty = local_decl.ty;
self.ensure_place_sized(ty, span);
}
}
fn ensure_place_sized(&mut self, ty: Ty<'tcx>, span: Span) {
let tcx = self.tcx();
// Erase the regions from `ty` to get a global type. The
// `Sized` bound in no way depends on precise regions, so this
// shouldn't affect `is_sized`.
let gcx = tcx.global_tcx();
let erased_ty = gcx.lift(&tcx.erase_regions(&ty)).unwrap();
if !erased_ty.is_sized(gcx.at(span), self.param_env) {
// in current MIR construction, all non-control-flow rvalue
// expressions evaluate through `as_temp` or `into` a return
// slot or local, so to find all unsized rvalues it is enough
// to check all temps, return slots and locals.
if let None = self.reported_errors.replace((ty, span)) {
let mut diag = struct_span_err!(
self.tcx().sess,
span,
E0161,
"cannot move a value of type {0}: the size of {0} \
cannot be statically determined",
ty
);
// While this is located in `nll::typeck` this error is not
// an NLL error, it's a required check to prevent creation
// of unsized rvalues in certain cases:
// * operand of a box expression
// * callee in a call expression
diag.emit();
}
}
}
fn aggregate_field_ty(
&mut self,
ak: &AggregateKind<'tcx>,
field_index: usize,
location: Location,
) -> Result<Ty<'tcx>, FieldAccessError> {
let tcx = self.tcx();
match *ak {
AggregateKind::Adt(def, variant_index, substs, _, active_field_index) => {
let variant = &def.variants[variant_index];
let adj_field_index = active_field_index.unwrap_or(field_index);
if let Some(field) = variant.fields.get(adj_field_index) {
Ok(self.normalize(field.ty(tcx, substs), location))
} else {
Err(FieldAccessError::OutOfRange {
field_count: variant.fields.len(),
})
}
}
AggregateKind::Closure(def_id, substs) => {
match substs.upvar_tys(def_id, tcx).nth(field_index) {
Some(ty) => Ok(ty),
None => Err(FieldAccessError::OutOfRange {
field_count: substs.upvar_tys(def_id, tcx).count(),
}),
}
}
AggregateKind::Generator(def_id, substs, _) => {
// Try pre-transform fields first (upvars and current state)
if let Some(ty) = substs.pre_transforms_tys(def_id, tcx).nth(field_index) {
Ok(ty)
} else {
// Then try `field_tys` which contains all the fields, but it
// requires the final optimized MIR.
match substs.field_tys(def_id, tcx).nth(field_index) {
Some(ty) => Ok(ty),
None => Err(FieldAccessError::OutOfRange {
field_count: substs.field_tys(def_id, tcx).count(),
}),
}
}
}
AggregateKind::Array(ty) => Ok(ty),
AggregateKind::Tuple => {
unreachable!("This should have been covered in check_rvalues");
}
}
}
fn check_rvalue(&mut self, mir: &Mir<'tcx>, rvalue: &Rvalue<'tcx>, location: Location) {
let tcx = self.tcx();
match rvalue {
Rvalue::Aggregate(ak, ops) => {
self.check_aggregate_rvalue(mir, rvalue, ak, ops, location)
}
Rvalue::Repeat(operand, len) => if *len > 1 {
let operand_ty = operand.ty(mir, tcx);
let trait_ref = ty::TraitRef {
def_id: tcx.lang_items().copy_trait().unwrap(),
substs: tcx.mk_substs_trait(operand_ty, &[]),
};
self.prove_trait_ref(
trait_ref,
location.to_locations(),
ConstraintCategory::CopyBound,
);
},
Rvalue::NullaryOp(_, ty) => {
// Even with unsized locals cannot box an unsized value.
if self.tcx().features().unsized_locals {
let span = mir.source_info(location).span;
self.ensure_place_sized(ty, span);
}
let trait_ref = ty::TraitRef {
def_id: tcx.lang_items().sized_trait().unwrap(),
substs: tcx.mk_substs_trait(ty, &[]),
};
self.prove_trait_ref(
trait_ref,
location.to_locations(),
ConstraintCategory::SizedBound,
);
}
Rvalue::Cast(cast_kind, op, ty) => {
match cast_kind {
CastKind::ReifyFnPointer => {
let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
// The type that we see in the fcx is like
// `foo::<'a, 'b>`, where `foo` is the path to a
// function definition. When we extract the
// signature, it comes from the `fn_sig` query,
// and hence may contain unnormalized results.
let fn_sig = self.normalize(fn_sig, location);
let ty_fn_ptr_from = tcx.mk_fn_ptr(fn_sig);
if let Err(terr) = self.eq_types(
ty_fn_ptr_from,
ty,
location.to_locations(),
ConstraintCategory::Cast,
) {
span_mirbug!(
self,
rvalue,
"equating {:?} with {:?} yields {:?}",
ty_fn_ptr_from,
ty,
terr
);
}
}
CastKind::ClosureFnPointer => {
let sig = match op.ty(mir, tcx).sty {
ty::Closure(def_id, substs) => {
substs.closure_sig_ty(def_id, tcx).fn_sig(tcx)
}
_ => bug!(),
};
let ty_fn_ptr_from = tcx.coerce_closure_fn_ty(sig);
if let Err(terr) = self.eq_types(
ty_fn_ptr_from,
ty,
location.to_locations(),
ConstraintCategory::Cast,
) {
span_mirbug!(
self,
rvalue,
"equating {:?} with {:?} yields {:?}",
ty_fn_ptr_from,
ty,
terr
);
}
}
CastKind::UnsafeFnPointer => {
let fn_sig = op.ty(mir, tcx).fn_sig(tcx);
// The type that we see in the fcx is like
// `foo::<'a, 'b>`, where `foo` is the path to a
// function definition. When we extract the
// signature, it comes from the `fn_sig` query,
// and hence may contain unnormalized results.
let fn_sig = self.normalize(fn_sig, location);
let ty_fn_ptr_from = tcx.safe_to_unsafe_fn_ty(fn_sig);
if let Err(terr) = self.eq_types(
ty_fn_ptr_from,
ty,
location.to_locations(),
ConstraintCategory::Cast,
) {
span_mirbug!(
self,
rvalue,
"equating {:?} with {:?} yields {:?}",
ty_fn_ptr_from,
ty,
terr
);
}
}
CastKind::Unsize => {
let &ty = ty;
let trait_ref = ty::TraitRef {
def_id: tcx.lang_items().coerce_unsized_trait().unwrap(),
substs: tcx.mk_substs_trait(op.ty(mir, tcx), &[ty.into()]),
};
self.prove_trait_ref(
trait_ref,
location.to_locations(),
ConstraintCategory::Cast,
);
}
CastKind::Misc => {}
}
}
Rvalue::Ref(region, _borrow_kind, borrowed_place) => {
self.add_reborrow_constraint(location, region, borrowed_place);
}
// FIXME: These other cases have to be implemented in future PRs
Rvalue::Use(..)
| Rvalue::Len(..)
| Rvalue::BinaryOp(..)
| Rvalue::CheckedBinaryOp(..)
| Rvalue::UnaryOp(..)
| Rvalue::Discriminant(..) => {}
}
}
/// If this rvalue supports a user-given type annotation, then
/// extract and return it. This represents the final type of the
/// rvalue and will be unified with the inferred type.
fn rvalue_user_ty(&self, rvalue: &Rvalue<'tcx>) -> Option<UserTypeAnnotation<'tcx>> {
match rvalue {
Rvalue::Use(_)
| Rvalue::Repeat(..)
| Rvalue::Ref(..)
| Rvalue::Len(..)
| Rvalue::Cast(..)
| Rvalue::BinaryOp(..)
| Rvalue::CheckedBinaryOp(..)
| Rvalue::NullaryOp(..)
| Rvalue::UnaryOp(..)
| Rvalue::Discriminant(..) => None,
Rvalue::Aggregate(aggregate, _) => match **aggregate {
AggregateKind::Adt(_, _, _, user_ty, _) => user_ty,
AggregateKind::Array(_) => None,
AggregateKind::Tuple => None,
AggregateKind::Closure(_, _) => None,
AggregateKind::Generator(_, _, _) => None,
},
}
}
fn check_aggregate_rvalue(
&mut self,
mir: &Mir<'tcx>,
rvalue: &Rvalue<'tcx>,
aggregate_kind: &AggregateKind<'tcx>,
operands: &[Operand<'tcx>],
location: Location,
) {
let tcx = self.tcx();
self.prove_aggregate_predicates(aggregate_kind, location);
if *aggregate_kind == AggregateKind::Tuple {
// tuple rvalue field type is always the type of the op. Nothing to check here.
return;
}
for (i, operand) in operands.iter().enumerate() {
let field_ty = match self.aggregate_field_ty(aggregate_kind, i, location) {
Ok(field_ty) => field_ty,
Err(FieldAccessError::OutOfRange { field_count }) => {
span_mirbug!(
self,
rvalue,
"accessed field #{} but variant only has {}",
i,
field_count
);
continue;
}
};
let operand_ty = operand.ty(mir, tcx);
if let Err(terr) = self.sub_types(
operand_ty,
field_ty,
location.to_locations(),
ConstraintCategory::Boring,
) {
span_mirbug!(
self,
rvalue,
"{:?} is not a subtype of {:?}: {:?}",
operand_ty,
field_ty,
terr
);
}
}
}
/// Add the constraints that arise from a borrow expression `&'a P` at the location `L`.
///
/// # Parameters
///
/// - `location`: the location `L` where the borrow expression occurs
/// - `borrow_region`: the region `'a` associated with the borrow
/// - `borrowed_place`: the place `P` being borrowed
fn add_reborrow_constraint(
&mut self,
location: Location,
borrow_region: ty::Region<'tcx>,
borrowed_place: &Place<'tcx>,
) {
// These constraints are only meaningful during borrowck:
let BorrowCheckContext {
borrow_set,
location_table,
all_facts,
constraints,
..
} = match self.borrowck_context {
Some(ref mut borrowck_context) => borrowck_context,
None => return,
};
// In Polonius mode, we also push a `borrow_region` fact
// linking the loan to the region (in some cases, though,
// there is no loan associated with this borrow expression --
// that occurs when we are borrowing an unsafe place, for
// example).
if let Some(all_facts) = all_facts {
if let Some(borrow_index) = borrow_set.location_map.get(&location) {
let region_vid = borrow_region.to_region_vid();
all_facts.borrow_region.push((
region_vid,
*borrow_index,
location_table.mid_index(location),
));
}
}
// If we are reborrowing the referent of another reference, we
// need to add outlives relationships. In a case like `&mut
// *p`, where the `p` has type `&'b mut Foo`, for example, we
// need to ensure that `'b: 'a`.
let mut borrowed_place = borrowed_place;
debug!(
"add_reborrow_constraint({:?}, {:?}, {:?})",
location, borrow_region, borrowed_place
);
while let Place::Projection(box PlaceProjection { base, elem }) = borrowed_place {
debug!("add_reborrow_constraint - iteration {:?}", borrowed_place);
match *elem {
ProjectionElem::Deref => {
let tcx = self.infcx.tcx;
let base_ty = base.ty(self.mir, tcx).to_ty(tcx);
debug!("add_reborrow_constraint - base_ty = {:?}", base_ty);
match base_ty.sty {
ty::Ref(ref_region, _, mutbl) => {
constraints.outlives_constraints.push(OutlivesConstraint {
sup: ref_region.to_region_vid(),
sub: borrow_region.to_region_vid(),
locations: location.to_locations(),
category: ConstraintCategory::Boring,
});
match mutbl {
hir::Mutability::MutImmutable => {
// Immutable reference. We don't need the base
// to be valid for the entire lifetime of
// the borrow.
break;
}
hir::Mutability::MutMutable => {
// Mutable reference. We *do* need the base
// to be valid, because after the base becomes
// invalid, someone else can use our mutable deref.
// This is in order to make the following function
// illegal:
// ```
// fn unsafe_deref<'a, 'b>(x: &'a &'b mut T) -> &'b mut T {
// &mut *x
// }
// ```
//
// As otherwise you could clone `&mut T` using the
// following function:
// ```
// fn bad(x: &mut T) -> (&mut T, &mut T) {
// let my_clone = unsafe_deref(&'a x);
// ENDREGION 'a;
// (my_clone, x)
// }
// ```
}
}
}
ty::RawPtr(..) => {
// deref of raw pointer, guaranteed to be valid
break;
}
ty::Adt(def, _) if def.is_box() => {
// deref of `Box`, need the base to be valid - propagate
}
_ => bug!("unexpected deref ty {:?} in {:?}", base_ty, borrowed_place),
}
}
ProjectionElem::Field(..)
| ProjectionElem::Downcast(..)
| ProjectionElem::Index(..)
| ProjectionElem::ConstantIndex { .. }
| ProjectionElem::Subslice { .. } => {
// other field access
}
}
// The "propagate" case. We need to check that our base is valid
// for the borrow's lifetime.
borrowed_place = base;
}
}
fn prove_aggregate_predicates(
&mut self,
aggregate_kind: &AggregateKind<'tcx>,
location: Location,
) {
let tcx = self.tcx();
debug!(
"prove_aggregate_predicates(aggregate_kind={:?}, location={:?})",
aggregate_kind, location
);
let instantiated_predicates = match aggregate_kind {
AggregateKind::Adt(def, _, substs, _, _) => {
tcx.predicates_of(def.did).instantiate(tcx, substs)
}
// For closures, we have some **extra requirements** we
//
// have to check. In particular, in their upvars and
// signatures, closures often reference various regions
// from the surrounding function -- we call those the
// closure's free regions. When we borrow-check (and hence
// region-check) closures, we may find that the closure
// requires certain relationships between those free
// regions. However, because those free regions refer to
// portions of the CFG of their caller, the closure is not
// in a position to verify those relationships. In that
// case, the requirements get "propagated" to us, and so
// we have to solve them here where we instantiate the
// closure.
//
// Despite the opacity of the previous parapgrah, this is
// actually relatively easy to understand in terms of the
// desugaring. A closure gets desugared to a struct, and
// these extra requirements are basically like where
// clauses on the struct.
AggregateKind::Closure(def_id, ty::ClosureSubsts { substs })
| AggregateKind::Generator(def_id, ty::GeneratorSubsts { substs }, _) => {
self.prove_closure_bounds(tcx, *def_id, substs, location)
}
AggregateKind::Array(_) | AggregateKind::Tuple => ty::InstantiatedPredicates::empty(),
};
self.normalize_and_prove_instantiated_predicates(
instantiated_predicates,
location.to_locations(),
);
}
fn prove_closure_bounds(
&mut self,
tcx: TyCtxt<'a, 'gcx, 'tcx>,
def_id: DefId,
substs: &'tcx Substs<'tcx>,
location: Location,
) -> ty::InstantiatedPredicates<'tcx> {
if let Some(closure_region_requirements) = tcx.mir_borrowck(def_id).closure_requirements {
let closure_constraints =
closure_region_requirements.apply_requirements(tcx, location, def_id, substs);
if let Some(ref mut borrowck_context) = self.borrowck_context {
let bounds_mapping = closure_constraints
.iter()
.enumerate()
.filter_map(|(idx, constraint)| {
let ty::OutlivesPredicate(k1, r2) =
constraint.no_bound_vars().unwrap_or_else(|| {
bug!("query_constraint {:?} contained bound vars", constraint,);
});
match k1.unpack() {
UnpackedKind::Lifetime(r1) => {
// constraint is r1: r2
let r1_vid = borrowck_context.universal_regions.to_region_vid(r1);
let r2_vid = borrowck_context.universal_regions.to_region_vid(r2);
let outlives_requirements =
&closure_region_requirements.outlives_requirements[idx];
Some((
(r1_vid, r2_vid),
(
outlives_requirements.category,
outlives_requirements.blame_span,
),
))
}
UnpackedKind::Type(_) => None,
}
})
.collect();
let existing = borrowck_context
.constraints
.closure_bounds_mapping
.insert(location, bounds_mapping);
assert!(
existing.is_none(),
"Multiple closures at the same location."
);
}
self.push_region_constraints(
location.to_locations(),
ConstraintCategory::ClosureBounds,
&closure_constraints,
);
}
tcx.predicates_of(def_id).instantiate(tcx, substs)
}
fn prove_trait_ref(
&mut self,
trait_ref: ty::TraitRef<'tcx>,
locations: Locations,
category: ConstraintCategory,
) {
self.prove_predicates(
Some(ty::Predicate::Trait(
trait_ref.to_poly_trait_ref().to_poly_trait_predicate(),
)),
locations,
category,
);
}
fn normalize_and_prove_instantiated_predicates(
&mut self,
instantiated_predicates: ty::InstantiatedPredicates<'tcx>,
locations: Locations,
) {
for predicate in instantiated_predicates.predicates {
let predicate = self.normalize(predicate, locations);
self.prove_predicate(predicate, locations, ConstraintCategory::Boring);
}
}
fn prove_predicates(
&mut self,
predicates: impl IntoIterator<Item = ty::Predicate<'tcx>>,
locations: Locations,
category: ConstraintCategory,
) {
for predicate in predicates {
debug!(
"prove_predicates(predicate={:?}, locations={:?})",
predicate, locations,
);
self.prove_predicate(predicate, locations, category);
}
}
fn prove_predicate(
&mut self,
predicate: ty::Predicate<'tcx>,
locations: Locations,
category: ConstraintCategory,
) {
debug!(
"prove_predicate(predicate={:?}, location={:?})",
predicate, locations,
);
let param_env = self.param_env;
self.fully_perform_op(
locations,
category,
param_env.and(type_op::prove_predicate::ProvePredicate::new(predicate)),
).unwrap_or_else(|NoSolution| {
span_mirbug!(self, NoSolution, "could not prove {:?}", predicate);
})
}
fn typeck_mir(&mut self, mir: &Mir<'tcx>) {
self.last_span = mir.span;
debug!("run_on_mir: {:?}", mir.span);
for (local, local_decl) in mir.local_decls.iter_enumerated() {
self.check_local(mir, local, local_decl);
}
for (block, block_data) in mir.basic_blocks().iter_enumerated() {
let mut location = Location {
block,
statement_index: 0,
};
for stmt in &block_data.statements {
if !stmt.source_info.span.is_dummy() {
self.last_span = stmt.source_info.span;
}
self.check_stmt(mir, stmt, location);
location.statement_index += 1;
}
self.check_terminator(mir, block_data.terminator(), location);
self.check_iscleanup(mir, block_data);
}
}
fn normalize<T>(&mut self, value: T, location: impl NormalizeLocation) -> T
where
T: type_op::normalize::Normalizable<'gcx, 'tcx> + Copy,
{
debug!("normalize(value={:?}, location={:?})", value, location);
let param_env = self.param_env;
self.fully_perform_op(
location.to_locations(),
ConstraintCategory::Boring,
param_env.and(type_op::normalize::Normalize::new(value)),
).unwrap_or_else(|NoSolution| {
span_mirbug!(self, NoSolution, "failed to normalize `{:?}`", value);
value
})
}
}
pub struct TypeckMir;
impl MirPass for TypeckMir {
fn run_pass<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, src: MirSource, mir: &mut Mir<'tcx>) {
let def_id = src.def_id;
debug!("run_pass: {:?}", def_id);
// When NLL is enabled, the borrow checker runs the typeck
// itself, so we don't need this MIR pass anymore.
if tcx.use_mir_borrowck() {
return;
}
if tcx.sess.err_count() > 0 {
// compiling a broken program can obviously result in a
// broken MIR, so try not to report duplicate errors.
return;
}
if tcx.is_struct_constructor(def_id) {
// We just assume that the automatically generated struct constructors are
// correct. See the comment in the `mir_borrowck` implementation for an
// explanation why we need this.
return;
}
let param_env = tcx.param_env(def_id);
tcx.infer_ctxt().enter(|infcx| {
type_check_internal(
&infcx,
def_id,
param_env,
mir,
&vec![],
None,
None,
None,
|_| (),
);
// For verification purposes, we just ignore the resulting
// region constraint sets. Not our problem. =)
});
}
}
trait NormalizeLocation: fmt::Debug + Copy {
fn to_locations(self) -> Locations;
}
impl NormalizeLocation for Locations {
fn to_locations(self) -> Locations {
self
}
}
impl NormalizeLocation for Location {
fn to_locations(self) -> Locations {
Locations::Single(self)
}
}
#[derive(Debug, Default)]
struct ObligationAccumulator<'tcx> {
obligations: PredicateObligations<'tcx>,
}
impl<'tcx> ObligationAccumulator<'tcx> {
fn add<T>(&mut self, value: InferOk<'tcx, T>) -> T {
let InferOk { value, obligations } = value;
self.obligations.extend(obligations);
value
}
fn into_vec(self) -> PredicateObligations<'tcx> {
self.obligations
}
}<|fim▁end|> | |
<|file_name|>review_group_user.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.utils import six
from djblets.util.decorators import augment_method_from
from djblets.webapi.decorators import (webapi_login_required,
webapi_response_errors,
webapi_request_fields)
from djblets.webapi.errors import (DOES_NOT_EXIST, NOT_LOGGED_IN,
PERMISSION_DENIED)
from reviewboard.reviews.models import Group
from reviewboard.webapi.base import WebAPIResource
from reviewboard.webapi.decorators import webapi_check_local_site
from reviewboard.webapi.errors import INVALID_USER
from reviewboard.webapi.resources import resources
from reviewboard.webapi.resources.user import UserResource
class ReviewGroupUserResource(UserResource):
"""Provides information on users that are members of a review group."""
allowed_methods = ('GET', 'POST', 'DELETE')
policy_id = 'review_group_user'
def get_queryset(self, request, group_name, local_site_name=None,
*args, **kwargs):
group = Group.objects.get(name=group_name,
local_site__name=local_site_name)
return group.users.all()
def has_access_permissions(self, request, user, *args, **kwargs):
group = resources.review_group.get_object(request, *args, **kwargs)
return group.is_accessible_by(request.user)
def has_list_access_permissions(self, request, *args, **kwargs):
group = resources.review_group.get_object(request, *args, **kwargs)
return group.is_accessible_by(request.user)
def has_modify_permissions(self, request, group, username, local_site):
return (
resources.review_group.has_modify_permissions(request, group) or
(request.user.username == username and
group.is_accessible_by(request.user))
)
def has_delete_permissions(self, request, user, *args, **kwargs):
group = resources.review_group.get_object(request, *args, **kwargs)
return group.is_mutable_by(request.user)
@webapi_check_local_site
@webapi_login_required
@webapi_response_errors(DOES_NOT_EXIST, INVALID_USER,
NOT_LOGGED_IN, PERMISSION_DENIED)
@webapi_request_fields(required={
'username': {
'type': six.text_type,
'description': 'The user to add to the group.',
},
})
def create(self, request, username, *args, **kwargs):
"""Adds a user to a review group."""
group_resource = resources.review_group
try:
group = group_resource.get_object(request, *args, **kwargs)
except ObjectDoesNotExist:
return DOES_NOT_EXIST
local_site = self._get_local_site(kwargs.get('local_site_name', None))
<|fim▁hole|> return self._no_access_error(request.user)
try:
if local_site:
user = local_site.users.get(username=username)
else:
user = User.objects.get(username=username)
except ObjectDoesNotExist:
return INVALID_USER
group.users.add(user)
return 201, {
self.item_result_key: user,
}
@webapi_check_local_site
@webapi_login_required
@webapi_response_errors(DOES_NOT_EXIST, INVALID_USER,
NOT_LOGGED_IN, PERMISSION_DENIED)
def delete(self, request, *args, **kwargs):
"""Removes a user from a review group."""
group_resource = resources.review_group
try:
group = group_resource.get_object(request, *args, **kwargs)
user = self.get_object(request, *args, **kwargs)
except ObjectDoesNotExist:
return DOES_NOT_EXIST
local_site = self._get_local_site(kwargs.get('local_site_name', None))
if (not group_resource.has_access_permissions(request, group) or
not self.has_modify_permissions(request, group, user.username,
local_site)):
return self._no_access_error(request.user)
group.users.remove(user)
return 204, {}
@webapi_check_local_site
@augment_method_from(WebAPIResource)
def get_list(self, *args, **kwargs):
"""Retrieves the list of users belonging to a specific review group.
This includes only the users who have active accounts on the site.
Any account that has been disabled (for inactivity, spam reasons,
or anything else) will be excluded from the list.
The list of users can be filtered down using the ``q`` and
``fullname`` parameters.
Setting ``q`` to a value will by default limit the results to
usernames starting with that value. This is a case-insensitive
comparison.
If ``fullname`` is set to ``1``, the first and last names will also be
checked along with the username. ``fullname`` is ignored if ``q``
is not set.
For example, accessing ``/api/users/?q=bo&fullname=1`` will list
any users with a username, first name or last name starting with
``bo``.
"""
pass
review_group_user_resource = ReviewGroupUserResource()<|fim▁end|> | if (not group_resource.has_access_permissions(request, group) or
not self.has_modify_permissions(request, group, username,
local_site)): |
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|><|fim▁hole|>from . import darknet53, efficientnet, xception<|fim▁end|> | """Kerasの各種モデル。"""
# pylint: skip-file
# flake8: noqa
|
<|file_name|>amqp-connection-manager-tests.ts<|end_file_name|><|fim▁begin|>import * as amqp from "amqplib";
import * as amqpConMgr from 'amqp-connection-manager';
// from README.md
const connection = amqpConMgr.connect(['amqp://localhost']);
const channelWrapper: amqpConMgr.ChannelWrapper = connection.createChannel({
json: true,
setup: async (channel: amqp.ConfirmChannel): Promise<void> => {
// `channel` here is a regular amqplib `ConfirmChannel`. Unfortunately its typings make it return a bluebird-specific promise
// tslint:disable-next-line:await-promise
await channel.assertQueue('rxQueueName', {durable: true});
}
});
connection.on("connect", (_arg: { connection: amqp.Connection, url: string }): void => undefined);
connection.on("disconnect", (_arg: { err: Error }): void => undefined);
channelWrapper.on("close", () => undefined);
channelWrapper.on("connect", () => undefined);
channelWrapper.on("error", (_error: Error) => undefined);
channelWrapper.sendToQueue("foo", Buffer.from("bar"))
.catch((error: Error): void => {
// nothing
});
// Test that plain objects are implicitly serialized.
channelWrapper.sendToQueue("foo", {a: 'bar'}).catch(_ => {});
// Checking connection options
amqpConMgr.connect(["foo", "bar"], {
findServers(callback) {
callback("x");
}
});
amqpConMgr.connect(["foo", "bar"], {
findServers(callback) {
callback(["x", "y"]);
}
});
amqpConMgr.connect(["foo", "bar"], {
findServers() {
return Promise.resolve("x");
}
});
amqpConMgr.connect(["foo", "bar"], {
findServers() {
return Promise.resolve(["x", "y"]);
}
});
amqpConMgr.connect(["foo", "bar"], {
reconnectTimeInSeconds: 123
});
amqpConMgr.connect(["foo", "bar"], {<|fim▁hole|> connectionOptions: {
ca: "some CA",
servername: "foo.example.com"
}
});<|fim▁end|> | heartbeatIntervalInSeconds: 123
});
amqpConMgr.connect(["foo", "bar"], { |
<|file_name|>TestType.java<|end_file_name|><|fim▁begin|>package edu.harvard.fas.rbrady.tpteam.tpbridge.hibernate;
// Generated Nov 10, 2006 5:22:58 PM by Hibernate Tools 3.2.0.beta8
import java.util.HashSet;
import java.util.Set;
/**
* TestType generated by hbm2java
*/
public class TestType implements java.io.Serializable {
// Fields
private static final long serialVersionUID = 1L;
private int id;
private String name;
<|fim▁hole|> private Set<Test> tests = new HashSet<Test>(0);
// Constructors
/** default constructor */
public TestType() {
}
/** minimal constructor */
public TestType(int id) {
this.id = id;
}
/** full constructor */
public TestType(int id, String name, Set<Test> tests) {
this.id = id;
this.name = name;
this.tests = tests;
}
// Property accessors
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Set<Test> getTests() {
return this.tests;
}
public void setTests(Set<Test> tests) {
this.tests = tests;
}
}<|fim▁end|> | |
<|file_name|>fixture.rs<|end_file_name|><|fim▁begin|>/// `fixture`'s related data and parsing
use syn::{
parse::{Parse, ParseStream},
parse_quote,
visit_mut::VisitMut,
Expr, FnArg, Ident, ItemFn, Token,
};
use super::{
extract_argument_attrs, extract_default_return_type, extract_defaults, extract_fixtures,
extract_partials_return_type, parse_vector_trailing_till_double_comma, Attributes,
ExtendWithFunctionAttrs, Fixture,
};
use crate::{
error::ErrorsVec,
parse::extract_once,
refident::{MaybeIdent, RefIdent},
utils::attr_is,
};
use crate::{parse::Attribute, utils::attr_in};
use proc_macro2::TokenStream;
use quote::{format_ident, ToTokens};
#[derive(PartialEq, Debug, Default)]
pub(crate) struct FixtureInfo {
pub(crate) data: FixtureData,
pub(crate) attributes: FixtureModifiers,
}
impl Parse for FixtureModifiers {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(input.parse::<Attributes>()?.into())
}
}
impl Parse for FixtureInfo {
fn parse(input: ParseStream) -> syn::Result<Self> {
Ok(if input.is_empty() {
Default::default()
} else {
Self {
data: input.parse()?,
attributes: input
.parse::<Token![::]>()
.or_else(|_| Ok(Default::default()))
.and_then(|_| input.parse())?,
}
})
}
}
impl ExtendWithFunctionAttrs for FixtureInfo {
fn extend_with_function_attrs(
&mut self,
item_fn: &mut ItemFn,
) -> std::result::Result<(), ErrorsVec> {
let composed_tuple!(
fixtures,
defaults,
default_return_type,
partials_return_type,
once
) = merge_errors!(
extract_fixtures(item_fn),
extract_defaults(item_fn),
extract_default_return_type(item_fn),
extract_partials_return_type(item_fn),
extract_once(item_fn)
)?;
self.data.items.extend(
fixtures
.into_iter()
.map(|f| f.into())
.chain(defaults.into_iter().map(|d| d.into())),
);
if let Some(return_type) = default_return_type {
self.attributes.set_default_return_type(return_type);
}
for (id, return_type) in partials_return_type {
self.attributes.set_partial_return_type(id, return_type);
}
if let Some(ident) = once {
self.attributes.set_once(ident)
};
Ok(())
}
}
fn parse_attribute_args_just_once<'a, T: Parse>(
attributes: impl Iterator<Item = &'a syn::Attribute>,
name: &str,
) -> (Option<T>, Vec<syn::Error>) {
let mut errors = Vec::new();
let val = attributes
.filter(|&a| attr_is(a, name))
.map(|a| (a, a.parse_args::<T>()))
.fold(None, |first, (a, res)| match (first, res) {
(None, Ok(parsed)) => Some(parsed),
(first, Err(err)) => {
errors.push(err);
first
}
(first, _) => {
errors.push(syn::Error::new_spanned(
a,
format!(
"You cannot use '{}' attribute more than once for the same argument",
name
),
));
first
}
});
(val, errors)
}
/// Simple struct used to visit function attributes and extract Fixtures and
/// eventualy parsing errors
#[derive(Default)]
pub(crate) struct FixturesFunctionExtractor(pub(crate) Vec<Fixture>, pub(crate) Vec<syn::Error>);
impl VisitMut for FixturesFunctionExtractor {
fn visit_fn_arg_mut(&mut self, node: &mut FnArg) {
if let FnArg::Typed(ref mut arg) = node {
let name = match arg.pat.as_ref() {
syn::Pat::Ident(ident) => ident.ident.clone(),
_ => return,
};
let (extracted, remain): (Vec<_>, Vec<_>) = std::mem::take(&mut arg.attrs)
.into_iter()
.partition(|attr| attr_in(attr, &["with", "from"]));
arg.attrs = remain;
let (pos, errors) = parse_attribute_args_just_once(extracted.iter(), "with");
self.1.extend(errors.into_iter());
let (resolve, errors) = parse_attribute_args_just_once(extracted.iter(), "from");
self.1.extend(errors.into_iter());
if pos.is_some() || resolve.is_some() {
self.0
.push(Fixture::new(name, resolve, pos.unwrap_or_default()))
}
}
}
}
/// Simple struct used to visit function attributes and extract fixture default values info and
/// eventualy parsing errors
#[derive(Default)]
pub(crate) struct DefaultsFunctionExtractor(
pub(crate) Vec<ArgumentValue>,
pub(crate) Vec<syn::Error>,
);
impl VisitMut for DefaultsFunctionExtractor {
fn visit_fn_arg_mut(&mut self, node: &mut FnArg) {
for r in extract_argument_attrs(
node,
|a| attr_is(a, "default"),
|a, name| {
a.parse_args::<Expr>()
.map(|e| ArgumentValue::new(name.clone(), e))
},
) {
match r {
Ok(value) => self.0.push(value),
Err(err) => self.1.push(err),
}
}
}
}
#[derive(PartialEq, Debug, Default)]
pub(crate) struct FixtureData {
pub items: Vec<FixtureItem>,
}
impl FixtureData {
pub(crate) fn fixtures(&self) -> impl Iterator<Item = &Fixture> {
self.items.iter().filter_map(|f| match f {
FixtureItem::Fixture(ref fixture) => Some(fixture),
_ => None,
})
}
pub(crate) fn values(&self) -> impl Iterator<Item = &ArgumentValue> {
self.items.iter().filter_map(|f| match f {
FixtureItem::ArgumentValue(ref value) => Some(value.as_ref()),
_ => None,
})
}
}
impl Parse for FixtureData {
fn parse(input: ParseStream) -> syn::Result<Self> {
if input.peek(Token![::]) {
Ok(Default::default())
} else {
Ok(Self {
items: parse_vector_trailing_till_double_comma::<_, Token![,]>(input)?,
})
}
}
}
#[derive(PartialEq, Debug)]
pub(crate) struct ArgumentValue {
pub name: Ident,
pub expr: Expr,
}
impl ArgumentValue {
pub(crate) fn new(name: Ident, expr: Expr) -> Self {
Self { name, expr }
}
}
<|fim▁hole|>}
impl From<Fixture> for FixtureItem {
fn from(f: Fixture) -> Self {
FixtureItem::Fixture(f)
}
}
impl Parse for FixtureItem {
fn parse(input: ParseStream) -> syn::Result<Self> {
if input.peek2(Token![=]) {
input.parse::<ArgumentValue>().map(|v| v.into())
} else {
input.parse::<Fixture>().map(|v| v.into())
}
}
}
impl RefIdent for FixtureItem {
fn ident(&self) -> &Ident {
match self {
FixtureItem::Fixture(Fixture { ref name, .. }) => name,
FixtureItem::ArgumentValue(ref av) => &av.name,
}
}
}
impl ToTokens for FixtureItem {
fn to_tokens(&self, tokens: &mut TokenStream) {
self.ident().to_tokens(tokens)
}
}
impl From<ArgumentValue> for FixtureItem {
fn from(av: ArgumentValue) -> Self {
FixtureItem::ArgumentValue(Box::new(av))
}
}
impl Parse for ArgumentValue {
fn parse(input: ParseStream) -> syn::Result<Self> {
let name = input.parse()?;
let _eq: Token![=] = input.parse()?;
let expr = input.parse()?;
Ok(ArgumentValue::new(name, expr))
}
}
wrap_attributes!(FixtureModifiers);
impl FixtureModifiers {
pub(crate) const DEFAULT_RET_ATTR: &'static str = "default";
pub(crate) const PARTIAL_RET_ATTR: &'static str = "partial_";
pub(crate) fn extract_default_type(&self) -> Option<syn::ReturnType> {
self.extract_type(Self::DEFAULT_RET_ATTR)
}
pub(crate) fn extract_partial_type(&self, pos: usize) -> Option<syn::ReturnType> {
self.extract_type(&format!("{}{}", Self::PARTIAL_RET_ATTR, pos))
}
pub(crate) fn set_default_return_type(&mut self, return_type: syn::Type) {
self.inner.attributes.push(Attribute::Type(
format_ident!("{}", Self::DEFAULT_RET_ATTR),
Box::new(return_type),
))
}
pub(crate) fn set_partial_return_type(&mut self, id: usize, return_type: syn::Type) {
self.inner.attributes.push(Attribute::Type(
format_ident!("{}{}", Self::PARTIAL_RET_ATTR, id),
Box::new(return_type),
))
}
pub(crate) fn set_once(&mut self, once: syn::Ident) {
self.inner.attributes.push(Attribute::Attr(once))
}
pub(crate) fn get_once(&self) -> Option<&Ident> {
self.iter()
.find(|&a| a == &Attribute::Attr(format_ident!("once")))
.and_then(|a| a.maybe_ident())
}
pub(crate) fn is_once(&self) -> bool {
self.get_once().is_some()
}
fn extract_type(&self, attr_name: &str) -> Option<syn::ReturnType> {
self.iter()
.filter_map(|m| match m {
Attribute::Type(name, t) if name == attr_name => Some(parse_quote! { -> #t}),
_ => None,
})
.next()
}
}
#[cfg(test)]
mod should {
use super::*;
use crate::test::{assert_eq, *};
mod parse {
use super::{assert_eq, *};
use mytest::rstest;
fn parse_fixture<S: AsRef<str>>(fixture_data: S) -> FixtureInfo {
parse_meta(fixture_data)
}
#[test]
fn happy_path() {
let data = parse_fixture(
r#"my_fixture(42, "other"), other(vec![42]), value=42, other_value=vec![1.0]
:: trace :: no_trace(some)"#,
);
let expected = FixtureInfo {
data: vec![
fixture("my_fixture", &["42", r#""other""#]).into(),
fixture("other", &["vec![42]"]).into(),
arg_value("value", "42").into(),
arg_value("other_value", "vec![1.0]").into(),
]
.into(),
attributes: Attributes {
attributes: vec![
Attribute::attr("trace"),
Attribute::tagged("no_trace", vec!["some"]),
],
}
.into(),
};
assert_eq!(expected, data);
}
#[test]
fn some_literals() {
let args_expressions = literal_expressions_str();
let fixture = parse_fixture(&format!("my_fixture({})", args_expressions.join(", ")));
let args = fixture.data.fixtures().next().unwrap().positional.clone();
assert_eq!(to_args!(args_expressions), args.0);
}
#[test]
fn empty_fixtures() {
let data = parse_fixture(r#"::trace::no_trace(some)"#);
let expected = FixtureInfo {
attributes: Attributes {
attributes: vec![
Attribute::attr("trace"),
Attribute::tagged("no_trace", vec!["some"]),
],
}
.into(),
..Default::default()
};
assert_eq!(expected, data);
}
#[test]
fn empty_attributes() {
let data = parse_fixture(r#"my_fixture(42, "other")"#);
let expected = FixtureInfo {
data: vec![fixture("my_fixture", &["42", r#""other""#]).into()].into(),
..Default::default()
};
assert_eq!(expected, data);
}
#[rstest]
#[case("first(42),", 1)]
#[case("first(42), second=42,", 2)]
#[case(r#"fixture(42, "other"), :: trace"#, 1)]
#[case(r#"second=42, fixture(42, "other"), :: trace"#, 2)]
fn should_accept_trailing_comma(#[case] input: &str, #[case] expected: usize) {
let info: FixtureInfo = input.ast();
assert_eq!(
expected,
info.data.fixtures().count() + info.data.values().count()
);
}
}
}
#[cfg(test)]
mod extend {
use super::*;
use crate::test::{assert_eq, *};
use syn::ItemFn;
mod should {
use super::{assert_eq, *};
#[test]
fn use_with_attributes() {
let to_parse = r#"
fn my_fix(#[with(2)] f1: &str, #[with(vec![1,2], "s")] f2: u32) {}
"#;
let mut item_fn: ItemFn = to_parse.ast();
let mut info = FixtureInfo::default();
info.extend_with_function_attrs(&mut item_fn).unwrap();
let expected = FixtureInfo {
data: vec![
fixture("f1", &["2"]).into(),
fixture("f2", &["vec![1,2]", r#""s""#]).into(),
]
.into(),
..Default::default()
};
assert!(!format!("{:?}", item_fn).contains("with"));
assert_eq!(expected, info);
}
#[test]
fn rename_with_attributes() {
let mut item_fn = r#"
fn test_fn(
#[from(long_fixture_name)]
#[with(42, "other")] short: u32,
#[from(simple)]
s: &str,
no_change: i32) {
}
"#
.ast();
let expected = FixtureInfo {
data: vec![
fixture("short", &["42", r#""other""#])
.with_resolve("long_fixture_name")
.into(),
fixture("s", &[]).with_resolve("simple").into(),
]
.into(),
..Default::default()
};
let mut data = FixtureInfo::default();
data.extend_with_function_attrs(&mut item_fn).unwrap();
assert_eq!(expected, data);
}
#[test]
fn use_default_values_attributes() {
let to_parse = r#"
fn my_fix(#[default(2)] f1: &str, #[default((vec![1,2], "s"))] f2: (Vec<u32>, &str)) {}
"#;
let mut item_fn: ItemFn = to_parse.ast();
let mut info = FixtureInfo::default();
info.extend_with_function_attrs(&mut item_fn).unwrap();
let expected = FixtureInfo {
data: vec![
arg_value("f1", "2").into(),
arg_value("f2", r#"(vec![1,2], "s")"#).into(),
]
.into(),
..Default::default()
};
assert!(!format!("{:?}", item_fn).contains("default"));
assert_eq!(expected, info);
}
#[test]
fn find_default_return_type() {
let mut item_fn: ItemFn = r#"
#[simple]
#[first(comp)]
#[second::default]
#[default(impl Iterator<Item=(u32, i32)>)]
#[last::more]
fn my_fix<I, J>(f1: I, f2: J) -> impl Iterator<Item=(I, J)> {}
"#
.ast();
let mut info = FixtureInfo::default();
info.extend_with_function_attrs(&mut item_fn).unwrap();
assert_eq!(
info.attributes.extract_default_type(),
Some(parse_quote! { -> impl Iterator<Item=(u32, i32)> })
);
assert_eq!(
attrs("#[simple]#[first(comp)]#[second::default]#[last::more]"),
item_fn.attrs
);
}
#[test]
fn find_partials_return_type() {
let mut item_fn: ItemFn = r#"
#[simple]
#[first(comp)]
#[second::default]
#[partial_1(impl Iterator<Item=(u32, J, K)>)]
#[partial_2(impl Iterator<Item=(u32, i32, K)>)]
#[last::more]
fn my_fix<I, J, K>(f1: I, f2: J, f3: K) -> impl Iterator<Item=(I, J, K)> {}
"#
.ast();
let mut info = FixtureInfo::default();
info.extend_with_function_attrs(&mut item_fn).unwrap();
assert_eq!(
info.attributes.extract_partial_type(1),
Some(parse_quote! { -> impl Iterator<Item=(u32, J, K)> })
);
assert_eq!(
info.attributes.extract_partial_type(2),
Some(parse_quote! { -> impl Iterator<Item=(u32, i32, K)> })
);
assert_eq!(
attrs("#[simple]#[first(comp)]#[second::default]#[last::more]"),
item_fn.attrs
);
}
#[test]
fn find_once_attribute() {
let mut item_fn: ItemFn = r#"
#[simple]
#[first(comp)]
#[second::default]
#[once]
#[last::more]
fn my_fix<I, J, K>(f1: I, f2: J, f3: K) -> impl Iterator<Item=(I, J, K)> {}
"#
.ast();
let mut info = FixtureInfo::default();
info.extend_with_function_attrs(&mut item_fn).unwrap();
assert!(info.attributes.is_once());
}
#[test]
fn no_once_attribute() {
let mut item_fn: ItemFn = r#"
fn my_fix<I, J, K>(f1: I, f2: J, f3: K) -> impl Iterator<Item=(I, J, K)> {}
"#
.ast();
let mut info = FixtureInfo::default();
info.extend_with_function_attrs(&mut item_fn).unwrap();
assert!(!info.attributes.is_once());
}
mod raise_error {
use super::{assert_eq, *};
use rstest_test::assert_in;
#[test]
fn for_invalid_expressions() {
let mut item_fn: ItemFn = r#"
fn my_fix(#[with(valid)] f1: &str, #[with(with(,.,))] f2: u32, #[with(with(use))] f3: u32) {}
"#
.ast();
let errors = FixtureInfo::default()
.extend_with_function_attrs(&mut item_fn)
.unwrap_err();
assert_eq!(2, errors.len());
}
#[test]
fn for_invalid_default_type() {
let mut item_fn: ItemFn = r#"
#[default(no<valid::>type)]
fn my_fix<I>() -> I {}
"#
.ast();
let errors = FixtureInfo::default()
.extend_with_function_attrs(&mut item_fn)
.unwrap_err();
assert_eq!(1, errors.len());
}
#[test]
fn with_used_more_than_once() {
let mut item_fn: ItemFn = r#"
fn my_fix(#[with(1)] #[with(2)] fixture1: &str, #[with(1)] #[with(2)] #[with(3)] fixture2: &str) {}
"#
.ast();
let errors = FixtureInfo::default()
.extend_with_function_attrs(&mut item_fn)
.err()
.unwrap_or_default();
assert_eq!(3, errors.len());
}
#[test]
fn from_used_more_than_once() {
let mut item_fn: ItemFn = r#"
fn my_fix(#[from(a)] #[from(b)] fixture1: &str, #[from(c)] #[from(d)] #[from(e)] fixture2: &str) {}
"#
.ast();
let errors = FixtureInfo::default()
.extend_with_function_attrs(&mut item_fn)
.err()
.unwrap_or_default();
assert_eq!(3, errors.len());
}
#[test]
fn if_once_is_defined_more_than_once() {
let mut item_fn: ItemFn = r#"
#[once]
#[once]
fn my_fix<I>() -> I {}
"#
.ast();
let mut info = FixtureInfo::default();
let error = info.extend_with_function_attrs(&mut item_fn).unwrap_err();
assert_in!(
format!("{:?}", error).to_lowercase(),
"cannot use #[once] more than once"
);
}
#[test]
fn if_default_is_defined_more_than_once() {
let mut item_fn: ItemFn = r#"
#[default(u32)]
#[default(u32)]
fn my_fix<I>() -> I {}
"#
.ast();
let mut info = FixtureInfo::default();
let error = info.extend_with_function_attrs(&mut item_fn).unwrap_err();
assert_in!(
format!("{:?}", error).to_lowercase(),
"cannot use default more than once"
);
}
#[test]
fn for_invalid_partial_type() {
let mut item_fn: ItemFn = r#"
#[partial_1(no<valid::>type)]
fn my_fix<I>(x: I, y: u32) -> I {}
"#
.ast();
let errors = FixtureInfo::default()
.extend_with_function_attrs(&mut item_fn)
.unwrap_err();
assert_eq!(1, errors.len());
}
#[test]
fn if_partial_is_not_correct() {
let mut item_fn: ItemFn = r#"
#[partial_not_a_number(u32)]
fn my_fix<I, J>(f1: I, f2: &str) -> I {}
"#
.ast();
let mut info = FixtureInfo::default();
let error = info.extend_with_function_attrs(&mut item_fn).unwrap_err();
assert_in!(
format!("{:?}", error).to_lowercase(),
"invalid partial syntax"
);
}
}
}
}<|fim▁end|> | #[derive(PartialEq, Debug)]
pub(crate) enum FixtureItem {
Fixture(Fixture),
ArgumentValue(Box<ArgumentValue>), |
<|file_name|>fabfile.py<|end_file_name|><|fim▁begin|>from fabric.api import *
import fabric.contrib.project as project
import os
import shutil
import sys
import SocketServer
from pelican.server import ComplexHTTPRequestHandler
# Local path configuration (can be absolute or relative to fabfile)
env.deploy_path = 'output'
DEPLOY_PATH = env.deploy_path
# Remote server configuration
production = 'root@localhost:22'
dest_path = '/var/www'
# Rackspace Cloud Files configuration settings
env.cloudfiles_username = 'my_rackspace_username'
env.cloudfiles_api_key = 'my_rackspace_api_key'
env.cloudfiles_container = 'my_cloudfiles_container'
# Github Pages configuration
env.github_pages_branch = "master"
# Port for `serve`
PORT = 8000
def clean():
"""Remove generated files"""
if os.path.isdir(DEPLOY_PATH):
shutil.rmtree(DEPLOY_PATH)
os.makedirs(DEPLOY_PATH)
def build():
"""Build local version of site"""
local('pelican -s pelicanconf.py')
def rebuild():
"""`build` with the delete switch"""
local('pelican -d -s pelicanconf.py')
def regenerate():
"""Automatically regenerate site upon file modification"""
local('pelican -r -s pelicanconf.py')
def serve():
"""Serve site at http://localhost:8000/"""
os.chdir(env.deploy_path)
class AddressReuseTCPServer(SocketServer.TCPServer):
allow_reuse_address = True
server = AddressReuseTCPServer(('', PORT), ComplexHTTPRequestHandler)
sys.stderr.write('Serving on port {0} ...\n'.format(PORT))
server.serve_forever()
def reserve():<|fim▁hole|> """`build`, then `serve`"""
build()
serve()
def preview():
"""Build production version of site"""
local('pelican -s publishconf.py')
def cf_upload():
"""Publish to Rackspace Cloud Files"""
rebuild()
with lcd(DEPLOY_PATH):
local('swift -v -A https://auth.api.rackspacecloud.com/v1.0 '
'-U {cloudfiles_username} '
'-K {cloudfiles_api_key} '
'upload -c {cloudfiles_container} .'.format(**env))
@hosts(production)
def publish():
"""Publish to production via rsync"""
local('pelican -s publishconf.py')
project.rsync_project(
remote_dir=dest_path,
exclude=".DS_Store",
local_dir=DEPLOY_PATH.rstrip('/') + '/',
delete=True,
extra_opts='-c',
)
def gh_pages():
"""Publish to GitHub Pages"""
rebuild()
local("ghp-import -b {github_pages_branch} {deploy_path} -p".format(**env))<|fim▁end|> | |
<|file_name|>public_domain.py<|end_file_name|><|fim▁begin|>from typing import Dict, List
from service.ws_re.register._base import Register
from service.ws_re.register.author import Author
from service.ws_re.register.authors import Authors
from service.ws_re.register.lemma import Lemma
from service.ws_re.register.register_types.volume import VolumeRegister
class PublicDomainRegister(Register):
def __init__(self,
year: int,
authors: Authors,
registers: Dict[str, VolumeRegister]):
super().__init__()
self.year: int = year
self._authors: Authors = authors
self._registers = registers
self._pd_authors: List[Author] = self._get_pd_authors()
self._init_lemmas()
def __repr__(self):
return f"<{self.__class__.__name__} - year:{self.year}, lemmas:{len(self)}>"
def __len__(self):
return len(self.squash_lemmas(self._lemmas))
def __getitem__(self, item: int) -> Lemma:
return self._lemmas[item]
def _init_lemmas(self):
lemmas = []
for volume_str in self._registers:
for lemma in self._registers[volume_str].lemmas:
if self._is_lemma_of_author(lemma):
lemmas.append(lemma)
self._lemmas = sorted(lemmas, key=lambda k: (k.sort_key, k.volume.sort_key))
def _get_pd_authors(self) -> List[Author]:
author_list = []
for author in self._authors:
if author.death:
if author.death == self.year - 71:
author_list.append(author)
continue
if author.birth == self.year - 171:
author_list.append(author)
return author_list
def _is_lemma_of_author(self, lemma: Lemma) -> bool:
for chapter in lemma.chapters:
if chapter.author:
authors_of_lemma = self._authors.get_author_by_mapping(chapter.author, lemma.volume.name)
for author in self._pd_authors:
if author in authors_of_lemma:
return True
return False
def _get_table(self) -> str:
header = """{|class="wikitable sortable"
!Artikel
!Band
!Status
!Wikilinks
!Seite
!Autor
!Sterbejahr"""
table = [header]
for lemmas in self.squash_lemmas(self._lemmas):
chapter_sum = 0
table_rows = []
lemma = None
for lemma in lemmas:
# if there are no chapters ... one line must be added no madder what
chapter_sum += max(len(lemma.chapters), 1)
table_rows.append(lemma.get_table_row(print_volume=True))
# strip |-/n form the first line it is later replaced by the lemma line
table_rows[0] = table_rows[0][3:]
if chapter_sum > 1:
table.append(f"|-\n|rowspan={chapter_sum} data-sort-value=\"{lemma.sort_key}\"|{lemma.get_link()}")
else:<|fim▁hole|> table.append(f"|-\n|data-sort-value=\"{lemma.sort_key}\"|{lemma.get_link()}")
table += table_rows
table.append("|}")
return "\n".join(table)
def get_register_str(self) -> str:
return f"{self._get_table()}\n[[Kategorie:RE:Register|!]]"<|fim▁end|> | |
<|file_name|>misc.py<|end_file_name|><|fim▁begin|>from __future__ import division
import numpy as np
from chainer.backends import cuda<|fim▁hole|>
from chainercv import transforms
exp_clip = np.log(1000 / 16)
def smooth_l1(x, t, beta):
return F.huber_loss(x, t, beta, reduce='no') / beta
# to avoid out of memory
def argsort(x):
xp = cuda.get_array_module(x)
i = np.argsort(cuda.to_cpu(x))
if xp is np:
return i
else:
return cuda.to_gpu(i)
# to avoid out of memory
def choice(x, size):
xp = cuda.get_array_module(x)
y = np.random.choice(cuda.to_cpu(x), size, replace=False)
if xp is np:
return y
else:
return cuda.to_gpu(y)
def scale_img(img, min_size, max_size):
"""Process image."""
_, H, W = img.shape
scale = min_size / min(H, W)
if scale * max(H, W) > max_size:
scale = max_size / max(H, W)
H, W = int(H * scale), int(W * scale)
img = transforms.resize(img, (H, W))
return img, scale<|fim▁end|> | import chainer.functions as F |
<|file_name|>urls.py<|end_file_name|><|fim▁begin|>#-*- coding: utf-8 -*-
from django.conf.urls import url
from . import views
app_name = "perso"
urlpatterns = [
url(r'^$', views.main, name='main'),
url(r'^(?P<pageId>[0-9]+)/?$', views.main, name='main'),
url(r'^about/?$', views.about, name='about'),
url(r'^contact/?$', views.contact, name='contact'),
url(r'^(?P<cat_slug>[-a-zA-Z0-9_]+)/?$', views.main, name='main'),
url(r'^(?P<cat_slug>[-a-zA-Z0-9_]+)/(?P<pageId>[0-9]+)/?$', views.main, name='main'),<|fim▁hole|><|fim▁end|> | url(r'^publication/(?P<slug>[-a-zA-Z0-9_]+)/?$', views.publication, name='publication'),
url(r'^tag/(?P<slug>[-a-zA-Z0-9_]+)/?$', views.tag, name='tag'),
] |
<|file_name|>nil.rs<|end_file_name|><|fim▁begin|>use lua::{Index, ToLua, FromLua, State};<|fim▁hole|>use types::{LuaStackable};
/// Represents a nil value on the Lua stack
pub struct LuaNil {
index: Index
}
impl LuaNil {
/// Create a new LuaNil given an index
pub fn new(i: Index) -> LuaNil {
LuaNil {
index: i
}
}
}
impl LuaStackable for LuaNil {
fn get_pos(&self) -> Index {
self.index
}
}
impl ToLua for LuaNil {
fn to_lua(&self, state: &mut State) {
state.push_value(self.get_pos());
}
}
impl FromLua for LuaNil {
fn from_lua(state: &mut State, index: Index) -> Option<LuaNil> {
if state.is_nil(index) {
Some(LuaNil::new(index))
} else {
None
}
}
}<|fim▁end|> | |
<|file_name|>select.js<|end_file_name|><|fim▁begin|>version https://git-lfs.github.com/spec/v1
oid sha256:0f088644576fe6fee42bb3ce7f1d056f5db1079bf284c312f2acb895c5510851<|fim▁hole|><|fim▁end|> | size 11112 |
<|file_name|>test_mapping.py<|end_file_name|><|fim▁begin|>import unittest
from fam.tests.models.test01 import Dog, Cat, Person, JackRussell, Monarch
from fam.mapper import ClassMapper
class MapperTests(unittest.TestCase):
def setUp(self):<|fim▁hole|>
def tearDown(self):
pass
def test_sub_class_refs(self):
self.assertEqual(set(Monarch.fields.keys()), set(["name", "country", "cats", "dogs", "animals", "callbacks"]))
self.assertEqual(set(Monarch.cls_fields.keys()), {"country"})<|fim▁end|> | self.mapper = ClassMapper([Dog, Cat, Person, JackRussell, Monarch])
|
<|file_name|>term.js<|end_file_name|><|fim▁begin|>/*<|fim▁hole|> *
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
"use strict";
function Term(width, height, handler)
{
this.w = width;
this.h = height;
this.cur_h = height; /* current height of the scroll back buffer */
this.tot_h = 1000; /* total height of the scroll back buffer */
this.y_base = 0; /* position of the current top screen line in the
* scroll back buffer */
this.y_disp = 0; /* position of the top displayed line in the
* scroll back buffer */
/* cursor position */
this.x = 0;
this.y = 0;
this.cursorstate = 0;
this.handler = handler;
this.convert_lf_to_crlf = false;
this.state = 0;
this.output_queue = "";
this.bg_colors = [
"#000000",
"#ff0000",
"#00ff00",
"#ffff00",
"#0000ff",
"#ff00ff",
"#00ffff",
"#ffffff"
];
this.fg_colors = [
"#000000",
"#ff0000",
"#00ff00",
"#ffff00",
"#0000ff",
"#ff00ff",
"#00ffff",
"#ffffff"
];
this.def_attr = (7 << 3) | 0;
this.cur_attr = this.def_attr;
this.is_mac = (navigator.userAgent.indexOf("Mac") >=0 ) ? true : false;
this.key_rep_state = 0;
this.key_rep_str = "";
}
Term.prototype.open = function()
{
var y, line, i, term, c;
/* set initial content */
this.lines = new Array();
c = 32 | (this.def_attr << 16);
for(y = 0; y < this.cur_h;y++) {
line = new Array();
for(i=0;i<this.w;i++)
line[i] = c;
this.lines[y] = line;
}
/* create terminal window */
document.writeln('<table border="0" cellspacing="0" cellpadding="0">');
for(y=0;y<this.h;y++) {
document.writeln('<tr><td class="term" id="tline' + y + '"></td></tr>');
}
document.writeln('</table>');
this.refresh(0, this.h - 1);
// key handler
document.addEventListener("keydown",
this.keyDownHandler.bind(this), true);
document.addEventListener("keypress",
this.keyPressHandler.bind(this), true);
// cursor blinking
term = this;
setInterval(function() { term.cursor_timer_cb(); }, 1000);
};
Term.prototype.refresh = function(ymin, ymax)
{
var el, y, line, outline, c, w, i, cx, attr, last_attr, fg, bg, y1;
for(y = ymin; y <= ymax; y++) {
/* convert to HTML string */
y1 = y + this.y_disp;
if (y1 >= this.cur_h)
y1 -= this.cur_h;
line = this.lines[y1];
outline = "";
w = this.w;
if (y == this.y && this.cursor_state &&
this.y_disp == this.y_base) {
cx = this.x;
} else {
cx = -1;
}
last_attr = this.def_attr;
for(i = 0; i < w; i++) {
c = line[i];
attr = c >> 16;
c &= 0xffff;
if (i == cx) {
attr = -1; /* cursor */
}
if (attr != last_attr) {
if (last_attr != this.def_attr)
outline += '</span>';
if (attr != this.def_attr) {
if (attr == -1) {
/* cursor */
outline += '<span class="termReverse">';
} else {
outline += '<span style="';
fg = (attr >> 3) & 7;
bg = attr & 7;
if (fg != 7) {
outline += 'color:' + this.fg_colors[fg] + ';';
}
if (bg != 0) {
outline += 'background-color:' +
this.bg_colors[bg] + ';';
}
outline += '">';
}
}
}
switch(c) {
case 32:
outline += " ";
break;
case 38: // '&'
outline += "&";
break;
case 60: // '<'
outline += "<";
break;
case 62: // '>'
outline += ">";
break;
default:
if (c < 32) {
outline += " ";
} else {
outline += String.fromCharCode(c);
}
break;
}
last_attr = attr;
}
if (last_attr != this.def_attr) {
outline += '</span>';
}
el = document.getElementById("tline" + y);
el.innerHTML = outline;
}
};
Term.prototype.cursor_timer_cb = function()
{
this.cursor_state ^= 1;
this.refresh(this.y, this.y);
};
Term.prototype.show_cursor = function()
{
if (!this.cursor_state) {
this.cursor_state = 1;
this.refresh(this.y, this.y);
}
};
Term.prototype.scroll = function()
{
var y, line, x, c, y1;
/* increase height of buffer if possible */
if (this.cur_h < this.tot_h) {
this.cur_h++;
}
/* move down one line */
if (++this.y_base == this.cur_h)
this.y_base = 0;
this.y_disp = this.y_base;
c = 32 | (this.def_attr << 16);
line = new Array();
for(x=0;x<this.w;x++)
line[x] = c;
y1 = this.y_base + this.h - 1;
if (y1 >= this.cur_h)
y1 -= this.cur_h;
this.lines[y1] = line;
};
/* scroll down or up in the scroll back buffer by n lines */
Term.prototype.scroll_disp = function(n)
{
var i, y1;
/* slow but it does not really matters */
if (n >= 0) {
for(i = 0; i < n; i++) {
if (this.y_disp == this.y_base)
break;
if (++this.y_disp == this.cur_h)
this.y_disp = 0;
}
} else {
n = -n;
y1 = this.y_base + this.h;
if (y1 >= this.cur_h)
y1 -= this.cur_h;
for(i = 0; i < n; i++) {
if (this.y_disp == y1)
break;
if (--this.y_disp < 0)
this.y_disp = this.cur_h - 1;
}
}
this.refresh(0, this.h - 1);
};
Term.prototype.write = function(str)
{
function update(y)
{
ymin = Math.min(ymin, y);
ymax = Math.max(ymax, y);
}
function erase_to_eol(s, x, y)
{
var l, i, c, y1;
y1 = s.y_base + y;
if (y1 >= s.cur_h)
y1 -= s.cur_h;
l = s.lines[y1];
c = 32 | (s.def_attr << 16);
for(i = x; i < s.w; i++)
l[i] = c;
update(y);
}
function csi_colors(s, esc_params)
{
var j, n;
if (esc_params.length == 0) {
s.cur_attr= s.def_attr;
} else {
for(j = 0; j < esc_params.length; j++) {
n = esc_params[j];
if (n >= 30 && n <= 37) {
/* foreground */
s.cur_attr = (s.cur_attr & ~(7 << 3)) | ((n - 30) << 3);
} else if (n >= 40 && n <= 47) {
/* background */
s.cur_attr = (s.cur_attr & ~7) | (n - 40);
} else if (n == 0) {
/* default attr */
s.cur_attr = s.def_attr;
}
}
}
}
var TTY_STATE_NORM = 0;
var TTY_STATE_ESC = 1;
var TTY_STATE_CSI = 2;
var i, c, ymin, ymax, l, n, j, y1;
/* update region is in ymin ymax */
ymin = this.h;
ymax = -1;
update(this.y); // remove the cursor
/* reset top of displayed screen to top of real screen */
if (this.y_base != this.y_disp) {
this.y_disp = this.y_base;
/* force redraw */
ymin = 0;
ymax = this.h - 1;
}
for(i = 0; i < str.length; i++) {
c = str.charCodeAt(i);
switch(this.state) {
case TTY_STATE_NORM:
switch(c) {
case 10:
if (this.convert_lf_to_crlf) {
this.x = 0; // emulates '\r'
}
this.y++;
if (this.y >= this.h) {
this.y--;
this.scroll();
ymin = 0;
ymax = this.h - 1;
}
break;
case 13:
this.x = 0;
break;
case 8:
if (this.x > 0) {
this.x--;
}
break;
case 9: /* tab */
n = (this.x + 8) & ~7;
if (n <= this.w) {
this.x = n;
}
break;
case 27:
this.state = TTY_STATE_ESC;
break;
default:
if (c >= 32) {
if (this.x >= this.w) {
this.x = 0;
this.y++;
if (this.y >= this.h) {
this.y--;
this.scroll();
ymin = 0;
ymax = this.h - 1;
}
}
y1 = this.y + this.y_base;
if (y1 >= this.cur_h)
y1 -= this.cur_h;
this.lines[y1][this.x] = (c & 0xffff) |
(this.cur_attr << 16);
this.x++;
update(this.y);
}
break;
}
break;
case TTY_STATE_ESC:
if (c == 91) { // '['
this.esc_params = new Array();
this.cur_param = 0;
this.state = TTY_STATE_CSI;
} else {
this.state = TTY_STATE_NORM;
}
break;
case TTY_STATE_CSI:
if (c >= 48 && c <= 57) { // '0' '9'
/* numeric */
this.cur_param = this.cur_param * 10 + c - 48;
} else {
/* add parsed parameter */
this.esc_params[this.esc_params.length] = this.cur_param;
this.cur_param = 0;
if (c == 59) // ;
break;
this.state = TTY_STATE_NORM;
// console.log("term: csi=" + this.esc_params + " cmd="+c);
switch(c) {
case 65: // 'A' up
n = this.esc_params[0];
if (n < 1)
n = 1;
this.y -= n;
if (this.y < 0)
this.y = 0;
break;
case 66: // 'B' down
n = this.esc_params[0];
if (n < 1)
n = 1;
this.y += n;
if (this.y >= this.h)
this.y = this.h - 1;
break;
case 67: // 'C' right
n = this.esc_params[0];
if (n < 1)
n = 1;
this.x += n;
if (this.x >= this.w - 1)
this.x = this.w - 1;
break;
case 68: // 'D' left
n = this.esc_params[0];
if (n < 1)
n = 1;
this.x -= n;
if (this.x < 0)
this.x = 0;
break;
case 72: // 'H' goto xy
{
var x1, y1;
y1 = this.esc_params[0] - 1;
if (this.esc_params.length >= 2)
x1 = this.esc_params[1] - 1;
else
x1 = 0;
if (y1 < 0)
y1 = 0;
else if (y1 >= this.h)
y1 = this.h - 1;
if (x1 < 0)
x1 = 0;
else if (x1 >= this.w)
x1 = this.w - 1;
this.x = x1;
this.y = y1;
}
break;
case 74: // 'J' erase to end of screen
erase_to_eol(this, this.x, this.y);
for(j = this.y + 1; j < this.h; j++)
erase_to_eol(this, 0, j);
break;
case 75: // 'K' erase to end of line
erase_to_eol(this, this.x, this.y);
break;
case 109: // 'm': set color
csi_colors(this, this.esc_params);
break;
case 110: // 'n' return the cursor position
this.queue_chars("\x1b[" + (this.y + 1) + ";" + (this.x + 1) + "R");
break;
default:
break;
}
}
break;
}
}
update(this.y); // show the cursor
if (ymax >= ymin)
this.refresh(ymin, ymax);
};
Term.prototype.writeln = function (str)
{
this.write(str + '\r\n');
};
Term.prototype.keyDownHandler = function (ev)
{
var str;
str="";
switch(ev.keyCode) {
case 8: /* backspace */
str = "\x7f";
break;
case 9: /* tab */
str = "\x09";
break;
case 13: /* enter */
str = "\x0d";
break;
case 27: /* escape */
str = "\x1b";
break;
case 37: /* left */
str = "\x1b[D";
break;
case 39: /* right */
str = "\x1b[C";
break;
case 38: /* up */
if (ev.ctrlKey) {
this.scroll_disp(-1);
} else {
str = "\x1b[A";
}
break;
case 40: /* down */
if (ev.ctrlKey) {
this.scroll_disp(1);
} else {
str = "\x1b[B";
}
break;
case 46: /* delete */
str = "\x1b[3~";
break;
case 45: /* insert */
str = "\x1b[2~";
break;
case 36: /* home */
str = "\x1bOH";
break;
case 35: /* end */
str = "\x1bOF";
break;
case 33: /* page up */
if (ev.ctrlKey) {
this.scroll_disp(-(this.h - 1));
} else {
str = "\x1b[5~";
}
break;
case 34: /* page down */
if (ev.ctrlKey) {
this.scroll_disp(this.h - 1);
} else {
str = "\x1b[6~";
}
break;
default:
if (ev.ctrlKey) {
/* ctrl + key */
if (ev.keyCode >= 65 && ev.keyCode <= 90) {
str = String.fromCharCode(ev.keyCode - 64);
} else if (ev.keyCode == 32) {
str = String.fromCharCode(0);
}
} else if ((!this.is_mac && ev.altKey) ||
(this.is_mac && ev.metaKey)) {
/* meta + key (Note: we only send lower case) */
if (ev.keyCode >= 65 && ev.keyCode <= 90) {
str = "\x1b" + String.fromCharCode(ev.keyCode + 32);
}
}
break;
}
// console.log("keydown: keycode=" + ev.keyCode + " charcode=" + ev.charCode + " str=" + str + " ctrl=" + ev.ctrlKey + " alt=" + ev.altKey + " meta=" + ev.metaKey);
if (str) {
if (ev.stopPropagation)
ev.stopPropagation();
if (ev.preventDefault)
ev.preventDefault();
this.show_cursor();
this.key_rep_state = 1;
this.key_rep_str = str;
this.handler(str);
return false;
} else {
this.key_rep_state = 0;
return true;
}
};
Term.prototype.keyPressHandler = function (ev)
{
var str, char_code;
if (ev.stopPropagation)
ev.stopPropagation();
if (ev.preventDefault)
ev.preventDefault();
str="";
if (!("charCode" in ev)) {
/* on Opera charCode is not defined and keypress is sent for
system keys. Moreover, only keupress is repeated which is a
problem for system keys. */
char_code = ev.keyCode;
if (this.key_rep_state == 1) {
this.key_rep_state = 2;
return false;
} else if (this.key_rep_state == 2) {
/* repetition */
this.show_cursor();
this.handler(this.key_rep_str);
return false;
}
} else {
char_code = ev.charCode;
}
if (char_code != 0) {
if (!ev.ctrlKey &&
((!this.is_mac && !ev.altKey) ||
(this.is_mac && !ev.metaKey))) {
str = String.fromCharCode(char_code);
}
}
// console.log("keypress: keycode=" + ev.keyCode + " charcode=" + ev.charCode + " str=" + str + " ctrl=" + ev.ctrlKey + " alt=" + ev.altKey + " meta=" + ev.metaKey);
if (str) {
this.show_cursor();
this.handler(str);
return false;
} else {
return true;
}
};
/* output queue to send back asynchronous responses */
Term.prototype.queue_chars = function (str)
{
this.output_queue += str;
if (this.output_queue)
setTimeout(this.outputHandler.bind(this), 0);
};
Term.prototype.outputHandler = function ()
{
if (this.output_queue) {
this.handler(this.output_queue);
this.output_queue = "";
}
};<|fim▁end|> | * Javascript terminal
*
* Copyright (c) 2011 Fabrice Bellard |
<|file_name|>adl_defines.py<|end_file_name|><|fim▁begin|># Copyright (C) 2011 by Mark Visser <[email protected]>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# This code is based on the AMD Display Library 3.0 SDK
ADL_TRUE = 1 # ADL_SDK_3.0/include/adl_defines.h:52
ADL_FALSE = 0 # ADL_SDK_3.0/include/adl_defines.h:55
ADL_MAX_CHAR = 4096 # ADL_SDK_3.0/include/adl_defines.h:59
ADL_MAX_PATH = 256 # ADL_SDK_3.0/include/adl_defines.h:62
ADL_MAX_ADAPTERS = 150 # ADL_SDK_3.0/include/adl_defines.h:65
ADL_MAX_DISPLAYS = 150 # ADL_SDK_3.0/include/adl_defines.h:68
ADL_MAX_DEVICENAME = 32 # ADL_SDK_3.0/include/adl_defines.h:71
ADL_ADAPTER_INDEX_ALL = -1 # ADL_SDK_3.0/include/adl_defines.h:74
ADL_MAIN_API_OPTION_NONE = 0 # ADL_SDK_3.0/include/adl_defines.h:77
ADL_DDC_OPTION_SWITCHDDC2 = 1 # ADL_SDK_3.0/include/adl_defines.h:90
ADL_DDC_OPTION_RESTORECOMMAND = 2 # ADL_SDK_3.0/include/adl_defines.h:93
ADL_DL_I2C_ACTIONREAD = 1 # ADL_SDK_3.0/include/adl_defines.h:104
ADL_DL_I2C_ACTIONWRITE = 2 # ADL_SDK_3.0/include/adl_defines.h:105
ADL_DL_I2C_ACTIONREAD_REPEATEDSTART = 3 # ADL_SDK_3.0/include/adl_defines.h:106
ADL_OK_WAIT = 4 # ADL_SDK_3.0/include/adl_defines.h:122
ADL_OK_RESTART = 3 # ADL_SDK_3.0/include/adl_defines.h:125
ADL_OK_MODE_CHANGE = 2 # ADL_SDK_3.0/include/adl_defines.h:128
ADL_OK_WARNING = 1 # ADL_SDK_3.0/include/adl_defines.h:131
ADL_OK = 0 # ADL_SDK_3.0/include/adl_defines.h:134
ADL_ERR = -1 # ADL_SDK_3.0/include/adl_defines.h:137
ADL_ERR_NOT_INIT = -2 # ADL_SDK_3.0/include/adl_defines.h:140
ADL_ERR_INVALID_PARAM = -3 # ADL_SDK_3.0/include/adl_defines.h:143
ADL_ERR_INVALID_PARAM_SIZE = -4 # ADL_SDK_3.0/include/adl_defines.h:146
ADL_ERR_INVALID_ADL_IDX = -5 # ADL_SDK_3.0/include/adl_defines.h:149
ADL_ERR_INVALID_CONTROLLER_IDX = -6 # ADL_SDK_3.0/include/adl_defines.h:152
ADL_ERR_INVALID_DIPLAY_IDX = -7 # ADL_SDK_3.0/include/adl_defines.h:155
ADL_ERR_NOT_SUPPORTED = -8 # ADL_SDK_3.0/include/adl_defines.h:158
ADL_ERR_NULL_POINTER = -9 # ADL_SDK_3.0/include/adl_defines.h:161
ADL_ERR_DISABLED_ADAPTER = -10 # ADL_SDK_3.0/include/adl_defines.h:164
ADL_ERR_INVALID_CALLBACK = -11 # ADL_SDK_3.0/include/adl_defines.h:167
ADL_ERR_RESOURCE_CONFLICT = -12 # ADL_SDK_3.0/include/adl_defines.h:170
ADL_DT_MONITOR = 0 # ADL_SDK_3.0/include/adl_defines.h:185
ADL_DT_TELEVISION = 1 # ADL_SDK_3.0/include/adl_defines.h:188
ADL_DT_LCD_PANEL = 2 # ADL_SDK_3.0/include/adl_defines.h:191
ADL_DT_DIGITAL_FLAT_PANEL = 3 # ADL_SDK_3.0/include/adl_defines.h:194
ADL_DT_COMPONENT_VIDEO = 4 # ADL_SDK_3.0/include/adl_defines.h:197
ADL_DT_PROJECTOR = 5 # ADL_SDK_3.0/include/adl_defines.h:200
ADL_DOT_UNKNOWN = 0 # ADL_SDK_3.0/include/adl_defines.h:210
ADL_DOT_COMPOSITE = 1 # ADL_SDK_3.0/include/adl_defines.h:213
ADL_DOT_SVIDEO = 2 # ADL_SDK_3.0/include/adl_defines.h:216
ADL_DOT_ANALOG = 3 # ADL_SDK_3.0/include/adl_defines.h:219
ADL_DOT_DIGITAL = 4 # ADL_SDK_3.0/include/adl_defines.h:222
ADL_DISPLAY_COLOR_BRIGHTNESS = 1 # ADL_SDK_3.0/include/adl_defines.h:232
ADL_DISPLAY_COLOR_CONTRAST = 2 # ADL_SDK_3.0/include/adl_defines.h:233
ADL_DISPLAY_COLOR_SATURATION = 4 # ADL_SDK_3.0/include/adl_defines.h:234
ADL_DISPLAY_COLOR_HUE = 8 # ADL_SDK_3.0/include/adl_defines.h:235
ADL_DISPLAY_COLOR_TEMPERATURE = 16 # ADL_SDK_3.0/include/adl_defines.h:236
ADL_DISPLAY_COLOR_TEMPERATURE_SOURCE_EDID = 32 # ADL_SDK_3.0/include/adl_defines.h:240
ADL_DISPLAY_COLOR_TEMPERATURE_SOURCE_USER = 64 # ADL_SDK_3.0/include/adl_defines.h:243
ADL_DISPLAY_ADJUST_OVERSCAN = 1 # ADL_SDK_3.0/include/adl_defines.h:253
ADL_DISPLAY_ADJUST_VERT_POS = 2 # ADL_SDK_3.0/include/adl_defines.h:254
ADL_DISPLAY_ADJUST_HOR_POS = 4 # ADL_SDK_3.0/include/adl_defines.h:255
ADL_DISPLAY_ADJUST_VERT_SIZE = 8 # ADL_SDK_3.0/include/adl_defines.h:256
ADL_DISPLAY_ADJUST_HOR_SIZE = 16 # ADL_SDK_3.0/include/adl_defines.h:257
ADL_DISPLAY_ADJUST_SIZEPOS = 30 # ADL_SDK_3.0/include/adl_defines.h:258
ADL_DISPLAY_CUSTOMMODES = 32 # ADL_SDK_3.0/include/adl_defines.h:259
ADL_DISPLAY_ADJUST_UNDERSCAN = 64 # ADL_SDK_3.0/include/adl_defines.h:260
ADL_DESKTOPCONFIG_UNKNOWN = 0 # ADL_SDK_3.0/include/adl_defines.h:271
ADL_DESKTOPCONFIG_SINGLE = 1 # ADL_SDK_3.0/include/adl_defines.h:272
ADL_DESKTOPCONFIG_CLONE = 4 # ADL_SDK_3.0/include/adl_defines.h:273
ADL_DESKTOPCONFIG_BIGDESK_H = 16 # ADL_SDK_3.0/include/adl_defines.h:274
ADL_DESKTOPCONFIG_BIGDESK_V = 32 # ADL_SDK_3.0/include/adl_defines.h:275
ADL_DESKTOPCONFIG_BIGDESK_HR = 64 # ADL_SDK_3.0/include/adl_defines.h:276
ADL_DESKTOPCONFIG_BIGDESK_VR = 128 # ADL_SDK_3.0/include/adl_defines.h:277
ADL_DESKTOPCONFIG_RANDR12 = 256 # ADL_SDK_3.0/include/adl_defines.h:278
ADL_MAX_DISPLAY_NAME = 256 # ADL_SDK_3.0/include/adl_defines.h:284
ADL_DISPLAYDDCINFOEX_FLAG_PROJECTORDEVICE = 1 # ADL_SDK_3.0/include/adl_defines.h:292
ADL_DISPLAYDDCINFOEX_FLAG_EDIDEXTENSION = 2 # ADL_SDK_3.0/include/adl_defines.h:293
ADL_DISPLAYDDCINFOEX_FLAG_DIGITALDEVICE = 4 # ADL_SDK_3.0/include/adl_defines.h:294
ADL_DISPLAYDDCINFOEX_FLAG_HDMIAUDIODEVICE = 8 # ADL_SDK_3.0/include/adl_defines.h:295
ADL_DISPLAYDDCINFOEX_FLAG_SUPPORTS_AI = 16 # ADL_SDK_3.0/include/adl_defines.h:296
ADL_DISPLAYDDCINFOEX_FLAG_SUPPORT_xvYCC601 = 32 # ADL_SDK_3.0/include/adl_defines.h:297
ADL_DISPLAYDDCINFOEX_FLAG_SUPPORT_xvYCC709 = 64 # ADL_SDK_3.0/include/adl_defines.h:298
ADL_DISPLAY_CONTYPE_UNKNOWN = 0 # ADL_SDK_3.0/include/adl_defines.h:308
ADL_DISPLAY_CONTYPE_VGA = 1 # ADL_SDK_3.0/include/adl_defines.h:309
ADL_DISPLAY_CONTYPE_DVI_D = 2 # ADL_SDK_3.0/include/adl_defines.h:310
ADL_DISPLAY_CONTYPE_DVI_I = 3 # ADL_SDK_3.0/include/adl_defines.h:311
ADL_DISPLAY_CONTYPE_ATICVDONGLE_NTSC = 4 # ADL_SDK_3.0/include/adl_defines.h:312
ADL_DISPLAY_CONTYPE_ATICVDONGLE_JPN = 5 # ADL_SDK_3.0/include/adl_defines.h:313
ADL_DISPLAY_CONTYPE_ATICVDONGLE_NONI2C_JPN = 6 # ADL_SDK_3.0/include/adl_defines.h:314
ADL_DISPLAY_CONTYPE_ATICVDONGLE_NONI2C_NTSC = 7 # ADL_SDK_3.0/include/adl_defines.h:315
ADL_DISPLAY_CONTYPE_HDMI_TYPE_A = 10 # ADL_SDK_3.0/include/adl_defines.h:316
ADL_DISPLAY_CONTYPE_HDMI_TYPE_B = 11 # ADL_SDK_3.0/include/adl_defines.h:317
ADL_DISPLAY_CONTYPE_SVIDEO = 12 # ADL_SDK_3.0/include/adl_defines.h:318
ADL_DISPLAY_CONTYPE_COMPOSITE = 13 # ADL_SDK_3.0/include/adl_defines.h:319
ADL_DISPLAY_CONTYPE_RCA_3COMPONENT = 14 # ADL_SDK_3.0/include/adl_defines.h:320
ADL_DISPLAY_CONTYPE_DISPLAYPORT = 15 # ADL_SDK_3.0/include/adl_defines.h:321
ADL_TV_STANDARDS = 1 # ADL_SDK_3.0/include/adl_defines.h:331
ADL_TV_SCART = 2 # ADL_SDK_3.0/include/adl_defines.h:332
ADL_STANDARD_NTSC_M = 1 # ADL_SDK_3.0/include/adl_defines.h:336
ADL_STANDARD_NTSC_JPN = 2 # ADL_SDK_3.0/include/adl_defines.h:337
ADL_STANDARD_NTSC_N = 4 # ADL_SDK_3.0/include/adl_defines.h:338
ADL_STANDARD_PAL_B = 8 # ADL_SDK_3.0/include/adl_defines.h:339
ADL_STANDARD_PAL_COMB_N = 16 # ADL_SDK_3.0/include/adl_defines.h:340
ADL_STANDARD_PAL_D = 32 # ADL_SDK_3.0/include/adl_defines.h:341
ADL_STANDARD_PAL_G = 64 # ADL_SDK_3.0/include/adl_defines.h:342
ADL_STANDARD_PAL_H = 128 # ADL_SDK_3.0/include/adl_defines.h:343
ADL_STANDARD_PAL_I = 256 # ADL_SDK_3.0/include/adl_defines.h:344
ADL_STANDARD_PAL_K = 512 # ADL_SDK_3.0/include/adl_defines.h:345
ADL_STANDARD_PAL_K1 = 1024 # ADL_SDK_3.0/include/adl_defines.h:346
ADL_STANDARD_PAL_L = 2048 # ADL_SDK_3.0/include/adl_defines.h:347
ADL_STANDARD_PAL_M = 4096 # ADL_SDK_3.0/include/adl_defines.h:348
ADL_STANDARD_PAL_N = 8192 # ADL_SDK_3.0/include/adl_defines.h:349
ADL_STANDARD_PAL_SECAM_D = 16384 # ADL_SDK_3.0/include/adl_defines.h:350
ADL_STANDARD_PAL_SECAM_K = 32768 # ADL_SDK_3.0/include/adl_defines.h:351
ADL_STANDARD_PAL_SECAM_K1 = 65536 # ADL_SDK_3.0/include/adl_defines.h:352
ADL_STANDARD_PAL_SECAM_L = 131072 # ADL_SDK_3.0/include/adl_defines.h:353
ADL_CUSTOMIZEDMODEFLAG_MODESUPPORTED = 1 # ADL_SDK_3.0/include/adl_defines.h:364
ADL_CUSTOMIZEDMODEFLAG_NOTDELETETABLE = 2 # ADL_SDK_3.0/include/adl_defines.h:365
ADL_CUSTOMIZEDMODEFLAG_INSERTBYDRIVER = 4 # ADL_SDK_3.0/include/adl_defines.h:366
ADL_CUSTOMIZEDMODEFLAG_INTERLACED = 8 # ADL_SDK_3.0/include/adl_defines.h:367
ADL_CUSTOMIZEDMODEFLAG_BASEMODE = 16 # ADL_SDK_3.0/include/adl_defines.h:368
ADL_DISPLAYDDCINFOEX_FLAG_PROJECTORDEVICE = 1 # ADL_SDK_3.0/include/adl_defines.h:378
ADL_DISPLAYDDCINFOEX_FLAG_EDIDEXTENSION = 2 # ADL_SDK_3.0/include/adl_defines.h:379
ADL_DISPLAYDDCINFOEX_FLAG_DIGITALDEVICE = 4 # ADL_SDK_3.0/include/adl_defines.h:380
ADL_DISPLAYDDCINFOEX_FLAG_HDMIAUDIODEVICE = 8 # ADL_SDK_3.0/include/adl_defines.h:381
ADL_DISPLAYDDCINFOEX_FLAG_SUPPORTS_AI = 16 # ADL_SDK_3.0/include/adl_defines.h:382
ADL_DISPLAYDDCINFOEX_FLAG_SUPPORT_xvYCC601 = 32 # ADL_SDK_3.0/include/adl_defines.h:383
ADL_DISPLAYDDCINFOEX_FLAG_SUPPORT_xvYCC709 = 64 # ADL_SDK_3.0/include/adl_defines.h:384
ADL_DISPLAY_CV_DONGLE_D1 = 1 # ADL_SDK_3.0/include/adl_defines.h:394
ADL_DISPLAY_CV_DONGLE_D2 = 2 # ADL_SDK_3.0/include/adl_defines.h:395
ADL_DISPLAY_CV_DONGLE_D3 = 4 # ADL_SDK_3.0/include/adl_defines.h:396
ADL_DISPLAY_CV_DONGLE_D4 = 8 # ADL_SDK_3.0/include/adl_defines.h:397
ADL_DISPLAY_CV_DONGLE_D5 = 16 # ADL_SDK_3.0/include/adl_defines.h:398
ADL_DISPLAY_CV_DONGLE_480I = 1 # ADL_SDK_3.0/include/adl_defines.h:403
ADL_DISPLAY_CV_DONGLE_480P = 2 # ADL_SDK_3.0/include/adl_defines.h:404
ADL_DISPLAY_CV_DONGLE_540P = 4 # ADL_SDK_3.0/include/adl_defines.h:405
ADL_DISPLAY_CV_DONGLE_720P = 8 # ADL_SDK_3.0/include/adl_defines.h:406
ADL_DISPLAY_CV_DONGLE_1080I = 16 # ADL_SDK_3.0/include/adl_defines.h:407
ADL_DISPLAY_CV_DONGLE_1080P = 32 # ADL_SDK_3.0/include/adl_defines.h:408
ADL_DISPLAY_CV_DONGLE_16_9 = 64 # ADL_SDK_3.0/include/adl_defines.h:409
ADL_DISPLAY_CV_DONGLE_720P50 = 128 # ADL_SDK_3.0/include/adl_defines.h:410
ADL_DISPLAY_CV_DONGLE_1080I25 = 256 # ADL_SDK_3.0/include/adl_defines.h:411
ADL_DISPLAY_CV_DONGLE_576I25 = 512 # ADL_SDK_3.0/include/adl_defines.h:412
ADL_DISPLAY_CV_DONGLE_576P50 = 1024 # ADL_SDK_3.0/include/adl_defines.h:413
ADL_DISPLAY_CV_DONGLE_1080P24 = 2048 # ADL_SDK_3.0/include/adl_defines.h:414
ADL_DISPLAY_CV_DONGLE_1080P25 = 4096 # ADL_SDK_3.0/include/adl_defines.h:415
ADL_DISPLAY_CV_DONGLE_1080P30 = 8192 # ADL_SDK_3.0/include/adl_defines.h:416
ADL_DISPLAY_CV_DONGLE_1080P50 = 16384 # ADL_SDK_3.0/include/adl_defines.h:417
ADL_DISPLAY_FORMAT_FORCE_720P = 1 # ADL_SDK_3.0/include/adl_defines.h:429
ADL_DISPLAY_FORMAT_FORCE_1080I = 2 # ADL_SDK_3.0/include/adl_defines.h:430
ADL_DISPLAY_FORMAT_FORCE_1080P = 4 # ADL_SDK_3.0/include/adl_defines.h:431
ADL_DISPLAY_FORMAT_FORCE_720P50 = 8 # ADL_SDK_3.0/include/adl_defines.h:432
ADL_DISPLAY_FORMAT_FORCE_1080I25 = 16 # ADL_SDK_3.0/include/adl_defines.h:433
ADL_DISPLAY_FORMAT_FORCE_576I25 = 32 # ADL_SDK_3.0/include/adl_defines.h:434
ADL_DISPLAY_FORMAT_FORCE_576P50 = 64 # ADL_SDK_3.0/include/adl_defines.h:435
ADL_DISPLAY_FORMAT_FORCE_1080P24 = 128 # ADL_SDK_3.0/include/adl_defines.h:436
ADL_DISPLAY_FORMAT_FORCE_1080P25 = 256 # ADL_SDK_3.0/include/adl_defines.h:437
ADL_DISPLAY_FORMAT_FORCE_1080P30 = 512 # ADL_SDK_3.0/include/adl_defines.h:438
ADL_DISPLAY_FORMAT_FORCE_1080P50 = 1024 # ADL_SDK_3.0/include/adl_defines.h:439
ADL_DISPLAY_FORMAT_CVDONGLEOVERIDE = 1 # ADL_SDK_3.0/include/adl_defines.h:444
ADL_DISPLAY_FORMAT_CVMODEUNDERSCAN = 2 # ADL_SDK_3.0/include/adl_defines.h:445
ADL_DISPLAY_FORMAT_FORCECONNECT_SUPPORTED = 4 # ADL_SDK_3.0/include/adl_defines.h:446
ADL_DISPLAY_FORMAT_RESTRICT_FORMAT_SELECTION = 8 # ADL_SDK_3.0/include/adl_defines.h:447
ADL_DISPLAY_FORMAT_SETASPECRATIO = 16 # ADL_SDK_3.0/include/adl_defines.h:448
ADL_DISPLAY_FORMAT_FORCEMODES = 32 # ADL_SDK_3.0/include/adl_defines.h:449
ADL_DISPLAY_FORMAT_LCDRTCCOEFF = 64 # ADL_SDK_3.0/include/adl_defines.h:450
ADL_PM_PARAM_DONT_CHANGE = 0 # ADL_SDK_3.0/include/adl_defines.h:456
ADL_BUSTYPE_PCI = 0 # ADL_SDK_3.0/include/adl_defines.h:462
ADL_BUSTYPE_AGP = 1 # ADL_SDK_3.0/include/adl_defines.h:463
ADL_BUSTYPE_PCIE = 2 # ADL_SDK_3.0/include/adl_defines.h:464
ADL_BUSTYPE_PCIE_GEN2 = 3 # ADL_SDK_3.0/include/adl_defines.h:465
ADL_STEREO_SUPPORTED = 4 # ADL_SDK_3.0/include/adl_defines.h:478
ADL_STEREO_BLUE_LINE = 8 # ADL_SDK_3.0/include/adl_defines.h:481
ADL_STEREO_OFF = 0 # ADL_SDK_3.0/include/adl_defines.h:484
ADL_STEREO_ACTIVE = 2 # ADL_SDK_3.0/include/adl_defines.h:487
ADL_STEREO_AUTO_HORIZONTAL = 1073741824 # ADL_SDK_3.0/include/adl_defines.h:490
ADL_STEREO_AUTO_VERTICAL = 2147483648 # ADL_SDK_3.0/include/adl_defines.h:493
ADL_STEREO_PASSIVE = 64 # ADL_SDK_3.0/include/adl_defines.h:496
ADL_STEREO_PASSIVE_HORIZ = 128 # ADL_SDK_3.0/include/adl_defines.h:499
ADL_STEREO_PASSIVE_VERT = 256 # ADL_SDK_3.0/include/adl_defines.h:502
ADL_WORKSTATION_LOADBALANCING_SUPPORTED = 1 # ADL_SDK_3.0/include/adl_defines.h:507
ADL_WORKSTATION_LOADBALANCING_AVAILABLE = 2 # ADL_SDK_3.0/include/adl_defines.h:510
ADL_WORKSTATION_LOADBALANCING_DISABLED = 0 # ADL_SDK_3.0/include/adl_defines.h:514
ADL_WORKSTATION_LOADBALANCING_ENABLED = 1 # ADL_SDK_3.0/include/adl_defines.h:517
ADL_CONTEXT_SPEED_UNFORCED = 0 # ADL_SDK_3.0/include/adl_defines.h:526
ADL_CONTEXT_SPEED_FORCEHIGH = 1 # ADL_SDK_3.0/include/adl_defines.h:527
ADL_CONTEXT_SPEED_FORCELOW = 2 # ADL_SDK_3.0/include/adl_defines.h:528
ADL_ADAPTER_SPEEDCAPS_SUPPORTED = 1 # ADL_SDK_3.0/include/adl_defines.h:530
ADL_GLSYNC_PORT_UNKNOWN = 0 # ADL_SDK_3.0/include/adl_defines.h:542
ADL_GLSYNC_PORT_BNC = 1 # ADL_SDK_3.0/include/adl_defines.h:545
ADL_GLSYNC_PORT_RJ45PORT1 = 2 # ADL_SDK_3.0/include/adl_defines.h:548
ADL_GLSYNC_PORT_RJ45PORT2 = 3 # ADL_SDK_3.0/include/adl_defines.h:551
ADL_GLSYNC_CONFIGMASK_NONE = 0 # ADL_SDK_3.0/include/adl_defines.h:558
ADL_GLSYNC_CONFIGMASK_SIGNALSOURCE = 1 # ADL_SDK_3.0/include/adl_defines.h:561
ADL_GLSYNC_CONFIGMASK_SYNCFIELD = 2 # ADL_SDK_3.0/include/adl_defines.h:564
ADL_GLSYNC_CONFIGMASK_SAMPLERATE = 4 # ADL_SDK_3.0/include/adl_defines.h:567
ADL_GLSYNC_CONFIGMASK_SYNCDELAY = 8 # ADL_SDK_3.0/include/adl_defines.h:570
ADL_GLSYNC_CONFIGMASK_TRIGGEREDGE = 16 # ADL_SDK_3.0/include/adl_defines.h:573
ADL_GLSYNC_CONFIGMASK_SCANRATECOEFF = 32 # ADL_SDK_3.0/include/adl_defines.h:576
ADL_GLSYNC_CONFIGMASK_FRAMELOCKCNTL = 64 # ADL_SDK_3.0/include/adl_defines.h:579
ADL_GLSYNC_FRAMELOCKCNTL_NONE = 0 # ADL_SDK_3.0/include/adl_defines.h:587
ADL_GLSYNC_FRAMELOCKCNTL_ENABLE = 1 # ADL_SDK_3.0/include/adl_defines.h:590
ADL_GLSYNC_FRAMELOCKCNTL_DISABLE = 2 # ADL_SDK_3.0/include/adl_defines.h:592
ADL_GLSYNC_FRAMELOCKCNTL_SWAP_COUNTER_RESET = 4 # ADL_SDK_3.0/include/adl_defines.h:593
ADL_GLSYNC_FRAMELOCKCNTL_SWAP_COUNTER_ACK = 8 # ADL_SDK_3.0/include/adl_defines.h:594
ADL_GLSYNC_FRAMELOCKCNTL_STATE_ENABLE = 1 # ADL_SDK_3.0/include/adl_defines.h:596
ADL_GLSYNC_COUNTER_SWAP = 1 # ADL_SDK_3.0/include/adl_defines.h:600
ADL_GLSYNC_SIGNALSOURCE_UNDEFINED = 256 # ADL_SDK_3.0/include/adl_defines.h:607
ADL_GLSYNC_SIGNALSOURCE_FREERUN = 257 # ADL_SDK_3.0/include/adl_defines.h:610
ADL_GLSYNC_SIGNALSOURCE_BNCPORT = 258 # ADL_SDK_3.0/include/adl_defines.h:613
ADL_GLSYNC_SIGNALSOURCE_RJ45PORT1 = 259 # ADL_SDK_3.0/include/adl_defines.h:616
ADL_GLSYNC_SIGNALSOURCE_RJ45PORT2 = 260 # ADL_SDK_3.0/include/adl_defines.h:619
ADL_GLSYNC_SIGNALTYPE_UNDEFINED = 0 # ADL_SDK_3.0/include/adl_defines.h:627
ADL_GLSYNC_SIGNALTYPE_480I = 1 # ADL_SDK_3.0/include/adl_defines.h:630
ADL_GLSYNC_SIGNALTYPE_576I = 2 # ADL_SDK_3.0/include/adl_defines.h:633
ADL_GLSYNC_SIGNALTYPE_480P = 3 # ADL_SDK_3.0/include/adl_defines.h:636
ADL_GLSYNC_SIGNALTYPE_576P = 4 # ADL_SDK_3.0/include/adl_defines.h:639
ADL_GLSYNC_SIGNALTYPE_720P = 5 # ADL_SDK_3.0/include/adl_defines.h:642
ADL_GLSYNC_SIGNALTYPE_1080P = 6 # ADL_SDK_3.0/include/adl_defines.h:645
ADL_GLSYNC_SIGNALTYPE_1080I = 7 # ADL_SDK_3.0/include/adl_defines.h:648
ADL_GLSYNC_SIGNALTYPE_SDI = 8 # ADL_SDK_3.0/include/adl_defines.h:651
ADL_GLSYNC_SIGNALTYPE_TTL = 9 # ADL_SDK_3.0/include/adl_defines.h:654
ADL_GLSYNC_SIGNALTYPE_ANALOG = 10 # ADL_SDK_3.0/include/adl_defines.h:657
ADL_GLSYNC_SYNCFIELD_UNDEFINED = 0 # ADL_SDK_3.0/include/adl_defines.h:664
ADL_GLSYNC_SYNCFIELD_BOTH = 1 # ADL_SDK_3.0/include/adl_defines.h:667
ADL_GLSYNC_SYNCFIELD_1 = 2 # ADL_SDK_3.0/include/adl_defines.h:670
ADL_GLSYNC_TRIGGEREDGE_UNDEFINED = 0 # ADL_SDK_3.0/include/adl_defines.h:678
ADL_GLSYNC_TRIGGEREDGE_RISING = 1 # ADL_SDK_3.0/include/adl_defines.h:681
ADL_GLSYNC_TRIGGEREDGE_FALLING = 2 # ADL_SDK_3.0/include/adl_defines.h:684
ADL_GLSYNC_TRIGGEREDGE_BOTH = 3 # ADL_SDK_3.0/include/adl_defines.h:687
ADL_GLSYNC_SCANRATECOEFF_UNDEFINED = 0 # ADL_SDK_3.0/include/adl_defines.h:695
ADL_GLSYNC_SCANRATECOEFF_x5 = 1 # ADL_SDK_3.0/include/adl_defines.h:698
ADL_GLSYNC_SCANRATECOEFF_x4 = 2 # ADL_SDK_3.0/include/adl_defines.h:701
ADL_GLSYNC_SCANRATECOEFF_x3 = 3 # ADL_SDK_3.0/include/adl_defines.h:704
ADL_GLSYNC_SCANRATECOEFF_x5_DIV_2 = 4 # ADL_SDK_3.0/include/adl_defines.h:707
ADL_GLSYNC_SCANRATECOEFF_x2 = 5 # ADL_SDK_3.0/include/adl_defines.h:710
ADL_GLSYNC_SCANRATECOEFF_x3_DIV_2 = 6 # ADL_SDK_3.0/include/adl_defines.h:713
ADL_GLSYNC_SCANRATECOEFF_x5_DIV_4 = 7 # ADL_SDK_3.0/include/adl_defines.h:716
ADL_GLSYNC_SCANRATECOEFF_x1 = 8 # ADL_SDK_3.0/include/adl_defines.h:719
ADL_GLSYNC_SCANRATECOEFF_x4_DIV_5 = 9 # ADL_SDK_3.0/include/adl_defines.h:722
ADL_GLSYNC_SCANRATECOEFF_x2_DIV_3 = 10 # ADL_SDK_3.0/include/adl_defines.h:725
ADL_GLSYNC_SCANRATECOEFF_x1_DIV_2 = 11 # ADL_SDK_3.0/include/adl_defines.h:728
ADL_GLSYNC_SCANRATECOEFF_x2_DIV_5 = 12 # ADL_SDK_3.0/include/adl_defines.h:731
ADL_GLSYNC_SCANRATECOEFF_x1_DIV_3 = 13 # ADL_SDK_3.0/include/adl_defines.h:734
ADL_GLSYNC_SCANRATECOEFF_x1_DIV_4 = 14 # ADL_SDK_3.0/include/adl_defines.h:737
ADL_GLSYNC_SCANRATECOEFF_x1_DIV_5 = 15 # ADL_SDK_3.0/include/adl_defines.h:740
ADL_GLSYNC_PORTSTATE_UNDEFINED = 0 # ADL_SDK_3.0/include/adl_defines.h:748
ADL_GLSYNC_PORTSTATE_NOCABLE = 1 # ADL_SDK_3.0/include/adl_defines.h:751
ADL_GLSYNC_PORTSTATE_IDLE = 2 # ADL_SDK_3.0/include/adl_defines.h:754
ADL_GLSYNC_PORTSTATE_INPUT = 3 # ADL_SDK_3.0/include/adl_defines.h:757
ADL_GLSYNC_PORTSTATE_OUTPUT = 4 # ADL_SDK_3.0/include/adl_defines.h:760
ADL_GLSYNC_LEDTYPE_BNC = 0 # ADL_SDK_3.0/include/adl_defines.h:768
ADL_GLSYNC_LEDTYPE_RJ45_LEFT = 0 # ADL_SDK_3.0/include/adl_defines.h:771
ADL_GLSYNC_LEDTYPE_RJ45_RIGHT = 1 # ADL_SDK_3.0/include/adl_defines.h:774
ADL_GLSYNC_LEDCOLOR_UNDEFINED = 0 # ADL_SDK_3.0/include/adl_defines.h:782
ADL_GLSYNC_LEDCOLOR_NOLIGHT = 1 # ADL_SDK_3.0/include/adl_defines.h:785
ADL_GLSYNC_LEDCOLOR_YELLOW = 2 # ADL_SDK_3.0/include/adl_defines.h:788
ADL_GLSYNC_LEDCOLOR_RED = 3 # ADL_SDK_3.0/include/adl_defines.h:791
ADL_GLSYNC_LEDCOLOR_GREEN = 4 # ADL_SDK_3.0/include/adl_defines.h:794
ADL_GLSYNC_LEDCOLOR_FLASH_GREEN = 5 # ADL_SDK_3.0/include/adl_defines.h:797
ADL_GLSYNC_PORTCNTL_NONE = 0 # ADL_SDK_3.0/include/adl_defines.h:805
ADL_GLSYNC_PORTCNTL_OUTPUT = 1 # ADL_SDK_3.0/include/adl_defines.h:808
ADL_GLSYNC_MODECNTL_NONE = 0 # ADL_SDK_3.0/include/adl_defines.h:816
ADL_GLSYNC_MODECNTL_GENLOCK = 1 # ADL_SDK_3.0/include/adl_defines.h:819
ADL_GLSYNC_MODECNTL_TIMINGSERVER = 2 # ADL_SDK_3.0/include/adl_defines.h:822
ADL_GLSYNC_MODECNTL_STATUS_NONE = 0 # ADL_SDK_3.0/include/adl_defines.h:828
ADL_GLSYNC_MODECNTL_STATUS_GENLOCK = 1 # ADL_SDK_3.0/include/adl_defines.h:831
ADL_GLSYNC_MODECNTL_STATUS_SETMODE_REQUIRED = 2 # ADL_SDK_3.0/include/adl_defines.h:834
ADL_GLSYNC_MODECNTL_STATUS_GENLOCK_ALLOWED = 4 # ADL_SDK_3.0/include/adl_defines.h:837
ADL_MAX_GLSYNC_PORTS = 8 # ADL_SDK_3.0/include/adl_defines.h:839
ADL_MAX_GLSYNC_PORT_LEDS = 8 # ADL_SDK_3.0/include/adl_defines.h:840
ADL_XFIREX_STATE_NOINTERCONNECT = 1 # ADL_SDK_3.0/include/adl_defines.h:849
ADL_XFIREX_STATE_DOWNGRADEPIPES = 2 # ADL_SDK_3.0/include/adl_defines.h:850
ADL_XFIREX_STATE_DOWNGRADEMEM = 4 # ADL_SDK_3.0/include/adl_defines.h:851
ADL_XFIREX_STATE_REVERSERECOMMENDED = 8 # ADL_SDK_3.0/include/adl_defines.h:852
ADL_XFIREX_STATE_3DACTIVE = 16 # ADL_SDK_3.0/include/adl_defines.h:853
ADL_XFIREX_STATE_MASTERONSLAVE = 32 # ADL_SDK_3.0/include/adl_defines.h:854
ADL_XFIREX_STATE_NODISPLAYCONNECT = 64 # ADL_SDK_3.0/include/adl_defines.h:855
ADL_XFIREX_STATE_NOPRIMARYVIEW = 128 # ADL_SDK_3.0/include/adl_defines.h:856
ADL_XFIREX_STATE_DOWNGRADEVISMEM = 256 # ADL_SDK_3.0/include/adl_defines.h:857
ADL_XFIREX_STATE_LESSTHAN8LANE_MASTER = 512 # ADL_SDK_3.0/include/adl_defines.h:858
ADL_XFIREX_STATE_LESSTHAN8LANE_SLAVE = 1024 # ADL_SDK_3.0/include/adl_defines.h:859
ADL_XFIREX_STATE_PEERTOPEERFAILED = 2048 # ADL_SDK_3.0/include/adl_defines.h:860
ADL_XFIREX_STATE_MEMISDOWNGRADED = 65536 # ADL_SDK_3.0/include/adl_defines.h:861
ADL_XFIREX_STATE_PIPESDOWNGRADED = 131072 # ADL_SDK_3.0/include/adl_defines.h:862
ADL_XFIREX_STATE_XFIREXACTIVE = 262144 # ADL_SDK_3.0/include/adl_defines.h:863
ADL_XFIREX_STATE_VISMEMISDOWNGRADED = 524288 # ADL_SDK_3.0/include/adl_defines.h:864
ADL_XFIREX_STATE_INVALIDINTERCONNECTION = 1048576 # ADL_SDK_3.0/include/adl_defines.h:865
ADL_XFIREX_STATE_NONP2PMODE = 2097152 # ADL_SDK_3.0/include/adl_defines.h:866
ADL_XFIREX_STATE_DOWNGRADEMEMBANKS = 4194304 # ADL_SDK_3.0/include/adl_defines.h:867
ADL_XFIREX_STATE_MEMBANKSDOWNGRADED = 8388608 # ADL_SDK_3.0/include/adl_defines.h:868
ADL_XFIREX_STATE_DUALDISPLAYSALLOWED = 16777216 # ADL_SDK_3.0/include/adl_defines.h:869
ADL_XFIREX_STATE_P2P_APERTURE_MAPPING = 33554432 # ADL_SDK_3.0/include/adl_defines.h:870
ADL_XFIREX_STATE_P2PFLUSH_REQUIRED = 33554432 # ADL_SDK_3.0/include/adl_defines.h:871
ADL_XFIREX_STATE_XSP_CONNECTED = 67108864 # ADL_SDK_3.0/include/adl_defines.h:872
ADL_XFIREX_STATE_ENABLE_CF_REBOOT_REQUIRED = 134217728 # ADL_SDK_3.0/include/adl_defines.h:873
ADL_XFIREX_STATE_DISABLE_CF_REBOOT_REQUIRED = 268435456 # ADL_SDK_3.0/include/adl_defines.h:874
ADL_XFIREX_STATE_DRV_HANDLE_DOWNGRADE_KEY = 536870912 # ADL_SDK_3.0/include/adl_defines.h:875
ADL_XFIREX_STATE_CF_RECONFIG_REQUIRED = 1073741824 # ADL_SDK_3.0/include/adl_defines.h:876
ADL_XFIREX_STATE_ERRORGETTINGSTATUS = 2147483648 # ADL_SDK_3.0/include/adl_defines.h:877
ADL_DISPLAY_PIXELFORMAT_UNKNOWN = 0 # ADL_SDK_3.0/include/adl_defines.h:897
ADL_DISPLAY_PIXELFORMAT_RGB = 1 # ADL_SDK_3.0/include/adl_defines.h:898
ADL_DISPLAY_PIXELFORMAT_YCRCB444 = 2 # ADL_SDK_3.0/include/adl_defines.h:899
ADL_DISPLAY_PIXELFORMAT_YCRCB422 = 4 # ADL_SDK_3.0/include/adl_defines.h:901
ADL_DISPLAY_PIXELFORMAT_RGB_LIMITED_RANGE = 8 # ADL_SDK_3.0/include/adl_defines.h:903
ADL_DISPLAY_PIXELFORMAT_RGB_FULL_RANGE = 1 # ADL_SDK_3.0/include/adl_defines.h:904
ADL_DL_DISPLAYCONFIG_CONTYPE_UNKNOWN = 0 # ADL_SDK_3.0/include/adl_defines.h:915
ADL_DL_DISPLAYCONFIG_CONTYPE_CV_NONI2C_JP = 1 # ADL_SDK_3.0/include/adl_defines.h:916
ADL_DL_DISPLAYCONFIG_CONTYPE_CV_JPN = 2 # ADL_SDK_3.0/include/adl_defines.h:917
ADL_DL_DISPLAYCONFIG_CONTYPE_CV_NA = 3 # ADL_SDK_3.0/include/adl_defines.h:918
ADL_DL_DISPLAYCONFIG_CONTYPE_CV_NONI2C_NA = 4 # ADL_SDK_3.0/include/adl_defines.h:919
ADL_DL_DISPLAYCONFIG_CONTYPE_VGA = 5 # ADL_SDK_3.0/include/adl_defines.h:920
ADL_DL_DISPLAYCONFIG_CONTYPE_DVI_D = 6 # ADL_SDK_3.0/include/adl_defines.h:921
ADL_DL_DISPLAYCONFIG_CONTYPE_DVI_I = 7 # ADL_SDK_3.0/include/adl_defines.h:922<|fim▁hole|>ADL_DISPLAY_DISPLAYINFO_DISPLAYMAPPED = 2 # ADL_SDK_3.0/include/adl_defines.h:945
ADL_DISPLAY_DISPLAYINFO_NONLOCAL = 4 # ADL_SDK_3.0/include/adl_defines.h:946
ADL_DISPLAY_DISPLAYINFO_FORCIBLESUPPORTED = 8 # ADL_SDK_3.0/include/adl_defines.h:947
ADL_DISPLAY_DISPLAYINFO_GENLOCKSUPPORTED = 16 # ADL_SDK_3.0/include/adl_defines.h:948
ADL_DISPLAY_DISPLAYINFO_MULTIVPU_SUPPORTED = 32 # ADL_SDK_3.0/include/adl_defines.h:949
ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_SINGLE = 256 # ADL_SDK_3.0/include/adl_defines.h:951
ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_CLONE = 512 # ADL_SDK_3.0/include/adl_defines.h:952
ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_2VSTRETCH = 1024 # ADL_SDK_3.0/include/adl_defines.h:956
ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_2HSTRETCH = 2048 # ADL_SDK_3.0/include/adl_defines.h:957
ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_EXTENDED = 4096 # ADL_SDK_3.0/include/adl_defines.h:958
ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_NSTRETCH1GPU = 65536 # ADL_SDK_3.0/include/adl_defines.h:962
ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_NSTRETCHNGPU = 131072 # ADL_SDK_3.0/include/adl_defines.h:963
ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_RESERVED2 = 262144 # ADL_SDK_3.0/include/adl_defines.h:964
ADL_DISPLAY_DISPLAYINFO_MANNER_SUPPORTED_RESERVED3 = 524288 # ADL_SDK_3.0/include/adl_defines.h:965
ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_NOTACTIVE = 1 # ADL_SDK_3.0/include/adl_defines.h:985
ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_SINGLE = 2 # ADL_SDK_3.0/include/adl_defines.h:986
ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_CLONE = 4 # ADL_SDK_3.0/include/adl_defines.h:987
ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_NSTRETCH1GPU = 8 # ADL_SDK_3.0/include/adl_defines.h:988
ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_NSTRETCHNGPU = 16 # ADL_SDK_3.0/include/adl_defines.h:989
ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_2VSTRETCH = 32 # ADL_SDK_3.0/include/adl_defines.h:993
ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_2HSTRETCH = 64 # ADL_SDK_3.0/include/adl_defines.h:994
ADL_ADAPTER_DISPLAYCAP_MANNER_SUPPORTED_EXTENDED = 128 # ADL_SDK_3.0/include/adl_defines.h:995
ADL_ADAPTER_DISPLAYCAP_PREFERDISPLAY_SUPPORTED = 256 # ADL_SDK_3.0/include/adl_defines.h:997
ADL_ADAPTER_DISPLAYCAP_BEZEL_SUPPORTED = 512 # ADL_SDK_3.0/include/adl_defines.h:998
ADL_DISPLAY_DISPLAYMAP_MANNER_RESERVED = 1 # ADL_SDK_3.0/include/adl_defines.h:1011
ADL_DISPLAY_DISPLAYMAP_MANNER_NOTACTIVE = 2 # ADL_SDK_3.0/include/adl_defines.h:1012
ADL_DISPLAY_DISPLAYMAP_MANNER_SINGLE = 4 # ADL_SDK_3.0/include/adl_defines.h:1013
ADL_DISPLAY_DISPLAYMAP_MANNER_CLONE = 8 # ADL_SDK_3.0/include/adl_defines.h:1014
ADL_DISPLAY_DISPLAYMAP_MANNER_RESERVED1 = 16 # ADL_SDK_3.0/include/adl_defines.h:1015
ADL_DISPLAY_DISPLAYMAP_MANNER_HSTRETCH = 32 # ADL_SDK_3.0/include/adl_defines.h:1017
ADL_DISPLAY_DISPLAYMAP_MANNER_VSTRETCH = 64 # ADL_SDK_3.0/include/adl_defines.h:1018
ADL_DISPLAY_DISPLAYMAP_MANNER_VLD = 128 # ADL_SDK_3.0/include/adl_defines.h:1019
ADL_DISPLAY_DISPLAYMAP_OPTION_GPUINFO = 1 # ADL_SDK_3.0/include/adl_defines.h:1034
ADL_DISPLAY_DISPLAYTARGET_PREFERRED = 1 # ADL_SDK_3.0/include/adl_defines.h:1046
ADL_DISPLAY_POSSIBLEMAPRESULT_VALID = 1 # ADL_SDK_3.0/include/adl_defines.h:1058
ADL_DISPLAY_POSSIBLEMAPRESULT_BEZELSUPPORTED = 2 # ADL_SDK_3.0/include/adl_defines.h:1059
ADL_DISPLAY_MODE_COLOURFORMAT_565 = 1 # ADL_SDK_3.0/include/adl_defines.h:1076
ADL_DISPLAY_MODE_COLOURFORMAT_8888 = 2 # ADL_SDK_3.0/include/adl_defines.h:1077
ADL_DISPLAY_MODE_ORIENTATION_SUPPORTED_000 = 4 # ADL_SDK_3.0/include/adl_defines.h:1078
ADL_DISPLAY_MODE_ORIENTATION_SUPPORTED_090 = 8 # ADL_SDK_3.0/include/adl_defines.h:1079
ADL_DISPLAY_MODE_ORIENTATION_SUPPORTED_180 = 16 # ADL_SDK_3.0/include/adl_defines.h:1080
ADL_DISPLAY_MODE_ORIENTATION_SUPPORTED_270 = 32 # ADL_SDK_3.0/include/adl_defines.h:1081
ADL_DISPLAY_MODE_REFRESHRATE_ROUNDED = 64 # ADL_SDK_3.0/include/adl_defines.h:1082
ADL_DISPLAY_MODE_REFRESHRATE_ONLY = 128 # ADL_SDK_3.0/include/adl_defines.h:1083
ADL_DISPLAY_MODE_PROGRESSIVE_FLAG = 0 # ADL_SDK_3.0/include/adl_defines.h:1085
ADL_DISPLAY_MODE_INTERLACED_FLAG = 2 # ADL_SDK_3.0/include/adl_defines.h:1086
ADL_OSMODEINFOXPOS_DEFAULT = -640 # ADL_SDK_3.0/include/adl_defines.h:1100
ADL_OSMODEINFOYPOS_DEFAULT = 0 # ADL_SDK_3.0/include/adl_defines.h:1101
ADL_OSMODEINFOXRES_DEFAULT = 640 # ADL_SDK_3.0/include/adl_defines.h:1102
ADL_OSMODEINFOYRES_DEFAULT = 480 # ADL_SDK_3.0/include/adl_defines.h:1103
ADL_OSMODEINFOXRES_DEFAULT800 = 800 # ADL_SDK_3.0/include/adl_defines.h:1104
ADL_OSMODEINFOYRES_DEFAULT600 = 600 # ADL_SDK_3.0/include/adl_defines.h:1105
ADL_OSMODEINFOREFRESHRATE_DEFAULT = 60 # ADL_SDK_3.0/include/adl_defines.h:1106
ADL_OSMODEINFOCOLOURDEPTH_DEFAULT = 8 # ADL_SDK_3.0/include/adl_defines.h:1107
ADL_OSMODEINFOCOLOURDEPTH_DEFAULT16 = 16 # ADL_SDK_3.0/include/adl_defines.h:1108
ADL_OSMODEINFOCOLOURDEPTH_DEFAULT24 = 24 # ADL_SDK_3.0/include/adl_defines.h:1109
ADL_OSMODEINFOCOLOURDEPTH_DEFAULT32 = 32 # ADL_SDK_3.0/include/adl_defines.h:1110
ADL_OSMODEINFOORIENTATION_DEFAULT = 0 # ADL_SDK_3.0/include/adl_defines.h:1111
ADL_OSMODEFLAG_DEFAULT = 0 # ADL_SDK_3.0/include/adl_defines.h:1113
ADL_I2C_MAJOR_API_REV = 1 # ADL_SDK_3.0/include/adl_defines.h:1193
ADL_I2C_MINOR_DEFAULT_API_REV = 0 # ADL_SDK_3.0/include/adl_defines.h:1194
ADL_I2C_MINOR_OEM_API_REV = 1 # ADL_SDK_3.0/include/adl_defines.h:1195
ADL_DL_I2C_LINE_OEM = 1 # ADL_SDK_3.0/include/adl_defines.h:1199
ADL_DL_I2C_LINE_OD_CONTROL = 2 # ADL_SDK_3.0/include/adl_defines.h:1200
ADL_DL_I2C_LINE_OEM2 = 3 # ADL_SDK_3.0/include/adl_defines.h:1201
ADL_DL_I2C_MAXDATASIZE = 64 # ADL_SDK_3.0/include/adl_defines.h:1205
ADL_DL_I2C_MAXWRITEDATASIZE = 12 # ADL_SDK_3.0/include/adl_defines.h:1206
ADL_DL_I2C_MAXADDRESSLENGTH = 6 # ADL_SDK_3.0/include/adl_defines.h:1207
ADL_DL_I2C_MAXOFFSETLENGTH = 4 # ADL_SDK_3.0/include/adl_defines.h:1208
ADL_DL_DISPLAYPROPERTY_TYPE_UNKNOWN = 0 # ADL_SDK_3.0/include/adl_defines.h:1213
ADL_DL_DISPLAYPROPERTY_TYPE_EXPANSIONMODE = 1 # ADL_SDK_3.0/include/adl_defines.h:1214
ADL_DL_DISPLAYPROPERTY_TYPE_USEUNDERSCANSCALING = 2 # ADL_SDK_3.0/include/adl_defines.h:1215
ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_CENTER = 0 # ADL_SDK_3.0/include/adl_defines.h:1219
ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_FULLSCREEN = 1 # ADL_SDK_3.0/include/adl_defines.h:1220
ADL_DL_DISPLAYPROPERTY_EXPANSIONMODE_ASPECTRATIO = 2 # ADL_SDK_3.0/include/adl_defines.h:1221
ADL_DL_DISPLAY_DITHER_UNKNOWN = 0 # ADL_SDK_3.0/include/adl_defines.h:1225
ADL_DL_DISPLAY_DITHER_DISABLED = 1 # ADL_SDK_3.0/include/adl_defines.h:1226
ADL_DL_DISPLAY_DITHER_ENABLED = 2 # ADL_SDK_3.0/include/adl_defines.h:1227
ADL_MAX_EDIDDATA_SIZE = 256 # ADL_SDK_3.0/include/adl_defines.h:1231
ADL_MAX_EDID_EXTENSION_BLOCKS = 3 # ADL_SDK_3.0/include/adl_defines.h:1233
ADL_DL_CONTROLLER_OVERLAY_ALPHA = 0 # ADL_SDK_3.0/include/adl_defines.h:1235
ADL_DL_CONTROLLER_OVERLAY_ALPHAPERPIX = 1 # ADL_SDK_3.0/include/adl_defines.h:1236
ADL_DL_DISPLAY_DATA_PACKET__INFO_PACKET_RESET = 0 # ADL_SDK_3.0/include/adl_defines.h:1238
ADL_DL_DISPLAY_DATA_PACKET__INFO_PACKET_SET = 1 # ADL_SDK_3.0/include/adl_defines.h:1239
ADL_DL_DISPLAY_DATA_PACKET__TYPE__AVI = 1 # ADL_SDK_3.0/include/adl_defines.h:1245
ADL_DL_DISPLAY_DATA_PACKET__TYPE__RESERVED = 2 # ADL_SDK_3.0/include/adl_defines.h:1246
ADL_DL_DISPLAY_DATA_PACKET__TYPE__VENDORINFO = 4 # ADL_SDK_3.0/include/adl_defines.h:1247
ADL_GAMUT_MATRIX_SD = 1 # ADL_SDK_3.0/include/adl_defines.h:1253
ADL_GAMUT_MATRIX_HD = 2 # ADL_SDK_3.0/include/adl_defines.h:1255
ADL_DL_CLOCKINFO_FLAG_FULLSCREEN3DONLY = 1 # ADL_SDK_3.0/include/adl_defines.h:1264
ADL_DL_CLOCKINFO_FLAG_ALWAYSFULLSCREEN3D = 2 # ADL_SDK_3.0/include/adl_defines.h:1265
ADL_DL_CLOCKINFO_FLAG_VPURECOVERYREDUCED = 4 # ADL_SDK_3.0/include/adl_defines.h:1266
ADL_DL_CLOCKINFO_FLAG_THERMALPROTECTION = 8 # ADL_SDK_3.0/include/adl_defines.h:1267
ADL_DL_POWERXPRESS_GPU_INTEGRATED = 1 # ADL_SDK_3.0/include/adl_defines.h:1275
ADL_DL_POWERXPRESS_GPU_DISCRETE = 2 # ADL_SDK_3.0/include/adl_defines.h:1276
ADL_DL_POWERXPRESS_SWITCH_RESULT_STARTED = 1 # ADL_SDK_3.0/include/adl_defines.h:1282
ADL_DL_POWERXPRESS_SWITCH_RESULT_DECLINED = 2 # ADL_SDK_3.0/include/adl_defines.h:1284
ADL_DL_POWERXPRESS_SWITCH_RESULT_ALREADY = 3 # ADL_SDK_3.0/include/adl_defines.h:1286
ADL_DL_POWERXPRESS_VERSION_MAJOR = 2 # ADL_SDK_3.0/include/adl_defines.h:1293
ADL_DL_POWERXPRESS_VERSION_MINOR = 0 # ADL_SDK_3.0/include/adl_defines.h:1295
ADL_DL_POWERXPRESS_VERSION = 131072 # ADL_SDK_3.0/include/adl_defines.h:1297
ADL_DL_THERMAL_DOMAIN_OTHER = 0 # ADL_SDK_3.0/include/adl_defines.h:1301
ADL_DL_THERMAL_DOMAIN_GPU = 1 # ADL_SDK_3.0/include/adl_defines.h:1302
ADL_DL_THERMAL_FLAG_INTERRUPT = 1 # ADL_SDK_3.0/include/adl_defines.h:1306
ADL_DL_THERMAL_FLAG_FANCONTROL = 2 # ADL_SDK_3.0/include/adl_defines.h:1307
ADL_DL_FANCTRL_SUPPORTS_PERCENT_READ = 1 # ADL_SDK_3.0/include/adl_defines.h:1315
ADL_DL_FANCTRL_SUPPORTS_PERCENT_WRITE = 2 # ADL_SDK_3.0/include/adl_defines.h:1316
ADL_DL_FANCTRL_SUPPORTS_RPM_READ = 4 # ADL_SDK_3.0/include/adl_defines.h:1317
ADL_DL_FANCTRL_SUPPORTS_RPM_WRITE = 8 # ADL_SDK_3.0/include/adl_defines.h:1318
ADL_DL_FANCTRL_SPEED_TYPE_PERCENT = 1 # ADL_SDK_3.0/include/adl_defines.h:1324
ADL_DL_FANCTRL_SPEED_TYPE_RPM = 2 # ADL_SDK_3.0/include/adl_defines.h:1325
ADL_DL_FANCTRL_FLAG_USER_DEFINED_SPEED = 1 # ADL_SDK_3.0/include/adl_defines.h:1329
ADL_DL_MAX_MVPU_ADAPTERS = 4 # ADL_SDK_3.0/include/adl_defines.h:1333
MVPU_ADAPTER_0 = 1 # ADL_SDK_3.0/include/adl_defines.h:1334
MVPU_ADAPTER_1 = 2 # ADL_SDK_3.0/include/adl_defines.h:1335
MVPU_ADAPTER_2 = 4 # ADL_SDK_3.0/include/adl_defines.h:1336
MVPU_ADAPTER_3 = 8 # ADL_SDK_3.0/include/adl_defines.h:1337
ADL_DL_MAX_REGISTRY_PATH = 256 # ADL_SDK_3.0/include/adl_defines.h:1338
ADL_DL_MVPU_STATUS_OFF = 0 # ADL_SDK_3.0/include/adl_defines.h:1342
ADL_DL_MVPU_STATUS_ON = 1 # ADL_SDK_3.0/include/adl_defines.h:1343
ADL_ASIC_UNDEFINED = 0 # ADL_SDK_3.0/include/adl_defines.h:1353
ADL_ASIC_DISCRETE = 1 # ADL_SDK_3.0/include/adl_defines.h:1354
ADL_ASIC_INTEGRATED = 2 # ADL_SDK_3.0/include/adl_defines.h:1355
ADL_ASIC_FIREGL = 4 # ADL_SDK_3.0/include/adl_defines.h:1356
ADL_ASIC_FIREMV = 8 # ADL_SDK_3.0/include/adl_defines.h:1357
ADL_ASIC_XGP = 16 # ADL_SDK_3.0/include/adl_defines.h:1358
ADL_ASIC_FUSION = 32 # ADL_SDK_3.0/include/adl_defines.h:1359
ADL_DL_TIMINGFLAG_DOUBLE_SCAN = 1 # ADL_SDK_3.0/include/adl_defines.h:1369
ADL_DL_TIMINGFLAG_INTERLACED = 2 # ADL_SDK_3.0/include/adl_defines.h:1370
ADL_DL_TIMINGFLAG_H_SYNC_POLARITY = 4 # ADL_SDK_3.0/include/adl_defines.h:1371
ADL_DL_TIMINGFLAG_V_SYNC_POLARITY = 8 # ADL_SDK_3.0/include/adl_defines.h:1372
ADL_DL_MODETIMING_STANDARD_CVT = 1 # ADL_SDK_3.0/include/adl_defines.h:1382
ADL_DL_MODETIMING_STANDARD_GTF = 2 # ADL_SDK_3.0/include/adl_defines.h:1384
ADL_DL_MODETIMING_STANDARD_DMT = 4 # ADL_SDK_3.0/include/adl_defines.h:1386
ADL_DL_MODETIMING_STANDARD_CUSTOM = 8 # ADL_SDK_3.0/include/adl_defines.h:1388
ADL_DL_MODETIMING_STANDARD_DRIVER_DEFAULT = 16 # ADL_SDK_3.0/include/adl_defines.h:1390
ADL_DL_MODETIMING_STANDARD_CVT_RB = 32
ADL_XSERVERINFO_XINERAMAACTIVE = 1 # ADL_SDK_3.0/include/adl_defines.h:1406
ADL_XSERVERINFO_RANDR12SUPPORTED = 2 # ADL_SDK_3.0/include/adl_defines.h:1412
ADL_CONTROLLERVECTOR_0 = 1 # ADL_SDK_3.0/include/adl_defines.h:1422
ADL_CONTROLLERVECTOR_1 = 2 # ADL_SDK_3.0/include/adl_defines.h:1424
ADL_DISPLAY_SLSGRID_ORIENTATION_000 = 1 # ADL_SDK_3.0/include/adl_defines.h:1427
ADL_DISPLAY_SLSGRID_ORIENTATION_090 = 2 # ADL_SDK_3.0/include/adl_defines.h:1428
ADL_DISPLAY_SLSGRID_ORIENTATION_180 = 4 # ADL_SDK_3.0/include/adl_defines.h:1429
ADL_DISPLAY_SLSGRID_ORIENTATION_270 = 8 # ADL_SDK_3.0/include/adl_defines.h:1430
ADL_DISPLAY_SLSGRID_CAP_OPTION_RELATIVETO_LANDSCAPE = 1 # ADL_SDK_3.0/include/adl_defines.h:1431
ADL_DISPLAY_SLSGRID_CAP_OPTION_RELATIVETO_CURRENTANGLE = 2 # ADL_SDK_3.0/include/adl_defines.h:1432
ADL_DISPLAY_SLSGRID_PORTAIT_MODE = 4 # ADL_SDK_3.0/include/adl_defines.h:1433
ADL_DISPLAY_SLSMAPCONFIG_GET_OPTION_RELATIVETO_LANDSCAPE = 1 # ADL_SDK_3.0/include/adl_defines.h:1436
ADL_DISPLAY_SLSMAPCONFIG_GET_OPTION_RELATIVETO_CURRENTANGLE = 2 # ADL_SDK_3.0/include/adl_defines.h:1437
ADL_DISPLAY_SLSMAPCONFIG_CREATE_OPTION_RELATIVETO_LANDSCAPE = 1 # ADL_SDK_3.0/include/adl_defines.h:1439
ADL_DISPLAY_SLSMAPCONFIG_CREATE_OPTION_RELATIVETO_CURRENTANGLE = 2 # ADL_SDK_3.0/include/adl_defines.h:1440
ADL_DISPLAY_SLSMAPCONFIG_REARRANGE_OPTION_RELATIVETO_LANDSCAPE = 1 # ADL_SDK_3.0/include/adl_defines.h:1442
ADL_DISPLAY_SLSMAPCONFIG_REARRANGE_OPTION_RELATIVETO_CURRENTANGLE = 2 # ADL_SDK_3.0/include/adl_defines.h:1443
ADL_DISPLAY_SLSGRID_RELATIVETO_LANDSCAPE = 16 # ADL_SDK_3.0/include/adl_defines.h:1446
ADL_DISPLAY_SLSGRID_RELATIVETO_CURRENTANGLE = 32 # ADL_SDK_3.0/include/adl_defines.h:1447
ADL_DISPLAY_SLSMAP_BEZELMODE = 16 # ADL_SDK_3.0/include/adl_defines.h:1452
ADL_DISPLAY_SLSMAP_DISPLAYARRANGED = 2 # ADL_SDK_3.0/include/adl_defines.h:1455
ADL_DISPLAY_SLSMAP_CURRENTCONFIG = 4 # ADL_SDK_3.0/include/adl_defines.h:1458
ADL_DISPLAY_SLSMAPINDEXLIST_OPTION_ACTIVE = 1 # ADL_SDK_3.0/include/adl_defines.h:1462
ADL_DISPLAY_BEZELOFFSET_STEPBYSTEPSET = 4 # ADL_SDK_3.0/include/adl_defines.h:1466
ADL_DISPLAY_BEZELOFFSET_COMMIT = 8 # ADL_SDK_3.0/include/adl_defines.h:1467
# http://forums.amd.com/forum/messageview.cfm?catid=347&threadid=144777
ADL_DL_I2C_LINE_OEM=0x00000001
ADL_DL_I2C_LINE_OD_CONTROL=0x00000002
ADL_DL_I2C_LINE_OEM2=0x00000003<|fim▁end|> | ADL_DL_DISPLAYCONFIG_CONTYPE_HDMI_TYPE_A = 8 # ADL_SDK_3.0/include/adl_defines.h:923
ADL_DL_DISPLAYCONFIG_CONTYPE_HDMI_TYPE_B = 9 # ADL_SDK_3.0/include/adl_defines.h:924
ADL_DL_DISPLAYCONFIG_CONTYPE_DISPLAYPORT = 10 # ADL_SDK_3.0/include/adl_defines.h:925
ADL_DISPLAY_DISPLAYINFO_DISPLAYCONNECTED = 1 # ADL_SDK_3.0/include/adl_defines.h:944 |
<|file_name|>getVariableQueryEditor.test.tsx<|end_file_name|><|fim▁begin|>import { VariableSupportType } from '@grafana/data';
import { getVariableQueryEditor, StandardVariableQueryEditor } from './getVariableQueryEditor';
import { LegacyVariableQueryEditor } from './LegacyVariableQueryEditor';
describe('getVariableQueryEditor', () => {
describe('happy cases', () => {
describe('when called with a data source with custom variable support', () => {
it('then it should return correct editor', async () => {
const editor: any = StandardVariableQueryEditor;
const datasource: any = {
variables: { getType: () => VariableSupportType.Custom, query: () => undefined, editor },
};
const result = await getVariableQueryEditor(datasource);
expect(result).toBe(editor);
});
});
describe('when called with a data source with standard variable support', () => {
it('then it should return correct editor', async () => {
const editor: any = StandardVariableQueryEditor;
const datasource: any = {
variables: { getType: () => VariableSupportType.Standard, toDataQuery: () => undefined },
};
const result = await getVariableQueryEditor(datasource);
expect(result).toBe(editor);
});
});
describe('when called with a data source with datasource variable support', () => {
it('then it should return correct editor', async () => {
const editor: any = StandardVariableQueryEditor;
const plugin = { components: { QueryEditor: editor } };
const importDataSourcePluginFunc = jest.fn().mockResolvedValue(plugin);
const datasource: any = { variables: { getType: () => VariableSupportType.Datasource }, meta: {} };
const result = await getVariableQueryEditor(datasource, importDataSourcePluginFunc);
expect(result).toBe(editor);
expect(importDataSourcePluginFunc).toHaveBeenCalledTimes(1);
expect(importDataSourcePluginFunc).toHaveBeenCalledWith({});
});
});<|fim▁hole|> const plugin = { components: { VariableQueryEditor: editor } };
const importDataSourcePluginFunc = jest.fn().mockResolvedValue(plugin);
const datasource: any = { metricFindQuery: () => undefined, meta: {} };
const result = await getVariableQueryEditor(datasource, importDataSourcePluginFunc);
expect(result).toBe(editor);
expect(importDataSourcePluginFunc).toHaveBeenCalledTimes(1);
expect(importDataSourcePluginFunc).toHaveBeenCalledWith({});
});
});
});
describe('negative cases', () => {
describe('when variable support is not recognized', () => {
it('then it should return null', async () => {
const datasource: any = {};
const result = await getVariableQueryEditor(datasource);
expect(result).toBeNull();
});
});
describe('when called with a data source with datasource variable support but missing QueryEditor', () => {
it('then it should return throw', async () => {
const plugin = { components: {} };
const importDataSourcePluginFunc = jest.fn().mockResolvedValue(plugin);
const datasource: any = { variables: { getType: () => VariableSupportType.Datasource }, meta: {} };
await expect(getVariableQueryEditor(datasource, importDataSourcePluginFunc)).rejects.toThrow(
new Error('Missing QueryEditor in plugin definition.')
);
expect(importDataSourcePluginFunc).toHaveBeenCalledTimes(1);
expect(importDataSourcePluginFunc).toHaveBeenCalledWith({});
});
});
describe('when called with a data source with legacy variable support but missing VariableQueryEditor', () => {
it('then it should return LegacyVariableQueryEditor', async () => {
const plugin = { components: {} };
const importDataSourcePluginFunc = jest.fn().mockResolvedValue(plugin);
const datasource: any = { metricFindQuery: () => undefined, meta: {} };
const result = await getVariableQueryEditor(datasource, importDataSourcePluginFunc);
expect(result).toBe(LegacyVariableQueryEditor);
expect(importDataSourcePluginFunc).toHaveBeenCalledTimes(1);
expect(importDataSourcePluginFunc).toHaveBeenCalledWith({});
});
});
});
});<|fim▁end|> |
describe('when called with a data source with legacy variable support', () => {
it('then it should return correct editor', async () => {
const editor: any = StandardVariableQueryEditor; |
<|file_name|>105c1c44ff70_login_is_not_nullabl.py<|end_file_name|><|fim▁begin|>"""login is not nullable
Revision ID: 105c1c44ff70
Revises: 2003c675a267
Create Date: 2013-12-09 10:52:50.646000
"""
# revision identifiers, used by Alembic.
revision = '105c1c44ff70'
down_revision = '2003c675a267'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.alter_column('labmanager_users', 'login',
existing_type=mysql.VARCHAR(length=50),
nullable=False)
### end Alembic commands ###
<|fim▁hole|> ### commands auto generated by Alembic - please adjust! ###
op.alter_column('labmanager_users', 'login',
existing_type=mysql.VARCHAR(length=50),
nullable=True)
### end Alembic commands ###<|fim▁end|> | def downgrade():
|
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>// Copyright 2020 TiKV Project Authors. Licensed under Apache-2.0.
//! This crate stores data types which used by other tidb query related crates.
#![feature(proc_macro_hygiene)]
#![feature(min_specialization)]
#![feature(test)]
#![feature(decl_macro)]
#![feature(str_internals)]
#[macro_use]
extern crate failure;
#[macro_use]
extern crate num_derive;
#[macro_use]
extern crate static_assertions;
#[macro_use(box_err, box_try, try_opt, error, warn)]
extern crate tikv_util;
#[macro_use]
extern crate bitflags;
#[allow(unused_extern_crates)]
extern crate tikv_alloc;
<|fim▁hole|>pub mod builder;
pub mod def;
pub mod error;
pub mod prelude {
pub use super::def::FieldTypeAccessor;
}
pub use self::def::*;
pub use self::error::*;
#[cfg(test)]
extern crate test;
pub mod codec;
pub mod expr;<|fim▁end|> | |
<|file_name|>fflat.cc<|end_file_name|><|fim▁begin|><|fim▁hole|> * 2005 Alan West <[email protected]>
*/
/* This file is part of Ragel.
*
* Ragel 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.
*
* Ragel 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 Ragel; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ragel.h"
#include "fflat.h"
#include "redfsm.h"
#include "gendata.h"
using std::endl;
namespace Go {
std::ostream &GoFFlatCodeGen::TO_STATE_ACTION( RedStateAp *state )
{
int act = 0;
if ( state->toStateAction != 0 )
act = state->toStateAction->actListId+1;
out << act;
return out;
}
std::ostream &GoFFlatCodeGen::FROM_STATE_ACTION( RedStateAp *state )
{
int act = 0;
if ( state->fromStateAction != 0 )
act = state->fromStateAction->actListId+1;
out << act;
return out;
}
std::ostream &GoFFlatCodeGen::EOF_ACTION( RedStateAp *state )
{
int act = 0;
if ( state->eofAction != 0 )
act = state->eofAction->actListId+1;
out << act;
return out;
}
/* Write out the function for a transition. */
std::ostream &GoFFlatCodeGen::TRANS_ACTION( RedTransAp *trans )
{
int action = 0;
if ( trans->action != 0 )
action = trans->action->actListId+1;
out << action;
return out;
}
/* Write out the function switch. This switch is keyed on the values
* of the func index. */
std::ostream &GoFFlatCodeGen::TO_STATE_ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numToStateRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, false, false );
}
}
genLineDirective( out );
return out;
}
/* Write out the function switch. This switch is keyed on the values
* of the func index. */
std::ostream &GoFFlatCodeGen::FROM_STATE_ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numFromStateRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, false, false );
}
}
genLineDirective( out );
return out;
}
std::ostream &GoFFlatCodeGen::EOF_ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numEofRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, true, false );
}
}
genLineDirective( out );
return out;
}
/* Write out the function switch. This switch is keyed on the values
* of the func index. */
std::ostream &GoFFlatCodeGen::ACTION_SWITCH( int level )
{
/* Loop the actions. */
for ( GenActionTableMap::Iter redAct = redFsm->actionMap; redAct.lte(); redAct++ ) {
if ( redAct->numTransRefs > 0 ) {
/* Write the entry label. */
out << TABS(level) << "case " << redAct->actListId+1 << ":" << endl;
/* Write each action in the list of action items. */
for ( GenActionTable::Iter item = redAct->key; item.lte(); item++ )
ACTION( out, item->value, 0, false, false );
}
}
genLineDirective( out );
return out;
}
void GoFFlatCodeGen::writeData()
{
if ( redFsm->anyConditions() ) {
OPEN_ARRAY( WIDE_ALPH_TYPE(), CK() );
COND_KEYS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCondSpan), CSP() );
COND_KEY_SPANS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCond), C() );
CONDS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxCondIndexOffset), CO() );
COND_INDEX_OFFSET();
CLOSE_ARRAY() <<
endl;
}
OPEN_ARRAY( WIDE_ALPH_TYPE(), K() );
KEYS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxSpan), SP() );
KEY_SPANS();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxFlatIndexOffset), IO() );
FLAT_INDEX_OFFSET();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxIndex), I() );
INDICIES();
CLOSE_ARRAY() <<
endl;
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxState), TT() );
TRANS_TARGS();
CLOSE_ARRAY() <<
endl;
if ( redFsm->anyActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActListId), TA() );
TRANS_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyToStateActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActionLoc), TSA() );
TO_STATE_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyFromStateActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActionLoc), FSA() );
FROM_STATE_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyEofActions() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxActListId), EA() );
EOF_ACTIONS();
CLOSE_ARRAY() <<
endl;
}
if ( redFsm->anyEofTrans() ) {
OPEN_ARRAY( ARRAY_TYPE(redFsm->maxIndexOffset+1), ET() );
EOF_TRANS();
CLOSE_ARRAY() <<
endl;
}
STATE_IDS();
}
void GoFFlatCodeGen::writeExec()
{
testEofUsed = false;
outLabelUsed = false;
out <<
" {" << endl <<
" var _slen " << INT() << endl;
if ( redFsm->anyRegCurStateRef() )
out << " var _ps " << INT() << endl;
out << " var _trans " << INT() << endl;
if ( redFsm->anyConditions() )
out << " var _cond " << INT() << endl;
out <<
" var _keys " << INT() << endl <<
" var _inds " << INT() << endl;
if ( redFsm->anyConditions() ) {
out <<
" var _conds " << INT() << endl <<
" var _widec " << WIDE_ALPH_TYPE() << endl;
}
if ( !noEnd ) {
testEofUsed = true;
out <<
" if " << P() << " == " << PE() << " {" << endl <<
" goto _test_eof" << endl <<
" }" << endl;
}
if ( redFsm->errState != 0 ) {
outLabelUsed = true;
out <<
" if " << vCS() << " == " << redFsm->errState->id << " {" << endl <<
" goto _out" << endl <<
" }" << endl;
}
out << "_resume:" << endl;
if ( redFsm->anyFromStateActions() ) {
out <<
" switch " << FSA() << "[" << vCS() << "] {" << endl;
FROM_STATE_ACTION_SWITCH(1);
out <<
" }" << endl <<
endl;
}
if ( redFsm->anyConditions() )
COND_TRANSLATE();
LOCATE_TRANS();
if ( redFsm->anyEofTrans() )
out << "_eof_trans:" << endl;
if ( redFsm->anyRegCurStateRef() )
out << " _ps = " << vCS() << endl;
out <<
" " << vCS() << " = " << CAST(INT(), TT() + "[_trans]") << endl <<
endl;
if ( redFsm->anyRegActions() ) {
out <<
" if " << TA() << "[_trans] == 0 {" << endl <<
" goto _again" << endl <<
" }" << endl <<
endl <<
" switch " << TA() << "[_trans] {" << endl;
ACTION_SWITCH(1);
out <<
" }" << endl <<
endl;
}
if ( redFsm->anyRegActions() || redFsm->anyActionGotos() ||
redFsm->anyActionCalls() || redFsm->anyActionRets() )
out << "_again:" << endl;
if ( redFsm->anyToStateActions() ) {
out <<
" switch " << TSA() << "[" << vCS() << "] {" << endl;
TO_STATE_ACTION_SWITCH(1);
out <<
" }" << endl <<
endl;
}
if ( redFsm->errState != 0 ) {
outLabelUsed = true;
out <<
" if " << vCS() << " == " << redFsm->errState->id << " {" << endl <<
" goto _out" << endl <<
" }" << endl;
}
if ( !noEnd ) {
out <<
" if " << P() << "++; " << P() << " != " << PE() << " {"
" goto _resume" << endl <<
" }" << endl;
}
else {
out <<
" " << P() << "++" << endl <<
" goto _resume" << endl;
}
if ( testEofUsed )
out << " _test_eof: {}" << endl;
if ( redFsm->anyEofTrans() || redFsm->anyEofActions() ) {
out <<
" if " << P() << " == " << vEOF() << " {" << endl;
if ( redFsm->anyEofTrans() ) {
out <<
" if " << ET() << "[" << vCS() << "] > 0 {" << endl <<
" _trans = " << CAST(INT(), ET() + "[" + vCS() + "] - 1") << endl <<
" goto _eof_trans" << endl <<
" }" << endl;
}
if ( redFsm->anyEofActions() ) {
out <<
" switch " << EA() << "[" << vCS() << "] {" << endl;
EOF_ACTION_SWITCH(2);
out <<
" }" << endl;
}
out <<
" }" << endl <<
endl;
}
if ( outLabelUsed )
out << " _out: {}" << endl;
out << " }" << endl;
}
}<|fim▁end|> | /*
* Copyright 2004-2006 Adrian Thurston <[email protected]>
* 2004 Erich Ocean <[email protected]> |
<|file_name|>c-style-enum.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// ignore-win32: FIXME #13256
// ignore-android: FIXME(#10381)
// compile-flags:-g
// gdb-command:rbreak zzz
// gdb-command:print 'c-style-enum::SINGLE_VARIANT'
// gdb-check:$1 = TheOnlyVariant
// gdb-command:print 'c-style-enum::AUTO_ONE'
// gdb-check:$2 = One
// gdb-command:print 'c-style-enum::AUTO_TWO'
// gdb-check:$3 = One
// gdb-command:print 'c-style-enum::AUTO_THREE'
// gdb-check:$4 = One
// gdb-command:print 'c-style-enum::MANUAL_ONE'
// gdb-check:$5 = OneHundred
// gdb-command:print 'c-style-enum::MANUAL_TWO'
// gdb-check:$6 = OneHundred
// gdb-command:print 'c-style-enum::MANUAL_THREE'
// gdb-check:$7 = OneHundred
// gdb-command:run
// gdb-command:finish
// gdb-command:print auto_one
// gdb-check:$8 = One
// gdb-command:print auto_two
// gdb-check:$9 = Two
// gdb-command:print auto_three
// gdb-check:$10 = Three
// gdb-command:print manual_one_hundred
// gdb-check:$11 = OneHundred
// gdb-command:print manual_one_thousand
// gdb-check:$12 = OneThousand
// gdb-command:print manual_one_million
// gdb-check:$13 = OneMillion
// gdb-command:print single_variant
// gdb-check:$14 = TheOnlyVariant
// gdb-command:print 'c-style-enum::AUTO_TWO'
// gdb-check:$15 = Two
// gdb-command:print 'c-style-enum::AUTO_THREE'
// gdb-check:$16 = Three
// gdb-command:print 'c-style-enum::MANUAL_TWO'
// gdb-check:$17 = OneThousand
// gdb-command:print 'c-style-enum::MANUAL_THREE'
// gdb-check:$18 = OneMillion
#![allow(unused_variable)]
#![allow(dead_code)]
enum AutoDiscriminant {
One,
Two,
Three
}
enum ManualDiscriminant {
OneHundred = 100,
OneThousand = 1000,
OneMillion = 1000000
}
enum SingleVariant {
TheOnlyVariant
}
static SINGLE_VARIANT: SingleVariant = TheOnlyVariant;
static mut AUTO_ONE: AutoDiscriminant = One;
static mut AUTO_TWO: AutoDiscriminant = One;
static mut AUTO_THREE: AutoDiscriminant = One;
<|fim▁hole|>static mut MANUAL_THREE: ManualDiscriminant = OneHundred;
fn main() {
let auto_one = One;
let auto_two = Two;
let auto_three = Three;
let manual_one_hundred = OneHundred;
let manual_one_thousand = OneThousand;
let manual_one_million = OneMillion;
let single_variant = TheOnlyVariant;
unsafe {
AUTO_TWO = Two;
AUTO_THREE = Three;
MANUAL_TWO = OneThousand;
MANUAL_THREE = OneMillion;
};
zzz();
let a = SINGLE_VARIANT;
let a = unsafe { AUTO_ONE };
let a = unsafe { MANUAL_ONE };
}
fn zzz() {()}<|fim▁end|> | static mut MANUAL_ONE: ManualDiscriminant = OneHundred;
static mut MANUAL_TWO: ManualDiscriminant = OneHundred; |
<|file_name|>ShippingRequest.java<|end_file_name|><|fim▁begin|>package in.clayfish.printful.models;
import java.io.Serializable;
import java.util.List;
import in.clayfish.printful.models.info.AddressInfo;
import in.clayfish.printful.models.info.ItemInfo;
/**
* @author shuklaalok7
* @since 24/12/2016
*/
public class ShippingRequest implements Serializable {
/**
* Recipient location information
*/
private AddressInfo recipient;
/**
* List of order items
*/
private List<ItemInfo> items;
/**
* 3 letter currency code (optional), required if the rates need to be converted to another currency instead of USD
*/
private String currency;
public AddressInfo getRecipient() {
return recipient;
}
public void setRecipient(AddressInfo recipient) {
this.recipient = recipient;
}
public List<ItemInfo> getItems() {
return items;
}
public void setItems(List<ItemInfo> items) {
this.items = items;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}<|fim▁hole|><|fim▁end|> |
} |
<|file_name|>main.py<|end_file_name|><|fim▁begin|>import json
import logging
import os
import sys
from datetime import datetime, timedelta, timezone
from signal import signal, SIGINT, SIGTERM, SIGUSR1
from typing import Optional
from apscheduler.schedulers import SchedulerNotRunningError
from dateutil.parser import isoparse as parse_iso_timestamp
from docker.models.containers import Container
from fasteners import InterProcessLock
from deck_chores import __version__, jobs
from deck_chores.config import cfg, generate_config, ConfigurationError
from deck_chores.indexes import (
container_name,
lock_service,
reassign_service_lock,
unlock_service,
service_locks_by_service_id,
service_locks_by_container_id,
)
from deck_chores.parsers import job_config_validator, parse_labels
from deck_chores.utils import DEBUG, log, setup_stderr_logging, stdout_log_handler
####
lock = InterProcessLock('/tmp/deck-chores.lock')
def there_is_another_deck_chores_container() -> bool:
matched_containers = 0
for container in cfg.client.containers.list(ignore_removed=True, sparse=True):
if container.image.labels.get('org.label-schema.name', '') == 'deck-chores':
matched_containers += 1
if matched_containers > 1:
return True
return False
####
def sigint_handler(signum, frame): # pragma: nocover
log.info("Keyboard interrupt.")
raise SystemExit(0)
def sigterm_handler(signum, frame): # pragma: nocover
log.info("Received SIGTERM.")
raise SystemExit(0)
def sigusr1_handler(signum, frame):
log.info("SIGUSR1 received, echoing all jobs.")
for job in jobs.scheduler.get_jobs():
log.info(f"ID: {job.id} Next execution: {job.next_run_time} Configuration:")
log.info(job.kwargs)
signal(SIGINT, sigint_handler)
signal(SIGTERM, sigterm_handler)
signal(SIGUSR1, sigusr1_handler)
####
def process_started_container_labels(container_id: str, paused: bool = False) -> None:
service_id, flags, definitions = parse_labels(container_id)
if not definitions:
return
if service_id and 'service' in flags:
other_container_id = service_locks_by_service_id.get(service_id)
if other_container_id:
log.debug(
f'Service id {service_id} is locked by container {other_container_id}.'
)
if cfg.client.containers.get(other_container_id).status == "paused":
assert reassign_jobs(other_container_id, consider_paused=False)
return
lock_service(service_id, container_id)
jobs.add(container_id, definitions, paused=paused)
def inspect_running_containers() -> datetime:
log.info("Inspecting running containers.")
last_event_time = datetime.now(timezone.utc)
containers = cfg.client.containers.list(ignore_removed=True, sparse=True)
for container in containers:
container_id = container.id
last_event_time = max(
last_event_time,
parse_iso_timestamp(
cfg.client.api.inspect_container(container_id)['State']['StartedAt']
),
)
process_started_container_labels(
container_id, paused=container.status == 'paused'
)
log.debug('Finished inspection of running containers.')
# the timezone info is removed here, because the object will be fed to docker-py
# (version 4.4.4 at the time of writing) which cannot process timezone aware
# datetime objects
return last_event_time.replace(tzinfo=None)
def reassign_jobs(container_id: str, consider_paused: bool) -> Optional[str]:
other_service_container = find_other_container_for_service(
container_id, consider_paused
)
if other_service_container is None:
return None
new_id = other_service_container.id
container_is_paused = other_service_container.status == "paused"
log.info(f"{container_name(container_id)}: Reassigning jobs to {new_id}.")
for job in jobs.get_jobs_for_container(container_id):
log.debug(f"Handling job: {job.kwargs}")
job_is_paused = not bool(job.next_run_time)
if container_is_paused and not job_is_paused:
job.pause()
log.debug("Paused job.")
elif not container_is_paused and job_is_paused:
job.resume()
log.debug("Resumed job.")
job.modify(kwargs={**job.kwargs, "container_id": new_id})
reassign_service_lock(container_id, new_id)
return new_id
def find_other_container_for_service(
container_id: str, consider_paused: bool
) -> Optional[Container]:
service_id = service_locks_by_container_id.get(container_id)
if service_id is None:
return None
for status in (
("running", "restarting", "paused", "created")
if consider_paused
else ("running", "restarting")
):
candidates = [
c
for c in cfg.client.containers.list(
all=True,
ignore_removed=True,
# TODO don't cast service_id to list when this patch is incorporated:
# https://github.com/docker/docker-py/pull/2445
filters={"status": status, "label": list(service_id)},
)
if c.id != container_id
]
if len(candidates):
return candidates[0]
return None
####
def listen(since: datetime) -> None:
log.info("Listening to events.")
for event_json in cfg.client.events(since=since):
if b'container' not in event_json:
continue
if not any((x in event_json) for x in (b'start', b'die', b'pause', b'unpause')):
continue
event = json.loads(event_json)
log.debug(f'Daemon event: {event}')
if event['Type'] != 'container':
continue
<|fim▁hole|> action = event['Action']
if action == 'start':
handle_start(event)
elif action == 'die':
handle_die(event)
elif action == 'pause':
handle_pause(event)
elif action == 'unpause':
handle_unpause(event)
def handle_start(event: dict):
container_id = event['Actor']['ID']
log.debug(f'Handling start of {container_id}.')
process_started_container_labels(container_id, paused=False)
def handle_die(event: dict):
container_id = event['Actor']['ID']
log.debug(f'Handling die of {container_id}.')
if reassign_jobs(container_id, consider_paused=True) is None:
for job in jobs.get_jobs_for_container(container_id):
definition = job.kwargs
log.debug(f"Removing job: {definition}")
job.remove()
log.info(
f"{container_name(container_id)}: Removed '"
+ definition["job_name"]
+ "'."
)
unlock_service(container_id)
def handle_pause(event: dict):
container_id = event['Actor']['ID']
log.debug(f'Handling pause of {container_id}.')
if reassign_jobs(container_id, consider_paused=False) is None:
counter = 0
for counter, job in enumerate(
jobs.get_jobs_for_container(container_id), start=1
):
job.pause()
log.debug(f"Paused job: {job.kwargs}")
if counter:
log.info(f"{container_name(container_id)}: Paused {counter} jobs.")
def handle_unpause(event: dict):
container_id = event['Actor']['ID']
log.debug(f'Handling unpause of {container_id}.')
if container_id not in service_locks_by_container_id:
service_id, _, _ = parse_labels(container_id)
if service_id:
other_container_id = service_locks_by_service_id.get(service_id)
if (
other_container_id is not None
and cfg.client.containers.get(other_container_id).status == "paused"
):
container_id = reassign_jobs(other_container_id, consider_paused=False)
counter = 0
for counter, job in enumerate(jobs.get_jobs_for_container(container_id), start=1):
job.resume()
log.debug(f"Resumed job: {job.kwargs}")
if counter:
log.info(f"{container_name(container_id)}: Resumed {counter} jobs.")
def shutdown() -> None: # pragma: nocover
try:
jobs.scheduler.shutdown()
except SchedulerNotRunningError:
pass
if hasattr(cfg, "client"):
cfg.client.close()
####
def main() -> None: # pragma: nocover
if DEBUG and not __debug__:
log.debug("Replacing process with Python's optimizations off.")
sys.stdout.flush()
os.execlpe("deck-chores", "deck-chores", {**os.environ, "PYTHONOPTIMIZE": "1"})
if not lock.acquire(blocking=False):
log.error(f"Couldn't acquire lock file at {lock.path}, exiting.")
sys.exit(1)
log.info(f'Deck Chores {__version__} started.')
try:
generate_config()
log_formatter = logging.Formatter(cfg.logformat, style='{')
stdout_log_handler.setFormatter(log_formatter)
setup_stderr_logging(log_formatter, cfg.stderr_level)
log.debug(f'Config: {cfg.__dict__}')
if there_is_another_deck_chores_container():
log.error(
"There's another container running deck-chores, maybe paused or "
"restarting."
)
raise SystemExit(1)
job_config_validator.set_defaults(cfg)
last_event_time = inspect_running_containers()
jobs.start_scheduler()
listen(since=last_event_time + timedelta(microseconds=1))
except SystemExit as e:
exit_code = e.code
except ConfigurationError as e:
log.error(e)
exit_code = 1
except Exception:
log.exception('Caught an unhandled exception:')
exit_code = 3
else:
exit_code = 0
finally:
shutdown()
lock.release()
sys.exit(exit_code)
if __name__ == '__main__':
main()<|fim▁end|> | |
<|file_name|>htmltitleelement.rs<|end_file_name|><|fim▁begin|>/* 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/. */
use dom::bindings::codegen::Bindings::HTMLTitleElementBinding;
use dom::bindings::codegen::Bindings::HTMLTitleElementBinding::HTMLTitleElementMethods;
use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods;
use dom::bindings::codegen::InheritTypes::{HTMLElementCast, HTMLTitleElementDerived, NodeCast};
use dom::bindings::codegen::InheritTypes::{TextCast};
use dom::bindings::js::{JSRef, Temporary};
use dom::document::{Document, DocumentHelpers};
use dom::eventtarget::{EventTarget, EventTargetTypeId};
use dom::element::ElementTypeId;
use dom::htmlelement::{HTMLElement, HTMLElementTypeId};
use dom::node::{Node, NodeHelpers, NodeTypeId};
use dom::text::Text;
use dom::virtualmethods::VirtualMethods;
use util::str::DOMString;
#[dom_struct]
pub struct HTMLTitleElement {<|fim▁hole|>}
impl HTMLTitleElementDerived for EventTarget {
fn is_htmltitleelement(&self) -> bool {
*self.type_id() == EventTargetTypeId::Node(NodeTypeId::Element(ElementTypeId::HTMLElement(HTMLElementTypeId::HTMLTitleElement)))
}
}
impl HTMLTitleElement {
fn new_inherited(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> HTMLTitleElement {
HTMLTitleElement {
htmlelement: HTMLElement::new_inherited(HTMLElementTypeId::HTMLTitleElement, localName, prefix, document)
}
}
#[allow(unrooted_must_root)]
pub fn new(localName: DOMString, prefix: Option<DOMString>, document: JSRef<Document>) -> Temporary<HTMLTitleElement> {
let element = HTMLTitleElement::new_inherited(localName, prefix, document);
Node::reflect_node(box element, document, HTMLTitleElementBinding::Wrap)
}
}
impl<'a> HTMLTitleElementMethods for JSRef<'a, HTMLTitleElement> {
// http://www.whatwg.org/html/#dom-title-text
fn Text(self) -> DOMString {
let node: JSRef<Node> = NodeCast::from_ref(self);
let mut content = String::new();
for child in node.children() {
let text: Option<JSRef<Text>> = TextCast::to_ref(child);
match text {
Some(text) => content.push_str(text.characterdata().data().as_slice()),
None => (),
}
}
content
}
// http://www.whatwg.org/html/#dom-title-text
fn SetText(self, value: DOMString) {
let node: JSRef<Node> = NodeCast::from_ref(self);
node.SetTextContent(Some(value))
}
}
impl<'a> VirtualMethods for JSRef<'a, HTMLTitleElement> {
fn super_type<'b>(&'b self) -> Option<&'b VirtualMethods> {
let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_borrowed_ref(self);
Some(htmlelement as &VirtualMethods)
}
fn bind_to_tree(&self, is_in_doc: bool) {
let node: JSRef<Node> = NodeCast::from_ref(*self);
if is_in_doc {
let document = node.owner_doc().root();
document.r().send_title_to_compositor()
}
}
}<|fim▁end|> | htmlelement: HTMLElement, |
<|file_name|>config.py<|end_file_name|><|fim▁begin|>#
# This is the configuration file for the RPi environd
#
### Presentation - General
# All datetime stamps use typical strftime codes: https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
# The date/time stamp of the last (most current) reading.
present_lastread_stamp = "%I:%M %p on %A, %b %d"
# How many decimal places to round to when displaying temperatures. For
# presentation only - does not impact reading precision in the database.
present_temp_precision = 1
### Presentation - Recent Graph
<|fim▁hole|>present_graph_recent_x = "%I:%M %p"
# How many data points to use.
# This does _not_ reflect how many points will be drawn. Also consider how
# often the readings are made - e.g., if a value is recorded every 15 minutes,
# then a full day's worth of data requires 24x(60/15) = 96 points.
present_recent_point_count = 720
# How much to reduce the specified number of data points.
# This is how many points will be drawn. The value of
# present_recent_point_count is divided in to this many chunks, and then time
# stamp and value of each chunk is averaged.
present_recent_reduce_to = 16
### Presentation - All Time Graph
# < tbd... not implemented yet >
### Files
# The static html file that is output. Must be writable by the user running
# environd. Presumably this is in the www directory of a web server.
www_out = "/var/www/environd.html"
# The template to use for generating static html.
# Must be readable by the user running environd.
html_template = "/opt/environd/template/environd.tpl"
# The (flat text) database file.
# Must be writable by the user running environd, and must exist, even if empty.
database = "/opt/environd/database/temperature_readings.json"
# The log file. Must be writable by the user running environd.
log_file = "/var/log/environd.log"
# Format of the timestamping used internally.
# Does not impact presentation unless presented values are omitted.
datetime_func_format = "%Y%m%dT%H%M%S"
### Tinker/Debug
# Set to True to print all log messages to the terminal, or False to suppress
# most output.
terminal_verbosity = True
# The size in mb after which the db file is rotated.
# The entire db is loaded in to memory, but each reading is a mere 60-80
# bytes, so 100 megs is about 10 years of recording every 15 minutes.
max_db_file_size = 100 # mb<|fim▁end|> | # The date/time stamp on the x-axis |
<|file_name|>JsonRawProvider.java<|end_file_name|><|fim▁begin|>package com.devicehive.client.impl.rest.providers;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.devicehive.client.impl.Constants;
import com.devicehive.client.impl.json.GsonFactory;
import com.devicehive.client.impl.util.Messages;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
/**
* Provider that converts hive entity to JSON and JSON to hive entity
*/
@Provider
public class JsonRawProvider implements MessageBodyWriter<JsonObject>, MessageBodyReader<JsonObject> {
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return MediaType.APPLICATION_JSON_TYPE.getType().equals(mediaType.getType()) && MediaType<|fim▁hole|> .APPLICATION_JSON_TYPE.getSubtype().equals(mediaType.getSubtype());
}
@Override
public JsonObject readFrom(Class<JsonObject> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
JsonElement element = new JsonParser().parse(new InputStreamReader(entityStream,
Charset.forName(Constants.CURRENT_CHARSET)));
if (element.isJsonObject()) {
return element.getAsJsonObject();
}
throw new IOException(Messages.NOT_A_JSON);
}
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return MediaType.APPLICATION_JSON_TYPE.getType().equals(mediaType.getType()) && MediaType
.APPLICATION_JSON_TYPE.getSubtype().equals(mediaType.getSubtype());
}
@Override
public long getSize(JsonObject jsonObject, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType) {
return 0;
}
@Override
public void writeTo(JsonObject jsonObject, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
Gson gson = GsonFactory.createGson();
Writer writer = null;
try {
writer = new OutputStreamWriter(entityStream, Charset.forName(Constants.CURRENT_CHARSET));
gson.toJson(jsonObject, writer);
} finally {
if (writer != null) {
writer.flush();
}
}
}
}<|fim▁end|> | |
<|file_name|>jasmine-this.test.ts<|end_file_name|><|fim▁begin|>/* eslint-env jest */
import chalk from 'chalk'
import { wrapPlugin } from '../utils/test-helpers'
import plugin from './jasmine-this'
chalk.level = 0
const wrappedPlugin = wrapPlugin(plugin)
function expectTransformation(source, expectedOutput, options = {}) {
const result = wrappedPlugin(source, options)
expect(result).toBe(expectedOutput)
}
test('transforms simple cases', () => {
expectTransformation(
`
describe('foo', function() {
beforeEach(function() {
this.foo = { id: 'FOO' };
this.bar = { id: 'BAR', child: this.foo };
});
it('should have proper IDs', function() {
expect(this.foo.id).to.equal('FOO');
expect(this.bar.id).to.equal('BAR');
expect(this.bar.child.id).to.equal('FOO');
});
});
`,
`
describe('foo', () => {
let testContext;
beforeEach(() => {
testContext = {};
});
beforeEach(() => {
testContext.foo = { id: 'FOO' };
testContext.bar = { id: 'BAR', child: testContext.foo };
});
it('should have proper IDs', () => {
expect(testContext.foo.id).to.equal('FOO');
expect(testContext.bar.id).to.equal('BAR');
expect(testContext.bar.child.id).to.equal('FOO');
});
});
`
)
})
test('does not transform generator functions', () => {
expectTransformation(
`
describe('foo', function*() {
beforeEach(function*() {
this.foo = { id: 'FOO' };
this.bar = { id: 'BAR', child: this.foo };
});
it('should have proper IDs', function*() {
expect(this.foo.id).to.equal('FOO');
expect(this.bar.id).to.equal('BAR');
expect(this.bar.child.id).to.equal('FOO');
});
});
`,
`
describe('foo', function*() {
let testContext;
beforeEach(() => {
testContext = {};
});
beforeEach(function*() {
testContext.foo = { id: 'FOO' };
testContext.bar = { id: 'BAR', child: testContext.foo };
});
it('should have proper IDs', function*() {
expect(testContext.foo.id).to.equal('FOO');
expect(testContext.bar.id).to.equal('BAR');
expect(testContext.bar.child.id).to.equal('FOO');
});
});
`
)
})
test('transforms only test functions context', () => {
expectTransformation(
`
describe('foo', function() {
const MockClass = function(options) {
this.options = options;
this.stop = sinon.spy();
};
MockClass.prototype.run = function() {
return this.options.path;
}
beforeEach(function() {
this.path = '/foo';
this.mocked = new MockClass({
limit: 123,
});
});
afterEach(function() {
this.mocked.stop();
});
it('should run with context data', function() {
this.mocked.run({ path: this.path });
});
});
describe('bar', function () {
describe('ham', function () {
const View = Marionette.ItemView.extend({
initialize: function (options) {
this.selected = options.selected;
}
});
});
});
`,
`
describe('foo', () => {
let testContext;
beforeEach(() => {
testContext = {};
});
const MockClass = function(options) {
this.options = options;
this.stop = sinon.spy();
};
MockClass.prototype.run = function() {
return this.options.path;
}
beforeEach(() => {
testContext.path = '/foo';
testContext.mocked = new MockClass({
limit: 123,
});
});
afterEach(() => {
testContext.mocked.stop();
});
it('should run with context data', () => {
testContext.mocked.run({ path: testContext.path });
});
});
describe('bar', () => {
describe('ham', () => {
const View = Marionette.ItemView.extend({
initialize: function (options) {
this.selected = options.selected;
}
});
});
});
`
)
})
test('transforms nested describes', () => {
expectTransformation(
`
describe('foo', function() {
beforeEach(function() {
this.foo = { id: 'FOO' };
this.bar = { id: 'BAR' };
});
describe('inner foo', function() {
beforeEach(function() {
this.foo = { id: 'OOF' };
this.ham = { id: 'HAM' };
});
it('should have proper IDs', function() {
const foo = this.foo;
expect(foo.id).to.equal('OOF');
expect(this.bar.id).to.equal('BAR');
expect(this.ham.id).to.equal('HAM');
});
});
});
`,
`
describe('foo', () => {
let testContext;
beforeEach(() => {
testContext = {};
});
beforeEach(() => {
testContext.foo = { id: 'FOO' };
testContext.bar = { id: 'BAR' };
});
describe('inner foo', () => {
beforeEach(() => {
testContext.foo = { id: 'OOF' };
testContext.ham = { id: 'HAM' };
});
it('should have proper IDs', () => {
const foo = testContext.foo;
expect(foo.id).to.equal('OOF');
expect(testContext.bar.id).to.equal('BAR');
expect(testContext.ham.id).to.equal('HAM');
});
});
});
`
)
})
test('transforms plain functions within lifecycle methods', () => {
expectTransformation(
`
describe('foo', function() {
beforeEach(function() {
this.foo = { id: 'FOO' };
this.action = function() {
return this.foo;
};
this.instance = {
action: function() {
this.bar = 123;
},
other: sinon.spy(function() {
this.bar = 456;
}),
};
});
test('should have proper IDs', function() {
class Container extends Component {
constructor() {
super();
this.state = 123;
}
}
expect(this.foo.id).to.equal('FOO');
expect(this.action().id).to.equal('FOO');
this.instance.action();
this.instance.other();
});
});
`,
`
describe('foo', () => {
let testContext;
beforeEach(() => {
testContext = {};
});
beforeEach(() => {
testContext.foo = { id: 'FOO' };
testContext.action = function() {
return testContext.foo;
};
testContext.instance = {
action: function() {
this.bar = 123;
},
other: sinon.spy(function() {
this.bar = 456;
}),
};
});
test('should have proper IDs', () => {
class Container extends Component {
constructor() {
super();
this.state = 123;
}
}
expect(testContext.foo.id).to.equal('FOO');
expect(testContext.action().id).to.equal('FOO');
testContext.instance.action();
testContext.instance.other();
});
});
`
)
})
test('transforms context within arrow functions', () => {
expectTransformation(
`
describe('foo', () => {
beforeEach(function() {
this.foo = { id: 'FOO' };
});
it('should have proper IDs', function() {
expect(this.foo.id).to.equal('FOO');
});
});
`,
`
describe('foo', () => {
let testContext;
beforeEach(() => {
testContext = {};
});
beforeEach(() => {
testContext.foo = { id: 'FOO' };
});
it('should have proper IDs', () => {
expect(testContext.foo.id).to.equal('FOO');
});
});
`
)
})
test('transforms context within async functions', () => {
expectTransformation(
`
describe('foo', function () {
beforeEach(async function() {
this.foo = await globalPromise();
});
it('should have proper IDs', async function() {
await otherPromise();
expect(this.foo).to.equal('FOO');
});
});
`,
`
describe('foo', () => {
let testContext;
beforeEach(() => {
testContext = {};
});
beforeEach(async () => {
testContext.foo = await globalPromise();
});
it('should have proper IDs', async () => {
await otherPromise();
expect(testContext.foo).to.equal('FOO');
});
});
`
)
})
test('original issue example', () => {
expectTransformation(
`
beforeEach(function () {
this.hello = 'hi';
});
afterEach(function () {
console.log(this.hello);
});
describe('context', () => {
it('should work', function () {
console.log(this.hello);
});
});
`,
`
let testContext;
beforeEach(() => {
testContext = {};
});
beforeEach(() => {
testContext.hello = 'hi';
});
afterEach(() => {
console.log(testContext.hello);
});
describe('context', () => {
it('should work', () => {
console.log(testContext.hello);
});
});
`
)
})
test('transforms before blocks', () => {
expectTransformation(
`
beforeAll(function () {
this.hello = 'hi';
});
beforeEach(function () {
this.goodbye = 'bye';
});
afterEach(function () {
console.log(this.hello);
console.log(this.goodbye);
});
describe('context', () => {
it('should work', function () {
console.log(this.hello);
console.log(this.goodbye);
});
});
`,
`
let testContext;
beforeAll(() => {
testContext = {};
});
beforeAll(() => {
testContext.hello = 'hi';
});
beforeEach(() => {
testContext.goodbye = 'bye';
});
afterEach(() => {
console.log(testContext.hello);
console.log(testContext.goodbye);
});
describe('context', () => {
it('should work', () => {
console.log(testContext.hello);
console.log(testContext.goodbye);
});
});
`
)
})
test('does not transform mocha specific methods', () => {
expectTransformation(
`
describe('foo', function () {
it('should keep mocha methods', function() {
this.timeout(500);
this.slow(100);
this.retries(2);
this.skip();
});
});
`,
`
describe('foo', () => {
it('should keep mocha methods', () => {<|fim▁hole|> });
});
`
)
})
test('ignores a function in an array', () => {
expectTransformation(
`
describe('foo', function() {
it('should tolerate an array of functions', function() {
foo.apply(model, [
function() {
bar();
}
]);
});
});
`,
`
describe('foo', () => {
it('should tolerate an array of functions', () => {
foo.apply(model, [
function() {
bar();
}
]);
});
});
`
)
})
test('adds any type to the test context with typescript (tsx)', () => {
expectTransformation(
`
beforeEach(function () {
this.hello = 'hi';
});
afterEach(function () {
console.log(this.hello);
});
describe('context', () => {
it('should work', function () {
console.log(this.hello);
});
});
`,
`
let testContext: any;
beforeEach(() => {
testContext = {};
});
beforeEach(() => {
testContext.hello = 'hi';
});
afterEach(() => {
console.log(testContext.hello);
});
describe('context', () => {
it('should work', () => {
console.log(testContext.hello);
});
});
`,
{ parser: 'tsx' }
)
})
test('adds any type to the test context with typescript (ts)', () => {
expectTransformation(
`
beforeEach(function () {
this.hello = 'hi';
});
afterEach(function () {
console.log(this.hello);
});
describe('context', () => {
it('should work', function () {
console.log(this.hello);
});
});
`,
`
let testContext: any;
beforeEach(() => {
testContext = {};
});
beforeEach(() => {
testContext.hello = 'hi';
});
afterEach(() => {
console.log(testContext.hello);
});
describe('context', () => {
it('should work', () => {
console.log(testContext.hello);
});
});
`,
{ parser: 'ts' }
)
})<|fim▁end|> | this.timeout(500);
this.slow(100);
this.retries(2);
this.skip(); |
<|file_name|>layout_optimizer_test.py<|end_file_name|><|fim▁begin|># Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for Grappler LayoutOptimizer."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.core.protobuf import config_pb2
from tensorflow.core.protobuf import device_properties_pb2
from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.core.protobuf import saver_pb2
from tensorflow.python.client import session
from tensorflow.python.compat import compat
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from tensorflow.python.framework import random_seed
from tensorflow.python.framework import test_util
from tensorflow.python.grappler import cluster as gcluster
from tensorflow.python.grappler import tf_optimizer
from tensorflow.python.layers import convolutional as conv_layers
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import gen_nn_ops
from tensorflow.python.ops import map_fn
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test
from tensorflow.python.training import gradient_descent
from tensorflow.python.training import saver as saver_lib
def _weight(shape):
"""Generates a weight of a given shape."""
return random_ops.truncated_normal(shape, seed=0, stddev=0.1)
def _bias(shape):
"""Generates a bias of a given shape."""
return constant_op.constant(0.1, shape=shape)
def _conv2d(x, w):
"""Returns a 2d convolution layer with full stride."""
return nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')
def _max_pool_2x2(x):
"""Downsamples a feature map by 2X."""
return nn.max_pool(
x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
# Taken from tensorflow/examples/tutorials/mnist/mnist_deep.py
def _two_layer_model(x):
x_image = array_ops.reshape(x, [-1, 28, 28, 1])
w_conv1 = _weight([5, 5, 1, 32])
b_conv1 = _bias([32])
h_conv1 = nn.relu(_conv2d(x_image, w_conv1) + b_conv1)
h_pool1 = _max_pool_2x2(h_conv1)
w_conv2 = _weight([5, 5, 32, 64])
b_conv2 = _bias([64])
h_conv2 = nn.relu(_conv2d(h_pool1, w_conv2) + b_conv2)
h_pool2 = _max_pool_2x2(h_conv2)
return h_pool2
def _model_with_second_port():
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([2, 5, 5, 4], seed=0)
scale = constant_op.constant(0.1, shape=[4])
offset = constant_op.constant(0.3, shape=[4])
y, mean, _ = nn.fused_batch_norm(x, scale, offset)
mul = math_ops.add(y, mean)
output = array_ops.identity(mul)
return output
def _model_with_branch(x):
x_image = array_ops.reshape(x, [-1, 28, 28, 1])
w_conv1 = _weight([5, 5, 1, 32])
w_conv2 = _weight([5, 5, 1, 32])
c_conv1 = _conv2d(x_image, w_conv1)
c_conv2 = _conv2d(x_image, w_conv2)
add = math_ops.add(c_conv1, c_conv2)
return add
def _model_with_vec_and_4d(x):
x_image = array_ops.reshape(x, [-1, 28, 28, 1])
w_conv1 = _weight([5, 5, 1, 32])
c_conv1 = _conv2d(x_image, w_conv1)
vector = constant_op.constant(6.4, shape=[32])
add = math_ops.add(c_conv1, vector)
return add
def _loop():
random_seed.set_random_seed(0)
x1 = random_ops.truncated_normal([1, 784], seed=0)
x2 = random_ops.truncated_normal([1, 784], seed=0)
x3 = random_ops.truncated_normal([1, 784], seed=0)
x4 = random_ops.truncated_normal([1, 784], seed=0)
elems = (x1, x2, x3, x4)
outputs = map_fn.map_fn(_two_layer_model, elems, dtype=dtypes.float32)
return outputs
def _loop_with_branch():
random_seed.set_random_seed(0)
x1 = random_ops.truncated_normal([1, 784], seed=0)
x2 = random_ops.truncated_normal([1, 784], seed=0)
x3 = random_ops.truncated_normal([1, 784], seed=0)
x4 = random_ops.truncated_normal([1, 784], seed=0)
elems = (x1, x2, x3, x4)
outputs = map_fn.map_fn(_model_with_branch, elems, dtype=dtypes.float32)
return outputs
def _loop_with_vec_and_4d():
random_seed.set_random_seed(0)
x1 = random_ops.truncated_normal([1, 784], seed=0)
x2 = random_ops.truncated_normal([1, 784], seed=0)
x3 = random_ops.truncated_normal([1, 784], seed=0)
x4 = random_ops.truncated_normal([1, 784], seed=0)
elems = (x1, x2, x3, x4)
outputs = map_fn.map_fn(_model_with_vec_and_4d, elems, dtype=dtypes.float32)
return outputs
def _get_config(layout_optimizer=True):
if layout_optimizer:
rewrite_options = rewriter_config_pb2.RewriterConfig(
layout_optimizer=rewriter_config_pb2.RewriterConfig.ON,
# do not remove duplicated nodes
arithmetic_optimization=rewriter_config_pb2.RewriterConfig.OFF)
else:
rewrite_options = rewriter_config_pb2.RewriterConfig(
layout_optimizer=rewriter_config_pb2.RewriterConfig.OFF,
# do not remove duplicated nodes
arithmetic_optimization=rewriter_config_pb2.RewriterConfig.OFF)
rewrite_options.min_graph_nodes = -1
graph_options = config_pb2.GraphOptions(
rewrite_options=rewrite_options, build_cost_model=1)
config = config_pb2.ConfigProto(graph_options=graph_options)
config.graph_options.optimizer_options.opt_level = -1
return config
def _simple_metagraph(depthwise=False):
random_seed.set_random_seed(0)
x = variables.Variable(random_ops.truncated_normal([1, 200, 200, 3], seed=0))
conv = conv_layers.separable_conv2d if depthwise else conv_layers.conv2d
y = conv(x, 32, [3, 3])
z = conv(y, 32, [3, 3])
optimizer = gradient_descent.GradientDescentOptimizer(1e-4)
loss = math_ops.reduce_mean(z)
train_op = optimizer.minimize(loss)
graph = ops.get_default_graph()
graph.add_to_collection('train_op', train_op)
meta_graph = saver_lib.export_meta_graph(graph_def=graph.as_graph_def())
return meta_graph
def _get_cluster():
named_device = device_properties_pb2.NamedDevice()
named_device.name = '/GPU:0'
named_device.properties.type = 'GPU'
named_device.properties.num_cores = 24
named_device.properties.frequency = 1000
named_device.properties.environment['architecture'] = '4'
cluster = gcluster.Cluster(devices=[named_device])
return cluster
def _is_transpose(node):
return node.endswith('TransposeNHWCToNCHW-LayoutOptimizer') or node.endswith(
'TransposeNCHWToNHWC-LayoutOptimizer')
def _is_permute(node):
return node.endswith('VecPermuteNHWCToNCHW-LayoutOptimizer') or node.endswith(
'VecPermuteNCHWToNHWC-LayoutOptimizer')
@test_util.for_all_test_methods(test_util.no_xla_auto_jit,
'Test does not apply in XLA setting')
class LayoutOptimizerTest(test.TestCase):
"""Tests the Grappler layout optimizer."""
def _assert_trans_nchw_to_nhwc(self, name, nodes):
self.assertIn(name + '-TransposeNCHWToNHWC-LayoutOptimizer', nodes)
def _assert_trans_nhwc_to_nchw(self, name, nodes):
self.assertIn(name + '-TransposeNHWCToNCHW-LayoutOptimizer', nodes)
def _assert_map_nhwc_to_nchw(self, name, nodes):
self.assertIn(name + '-DimMapNHWCToNCHW-LayoutOptimizer', nodes)
def _assert_vec_nchw_to_nhwc(self, name, nodes):
self.assertIn(name + '-VecPermuteNCHWToNHWC-LayoutOptimizer', nodes)
def _assert_vec_nhwc_to_nchw(self, name, nodes):
self.assertIn(name + '-VecPermuteNHWCToNCHW-LayoutOptimizer', nodes)
def _train(self, checkpoint_path, layout_optimizer=False, restore=False):
ops.reset_default_graph()
graph = ops.get_default_graph()
with session.Session(
config=_get_config(layout_optimizer), graph=graph) as sess:
batch = 2
height = 6
width = 7
input_channels = 3
shape = [batch, height, width, input_channels]
image = array_ops.placeholder(dtype='float32', shape=shape)
conv1 = conv_layers.conv2d(image, 32, [3, 3])
conv2 = conv_layers.conv2d(conv1, 32, [3, 3])
optimizer = gradient_descent.GradientDescentOptimizer(0.01)
loss = math_ops.reduce_mean(conv2)
train_op = optimizer.minimize(loss)
saver = saver_lib.Saver(write_version=saver_pb2.SaverDef.V2)
if restore:
saver.restore(sess, checkpoint_path)
else:
self.evaluate(variables.global_variables_initializer())
np.random.seed(0)
for _ in range(2):
image_val = np.random.rand(*shape).astype(np.float32)
sess.run([loss, train_op], feed_dict={image: image_val})
if restore:
all_vars = ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES)
all_vars_values = [var.eval(session=sess) for var in all_vars]
return all_vars_values
else:
saver.save(sess, checkpoint_path)
@test_util.deprecated_graph_mode_only
def testTwoConvLayers(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
output = _two_layer_model(x)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Relu_1-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSplitWithNonConstAxis(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
dim = array_ops.placeholder(dtype='int32')
split = array_ops.split(conv, 2, axis=dim)
scale = constant_op.constant(0.1, shape=[32])
offset = constant_op.constant(0.3, shape=[32])
bn0 = nn.fused_batch_norm(split[0], scale, offset)
bn1 = nn.fused_batch_norm(split[1], scale, offset)
add = bn0[0] + bn1[0]
output = array_ops.identity(add)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={dim: 3})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata, feed_dict={dim: 3})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('add_2-0-0', nodes)
self._assert_map_nhwc_to_nchw('split-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSplitVWithNonConstAxis(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
dim = array_ops.placeholder(dtype='int32')
sizes = constant_op.constant([50, 10, 4], shape=[3])
split = gen_array_ops.split_v(
value=conv, size_splits=sizes, axis=dim, num_split=3)
output = math_ops.reduce_sum(split[0])
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={dim: 3})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata, feed_dict={dim: 3})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('SplitV-0-0', nodes)
self._assert_map_nhwc_to_nchw('SplitV-2', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testPadWithConstPaddings(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
paddings_val = [[1, 2], [3, 4], [5, 6], [7, 8]]
paddings = constant_op.constant(
paddings_val, dtype='int32', name='PaddingsConst')
pad = array_ops.pad(conv, paddings)
output = array_ops.identity(pad)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Pad-0-0', nodes)
self.assertIn('Pad-1-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSum(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv)
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testCast(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
cast = math_ops.cast(conv, dtype='bool')
output = array_ops.identity(cast)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Cast-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSqueeze(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[1, 2])
squeeze = array_ops.squeeze(reduce_sum)
output = array_ops.identity(squeeze)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSqueezeAlongHW(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[1, 2], keepdims=True)
squeeze = array_ops.squeeze(reduce_sum, axis=[1, 2])
output = array_ops.identity(squeeze)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSqueezeAlongNHW(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[0, 1, 2], keepdims=True)
squeeze = array_ops.squeeze(reduce_sum, axis=[0, 1, 2])
output = array_ops.identity(squeeze)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongHWC(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[1, 2, 3])
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongNHW(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[0, 1, 2])
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongC(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[3])
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Three transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongCKeepDims(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[3], keepdims=True)
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Sum-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongHKeepDims(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[2], keepdims=True)
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReduceSumAlongWCKeepDims(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
reduce_sum = math_ops.reduce_sum(conv, axis=[2, 3], keepdims=True)
output = array_ops.identity(reduce_sum)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testConcatWithControlDependency(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
axis = constant_op.constant(3)
var = variables.Variable(3)
assign = state_ops.assign(var, 6)
with ops.control_dependencies([assign]):
concat = array_ops.concat([conv, conv], axis)
output = array_ops.identity(concat)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('concat-0-0', nodes)
self.assertIn('concat-2-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testFill(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = array_ops.placeholder(dtype='float32')
conv = _two_layer_model(x)
shape = array_ops.shape(conv)
scalar = array_ops.constant(5.7)
fill = array_ops.fill(shape, scalar)
output = array_ops.identity(fill)
x_val = [3.4] * 784
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={x: x_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
x: x_val
})
nodes = []
num_transposes = 0
num_vec_permute = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
if _is_permute(node.name):
num_vec_permute += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
# Two vector permute nodes were initially added in the Expand phase of
# LayoutOptimizer; they cancelled out each other in the Collapse phase.
expected_vec_permute = 0
self.assertEqual(expected_vec_permute, num_vec_permute)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Fill-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testTile(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
multiple = array_ops.placeholder(dtype='int32')
tile = array_ops.tile(conv, multiple)
output = array_ops.identity(tile)
multiple_val = [2, 3, 4, 1]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={multiple: multiple_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
multiple: multiple_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Tile-0-0', nodes)
self._assert_vec_nhwc_to_nchw('Tile-1', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReverseWithConstDims(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
dims = constant_op.constant([3, 1], name='DimsConst')
reverse = array_ops.reverse(conv, dims)
output = array_ops.identity(reverse)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('ReverseV2-0-0', nodes)
self.assertIn('ReverseV2-1-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testReverseWithNonConstDims(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
dims = array_ops.placeholder(dtype='int32')
reverse = array_ops.reverse(conv, dims)
output = array_ops.identity(reverse)
dims_val = [2, 3]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={dims: dims_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
dims: dims_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('ReverseV2-0-0', nodes)
self._assert_map_nhwc_to_nchw('ReverseV2-1', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSelectOp(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
add = math_ops.add(conv, conv)
mean = math_ops.reduce_mean(conv)
condition = math_ops.less(conv, mean)
select = gen_math_ops.select(condition, conv, add)
output = array_ops.identity(select)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Select-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSelectOpConditionUnknownShape(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
add = math_ops.add(conv, conv)
condition = array_ops.placeholder(dtype='bool')
select = gen_math_ops.select(condition, conv, add)
output = array_ops.identity(select)
condition_val = np.zeros((1, 7, 7, 64))
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={condition: condition_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={condition: condition_val})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 3
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSelectOpScalarCondition(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
add = math_ops.add(conv, conv)
condition = constant_op.constant(True)
select = gen_math_ops.select(condition, conv, add)
output = array_ops.identity(select)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Select-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testPadWithNonConstPaddings(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
paddings = array_ops.placeholder(dtype='int32')
pad = array_ops.pad(conv, paddings)
output = array_ops.identity(pad)
paddings_val = [[1, 2], [3, 4], [5, 6], [7, 8]]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={paddings: paddings_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
paddings: paddings_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Pad-0-0', nodes)
self._assert_vec_nhwc_to_nchw('Pad-1', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testMaxPoolV2(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
ksize = constant_op.constant([1, 2, 3, 1], shape=[4])
strides = array_ops.placeholder(dtype='int32', shape=[4])
max_pool = gen_nn_ops.max_pool_v2(conv, ksize, strides, 'VALID')
output = array_ops.identity(max_pool)
strides_val = [1, 3, 2, 1]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={strides: strides_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
strides: strides_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('MaxPoolV2-0-0', nodes)
self._assert_vec_nhwc_to_nchw('MaxPoolV2-2', nodes)
self.assertIn('MaxPoolV2-1-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testMaxPoolGradV2(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
ksize = constant_op.constant([1, 2, 3, 1], shape=[4])
strides = array_ops.placeholder(dtype='int32', shape=[4])
max_pool_grad = gen_nn_ops.max_pool_grad_v2(conv, conv, conv, ksize,
strides, 'VALID')
output = array_ops.identity(max_pool_grad)
strides_val = [1, 3, 2, 1]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={strides: strides_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
strides: strides_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('MaxPoolGradV2-0-0', nodes)
self._assert_vec_nhwc_to_nchw('MaxPoolGradV2-4', nodes)
self.assertIn('MaxPoolGradV2-3-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testSliceWithNonConstAxis(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
size = array_ops.placeholder(dtype='int32')
s = array_ops.slice(conv, [0, 0, 0, 0], size)
output = array_ops.identity(s)
size_val = [1, 2, 3, 4]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={size: size_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
size: size_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('Slice-0-0', nodes)
self._assert_vec_nhwc_to_nchw('Slice-2', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testStridedSliceWithNonConstAxis(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
end = array_ops.placeholder(dtype='int32')
s = array_ops.strided_slice(conv, [0, 0, 0, 0], end, strides=[1, 2, 3, 1])
output = array_ops.identity(s)
end_val = [1, 2, 3, 4]
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={end: end_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
end: end_val
})
<|fim▁hole|> for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('StridedSlice-0-0', nodes)
self._assert_vec_nhwc_to_nchw('StridedSlice-2', nodes)
self.assertIn('StridedSlice-1-LayoutOptimizer', nodes)
self.assertIn('StridedSlice-3-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testStridedSliceWithMask1011(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
# This will generate a StridedSlice op with begin mask and
# end mask 11(1011).
s = conv[:, :, 1:-1, :]
output = array_ops.identity(s)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('strided_slice-0-0', nodes)
self.assertIn('strided_slice-1-LayoutOptimizer', nodes)
self.assertIn('strided_slice-2-LayoutOptimizer', nodes)
self.assertIn('strided_slice-3-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testStridedSliceWithMask0111(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
# This will generate a StridedSlice op with begin mask and
# end mask 7(0111).
s = conv[:, :, :, 1:-1]
output = array_ops.identity(s)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('strided_slice-0-0', nodes)
self.assertIn('strided_slice-1-LayoutOptimizer', nodes)
self.assertIn('strided_slice-2-LayoutOptimizer', nodes)
self.assertIn('strided_slice-3-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testStridedSliceGradWithNonConstAxis(self):
if test.is_gpu_available(cuda_only=True):
random_seed.set_random_seed(0)
x = random_ops.truncated_normal([1, 784], seed=0)
conv = _two_layer_model(x)
end = array_ops.placeholder(dtype='int32')
shape = array_ops.shape(conv)
end_val = [1, 2, 3, 4]
s = array_ops.strided_slice(
conv, [0, 0, 0, 0], end_val, strides=[1, 2, 3, 1])
s_grad = array_ops.strided_slice_grad(shape, [0, 0, 0, 0], end,
[1, 2, 3, 1], s)
output = array_ops.identity(s_grad)
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={end: end_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
end: end_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('StridedSliceGrad-0-0', nodes)
self._assert_vec_nhwc_to_nchw('StridedSliceGrad-2', nodes)
self.assertIn('StridedSlice-1-LayoutOptimizer', nodes)
self.assertIn('StridedSlice-2-LayoutOptimizer', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testShapeN(self):
if test.is_gpu_available(cuda_only=True):
x = array_ops.placeholder(dtype='float32')
conv = _two_layer_model(x)
shapen = array_ops.shape_n([conv, conv])
output = math_ops.add(shapen[0], shapen[1])
x_val = [1.7] * 784
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={x: x_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={
x: x_val
})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 1
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self._assert_vec_nchw_to_nhwc('ShapeN-0-0', nodes)
self.assertAllEqual(output_val_ref, output_val)
@test_util.deprecated_graph_mode_only
def testShapeNFollowedByNotConvertibleNodeReshape(self):
if test.is_gpu_available(cuda_only=True):
x = array_ops.placeholder(dtype='float32')
conv = _two_layer_model(x)
conv_reshape = array_ops.reshape(conv, [1, 1, 1, -1])
shapen = array_ops.shape_n([conv, conv_reshape])
shape = array_ops.identity(shapen[1])
ones = array_ops.ones(shape)
output = math_ops.add_n([conv_reshape, ones])
x_val = [1.7] * 784
with session.Session(config=_get_config(False)) as sess:
output_val_ref = sess.run(output, feed_dict={x: x_val})
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(
output, run_metadata=metadata, feed_dict={x: x_val})
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('Conv2D-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testLoop(self):
if test.is_gpu_available(cuda_only=True):
output = _loop()
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
# Four transposes were initially added in the Expand phase of
# LayoutOptimizer; two of them are cancelled out in the Collapse phase.
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('map/while/Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('map/while/MaxPool_1-0-2', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testLoopWithBranch(self):
if test.is_gpu_available(cuda_only=True):
output = _loop_with_branch()
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 3
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('map/while/Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('map/while/Add_1-0-2', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testLoopWithVecAnd4D(self):
if test.is_gpu_available(cuda_only=True):
output = _loop_with_vec_and_4d()
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('map/while/Conv2D-0', nodes)
self._assert_trans_nchw_to_nhwc('map/while/Add_1-0-2', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testBinaryOpSecondPort(self):
with compat.forward_compatibility_horizon(2019, 6, 7):
if test.is_gpu_available(cuda_only=True):
output = _model_with_second_port()
with session.Session(config=_get_config(False)) as sess:
output_val_ref = self.evaluate(output)
with session.Session(config=_get_config()) as sess:
metadata = config_pb2.RunMetadata()
output_val = sess.run(output, run_metadata=metadata)
nodes = []
num_transposes = 0
for node in metadata.cost_graph.node:
if _is_transpose(node.name):
num_transposes += 1
nodes.append(node.name)
expected_num_transposes = 2
self.assertEqual(expected_num_transposes, num_transposes)
self._assert_trans_nhwc_to_nchw('FusedBatchNormV3-0', nodes)
self._assert_trans_nchw_to_nhwc('Add-0-0', nodes)
self.assertAllClose(output_val_ref, output_val, atol=1e-3)
@test_util.deprecated_graph_mode_only
def testGradient(self):
meta_graph = _simple_metagraph()
config = config_pb2.ConfigProto()
config.graph_options.rewrite_options.CopyFrom(
rewriter_config_pb2.RewriterConfig(
layout_optimizer=rewriter_config_pb2.RewriterConfig.ON,
min_graph_nodes=-1))
optimized_graph = tf_optimizer.OptimizeGraph(
config, meta_graph, cluster=_get_cluster())
found = 0
for node in optimized_graph.node:
if node.op in ['Conv2D', 'Conv2DBackpropFilter', 'Conv2DBackpropInput']:
found += 1
self.assertEqual(node.attr['data_format'].s, b'NCHW')
self.assertEqual(found, 5)
@test_util.deprecated_graph_mode_only
def testDepthwise(self):
meta_graph = _simple_metagraph(depthwise=True)
config = config_pb2.ConfigProto()
config.graph_options.rewrite_options.CopyFrom(
rewriter_config_pb2.RewriterConfig(
layout_optimizer=rewriter_config_pb2.RewriterConfig.ON,
min_graph_nodes=-1))
optimized_graph = tf_optimizer.OptimizeGraph(
config, meta_graph, cluster=_get_cluster())
found = 0
for node in optimized_graph.node:
if node.op in [
'DepthwiseConv2dNative', 'DepthwiseConv2dNativeBackpropFilter',
'DepthwiseConv2dNativeBackpropInput'
]:
found += 1
self.assertEqual(node.attr['data_format'].s, b'NCHW')
self.assertEqual(found, 6)
def testCheckpointCompatibility(self):
if not test.is_gpu_available(cuda_only=True):
self.skipTest('GPU required')
checkpoint_path = self.get_temp_dir()
self._train(checkpoint_path)
vars_expected = self._train(checkpoint_path, restore=True)
vars_layout_optimized = self._train(
checkpoint_path, restore=True, layout_optimizer=True)
for var_expected, var_layout_optimized in zip(vars_expected,
vars_layout_optimized):
self.assertAllClose(var_expected, var_layout_optimized, atol=1e-6)
if __name__ == '__main__':
test.main()<|fim▁end|> | nodes = []
num_transposes = 0 |
<|file_name|>typeGuardFunctionOfFormThis.js<|end_file_name|><|fim▁begin|>//// [typeGuardFunctionOfFormThis.ts]
class RoyalGuard {
isLeader(): this is LeadGuard {
return this instanceof LeadGuard;
}
isFollower(): this is FollowerGuard {
return this instanceof FollowerGuard;
}
}
<|fim▁hole|>class LeadGuard extends RoyalGuard {
lead(): void {};
}
class FollowerGuard extends RoyalGuard {
follow(): void {};
}
let a: RoyalGuard = new FollowerGuard();
if (a.isLeader()) {
a.lead();
}
else if (a.isFollower()) {
a.follow();
}
interface GuardInterface extends RoyalGuard {}
let b: GuardInterface;
if (b.isLeader()) {
b.lead();
}
else if (b.isFollower()) {
b.follow();
}
// if (((a.isLeader)())) {
// a.lead();
// }
// else if (((a).isFollower())) {
// a.follow();
// }
// if (((a["isLeader"])())) {
// a.lead();
// }
// else if (((a)["isFollower"]())) {
// a.follow();
// }
var holder2 = {a};
if (holder2.a.isLeader()) {
holder2.a;
}
else {
holder2.a;
}
class ArrowGuard {
isElite = (): this is ArrowElite => {
return this instanceof ArrowElite;
}
isMedic = (): this is ArrowMedic => {
return this instanceof ArrowMedic;
}
}
class ArrowElite extends ArrowGuard {
defend(): void {}
}
class ArrowMedic extends ArrowGuard {
heal(): void {}
}
let guard = new ArrowGuard();
if (guard.isElite()) {
guard.defend();
}
else if (guard.isMedic()) {
guard.heal();
}
interface Supplies {
spoiled: boolean;
}
interface Sundries {
broken: boolean;
}
interface Crate<T> {
contents: T;
volume: number;
isSupplies(): this is Crate<Supplies>;
isSundries(): this is Crate<Sundries>;
}
let crate: Crate<{}>;
if (crate.isSundries()) {
crate.contents.broken = true;
}
else if (crate.isSupplies()) {
crate.contents.spoiled = true;
}
// Matching guards should be assignable
a.isFollower = b.isFollower;
a.isLeader = b.isLeader;
class MimicGuard {
isLeader(): this is MimicLeader { return this instanceof MimicLeader; };
isFollower(): this is MimicFollower { return this instanceof MimicFollower; };
}
class MimicLeader extends MimicGuard {
lead(): void {}
}
class MimicFollower extends MimicGuard {
follow(): void {}
}
let mimic = new MimicGuard();
a.isLeader = mimic.isLeader;
a.isFollower = mimic.isFollower;
if (mimic.isFollower()) {
mimic.follow();
mimic.isFollower = a.isFollower;
}
interface MimicGuardInterface {
isLeader(): this is LeadGuard;
isFollower(): this is FollowerGuard;
}
//// [typeGuardFunctionOfFormThis.js]
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var RoyalGuard = /** @class */ (function () {
function RoyalGuard() {
}
RoyalGuard.prototype.isLeader = function () {
return this instanceof LeadGuard;
};
RoyalGuard.prototype.isFollower = function () {
return this instanceof FollowerGuard;
};
return RoyalGuard;
}());
var LeadGuard = /** @class */ (function (_super) {
__extends(LeadGuard, _super);
function LeadGuard() {
return _super !== null && _super.apply(this, arguments) || this;
}
LeadGuard.prototype.lead = function () { };
;
return LeadGuard;
}(RoyalGuard));
var FollowerGuard = /** @class */ (function (_super) {
__extends(FollowerGuard, _super);
function FollowerGuard() {
return _super !== null && _super.apply(this, arguments) || this;
}
FollowerGuard.prototype.follow = function () { };
;
return FollowerGuard;
}(RoyalGuard));
var a = new FollowerGuard();
if (a.isLeader()) {
a.lead();
}
else if (a.isFollower()) {
a.follow();
}
var b;
if (b.isLeader()) {
b.lead();
}
else if (b.isFollower()) {
b.follow();
}
// if (((a.isLeader)())) {
// a.lead();
// }
// else if (((a).isFollower())) {
// a.follow();
// }
// if (((a["isLeader"])())) {
// a.lead();
// }
// else if (((a)["isFollower"]())) {
// a.follow();
// }
var holder2 = { a: a };
if (holder2.a.isLeader()) {
holder2.a;
}
else {
holder2.a;
}
var ArrowGuard = /** @class */ (function () {
function ArrowGuard() {
var _this = this;
this.isElite = function () {
return _this instanceof ArrowElite;
};
this.isMedic = function () {
return _this instanceof ArrowMedic;
};
}
return ArrowGuard;
}());
var ArrowElite = /** @class */ (function (_super) {
__extends(ArrowElite, _super);
function ArrowElite() {
return _super !== null && _super.apply(this, arguments) || this;
}
ArrowElite.prototype.defend = function () { };
return ArrowElite;
}(ArrowGuard));
var ArrowMedic = /** @class */ (function (_super) {
__extends(ArrowMedic, _super);
function ArrowMedic() {
return _super !== null && _super.apply(this, arguments) || this;
}
ArrowMedic.prototype.heal = function () { };
return ArrowMedic;
}(ArrowGuard));
var guard = new ArrowGuard();
if (guard.isElite()) {
guard.defend();
}
else if (guard.isMedic()) {
guard.heal();
}
var crate;
if (crate.isSundries()) {
crate.contents.broken = true;
}
else if (crate.isSupplies()) {
crate.contents.spoiled = true;
}
// Matching guards should be assignable
a.isFollower = b.isFollower;
a.isLeader = b.isLeader;
var MimicGuard = /** @class */ (function () {
function MimicGuard() {
}
MimicGuard.prototype.isLeader = function () { return this instanceof MimicLeader; };
;
MimicGuard.prototype.isFollower = function () { return this instanceof MimicFollower; };
;
return MimicGuard;
}());
var MimicLeader = /** @class */ (function (_super) {
__extends(MimicLeader, _super);
function MimicLeader() {
return _super !== null && _super.apply(this, arguments) || this;
}
MimicLeader.prototype.lead = function () { };
return MimicLeader;
}(MimicGuard));
var MimicFollower = /** @class */ (function (_super) {
__extends(MimicFollower, _super);
function MimicFollower() {
return _super !== null && _super.apply(this, arguments) || this;
}
MimicFollower.prototype.follow = function () { };
return MimicFollower;
}(MimicGuard));
var mimic = new MimicGuard();
a.isLeader = mimic.isLeader;
a.isFollower = mimic.isFollower;
if (mimic.isFollower()) {
mimic.follow();
mimic.isFollower = a.isFollower;
}
//// [typeGuardFunctionOfFormThis.d.ts]
declare class RoyalGuard {
isLeader(): this is LeadGuard;
isFollower(): this is FollowerGuard;
}
declare class LeadGuard extends RoyalGuard {
lead(): void;
}
declare class FollowerGuard extends RoyalGuard {
follow(): void;
}
declare let a: RoyalGuard;
interface GuardInterface extends RoyalGuard {
}
declare let b: GuardInterface;
declare var holder2: {
a: RoyalGuard;
};
declare class ArrowGuard {
isElite: () => this is ArrowElite;
isMedic: () => this is ArrowMedic;
}
declare class ArrowElite extends ArrowGuard {
defend(): void;
}
declare class ArrowMedic extends ArrowGuard {
heal(): void;
}
declare let guard: ArrowGuard;
interface Supplies {
spoiled: boolean;
}
interface Sundries {
broken: boolean;
}
interface Crate<T> {
contents: T;
volume: number;
isSupplies(): this is Crate<Supplies>;
isSundries(): this is Crate<Sundries>;
}
declare let crate: Crate<{}>;
declare class MimicGuard {
isLeader(): this is MimicLeader;
isFollower(): this is MimicFollower;
}
declare class MimicLeader extends MimicGuard {
lead(): void;
}
declare class MimicFollower extends MimicGuard {
follow(): void;
}
declare let mimic: MimicGuard;
interface MimicGuardInterface {
isLeader(): this is LeadGuard;
isFollower(): this is FollowerGuard;
}<|fim▁end|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.