text
stringlengths
2
100k
meta
dict
// 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.impala.analysis; import org.apache.impala.authorization.Privilege; import org.apache.impala.catalog.FeDb; import org.apache.impala.common.AnalysisException; import org.apache.impala.thrift.TDropDbParams; /** * Represents a DROP [IF EXISTS] DATABASE [CASCADE | RESTRICT] statement */ public class DropDbStmt extends StatementBase { private final String dbName_; private final boolean ifExists_; private final boolean cascade_; // Server name needed for privileges. Set during analysis. private String serverName_; /** * Constructor for building the drop statement. If ifExists is true, an error will not * be thrown if the database does not exist. If cascade is true, all the tables in the * database will be dropped. */ public DropDbStmt(String dbName, boolean ifExists, boolean cascade) { this.dbName_ = dbName; this.ifExists_ = ifExists; this.cascade_ = cascade; } public String getDb() { return dbName_; } public boolean getIfExists() { return ifExists_; } public boolean getCascade() { return cascade_; } @Override public String toSql(ToSqlOptions options) { StringBuilder sb = new StringBuilder("DROP DATABASE"); if (ifExists_) sb.append(" IF EXISTS "); sb.append(getDb()); if (cascade_) sb.append(" CASCADE"); return sb.toString(); } public TDropDbParams toThrift() { TDropDbParams params = new TDropDbParams(); params.setDb(getDb()); params.setIf_exists(getIfExists()); params.setCascade(getCascade()); params.setServer_name(serverName_); return params; } @Override public void analyze(Analyzer analyzer) throws AnalysisException { // Set the servername here if authorization is enabled because analyzer_ is not // available in the toThrift() method. serverName_ = analyzer.getServerName(); // Fetch the owner information if the db exists. FeDb db = analyzer.getDb(dbName_, /*ThrowIfNotExists*/ false); String ownerUser = db == null ? null : db.getOwnerUser(); if (ifExists_) { // Start with ANY privilege in case of IF EXISTS, and register DROP privilege // later only if the database exists. See IMPALA-8851 for more explanation. analyzer.registerPrivReq(builder -> builder.allOf(Privilege.ANY) .onDb(dbName_, ownerUser) .build()); if (!analyzer.dbExists(dbName_)) return; } // Register the DROP privilege request. db = analyzer.getDb(dbName_, Privilege.DROP, false, false); if (db == null && !ifExists_) { throw new AnalysisException(Analyzer.DB_DOES_NOT_EXIST_ERROR_MSG + dbName_); } if (analyzer.getDefaultDb().toLowerCase().equals(dbName_.toLowerCase())) { throw new AnalysisException("Cannot drop current default database: " + dbName_); } if (db != null && db.numFunctions() > 0 && !cascade_) { throw new AnalysisException("Cannot drop non-empty database: " + dbName_); } } }
{ "pile_set_name": "Github" }
<html lang="en"> <head> <title>D30V-Size - Using as</title> <meta http-equiv="Content-Type" content="text/html"> <meta name="description" content="Using as"> <meta name="generator" content="makeinfo 4.7"> <link title="Top" rel="start" href="index.html#Top"> <link rel="up" href="D30V_002dSyntax.html#D30V_002dSyntax" title="D30V-Syntax"> <link rel="next" href="D30V_002dSubs.html#D30V_002dSubs" title="D30V-Subs"> <link href="http://www.gnu.org/software/texinfo/" rel="generator-home" title="Texinfo Homepage"> <!-- This file documents the GNU Assembler "as". Copyright (C) 1991, 92, 93, 94, 95, 96, 97, 98, 99, 2000, 2001, 2002, 2006, 2007 Free Software Foundation, Inc. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with no Invariant Sections, with no Front-Cover Texts, and with no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''. man end--> <meta http-equiv="Content-Style-Type" content="text/css"> <style type="text/css"><!-- pre.display { font-family:inherit } pre.format { font-family:inherit } pre.smalldisplay { font-family:inherit; font-size:smaller } pre.smallformat { font-family:inherit; font-size:smaller } pre.smallexample { font-size:smaller } pre.smalllisp { font-size:smaller } span.sc { font-variant:small-caps } span.roman { font-family: serif; font-weight: normal; } --></style> </head> <body> <div class="node"> <p> <a name="D30V_002dSize"></a>Next:&nbsp;<a rel="next" accesskey="n" href="D30V_002dSubs.html#D30V_002dSubs">D30V-Subs</a>, Up:&nbsp;<a rel="up" accesskey="u" href="D30V_002dSyntax.html#D30V_002dSyntax">D30V-Syntax</a> <hr><br> </div> <h5 class="subsubsection">9.9.2.1 Size Modifiers</h5> <p><a name="index-D30V-size-modifiers-754"></a><a name="index-size-modifiers_002c-D30V-755"></a>The D30V version of <code>as</code> uses the instruction names in the D30V Architecture Manual. However, the names in the manual are sometimes ambiguous. There are instruction names that can assemble to a short or long form opcode. How does the assembler pick the correct form? <code>as</code> will always pick the smallest form if it can. When dealing with a symbol that is not defined yet when a line is being assembled, it will always use the long form. If you need to force the assembler to use either the short or long form of the instruction, you can append either <span class="samp">.s</span> (short) or <span class="samp">.l</span> (long) to it. For example, if you are writing an assembly program and you want to do a branch to a symbol that is defined later in your program, you can write <span class="samp">bra.s foo</span>. Objdump and GDB will always append <span class="samp">.s</span> or <span class="samp">.l</span> to instructions which have both short and long forms. </body></html>
{ "pile_set_name": "Github" }
/* Software floating-point emulation. Definitions for IEEE Half Precision. Copyright (C) 1997-2018 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. In addition to the permissions in the GNU Lesser General Public License, the Free Software Foundation gives you unlimited permission to link the compiled version of this file into combinations with other programs, and to distribute those combinations without any restriction coming from the use of this file. (The Lesser General Public License restrictions do apply in other respects; for example, they cover modification of the file, and distribution when not linked into a combine executable.) The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #ifndef SOFT_FP_HALF_H #define SOFT_FP_HALF_H 1 #if _FP_W_TYPE_SIZE < 32 # error "Here's a nickel kid. Go buy yourself a real computer." #endif #define _FP_FRACTBITS_H (_FP_W_TYPE_SIZE) #define _FP_FRACTBITS_DW_H (_FP_W_TYPE_SIZE) #define _FP_FRACBITS_H 11 #define _FP_FRACXBITS_H (_FP_FRACTBITS_H - _FP_FRACBITS_H) #define _FP_WFRACBITS_H (_FP_WORKBITS + _FP_FRACBITS_H) #define _FP_WFRACXBITS_H (_FP_FRACTBITS_H - _FP_WFRACBITS_H) #define _FP_EXPBITS_H 5 #define _FP_EXPBIAS_H 15 #define _FP_EXPMAX_H 31 #define _FP_QNANBIT_H ((_FP_W_TYPE) 1 << (_FP_FRACBITS_H-2)) #define _FP_QNANBIT_SH_H ((_FP_W_TYPE) 1 << (_FP_FRACBITS_H-2+_FP_WORKBITS)) #define _FP_IMPLBIT_H ((_FP_W_TYPE) 1 << (_FP_FRACBITS_H-1)) #define _FP_IMPLBIT_SH_H ((_FP_W_TYPE) 1 << (_FP_FRACBITS_H-1+_FP_WORKBITS)) #define _FP_OVERFLOW_H ((_FP_W_TYPE) 1 << (_FP_WFRACBITS_H)) #define _FP_WFRACBITS_DW_H (2 * _FP_WFRACBITS_H) #define _FP_WFRACXBITS_DW_H (_FP_FRACTBITS_DW_H - _FP_WFRACBITS_DW_H) #define _FP_HIGHBIT_DW_H \ ((_FP_W_TYPE) 1 << (_FP_WFRACBITS_DW_H - 1) % _FP_W_TYPE_SIZE) /* The implementation of _FP_MUL_MEAT_H and _FP_DIV_MEAT_H should be chosen by the target machine. */ typedef float HFtype __attribute__ ((mode (HF))); union _FP_UNION_H { HFtype flt; struct _FP_STRUCT_LAYOUT { #if __BYTE_ORDER == __BIG_ENDIAN unsigned sign : 1; unsigned exp : _FP_EXPBITS_H; unsigned frac : _FP_FRACBITS_H - (_FP_IMPLBIT_H != 0); #else unsigned frac : _FP_FRACBITS_H - (_FP_IMPLBIT_H != 0); unsigned exp : _FP_EXPBITS_H; unsigned sign : 1; #endif } bits; }; #define FP_DECL_H(X) _FP_DECL (1, X) #define FP_UNPACK_RAW_H(X, val) _FP_UNPACK_RAW_1 (H, X, (val)) #define FP_UNPACK_RAW_HP(X, val) _FP_UNPACK_RAW_1_P (H, X, (val)) #define FP_PACK_RAW_H(val, X) _FP_PACK_RAW_1 (H, (val), X) #define FP_PACK_RAW_HP(val, X) \ do \ { \ if (!FP_INHIBIT_RESULTS) \ _FP_PACK_RAW_1_P (H, (val), X); \ } \ while (0) #define FP_UNPACK_H(X, val) \ do \ { \ _FP_UNPACK_RAW_1 (H, X, (val)); \ _FP_UNPACK_CANONICAL (H, 1, X); \ } \ while (0) #define FP_UNPACK_HP(X, val) \ do \ { \ _FP_UNPACK_RAW_1_P (H, X, (val)); \ _FP_UNPACK_CANONICAL (H, 1, X); \ } \ while (0) #define FP_UNPACK_SEMIRAW_H(X, val) \ do \ { \ _FP_UNPACK_RAW_1 (H, X, (val)); \ _FP_UNPACK_SEMIRAW (H, 1, X); \ } \ while (0) #define FP_UNPACK_SEMIRAW_HP(X, val) \ do \ { \ _FP_UNPACK_RAW_1_P (H, X, (val)); \ _FP_UNPACK_SEMIRAW (H, 1, X); \ } \ while (0) #define FP_PACK_H(val, X) \ do \ { \ _FP_PACK_CANONICAL (H, 1, X); \ _FP_PACK_RAW_1 (H, (val), X); \ } \ while (0) #define FP_PACK_HP(val, X) \ do \ { \ _FP_PACK_CANONICAL (H, 1, X); \ if (!FP_INHIBIT_RESULTS) \ _FP_PACK_RAW_1_P (H, (val), X); \ } \ while (0) #define FP_PACK_SEMIRAW_H(val, X) \ do \ { \ _FP_PACK_SEMIRAW (H, 1, X); \ _FP_PACK_RAW_1 (H, (val), X); \ } \ while (0) #define FP_PACK_SEMIRAW_HP(val, X) \ do \ { \ _FP_PACK_SEMIRAW (H, 1, X); \ if (!FP_INHIBIT_RESULTS) \ _FP_PACK_RAW_1_P (H, (val), X); \ } \ while (0) #define FP_TO_INT_H(r, X, rsz, rsg) _FP_TO_INT (H, 1, (r), X, (rsz), (rsg)) #define FP_TO_INT_ROUND_H(r, X, rsz, rsg) \ _FP_TO_INT_ROUND (H, 1, (r), X, (rsz), (rsg)) #define FP_FROM_INT_H(X, r, rs, rt) _FP_FROM_INT (H, 1, X, (r), (rs), rt) /* HFmode arithmetic is not implemented. */ #define _FP_FRAC_HIGH_H(X) _FP_FRAC_HIGH_1 (X) #define _FP_FRAC_HIGH_RAW_H(X) _FP_FRAC_HIGH_1 (X) #define _FP_FRAC_HIGH_DW_H(X) _FP_FRAC_HIGH_1 (X) #endif /* !SOFT_FP_HALF_H */
{ "pile_set_name": "Github" }
/** * @license * Copyright 2018 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 * * 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 { LitElement, html } from '@polymer/lit-element' import { commonStyle } from './InputStyle' customElements.define('magenta-slider', class MagentaSlider extends LitElement { static get properties(){ return { label : { type : String }, units : { type : String }, value : { type : Number }, min : { type : Number }, max : { type : Number }, step : { type : Number }, } } constructor(){ super() this.value = '2' this.min = '0' this.max = '100' this.step = '1' this.units = '' } _generateGradient(e){ this.value = (e && e.target.value) || this.value const input = this.shadowRoot.querySelector('input') const pos = Math.scale(parseFloat(this.value), parseFloat(this.min), parseFloat(this.max), 0, 1) this.dispatchEvent(new CustomEvent('input', { bubbles : true, composed : true, detail : { value : this.value } })) input.style.backgroundImage = `-webkit-gradient( linear, left top, right top, color-stop(${pos}, var(--accent-color)), color-stop(${pos}, white) )` } firstUpdated(){ this._generateGradient() } render(){ return html` ${commonStyle} <style> :host { display: inline-block; } #top { display: block; margin-bottom: 5px; } #value-group { float: right; } label, #value { font-weight: bold; } label, #units, #value { color: white; font-family: var(--title-font-family); font-size: 14px; } #units { margin-left: 4px; } div { margin-top: 10px; width: 100%; display: flex; flex-direction: row; align-items: stretch; } #units { color: var(--color-gray); ${this.units === '' ? 'margin-left: 0' : ''}; } input, input[type="range"]{ width: 100%; border: none; -webkit-appearance: none; -moz-apperance: none; height: 19px; border-top: 8px solid var(--background-color); border-bottom: 8px solid var(--background-color); box-sizing: border-box; padding: 0px; margin: 0px; } input[type='range']::-webkit-slider-thumb { -webkit-appearance: none !important; background-color: white; height: 18px; width: 18px; border-radius: 50%; } input[type='range']:focus::-webkit-slider-thumb { box-shadow: 0 0 1pt 1pt var(--shadow-color); } </style> <div id="top"> <label for="slider">${this.label}</label> <span id="value-group"> <span id="value">${parseFloat(this.step) < 1 ? parseFloat(this.value).toFixed(1) : this.value}</span> <span id="units">${this.units}</span> </span> </div> <input name="slider" .min=${this.min} .max=${this.max} .value=${this.value} .step=${this.step} @input=${e => this._generateGradient(e)} @change=${e => this.value = parseFloat(e.target.value)} type="range" > ` } })
{ "pile_set_name": "Github" }
/** * Copyright (c) 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow * @format */ import * as React from 'react'; import ReactDOM from 'react-dom'; import classnames from 'classnames'; import {getLogger} from 'log4js'; import UniversalDisposable from 'nuclide-commons/UniversalDisposable'; import {Icon} from './Icon'; function WarningIconWithShadow(): React.Node { return ( <div> <svg className="nuclide-ui-path-with-file-icon-warning-icon-background" width="20" height="18" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"> <polygon points="10,2 0,18 20,18" /> </svg> <Icon className="text-warning" icon="alert" /> </div> ); } function ErrorIconWithShadow(): React.Node { return ( <div> <svg className="nuclide-ui-path-with-file-icon-error-icon-background" width="16" height="16" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"> <circle cx="10" cy="10" r="8" /> </svg> <Icon className="text-error" icon="stop" /> </div> ); } // The decoration icons require a backdrop to be fully visible, // so we only allow the following, blessed decorations: export const DecorationIcons = Object.freeze({ Warning: WarningIconWithShadow, Error: ErrorIconWithShadow, }); export type FileIconsAddItemToElementFn = ( element: HTMLElement, path: string, ) => IDisposable; type Props = { className?: string, children?: React.Node, // Optional <Icon /> element. If set, will render a small version of // the decorationIcon on top of the file icon. decorationIcon?: typeof WarningIconWithShadow | typeof ErrorIconWithShadow, isFolder?: boolean, path: string, }; let addItemToElement: ?FileIconsAddItemToElementFn; atom.packages.serviceHub.consume( 'file-icons.element-icons', '1.0.0', (_addItemToElement: FileIconsAddItemToElementFn) => { addItemToElement = (element: HTMLElement, path: string) => { try { return _addItemToElement(element, path); } catch (e) { getLogger('nuclide-ui-path-with-file-icon').error( 'Error adding item to element', e, ); return new UniversalDisposable(); } }; return new UniversalDisposable(() => { addItemToElement = null; }); }, ); export default class PathWithFileIcon extends React.Component<Props> { _disposables: UniversalDisposable; _fileIconsDisposable: ?IDisposable; _mounted: boolean; constructor(props: Props) { super(props); this._mounted = false; this._disposables = new UniversalDisposable(() => { if (this._fileIconsDisposable != null) { this._fileIconsDisposable.dispose(); } }); } componentDidMount(): void { this._mounted = true; } componentDidUpdate(prevProps: Props) { if (prevProps.path !== this.props.path) { this._forceIconUpdate(); } } _handleRef = (element: ?HTMLElement): void => { if (this.props.isFolder) { return; } this._ensureIconRemoved(); if (addItemToElement == null) { // file-icons service not available; ignore. return; } if (element == null) { // Element is unmounting. return; } this._fileIconsDisposable = addItemToElement(element, this.props.path); }; _getDefaultClassName(): string { const {className, isFolder} = this.props; return classnames( 'icon', 'name', 'nuclide-ui-path-with-file-icon', { 'icon-file-text': isFolder !== true, 'icon-file-directory': isFolder === true, }, className, ); } _forceIconUpdate(): void { if (!this._mounted) { return; } const element = ReactDOM.findDOMNode(this); // $FlowIssue `element` is an HTMLElement this._handleRef(element); } _ensureIconRemoved(): void { if (this._fileIconsDisposable == null) { return; } this._fileIconsDisposable.dispose(); this._fileIconsDisposable = null; } componentWillUnmount(): void { this._disposables.dispose(); this._mounted = false; } render(): React.Node { const { className, children, decorationIcon: DecorationIcon, isFolder, path, // forward properties such as `data-path`, etc ...rest } = this.props; const displayPath = children == null ? path : children; const decoration = DecorationIcon == null ? null : ( <div className="nuclide-ui-path-with-file-icon-decoration-icon"> {/* $FlowIssue "expected React component instead of prototype" */} <DecorationIcon /> </div> ); return ( <div className={this._getDefaultClassName()} ref={this._handleRef} {...rest}> {displayPath} {decoration} </div> ); } }
{ "pile_set_name": "Github" }
//////////////////////////////////////////////////////////////////////// // // Copyright (C) 2005-2020 The Octave Project Developers // // See the file COPYRIGHT.md in the top-level directory of this // distribution or <https://octave.org/copyright/>. // // This file is part of Octave. // // Octave 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. // // Octave 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 Octave; see the file COPYING. If not, see // <https://www.gnu.org/licenses/>. // //////////////////////////////////////////////////////////////////////// /* This file is adapted from the zlib 1.2.2 contrib/iostream3 code, written by Ludwig Schwardt <[email protected]> original version by Kevin Ruland <[email protected]> */ #if ! defined (octave_zfsstream_h) #define octave_zfsstream_h 1 #include "octave-config.h" #if defined (HAVE_ZLIB) #include <iosfwd> #include "zlib.h" /** * @brief Gzipped file stream buffer class. * * This class implements basic_filebuf for gzipped files. It doesn't yet * support seeking (allowed by zlib but slow/limited), putback and read/write * access * (tricky). Otherwise, it attempts to be a drop-in replacement for * the standard file streambuf. */ class gzfilebuf : public std::streambuf { public: // Default constructor. gzfilebuf (); // No copying! gzfilebuf (const gzfilebuf&) = delete; gzfilebuf& operator = (const gzfilebuf&) = delete; // Destructor. virtual ~gzfilebuf (); /** * @brief Set compression level and strategy on the fly. * @param comp_level Compression level (see zlib.h for allowed values) * @param comp_strategy Compression strategy (see zlib.h for allowed values) * @return Z_OK on success, Z_STREAM_ERROR otherwise. * * Unfortunately, these parameters cannot be modified separately, as the * previous zfstream version assumed. Since the strategy is seldom changed, * it can default and setcompression(level) then becomes like the old * setcompressionlevel(level). */ int setcompression (int comp_level, int comp_strategy = Z_DEFAULT_STRATEGY); /** * @brief Check if file is open. * @return True if file is open. */ bool is_open () const { return (file != nullptr); } /** * @brief Open gzipped file. * @param name Filename. * @param mode Open mode flags. * @return @c this on success, NULL on failure. */ gzfilebuf* open (const char *name, std::ios_base::openmode mode); /** * @brief Attach to already open gzipped file. * @param fd File descriptor. * @param mode Open mode flags. * @return @c this on success, NULL on failure. */ gzfilebuf* attach (int fd, std::ios_base::openmode mode); /** * @brief Close gzipped file. * @return @c this on success, NULL on failure. */ gzfilebuf* close (); protected: /** * @brief Convert ios open mode int to mode string used by zlib. * @return True if valid mode flag combination. */ bool open_mode (std::ios_base::openmode mode, char *c_mode) const; /** * @brief Number of characters available in stream buffer. * @return Number of characters. * * This indicates number of characters in get area of stream buffer. * These characters can be read without accessing the gzipped file. */ virtual std::streamsize showmanyc (); /** * @brief Fill get area from gzipped file. * @return First character in get area on success, EOF on error. * * This actually reads characters from gzipped file to stream * buffer. Always buffered. */ virtual int_type underflow (); /** * @brief Write put area to gzipped file. * @param c Extra character to add to buffer contents. * @return Non-EOF on success, EOF on error. * * This actually writes characters in stream buffer to * gzipped file. With unbuffered output this is done one * character at a time. */ virtual int_type overflow (int_type c = traits_type::eof ()); /** * @brief Installs external stream buffer. * @param p Pointer to char buffer. * @param n Size of external buffer. * @return @c this on success, NULL on failure. * * Call setbuf(0,0) to enable unbuffered output. */ virtual std::streambuf* setbuf (char_type *p, std::streamsize n); /** * @brief Flush stream buffer to file. * @return 0 on success, -1 on error. * * This calls underflow(EOF) to do the job. */ virtual int sync (); /** * @brief Alters the stream positions. * * Each derived class provides its own appropriate behavior. */ virtual pos_type seekoff (off_type off, std::ios_base::seekdir way, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out); /** * @brief Alters the stream positions. * * Each derived class provides its own appropriate behavior. */ virtual pos_type seekpos (pos_type sp, std::ios_base::openmode mode = std::ios_base::in | std::ios_base::out); virtual int_type pbackfail (int_type c = traits_type::eof ()); // // Some future enhancements // // virtual int_type uflow(); // virtual int_type pbackfail(int_type c = traits_type::eof()); private: /** * @brief Allocate internal buffer. * * This function is safe to call multiple times. It will ensure * that a proper internal buffer exists if it is required. If the * buffer already exists or is external, the buffer pointers will be * reset to their original state. */ void enable_buffer (); /** * @brief Destroy internal buffer. * * This function is safe to call multiple times. It will ensure * that the internal buffer is deallocated if it exists. In any * case, it will also reset the buffer pointers. */ void disable_buffer (); /** * Underlying file pointer. */ gzFile file; /** * Mode in which file was opened. */ std::ios_base::openmode io_mode; /** * @brief True if this object owns file descriptor. * * This makes the class responsible for closing the file * upon destruction. */ bool own_fd; /** * @brief Stream buffer. * * For simplicity this remains allocated on the free store for the * entire life span of the gzfilebuf object, unless replaced by setbuf. */ char_type *buffer; /** * @brief Stream buffer size. * * Defaults to system default buffer size (typically 8192 bytes). * Modified by setbuf. */ std::streamsize buffer_size; /** * @brief True if this object owns stream buffer. * * This makes the class responsible for deleting the buffer * upon destruction. */ bool own_buffer; }; /** * @brief Gzipped file input stream class. * * This class implements ifstream for gzipped files. Seeking and putback * is not supported yet. */ class gzifstream : public std::istream { public: // Default constructor gzifstream (); /** * @brief Construct stream on gzipped file to be opened. * @param name Filename. * @param mode Open mode flags (forced to contain ios::in). */ explicit gzifstream (const char *name, std::ios_base::openmode mode = std::ios_base::in); /** * @brief Construct stream on already open gzipped file. * @param fd File descriptor. * @param mode Open mode flags (forced to contain ios::in). */ explicit gzifstream (int fd, std::ios_base::openmode mode = std::ios_base::in); /** * Obtain underlying stream buffer. */ gzfilebuf* rdbuf () const { return const_cast<gzfilebuf *>(&sb); } /** * @brief Check if file is open. * @return True if file is open. */ bool is_open () { return sb.is_open (); } /** * @brief Open gzipped file. * @param name Filename. * @param mode Open mode flags (forced to contain ios::in). * * Stream will be in state good() if file opens successfully; * otherwise in state fail(). This differs from the behavior of * ifstream, which never sets the state to good() and therefore * won't allow you to reuse the stream for a second file unless * you manually clear() the state. The choice is a matter of * convenience. */ void open (const char *name, std::ios_base::openmode mode = std::ios_base::in); /** * @brief Attach to already open gzipped file. * @param fd File descriptor. * @param mode Open mode flags (forced to contain ios::in). * * Stream will be in state good() if attach succeeded; otherwise * in state fail(). */ void attach (int fd, std::ios_base::openmode mode = std::ios_base::in); /** * @brief Close gzipped file. * * Stream will be in state fail() if close failed. */ void close (); private: /** * Underlying stream buffer. */ gzfilebuf sb; }; /** * @brief Gzipped file output stream class. * * This class implements ofstream for gzipped files. Seeking and putback * is not supported yet. */ class gzofstream : public std::ostream { public: // Default constructor gzofstream (); /** * @brief Construct stream on gzipped file to be opened. * @param name Filename. * @param mode Open mode flags (forced to contain ios::out). */ explicit gzofstream (const char *name, std::ios_base::openmode mode = std::ios_base::out); /** * @brief Construct stream on already open gzipped file. * @param fd File descriptor. * @param mode Open mode flags (forced to contain ios::out). */ explicit gzofstream (int fd, std::ios_base::openmode mode = std::ios_base::out); /** * Obtain underlying stream buffer. */ gzfilebuf* rdbuf () const { return const_cast<gzfilebuf *>(&sb); } /** * @brief Check if file is open. * @return True if file is open. */ bool is_open () { return sb.is_open (); } /** * @brief Open gzipped file. * @param name Filename. * @param mode Open mode flags (forced to contain ios::out). * * Stream will be in state good() if file opens successfully; * otherwise in state fail(). This differs from the behavior of * ofstream, which never sets the state to good() and therefore * won't allow you to reuse the stream for a second file unless * you manually clear() the state. The choice is a matter of * convenience. */ void open (const char *name, std::ios_base::openmode mode = std::ios_base::out); /** * @brief Attach to already open gzipped file. * @param fd File descriptor. * @param mode Open mode flags (forced to contain ios::out). * * Stream will be in state good() if attach succeeded; otherwise * in state fail(). */ void attach (int fd, std::ios_base::openmode mode = std::ios_base::out); /** * @brief Close gzipped file. * * Stream will be in state fail() if close failed. */ void close (); private: /** * Underlying stream buffer. */ gzfilebuf sb; }; /** * @brief Gzipped file output stream manipulator class. * * This class defines a two-argument manipulator for gzofstream. It is used * as base for the setcompression(int,int) manipulator. */ template <typename T1, typename T2> class gzomanip2 { public: // Allows insertor to peek at internals template <typename Ta, typename Tb> friend gzofstream& operator<<(gzofstream&, const gzomanip2<Ta,Tb>&); // Constructor gzomanip2 (gzofstream& (*f)(gzofstream&, T1, T2), T1 v1, T2 v2); private: // Underlying manipulator function gzofstream& (*func)(gzofstream&, T1, T2); // Arguments for manipulator function T1 val1; T2 val2; }; // Manipulator function thunks through to stream buffer inline gzofstream& setcompression (gzofstream& gzs, int l, int s = Z_DEFAULT_STRATEGY) { (gzs.rdbuf ())->setcompression (l, s); return gzs; } // Manipulator constructor stores arguments template <typename T1, typename T2> inline gzomanip2<T1,T2>::gzomanip2 (gzofstream &(*f)(gzofstream &, T1, T2), T1 v1, T2 v2) : func(f), val1(v1), val2(v2) { } // Insertor applies underlying manipulator function to stream template <typename T1, typename T2> inline gzofstream& operator<<(gzofstream& s, const gzomanip2<T1,T2>& m) { return (*m.func)(s, m.val1, m.val2); } // Insert this onto stream to simplify setting of compression level inline gzomanip2<int,int> setcompression (int l, int s = Z_DEFAULT_STRATEGY) { return gzomanip2<int,int>(&setcompression, l, s); } #endif #endif
{ "pile_set_name": "Github" }
# Translation of Odoo Server. # This file contains the translation of the following modules: # * bus # # Translators: # Martin Trigaux, 2019 # liAnGjiA <[email protected]>, 2019 # 老窦 北京 <[email protected]>, 2019 # guohuadeng <[email protected]>, 2019 # boho wong <[email protected]>, 2019 # Youfu Sheng <[email protected]>, 2019 # inspur qiuguodong <[email protected]>, 2019 # msgid "" msgstr "" "Project-Id-Version: Odoo Server saas~12.5\n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2019-08-26 08:16+0000\n" "PO-Revision-Date: 2019-08-26 09:09+0000\n" "Last-Translator: inspur qiuguodong <[email protected]>, 2019\n" "Language-Team: Chinese (China) (https://www.transifex.com/odoo/teams/41243/zh_CN/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: \n" "Language: zh_CN\n" "Plural-Forms: nplurals=1; plural=0;\n" #. module: bus #: model:ir.model.constraint,message:bus.constraint_bus_presence_bus_user_presence_unique msgid "A user can only have one IM status." msgstr "用户只能有一个IM状态" #. module: bus #: model:ir.model,name:bus.model_ir_autovacuum msgid "Automatic Vacuum" msgstr "自动清空" #. module: bus #: model:ir.model.fields.selection,name:bus.selection__bus_presence__status__away msgid "Away" msgstr "离开" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_bus__channel msgid "Channel" msgstr "频道" #. module: bus #: model:ir.model,name:bus.model_bus_bus msgid "Communication Bus" msgstr "通讯总线" #. module: bus #: model:ir.model,name:bus.model_res_partner msgid "Contact" msgstr "联系人" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_bus__create_uid msgid "Created by" msgstr "创建者" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_bus__create_date msgid "Created on" msgstr "创建时间" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_bus__display_name #: model:ir.model.fields,field_description:bus.field_bus_presence__display_name msgid "Display Name" msgstr "显示名称" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_bus__id #: model:ir.model.fields,field_description:bus.field_bus_presence__id msgid "ID" msgstr "ID" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_presence__status #: model:ir.model.fields,field_description:bus.field_res_partner__im_status #: model:ir.model.fields,field_description:bus.field_res_users__im_status msgid "IM Status" msgstr "IM的状态" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_bus____last_update #: model:ir.model.fields,field_description:bus.field_bus_presence____last_update msgid "Last Modified on" msgstr "最后更改日" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_presence__last_poll msgid "Last Poll" msgstr "最后在线" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_presence__last_presence msgid "Last Presence" msgstr "最后登录" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_bus__write_uid msgid "Last Updated by" msgstr "最后更新者" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_bus__write_date msgid "Last Updated on" msgstr "更新时间" #. module: bus #: model:ir.model.fields,field_description:bus.field_bus_bus__message msgid "Message" msgstr "消息" #. module: bus #: model:ir.model.fields.selection,name:bus.selection__bus_presence__status__offline msgid "Offline" msgstr "离线" #. module: bus #: model:ir.model.fields.selection,name:bus.selection__bus_presence__status__online msgid "Online" msgstr "在线" #. module: bus #: model:ir.model,name:bus.model_bus_presence msgid "User Presence" msgstr "用户上线" #. module: bus #: model:ir.model,name:bus.model_res_users #: model:ir.model.fields,field_description:bus.field_bus_presence__user_id msgid "Users" msgstr "用户" #. module: bus #: code:addons/bus/controllers/main.py:0 #, python-format msgid "bus.Bus not available in test mode" msgstr "测试模式下Bus总线不可用"
{ "pile_set_name": "Github" }
@import 'mixins'; .footer { background-color: white; ul { padding: 0; list-style: none; li { } } a { color: #333; font-weight: 300; &:hover { text-decoration: underline; } } @media(max-width: 768px) { h3 { font-size: 18px; } ul { margin-left: 24px; } } .copy { padding: 30px 15px; font-size: 80%; } .center {display:table;width:97%;text-align:center;vertical-align: top;} .col2 {width:49.9%;} .col3 {width:26.99999%;} .col4 {width:22.99999%;} .col4, .col3, .col2, .col1 { padding: 15px; display:table-cell; text-align:left; @media(max-width:768px){ display:table-row; width:80%; margin-left: 64px; } } }
{ "pile_set_name": "Github" }
/************************************************************************************* * Copyright (c) 2011, 2012, 2013 James Talbut. * [email protected] * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * James Talbut - Initial implementation. ************************************************************************************/ package uk.co.spudsoft.birt.emitters.excel.tests; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.InputStream; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.eclipse.birt.core.exception.BirtException; import org.junit.Test; public class Groupings extends ReportRunner { @Test public void testGroupings() throws BirtException, IOException { InputStream inputStream = runAndRenderReport("Grouping.rptdesign", "xlsx"); assertNotNull(inputStream); try { XSSFWorkbook workbook = new XSSFWorkbook(inputStream); assertNotNull(workbook); assertEquals( 3, workbook.getNumberOfSheets() ); XSSFSheet sheet0 = workbook.getSheetAt(0); XSSFSheet sheet1 = workbook.getSheetAt(1); XSSFSheet sheet2 = workbook.getSheetAt(2); assertEquals( "HeaderAndFooter", sheet0.getSheetName()); int rowNum0 = 1; int rowNum1 = 1; int rowNum2 = 1; for( int i = 1; i < 9; ++i ) { System.out.println( "i==" + i ); assertEquals( "rowNum=" + rowNum0, 0, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum1, 0, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, 1, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); for( int j = 0; j < i; ++j) { assertEquals( "rowNum=" + rowNum0, 1, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); if( j < i - 1 ) { assertEquals( "rowNum=" + rowNum1, i == 1 ? 0 : 1, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, i == 1 ? 0 : 1, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); } } assertEquals( "rowNum=" + rowNum0, 1, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum1, 1, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, 0, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); } assertTrue( rowNum0 > 50 ); assertTrue( rowNum1 > 40 ); assertTrue( rowNum2 > 40 ); } finally { inputStream.close(); } } @Test public void testGroupingsBlockedByContext() throws BirtException, IOException { disableGrouping = Boolean.TRUE; InputStream inputStream = runAndRenderReport("Grouping.rptdesign", "xlsx"); disableGrouping = null; assertNotNull(inputStream); try { XSSFWorkbook workbook = new XSSFWorkbook(inputStream); assertNotNull(workbook); assertEquals( 3, workbook.getNumberOfSheets() ); XSSFSheet sheet0 = workbook.getSheetAt(0); XSSFSheet sheet1 = workbook.getSheetAt(1); XSSFSheet sheet2 = workbook.getSheetAt(2); assertEquals( "HeaderAndFooter", sheet0.getSheetName()); int rowNum0 = 1; int rowNum1 = 1; int rowNum2 = 1; for( int i = 1; i < 9; ++i ) { System.out.println( "i==" + i ); assertEquals( "rowNum=" + rowNum0, 0, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum1, 0, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, 0, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); for( int j = 0; j < i; ++j) { assertEquals( "rowNum=" + rowNum0, 0, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); if( j < i - 1 ) { assertEquals( "rowNum=" + rowNum1, 0, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, 0, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); } } assertEquals( "rowNum=" + rowNum0, 0, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum1, 0, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, 0, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); } assertTrue( rowNum0 > 50 ); assertTrue( rowNum1 > 40 ); assertTrue( rowNum2 > 40 ); } finally { inputStream.close(); } } @Test public void testGroupingsBlockedByReport() throws BirtException, IOException { InputStream inputStream = runAndRenderReport("GroupingDisabledAtReport.rptdesign", "xlsx"); assertNotNull(inputStream); try { XSSFWorkbook workbook = new XSSFWorkbook(inputStream); assertNotNull(workbook); assertEquals( 3, workbook.getNumberOfSheets() ); XSSFSheet sheet0 = workbook.getSheetAt(0); XSSFSheet sheet1 = workbook.getSheetAt(1); XSSFSheet sheet2 = workbook.getSheetAt(2); assertEquals( "HeaderAndFooter", sheet0.getSheetName()); int rowNum0 = 1; int rowNum1 = 1; int rowNum2 = 1; for( int i = 1; i < 9; ++i ) { System.out.println( "i==" + i ); assertEquals( "rowNum=" + rowNum0, 0, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum1, 0, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, 0, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); for( int j = 0; j < i; ++j) { assertEquals( "rowNum=" + rowNum0, 0, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); if( j < i - 1 ) { assertEquals( "rowNum=" + rowNum1, 0, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, 0, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); } } assertEquals( "rowNum=" + rowNum0, 0, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum1, 0, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, 0, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); } assertTrue( rowNum0 > 50 ); assertTrue( rowNum1 > 40 ); assertTrue( rowNum2 > 40 ); } finally { inputStream.close(); } } @Test public void testGroupingsBlockedByTable() throws BirtException, IOException { InputStream inputStream = runAndRenderReport("GroupingDisabledAtTable.rptdesign", "xlsx"); assertNotNull(inputStream); try { XSSFWorkbook workbook = new XSSFWorkbook(inputStream); assertNotNull(workbook); assertEquals( 3, workbook.getNumberOfSheets() ); XSSFSheet sheet0 = workbook.getSheetAt(0); XSSFSheet sheet1 = workbook.getSheetAt(1); XSSFSheet sheet2 = workbook.getSheetAt(2); assertEquals( "HeaderAndFooter", sheet0.getSheetName()); int rowNum0 = 1; int rowNum1 = 1; int rowNum2 = 1; for( int i = 1; i < 9; ++i ) { System.out.println( "i==" + i ); assertEquals( "rowNum=" + rowNum0, 0, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum1, 1, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, 0, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); for( int j = 0; j < i; ++j) { assertEquals( "rowNum=" + rowNum0, 0, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); if( j < i - 1 ) { assertEquals( "rowNum=" + rowNum1, i == 1 ? 0 : 1, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, 0, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); } } assertEquals( "rowNum=" + rowNum0, 0, sheet0.getRow( rowNum0++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum1, 0, sheet1.getRow( rowNum1++ ).getCTRow().getOutlineLevel() ); assertEquals( "rowNum=" + rowNum2, 0, sheet2.getRow( rowNum2++ ).getCTRow().getOutlineLevel() ); } assertTrue( rowNum0 > 50 ); assertTrue( rowNum1 > 40 ); assertTrue( rowNum2 > 40 ); } finally { inputStream.close(); } } }
{ "pile_set_name": "Github" }
package com.orientechnologies.orient.core.tx; import static org.junit.Assert.assertEquals; import com.orientechnologies.orient.core.db.ODatabaseType; import com.orientechnologies.orient.core.db.OrientDB; import com.orientechnologies.orient.core.db.OrientDBConfig; import com.orientechnologies.orient.core.db.document.ODatabaseDocument; import com.orientechnologies.orient.core.metadata.schema.OClass; import com.orientechnologies.orient.core.metadata.schema.OProperty; import com.orientechnologies.orient.core.metadata.schema.OType; import com.orientechnologies.orient.core.record.impl.ODocument; import com.orientechnologies.orient.core.sql.executor.OResultSet; import org.junit.After; import org.junit.Before; import org.junit.Test; /** Created by tglman on 12/04/17. */ public class TransactionQueryIndexTests { private OrientDB orientDB; private ODatabaseDocument database; @Before public void before() { orientDB = new OrientDB("embedded:", OrientDBConfig.defaultConfig()); orientDB.create("test", ODatabaseType.MEMORY); database = orientDB.open("test", "admin", "admin"); } @Test public void test() { OClass clazz = database.createClass("test"); OProperty prop = clazz.createProperty("test", OType.STRING); prop.createIndex(OClass.INDEX_TYPE.NOTUNIQUE); database.begin(); ODocument doc = database.newInstance("test"); doc.setProperty("test", "abcdefg"); database.save(doc); OResultSet res = database.query("select from Test where test='abcdefg' "); assertEquals(1L, res.stream().count()); res.close(); res = database.query("select from Test where test='aaaaa' "); System.out.println(res.getExecutionPlan().get().prettyPrint(0, 0)); assertEquals(0L, res.stream().count()); res.close(); } @Test public void test2() { OClass clazz = database.createClass("Test2"); clazz.createProperty("foo", OType.STRING); clazz.createProperty("bar", OType.STRING); clazz.createIndex("Test2.foo_bar", OClass.INDEX_TYPE.NOTUNIQUE, "foo", "bar"); database.begin(); ODocument doc = database.newInstance("Test2"); doc.setProperty("foo", "abcdefg"); doc.setProperty("bar", "abcdefg"); database.save(doc); OResultSet res = database.query("select from Test2 where foo='abcdefg' and bar = 'abcdefg' "); assertEquals(1L, res.stream().count()); res.close(); res = database.query("select from Test2 where foo='aaaaa' and bar = 'aaa'"); System.out.println(res.getExecutionPlan().get().prettyPrint(0, 0)); assertEquals(0L, res.stream().count()); res.close(); } @After public void after() { database.close(); orientDB.close(); } }
{ "pile_set_name": "Github" }
// Boost.TypeErasure library // // Copyright 2011 Steven Watanabe // // Distributed under the Boost Software License Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // $Id$ #ifndef BOOST_TYPE_ERASURE_CONCEPT_INTERFACE_HPP_INCLUDED #define BOOST_TYPE_ERASURE_CONCEPT_INTERFACE_HPP_INCLUDED namespace boost { namespace type_erasure { /** * The @ref concept_interface class can be specialized to * add behavior to an @ref any. An @ref any inherits from * all the relevant specializations of @ref concept_interface. * * @ref concept_interface can be specialized for either * primitive or composite concepts. If a concept @c C1 * contains another concept @c C2, then the library guarantees * that the specialization of @ref concept_interface for * @c C2 is a base class of the specialization for @c C1. * This means that @c C1 can safely override members of @c C2. * * @ref concept_interface may only be specialized for user-defined * concepts. The library owns the specializations of its own * built in concepts. * * \tparam Concept The concept that we're specializing * @ref concept_interface for. One of its * placeholders should be @c ID. * \tparam Base The base of this class. Specializations of @ref * concept_interface must inherit publicly from this type. * \tparam ID The placeholder representing this type. * \tparam Enable A dummy parameter that can be used for SFINAE. * * The metafunctions @ref derived, @ref rebind_any, and @ref as_param * (which can be applied to @c Base) are useful for determining the * argument and return types of functions defined in @ref concept_interface. * * For dispatching the function use \call. */ template<class Concept, class Base, class ID, class Enable = void> struct concept_interface : Base {}; } } #endif
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <Workspace version = "1.0"> <FileRef location = "self:"> </FileRef> </Workspace>
{ "pile_set_name": "Github" }
/* * Copyright The Dragonfly Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package fileutils import ( "github.com/dragonflyoss/Dragonfly/pkg/errortypes" "github.com/go-check/check" "gopkg.in/yaml.v2" ) type FsizeTestSuite struct { tmpDir string username string } func init() { check.Suite(&FsizeTestSuite{}) } func (suite *FsizeTestSuite) TestFsizeToString(c *check.C) { var cases = []struct { fsize Fsize fsizeStr string }{ {B, "1B"}, {1024 * B, "1KB"}, {3 * MB, "3MB"}, {0 * GB, "0B"}, } for _, ca := range cases { result := FsizeToString(ca.fsize) c.Assert(result, check.Equals, ca.fsizeStr) } } func (suite *FsizeTestSuite) TestStringToFSize(c *check.C) { var cases = []struct { fsizeStr string fsize Fsize errAssertFunc errortypes.ErrAssertFunc }{ {"0B", 0 * B, errortypes.IsNilError}, {"1B", B, errortypes.IsNilError}, {"10G", 10 * GB, errortypes.IsNilError}, {"1024", 1 * KB, errortypes.IsNilError}, {"-1", 0, errortypes.IsInvalidValue}, {"10b", 0, errortypes.IsInvalidValue}, } for _, ca := range cases { result, err := StringToFSize(ca.fsizeStr) c.Assert(ca.errAssertFunc(err), check.Equals, true) c.Assert(result, check.DeepEquals, ca.fsize) } } func (suite *FsizeTestSuite) TestMarshalYAML(c *check.C) { var cases = []struct { input Fsize output string }{ {5 * MB, "5MB\n"}, {1 * GB, "1GB\n"}, {1 * KB, "1KB\n"}, {1 * B, "1B\n"}, {0, "0B\n"}, } for _, ca := range cases { output, err := yaml.Marshal(ca.input) c.Check(err, check.IsNil) c.Check(string(output), check.Equals, ca.output) } } func (suite *FsizeTestSuite) TestUnMarshalYAML(c *check.C) { var cases = []struct { input string output Fsize }{ {"5M\n", 5 * MB}, {"1G\n", 1 * GB}, {"1B\n", 1 * B}, {"1\n", 1 * B}, {"1024\n", 1 * KB}, {"1K\n", 1 * KB}, } for _, ca := range cases { var output Fsize err := yaml.Unmarshal([]byte(ca.input), &output) c.Check(err, check.IsNil) c.Check(output, check.Equals, ca.output) } }
{ "pile_set_name": "Github" }
/* Copyright (C) 2005 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2.1 of the GNU Lesser General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write the Free Software Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston MA 02110-1301, USA. */ /* malloc_check.h */ /* A simple libdwarf-aware malloc checker. define WANT_LIBBDWARF_MALLOC_CHECK and rebuild libdwarf do make a checking-for-alloc-mistakes libdwarf. NOT recommended for production use. When defined, also add malloc_check.c to the list of files in Makefile. */ #undef WANT_LIBBDWARF_MALLOC_CHECK /*#define WANT_LIBBDWARF_MALLOC_CHECK 1 */ #ifdef WANT_LIBBDWARF_MALLOC_CHECK void dwarf_malloc_check_alloc_data(void * addr,unsigned char code); void dwarf_malloc_check_dealloc_data(void * addr,unsigned char code); void dwarf_malloc_check_complete(char *wheremsg); /* called at exit of app */ #else /* !WANT_LIBBDWARF_MALLOC_CHECK */ #define dwarf_malloc_check_alloc_data(a,b) /* nothing */ #define dwarf_malloc_check_dealloc_data(a,b) /* nothing */ #define dwarf_malloc_check_complete(a) /* nothing */ #endif /* WANT_LIBBDWARF_MALLOC_CHECK */
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2001-2011 Joel de Guzman Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #if !defined(BOOST_FUSION_IS_SEQUENCE_IMPL_09272006_0726) #define BOOST_FUSION_IS_SEQUENCE_IMPL_09272006_0726 #include <boost/fusion/support/config.hpp> #include <boost/mpl/bool.hpp> namespace boost { namespace fusion { struct boost_tuple_tag; namespace extension { template<typename Tag> struct is_sequence_impl; template<> struct is_sequence_impl<boost_tuple_tag> { template<typename Sequence> struct apply : mpl::true_ {}; }; } }} #endif
{ "pile_set_name": "Github" }
package volume // ---------------------------------------------------------------------------- // DO NOT EDIT THIS FILE // This file was generated by `swagger generate operation` // // See hack/generate-swagger-api.sh // ---------------------------------------------------------------------------- // VolumesCreateBody volumes create body // swagger:model VolumesCreateBody type VolumesCreateBody struct { // Name of the volume driver to use. // Required: true Driver string `json:"Driver"` // A mapping of driver options and values. These options are passed directly to the driver and are driver specific. // Required: true DriverOpts map[string]string `json:"DriverOpts"` // User-defined key/value metadata. // Required: true Labels map[string]string `json:"Labels"` // The new volume's name. If not specified, Docker generates a name. // Required: true Name string `json:"Name"` }
{ "pile_set_name": "Github" }
// // ZSBaseService.swift // zhuishushenqi // // Created by caonongyun on 2018/6/16. // Copyright © 2018年 QS. All rights reserved. // import Foundation import RxSwift import RxCocoa import RxAlamofire import Alamofire import HandyJSON public typealias ZSBaseCallback<T> = (T?)->Void public typealias ZSReaderBaseCallback<T> = (T)->Void public typealias ZSReaderTypeCallback<T,S> = (T,S)->Void class ZSBaseService { }
{ "pile_set_name": "Github" }
{ "en" : "Ingl&ecirc;s", "ru" : "Russo", "nl" : "Holand&ecirc;s", "fr" : "Franc&ecirc;s", "pt_br" : "Portugu&ecirc;s (Brasil) ", "Search": "Pesquisar", "All notes": "Todas as Notas", "Favourites": "Favoritos", "Favorite": "Favorito", "Trash": "Lixeira", "Notebooks": "Blocos de Notas", "Settings": "Configura&ccedil;&otilde;es", "About": "Sobre", "Save": "Salvar", "Save & Exit": "Salvar e Sair", "Cancel": "Cancelar", "Full screen": "Tela cheia", "Preview": "Pr&eacute;-visualizar", "Normal": "Normal", "Select notebook": "Selecionar bloco de notas", "Title": "T&iacute;tulo", "Submit": "Enviar", "Tags": "Tags", "Tag": "Tag", "Parent": "Pai", "Root": "Raiz", "Notebooks & tags": "Blocos de Notas & tags", "Notebook": "Bloco de Notas", "Restore": "Restaurar", "Delete": "Excluir", "New tag": "Nova tag", "Edit": "Editar", "Remove": "Remover", "Forever": "Para sempre", "No": "N&atilde;o", "Yes": "Sim", "Basic": "B&aacute;sico", "Cloud storage": "Armazenamento na nuvem", "Notes per page": "Notas por p&aacute;gina", "Default edit mode": "Modo de edi&ccedil;&atilde;o padr&atilde;o", "Fullscreen with preview": "Tela cheia com pr&eacute;-visualiza&ccedil;&atilde;o", "Use encryption": "Usar criptografia", "Encryption parameters": "Par&acirc;metros de criptografia", "Encryption Password": "Senha da criptografia", "Salt": "Sal", "Random": "Aleat&oacute;rio", "Key size": "Tamanho da chave", "Strengthen by a factor of": "Fator de refor&ccedil;o", "Authentication strength": "For&ccedil;a da autentica&ccedil;&atilde;o", "Unlock": "Desbloquear", "Your new encryption password": "Sua nova senha de criptografia", "Your old encryption password": "Sua antiga senha de criptografia", "Please wait until the encryption will be completed": "Por favor, aguarde at&eacute; que a criptografia seja conclu&iacute;da", "Shortcuts": "Atalhos", "Newer": "Anterior", "Older": "Pr&oacute;ximo", "Navigation": "Navega&ccedil;&atilde;o", "navigateTop": "Topo", "navigateBottom": "Rodap&eacute;", "Jump": "Pular", "jumpInbox": "Ir para a caixa de entrada", "jumpNotebook": "Ir para a lista de blocos de notas", "jumpFavorite": "Ir para as notas favoritas", "jumpRemoved": "Ir para as notas removidas", "Actions": "A&ccedil;&otilde;es", "actionsOpen": "Abrir", "actionsRotateStar": "Remover dos favoritos", "App": "App", "appCreateNote": "Criar nova nota", "appSearch": "Procurar nota", "appKeyboardHelp": "Ajuda com o teclado" }
{ "pile_set_name": "Github" }
.red { color: #e34343 !important; } .gray { color: #6a6a6a; } .green { color: #6DE08E; } .cold { color: #6DE08E; } .warm { color: #e34343; } .gridster > ul > li, .card, section { background-color:#223343; } .gridster li header, .card > header { background: #3a4f5c; color: #aaa; border-bottom: 1px solid #222; } /* label widget */ [data-type="label"].active { color: #0088CC !important; } polyline { stroke: #337ab7 !important; } /* circlemenu widget */ div[data-type="circlemenu"] > .circlemenu-wrapper > .circlemenu > li { background-color: #333; } div[data-type="circlemenu"] > .circlemenu-wrapper > .circlemenu li div[data-type="push"] { color: #697C90; } option {background-color: #ffffff;} /* spinner colors */ [data-type="spinner"]:not([data-color]) .spinner { color: #337ab7; } [data-type="spinner"]:not([data-background-color]) .spinner { background-color: #495C70 !important; } [data-type="spinner"]:not([data-background-color]) .spinner .levelRange { background-color: #0088CC !important; } [data-type="spinner"]:not([data-background-color]) .spinner .levelArea { background-color: #1B344A !important; } /* Slider colors */ .range-handle { background-color: #bcbcbc !important; } [data-type="slider"]:not([data-background-color]) .range-bar { background-color: #404040; } [data-type="slider"]:not([data-color]) .range-quantity { background-color: #0088CC !important; } /* symbol widget */ /* foreground on */ [data-type="symbol"]:not([data-colors]):not([data-on-color]):not([data-color]) .active i#fg { color: #0088CC !important; } /* foreground off */ [data-type="symbol"]:not([data-colors]):not([data-off-color]):not([data-color]) :not(.active) i#fg { color: #3a4f5c !important; } /* switch widget */ /* background on */ [data-type="switch"]:not([data-background-colors]):not([data-on-background-color]):not([data-background-color]) .active i#bg, [data-type="dimmer"]:not([data-background-colors]):not([data-on-background-color]):not([data-background-color]) .active i#bg, [data-type="button"]:not([data-background-colors]):not([data-on-background-color]):not([data-background-color]) .active i#bg { color: #0088CC !important; } /* background off */ [data-type="switch"]:not([data-background-colors]):not([data-off-background-color]):not([data-background-color]) :not(.active) i#bg, [data-type="dimmer"]:not([data-background-colors]):not([data-off-background-color]):not([data-background-color]) :not(.active) i#bg, [data-type="button"]:not([data-background-colors]):not([data-off-background-color]):not([data-background-color]) :not(.active) i#bg { color: #495C70 !important; } /* switch widget invert */ /* foreground on */ [data-type="switch"]:not([data-colors]):not([data-on-color]):not([data-color]).invert .active i#fg, [data-type="dimmer"]:not([data-colors]):not([data-on-color]):not([data-color]).invert .active i#fg, [data-type="button"]:not([data-colors]):not([data-on-color]):not([data-color]).invert .active i#fg { color: #0088CC !important; } /* foreground off */ [data-type="switch"]:not([data-colors]):not([data-on-color]):not([data-color]).invert :not(.active) i#fg, [data-type="dimmer"]:not([data-colors]):not([data-on-color]):not([data-color]).invert :not(.active) i#fg, [data-type="button"]:not([data-colors]):not([data-on-color]):not([data-color]).invert :not(.active) i#fg { color: #495C70 !important; } /* background on */ [data-type="switch"]:not([data-background-colors]):not([data-on-background-color]):not([data-background-color]).invert .active i#bg, [data-type="dimmer"]:not([data-background-colors]):not([data-on-background-color]):not([data-background-color]).invert .active i#bg, [data-type="button"]:not([data-background-colors]):not([data-on-background-color]):not([data-background-color]).invert .active i#bg { color: #2B445A !important; } /* background off */ [data-type="switch"]:not([data-background-colors]):not([data-off-background-color]):not([data-background-color]).invert :not(.active) i#bg, [data-type="dimmer"]:not([data-background-colors]):not([data-off-background-color]):not([data-background-color]).invert :not(.active) i#bg, [data-type="button"]:not([data-background-colors]):not([data-off-background-color]):not([data-background-color]).invert :not(.active) i#bg { color: #2B445A !important; } /* push widget */ /* foreground on */ [data-type="push"]:not([data-colors]):not([data-on-color]):not([data-color]) .active i#fg { color: #0088CC !important; } /* foreground off */ [data-type="push"]:not([data-colors]):not([data-on-color]):not([data-color]) :not(.active) i#fg { color: #495C70 !important; } /* background on */ [data-type="push"]:not([data-background-colors]):not([data-on-background-color]):not([data-background-color]) .active i#bg { color: #0088CC !important; } /* background off */ [data-type="push"]:not([data-background-colors]):not([data-off-background-color]):not([data-background-color]) :not(.active) i#bg { color: #495C70 !important; } /* pagebutton widget */ /* foreground on */ [data-type="pagebutton"]:not([data-colors]):not([data-on-color]):not([data-color]) .active i#fg { color: rgba(206, 206, 206, 0.6) !important; } /* foreground off */ [data-type="pagebutton"]:not([data-colors]):not([data-off-color]):not([data-color]) :not(.active) i#fg { color: #4d6879 !important; } /* background on */ [data-type="pagebutton"]:not([data-background-colors]):not([data-on-background-color]):not([data-background-color]) .active i#bg { color: #495C70 !important; } /* background off */ [data-type="pagebutton"]:not([data-background-colors]):not([data-off-background-color]):not([data-background-color]) :not(.active) i#bg { color: rgba(21, 21, 21, 0.2) !important; } /* pseudo classes for canvas painted widgets read by ftui.getStyle() in init and reinit function */ .thermostat{background-color:#1B344A;color:#667d94;} .thermostat.actual{color:#aaa;} .thermostat.nominal{color:#aaa;} .thermostat.min{color:#0088CC;} .thermostat.max{color:#f71525;} .homestatus{background-color:#667d94;color:#0088CC;} .homestatus.min{color:#eee;} .homestatus.max{color:#495C70;} .volume.handle{color:#0088CC;} .volume{background-color:#1B344A;color:#667d94;} .volume.nominal{color:#444;} .wind_direction.handle{color:#0088CC;} .wind_direction{background-color:#1B344A;color:#555;} .wind_direction.nominal{color:#444;} .checkbox.on {color:#fff;background-color:#0088CC;} .checkbox.off {color:#fff;background-color:#999;} .playstream.on {color:#fff;background-color:#0088CC;} .playstream.off {color:#fff;background-color:#999;}
{ "pile_set_name": "Github" }
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing e B { struct A : A<T where B : e, f: a { extension NSData { let v: Int = compose(e, f: a = compose(e: (f.c { b = c { { (e, f: e: A? { struct g<T : AnyObject.h = b(f.dynamicType)" } } } Any) let f = compose(e, f: e, f.c { class A { class case c, let
{ "pile_set_name": "Github" }
tab-size:0
{ "pile_set_name": "Github" }
-- :api: templates-exist :request: IndexTemplatesExistRequest :response: Boolean -- [id="{upid}-{api}"] === Templates Exist API [id="{upid}-{api}-request"] ==== Templates Exist Request The Templates Exist API uses +{request}+ as its request object. One or more index template names can be provided at construction. ["source","java",subs="attributes,callouts,macros"] -------------------------------------------------- include-tagged::{doc-tests-file}[{api}-request] -------------------------------------------------- <1> A single index template name <2> Multiple index template names <3> An index template name using wildcard ==== Optional arguments ["source","java",subs="attributes,callouts,macros"] -------------------------------------------------- include-tagged::{doc-tests-file}[{api}-request-optionals] -------------------------------------------------- <1> If `true`, reads templates from the node's local cluster state. Otherwise reads from the cluster state of the elected master node <2> Timeout to connect to the master node as a `TimeValue` <3> Timeout to connect to the master node as a `String` include::../execution.asciidoc[] [id="{upid}-{api}-response"] ==== Response The response is a +{response}+ value, `true` if any of the request's template names match existing templates and `false` otherwise
{ "pile_set_name": "Github" }
// Copyright 2015 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package htmlindex import ( "testing" "golang.org/x/text/encoding" "golang.org/x/text/encoding/charmap" "golang.org/x/text/encoding/internal/identifier" "golang.org/x/text/encoding/unicode" "golang.org/x/text/language" ) func TestGet(t *testing.T) { for i, tc := range []struct { name string canonical string err error }{ {"utf-8", "utf-8", nil}, {" utf-8 ", "utf-8", nil}, {" l5 ", "windows-1254", nil}, {"latin5 ", "windows-1254", nil}, {"latin 5", "", errInvalidName}, {"latin-5", "", errInvalidName}, } { enc, err := Get(tc.name) if err != tc.err { t.Errorf("%d: error was %v; want %v", i, err, tc.err) } if err != nil { continue } if got, err := Name(enc); got != tc.canonical { t.Errorf("%d: Name(Get(%q)) = %q; want %q (%v)", i, tc.name, got, tc.canonical, err) } } } func TestTables(t *testing.T) { for name, index := range nameMap { got, err := Get(name) if err != nil { t.Errorf("%s:err: expected non-nil error", name) } if want := encodings[index]; got != want { t.Errorf("%s:encoding: got %v; want %v", name, got, want) } mib, _ := got.(identifier.Interface).ID() if mibMap[mib] != index { t.Errorf("%s:mibMab: got %d; want %d", name, mibMap[mib], index) } } } func TestName(t *testing.T) { for i, tc := range []struct { desc string enc encoding.Encoding name string err error }{{ "defined encoding", charmap.ISO8859_2, "iso-8859-2", nil, }, { "defined Unicode encoding", unicode.UTF16(unicode.BigEndian, unicode.IgnoreBOM), "utf-16be", nil, }, { "undefined Unicode encoding in HTML standard", unicode.UTF16(unicode.BigEndian, unicode.UseBOM), "", errUnsupported, }, { "undefined other encoding in HTML standard", charmap.CodePage437, "", errUnsupported, }, { "unknown encoding", encoding.Nop, "", errUnknown, }} { name, err := Name(tc.enc) if name != tc.name || err != tc.err { t.Errorf("%d:%s: got %q, %v; want %q, %v", i, tc.desc, name, err, tc.name, tc.err) } } } func TestLanguageDefault(t *testing.T) { for _, tc := range []struct{ tag, want string }{ {"und", "windows-1252"}, // The default value. {"ar", "windows-1256"}, {"ba", "windows-1251"}, {"be", "windows-1251"}, {"bg", "windows-1251"}, {"cs", "windows-1250"}, {"el", "iso-8859-7"}, {"et", "windows-1257"}, {"fa", "windows-1256"}, {"he", "windows-1255"}, {"hr", "windows-1250"}, {"hu", "iso-8859-2"}, {"ja", "shift_jis"}, {"kk", "windows-1251"}, {"ko", "euc-kr"}, {"ku", "windows-1254"}, {"ky", "windows-1251"}, {"lt", "windows-1257"}, {"lv", "windows-1257"}, {"mk", "windows-1251"}, {"pl", "iso-8859-2"}, {"ru", "windows-1251"}, {"sah", "windows-1251"}, {"sk", "windows-1250"}, {"sl", "iso-8859-2"}, {"sr", "windows-1251"}, {"tg", "windows-1251"}, {"th", "windows-874"}, {"tr", "windows-1254"}, {"tt", "windows-1251"}, {"uk", "windows-1251"}, {"vi", "windows-1258"}, {"zh-hans", "gb18030"}, {"zh-hant", "big5"}, // Variants and close approximates of the above. {"ar_EG", "windows-1256"}, {"bs", "windows-1250"}, // Bosnian Latin maps to Croatian. // Use default fallback in case of miss. {"nl", "windows-1252"}, } { if got := LanguageDefault(language.MustParse(tc.tag)); got != tc.want { t.Errorf("LanguageDefault(%s) = %s; want %s", tc.tag, got, tc.want) } } }
{ "pile_set_name": "Github" }
import Foundation extension SourceCode { func optional<T>(decode: (SourceCode) throws -> T) rethrows -> T? { do { return try decode(self) } catch ParseError.missingKey { return nil } } }
{ "pile_set_name": "Github" }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using Microsoft.TestCommon; namespace Microsoft.Web.Mvc.Test { public class ModelCopierTest { [Fact] public void CopyCollection_FromIsNull_DoesNothing() { // Arrange int[] from = null; List<int> to = new List<int> { 1, 2, 3 }; // Act ModelCopier.CopyCollection(from, to); // Assert Assert.Equal(new[] { 1, 2, 3 }, to.ToArray()); } [Fact] public void CopyCollection_ToIsImmutable_DoesNothing() { // Arrange List<int> from = new List<int> { 1, 2, 3 }; ICollection<int> to = new ReadOnlyCollection<int>(new[] { 4, 5, 6 }); // Act ModelCopier.CopyCollection(from, to); // Assert Assert.Equal(new[] { 1, 2, 3 }, from.ToArray()); Assert.Equal(new[] { 4, 5, 6 }, to.ToArray()); } [Fact] public void CopyCollection_ToIsMmutable_ClearsAndCopies() { // Arrange List<int> from = new List<int> { 1, 2, 3 }; ICollection<int> to = new List<int> { 4, 5, 6 }; // Act ModelCopier.CopyCollection(from, to); // Assert Assert.Equal(new[] { 1, 2, 3 }, from.ToArray()); Assert.Equal(new[] { 1, 2, 3 }, to.ToArray()); } [Fact] public void CopyCollection_ToIsNull_DoesNothing() { // Arrange List<int> from = new List<int> { 1, 2, 3 }; List<int> to = null; // Act ModelCopier.CopyCollection(from, to); // Assert Assert.Equal(new[] { 1, 2, 3 }, from.ToArray()); } [Fact] public void CopyModel_ExactTypeMatch_Copies() { // Arrange GenericModel<int> from = new GenericModel<int> { TheProperty = 21 }; GenericModel<int> to = new GenericModel<int> { TheProperty = 42 }; // Act ModelCopier.CopyModel(from, to); // Assert Assert.Equal(21, from.TheProperty); Assert.Equal(21, to.TheProperty); } [Fact] public void CopyModel_FromIsNull_DoesNothing() { // Arrange GenericModel<int> from = null; GenericModel<int> to = new GenericModel<int> { TheProperty = 42 }; // Act ModelCopier.CopyModel(from, to); // Assert Assert.Equal(42, to.TheProperty); } [Fact] public void CopyModel_LiftedTypeMatch_ActualValueIsNotNull_Copies() { // Arrange GenericModel<int?> from = new GenericModel<int?> { TheProperty = 21 }; GenericModel<int> to = new GenericModel<int> { TheProperty = 42 }; // Act ModelCopier.CopyModel(from, to); // Assert Assert.Equal(21, from.TheProperty); Assert.Equal(21, to.TheProperty); } [Fact] public void CopyModel_LiftedTypeMatch_ActualValueIsNull_DoesNothing() { // Arrange GenericModel<int?> from = new GenericModel<int?> { TheProperty = null }; GenericModel<int> to = new GenericModel<int> { TheProperty = 42 }; // Act ModelCopier.CopyModel(from, to); // Assert Assert.Null(from.TheProperty); Assert.Equal(42, to.TheProperty); } [Fact] public void CopyModel_NoTypeMatch_DoesNothing() { // Arrange GenericModel<int> from = new GenericModel<int> { TheProperty = 21 }; GenericModel<long> to = new GenericModel<long> { TheProperty = 42 }; // Act ModelCopier.CopyModel(from, to); // Assert Assert.Equal(21, from.TheProperty); Assert.Equal(42, to.TheProperty); } [Fact] public void CopyModel_SubclassedTypeMatch_Copies() { // Arrange string originalModel = "Hello, world!"; GenericModel<string> from = new GenericModel<string> { TheProperty = originalModel }; GenericModel<object> to = new GenericModel<object> { TheProperty = 42 }; // Act ModelCopier.CopyModel(from, to); // Assert Assert.Same(originalModel, from.TheProperty); Assert.Same(originalModel, to.TheProperty); } [Fact] public void CopyModel_ToDoesNotContainProperty_DoesNothing() { // Arrange GenericModel<int> from = new GenericModel<int> { TheProperty = 21 }; OtherGenericModel<int> to = new OtherGenericModel<int> { SomeOtherProperty = 42 }; // Act ModelCopier.CopyModel(from, to); // Assert Assert.Equal(21, from.TheProperty); Assert.Equal(42, to.SomeOtherProperty); } [Fact] public void CopyModel_ToIsNull_DoesNothing() { // Arrange GenericModel<int> from = new GenericModel<int> { TheProperty = 21 }; GenericModel<int> to = null; // Act ModelCopier.CopyModel(from, to); // Assert Assert.Equal(21, from.TheProperty); } [Fact] public void CopyModel_ToIsReadOnly_DoesNothing() { // Arrange GenericModel<int> from = new GenericModel<int> { TheProperty = 21 }; ReadOnlyGenericModel<int> to = new ReadOnlyGenericModel<int>(42); // Act ModelCopier.CopyModel(from, to); // Assert Assert.Equal(21, from.TheProperty); Assert.Equal(42, to.TheProperty); } private class GenericModel<T> { public T TheProperty { get; set; } } private class OtherGenericModel<T> { public T SomeOtherProperty { get; set; } } private class ReadOnlyGenericModel<T> { public ReadOnlyGenericModel(T propertyValue) { TheProperty = propertyValue; } public T TheProperty { get; private set; } } } }
{ "pile_set_name": "Github" }
require 'spec_helper' require 'ruby_event_store' require 'ruby_event_store/spec/event_repository_lint' module RailsEventStoreActiveRecord class EventRepository class SpecHelper < RubyEventStore::EventRepositoryHelper def supports_concurrent_auto? !ENV['DATABASE_URL'].include?("sqlite") end def supports_concurrent_any? !ENV['DATABASE_URL'].include?("sqlite") end def has_connection_pooling? true end def connection_pool_size ActiveRecord::Base.connection.pool.size end def cleanup_concurrency_test ActiveRecord::Base.connection_pool.disconnect! end end end RSpec.describe EventRepository do include_examples :event_repository let(:repository) { EventRepository.new(serializer: YAML) } let(:helper) { EventRepository::SpecHelper.new } include SchemaHelper around(:each) do |example| begin establish_database_connection load_database_schema example.run ensure drop_database end end let(:specification) do RubyEventStore::Specification.new( RubyEventStore::SpecificationReader.new( repository, RubyEventStore::Mappers::NullMapper.new ) ) end specify "does not confuse all with GLOBAL_STREAM" do repository.append_to_stream( RubyEventStore::SRecord.new(event_id: "fbce0b3d-40e3-4d1d-90a1-901f1ded5a4a"), RubyEventStore::Stream.new('all'), RubyEventStore::ExpectedVersion.none ) repository.append_to_stream( RubyEventStore::SRecord.new(event_id: "a1b49edb-7636-416f-874a-88f94b859bef"), RubyEventStore::Stream.new(RubyEventStore::GLOBAL_STREAM), RubyEventStore::ExpectedVersion.any ) expect(repository.read(specification.result)) .to(contains_ids(%w[fbce0b3d-40e3-4d1d-90a1-901f1ded5a4a a1b49edb-7636-416f-874a-88f94b859bef])) expect(repository.read(specification.stream('all').result)) .to(contains_ids(%w[fbce0b3d-40e3-4d1d-90a1-901f1ded5a4a])) end specify "using preload()" do repository.append_to_stream([ event0 = RubyEventStore::SRecord.new, event1 = RubyEventStore::SRecord.new, ], RubyEventStore::Stream.new('stream'), RubyEventStore::ExpectedVersion.auto) c1 = count_queries{ repository.read(specification.limit(2).result) } expect(c1).to eq(1) c2 = count_queries{ repository.read(specification.limit(2).backward.result) } expect(c2).to eq(1) c3 = count_queries{ repository.read(specification.stream("stream").result) } expect(c3).to eq(2) c4 = count_queries{ repository.read(specification.stream("stream").backward.result) } expect(c4).to eq(2) c5 = count_queries{ repository.read(specification.stream("stream").limit(2).result) } expect(c5).to eq(2) c6 = count_queries{ repository.read(specification.stream("stream").limit(2).backward.result) } expect(c6).to eq(2) end specify "explicit sorting by position rather than accidental" do e1 = Event.create!( event_id: u1 = SecureRandom.uuid, data: '{}', metadata: '{}', event_type: "TestDomainEvent", ) e2 = Event.create!( event_id: u2 = SecureRandom.uuid, data: '{}', metadata: '{}', event_type: "TestDomainEvent", ) e3 = Event.create!( event_id: u3 = SecureRandom.uuid, data: '{}', metadata: '{}', event_type: "TestDomainEvent", ) EventInStream.create!( stream: "stream", position: 1, event_id: e2.event_id, ) EventInStream.create!( stream: "stream", position: 0, event_id: e1.event_id, ) EventInStream.create!( stream: "stream", position: 2, event_id: e3.event_id, ) ActiveRecord::Schema.define do self.verbose = false remove_index :event_store_events_in_streams, [:stream, :position] end expect(repository.read(specification.stream("stream").limit(3).result).map(&:event_id)).to eq([u1,u2,u3]) expect(repository.read(specification.stream("stream").result).map(&:event_id)).to eq([u1,u2,u3]) expect(repository.read(specification.stream("stream").backward.limit(3).result).map(&:event_id)).to eq([u3,u2,u1]) expect(repository.read(specification.stream("stream").backward.result).map(&:event_id)).to eq([u3,u2,u1]) end specify "explicit sorting by id rather than accidental for all events" do e1 = Event.create!( event_id: u1 = SecureRandom.uuid, data: '{}', metadata: '{}', event_type: "TestDomainEvent", ) e2 = Event.create!( event_id: u2 = SecureRandom.uuid, data: '{}', metadata: '{}', event_type: "TestDomainEvent", ) e3 = Event.create!( event_id: u3 = SecureRandom.uuid, data: '{}', metadata: '{}', event_type: "TestDomainEvent", ) EventInStream.create!( stream: "all", position: 1, event_id: e1.event_id, ) EventInStream.create!( stream: "all", position: 0, event_id: e2.event_id, ) EventInStream.create!( stream: "all", position: 2, event_id: e3.event_id, ) expect(repository.read(specification.limit(3).result).map(&:event_id)).to eq([u1,u2,u3]) expect(repository.read(specification.limit(3).backward.result).map(&:event_id)).to eq([u3,u2,u1]) end specify do e1 = Event.create!( event_id: u1 = SecureRandom.uuid, data: '{}', metadata: '{}', event_type: "TestDomainEvent", ) e2 = Event.create!( event_id: u2 = SecureRandom.uuid, data: '{}', metadata: '{}', event_type: "TestDomainEvent", ) e3 = Event.create!( event_id: u3 = SecureRandom.uuid, data: '{}', metadata: '{}', event_type: "TestDomainEvent", ) EventInStream.create!( stream: "all", position: 1, event_id: e1.event_id, ) EventInStream.create!( stream: "all", position: 0, event_id: e2.event_id, ) EventInStream.create!( stream: "all", position: 2, event_id: e3.event_id, ) expect(repository.read(specification.to(u3).limit(3).result).map(&:event_id)).to eq([u1,u2]) expect(repository.read(specification.to(u1).limit(3).backward.result).map(&:event_id)).to eq([u3,u2]) end specify do expect_query(/SELECT.*FROM.*event_store_events.*ORDER BY .*event_store_events.*id.* ASC LIMIT.*/) do repository.read(specification.limit(3).result) end end specify do expect_query(/SELECT.*FROM.*event_store_events.*ORDER BY .*event_store_events.*id.* DESC LIMIT.*/) do repository.read(specification.limit(3).backward.result) end end specify do expect_query(/SELECT.*FROM.*event_store_events_in_streams.*ORDER BY .*event_store_events_in_streams.*position.* ASC, .*event_store_events_in_streams.*id.* ASC LIMIT.*/) do repository.read(specification.stream('stream').limit(3).result) end end specify do expect_query(/SELECT.*FROM.*event_store_events_in_streams.*ORDER BY .*event_store_events_in_streams.*position.* DESC, .*event_store_events_in_streams.*id.* DESC LIMIT.*/) do repository.read(specification.stream('stream').limit(3).backward.result) end end specify "explicit ORDER BY position" do expect_query(/SELECT.*FROM.*event_store_events_in_streams.*WHERE.*event_store_events_in_streams.*stream.*=.*ORDER BY position DESC LIMIT.*/) do repository.append_to_stream([ RubyEventStore::SRecord.new, ], RubyEventStore::Stream.new('stream'), RubyEventStore::ExpectedVersion.auto) end end specify "nested transaction - events still not persisted if append failed" do repository.append_to_stream([ event = RubyEventStore::SRecord.new(event_id: SecureRandom.uuid), ], RubyEventStore::Stream.new('stream'), RubyEventStore::ExpectedVersion.none) ActiveRecord::Base.transaction do expect do repository.append_to_stream([ RubyEventStore::SRecord.new( event_id: '9bedf448-e4d0-41a3-a8cd-f94aec7aa763' ), ], RubyEventStore::Stream.new('stream'), RubyEventStore::ExpectedVersion.none) end.to raise_error(RubyEventStore::WrongExpectedEventVersion) expect(repository.has_event?('9bedf448-e4d0-41a3-a8cd-f94aec7aa763')).to be_falsey expect(repository.read(specification.limit(2).result).to_a).to eq([event]) end expect(repository.has_event?('9bedf448-e4d0-41a3-a8cd-f94aec7aa763')).to be_falsey expect(repository.read(specification.limit(2).result).to_a).to eq([event]) end specify "limited query when looking for unexisting events during linking" do expect_query(/SELECT.*event_store_events.*id.*FROM.*event_store_events.*WHERE.*event_store_events.*id.*=.*/) do expect do repository.link_to_stream('72922e65-1b32-4e97-8023-03ae81dd3a27', "flow", RubyEventStore::ExpectedVersion.none) end.to raise_error(RubyEventStore::EventNotFound) end end class FillInRepository < EventRepository def fill_ids(in_stream) in_stream.each.with_index.map do |is, index| is[:id] = index + 987_654_321 is[:id] += 3 if is[:stream] == "whoo" end end end specify 'fill_ids in append_to_stream' do repository = FillInRepository.new(serializer: YAML) repository.append_to_stream( [event = RubyEventStore::SRecord.new], RubyEventStore::Stream.new('stream'), RubyEventStore::ExpectedVersion.any ) expect(EventInStream.find(987_654_321).stream).to eq("stream") end specify 'fill_ids in link_to_stream' do repository = FillInRepository.new(serializer: YAML) repository.append_to_stream( [event = RubyEventStore::SRecord.new], RubyEventStore::Stream.new('stream'), RubyEventStore::ExpectedVersion.any ) repository.link_to_stream( [event.event_id], RubyEventStore::Stream.new("whoo"), RubyEventStore::ExpectedVersion.any ) expect(EventInStream.find(987_654_321).stream).to eq("stream") expect(EventInStream.find(987_654_324).stream).to eq("whoo") end specify 'read in batches forward' do events = Array.new(200) { RubyEventStore::SRecord.new } repository.append_to_stream( events, RubyEventStore::Stream.new(RubyEventStore::GLOBAL_STREAM), RubyEventStore::ExpectedVersion.any ) batches = repository.read(specification.forward.limit(101).in_batches.result).to_a expect(batches.size).to eq(2) expect(batches[0].size).to eq(100) expect(batches[1].size).to eq(1) expect(batches[0]).to eq(events[0..99]) expect(batches[1]).to eq([events[100]]) end specify 'read in batches backward' do events = Array.new(200) { RubyEventStore::SRecord.new } repository.append_to_stream( events, RubyEventStore::Stream.new(RubyEventStore::GLOBAL_STREAM), RubyEventStore::ExpectedVersion.any ) batches = repository.read(specification.backward.limit(101).in_batches.result).to_a expect(batches.size).to eq(2) expect(batches[0].size).to eq(100) expect(batches[1].size).to eq(1) expect(batches[0]).to eq(events[100..-1].reverse) expect(batches[1]).to eq([events[99]]) end specify 'use default models' do repository = EventRepository.new(serializer: YAML) expect(repository.instance_variable_get(:@event_klass)).to be(Event) expect(repository.instance_variable_get(:@stream_klass)).to be(EventInStream) end specify 'allows custom base class' do repository = EventRepository.new(model_factory: WithAbstractBaseClass.new(CustomApplicationRecord), serializer: YAML) expect(repository.instance_variable_get(:@event_klass).ancestors).to include(CustomApplicationRecord) expect(repository.instance_variable_get(:@stream_klass).ancestors).to include(CustomApplicationRecord) end specify 'reading/writting works with custom base class' do repository = EventRepository.new(model_factory: WithAbstractBaseClass.new(CustomApplicationRecord), serializer: YAML) repository.append_to_stream( [event = RubyEventStore::SRecord.new], RubyEventStore::Stream.new(RubyEventStore::GLOBAL_STREAM), RubyEventStore::ExpectedVersion.any ) reader = RubyEventStore::SpecificationReader.new(repository, RubyEventStore::Mappers::NullMapper.new) specification = RubyEventStore::Specification.new(reader) read_event = repository.read(specification.result).first expect(read_event).to eq(event) end specify 'timestamps not overwritten by activerecord-import' do repository.append_to_stream( [event = RubyEventStore::SRecord.new(timestamp: time = Time.at(0))], RubyEventStore::Stream.new(RubyEventStore::GLOBAL_STREAM), RubyEventStore::ExpectedVersion.any ) event_ = repository.read(specification.result).first expect(event_.timestamp).to eq(time) end def cleanup_concurrency_test ActiveRecord::Base.connection_pool.disconnect! end def verify_conncurency_assumptions expect(ActiveRecord::Base.connection.pool.size).to eq(5) end def additional_limited_concurrency_for_auto_check positions = RailsEventStoreActiveRecord::EventInStream .where(stream: "stream") .order("position ASC") .map(&:position) expect(positions).to eq((0..positions.size-1).to_a) end private def count_queries(&block) count = 0 counter_f = ->(_name, _started, _finished, _unique_id, payload) { unless %w[ CACHE SCHEMA ].include?(payload[:name]) count += 1 end } ActiveSupport::Notifications.subscribed(counter_f, "sql.active_record", &block) count end def expect_query(match, &block) count = 0 counter_f = ->(_name, _started, _finished, _unique_id, payload) { count +=1 if match === payload[:sql] } ActiveSupport::Notifications.subscribed(counter_f, "sql.active_record", &block) expect(count).to eq(1) end end end
{ "pile_set_name": "Github" }
&pinctrl { usart1_pins_a: usart1@0 { u-boot,dm-pre-reloc; pins1 { u-boot,dm-pre-reloc; }; pins2 { u-boot,dm-pre-reloc; }; }; fmc_pins: fmc@0 { u-boot,dm-pre-reloc; pins { u-boot,dm-pre-reloc; }; }; }; &fmc { bank1: bank@0 { u-boot,dm-pre-reloc; }; };
{ "pile_set_name": "Github" }
Protected directory. username: user password: pass
{ "pile_set_name": "Github" }
# Contributing to Heroic Thanks for taking the time to contribute! The following is a set of guidelines for contributing to Heroic. ## Ground Rules * Please open an [issue](https://github.com/spotify/heroic/issues) for discussion before submitting any major changes. * Be sure to add a title and description to your PR explaining the reason for the change. Please include some context behind a bug or issue you ran in to, or your use case and why you need a particular feature added. If you're unsure about formatting, you can follow [this article](https://medium.com/@steveamaza/how-to-write-a-proper-git-commit-message-e028865e5791) which dives into writing a proper commit message. * Include tests for any large changes. Read here to learn how to run the [tests](https://github.com/spotify/heroic#testing). * Include new or updated documentation in the related PR. ## Your First Contribution Unsure where to begin contributing to Heroic? You can start by browsing through these [starter issues](https://github.com/spotify/heroic/labels/level%3Astarter). Working on your first Pull Request? You can learn how from this free series, [How to Contribute to an Open Source Project on GitHub](https://egghead.io/series/how-to-contribute-to-an-open-source-project-on-github). ## Getting started We use GitHub to manage issues. You can follow along and create issues [here](https://github.com/spotify/heroic/issues). ### Create your own fork of the code ### Code style * Make sure you format the code using the provided formatter in [idea](https://github.com/spotify/heroic/blob/master/idea). Even if you disagree with the way it is formatted, consistency is more important. For special cases, see [Bypassing Validation](https://github.com/spotify/heroic#bypassing-validation). ### Commit message conventions * If possible, limit your changes to one module per commit. If you add new, or modify existing classes. Keep that change to a single commit while maintaining backwards compatible behaviour. Deprecate any old APIs as appropriate with `@Deprecated` and add documentation for how to use the new API. * The first line of the commit should be formatted with `[module1,module2] my message`. * `module1` and `module2` are paths to the modules affected with any `heroic-` prefix stripped. So if your change affects `heroic-core` and `metric/bigtable`, the message should say `[core,metric/bigtable] did x to y`. * If more than _3 modules_ are affected by a commit, use `[all]`. For other cases, adapt to the format of existing commit messages. ### Testing * Before setting up a pull request, run the comprehensive test suite as specified in [Testing](#testing). * PRs with failing tests will not be merged. [A Guide to Dagger 2](docs/guide-to-dagger2.md) [Using IDEA](idea/README.md) ## How to report a bug Please open an [issue under the bug label](https://github.com/spotify/heroic/issues?q=is%3Aopen+is%3Aissue+label%3Atype%3Abug) and we will prioritize it based on the severity. ## How to suggest a feature or enhancement If you find yourself wishing for a feature that doesn't exist in Heroic, you are probably not alone. Open an issue on our [issues list](https://github.com/spotify/heroic/issues) on GitHub which describes the feature you would like to see, why you need it, and how it should work. ## Code of Conduct This project adheres to the [Open Code of Conduct](https://github.com/spotify/code-of-conduct/blob/master/code-of-conduct.md). By participating, you are expected to honor this code.
{ "pile_set_name": "Github" }
% Latex header for doxygen 1.8.3.1 \documentclass{book} \usepackage[a4paper,top=2.5cm,bottom=2.5cm,left=2.5cm,right=2.5cm]{geometry} \usepackage{makeidx} \usepackage{natbib} \usepackage{graphicx} \usepackage{multicol} \usepackage{float} \usepackage{listings} \usepackage{color} \usepackage{ifthen} \usepackage[table]{xcolor} \usepackage{textcomp} \usepackage{alltt} \usepackage{ifpdf} \ifpdf \usepackage[pdftex, pagebackref=true, colorlinks=true, linkcolor=blue, unicode ]{hyperref} \else \usepackage[ps2pdf, pagebackref=true, colorlinks=true, linkcolor=blue, unicode ]{hyperref} \usepackage{pspicture} \fi \usepackage[utf8]{inputenc} \usepackage{mathptmx} \usepackage[scaled=.90]{helvet} \usepackage{courier} \usepackage{sectsty} \usepackage{amssymb} \usepackage[titles]{tocloft} \usepackage{doxygen} \usepackage{fancyhdr} \pagestyle{fancy} \lstset{language=C++,inputencoding=utf8,basicstyle=\footnotesize,breaklines=true,breakatwhitespace=true,tabsize=4,numbers=left } \makeindex \setcounter{tocdepth}{3} \renewcommand{\footrulewidth}{0.4pt} \renewcommand{\familydefault}{\sfdefault} \hfuzz=15pt \setlength{\emergencystretch}{15pt} \hbadness=750 \tolerance=750 \begin{document} \hypersetup{pageanchor=false,citecolor=blue} \begin{titlepage} \vspace*{7cm} \begin{center} {\Large Intel\textsuperscript{\textregistered} Offload Runtime Library }\\ \vspace*{1cm} {\large Generated by Doxygen $doxygenversion }\\ \vspace*{0.5cm} {\small $datetime }\\ \end{center} \end{titlepage} {\bf FTC Optimization Notice} Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors. These optimizations include SSE2, SSE3, and SSSE3 instruction sets and other optimizations. Intel does not guarantee the availability, functionality, or effectiveness of any optimization on microprocessors not manufactured by Intel. Microprocessor-dependent optimizations in this product are intended for use with Intel microprocessors. Certain optimizations not specific to Intel microarchitecture are reserved for Intel microprocessors. Please refer to the applicable product User and Reference Guides for more information regarding the specific instruction sets covered by this notice. Notice revision \#20110804 \vspace*{0.5cm} {\bf Trademarks} Intel, Xeon, and Intel Xeon Phi are trademarks of Intel Corporation in the U.S. and/or other countries. This document is Copyright \textcopyright 2014-2016, Intel Corporation. All rights reserved. \pagenumbering{roman} \tableofcontents \pagenumbering{arabic} \hypersetup{pageanchor=true,citecolor=blue}
{ "pile_set_name": "Github" }
## Syntactic Parsing Syntactic parsing is the process of analysing words for grammar and arranging them such that the relationship between them is shown. Its attributes include dependency and part of speech tags- - Dependency is analysis of binary relations between 2 lexical items or words. Each relation is represented in the form of triplets( relation,governor,dependent) - Part of Speech tagging or POS tagging - This helps in identifying each word of the sentenceas a noun,pronoun,adjective and so on. It is used to improve word features and converting a word to its base(for example swimming,swam are derived from same word, swim). It can also be used to removed stopwords(repeatable words that are not required for analysis like 'the','if' etc) Motivations for syntactic parsing include machine translation, speech recognition, grammar checking, relation extraction, and question answering.
{ "pile_set_name": "Github" }
// Copyright 2016 The etcd Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package clientv3 import ( "context" "fmt" "strings" "go.etcd.io/etcd/auth/authpb" pb "go.etcd.io/etcd/etcdserver/etcdserverpb" "google.golang.org/grpc" ) type ( AuthEnableResponse pb.AuthEnableResponse AuthDisableResponse pb.AuthDisableResponse AuthenticateResponse pb.AuthenticateResponse AuthUserAddResponse pb.AuthUserAddResponse AuthUserDeleteResponse pb.AuthUserDeleteResponse AuthUserChangePasswordResponse pb.AuthUserChangePasswordResponse AuthUserGrantRoleResponse pb.AuthUserGrantRoleResponse AuthUserGetResponse pb.AuthUserGetResponse AuthUserRevokeRoleResponse pb.AuthUserRevokeRoleResponse AuthRoleAddResponse pb.AuthRoleAddResponse AuthRoleGrantPermissionResponse pb.AuthRoleGrantPermissionResponse AuthRoleGetResponse pb.AuthRoleGetResponse AuthRoleRevokePermissionResponse pb.AuthRoleRevokePermissionResponse AuthRoleDeleteResponse pb.AuthRoleDeleteResponse AuthUserListResponse pb.AuthUserListResponse AuthRoleListResponse pb.AuthRoleListResponse PermissionType authpb.Permission_Type Permission authpb.Permission ) const ( PermRead = authpb.READ PermWrite = authpb.WRITE PermReadWrite = authpb.READWRITE ) type UserAddOptions authpb.UserAddOptions type Auth interface { // AuthEnable enables auth of an etcd cluster. AuthEnable(ctx context.Context) (*AuthEnableResponse, error) // AuthDisable disables auth of an etcd cluster. AuthDisable(ctx context.Context) (*AuthDisableResponse, error) // UserAdd adds a new user to an etcd cluster. UserAdd(ctx context.Context, name string, password string) (*AuthUserAddResponse, error) // UserAddWithOptions adds a new user to an etcd cluster with some options. UserAddWithOptions(ctx context.Context, name string, password string, opt *UserAddOptions) (*AuthUserAddResponse, error) // UserDelete deletes a user from an etcd cluster. UserDelete(ctx context.Context, name string) (*AuthUserDeleteResponse, error) // UserChangePassword changes a password of a user. UserChangePassword(ctx context.Context, name string, password string) (*AuthUserChangePasswordResponse, error) // UserGrantRole grants a role to a user. UserGrantRole(ctx context.Context, user string, role string) (*AuthUserGrantRoleResponse, error) // UserGet gets a detailed information of a user. UserGet(ctx context.Context, name string) (*AuthUserGetResponse, error) // UserList gets a list of all users. UserList(ctx context.Context) (*AuthUserListResponse, error) // UserRevokeRole revokes a role of a user. UserRevokeRole(ctx context.Context, name string, role string) (*AuthUserRevokeRoleResponse, error) // RoleAdd adds a new role to an etcd cluster. RoleAdd(ctx context.Context, name string) (*AuthRoleAddResponse, error) // RoleGrantPermission grants a permission to a role. RoleGrantPermission(ctx context.Context, name string, key, rangeEnd string, permType PermissionType) (*AuthRoleGrantPermissionResponse, error) // RoleGet gets a detailed information of a role. RoleGet(ctx context.Context, role string) (*AuthRoleGetResponse, error) // RoleList gets a list of all roles. RoleList(ctx context.Context) (*AuthRoleListResponse, error) // RoleRevokePermission revokes a permission from a role. RoleRevokePermission(ctx context.Context, role string, key, rangeEnd string) (*AuthRoleRevokePermissionResponse, error) // RoleDelete deletes a role. RoleDelete(ctx context.Context, role string) (*AuthRoleDeleteResponse, error) } type authClient struct { remote pb.AuthClient callOpts []grpc.CallOption } func NewAuth(c *Client) Auth { api := &authClient{remote: RetryAuthClient(c)} if c != nil { api.callOpts = c.callOpts } return api } func (auth *authClient) AuthEnable(ctx context.Context) (*AuthEnableResponse, error) { resp, err := auth.remote.AuthEnable(ctx, &pb.AuthEnableRequest{}, auth.callOpts...) return (*AuthEnableResponse)(resp), toErr(ctx, err) } func (auth *authClient) AuthDisable(ctx context.Context) (*AuthDisableResponse, error) { resp, err := auth.remote.AuthDisable(ctx, &pb.AuthDisableRequest{}, auth.callOpts...) return (*AuthDisableResponse)(resp), toErr(ctx, err) } func (auth *authClient) UserAdd(ctx context.Context, name string, password string) (*AuthUserAddResponse, error) { resp, err := auth.remote.UserAdd(ctx, &pb.AuthUserAddRequest{Name: name, Password: password, Options: &authpb.UserAddOptions{NoPassword: false}}, auth.callOpts...) return (*AuthUserAddResponse)(resp), toErr(ctx, err) } func (auth *authClient) UserAddWithOptions(ctx context.Context, name string, password string, options *UserAddOptions) (*AuthUserAddResponse, error) { resp, err := auth.remote.UserAdd(ctx, &pb.AuthUserAddRequest{Name: name, Password: password, Options: (*authpb.UserAddOptions)(options)}, auth.callOpts...) return (*AuthUserAddResponse)(resp), toErr(ctx, err) } func (auth *authClient) UserDelete(ctx context.Context, name string) (*AuthUserDeleteResponse, error) { resp, err := auth.remote.UserDelete(ctx, &pb.AuthUserDeleteRequest{Name: name}, auth.callOpts...) return (*AuthUserDeleteResponse)(resp), toErr(ctx, err) } func (auth *authClient) UserChangePassword(ctx context.Context, name string, password string) (*AuthUserChangePasswordResponse, error) { resp, err := auth.remote.UserChangePassword(ctx, &pb.AuthUserChangePasswordRequest{Name: name, Password: password}, auth.callOpts...) return (*AuthUserChangePasswordResponse)(resp), toErr(ctx, err) } func (auth *authClient) UserGrantRole(ctx context.Context, user string, role string) (*AuthUserGrantRoleResponse, error) { resp, err := auth.remote.UserGrantRole(ctx, &pb.AuthUserGrantRoleRequest{User: user, Role: role}, auth.callOpts...) return (*AuthUserGrantRoleResponse)(resp), toErr(ctx, err) } func (auth *authClient) UserGet(ctx context.Context, name string) (*AuthUserGetResponse, error) { resp, err := auth.remote.UserGet(ctx, &pb.AuthUserGetRequest{Name: name}, auth.callOpts...) return (*AuthUserGetResponse)(resp), toErr(ctx, err) } func (auth *authClient) UserList(ctx context.Context) (*AuthUserListResponse, error) { resp, err := auth.remote.UserList(ctx, &pb.AuthUserListRequest{}, auth.callOpts...) return (*AuthUserListResponse)(resp), toErr(ctx, err) } func (auth *authClient) UserRevokeRole(ctx context.Context, name string, role string) (*AuthUserRevokeRoleResponse, error) { resp, err := auth.remote.UserRevokeRole(ctx, &pb.AuthUserRevokeRoleRequest{Name: name, Role: role}, auth.callOpts...) return (*AuthUserRevokeRoleResponse)(resp), toErr(ctx, err) } func (auth *authClient) RoleAdd(ctx context.Context, name string) (*AuthRoleAddResponse, error) { resp, err := auth.remote.RoleAdd(ctx, &pb.AuthRoleAddRequest{Name: name}, auth.callOpts...) return (*AuthRoleAddResponse)(resp), toErr(ctx, err) } func (auth *authClient) RoleGrantPermission(ctx context.Context, name string, key, rangeEnd string, permType PermissionType) (*AuthRoleGrantPermissionResponse, error) { perm := &authpb.Permission{ Key: []byte(key), RangeEnd: []byte(rangeEnd), PermType: authpb.Permission_Type(permType), } resp, err := auth.remote.RoleGrantPermission(ctx, &pb.AuthRoleGrantPermissionRequest{Name: name, Perm: perm}, auth.callOpts...) return (*AuthRoleGrantPermissionResponse)(resp), toErr(ctx, err) } func (auth *authClient) RoleGet(ctx context.Context, role string) (*AuthRoleGetResponse, error) { resp, err := auth.remote.RoleGet(ctx, &pb.AuthRoleGetRequest{Role: role}, auth.callOpts...) return (*AuthRoleGetResponse)(resp), toErr(ctx, err) } func (auth *authClient) RoleList(ctx context.Context) (*AuthRoleListResponse, error) { resp, err := auth.remote.RoleList(ctx, &pb.AuthRoleListRequest{}, auth.callOpts...) return (*AuthRoleListResponse)(resp), toErr(ctx, err) } func (auth *authClient) RoleRevokePermission(ctx context.Context, role string, key, rangeEnd string) (*AuthRoleRevokePermissionResponse, error) { resp, err := auth.remote.RoleRevokePermission(ctx, &pb.AuthRoleRevokePermissionRequest{Role: role, Key: []byte(key), RangeEnd: []byte(rangeEnd)}, auth.callOpts...) return (*AuthRoleRevokePermissionResponse)(resp), toErr(ctx, err) } func (auth *authClient) RoleDelete(ctx context.Context, role string) (*AuthRoleDeleteResponse, error) { resp, err := auth.remote.RoleDelete(ctx, &pb.AuthRoleDeleteRequest{Role: role}, auth.callOpts...) return (*AuthRoleDeleteResponse)(resp), toErr(ctx, err) } func StrToPermissionType(s string) (PermissionType, error) { val, ok := authpb.Permission_Type_value[strings.ToUpper(s)] if ok { return PermissionType(val), nil } return PermissionType(-1), fmt.Errorf("invalid permission type: %s", s) } type authenticator struct { conn *grpc.ClientConn // conn in-use remote pb.AuthClient callOpts []grpc.CallOption } func (auth *authenticator) authenticate(ctx context.Context, name string, password string) (*AuthenticateResponse, error) { resp, err := auth.remote.Authenticate(ctx, &pb.AuthenticateRequest{Name: name, Password: password}, auth.callOpts...) return (*AuthenticateResponse)(resp), toErr(ctx, err) } func (auth *authenticator) close() { auth.conn.Close() } func newAuthenticator(ctx context.Context, target string, opts []grpc.DialOption, c *Client) (*authenticator, error) { conn, err := grpc.DialContext(ctx, target, opts...) if err != nil { return nil, err } api := &authenticator{ conn: conn, remote: pb.NewAuthClient(conn), } if c != nil { api.callOpts = c.callOpts } return api, nil }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <file xmlns="http://bibtexml.sf.net/"> <entry id="Mustermann2016"> <misc> <author>Max Mustermann</author> <title>Java Misc</title> <howpublished>Internet</howpublished> <month>February</month> <year>2016</year> <keywords>java</keywords> </misc> </entry> </file>
{ "pile_set_name": "Github" }
import reducer, { initialState } from '../catalog'; import actions from '../../actions/catalog'; const state = { ...initialState }; describe('setCurrentPage.receive', () => { const actionType = actions.setCurrentPage.receive; test('it sets currentPage to payload', () => { const action = { payload: 7, type: actionType }; const result = reducer(state, action); expect(result).toHaveProperty('currentPage', 7); }); test('it does not alter state on error', () => { const action = { error: true, payload: new Error('unit test'), type: actionType }; const result = reducer(state, action); expect(result).toEqual(state); }); }); describe('setPrevPageTotal.receive', () => { const actionType = actions.setPrevPageTotal.receive; test('it sets prevPageTotal to payload', () => { const action = { payload: 5, type: actionType }; const result = reducer(state, action); expect(result).toHaveProperty('prevPageTotal', 5); }); test('it does not alter state on error', () => { const action = { error: true, payload: new Error('unit test'), type: actionType }; const result = reducer(state, action); expect(result).toEqual(state); }); });
{ "pile_set_name": "Github" }
{ "name": "cloudbuild", "version": "1.0.0", "lockfileVersion": 1, "requires": true, "dependencies": { "abort-controller": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", "requires": { "event-target-shim": "^5.0.0" } }, "agent-base": { "version": "4.2.1", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-4.2.1.tgz", "integrity": "sha512-JVwXMr9nHYTUXsBFKUqhJwvlcYU/blreOEUkhNR2eXZIvwd+c+o5V4MgDPKWnMS/56awN3TRzIP+KoPn+roQtg==", "requires": { "es6-promisify": "^5.0.0" } }, "base64-js": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.0.tgz", "integrity": "sha512-ccav/yGvoa80BQDljCxsmmQ3Xvx60/UpBIij5QN21W3wBi/hhIC9OoO+KLpu9IJTS9j4DRVJ3aDDF9cMSoa2lw==" }, "bignumber.js": { "version": "7.2.1", "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-7.2.1.tgz", "integrity": "sha512-S4XzBk5sMB+Rcb/LNcpzXr57VRTxgAvaAEDAl1AwRx27j00hT84O6OkteE7u8UB3NuaaygCRrEpqox4uDOrbdQ==" }, "buffer-equal-constant-time": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" }, "debug": { "version": "3.2.6", "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.6.tgz", "integrity": "sha512-mel+jf7nrtEl5Pn1Qx46zARXKDpBbvzezse7p7LqINmdoIk8PYP5SySaxEmYv6TZ0JyEKA1hsCId6DIhgITtWQ==", "requires": { "ms": "^2.1.1" } }, "ecdsa-sig-formatter": { "version": "1.0.11", "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", "requires": { "safe-buffer": "^5.0.1" } }, "es6-promise": { "version": "4.2.6", "resolved": "https://registry.npmjs.org/es6-promise/-/es6-promise-4.2.6.tgz", "integrity": "sha512-aRVgGdnmW2OiySVPUC9e6m+plolMAJKjZnQlCwNSuK5yQ0JN61DZSO1X1Ufd1foqWRAlig0rhduTCHe7sVtK5Q==" }, "es6-promisify": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/es6-promisify/-/es6-promisify-5.0.0.tgz", "integrity": "sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM=", "requires": { "es6-promise": "^4.0.3" } }, "event-target-shim": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==" }, "extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" }, "fast-text-encoding": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fast-text-encoding/-/fast-text-encoding-1.0.0.tgz", "integrity": "sha512-R9bHCvweUxxwkDwhjav5vxpFvdPGlVngtqmx4pIZfSUhM/Q4NiIUHB456BAf+Q1Nwu3HEZYONtu+Rya+af4jiQ==" }, "gaxios": { "version": "1.8.3", "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-1.8.3.tgz", "integrity": "sha512-6Lc1P0NjbPNQ2FGgTRurz32P6FktNJbwLqXvrUNhfwzKb9iizcWuAJiHoSG2W186K9ZL0X6ST5xD9gJWhHI1sg==", "requires": { "abort-controller": "^3.0.0", "extend": "^3.0.2", "https-proxy-agent": "^2.2.1", "node-fetch": "^2.3.0" } }, "gcp-metadata": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-1.0.0.tgz", "integrity": "sha512-Q6HrgfrCQeEircnNP3rCcEgiDv7eF9+1B+1MMgpE190+/+0mjQR8PxeOaRgxZWmdDAF9EIryHB9g1moPiw1SbQ==", "requires": { "gaxios": "^1.0.2", "json-bigint": "^0.3.0" } }, "google-auth-library": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-3.1.2.tgz", "integrity": "sha512-cDQMzTotwyWMrg5jRO7q0A4TL/3GWBgO7I7q5xGKNiiFf9SmGY/OJ1YsLMgI2MVHHsEGyrqYnbnmV1AE+Z6DnQ==", "requires": { "base64-js": "^1.3.0", "fast-text-encoding": "^1.0.0", "gaxios": "^1.2.1", "gcp-metadata": "^1.0.0", "gtoken": "^2.3.2", "https-proxy-agent": "^2.2.1", "jws": "^3.1.5", "lru-cache": "^5.0.0", "semver": "^5.5.0" } }, "google-p12-pem": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/google-p12-pem/-/google-p12-pem-1.0.4.tgz", "integrity": "sha512-SwLAUJqUfTB2iS+wFfSS/G9p7bt4eWcc2LyfvmUXe7cWp6p3mpxDo6LLI29MXdU6wvPcQ/up298X7GMC5ylAlA==", "requires": { "node-forge": "^0.8.0", "pify": "^4.0.0" } }, "googleapis": { "version": "39.2.0", "resolved": "https://registry.npmjs.org/googleapis/-/googleapis-39.2.0.tgz", "integrity": "sha512-66X8TG1B33zAt177sG1CoKoYHPP/B66tEpnnSANGCqotMuY5gqSQO8G/0gqHZR2jRgc5CHSSNOJCnpI0SuDxMQ==", "requires": { "google-auth-library": "^3.0.0", "googleapis-common": "^0.7.0" } }, "googleapis-common": { "version": "0.7.2", "resolved": "https://registry.npmjs.org/googleapis-common/-/googleapis-common-0.7.2.tgz", "integrity": "sha512-9DEJIiO4nS7nw0VE1YVkEfXEj8x8MxsuB+yZIpOBULFSN9OIKcUU8UuKgSZFU4lJmRioMfngktrbkMwWJcUhQg==", "requires": { "gaxios": "^1.2.2", "google-auth-library": "^3.0.0", "pify": "^4.0.0", "qs": "^6.5.2", "url-template": "^2.0.8", "uuid": "^3.2.1" } }, "gtoken": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-2.3.3.tgz", "integrity": "sha512-EaB49bu/TCoNeQjhCYKI/CurooBKkGxIqFHsWABW0b25fobBYVTMe84A8EBVVZhl8emiUdNypil9huMOTmyAnw==", "requires": { "gaxios": "^1.0.4", "google-p12-pem": "^1.0.0", "jws": "^3.1.5", "mime": "^2.2.0", "pify": "^4.0.0" } }, "https-proxy-agent": { "version": "2.2.1", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-2.2.1.tgz", "integrity": "sha512-HPCTS1LW51bcyMYbxUIOO4HEOlQ1/1qRaFWcyxvwaqUS9TY88aoEuHUY33kuAh1YhVVaDQhLZsnPd+XNARWZlQ==", "requires": { "agent-base": "^4.1.0", "debug": "^3.1.0" } }, "json-bigint": { "version": "0.3.0", "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-0.3.0.tgz", "integrity": "sha1-DM2RLEuCcNBfBW+9E4FLU9OCWx4=", "requires": { "bignumber.js": "^7.0.0" } }, "jwa": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.1.tgz", "integrity": "sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==", "requires": { "buffer-equal-constant-time": "1.0.1", "ecdsa-sig-formatter": "1.0.11", "safe-buffer": "^5.0.1" } }, "jws": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", "requires": { "jwa": "^1.4.1", "safe-buffer": "^5.0.1" } }, "lru-cache": { "version": "5.1.1", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", "requires": { "yallist": "^3.0.2" } }, "mime": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.2.tgz", "integrity": "sha512-zJBfZDkwRu+j3Pdd2aHsR5GfH2jIWhmL1ZzBoc+X+3JEti2hbArWcyJ+1laC1D2/U/W1a/+Cegj0/OnEU2ybjg==" }, "ms": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.1.tgz", "integrity": "sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==" }, "node-fetch": { "version": "2.3.0", "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.3.0.tgz", "integrity": "sha512-MOd8pV3fxENbryESLgVIeaGKrdl+uaYhCSSVkjeOb/31/njTpcis5aWfdqgNlHIrKOLRbMnfPINPOML2CIFeXA==" }, "node-forge": { "version": "0.8.2", "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.8.2.tgz", "integrity": "sha512-mXQ9GBq1N3uDCyV1pdSzgIguwgtVpM7f5/5J4ipz12PKWElmPpVWLDuWl8iXmhysr21+WmX/OJ5UKx82wjomgg==" }, "pify": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/pify/-/pify-4.0.1.tgz", "integrity": "sha512-uB80kBFb/tfd68bVleG9T5GGsGPjJrLAUpR5PZIrhBnIaRTQRjqdJSsIKkOP6OAIFbj7GOrcudc5pNjZ+geV2g==" }, "qs": { "version": "6.7.0", "resolved": "https://registry.npmjs.org/qs/-/qs-6.7.0.tgz", "integrity": "sha512-VCdBRNFTX1fyE7Nb6FYoURo/SPe62QCaAyzJvUjwRaIsc+NePBEniHlvxFmmX56+HZphIGtV0XeCirBtpDrTyQ==" }, "safe-buffer": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" }, "semver": { "version": "5.7.0", "resolved": "https://registry.npmjs.org/semver/-/semver-5.7.0.tgz", "integrity": "sha512-Ya52jSX2u7QKghxeoFGpLwCtGlt7j0oY9DYb5apt9nPlJ42ID+ulTXESnt/qAQcoSERyZ5sl3LDIOw0nAn/5DA==" }, "url-template": { "version": "2.0.8", "resolved": "https://registry.npmjs.org/url-template/-/url-template-2.0.8.tgz", "integrity": "sha1-/FZaPMy/93MMd19WQflVV5FDnyE=" }, "uuid": { "version": "3.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-3.3.2.tgz", "integrity": "sha512-yXJmeNaw3DnnKAOKJE51sL/ZaYfWJRl1pK9dr19YFCu0ObS231AB1/LbqTKRAQ5kw8A90rA6fr4riOUpTZvQZA==" }, "yallist": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.0.3.tgz", "integrity": "sha512-S+Zk8DEWE6oKpV+vI3qWkaK+jSbIK86pCwe2IF/xwIpQ8jEuxpw9NyaGjmp9+BoJv5FV2piqCDcoCtStppiq2A==" } } }
{ "pile_set_name": "Github" }
# 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. # pylint: skip-file import os, gzip import pickle as pickle import sys from mxnet.test_utils import download import zipfile import mxnet as mx # download mnist.pkl.gz def GetMNIST_pkl(): if not os.path.isdir("data"): os.makedirs('data') if not os.path.exists('data/mnist.pkl.gz'): download('http://deeplearning.net/data/mnist/mnist.pkl.gz', dirname='data') # download ubyte version of mnist and untar def GetMNIST_ubyte(): if not os.path.isdir("data"): os.makedirs('data') if (not os.path.exists('data/train-images-idx3-ubyte')) or \ (not os.path.exists('data/train-labels-idx1-ubyte')) or \ (not os.path.exists('data/t10k-images-idx3-ubyte')) or \ (not os.path.exists('data/t10k-labels-idx1-ubyte')): zip_file_path = download('http://data.mxnet.io/mxnet/data/mnist.zip', dirname='data') with zipfile.ZipFile(zip_file_path) as zf: zf.extractall('data') # download cifar def GetCifar10(): if not os.path.isdir("data"): os.makedirs('data') if (not os.path.exists('data/cifar/train.rec')) or \ (not os.path.exists('data/cifar/test.rec')) or \ (not os.path.exists('data/cifar/train.lst')) or \ (not os.path.exists('data/cifar/test.lst')): zip_file_path = download('http://data.mxnet.io/mxnet/data/cifar10.zip', dirname='data') with zipfile.ZipFile(zip_file_path) as zf: zf.extractall('data') def MNISTIterator(batch_size, input_shape): """return train and val iterators for mnist""" # download data GetMNIST_ubyte() flat = False if len(input_shape) == 3 else True train_dataiter = mx.io.MNISTIter( image="data/train-images-idx3-ubyte", label="data/train-labels-idx1-ubyte", input_shape=input_shape, batch_size=batch_size, shuffle=True, flat=flat) val_dataiter = mx.io.MNISTIter( image="data/t10k-images-idx3-ubyte", label="data/t10k-labels-idx1-ubyte", input_shape=input_shape, batch_size=batch_size, flat=flat) return (train_dataiter, val_dataiter)
{ "pile_set_name": "Github" }
/* * page.h - buffer/page management specific to NILFS * * Copyright (C) 2005-2008 Nippon Telegraph and Telephone Corporation. * * 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 St, Fifth Floor, Boston, MA 02110-1301 USA * * Written by Ryusuke Konishi <[email protected]>, * Seiji Kihara <[email protected]>. */ #ifndef _NILFS_PAGE_H #define _NILFS_PAGE_H #include <linux/buffer_head.h> #include "nilfs.h" /* * Extended buffer state bits */ enum { BH_NILFS_Allocated = BH_PrivateStart, BH_NILFS_Node, BH_NILFS_Volatile, }; BUFFER_FNS(NILFS_Allocated, nilfs_allocated) /* nilfs private buffers */ BUFFER_FNS(NILFS_Node, nilfs_node) /* nilfs node buffers */ BUFFER_FNS(NILFS_Volatile, nilfs_volatile) void nilfs_mark_buffer_dirty(struct buffer_head *bh); int __nilfs_clear_page_dirty(struct page *); struct buffer_head *nilfs_grab_buffer(struct inode *, struct address_space *, unsigned long, unsigned long); void nilfs_forget_buffer(struct buffer_head *); void nilfs_copy_buffer(struct buffer_head *, struct buffer_head *); int nilfs_page_buffers_clean(struct page *); void nilfs_page_bug(struct page *); struct page *nilfs_alloc_private_page(struct block_device *, int, unsigned long); void nilfs_free_private_page(struct page *); int nilfs_copy_dirty_pages(struct address_space *, struct address_space *); void nilfs_copy_back_pages(struct address_space *, struct address_space *); void nilfs_clear_dirty_pages(struct address_space *); unsigned nilfs_page_count_clean_buffers(struct page *, unsigned, unsigned); #define NILFS_PAGE_BUG(page, m, a...) \ do { nilfs_page_bug(page); BUG(); } while (0) static inline struct buffer_head * nilfs_page_get_nth_block(struct page *page, unsigned int count) { struct buffer_head *bh = page_buffers(page); while (count-- > 0) bh = bh->b_this_page; get_bh(bh); return bh; } #endif /* _NILFS_PAGE_H */
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8" ?> <localizationPack name="Chile" version="1.0"> <currencies> <currency name="Peso" iso_code="CLP" iso_code_num="152" sign="$" blank="1" format="2" decimals="1" /> </currencies> <languages> <language iso_code="es" /> </languages> <taxes> <tax id="1" name="IVA CL 19%" rate="19" /> <taxRulesGroup name="CL Standard Rate (19%)"> <taxRule iso_code_country="cl" id_tax="1" /> </taxRulesGroup> </taxes> <units> <unit type="weight" value="kg" /> <unit type="volume" value="L" /> <unit type="short_distance" value="cm" /> <unit type="base_distance" value="m" /> <unit type="long_distance" value="km" /> </units> </localizationPack>
{ "pile_set_name": "Github" }
# DescribeTags {#doc_api_1006035 .reference} Queries available tags. You can query the tags by specifying the ECS resource types, resource IDs, tag keys, or tag values. The system uses the Boolean operator AND \(&&\) between theses specified filtering conditions and returns a specific list of results from the operation. ## Description {#description .section} When a tag key is specified and no tag value is specified, all tags related to the tag key are queried. When both the tag key and tag value are specified, tags that exactly match the key-value are queried. ## Debugging {#apiExplorer .section} You can use [API Explorer](https://api.aliyun.com/#product=Ecs&api=DescribeTags) to perform debugging. API Explorer allows you to perform various operations to simplify API usage. For example, you can retrieve APIs, call APIs, and dynamically generate SDK example code. ## Request parameters {#parameters .section} |Name|Type|Required|Example|Description| |----|----|--------|-------|-----------| |RegionId|String|Yes|cn-hangzhou| The ID of the region. You can call [DescribeRegions](~~25609~~) to view the latest regions of Alibaba Cloud. | |Action|String|No|DescribeTags| The operation that you want to perform. Set the value to DescribeTags. | |PageNumber|Integer|No|1| The page number of the tag list. Starting value: 1. Default value: 1. | |PageSize|Integer|No|50| The number of entries per page. Maximum value: 100. Default value: 50. | |ResourceId|String|No|s-946ntx4wr| The ID of the resource to which the tag is bound. When the retrieved resources are instances, this parameter can be interpreted as InstanceId. | |ResourceType|String|No|snapshot| The type of the resource. Valid values: - disk - instance - image - securitygroup - snapshot All values must be lowercase. | |Tag.N.Key|String|No|Finance| The tag key of the resource. Valid values of N: 1 to 20. | |Tag.N.Value|String|No|Finance| The tag value of the resource. Valid values of N: 1 to 20. | |Tag.N.key|String|No|Finance| The tag key of the resource. **Note:** This parameter will be removed in the future. We recommend that you use the Tag.N.Key parameter to ensure compatibility. | |Tag.N.value|String|No|Finance| The tag value of the resource. **Note:** This parameter will be removed in the future. We recommend that you use the Tag.N.Value parameter to ensure compatibility. | ## Response parameters {#resultMapping .section} |Name|Type|Example|Description| |----|----|-------|-----------| |PageNumber|Integer|1| The page number of the tag list. | |PageSize|Integer|50| The number of entries per page. | |RequestId|String|B04B8CF3-4489-432D-83BA-6F128E4F2295| The ID of the request. | |Tags| | | The tags that match all the criteria. | |└ResourceTypeCount| | | The number of resource types. | |└Ddh|Integer|1| The number of dedicated hosts to which the tag is bound. | |└Disk|Integer|15| The number of disks to which the tag is bound. | |└Eni|Integer|5| The number of ENIs to which the tag is bound. | |└Image|Integer|6| The number of images to which the tag is bound. | |└Instance|Integer|45| The number of instances to which the tag is bound. | |└KeyPair|Integer|17| The number of key pairs to which the tag is bound. | |└LaunchTemplate|Integer|6| The number of launch templates to which the tag is bound. | |└Securitygroup|Integer|4| The number of security groups to which the tag is bound. | |└Snapshot|Integer|15| The number of snapshots to which the tag is bound. | |└Volume|Integer|6| The number of extended volumes to which the tag is bound. | |└TagKey|String|test| The key of the tag. | |└TagValue|String|api| The value of the tag. | |TotalCount|Integer|1| The total number of tags. | ## Examples {#demo .section} Sample requests ``` {#request_demo} https://ecs.aliyuncs.com/?Action=DescribeTags &RegionId=cn-hangzhou &PageSize=50 &PageNumber=1 &ResourceType=snapshot &ResourceId=s-946ntx4wr &Tag.1.Key=Finance &Tag.1.Value=Finance &<Common request parameters> ``` Successful response examples `XML` format ``` {#xml_return_success_demo} <DescribeTagsResponse> <RequestId>B04B8CF3-4489-432D-83BA-6F128E4F2295</RequestId> <PageNumber>1</PageNumber> <PageSize>50</PageSize> <Tags> <Tag> <TagKey>test</TagKey> <TagValue>api</TagValue> </Tag> </Tags> <TotalCount>1</TotalCount> </DescribeTagsResponse> ``` `JSON` format ``` {#json_return_success_demo} { "Tags":{ "Tag":[ { "TagValue":"api", "TagKey":"test" } ] }, "PageNumber":1, "TotalCount":1, "PageSize":50, "RequestId":"B04B8CF3-4489-432D-83BA-6F128E4F2295" } ``` ## Error codes {#section_ggx_15e_5iz .section} |HTTP status code|Error code|Error message|Description| |----------------|----------|-------------|-----------| |404|InvalidRegionId.NotFound|The specified RegionId does not exist.|The error message returned when the specified Region ID does not exist. Check whether the service is available in this region.| |404|InvalidResourceType.NotFound|The ResourceType provided does not exist in our records.|The error message returned when the specified resource does not exist.| |400|InvalidTagCount|The specified tags are beyond the permitted range.|The error message returned when the specified tags are outside of the valid range.| |400|InvalidTagKey.Malformed|The parameter Tag.n.Key is illegal.|The error message returned when the Tag.n.Key parameter is invalid.| [View error codes](https://error-center.aliyun.com/status/product/Ecs)
{ "pile_set_name": "Github" }
tensortrade.env.generic.components.reward\_scheme module ======================================================== .. automodule:: tensortrade.env.generic.components.reward_scheme :members: :undoc-members: :show-inheritance:
{ "pile_set_name": "Github" }
// GPL v3 License // // Copyright (c) 2016-2017 Bismur Studios Ltd. // Copyright (c) 2016-2017 Ioannis Giagkiozis // // AiCollectionConstructor.cs is part of Crystal AI. // // Crystal AI 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. // // Crystal AI 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 Crystal AI. If not, see <http://www.gnu.org/licenses/>. namespace Crystal { /// <summary> /// A convenience static class to create the collection hierarchy required by AiCollection. /// </summary> public static class AiCollectionConstructor { /// <summary> /// Creates all necessary collections for the AI. Note that the collections created by this /// will in most instances be unique. If however, for some reason, there is the need for different /// AI systems, then these should have separate collections. /// </summary> /// <returns></returns> public static IAiCollection Create() { var a = new ActionCollection(); var c = new ConsiderationCollection(); var o = new OptionCollection(a, c); var b = new BehaviourCollection(o); return new AiCollection(b); } } }
{ "pile_set_name": "Github" }
package org.compiere.model; import java.math.BigDecimal; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Properties; import java.util.logging.Level; import org.compiere.util.CLogger; import org.compiere.util.DB; import org.compiere.util.Env; public class MProductionLineMA extends X_M_ProductionLineMA { /** * */ private static final long serialVersionUID = 1L; /** Logger */ private static CLogger s_log = CLogger.getCLogger (MInventoryLineMA.class); public MProductionLineMA(Properties ctx, int M_ProductionLineMA_ID, String trxName) { super(ctx, M_ProductionLineMA_ID, trxName); // TODO Auto-generated constructor stub } public MProductionLineMA(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); // TODO Auto-generated constructor stub } /** * Parent constructor * @param parent * @param asi * @param qty * @param ctx * @param trxName */ public MProductionLineMA( MProductionLine parent, int asi, BigDecimal qty) { super(parent.getCtx(),0,parent.get_TrxName()); setM_AttributeSetInstance_ID(asi); setM_ProductionLine_ID(parent.get_ID()); setMovementQty(qty); setAD_Org_ID(parent.getAD_Org_ID()); } public static MProductionLineMA get( MProductionLine parent, int asi ) { String where = " M_ProductionLine_ID = ? AND M_AttributeSetInstance_ID = ? "; MProductionLineMA lineMA = MTable.get(parent.getCtx(), MProductionLineMA.Table_Name).createQuery(where, parent.get_TrxName()) .setParameters(parent.getM_ProductionLine_ID(), asi).firstOnly(); if (lineMA != null) return lineMA; else return new MProductionLineMA( parent, asi, Env.ZERO); } public static MProductionLineMA[] get (Properties ctx, int M_ProductionLine_ID, String trxName) { ArrayList<MProductionLineMA> list = new ArrayList<MProductionLineMA>(); String sql = "SELECT * FROM M_ProductionLineMA WHERE M_ProductionLine_ID=?"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, trxName); pstmt.setInt (1, M_ProductionLine_ID); rs = pstmt.executeQuery (); while (rs.next ()) list.add (new MProductionLineMA (ctx, rs, trxName)); } catch (Exception e) { s_log.log (Level.SEVERE, sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } MProductionLineMA[] retValue = new MProductionLineMA[list.size ()]; list.toArray (retValue); return retValue; } }
{ "pile_set_name": "Github" }
{ "id": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "modelName": "GMSprite", "mvc": "1.12", "name": "spr_scrollbar_h_button_left", "For3D": false, "HTile": true, "VTile": true, "bbox_bottom": 15, "bbox_left": 0, "bbox_right": 15, "bbox_top": 0, "bboxmode": 0, "colkind": 1, "coltolerance": 0, "edgeFiltering": false, "frames": [ { "id": "3e371bcc-95e8-4c7e-80b8-182220ed03bd", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "f5259857-0b9e-4b76-a4f5-fdd33412c9ad", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "3e371bcc-95e8-4c7e-80b8-182220ed03bd", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "818e9809-ea32-400c-9b87-198caf5d041b", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "3e371bcc-95e8-4c7e-80b8-182220ed03bd", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] }, { "id": "aedbd662-a5ba-4316-a2a5-1472f9553c8a", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "bf2d7588-73f5-46b1-82e0-4306be62b18a", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "aedbd662-a5ba-4316-a2a5-1472f9553c8a", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "d7668927-5e6b-4fdd-b56f-3db85e947c52", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "aedbd662-a5ba-4316-a2a5-1472f9553c8a", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] }, { "id": "ae6ee3c9-4009-43c0-80e6-9c6a1d2429eb", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "7c29bed4-d038-42b0-9e32-0179dcc94a81", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "ae6ee3c9-4009-43c0-80e6-9c6a1d2429eb", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "e3a127e3-49d2-4fa0-971c-4c9d0451ce92", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "ae6ee3c9-4009-43c0-80e6-9c6a1d2429eb", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] }, { "id": "99849c27-4d0c-48a5-91fd-5b945a5f735e", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "a1838a58-9f2b-42a4-9885-d6d8ad393069", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "99849c27-4d0c-48a5-91fd-5b945a5f735e", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "851efb8b-3e29-49e6-9fd1-8d564f5788cd", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "99849c27-4d0c-48a5-91fd-5b945a5f735e", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] }, { "id": "9763547a-08c6-4a3e-8a72-fd8257f1d2a4", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "c87a1443-42be-4112-94c8-6ff56602df5c", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "9763547a-08c6-4a3e-8a72-fd8257f1d2a4", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "869a2663-16c7-4e70-be3b-d49f10cee4e1", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "9763547a-08c6-4a3e-8a72-fd8257f1d2a4", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] }, { "id": "317e608a-9568-4c68-8580-8f625ff5da7c", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "3b9117fd-5374-465b-8e66-e8decbc9a4d1", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "317e608a-9568-4c68-8580-8f625ff5da7c", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "42878d35-2052-4263-8c6b-b94e32805642", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "317e608a-9568-4c68-8580-8f625ff5da7c", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] }, { "id": "e8c18136-0c2b-4881-b06c-74756bc5057d", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "7a9bbed0-6831-477a-a69d-88f9a7bec8cc", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "e8c18136-0c2b-4881-b06c-74756bc5057d", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "3c9aef09-d16e-48e8-a497-142610c2b8e3", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "e8c18136-0c2b-4881-b06c-74756bc5057d", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] }, { "id": "68bc0e94-839c-4fa9-8bae-568786e37849", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "0fb489cf-92ab-4e7d-81cf-7bdb06192bb7", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "68bc0e94-839c-4fa9-8bae-568786e37849", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "09cb9ccc-dd3f-4a30-86ac-5fc4a1cfe0d4", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "68bc0e94-839c-4fa9-8bae-568786e37849", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] }, { "id": "45a5dced-6743-4b1c-b7e5-7bfeaf07144f", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "a1115241-b839-4219-956a-a66efd00d756", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "45a5dced-6743-4b1c-b7e5-7bfeaf07144f", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "23a2de33-1938-430e-a25b-08fc3ae5a3cf", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "45a5dced-6743-4b1c-b7e5-7bfeaf07144f", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] }, { "id": "6cd8577b-5102-4a42-91f1-4c5ca97d3abf", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "bc8f54dc-80c2-473b-846d-b02f258aeea1", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "6cd8577b-5102-4a42-91f1-4c5ca97d3abf", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "897d9397-2ae3-4187-8d98-12deb1ee9c7a", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "6cd8577b-5102-4a42-91f1-4c5ca97d3abf", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] }, { "id": "ddfbfe3b-0396-4a6c-bcdc-9173ababcdc0", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "de2be876-563b-46a0-851e-45975c7b03fe", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "ddfbfe3b-0396-4a6c-bcdc-9173ababcdc0", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "cc230202-114a-4f32-a45d-d787691b215f", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "ddfbfe3b-0396-4a6c-bcdc-9173ababcdc0", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] }, { "id": "f2f08e58-ab2a-4cd0-84fa-9a9dfbe9cddf", "modelName": "GMSpriteFrame", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "compositeImage": { "id": "da8a3a62-8bc5-4ef5-8d26-70a20b5bb6bb", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "f2f08e58-ab2a-4cd0-84fa-9a9dfbe9cddf", "LayerId": "00000000-0000-0000-0000-000000000000" }, "images": [ { "id": "c2a0d012-5376-40d2-921d-7df11968af04", "modelName": "GMSpriteImage", "mvc": "1.0", "FrameId": "f2f08e58-ab2a-4cd0-84fa-9a9dfbe9cddf", "LayerId": "b0d8a702-0760-45dc-ac5d-e5f281387d9e" } ] } ], "gridX": 0, "gridY": 0, "height": 16, "layers": [ { "id": "b0d8a702-0760-45dc-ac5d-e5f281387d9e", "modelName": "GMImageLayer", "mvc": "1.0", "SpriteId": "379fed1d-3f1e-438d-96f6-c933ecc7158f", "blendMode": 0, "isLocked": false, "name": "default", "opacity": 100, "visible": true } ], "origin": 0, "originLocked": false, "playbackSpeed": 15, "playbackSpeedType": 0, "premultiplyAlpha": false, "sepmasks": false, "swatchColours": null, "swfPrecision": 2.525, "textureGroupId": "1225f6b0-ac20-43bd-a82e-be73fa0b6f4f", "type": 0, "width": 16, "xorig": 0, "yorig": 0 }
{ "pile_set_name": "Github" }
/* * This file is provided under a dual BSD/GPLv2 license. When using or * redistributing this file, you may do so under either license. * * GPL LICENSE SUMMARY * * Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. * The full GNU General Public License is included in this distribution * in the file called LICENSE.GPL. * * BSD LICENSE * * Copyright(c) 2008 - 2011 Intel Corporation. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name of Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <scsi/sas.h> #include <linux/bitops.h> #include "isci.h" #include "port.h" #include "remote_device.h" #include "request.h" #include "remote_node_context.h" #include "scu_event_codes.h" #include "task.h" #undef C #define C(a) (#a) const char *dev_state_name(enum sci_remote_device_states state) { static const char * const strings[] = REMOTE_DEV_STATES; return strings[state]; } #undef C /** * isci_remote_device_not_ready() - This function is called by the ihost when * the remote device is not ready. We mark the isci device as ready (not * "ready_for_io") and signal the waiting proccess. * @isci_host: This parameter specifies the isci host object. * @isci_device: This parameter specifies the remote device * * sci_lock is held on entrance to this function. */ static void isci_remote_device_not_ready(struct isci_host *ihost, struct isci_remote_device *idev, u32 reason) { struct isci_request *ireq; dev_dbg(&ihost->pdev->dev, "%s: isci_device = %p\n", __func__, idev); switch (reason) { case SCIC_REMOTE_DEVICE_NOT_READY_STOP_REQUESTED: set_bit(IDEV_GONE, &idev->flags); break; case SCIC_REMOTE_DEVICE_NOT_READY_SATA_SDB_ERROR_FIS_RECEIVED: set_bit(IDEV_IO_NCQERROR, &idev->flags); /* Kill all outstanding requests for the device. */ list_for_each_entry(ireq, &idev->reqs_in_process, dev_node) { dev_dbg(&ihost->pdev->dev, "%s: isci_device = %p request = %p\n", __func__, idev, ireq); sci_controller_terminate_request(ihost, idev, ireq); } /* Fall through into the default case... */ default: clear_bit(IDEV_IO_READY, &idev->flags); break; } } /** * isci_remote_device_ready() - This function is called by the ihost when the * remote device is ready. We mark the isci device as ready and signal the * waiting proccess. * @ihost: our valid isci_host * @idev: remote device * */ static void isci_remote_device_ready(struct isci_host *ihost, struct isci_remote_device *idev) { dev_dbg(&ihost->pdev->dev, "%s: idev = %p\n", __func__, idev); clear_bit(IDEV_IO_NCQERROR, &idev->flags); set_bit(IDEV_IO_READY, &idev->flags); if (test_and_clear_bit(IDEV_START_PENDING, &idev->flags)) wake_up(&ihost->eventq); } /* called once the remote node context is ready to be freed. * The remote device can now report that its stop operation is complete. none */ static void rnc_destruct_done(void *_dev) { struct isci_remote_device *idev = _dev; BUG_ON(idev->started_request_count != 0); sci_change_state(&idev->sm, SCI_DEV_STOPPED); } static enum sci_status sci_remote_device_terminate_requests(struct isci_remote_device *idev) { struct isci_host *ihost = idev->owning_port->owning_controller; enum sci_status status = SCI_SUCCESS; u32 i; for (i = 0; i < SCI_MAX_IO_REQUESTS; i++) { struct isci_request *ireq = ihost->reqs[i]; enum sci_status s; if (!test_bit(IREQ_ACTIVE, &ireq->flags) || ireq->target_device != idev) continue; s = sci_controller_terminate_request(ihost, idev, ireq); if (s != SCI_SUCCESS) status = s; } return status; } enum sci_status sci_remote_device_stop(struct isci_remote_device *idev, u32 timeout) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; switch (state) { case SCI_DEV_INITIAL: case SCI_DEV_FAILED: case SCI_DEV_FINAL: default: dev_warn(scirdev_to_dev(idev), "%s: in wrong state: %s\n", __func__, dev_state_name(state)); return SCI_FAILURE_INVALID_STATE; case SCI_DEV_STOPPED: return SCI_SUCCESS; case SCI_DEV_STARTING: /* device not started so there had better be no requests */ BUG_ON(idev->started_request_count != 0); sci_remote_node_context_destruct(&idev->rnc, rnc_destruct_done, idev); /* Transition to the stopping state and wait for the * remote node to complete being posted and invalidated. */ sci_change_state(sm, SCI_DEV_STOPPING); return SCI_SUCCESS; case SCI_DEV_READY: case SCI_STP_DEV_IDLE: case SCI_STP_DEV_CMD: case SCI_STP_DEV_NCQ: case SCI_STP_DEV_NCQ_ERROR: case SCI_STP_DEV_AWAIT_RESET: case SCI_SMP_DEV_IDLE: case SCI_SMP_DEV_CMD: sci_change_state(sm, SCI_DEV_STOPPING); if (idev->started_request_count == 0) { sci_remote_node_context_destruct(&idev->rnc, rnc_destruct_done, idev); return SCI_SUCCESS; } else return sci_remote_device_terminate_requests(idev); break; case SCI_DEV_STOPPING: /* All requests should have been terminated, but if there is an * attempt to stop a device already in the stopping state, then * try again to terminate. */ return sci_remote_device_terminate_requests(idev); case SCI_DEV_RESETTING: sci_change_state(sm, SCI_DEV_STOPPING); return SCI_SUCCESS; } } enum sci_status sci_remote_device_reset(struct isci_remote_device *idev) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; switch (state) { case SCI_DEV_INITIAL: case SCI_DEV_STOPPED: case SCI_DEV_STARTING: case SCI_SMP_DEV_IDLE: case SCI_SMP_DEV_CMD: case SCI_DEV_STOPPING: case SCI_DEV_FAILED: case SCI_DEV_RESETTING: case SCI_DEV_FINAL: default: dev_warn(scirdev_to_dev(idev), "%s: in wrong state: %s\n", __func__, dev_state_name(state)); return SCI_FAILURE_INVALID_STATE; case SCI_DEV_READY: case SCI_STP_DEV_IDLE: case SCI_STP_DEV_CMD: case SCI_STP_DEV_NCQ: case SCI_STP_DEV_NCQ_ERROR: case SCI_STP_DEV_AWAIT_RESET: sci_change_state(sm, SCI_DEV_RESETTING); return SCI_SUCCESS; } } enum sci_status sci_remote_device_reset_complete(struct isci_remote_device *idev) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; if (state != SCI_DEV_RESETTING) { dev_warn(scirdev_to_dev(idev), "%s: in wrong state: %s\n", __func__, dev_state_name(state)); return SCI_FAILURE_INVALID_STATE; } sci_change_state(sm, SCI_DEV_READY); return SCI_SUCCESS; } enum sci_status sci_remote_device_suspend(struct isci_remote_device *idev, u32 suspend_type) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; if (state != SCI_STP_DEV_CMD) { dev_warn(scirdev_to_dev(idev), "%s: in wrong state: %s\n", __func__, dev_state_name(state)); return SCI_FAILURE_INVALID_STATE; } return sci_remote_node_context_suspend(&idev->rnc, suspend_type, NULL, NULL); } enum sci_status sci_remote_device_frame_handler(struct isci_remote_device *idev, u32 frame_index) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; struct isci_host *ihost = idev->owning_port->owning_controller; enum sci_status status; switch (state) { case SCI_DEV_INITIAL: case SCI_DEV_STOPPED: case SCI_DEV_STARTING: case SCI_STP_DEV_IDLE: case SCI_SMP_DEV_IDLE: case SCI_DEV_FINAL: default: dev_warn(scirdev_to_dev(idev), "%s: in wrong state: %s\n", __func__, dev_state_name(state)); /* Return the frame back to the controller */ sci_controller_release_frame(ihost, frame_index); return SCI_FAILURE_INVALID_STATE; case SCI_DEV_READY: case SCI_STP_DEV_NCQ_ERROR: case SCI_STP_DEV_AWAIT_RESET: case SCI_DEV_STOPPING: case SCI_DEV_FAILED: case SCI_DEV_RESETTING: { struct isci_request *ireq; struct ssp_frame_hdr hdr; void *frame_header; ssize_t word_cnt; status = sci_unsolicited_frame_control_get_header(&ihost->uf_control, frame_index, &frame_header); if (status != SCI_SUCCESS) return status; word_cnt = sizeof(hdr) / sizeof(u32); sci_swab32_cpy(&hdr, frame_header, word_cnt); ireq = sci_request_by_tag(ihost, be16_to_cpu(hdr.tag)); if (ireq && ireq->target_device == idev) { /* The IO request is now in charge of releasing the frame */ status = sci_io_request_frame_handler(ireq, frame_index); } else { /* We could not map this tag to a valid IO * request Just toss the frame and continue */ sci_controller_release_frame(ihost, frame_index); } break; } case SCI_STP_DEV_NCQ: { struct dev_to_host_fis *hdr; status = sci_unsolicited_frame_control_get_header(&ihost->uf_control, frame_index, (void **)&hdr); if (status != SCI_SUCCESS) return status; if (hdr->fis_type == FIS_SETDEVBITS && (hdr->status & ATA_ERR)) { idev->not_ready_reason = SCIC_REMOTE_DEVICE_NOT_READY_SATA_SDB_ERROR_FIS_RECEIVED; /* TODO Check sactive and complete associated IO if any. */ sci_change_state(sm, SCI_STP_DEV_NCQ_ERROR); } else if (hdr->fis_type == FIS_REGD2H && (hdr->status & ATA_ERR)) { /* * Some devices return D2H FIS when an NCQ error is detected. * Treat this like an SDB error FIS ready reason. */ idev->not_ready_reason = SCIC_REMOTE_DEVICE_NOT_READY_SATA_SDB_ERROR_FIS_RECEIVED; sci_change_state(&idev->sm, SCI_STP_DEV_NCQ_ERROR); } else status = SCI_FAILURE; sci_controller_release_frame(ihost, frame_index); break; } case SCI_STP_DEV_CMD: case SCI_SMP_DEV_CMD: /* The device does not process any UF received from the hardware while * in this state. All unsolicited frames are forwarded to the io request * object. */ status = sci_io_request_frame_handler(idev->working_request, frame_index); break; } return status; } static bool is_remote_device_ready(struct isci_remote_device *idev) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; switch (state) { case SCI_DEV_READY: case SCI_STP_DEV_IDLE: case SCI_STP_DEV_CMD: case SCI_STP_DEV_NCQ: case SCI_STP_DEV_NCQ_ERROR: case SCI_STP_DEV_AWAIT_RESET: case SCI_SMP_DEV_IDLE: case SCI_SMP_DEV_CMD: return true; default: return false; } } /* * called once the remote node context has transisitioned to a ready * state (after suspending RX and/or TX due to early D2H fis) */ static void atapi_remote_device_resume_done(void *_dev) { struct isci_remote_device *idev = _dev; struct isci_request *ireq = idev->working_request; sci_change_state(&ireq->sm, SCI_REQ_COMPLETED); } enum sci_status sci_remote_device_event_handler(struct isci_remote_device *idev, u32 event_code) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; enum sci_status status; switch (scu_get_event_type(event_code)) { case SCU_EVENT_TYPE_RNC_OPS_MISC: case SCU_EVENT_TYPE_RNC_SUSPEND_TX: case SCU_EVENT_TYPE_RNC_SUSPEND_TX_RX: status = sci_remote_node_context_event_handler(&idev->rnc, event_code); break; case SCU_EVENT_TYPE_PTX_SCHEDULE_EVENT: if (scu_get_event_code(event_code) == SCU_EVENT_IT_NEXUS_TIMEOUT) { status = SCI_SUCCESS; /* Suspend the associated RNC */ sci_remote_node_context_suspend(&idev->rnc, SCI_SOFTWARE_SUSPENSION, NULL, NULL); dev_dbg(scirdev_to_dev(idev), "%s: device: %p event code: %x: %s\n", __func__, idev, event_code, is_remote_device_ready(idev) ? "I_T_Nexus_Timeout event" : "I_T_Nexus_Timeout event in wrong state"); break; } /* Else, fall through and treat as unhandled... */ default: dev_dbg(scirdev_to_dev(idev), "%s: device: %p event code: %x: %s\n", __func__, idev, event_code, is_remote_device_ready(idev) ? "unexpected event" : "unexpected event in wrong state"); status = SCI_FAILURE_INVALID_STATE; break; } if (status != SCI_SUCCESS) return status; if (state == SCI_STP_DEV_ATAPI_ERROR) { /* For ATAPI error state resume the RNC right away. */ if (scu_get_event_type(event_code) == SCU_EVENT_TYPE_RNC_SUSPEND_TX || scu_get_event_type(event_code) == SCU_EVENT_TYPE_RNC_SUSPEND_TX_RX) { return sci_remote_node_context_resume(&idev->rnc, atapi_remote_device_resume_done, idev); } } if (state == SCI_STP_DEV_IDLE) { /* We pick up suspension events to handle specifically to this * state. We resume the RNC right away. */ if (scu_get_event_type(event_code) == SCU_EVENT_TYPE_RNC_SUSPEND_TX || scu_get_event_type(event_code) == SCU_EVENT_TYPE_RNC_SUSPEND_TX_RX) status = sci_remote_node_context_resume(&idev->rnc, NULL, NULL); } return status; } static void sci_remote_device_start_request(struct isci_remote_device *idev, struct isci_request *ireq, enum sci_status status) { struct isci_port *iport = idev->owning_port; /* cleanup requests that failed after starting on the port */ if (status != SCI_SUCCESS) sci_port_complete_io(iport, idev, ireq); else { kref_get(&idev->kref); idev->started_request_count++; } } enum sci_status sci_remote_device_start_io(struct isci_host *ihost, struct isci_remote_device *idev, struct isci_request *ireq) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; struct isci_port *iport = idev->owning_port; enum sci_status status; switch (state) { case SCI_DEV_INITIAL: case SCI_DEV_STOPPED: case SCI_DEV_STARTING: case SCI_STP_DEV_NCQ_ERROR: case SCI_DEV_STOPPING: case SCI_DEV_FAILED: case SCI_DEV_RESETTING: case SCI_DEV_FINAL: default: dev_warn(scirdev_to_dev(idev), "%s: in wrong state: %s\n", __func__, dev_state_name(state)); return SCI_FAILURE_INVALID_STATE; case SCI_DEV_READY: /* attempt to start an io request for this device object. The remote * device object will issue the start request for the io and if * successful it will start the request for the port object then * increment its own request count. */ status = sci_port_start_io(iport, idev, ireq); if (status != SCI_SUCCESS) return status; status = sci_remote_node_context_start_io(&idev->rnc, ireq); if (status != SCI_SUCCESS) break; status = sci_request_start(ireq); break; case SCI_STP_DEV_IDLE: { /* handle the start io operation for a sata device that is in * the command idle state. - Evalute the type of IO request to * be started - If its an NCQ request change to NCQ substate - * If its any other command change to the CMD substate * * If this is a softreset we may want to have a different * substate. */ enum sci_remote_device_states new_state; struct sas_task *task = isci_request_access_task(ireq); status = sci_port_start_io(iport, idev, ireq); if (status != SCI_SUCCESS) return status; status = sci_remote_node_context_start_io(&idev->rnc, ireq); if (status != SCI_SUCCESS) break; status = sci_request_start(ireq); if (status != SCI_SUCCESS) break; if (task->ata_task.use_ncq) new_state = SCI_STP_DEV_NCQ; else { idev->working_request = ireq; new_state = SCI_STP_DEV_CMD; } sci_change_state(sm, new_state); break; } case SCI_STP_DEV_NCQ: { struct sas_task *task = isci_request_access_task(ireq); if (task->ata_task.use_ncq) { status = sci_port_start_io(iport, idev, ireq); if (status != SCI_SUCCESS) return status; status = sci_remote_node_context_start_io(&idev->rnc, ireq); if (status != SCI_SUCCESS) break; status = sci_request_start(ireq); } else return SCI_FAILURE_INVALID_STATE; break; } case SCI_STP_DEV_AWAIT_RESET: return SCI_FAILURE_REMOTE_DEVICE_RESET_REQUIRED; case SCI_SMP_DEV_IDLE: status = sci_port_start_io(iport, idev, ireq); if (status != SCI_SUCCESS) return status; status = sci_remote_node_context_start_io(&idev->rnc, ireq); if (status != SCI_SUCCESS) break; status = sci_request_start(ireq); if (status != SCI_SUCCESS) break; idev->working_request = ireq; sci_change_state(&idev->sm, SCI_SMP_DEV_CMD); break; case SCI_STP_DEV_CMD: case SCI_SMP_DEV_CMD: /* device is already handling a command it can not accept new commands * until this one is complete. */ return SCI_FAILURE_INVALID_STATE; } sci_remote_device_start_request(idev, ireq, status); return status; } static enum sci_status common_complete_io(struct isci_port *iport, struct isci_remote_device *idev, struct isci_request *ireq) { enum sci_status status; status = sci_request_complete(ireq); if (status != SCI_SUCCESS) return status; status = sci_port_complete_io(iport, idev, ireq); if (status != SCI_SUCCESS) return status; sci_remote_device_decrement_request_count(idev); return status; } enum sci_status sci_remote_device_complete_io(struct isci_host *ihost, struct isci_remote_device *idev, struct isci_request *ireq) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; struct isci_port *iport = idev->owning_port; enum sci_status status; switch (state) { case SCI_DEV_INITIAL: case SCI_DEV_STOPPED: case SCI_DEV_STARTING: case SCI_STP_DEV_IDLE: case SCI_SMP_DEV_IDLE: case SCI_DEV_FAILED: case SCI_DEV_FINAL: default: dev_warn(scirdev_to_dev(idev), "%s: in wrong state: %s\n", __func__, dev_state_name(state)); return SCI_FAILURE_INVALID_STATE; case SCI_DEV_READY: case SCI_STP_DEV_AWAIT_RESET: case SCI_DEV_RESETTING: status = common_complete_io(iport, idev, ireq); break; case SCI_STP_DEV_CMD: case SCI_STP_DEV_NCQ: case SCI_STP_DEV_NCQ_ERROR: case SCI_STP_DEV_ATAPI_ERROR: status = common_complete_io(iport, idev, ireq); if (status != SCI_SUCCESS) break; if (ireq->sci_status == SCI_FAILURE_REMOTE_DEVICE_RESET_REQUIRED) { /* This request causes hardware error, device needs to be Lun Reset. * So here we force the state machine to IDLE state so the rest IOs * can reach RNC state handler, these IOs will be completed by RNC with * status of "DEVICE_RESET_REQUIRED", instead of "INVALID STATE". */ sci_change_state(sm, SCI_STP_DEV_AWAIT_RESET); } else if (idev->started_request_count == 0) sci_change_state(sm, SCI_STP_DEV_IDLE); break; case SCI_SMP_DEV_CMD: status = common_complete_io(iport, idev, ireq); if (status != SCI_SUCCESS) break; sci_change_state(sm, SCI_SMP_DEV_IDLE); break; case SCI_DEV_STOPPING: status = common_complete_io(iport, idev, ireq); if (status != SCI_SUCCESS) break; if (idev->started_request_count == 0) sci_remote_node_context_destruct(&idev->rnc, rnc_destruct_done, idev); break; } if (status != SCI_SUCCESS) dev_err(scirdev_to_dev(idev), "%s: Port:0x%p Device:0x%p Request:0x%p Status:0x%x " "could not complete\n", __func__, iport, idev, ireq, status); else isci_put_device(idev); return status; } static void sci_remote_device_continue_request(void *dev) { struct isci_remote_device *idev = dev; /* we need to check if this request is still valid to continue. */ if (idev->working_request) sci_controller_continue_io(idev->working_request); } enum sci_status sci_remote_device_start_task(struct isci_host *ihost, struct isci_remote_device *idev, struct isci_request *ireq) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; struct isci_port *iport = idev->owning_port; enum sci_status status; switch (state) { case SCI_DEV_INITIAL: case SCI_DEV_STOPPED: case SCI_DEV_STARTING: case SCI_SMP_DEV_IDLE: case SCI_SMP_DEV_CMD: case SCI_DEV_STOPPING: case SCI_DEV_FAILED: case SCI_DEV_RESETTING: case SCI_DEV_FINAL: default: dev_warn(scirdev_to_dev(idev), "%s: in wrong state: %s\n", __func__, dev_state_name(state)); return SCI_FAILURE_INVALID_STATE; case SCI_STP_DEV_IDLE: case SCI_STP_DEV_CMD: case SCI_STP_DEV_NCQ: case SCI_STP_DEV_NCQ_ERROR: case SCI_STP_DEV_AWAIT_RESET: status = sci_port_start_io(iport, idev, ireq); if (status != SCI_SUCCESS) return status; status = sci_remote_node_context_start_task(&idev->rnc, ireq); if (status != SCI_SUCCESS) goto out; status = sci_request_start(ireq); if (status != SCI_SUCCESS) goto out; /* Note: If the remote device state is not IDLE this will * replace the request that probably resulted in the task * management request. */ idev->working_request = ireq; sci_change_state(sm, SCI_STP_DEV_CMD); /* The remote node context must cleanup the TCi to NCQ mapping * table. The only way to do this correctly is to either write * to the TLCR register or to invalidate and repost the RNC. In * either case the remote node context state machine will take * the correct action when the remote node context is suspended * and later resumed. */ sci_remote_node_context_suspend(&idev->rnc, SCI_SOFTWARE_SUSPENSION, NULL, NULL); sci_remote_node_context_resume(&idev->rnc, sci_remote_device_continue_request, idev); out: sci_remote_device_start_request(idev, ireq, status); /* We need to let the controller start request handler know that * it can't post TC yet. We will provide a callback function to * post TC when RNC gets resumed. */ return SCI_FAILURE_RESET_DEVICE_PARTIAL_SUCCESS; case SCI_DEV_READY: status = sci_port_start_io(iport, idev, ireq); if (status != SCI_SUCCESS) return status; status = sci_remote_node_context_start_task(&idev->rnc, ireq); if (status != SCI_SUCCESS) break; status = sci_request_start(ireq); break; } sci_remote_device_start_request(idev, ireq, status); return status; } void sci_remote_device_post_request(struct isci_remote_device *idev, u32 request) { struct isci_port *iport = idev->owning_port; u32 context; context = request | (ISCI_PEG << SCU_CONTEXT_COMMAND_PROTOCOL_ENGINE_GROUP_SHIFT) | (iport->physical_port_index << SCU_CONTEXT_COMMAND_LOGICAL_PORT_SHIFT) | idev->rnc.remote_node_index; sci_controller_post_request(iport->owning_controller, context); } /* called once the remote node context has transisitioned to a * ready state. This is the indication that the remote device object can also * transition to ready. */ static void remote_device_resume_done(void *_dev) { struct isci_remote_device *idev = _dev; if (is_remote_device_ready(idev)) return; /* go 'ready' if we are not already in a ready state */ sci_change_state(&idev->sm, SCI_DEV_READY); } static void sci_stp_remote_device_ready_idle_substate_resume_complete_handler(void *_dev) { struct isci_remote_device *idev = _dev; struct isci_host *ihost = idev->owning_port->owning_controller; /* For NCQ operation we do not issue a isci_remote_device_not_ready(). * As a result, avoid sending the ready notification. */ if (idev->sm.previous_state_id != SCI_STP_DEV_NCQ) isci_remote_device_ready(ihost, idev); } static void sci_remote_device_initial_state_enter(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); /* Initial state is a transitional state to the stopped state */ sci_change_state(&idev->sm, SCI_DEV_STOPPED); } /** * sci_remote_device_destruct() - free remote node context and destruct * @remote_device: This parameter specifies the remote device to be destructed. * * Remote device objects are a limited resource. As such, they must be * protected. Thus calls to construct and destruct are mutually exclusive and * non-reentrant. The return value shall indicate if the device was * successfully destructed or if some failure occurred. enum sci_status This value * is returned if the device is successfully destructed. * SCI_FAILURE_INVALID_REMOTE_DEVICE This value is returned if the supplied * device isn't valid (e.g. it's already been destoryed, the handle isn't * valid, etc.). */ static enum sci_status sci_remote_device_destruct(struct isci_remote_device *idev) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; struct isci_host *ihost; if (state != SCI_DEV_STOPPED) { dev_warn(scirdev_to_dev(idev), "%s: in wrong state: %s\n", __func__, dev_state_name(state)); return SCI_FAILURE_INVALID_STATE; } ihost = idev->owning_port->owning_controller; sci_controller_free_remote_node_context(ihost, idev, idev->rnc.remote_node_index); idev->rnc.remote_node_index = SCIC_SDS_REMOTE_NODE_CONTEXT_INVALID_INDEX; sci_change_state(sm, SCI_DEV_FINAL); return SCI_SUCCESS; } /** * isci_remote_device_deconstruct() - This function frees an isci_remote_device. * @ihost: This parameter specifies the isci host object. * @idev: This parameter specifies the remote device to be freed. * */ static void isci_remote_device_deconstruct(struct isci_host *ihost, struct isci_remote_device *idev) { dev_dbg(&ihost->pdev->dev, "%s: isci_device = %p\n", __func__, idev); /* There should not be any outstanding io's. All paths to * here should go through isci_remote_device_nuke_requests. * If we hit this condition, we will need a way to complete * io requests in process */ BUG_ON(!list_empty(&idev->reqs_in_process)); sci_remote_device_destruct(idev); list_del_init(&idev->node); isci_put_device(idev); } static void sci_remote_device_stopped_state_enter(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); struct isci_host *ihost = idev->owning_port->owning_controller; u32 prev_state; /* If we are entering from the stopping state let the SCI User know that * the stop operation has completed. */ prev_state = idev->sm.previous_state_id; if (prev_state == SCI_DEV_STOPPING) isci_remote_device_deconstruct(ihost, idev); sci_controller_remote_device_stopped(ihost, idev); } static void sci_remote_device_starting_state_enter(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); struct isci_host *ihost = idev->owning_port->owning_controller; isci_remote_device_not_ready(ihost, idev, SCIC_REMOTE_DEVICE_NOT_READY_START_REQUESTED); } static void sci_remote_device_ready_state_enter(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); struct isci_host *ihost = idev->owning_port->owning_controller; struct domain_device *dev = idev->domain_dev; if (dev->dev_type == SATA_DEV || (dev->tproto & SAS_PROTOCOL_SATA)) { sci_change_state(&idev->sm, SCI_STP_DEV_IDLE); } else if (dev_is_expander(dev)) { sci_change_state(&idev->sm, SCI_SMP_DEV_IDLE); } else isci_remote_device_ready(ihost, idev); } static void sci_remote_device_ready_state_exit(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); struct domain_device *dev = idev->domain_dev; if (dev->dev_type == SAS_END_DEV) { struct isci_host *ihost = idev->owning_port->owning_controller; isci_remote_device_not_ready(ihost, idev, SCIC_REMOTE_DEVICE_NOT_READY_STOP_REQUESTED); } } static void sci_remote_device_resetting_state_enter(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); sci_remote_node_context_suspend( &idev->rnc, SCI_SOFTWARE_SUSPENSION, NULL, NULL); } static void sci_remote_device_resetting_state_exit(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); sci_remote_node_context_resume(&idev->rnc, NULL, NULL); } static void sci_stp_remote_device_ready_idle_substate_enter(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); idev->working_request = NULL; if (sci_remote_node_context_is_ready(&idev->rnc)) { /* * Since the RNC is ready, it's alright to finish completion * processing (e.g. signal the remote device is ready). */ sci_stp_remote_device_ready_idle_substate_resume_complete_handler(idev); } else { sci_remote_node_context_resume(&idev->rnc, sci_stp_remote_device_ready_idle_substate_resume_complete_handler, idev); } } static void sci_stp_remote_device_ready_cmd_substate_enter(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); struct isci_host *ihost = idev->owning_port->owning_controller; BUG_ON(idev->working_request == NULL); isci_remote_device_not_ready(ihost, idev, SCIC_REMOTE_DEVICE_NOT_READY_SATA_REQUEST_STARTED); } static void sci_stp_remote_device_ready_ncq_error_substate_enter(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); struct isci_host *ihost = idev->owning_port->owning_controller; if (idev->not_ready_reason == SCIC_REMOTE_DEVICE_NOT_READY_SATA_SDB_ERROR_FIS_RECEIVED) isci_remote_device_not_ready(ihost, idev, idev->not_ready_reason); } static void sci_smp_remote_device_ready_idle_substate_enter(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); struct isci_host *ihost = idev->owning_port->owning_controller; isci_remote_device_ready(ihost, idev); } static void sci_smp_remote_device_ready_cmd_substate_enter(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); struct isci_host *ihost = idev->owning_port->owning_controller; BUG_ON(idev->working_request == NULL); isci_remote_device_not_ready(ihost, idev, SCIC_REMOTE_DEVICE_NOT_READY_SMP_REQUEST_STARTED); } static void sci_smp_remote_device_ready_cmd_substate_exit(struct sci_base_state_machine *sm) { struct isci_remote_device *idev = container_of(sm, typeof(*idev), sm); idev->working_request = NULL; } static const struct sci_base_state sci_remote_device_state_table[] = { [SCI_DEV_INITIAL] = { .enter_state = sci_remote_device_initial_state_enter, }, [SCI_DEV_STOPPED] = { .enter_state = sci_remote_device_stopped_state_enter, }, [SCI_DEV_STARTING] = { .enter_state = sci_remote_device_starting_state_enter, }, [SCI_DEV_READY] = { .enter_state = sci_remote_device_ready_state_enter, .exit_state = sci_remote_device_ready_state_exit }, [SCI_STP_DEV_IDLE] = { .enter_state = sci_stp_remote_device_ready_idle_substate_enter, }, [SCI_STP_DEV_CMD] = { .enter_state = sci_stp_remote_device_ready_cmd_substate_enter, }, [SCI_STP_DEV_NCQ] = { }, [SCI_STP_DEV_NCQ_ERROR] = { .enter_state = sci_stp_remote_device_ready_ncq_error_substate_enter, }, [SCI_STP_DEV_ATAPI_ERROR] = { }, [SCI_STP_DEV_AWAIT_RESET] = { }, [SCI_SMP_DEV_IDLE] = { .enter_state = sci_smp_remote_device_ready_idle_substate_enter, }, [SCI_SMP_DEV_CMD] = { .enter_state = sci_smp_remote_device_ready_cmd_substate_enter, .exit_state = sci_smp_remote_device_ready_cmd_substate_exit, }, [SCI_DEV_STOPPING] = { }, [SCI_DEV_FAILED] = { }, [SCI_DEV_RESETTING] = { .enter_state = sci_remote_device_resetting_state_enter, .exit_state = sci_remote_device_resetting_state_exit }, [SCI_DEV_FINAL] = { }, }; /** * sci_remote_device_construct() - common construction * @sci_port: SAS/SATA port through which this device is accessed. * @sci_dev: remote device to construct * * This routine just performs benign initialization and does not * allocate the remote_node_context which is left to * sci_remote_device_[de]a_construct(). sci_remote_device_destruct() * frees the remote_node_context(s) for the device. */ static void sci_remote_device_construct(struct isci_port *iport, struct isci_remote_device *idev) { idev->owning_port = iport; idev->started_request_count = 0; sci_init_sm(&idev->sm, sci_remote_device_state_table, SCI_DEV_INITIAL); sci_remote_node_context_construct(&idev->rnc, SCIC_SDS_REMOTE_NODE_CONTEXT_INVALID_INDEX); } /** * sci_remote_device_da_construct() - construct direct attached device. * * The information (e.g. IAF, Signature FIS, etc.) necessary to build * the device is known to the SCI Core since it is contained in the * sci_phy object. Remote node context(s) is/are a global resource * allocated by this routine, freed by sci_remote_device_destruct(). * * Returns: * SCI_FAILURE_DEVICE_EXISTS - device has already been constructed. * SCI_FAILURE_UNSUPPORTED_PROTOCOL - e.g. sas device attached to * sata-only controller instance. * SCI_FAILURE_INSUFFICIENT_RESOURCES - remote node contexts exhausted. */ static enum sci_status sci_remote_device_da_construct(struct isci_port *iport, struct isci_remote_device *idev) { enum sci_status status; struct sci_port_properties properties; struct domain_device *dev = idev->domain_dev; sci_remote_device_construct(iport, idev); /* * This information is request to determine how many remote node context * entries will be needed to store the remote node. */ idev->is_direct_attached = true; sci_port_get_properties(iport, &properties); /* Get accurate port width from port's phy mask for a DA device. */ idev->device_port_width = hweight32(properties.phy_mask); status = sci_controller_allocate_remote_node_context(iport->owning_controller, idev, &idev->rnc.remote_node_index); if (status != SCI_SUCCESS) return status; if (dev->dev_type == SAS_END_DEV || dev->dev_type == SATA_DEV || (dev->tproto & SAS_PROTOCOL_STP) || dev_is_expander(dev)) /* pass */; else return SCI_FAILURE_UNSUPPORTED_PROTOCOL; idev->connection_rate = sci_port_get_max_allowed_speed(iport); return SCI_SUCCESS; } /** * sci_remote_device_ea_construct() - construct expander attached device * * Remote node context(s) is/are a global resource allocated by this * routine, freed by sci_remote_device_destruct(). * * Returns: * SCI_FAILURE_DEVICE_EXISTS - device has already been constructed. * SCI_FAILURE_UNSUPPORTED_PROTOCOL - e.g. sas device attached to * sata-only controller instance. * SCI_FAILURE_INSUFFICIENT_RESOURCES - remote node contexts exhausted. */ static enum sci_status sci_remote_device_ea_construct(struct isci_port *iport, struct isci_remote_device *idev) { struct domain_device *dev = idev->domain_dev; enum sci_status status; sci_remote_device_construct(iport, idev); status = sci_controller_allocate_remote_node_context(iport->owning_controller, idev, &idev->rnc.remote_node_index); if (status != SCI_SUCCESS) return status; if (dev->dev_type == SAS_END_DEV || dev->dev_type == SATA_DEV || (dev->tproto & SAS_PROTOCOL_STP) || dev_is_expander(dev)) /* pass */; else return SCI_FAILURE_UNSUPPORTED_PROTOCOL; /* * For SAS-2 the physical link rate is actually a logical link * rate that incorporates multiplexing. The SCU doesn't * incorporate multiplexing and for the purposes of the * connection the logical link rate is that same as the * physical. Furthermore, the SAS-2 and SAS-1.1 fields overlay * one another, so this code works for both situations. */ idev->connection_rate = min_t(u16, sci_port_get_max_allowed_speed(iport), dev->linkrate); /* / @todo Should I assign the port width by reading all of the phys on the port? */ idev->device_port_width = 1; return SCI_SUCCESS; } /** * sci_remote_device_start() - This method will start the supplied remote * device. This method enables normal IO requests to flow through to the * remote device. * @remote_device: This parameter specifies the device to be started. * @timeout: This parameter specifies the number of milliseconds in which the * start operation should complete. * * An indication of whether the device was successfully started. SCI_SUCCESS * This value is returned if the device was successfully started. * SCI_FAILURE_INVALID_PHY This value is returned if the user attempts to start * the device when there have been no phys added to it. */ static enum sci_status sci_remote_device_start(struct isci_remote_device *idev, u32 timeout) { struct sci_base_state_machine *sm = &idev->sm; enum sci_remote_device_states state = sm->current_state_id; enum sci_status status; if (state != SCI_DEV_STOPPED) { dev_warn(scirdev_to_dev(idev), "%s: in wrong state: %s\n", __func__, dev_state_name(state)); return SCI_FAILURE_INVALID_STATE; } status = sci_remote_node_context_resume(&idev->rnc, remote_device_resume_done, idev); if (status != SCI_SUCCESS) return status; sci_change_state(sm, SCI_DEV_STARTING); return SCI_SUCCESS; } static enum sci_status isci_remote_device_construct(struct isci_port *iport, struct isci_remote_device *idev) { struct isci_host *ihost = iport->isci_host; struct domain_device *dev = idev->domain_dev; enum sci_status status; if (dev->parent && dev_is_expander(dev->parent)) status = sci_remote_device_ea_construct(iport, idev); else status = sci_remote_device_da_construct(iport, idev); if (status != SCI_SUCCESS) { dev_dbg(&ihost->pdev->dev, "%s: construct failed: %d\n", __func__, status); return status; } /* start the device. */ status = sci_remote_device_start(idev, ISCI_REMOTE_DEVICE_START_TIMEOUT); if (status != SCI_SUCCESS) dev_warn(&ihost->pdev->dev, "remote device start failed: %d\n", status); return status; } void isci_remote_device_nuke_requests(struct isci_host *ihost, struct isci_remote_device *idev) { DECLARE_COMPLETION_ONSTACK(aborted_task_completion); dev_dbg(&ihost->pdev->dev, "%s: idev = %p\n", __func__, idev); /* Cleanup all requests pending for this device. */ isci_terminate_pending_requests(ihost, idev); dev_dbg(&ihost->pdev->dev, "%s: idev = %p, done\n", __func__, idev); } /** * This function builds the isci_remote_device when a libsas dev_found message * is received. * @isci_host: This parameter specifies the isci host object. * @port: This parameter specifies the isci_port conected to this device. * * pointer to new isci_remote_device. */ static struct isci_remote_device * isci_remote_device_alloc(struct isci_host *ihost, struct isci_port *iport) { struct isci_remote_device *idev; int i; for (i = 0; i < SCI_MAX_REMOTE_DEVICES; i++) { idev = &ihost->devices[i]; if (!test_and_set_bit(IDEV_ALLOCATED, &idev->flags)) break; } if (i >= SCI_MAX_REMOTE_DEVICES) { dev_warn(&ihost->pdev->dev, "%s: failed\n", __func__); return NULL; } if (WARN_ONCE(!list_empty(&idev->reqs_in_process), "found requests in process\n")) return NULL; if (WARN_ONCE(!list_empty(&idev->node), "found non-idle remote device\n")) return NULL; return idev; } void isci_remote_device_release(struct kref *kref) { struct isci_remote_device *idev = container_of(kref, typeof(*idev), kref); struct isci_host *ihost = idev->isci_port->isci_host; idev->domain_dev = NULL; idev->isci_port = NULL; clear_bit(IDEV_START_PENDING, &idev->flags); clear_bit(IDEV_STOP_PENDING, &idev->flags); clear_bit(IDEV_IO_READY, &idev->flags); clear_bit(IDEV_GONE, &idev->flags); smp_mb__before_clear_bit(); clear_bit(IDEV_ALLOCATED, &idev->flags); wake_up(&ihost->eventq); } /** * isci_remote_device_stop() - This function is called internally to stop the * remote device. * @isci_host: This parameter specifies the isci host object. * @isci_device: This parameter specifies the remote device. * * The status of the ihost request to stop. */ enum sci_status isci_remote_device_stop(struct isci_host *ihost, struct isci_remote_device *idev) { enum sci_status status; unsigned long flags; dev_dbg(&ihost->pdev->dev, "%s: isci_device = %p\n", __func__, idev); spin_lock_irqsave(&ihost->scic_lock, flags); idev->domain_dev->lldd_dev = NULL; /* disable new lookups */ set_bit(IDEV_GONE, &idev->flags); spin_unlock_irqrestore(&ihost->scic_lock, flags); /* Kill all outstanding requests. */ isci_remote_device_nuke_requests(ihost, idev); set_bit(IDEV_STOP_PENDING, &idev->flags); spin_lock_irqsave(&ihost->scic_lock, flags); status = sci_remote_device_stop(idev, 50); spin_unlock_irqrestore(&ihost->scic_lock, flags); /* Wait for the stop complete callback. */ if (WARN_ONCE(status != SCI_SUCCESS, "failed to stop device\n")) /* nothing to wait for */; else wait_for_device_stop(ihost, idev); return status; } /** * isci_remote_device_gone() - This function is called by libsas when a domain * device is removed. * @domain_device: This parameter specifies the libsas domain device. * */ void isci_remote_device_gone(struct domain_device *dev) { struct isci_host *ihost = dev_to_ihost(dev); struct isci_remote_device *idev = dev->lldd_dev; dev_dbg(&ihost->pdev->dev, "%s: domain_device = %p, isci_device = %p, isci_port = %p\n", __func__, dev, idev, idev->isci_port); isci_remote_device_stop(ihost, idev); } /** * isci_remote_device_found() - This function is called by libsas when a remote * device is discovered. A remote device object is created and started. the * function then sleeps until the sci core device started message is * received. * @domain_device: This parameter specifies the libsas domain device. * * status, zero indicates success. */ int isci_remote_device_found(struct domain_device *dev) { struct isci_host *isci_host = dev_to_ihost(dev); struct isci_port *isci_port = dev->port->lldd_port; struct isci_remote_device *isci_device; enum sci_status status; dev_dbg(&isci_host->pdev->dev, "%s: domain_device = %p\n", __func__, dev); if (!isci_port) return -ENODEV; isci_device = isci_remote_device_alloc(isci_host, isci_port); if (!isci_device) return -ENODEV; kref_init(&isci_device->kref); INIT_LIST_HEAD(&isci_device->node); spin_lock_irq(&isci_host->scic_lock); isci_device->domain_dev = dev; isci_device->isci_port = isci_port; list_add_tail(&isci_device->node, &isci_port->remote_dev_list); set_bit(IDEV_START_PENDING, &isci_device->flags); status = isci_remote_device_construct(isci_port, isci_device); dev_dbg(&isci_host->pdev->dev, "%s: isci_device = %p\n", __func__, isci_device); if (status == SCI_SUCCESS) { /* device came up, advertise it to the world */ dev->lldd_dev = isci_device; } else isci_put_device(isci_device); spin_unlock_irq(&isci_host->scic_lock); /* wait for the device ready callback. */ wait_for_device_start(isci_host, isci_device); return status == SCI_SUCCESS ? 0 : -ENODEV; }
{ "pile_set_name": "Github" }
/* * 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.commons.math.ode.sampling; import org.apache.commons.math.exception.MathUserException; import org.apache.commons.math.ode.FirstOrderIntegrator; import org.apache.commons.math.ode.IntegratorException; import org.apache.commons.math.ode.TestProblem3; import org.apache.commons.math.ode.nonstiff.DormandPrince54Integrator; import org.apache.commons.math.ode.sampling.FixedStepHandler; import org.apache.commons.math.ode.sampling.StepNormalizer; import org.apache.commons.math.util.FastMath; import junit.framework.*; public class StepNormalizerTest extends TestCase { public StepNormalizerTest(String name) { super(name); pb = null; integ = null; } public void testBoundaries() throws MathUserException, IntegratorException { double range = pb.getFinalTime() - pb.getInitialTime(); setLastSeen(false); integ.addStepHandler(new StepNormalizer(range / 10.0, new FixedStepHandler() { private static final long serialVersionUID = 1650337364641626444L; private boolean firstCall = true; public void handleStep(double t, double[] y, double[] yDot, boolean isLast) { if (firstCall) { checkValue(t, pb.getInitialTime()); firstCall = false; } if (isLast) { setLastSeen(true); checkValue(t, pb.getFinalTime()); } } })); integ.integrate(pb, pb.getInitialTime(), pb.getInitialState(), pb.getFinalTime(), new double[pb.getDimension()]); assertTrue(lastSeen); } public void testBeforeEnd() throws MathUserException, IntegratorException { final double range = pb.getFinalTime() - pb.getInitialTime(); setLastSeen(false); integ.addStepHandler(new StepNormalizer(range / 10.5, new FixedStepHandler() { private static final long serialVersionUID = 2228457391561277298L; public void handleStep(double t, double[] y, double[] yDot, boolean isLast) { if (isLast) { setLastSeen(true); checkValue(t, pb.getFinalTime() - range / 21.0); } } })); integ.integrate(pb, pb.getInitialTime(), pb.getInitialState(), pb.getFinalTime(), new double[pb.getDimension()]); assertTrue(lastSeen); } public void checkValue(double value, double reference) { assertTrue(FastMath.abs(value - reference) < 1.0e-10); } public void setLastSeen(boolean lastSeen) { this.lastSeen = lastSeen; } @Override public void setUp() { pb = new TestProblem3(0.9); double minStep = 0; double maxStep = pb.getFinalTime() - pb.getInitialTime(); integ = new DormandPrince54Integrator(minStep, maxStep, 10.e-8, 1.0e-8); lastSeen = false; } @Override public void tearDown() { pb = null; integ = null; } TestProblem3 pb; FirstOrderIntegrator integ; boolean lastSeen; }
{ "pile_set_name": "Github" }
// ============================================================================= // Mathigon.org | Graph Geometry Functions // (c) Mathigon // ============================================================================= import {list, repeat} from '@mathigon/core'; import {permutations} from '@mathigon/fermat'; export function travellingSalesman(dist: number[][]) { const n = dist.length; const cities = list(n); let minLength = Infinity; let minPath = undefined; loop1: for (const path of permutations(cities)) { let length = 0; for (let i = 0; i < n - 1; ++i) { length += dist[path[i]][path[i + 1]]; if (length > minLength) continue loop1; } if (length < minLength) { minLength = length; minPath = path; } } return {path: minPath, length: minLength}; } const COLOURS = [1, 2, 3, 4]; function canColour(adjMatrix: number[][], colours: number[], index: number, colour: number) { for (let i = 0; i < index; ++i) { if (adjMatrix[i][index] && colours[i] === colour) return false; } return true; } function colourMe(adjMatrix: number[][], colours: number[], index: number) { for (const c of COLOURS) { if (canColour(adjMatrix, colours, index, c)) { colours[index] = c; if (colourMe(adjMatrix, colours, index + 1)) return true; } } return false; } export function graphColouring(adjMatrix: number[][]) { const colours = repeat(0, adjMatrix.length); const result = colourMe(adjMatrix, colours, 0); return result ? colours : undefined; }
{ "pile_set_name": "Github" }
<?php namespace Sabre\Xml; use LibXMLError; /** * This exception is thrown when the Readers runs into a parsing error. * * This exception effectively wraps 1 or more LibXMLError objects. * * @copyright Copyright (C) 2009-2015 fruux GmbH (https://fruux.com/). * @author Evert Pot (http://evertpot.com/) * @license http://sabre.io/license/ Modified BSD License */ class LibXMLException extends ParseException { /** * The error list. * * @var LibXMLError[] */ protected $errors; /** * Creates the exception. * * You should pass a list of LibXMLError objects in its constructor. * * @param LibXMLError[] $errors * @param int $code * @param Exception $previousException */ function __construct(array $errors, $code = null, Exception $previousException = null) { $this->errors = $errors; parent::__construct($errors[0]->message . ' on line ' . $errors[0]->line . ', column ' . $errors[0]->column, $code, $previousException); } /** * Returns the LibXML errors * * @return void */ function getErrors() { return $this->errors; } }
{ "pile_set_name": "Github" }
class AnnotationText < ApplicationRecord belongs_to :creator, class_name: 'User', foreign_key: :creator_id belongs_to :last_editor, class_name: 'User', foreign_key: :last_editor_id, optional: true after_update :update_mark_deductions before_update :check_if_released, unless: ->(t) { t.deduction.nil? } before_destroy :check_if_released, unless: ->(t) { t.deduction.nil? } # An AnnotationText has many Annotations that are destroyed when an # AnnotationText is destroyed. has_many :annotations, dependent: :destroy belongs_to :annotation_category, optional: true, counter_cache: true validates_associated :annotation_category, on: :create validates_numericality_of :deduction, if: :should_have_deduction?, greater_than_or_equal_to: 0, less_than_or_equal_to: ->(t) { t.annotation_category.flexible_criterion.max_mark } validates_absence_of :deduction, unless: :should_have_deduction? def should_have_deduction? !self&.annotation_category&.flexible_criterion_id.nil? end def escape_content content.gsub('\\', '\\\\\\') # Replaces '\\' with '\\\\' .gsub(/\r?\n/, '\\n') end def check_if_released # Cannot update if any results have been released with the annotation and the deduction is non nil return if self.annotations.joins(:result).where('results.released_to_students' => true).empty? errors.add(:base, 'Cannot update/destroy annotation_text once results are released.') throw(:abort) end def update_mark_deductions return unless previous_changes.key?('deduction') if self.annotation_category.changes_to_save.key?('flexible_criterion_id') criterion = FlexibleCriterion.find_by(id: self.annotation_category .changes_to_save['flexible_criterion_id'] .first) return if criterion.nil? || criterion.marks == [] criterion_id = self.annotation_category.changes_to_save['flexible_criterion_id'].first else criterion_id = self.annotation_category.flexible_criterion_id end annotations = self.annotations.includes(:result) annotations.each do |annotation| annotation.result.marks .find_by(criterion_id: criterion_id) .update_deduction end end def scale_deduction(scalar) return if self.deduction.nil? prev_deduction = self.deduction self.update!(deduction: (prev_deduction * scalar).round(2)) end def uses # TODO: simplify second join once creator is no longer polymoprhic self.annotations .joins(result: { grouping: :group }) .joins('INNER JOIN users ON annotations.creator_id = users.id') .order('groups.group_name') .group('results.id', 'groupings.assessment_id', 'results.submission_id', 'groups.group_name', 'users.first_name', 'users.last_name', 'users.user_name') .pluck_to_hash('results.id AS result_id', 'groupings.assessment_id AS assignment_id', 'results.submission_id AS submission_id', 'groups.group_name AS group_name', 'users.first_name AS first_name', 'users.last_name AS last_name', 'users.user_name AS user_name', Arel.sql('count(*) AS count')) end end
{ "pile_set_name": "Github" }
Cython >=0.20.2
{ "pile_set_name": "Github" }
<?php namespace Fisharebest\Localization\Territory; /** * Class AbstractTerritory - Representation of the territory AX - Åland Islands. * * @author Greg Roach <[email protected]> * @copyright (c) 2019 Greg Roach * @license GPLv3+ */ class TerritoryAx extends AbstractTerritory implements TerritoryInterface { public function code() { return 'AX'; } }
{ "pile_set_name": "Github" }
<div data-ds-hide="edit" class="btn-group" align="left"> <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu dropdown-menu-right ds-action-menu" role="menu"> {{actions 'presentation-transform-actions'}} {{actions 'presentation-actions' true}} {{actions item.item_type true}} </ul> </div>
{ "pile_set_name": "Github" }
//-------------------------------------------- // Linux/Mac/FreeBSD //-------------------------------------------- The build for Linux/Mac/FreeBSD uses the default Linux build: from the trunk/ directory, run: Pre-requisits: Mac: wxWidgets 2.9.5 or later Linux/FreeBSD: wxWidgets 2.9.5 or later, gtk2 development package, cmake Building: //----------------------------------------------------- // Linux/FreeBSD //----------------------------------------------------- In the CodeLite source dir, do: mkdir build-release cd build-release cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release .. make (Become the superuser) make install There are various other options that you could pass to cmake. See CMakeLists.txt for the commonest. //----------------------------------------------------- // Windows: MinGW //----------------------------------------------------- To build: Download CodeLite for Windows + wxWidgets development 2.9.5 from here: (2 installers ): https://sourceforge.net/projects/codelite/files/Releases/ Install them - it is recommended to _accept_ the default options suggested by the installer Step 1: Load the workspace codelite-sources/LiteEditor.workspace - and hit 'F7' ** Make sure that the active project (bold text) is set to "CodeLiteIDE" ** Step 2: Close the current workspace Load the workspace codelite-sources/codelite_utils/codelite_utils.workspace Step 3: Select the 'Release' configuration and build it using F7 Once build is done, you can copy the files to the target directory by running the script: codelite-sources/Runtime/update.bat **** Note that you may need to update the script to point it to the codelite installation directory **** //--------------------------------------------------------- // MacOSX //--------------------------------------------------------- You should have wxWidgets 2.9.5 or higher To build wx under Mac, download the latest source package and build it as follows: $> cd wx-sources/ $> mkdir build-release $> cd build-release $> ../configure --disable-debug --with-osx_cocoa --enable-shared --enable-monolithic $> make -j4 $> sudo make install Next, build codelite: $> cd codelite-src/ $> ./mac-build.sh --cmake ... codelite will compile and will create a bundle, to run it: $> open build-release/pack/codelite.app/ Enjoy, Eran
{ "pile_set_name": "Github" }
using System; using System.Collections; using NUnit.Framework; using Org.BouncyCastle.Asn1; using Asn1Cms = Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Utilities.Test; namespace Org.BouncyCastle.Asn1.Tests { [TestFixture] public class AttributeTableUnitTest : SimpleTest { private static readonly DerObjectIdentifier type1 = new DerObjectIdentifier("1.1.1"); private static readonly DerObjectIdentifier type2 = new DerObjectIdentifier("1.1.2"); private static readonly DerObjectIdentifier type3 = new DerObjectIdentifier("1.1.3"); public override string Name { get { return "AttributeTable"; } } public override void PerformTest() { Asn1EncodableVector v = new Asn1EncodableVector( new Asn1Cms.Attribute(type1, new DerSet(type1)), new Asn1Cms.Attribute(type2, new DerSet(type2))); Asn1Cms.AttributeTable table = new Asn1Cms.AttributeTable(v); Asn1Cms.Attribute a = table[type1]; if (a == null) { Fail("type1 attribute not found."); } if (!a.AttrValues.Equals(new DerSet(type1))) { Fail("wrong value retrieved for type1!"); } a = table[type2]; if (a == null) { Fail("type2 attribute not found."); } if (!a.AttrValues.Equals(new DerSet(type2))) { Fail("wrong value retrieved for type2!"); } a = table[type3]; if (a != null) { Fail("type3 attribute found when none expected."); } Asn1EncodableVector vec = table.GetAll(type1); if (vec.Count != 1) { Fail("wrong vector size for type1."); } vec = table.GetAll(type3); if (vec.Count != 0) { Fail("wrong vector size for type3."); } vec = table.ToAsn1EncodableVector(); if (vec.Count != 2) { Fail("wrong vector size for single."); } IDictionary t = table.ToDictionary(); if (t.Count != 2) { Fail("hashtable wrong size."); } // multiple v = new Asn1EncodableVector( new Asn1Cms.Attribute(type1, new DerSet(type1)), new Asn1Cms.Attribute(type1, new DerSet(type2)), new Asn1Cms.Attribute(type1, new DerSet(type3)), new Asn1Cms.Attribute(type2, new DerSet(type2))); table = new Asn1Cms.AttributeTable(v); a = table[type1]; if (!a.AttrValues.Equals(new DerSet(type1))) { Fail("wrong value retrieved for type1 multi Get!"); } vec = table.GetAll(type1); if (vec.Count != 3) { Fail("wrong vector size for multiple type1."); } a = (Asn1Cms.Attribute)vec[0]; if (!a.AttrValues.Equals(new DerSet(type1))) { Fail("wrong value retrieved for type1(0)!"); } a = (Asn1Cms.Attribute)vec[1]; if (!a.AttrValues.Equals(new DerSet(type2))) { Fail("wrong value retrieved for type1(1)!"); } a = (Asn1Cms.Attribute)vec[2]; if (!a.AttrValues.Equals(new DerSet(type3))) { Fail("wrong value retrieved for type1(2)!"); } vec = table.GetAll(type2); if (vec.Count != 1) { Fail("wrong vector size for multiple type2."); } vec = table.ToAsn1EncodableVector(); if (vec.Count != 4) { Fail("wrong vector size for multiple."); } } public static void Main( string[] args) { RunTest(new AttributeTableUnitTest()); } [Test] public void TestFunction() { string resultText = Perform().ToString(); Assert.AreEqual(Name + ": Okay", resultText); } } }
{ "pile_set_name": "Github" }
/** * Copyright (c) 2015, The Regents of the University of California, * through Lawrence Berkeley National Laboratory (subject to receipt * of any required approvals from the U.S. Dept. of Energy). * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ /* eslint max-len:0 */ /* eslint-disable react/prefer-es6-class */ import "moment-duration-format"; import moment from "moment"; import React from "react"; import { format } from "d3-format"; import _ from "underscore"; // Pond import { TimeSeries, TimeRange, avg, percentile, median } from "pondjs"; // Imports from the charts library import AreaChart from "../../../../../components/AreaChart"; import Baseline from "../../../../../components/Baseline"; import BoxChart from "../../../../../components/BoxChart"; import Brush from "../../../../../components/Brush"; import ChartContainer from "../../../../../components/ChartContainer"; import ChartRow from "../../../../../components/ChartRow"; import Charts from "../../../../../components/Charts"; import LabelAxis from "../../../../../components/LabelAxis"; import LineChart from "../../../../../components/LineChart"; import Resizable from "../../../../../components/Resizable"; import ValueAxis from "../../../../../components/ValueAxis"; import YAxis from "../../../../../components/YAxis"; import styler from "../../../../../js/styler"; import Legend from "../../../../../components/Legend"; import cycling_docs from "./cycling_docs.md"; import cycling_thumbnail from "./cycling_thumbnail.png"; // // Load our data file // const data = require("./bike.json"); // Styling relates a channel to its rendering properties. In this way you // can achieve consistent styles across different charts and labels by supplying // the components with this styler object const style = styler([ { key: "distance", color: "#e2e2e2" }, { key: "altitude", color: "#e2e2e2" }, { key: "cadence", color: "#ff47ff" }, { key: "power", color: "green", width: 1, opacity: 0.5 }, { key: "temperature", color: "#cfc793" }, { key: "speed", color: "steelblue", width: 1, opacity: 0.5 } ]); // Baselines are the dotted average lines displayed on the chart // In this case these are separately styled const baselineStyles = { speed: { stroke: "steelblue", opacity: 0.5, width: 0.25 }, power: { stroke: "green", opacity: 0.5, width: 0.25 } }; // d3 formatter to display the speed with one decimal place const speedFormat = format(".1f"); class cycling extends React.Component { constructor(props) { super(props); const initialRange = new TimeRange([75 * 60 * 1000, 125 * 60 * 1000]); // Storage for all the data channels const channels = { distance: { units: "miles", label: "Distance", format: ",.1f", series: null, show: false }, altitude: { units: "feet", label: "Altitude", format: "d", series: null, show: false }, cadence: { units: "rpm", label: "Cadence", format: "d", series: null, show: true }, power: { units: "watts", label: "Power", format: ",.1f", series: null, show: true }, temperature: { units: "deg F", label: "Temp", format: "d", series: null, show: false }, speed: { units: "mph", label: "Speed", format: ",.1f", series: null, show: true } }; // Channel names list, in order we want them shown const channelNames = ["speed", "power", "cadence", "temperature", "distance", "altitude"]; // Channels we'll actually display on our charts const displayChannels = ["speed", "power", "cadence"]; // Rollups we'll generate to reduce data for the screen const rollupLevels = ["1s", "5s", "15s", "25s"]; this.state = { ready: false, mode: "channels", channels, channelNames, displayChannels, rollupLevels, rollup: "1m", tracker: null, timerange: initialRange, brushrange: initialRange }; } componentDidMount() { setTimeout(() => { const { channelNames, channels, displayChannels, rollupLevels } = this.state; // // Process the data file into channels // const points = {}; channelNames.forEach(channel => { points[channel] = []; }); for (let i = 0; i < data.time.length; i += 1) { if (i > 0) { const deltaTime = data.time[i] - data.time[i - 1]; const time = data.time[i] * 1000; points["distance"].push([time, data.distance[i]]); points["altitude"].push([time, data.altitude[i] * 3.28084]); // convert m to ft points["cadence"].push([time, data.cadence[i]]); points["power"].push([time, data.watts[i]]); points["temperature"].push([time, data.temp[i]]); // insert a null into the speed data to put breaks in the data where // the rider was stationary if (deltaTime > 10) { points["speed"].push([time - 1000, null]); } const speed = (data.distance[i] - data.distance[i - 1]) / (data.time[i] - data.time[i - 1]); // meters/sec points["speed"].push([time, 2.236941 * speed]); // convert m/s to miles/hr } } // Make the TimeSeries here from the points collected above for (let channelName of channelNames) { // The TimeSeries itself, for this channel const series = new TimeSeries({ name: channels[channelName].name, columns: ["time", channelName], points: points[channelName] }); if (_.contains(displayChannels, channelName)) { const rollups = _.map(rollupLevels, rollupLevel => { return { duration: parseInt(rollupLevel.split("s")[0], 10), series: series.fixedWindowRollup({ windowSize: rollupLevel, aggregation: { [channelName]: { [channelName]: avg() } } }) }; }); // Rollup series levels channels[channelName].rollups = rollups; } // Raw series channels[channelName].series = series; // Some simple statistics for each channel channels[channelName].avg = parseInt(series.avg(channelName), 10); channels[channelName].max = parseInt(series.max(channelName), 10); } // Min and max time constraints for pan/zoom, along with the smallest timerange // the user can zoom into. These are passed into the ChartContainers when we come to // rendering. const minTime = channels.altitude.series.range().begin(); const maxTime = channels.altitude.series.range().end(); const minDuration = 10 * 60 * 1000; this.setState({ ready: true, channels, minTime, maxTime, minDuration }); }, 0); } handleTrackerChanged = t => { this.setState({ tracker: t }); }; // Handles when the brush changes the timerange handleTimeRangeChange = timerange => { const { channels } = this.state; if (timerange) { this.setState({ timerange, brushrange: timerange }); } else { this.setState({ timerange: channels["altitude"].range(), brushrange: null }); } }; handleChartResize = width => { this.setState({ width }); }; handleActiveChange = channelName => { const channels = this.state.channels; channels[channelName].show = !channels[channelName].show; this.setState({ channels }); }; renderChart = () => { if (this.state.mode === "multiaxis") { return this.renderMultiAxisChart(); } else if (this.state.mode === "channels") { return this.renderChannelsChart(); } else if (this.state.mode === "rollup") { return this.renderBoxChart(); } return <div>No chart</div>; }; renderChannelsChart = () => { const { timerange, displayChannels, channels, maxTime, minTime, minDuration } = this.state; const durationPerPixel = timerange.duration() / 800 / 1000; const rows = []; for (let channelName of displayChannels) { const charts = []; let series = channels[channelName].series; _.forEach(channels[channelName].rollups, rollup => { if (rollup.duration < durationPerPixel * 2) { series = rollup.series.crop(timerange); } }); charts.push( <LineChart key={`line-${channelName}`} axis={`${channelName}_axis`} series={series} columns={[channelName]} style={style} breakLine /> ); charts.push( <Baseline key={`baseline-${channelName}`} axis={`${channelName}_axis`} style={baselineStyles.speed} value={channels[channelName].avg} /> ); // Get the value at the current tracker position for the ValueAxis let value = "--"; if (this.state.tracker) { const approx = (+this.state.tracker - +timerange.begin()) / (+timerange.end() - +timerange.begin()); const ii = Math.floor(approx * series.size()); const i = series.bisect(new Date(this.state.tracker), ii); const v = i < series.size() ? series.at(i).get(channelName) : null; if (v) { value = parseInt(v, 10); } } // Get the summary values for the LabelAxis const summary = [ { label: "Max", value: speedFormat(channels[channelName].max) }, { label: "Avg", value: speedFormat(channels[channelName].avg) } ]; rows.push( <ChartRow height="100" visible={channels[channelName].show} key={`row-${channelName}`} > <LabelAxis id={`${channelName}_axis`} label={channels[channelName].label} values={summary} min={0} max={channels[channelName].max} width={140} type="linear" format=",.1f" /> <Charts>{charts}</Charts> <ValueAxis id={`${channelName}_valueaxis`} value={value} detail={channels[channelName].units} width={80} min={0} max={35} /> </ChartRow> ); } return ( <ChartContainer timeRange={this.state.timerange} format="relative" showGrid={false} enablePanZoom maxTime={maxTime} minTime={minTime} minDuration={minDuration} trackerPosition={this.state.tracker} onTimeRangeChanged={this.handleTimeRangeChange} onChartResize={width => this.handleChartResize(width)} onTrackerChanged={this.handleTrackerChanged} > {rows} </ChartContainer> ); }; renderBoxChart = () => { const { timerange, displayChannels, channels, maxTime, minTime, minDuration } = this.state; const rows = []; for (let channelName of displayChannels) { const charts = []; const series = channels[channelName].series; charts.push( <BoxChart key={`box-${channelName}`} axis={`${channelName}_axis`} series={series} column={channelName} style={style} aggregation={{ size: this.state.rollup, reducers: { outer: [percentile(5), percentile(95)], inner: [percentile(25), percentile(75)], center: median() } }} /> ); charts.push( <Baseline key={`baseline-${channelName}`} axis={`${channelName}_axis`} style={baselineStyles.speed} value={channels[channelName].avg} /> ); // Get the value at the current tracker position for the ValueAxis let value = "--"; if (this.state.tracker) { const approx = (+this.state.tracker - +timerange.begin()) / (+timerange.end() - +timerange.begin()); const ii = Math.floor(approx * series.size()); const i = series.bisect(new Date(this.state.tracker), ii); const v = i < series.size() ? series.at(i).get(channelName) : null; if (v) { value = parseInt(v, 10); } } // Get the summary values for the LabelAxis const summary = [ { label: "Max", value: speedFormat(channels[channelName].max) }, { label: "Avg", value: speedFormat(channels[channelName].avg) } ]; rows.push( <ChartRow height="100" visible={channels[channelName].show} key={`row-${channelName}`} > <LabelAxis id={`${channelName}_axis`} label={channels[channelName].label} values={summary} min={0} max={channels[channelName].max} width={140} type="linear" format=",.1f" /> <Charts>{charts}</Charts> <ValueAxis id={`${channelName}_valueaxis`} value={value} detail={channels[channelName].units} width={80} min={0} max={35} /> </ChartRow> ); } return ( <ChartContainer timeRange={this.state.timerange} format="relative" showGrid={false} enablePanZoom maxTime={maxTime} minTime={minTime} minDuration={minDuration} trackerPosition={this.state.tracker} onTimeRangeChanged={this.handleTimeRangeChange} onChartResize={width => this.handleChartResize(width)} onTrackerChanged={this.handleTrackerChanged} > {rows} </ChartContainer> ); }; renderMultiAxisChart() { const { timerange, displayChannels, channels, maxTime, minTime, minDuration } = this.state; const durationPerPixel = timerange.duration() / 800 / 1000; // Line charts const charts = []; for (let channelName of displayChannels) { let series = channels[channelName].series; _.forEach(channels[channelName].rollups, rollup => { if (rollup.duration < durationPerPixel * 2) { series = rollup.series.crop(timerange); } }); charts.push( <LineChart key={`line-${channelName}`} axis={`${channelName}_axis`} visible={channels[channelName].show} series={series} columns={[channelName]} style={style} breakLine /> ); } // Tracker info box const trackerInfoValues = displayChannels .filter(channelName => channels[channelName].show) .map(channelName => { const fmt = format(channels[channelName].format); let series = channels[channelName].series.crop(timerange); let v = "--"; if (this.state.tracker) { const i = series.bisect(new Date(this.state.tracker)); const vv = series.at(i).get(channelName); if (vv) { v = fmt(vv); } } const label = channels[channelName].label; const value = `${v} ${channels[channelName].units}`; return { label, value }; }); // Axis list const axisList = []; for (let channelName of displayChannels) { const label = channels[channelName].label; const max = channels[channelName].max; const format = channels[channelName].format; const id = `${channelName}_axis`; const visible = channels[channelName].show; axisList.push( <YAxis id={id} key={id} visible={visible} label={label} min={0} max={max} width={70} type="linear" format={format} /> ); } return ( <ChartContainer timeRange={this.state.timerange} format="relative" trackerPosition={this.state.tracker} onTrackerChanged={this.handleTrackerChanged} trackerShowTime enablePanZoom maxTime={maxTime} minTime={minTime} minDuration={minDuration} onTimeRangeChanged={this.handleTimeRangeChange} > <ChartRow height="200" trackerInfoValues={trackerInfoValues} trackerInfoHeight={10 + trackerInfoValues.length * 16} trackerInfoWidth={140} > {axisList} <Charts>{charts}</Charts> </ChartRow> </ChartContainer> ); } renderBrush = () => { const { channels } = this.state; return ( <ChartContainer timeRange={channels.altitude.series.range()} format="relative" trackerPosition={this.state.tracker} > <ChartRow height="100" debug={false}> <Brush timeRange={this.state.brushrange} allowSelectionClear onTimeRangeChanged={this.handleTimeRangeChange} /> <YAxis id="axis1" label="Altitude (ft)" min={0} max={channels.altitude.max} width={70} type="linear" format="d" /> <Charts> <AreaChart axis="axis1" style={style.areaChartStyle()} columns={{ up: ["altitude"], down: [] }} series={channels.altitude.series} /> </Charts> </ChartRow> </ChartContainer> ); }; renderMode = () => { const linkStyle = { fontWeight: 600, color: "grey", cursor: "default" }; const linkStyleActive = { color: "steelblue", cursor: "pointer" }; return ( <div className="col-md-6" style={{ fontSize: 14, color: "#777" }}> <span style={this.state.mode !== "multiaxis" ? linkStyleActive : linkStyle} onClick={() => this.setState({ mode: "multiaxis" })} > Multi-axis </span> <span> | </span> <span style={this.state.mode !== "channels" ? linkStyleActive : linkStyle} onClick={() => this.setState({ mode: "channels" })} > Channels </span> <span> | </span> <span style={this.state.mode !== "rollup" ? linkStyleActive : linkStyle} onClick={() => this.setState({ mode: "rollup" })} > Rollups </span> </div> ); }; renderModeOptions = () => { const linkStyle = { fontWeight: 600, color: "grey", cursor: "default" }; const linkStyleActive = { color: "steelblue", cursor: "pointer" }; if (this.state.mode === "multiaxis") { return <div />; } else if (this.state.mode === "channels") { return <div />; } else if (this.state.mode === "rollup") { return ( <div className="col-md-6" style={{ fontSize: 14, color: "#777" }}> <span style={this.state.rollup !== "1m" ? linkStyleActive : linkStyle} onClick={() => this.setState({ rollup: "1m" })} > 1m </span> <span> | </span> <span style={this.state.rollup !== "5m" ? linkStyleActive : linkStyle} onClick={() => this.setState({ rollup: "5m" })} > 5m </span> <span> | </span> <span style={this.state.rollup !== "15m" ? linkStyleActive : linkStyle} onClick={() => this.setState({ rollup: "15m" })} > 15m </span> </div> ); } return <div />; }; render() { const { ready, channels, displayChannels } = this.state; if (!ready) { return <div>{`Building rollups...`}</div>; } const chartStyle = { borderStyle: "solid", borderWidth: 1, borderColor: "#DDD", paddingTop: 10, marginBottom: 10 }; const brushStyle = { boxShadow: "inset 0px 2px 5px -2px rgba(189, 189, 189, 0.75)", background: "#FEFEFE", paddingTop: 10 }; // Generate the legend const legend = displayChannels.map(channelName => ({ key: channelName, label: channels[channelName].label, disabled: !channels[channelName].show })); return ( <div> <div className="row"> {this.renderMode()} {this.renderModeOptions()} </div> <div className="row"> <div className="col-md-12"> <hr /> </div> </div> <div className="row"> <div className="col-md-6"> <Legend type={this.state.mode === "rollup" ? "swatch" : "line"} style={style} categories={legend} onSelectionChange={this.handleActiveChange} /> </div> <div className="col-md-6"> {this.state.tracker ? `${moment.duration(+this.state.tracker).format()}` : "-:--:--"} </div> </div> <div className="row"> <div className="col-md-12"> <hr /> </div> </div> <div className="row"> <div className="col-md-12" style={chartStyle}> <Resizable> {ready ? this.renderChart() : <div>Loading.....</div>} </Resizable> </div> </div> <div className="row"> <div className="col-md-12" style={brushStyle}> <Resizable>{ready ? this.renderBrush() : <div />}</Resizable> </div> </div> </div> ); } } // Export example export default { cycling, cycling_docs, cycling_thumbnail };
{ "pile_set_name": "Github" }
<div class="location">Someplace else</div>
{ "pile_set_name": "Github" }
# Array Flatten [![NPM version][npm-image]][npm-url] [![NPM downloads][downloads-image]][downloads-url] [![Build status][travis-image]][travis-url] [![Test coverage][coveralls-image]][coveralls-url] > Flatten an array of nested arrays into a single flat array. Accepts an optional depth. ## Installation ``` npm install array-flatten --save ``` ## Usage ```javascript var flatten = require('array-flatten') flatten([1, [2, [3, [4, [5], 6], 7], 8], 9]) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9] flatten([1, [2, [3, [4, [5], 6], 7], 8], 9], 2) //=> [1, 2, 3, [4, [5], 6], 7, 8, 9] (function () { flatten(arguments) //=> [1, 2, 3] })(1, [2, 3]) ``` ## License MIT [npm-image]: https://img.shields.io/npm/v/array-flatten.svg?style=flat [npm-url]: https://npmjs.org/package/array-flatten [downloads-image]: https://img.shields.io/npm/dm/array-flatten.svg?style=flat [downloads-url]: https://npmjs.org/package/array-flatten [travis-image]: https://img.shields.io/travis/blakeembrey/array-flatten.svg?style=flat [travis-url]: https://travis-ci.org/blakeembrey/array-flatten [coveralls-image]: https://img.shields.io/coveralls/blakeembrey/array-flatten.svg?style=flat [coveralls-url]: https://coveralls.io/r/blakeembrey/array-flatten?branch=master
{ "pile_set_name": "Github" }
define( //begin v1.x content { "scientificFormat": "#E0", "infinity": "∞", "superscriptingExponent": "×", "list": ";", "percentSign": "%", "minusSign": "-", "decimalFormat-short": "000 ล'.'ล'.'", "nan": "NaN", "plusSign": "+", "currencyFormat": "¤#,##0.00;(¤#,##0.00)", "perMille": "‰", "group": ",", "percentFormat": "#,##0%", "decimalFormat-long": "000 ล้านล้าน", "decimalFormat": "#,##0.###", "currencyFormat-short": "¤000 ล'.'ล'.'", "timeSeparator": ":", "decimal": ".", "exponential": "E" } //end v1.x content );
{ "pile_set_name": "Github" }
/* 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::attr::Attr; use dom::bindings::codegen::Bindings::SVGSVGElementBinding; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, LayoutDom}; use dom::bindings::str::DOMString; use dom::document::Document; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers}; use dom::node::Node; use dom::svggraphicselement::SVGGraphicsElement; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use script_layout_interface::SVGSVGData; use style::attr::AttrValue; const DEFAULT_WIDTH: u32 = 300; const DEFAULT_HEIGHT: u32 = 150; #[dom_struct] pub struct SVGSVGElement { svggraphicselement: SVGGraphicsElement } impl SVGSVGElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> SVGSVGElement { SVGSVGElement { svggraphicselement: SVGGraphicsElement::new_inherited(local_name, prefix, document) } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document) -> DomRoot<SVGSVGElement> { Node::reflect_node(box SVGSVGElement::new_inherited(local_name, prefix, document), document, SVGSVGElementBinding::Wrap) } } pub trait LayoutSVGSVGElementHelpers { fn data(&self) -> SVGSVGData; } impl LayoutSVGSVGElementHelpers for LayoutDom<SVGSVGElement> { #[allow(unsafe_code)] fn data(&self) -> SVGSVGData { unsafe { let SVG = &*self.unsafe_get(); let width_attr = SVG.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("width")); let height_attr = SVG.upcast::<Element>().get_attr_for_layout(&ns!(), &local_name!("height")); SVGSVGData { width: width_attr.map_or(DEFAULT_WIDTH, |val| val.as_uint()), height: height_attr.map_or(DEFAULT_HEIGHT, |val| val.as_uint()), } } } } impl VirtualMethods for SVGSVGElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<SVGGraphicsElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); } fn parse_plain_attribute(&self, name: &LocalName, value: DOMString) -> AttrValue { match name { &local_name!("width") => AttrValue::from_u32(value.into(), DEFAULT_WIDTH), &local_name!("height") => AttrValue::from_u32(value.into(), DEFAULT_HEIGHT), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } }
{ "pile_set_name": "Github" }
// Code generated by stringdata. DO NOT EDIT. package schema // PhabricatorSchemaJSON is the content of the file "phabricator.schema.json". const PhabricatorSchemaJSON = `{ "$schema": "http://json-schema.org/draft-07/schema#", "$id": "phabricator.schema.json#", "title": "PhabricatorConnection", "description": "Configuration for a connection to Phabricator.", "allowComments": true, "type": "object", "additionalProperties": false, "anyOf": [{ "required": ["token"] }, { "required": ["repos"] }], "properties": { "url": { "description": "URL of a Phabricator instance, such as https://phabricator.example.com", "type": "string", "examples": ["https://phabricator.example.com"] }, "token": { "description": "API token for the Phabricator instance.", "type": "string", "minLength": 1 }, "repos": { "description": "The list of repositories available on Phabricator.", "type": "array", "minItems": 1, "items": { "type": "object", "additionalProperties": false, "required": ["path", "callsign"], "properties": { "path": { "description": "Display path for the url e.g. gitolite/my/repo", "type": "string" }, "callsign": { "description": "The unique Phabricator identifier for the repository, like 'MUX'.", "type": "string" } } } } } } `
{ "pile_set_name": "Github" }
$NetBSD: distinfo,v 1.9 2016/10/04 22:01:41 wiz Exp $ SHA1 (libXrender-0.9.10.tar.bz2) = d55106de9260c2377c19d271d9b677744a6c7e81 RMD160 (libXrender-0.9.10.tar.bz2) = 1b6641020018942209d48a85b103b8df9c6c4f9e SHA512 (libXrender-0.9.10.tar.bz2) = 16ea0cf638b32d7df54b270457ef8c9d9a80da27fa845b105b560cb31027b4c7fe799cf23d6b6bac492be5961264e96d7845d316a9af4de9ff38bf40885ea6fe Size (libXrender-0.9.10.tar.bz2) = 308318 bytes
{ "pile_set_name": "Github" }
const Sentry = require('@sentry/electron'); const { SENTRY_DSN } = require('./helpers/constants'); try { Sentry.init({ dsn: SENTRY_DSN }); } catch (err) { // eslint-disable-next-line no-console console.log('Error initializing Sentry: ', err); }
{ "pile_set_name": "Github" }
one_CD fun_NN activity_NN for_IN parents_NNS during_IN the_DT holidays_NNS is_BEZ to_TO suggest_VB an_DT old_JJ film_NN and_CC see_VB if_CS they_PP can_MD interest_NN their_PP$ kids_NNS ._. although_CS black-and-white_JJ films_NNS are_BER frequently_RB viewed_VBN as_IN suspect_NN ,_, ones_NNS in_IN color_NN are_BER greeted_VBN with_IN more_DT of_IN an_DT open_JJ mind_NN ._. and_CC if_CS you_PP can_MD find_VB a_DT colorful_JJ action_NN film_NN ,_, even_RB if_CS it_PP is_BEZ from_IN six_CD decades_NNS ago_RB ,_, then_RB there_EX is_BEZ a_DT real_JJ possibility_NN of_IN a_DT take_VB home_NN hit_VBD ._. so_RB it_PP was_BEDZ in_IN our_PP$ family_NN when_CS we_PP wandered_VBD over_IN to_IN the_DT classic_JJ section_NN of_IN our_PP$ local_JJ video_NN store_NN the_DT other_JJ day_NN and_CC picked_VBD up_RP a_DT copy_NN of_IN the_DT adventures_NNS of_IN robin_NP hood_NP ,_, a_DT high_JJ spirited_JJ version_NN of_IN the_DT walter_NP scott_NP story_NN ._. nominated_VBN for_IN the_DT 1938_CD academy_NN award_NN for_IN best_JJS picture_NN and_CC winner_NN of_IN three_CD oscars_NNS for_IN erich_NP wolfgang_NP korngold_NN 's_POS melodramatic_JJ music_NN ,_, ralph_NP dawson_NP 's_POS fast_JJ paced_VBD editing_NN and_CC carl_NP jules_NNS weyl_??? 's_MD lush_JJ sets_NNS ,_, the_DT film_NN is_BEZ probably_RB best_RBS remembered_VBD for_CS errol_NN flynn_NP 's_POS charismatic_JJ acting_NN as_IN sir_NN robin_NP of_IN locksley_NP ,_, a_DT ._. k_NN ._. a_DT ._. robin_NP hood_NP ._. flynn_NP ,_, with_IN his_PP$ handsome_JJ figure_NN and_CC toothy_JJ smile_NN ,_, charms_NNS the_DT audience_NN while_CS clearly_RB having_HVG a_DT high_JJ old_JJ time_NN himself_PPX ._. let_VBN me_NN cut_NN to_IN the_DT chase_NN and_CC say_VB that_DT the_DT tape_NN was_BEDZ indeed_RB popular_JJ in_IN the_DT rhodes_NP household_NN ._. the_DT littlest_NN rhodes_NP ,_, jeffrey_NP ,_, age_NN 8_CD ,_, liked_VBD it_PP so_RB much_RB that_CS he_PP viewed_VBD it_PP at_IN least_DT three_CD times_NNS and_CC maybe_RB more_DT ._. i'll_??? let_VBN him_PP discuss_VB his_PP$ fascination_NN with_IN the_DT picture_NN in_IN his_PP$ usual_JJ section_NN at_IN the_DT end_NN of_IN the_DT review_NN ._. simply_RB stated_VBN ,_, the_DT film_NN derives_VBZ its_PP$ success_NN from_IN being_BEG one_CD of_IN the_DT best_JJS of_IN its_PP$ genre_NN ,_, the_DT swashbuckler_NN ._. robin_NP ,_, with_IN a_DT smile_NN from_IN ear-to-ear_JJ ,_, fights_NNS off_IN a_DT hundred_NN men_NNS without_IN a_DT scratch_NN ._. although_CS the_DT picture_NN can_MD be_BE considered_VBN as_IN little_DT more_DT than_CS a_DT 1930_CD 's_BEZ james_NP bond_NN ,_, the_DT production_NN values_NNS and_CC the_DT acting_JJ raise_VB it_PP above_IN that_DT level_NN ._. robin_NP hood_NP is_BEZ a_DT classic_JJ story_NN of_IN rich_JJ and_CC poor_JJ ._. robin_NP steals_VBZ from_IN the_DT rich_JJ and_CC gives_VBZ to_TO the_DT poor_JJ as_IN every_DT schoolchild_NN knows_VBZ ._. in_IN this_DT movie_NN ,_, however_RB ,_, he_PP seems_VBZ much_DT less_DT interested_JJ in_IN income_NN redistribution_NN than_CS in_IN fighting_NN for_IN his_PP$ king_NN and_CC country_NN ._. robin_NP ,_, with_IN his_PP$ courage_NN and_CC athletic_JJ skills_NNS ,_, serves_VBZ as_CS a_DT role_NN model_NN for_IN kids_NNS ._. and_CC with_IN the_DT lovely_JJ olivia_NP de_NP havilland_NP playing_VBG the_DT dreamy-eyed_JJ lady_NN marian_NP fitzswalter_NN ,_, the_DT story_NN has_HVZ heavy_JJ romantic_JJ overtones_NNS ._. filmed_JJ in_IN the_DT typical_JJ ,_, richly_RB oversaturated_VBN colors_NNS produced_VBN by_IN early_JJ technicolor_NN ,_, the_DT flesh_NN tones_NNS are_BER overly_RB pink_JJ and_CC there_RB few_DT color_NN subtleties_NNS ,_, which_WDT match_VB perfectly_RB the_DT wonderfully_RB exaggerated_JJ acting_VBG of_IN the_DT players_NNS ._. in_IN scene_NN after_IN scene_NN the_DT picture_NN charms_NNS the_DT audience_NN ._. who_WP wouldn't_MD fall_VB for_IN robin_NP as_IN he_PP shows_VBZ up_RP incognito_NP to_IN win_NN the_DT archery_NN contest_NN ,_, even_RB if_CS the_DT outcome_NN is_BEZ so_RB clearly_RB preordained_VBN ._. and_CC ,_, of_IN course_NN ,_, he_PP doesn't_DOZ just_RB win_VB ,_, he_PP does_DOZ so_RB by_IN splitting_VBG the_DT other_JJ man_NN 's_POS arrow_NN ._. watching_VBG the_DT picture_NN today_RB does_DOZ provide_VB some_DT jarring_NN moments_NNS ._. sherlock_NP holmes_NP as_IN the_DT villain_NN ,_, sir_NN guy_NP of_IN gisbourne_NP ,_, for_IN example_NN ,_, just_RB doesn't_DOZ seem_VB right_JJ ,_, even_RB if_CS basil_NP rathbone_NN did_DOD have_HV a_DT real-life_JJ identity_NN outside_IN of_IN his_PP$ most_DT famous_JJ role_NN ._. and_CC then_RB there_EX are_BER those_DT wigs_NNS from_IN the_DT makeup_NN department_NN --_??? so_RB bad_JJ ,_, they_PP look_VB like_IN rejects_VBZ from_IN a_DT mel_NP brooks_NP comedy_NN ._. as_CS was_BEDZ popular_JJ in_IN the_DT cinema_NN of_IN that_DT era_NN ,_, people_NN die_VB with_IN the_DT most_DT gentle_JJ prick_NN of_IN the_DT sword_NN and_CC without_IN any_DT nasty_JJ ,_, bloody_JJ holes_NNS to_IN spoil_NN the_DT wardrobe_NN or_CC the_DT looks_VBZ ._. bad_JJ guys_NNS are_BER banished_VBN rather_RB than_CS killed_VBN ,_, and_CC lovers_NNS go_VB off_RP hand-in-hand_NN ,_, doing_DOG nothing_PN more_RBR explicitly_RB sexual_JJ than_CS kissing_VBG ._. the_DT result_NN is_BEZ a_DT wonderful_JJ fairy_NN tale_NN of_IN a_DT movie_NN with_IN delightful_JJ ,_, cartoonish_JJ figures_NNS ._. hollywood_NP rarely_RB makes_VBZ such_DT high_JJ quality_NN family_NN films_NNS like_IN this_DT anymore_RB ,_, so_RB try_VB to_IN savor_NP the_DT old_JJ ones_NNS when_CS you_PP can_MD ._. the_DT adventures_NNS of_IN robin_NP hood_NP runs_VBZ 42_CD :_: 42_CD ._. it_PP is_BEZ not_XNOT rated_VBN ,_, but_CC containing_VBG absolutely_RB nothing_PN offensive_JJ ,_, it_PP would_MD get_VB a_DT g_NN rating_NN and_CC is_BEZ fine_JJ for_IN all_PDT ages_NNS ._. jeffrey_NP thinks_VBZ the_DT film_NN is_BEZ "_" great_JJ "_" and_CC gives_VBZ it_PP *_??? *_??? *_??? *_??? ._. he_PP recommends_VBZ the_DT movie_NN particularly_RB for_IN people_NN who_WP do_DO not_XNOT likely_JJ bloody_JJ pictures_NNS --_??? he_PP hates_VBZ the_DT sight_NN of_IN blood_NN in_IN movies_NNS ._. his_PP$ favorite_JJ parts_NNS are_BER the_DT battles_NNS and_CC the_DT ending_NN ,_, and_CC his_PP$ favorite_JJ characters_NNS are_BER robin_NP and_CC king_NN richard_NP (_( ian_NP hunter_NN )_) ._.
{ "pile_set_name": "Github" }
/*********************************************************************** * Software License Agreement (BSD License) * * Copyright 2008-2009 Marius Muja ([email protected]). All rights reserved. * Copyright 2008-2009 David G. Lowe ([email protected]). All rights reserved. * Copyright 2011-2016 Jose Luis Blanco ([email protected]). * All rights reserved. * * THE BSD LICENSE * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *************************************************************************/ /** \mainpage nanoflann C++ API documentation * nanoflann is a C++ header-only library for building KD-Trees, mostly * optimized for 2D or 3D point clouds. * * nanoflann does not require compiling or installing, just an * #include <nanoflann.hpp> in your code. * * See: * - <a href="modules.html" >C++ API organized by modules</a> * - <a href="https://github.com/jlblancoc/nanoflann" >Online README</a> * - <a href="http://jlblancoc.github.io/nanoflann/" >Doxygen * documentation</a> */ #ifndef NANOFLANN_HPP_ #define NANOFLANN_HPP_ #include <algorithm> #include <array> #include <cassert> #include <cmath> // for abs() #include <cstdio> // for fwrite() #include <cstdlib> // for abs() #include <functional> #include <limits> // std::reference_wrapper #include <stdexcept> #include <vector> /** Library version: 0xMmP (M=Major,m=minor,P=patch) */ #define NANOFLANN_VERSION 0x130 // Avoid conflicting declaration of min/max macros in windows headers #if !defined(NOMINMAX) && \ (defined(_WIN32) || defined(_WIN32_) || defined(WIN32) || defined(_WIN64)) #define NOMINMAX #ifdef max #undef max #undef min #endif #endif namespace nanoflann { /** @addtogroup nanoflann_grp nanoflann C++ library for ANN * @{ */ /** the PI constant (required to avoid MSVC missing symbols) */ template <typename T> T pi_const() { return static_cast<T>(3.14159265358979323846); } /** * Traits if object is resizable and assignable (typically has a resize | assign * method) */ template <typename T, typename = int> struct has_resize : std::false_type {}; template <typename T> struct has_resize<T, decltype((void)std::declval<T>().resize(1), 0)> : std::true_type {}; template <typename T, typename = int> struct has_assign : std::false_type {}; template <typename T> struct has_assign<T, decltype((void)std::declval<T>().assign(1, 0), 0)> : std::true_type {}; /** * Free function to resize a resizable object */ template <typename Container> inline typename std::enable_if<has_resize<Container>::value, void>::type resize(Container &c, const size_t nElements) { c.resize(nElements); } /** * Free function that has no effects on non resizable containers (e.g. * std::array) It raises an exception if the expected size does not match */ template <typename Container> inline typename std::enable_if<!has_resize<Container>::value, void>::type resize(Container &c, const size_t nElements) { if (nElements != c.size()) throw std::logic_error("Try to change the size of a std::array."); } /** * Free function to assign to a container */ template <typename Container, typename T> inline typename std::enable_if<has_assign<Container>::value, void>::type assign(Container &c, const size_t nElements, const T &value) { c.assign(nElements, value); } /** * Free function to assign to a std::array */ template <typename Container, typename T> inline typename std::enable_if<!has_assign<Container>::value, void>::type assign(Container &c, const size_t nElements, const T &value) { for (size_t i = 0; i < nElements; i++) c[i] = value; } /** @addtogroup result_sets_grp Result set classes * @{ */ template <typename _DistanceType, typename _IndexType = size_t, typename _CountType = size_t> class KNNResultSet { public: typedef _DistanceType DistanceType; typedef _IndexType IndexType; typedef _CountType CountType; private: IndexType *indices; DistanceType *dists; CountType capacity; CountType count; public: inline KNNResultSet(CountType capacity_) : indices(0), dists(0), capacity(capacity_), count(0) {} inline void init(IndexType *indices_, DistanceType *dists_) { indices = indices_; dists = dists_; count = 0; if (capacity) dists[capacity - 1] = (std::numeric_limits<DistanceType>::max)(); } inline CountType size() const { return count; } inline bool full() const { return count == capacity; } /** * Called during search to add an element matching the criteria. * @return true if the search should be continued, false if the results are * sufficient */ inline bool addPoint(DistanceType dist, IndexType index) { CountType i; for (i = count; i > 0; --i) { #ifdef NANOFLANN_FIRST_MATCH // If defined and two points have the same // distance, the one with the lowest-index will be // returned first. if ((dists[i - 1] > dist) || ((dist == dists[i - 1]) && (indices[i - 1] > index))) { #else if (dists[i - 1] > dist) { #endif if (i < capacity) { dists[i] = dists[i - 1]; indices[i] = indices[i - 1]; } } else break; } if (i < capacity) { dists[i] = dist; indices[i] = index; } if (count < capacity) count++; // tell caller that the search shall continue return true; } inline DistanceType worstDist() const { return dists[capacity - 1]; } }; /** operator "<" for std::sort() */ struct IndexDist_Sorter { /** PairType will be typically: std::pair<IndexType,DistanceType> */ template <typename PairType> inline bool operator()(const PairType &p1, const PairType &p2) const { return p1.second < p2.second; } }; /** * A result-set class used when performing a radius based search. */ template <typename _DistanceType, typename _IndexType = size_t> class RadiusResultSet { public: typedef _DistanceType DistanceType; typedef _IndexType IndexType; public: const DistanceType radius; std::vector<std::pair<IndexType, DistanceType>> &m_indices_dists; inline RadiusResultSet( DistanceType radius_, std::vector<std::pair<IndexType, DistanceType>> &indices_dists) : radius(radius_), m_indices_dists(indices_dists) { init(); } inline void init() { clear(); } inline void clear() { m_indices_dists.clear(); } inline size_t size() const { return m_indices_dists.size(); } inline bool full() const { return true; } /** * Called during search to add an element matching the criteria. * @return true if the search should be continued, false if the results are * sufficient */ inline bool addPoint(DistanceType dist, IndexType index) { if (dist < radius) m_indices_dists.push_back(std::make_pair(index, dist)); return true; } inline DistanceType worstDist() const { return radius; } /** * Find the worst result (furtherest neighbor) without copying or sorting * Pre-conditions: size() > 0 */ std::pair<IndexType, DistanceType> worst_item() const { if (m_indices_dists.empty()) throw std::runtime_error("Cannot invoke RadiusResultSet::worst_item() on " "an empty list of results."); typedef typename std::vector<std::pair<IndexType, DistanceType>>::const_iterator DistIt; DistIt it = std::max_element(m_indices_dists.begin(), m_indices_dists.end(), IndexDist_Sorter()); return *it; } }; /** @} */ /** @addtogroup loadsave_grp Load/save auxiliary functions * @{ */ template <typename T> void save_value(FILE *stream, const T &value, size_t count = 1) { fwrite(&value, sizeof(value), count, stream); } template <typename T> void save_value(FILE *stream, const std::vector<T> &value) { size_t size = value.size(); fwrite(&size, sizeof(size_t), 1, stream); fwrite(&value[0], sizeof(T), size, stream); } template <typename T> void load_value(FILE *stream, T &value, size_t count = 1) { size_t read_cnt = fread(&value, sizeof(value), count, stream); if (read_cnt != count) { throw std::runtime_error("Cannot read from file"); } } template <typename T> void load_value(FILE *stream, std::vector<T> &value) { size_t size; size_t read_cnt = fread(&size, sizeof(size_t), 1, stream); if (read_cnt != 1) { throw std::runtime_error("Cannot read from file"); } value.resize(size); read_cnt = fread(&value[0], sizeof(T), size, stream); if (read_cnt != size) { throw std::runtime_error("Cannot read from file"); } } /** @} */ /** @addtogroup metric_grp Metric (distance) classes * @{ */ struct Metric {}; /** Manhattan distance functor (generic version, optimized for * high-dimensionality data sets). Corresponding distance traits: * nanoflann::metric_L1 \tparam T Type of the elements (e.g. double, float, * uint8_t) \tparam _DistanceType Type of distance variables (must be signed) * (e.g. float, double, int64_t) */ template <class T, class DataSource, typename _DistanceType = T> struct L1_Adaptor { typedef T ElementType; typedef _DistanceType DistanceType; const DataSource &data_source; L1_Adaptor(const DataSource &_data_source) : data_source(_data_source) {} inline DistanceType evalMetric(const T *a, const size_t b_idx, size_t size, DistanceType worst_dist = -1) const { DistanceType result = DistanceType(); const T *last = a + size; const T *lastgroup = last - 3; size_t d = 0; /* Process 4 items with each loop for efficiency. */ while (a < lastgroup) { const DistanceType diff0 = std::abs(a[0] - data_source.kdtree_get_pt(b_idx, d++)); const DistanceType diff1 = std::abs(a[1] - data_source.kdtree_get_pt(b_idx, d++)); const DistanceType diff2 = std::abs(a[2] - data_source.kdtree_get_pt(b_idx, d++)); const DistanceType diff3 = std::abs(a[3] - data_source.kdtree_get_pt(b_idx, d++)); result += diff0 + diff1 + diff2 + diff3; a += 4; if ((worst_dist > 0) && (result > worst_dist)) { return result; } } /* Process last 0-3 components. Not needed for standard vector lengths. */ while (a < last) { result += std::abs(*a++ - data_source.kdtree_get_pt(b_idx, d++)); } return result; } template <typename U, typename V> inline DistanceType accum_dist(const U a, const V b, const size_t) const { return std::abs(a - b); } }; /** Squared Euclidean distance functor (generic version, optimized for * high-dimensionality data sets). Corresponding distance traits: * nanoflann::metric_L2 \tparam T Type of the elements (e.g. double, float, * uint8_t) \tparam _DistanceType Type of distance variables (must be signed) * (e.g. float, double, int64_t) */ template <class T, class DataSource, typename _DistanceType = T> struct L2_Adaptor { typedef T ElementType; typedef _DistanceType DistanceType; const DataSource &data_source; L2_Adaptor(const DataSource &_data_source) : data_source(_data_source) {} inline DistanceType evalMetric(const T *a, const size_t b_idx, size_t size, DistanceType worst_dist = -1) const { DistanceType result = DistanceType(); const T *last = a + size; const T *lastgroup = last - 3; size_t d = 0; /* Process 4 items with each loop for efficiency. */ while (a < lastgroup) { const DistanceType diff0 = a[0] - data_source.kdtree_get_pt(b_idx, d++); const DistanceType diff1 = a[1] - data_source.kdtree_get_pt(b_idx, d++); const DistanceType diff2 = a[2] - data_source.kdtree_get_pt(b_idx, d++); const DistanceType diff3 = a[3] - data_source.kdtree_get_pt(b_idx, d++); result += diff0 * diff0 + diff1 * diff1 + diff2 * diff2 + diff3 * diff3; a += 4; if ((worst_dist > 0) && (result > worst_dist)) { return result; } } /* Process last 0-3 components. Not needed for standard vector lengths. */ while (a < last) { const DistanceType diff0 = *a++ - data_source.kdtree_get_pt(b_idx, d++); result += diff0 * diff0; } return result; } template <typename U, typename V> inline DistanceType accum_dist(const U a, const V b, const size_t) const { return (a - b) * (a - b); } }; /** Squared Euclidean (L2) distance functor (suitable for low-dimensionality * datasets, like 2D or 3D point clouds) Corresponding distance traits: * nanoflann::metric_L2_Simple \tparam T Type of the elements (e.g. double, * float, uint8_t) \tparam _DistanceType Type of distance variables (must be * signed) (e.g. float, double, int64_t) */ template <class T, class DataSource, typename _DistanceType = T> struct L2_Simple_Adaptor { typedef T ElementType; typedef _DistanceType DistanceType; const DataSource &data_source; L2_Simple_Adaptor(const DataSource &_data_source) : data_source(_data_source) {} inline DistanceType evalMetric(const T *a, const size_t b_idx, size_t size) const { DistanceType result = DistanceType(); for (size_t i = 0; i < size; ++i) { const DistanceType diff = a[i] - data_source.kdtree_get_pt(b_idx, i); result += diff * diff; } return result; } template <typename U, typename V> inline DistanceType accum_dist(const U a, const V b, const size_t) const { return (a - b) * (a - b); } }; /** SO2 distance functor * Corresponding distance traits: nanoflann::metric_SO2 * \tparam T Type of the elements (e.g. double, float) * \tparam _DistanceType Type of distance variables (must be signed) (e.g. * float, double) orientation is constrained to be in [-pi, pi] */ template <class T, class DataSource, typename _DistanceType = T> struct SO2_Adaptor { typedef T ElementType; typedef _DistanceType DistanceType; const DataSource &data_source; SO2_Adaptor(const DataSource &_data_source) : data_source(_data_source) {} inline DistanceType evalMetric(const T *a, const size_t b_idx, size_t size) const { return accum_dist(a[size - 1], data_source.kdtree_get_pt(b_idx, size - 1), size - 1); } /** Note: this assumes that input angles are already in the range [-pi,pi] */ template <typename U, typename V> inline DistanceType accum_dist(const U a, const V b, const size_t) const { DistanceType result = DistanceType(), PI = pi_const<DistanceType>(); result = b - a; if (result > PI) result -= 2 * PI; else if (result < -PI) result += 2 * PI; return result; } }; /** SO3 distance functor (Uses L2_Simple) * Corresponding distance traits: nanoflann::metric_SO3 * \tparam T Type of the elements (e.g. double, float) * \tparam _DistanceType Type of distance variables (must be signed) (e.g. * float, double) */ template <class T, class DataSource, typename _DistanceType = T> struct SO3_Adaptor { typedef T ElementType; typedef _DistanceType DistanceType; L2_Simple_Adaptor<T, DataSource> distance_L2_Simple; SO3_Adaptor(const DataSource &_data_source) : distance_L2_Simple(_data_source) {} inline DistanceType evalMetric(const T *a, const size_t b_idx, size_t size) const { return distance_L2_Simple.evalMetric(a, b_idx, size); } template <typename U, typename V> inline DistanceType accum_dist(const U a, const V b, const size_t idx) const { return distance_L2_Simple.accum_dist(a, b, idx); } }; /** Metaprogramming helper traits class for the L1 (Manhattan) metric */ struct metric_L1 : public Metric { template <class T, class DataSource> struct traits { typedef L1_Adaptor<T, DataSource> distance_t; }; }; /** Metaprogramming helper traits class for the L2 (Euclidean) metric */ struct metric_L2 : public Metric { template <class T, class DataSource> struct traits { typedef L2_Adaptor<T, DataSource> distance_t; }; }; /** Metaprogramming helper traits class for the L2_simple (Euclidean) metric */ struct metric_L2_Simple : public Metric { template <class T, class DataSource> struct traits { typedef L2_Simple_Adaptor<T, DataSource> distance_t; }; }; /** Metaprogramming helper traits class for the SO3_InnerProdQuat metric */ struct metric_SO2 : public Metric { template <class T, class DataSource> struct traits { typedef SO2_Adaptor<T, DataSource> distance_t; }; }; /** Metaprogramming helper traits class for the SO3_InnerProdQuat metric */ struct metric_SO3 : public Metric { template <class T, class DataSource> struct traits { typedef SO3_Adaptor<T, DataSource> distance_t; }; }; /** @} */ /** @addtogroup param_grp Parameter structs * @{ */ /** Parameters (see README.md) */ struct KDTreeSingleIndexAdaptorParams { KDTreeSingleIndexAdaptorParams(size_t _leaf_max_size = 10) : leaf_max_size(_leaf_max_size) {} size_t leaf_max_size; }; /** Search options for KDTreeSingleIndexAdaptor::findNeighbors() */ struct SearchParams { /** Note: The first argument (checks_IGNORED_) is ignored, but kept for * compatibility with the FLANN interface */ SearchParams(int checks_IGNORED_ = 32, float eps_ = 0, bool sorted_ = true) : checks(checks_IGNORED_), eps(eps_), sorted(sorted_) {} int checks; //!< Ignored parameter (Kept for compatibility with the FLANN //!< interface). float eps; //!< search for eps-approximate neighbours (default: 0) bool sorted; //!< only for radius search, require neighbours sorted by //!< distance (default: true) }; /** @} */ /** @addtogroup memalloc_grp Memory allocation * @{ */ /** * Allocates (using C's malloc) a generic type T. * * Params: * count = number of instances to allocate. * Returns: pointer (of type T*) to memory buffer */ template <typename T> inline T *allocate(size_t count = 1) { T *mem = static_cast<T *>(::malloc(sizeof(T) * count)); return mem; } /** * Pooled storage allocator * * The following routines allow for the efficient allocation of storage in * small chunks from a specified pool. Rather than allowing each structure * to be freed individually, an entire pool of storage is freed at once. * This method has two advantages over just using malloc() and free(). First, * it is far more efficient for allocating small objects, as there is * no overhead for remembering all the information needed to free each * object or consolidating fragmented memory. Second, the decision about * how long to keep an object is made at the time of allocation, and there * is no need to track down all the objects to free them. * */ const size_t WORDSIZE = 16; const size_t BLOCKSIZE = 8192; class PooledAllocator { /* We maintain memory alignment to word boundaries by requiring that all allocations be in multiples of the machine wordsize. */ /* Size of machine word in bytes. Must be power of 2. */ /* Minimum number of bytes requested at a time from the system. Must be * multiple of WORDSIZE. */ size_t remaining; /* Number of bytes left in current block of storage. */ void *base; /* Pointer to base of current block of storage. */ void *loc; /* Current location in block to next allocate memory. */ void internal_init() { remaining = 0; base = NULL; usedMemory = 0; wastedMemory = 0; } public: size_t usedMemory; size_t wastedMemory; /** Default constructor. Initializes a new pool. */ PooledAllocator() { internal_init(); } /** * Destructor. Frees all the memory allocated in this pool. */ ~PooledAllocator() { free_all(); } /** Frees all allocated memory chunks */ void free_all() { while (base != NULL) { void *prev = *(static_cast<void **>(base)); /* Get pointer to prev block. */ ::free(base); base = prev; } internal_init(); } /** * Returns a pointer to a piece of new memory of the given size in bytes * allocated from the pool. */ void *malloc(const size_t req_size) { /* Round size up to a multiple of wordsize. The following expression only works for WORDSIZE that is a power of 2, by masking last bits of incremented size to zero. */ const size_t size = (req_size + (WORDSIZE - 1)) & ~(WORDSIZE - 1); /* Check whether a new block must be allocated. Note that the first word of a block is reserved for a pointer to the previous block. */ if (size > remaining) { wastedMemory += remaining; /* Allocate new storage. */ const size_t blocksize = (size + sizeof(void *) + (WORDSIZE - 1) > BLOCKSIZE) ? size + sizeof(void *) + (WORDSIZE - 1) : BLOCKSIZE; // use the standard C malloc to allocate memory void *m = ::malloc(blocksize); if (!m) { fprintf(stderr, "Failed to allocate memory.\n"); return NULL; } /* Fill first word of new block with pointer to previous block. */ static_cast<void **>(m)[0] = base; base = m; size_t shift = 0; // int size_t = (WORDSIZE - ( (((size_t)m) + sizeof(void*)) & // (WORDSIZE-1))) & (WORDSIZE-1); remaining = blocksize - sizeof(void *) - shift; loc = (static_cast<char *>(m) + sizeof(void *) + shift); } void *rloc = loc; loc = static_cast<char *>(loc) + size; remaining -= size; usedMemory += size; return rloc; } /** * Allocates (using this pool) a generic type T. * * Params: * count = number of instances to allocate. * Returns: pointer (of type T*) to memory buffer */ template <typename T> T *allocate(const size_t count = 1) { T *mem = static_cast<T *>(this->malloc(sizeof(T) * count)); return mem; } }; /** @} */ /** @addtogroup nanoflann_metaprog_grp Auxiliary metaprogramming stuff * @{ */ /** Used to declare fixed-size arrays when DIM>0, dynamically-allocated vectors * when DIM=-1. Fixed size version for a generic DIM: */ template <int DIM, typename T> struct array_or_vector_selector { typedef std::array<T, DIM> container_t; }; /** Dynamic size version */ template <typename T> struct array_or_vector_selector<-1, T> { typedef std::vector<T> container_t; }; /** @} */ /** kd-tree base-class * * Contains the member functions common to the classes KDTreeSingleIndexAdaptor * and KDTreeSingleIndexDynamicAdaptor_. * * \tparam Derived The name of the class which inherits this class. * \tparam DatasetAdaptor The user-provided adaptor (see comments above). * \tparam Distance The distance metric to use, these are all classes derived * from nanoflann::Metric \tparam DIM Dimensionality of data points (e.g. 3 for * 3D points) \tparam IndexType Will be typically size_t or int */ template <class Derived, typename Distance, class DatasetAdaptor, int DIM = -1, typename IndexType = size_t> class KDTreeBaseClass { public: /** Frees the previously-built index. Automatically called within * buildIndex(). */ void freeIndex(Derived &obj) { obj.pool.free_all(); obj.root_node = NULL; obj.m_size_at_index_build = 0; } typedef typename Distance::ElementType ElementType; typedef typename Distance::DistanceType DistanceType; /*--------------------- Internal Data Structures --------------------------*/ struct Node { /** Union used because a node can be either a LEAF node or a non-leaf node, * so both data fields are never used simultaneously */ union { struct leaf { IndexType left, right; //!< Indices of points in leaf node } lr; struct nonleaf { int divfeat; //!< Dimension used for subdivision. DistanceType divlow, divhigh; //!< The values used for subdivision. } sub; } node_type; Node *child1, *child2; //!< Child nodes (both=NULL mean its a leaf node) }; typedef Node *NodePtr; struct Interval { ElementType low, high; }; /** * Array of indices to vectors in the dataset. */ std::vector<IndexType> vind; NodePtr root_node; size_t m_leaf_max_size; size_t m_size; //!< Number of current points in the dataset size_t m_size_at_index_build; //!< Number of points in the dataset when the //!< index was built int dim; //!< Dimensionality of each data point /** Define "BoundingBox" as a fixed-size or variable-size container depending * on "DIM" */ typedef typename array_or_vector_selector<DIM, Interval>::container_t BoundingBox; /** Define "distance_vector_t" as a fixed-size or variable-size container * depending on "DIM" */ typedef typename array_or_vector_selector<DIM, DistanceType>::container_t distance_vector_t; /** The KD-tree used to find neighbours */ BoundingBox root_bbox; /** * Pooled memory allocator. * * Using a pooled memory allocator is more efficient * than allocating memory directly when there is a large * number small of memory allocations. */ PooledAllocator pool; /** Returns number of points in dataset */ size_t size(const Derived &obj) const { return obj.m_size; } /** Returns the length of each point in the dataset */ size_t veclen(const Derived &obj) { return static_cast<size_t>(DIM > 0 ? DIM : obj.dim); } /// Helper accessor to the dataset points: inline ElementType dataset_get(const Derived &obj, size_t idx, int component) const { return obj.dataset.kdtree_get_pt(idx, component); } /** * Computes the inde memory usage * Returns: memory used by the index */ size_t usedMemory(Derived &obj) { return obj.pool.usedMemory + obj.pool.wastedMemory + obj.dataset.kdtree_get_point_count() * sizeof(IndexType); // pool memory and vind array memory } void computeMinMax(const Derived &obj, IndexType *ind, IndexType count, int element, ElementType &min_elem, ElementType &max_elem) { min_elem = dataset_get(obj, ind[0], element); max_elem = dataset_get(obj, ind[0], element); for (IndexType i = 1; i < count; ++i) { ElementType val = dataset_get(obj, ind[i], element); if (val < min_elem) min_elem = val; if (val > max_elem) max_elem = val; } } /** * Create a tree node that subdivides the list of vecs from vind[first] * to vind[last]. The routine is called recursively on each sublist. * * @param left index of the first vector * @param right index of the last vector */ NodePtr divideTree(Derived &obj, const IndexType left, const IndexType right, BoundingBox &bbox) { NodePtr node = obj.pool.template allocate<Node>(); // allocate memory /* If too few exemplars remain, then make this a leaf node. */ if ((right - left) <= static_cast<IndexType>(obj.m_leaf_max_size)) { node->child1 = node->child2 = NULL; /* Mark as leaf node. */ node->node_type.lr.left = left; node->node_type.lr.right = right; // compute bounding-box of leaf points for (int i = 0; i < (DIM > 0 ? DIM : obj.dim); ++i) { bbox[i].low = dataset_get(obj, obj.vind[left], i); bbox[i].high = dataset_get(obj, obj.vind[left], i); } for (IndexType k = left + 1; k < right; ++k) { for (int i = 0; i < (DIM > 0 ? DIM : obj.dim); ++i) { if (bbox[i].low > dataset_get(obj, obj.vind[k], i)) bbox[i].low = dataset_get(obj, obj.vind[k], i); if (bbox[i].high < dataset_get(obj, obj.vind[k], i)) bbox[i].high = dataset_get(obj, obj.vind[k], i); } } } else { IndexType idx; int cutfeat; DistanceType cutval; middleSplit_(obj, &obj.vind[0] + left, right - left, idx, cutfeat, cutval, bbox); node->node_type.sub.divfeat = cutfeat; BoundingBox left_bbox(bbox); left_bbox[cutfeat].high = cutval; node->child1 = divideTree(obj, left, left + idx, left_bbox); BoundingBox right_bbox(bbox); right_bbox[cutfeat].low = cutval; node->child2 = divideTree(obj, left + idx, right, right_bbox); node->node_type.sub.divlow = left_bbox[cutfeat].high; node->node_type.sub.divhigh = right_bbox[cutfeat].low; for (int i = 0; i < (DIM > 0 ? DIM : obj.dim); ++i) { bbox[i].low = std::min(left_bbox[i].low, right_bbox[i].low); bbox[i].high = std::max(left_bbox[i].high, right_bbox[i].high); } } return node; } void middleSplit_(Derived &obj, IndexType *ind, IndexType count, IndexType &index, int &cutfeat, DistanceType &cutval, const BoundingBox &bbox) { const DistanceType EPS = static_cast<DistanceType>(0.00001); ElementType max_span = bbox[0].high - bbox[0].low; for (int i = 1; i < (DIM > 0 ? DIM : obj.dim); ++i) { ElementType span = bbox[i].high - bbox[i].low; if (span > max_span) { max_span = span; } } ElementType max_spread = -1; cutfeat = 0; for (int i = 0; i < (DIM > 0 ? DIM : obj.dim); ++i) { ElementType span = bbox[i].high - bbox[i].low; if (span > (1 - EPS) * max_span) { ElementType min_elem, max_elem; computeMinMax(obj, ind, count, i, min_elem, max_elem); ElementType spread = max_elem - min_elem; ; if (spread > max_spread) { cutfeat = i; max_spread = spread; } } } // split in the middle DistanceType split_val = (bbox[cutfeat].low + bbox[cutfeat].high) / 2; ElementType min_elem, max_elem; computeMinMax(obj, ind, count, cutfeat, min_elem, max_elem); if (split_val < min_elem) cutval = min_elem; else if (split_val > max_elem) cutval = max_elem; else cutval = split_val; IndexType lim1, lim2; planeSplit(obj, ind, count, cutfeat, cutval, lim1, lim2); if (lim1 > count / 2) index = lim1; else if (lim2 < count / 2) index = lim2; else index = count / 2; } /** * Subdivide the list of points by a plane perpendicular on axe corresponding * to the 'cutfeat' dimension at 'cutval' position. * * On return: * dataset[ind[0..lim1-1]][cutfeat]<cutval * dataset[ind[lim1..lim2-1]][cutfeat]==cutval * dataset[ind[lim2..count]][cutfeat]>cutval */ void planeSplit(Derived &obj, IndexType *ind, const IndexType count, int cutfeat, DistanceType &cutval, IndexType &lim1, IndexType &lim2) { /* Move vector indices for left subtree to front of list. */ IndexType left = 0; IndexType right = count - 1; for (;;) { while (left <= right && dataset_get(obj, ind[left], cutfeat) < cutval) ++left; while (right && left <= right && dataset_get(obj, ind[right], cutfeat) >= cutval) --right; if (left > right || !right) break; // "!right" was added to support unsigned Index types std::swap(ind[left], ind[right]); ++left; --right; } /* If either list is empty, it means that all remaining features * are identical. Split in the middle to maintain a balanced tree. */ lim1 = left; right = count - 1; for (;;) { while (left <= right && dataset_get(obj, ind[left], cutfeat) <= cutval) ++left; while (right && left <= right && dataset_get(obj, ind[right], cutfeat) > cutval) --right; if (left > right || !right) break; // "!right" was added to support unsigned Index types std::swap(ind[left], ind[right]); ++left; --right; } lim2 = left; } DistanceType computeInitialDistances(const Derived &obj, const ElementType *vec, distance_vector_t &dists) const { assert(vec); DistanceType distsq = DistanceType(); for (int i = 0; i < (DIM > 0 ? DIM : obj.dim); ++i) { if (vec[i] < obj.root_bbox[i].low) { dists[i] = obj.distance.accum_dist(vec[i], obj.root_bbox[i].low, i); distsq += dists[i]; } if (vec[i] > obj.root_bbox[i].high) { dists[i] = obj.distance.accum_dist(vec[i], obj.root_bbox[i].high, i); distsq += dists[i]; } } return distsq; } void save_tree(Derived &obj, FILE *stream, NodePtr tree) { save_value(stream, *tree); if (tree->child1 != NULL) { save_tree(obj, stream, tree->child1); } if (tree->child2 != NULL) { save_tree(obj, stream, tree->child2); } } void load_tree(Derived &obj, FILE *stream, NodePtr &tree) { tree = obj.pool.template allocate<Node>(); load_value(stream, *tree); if (tree->child1 != NULL) { load_tree(obj, stream, tree->child1); } if (tree->child2 != NULL) { load_tree(obj, stream, tree->child2); } } /** Stores the index in a binary file. * IMPORTANT NOTE: The set of data points is NOT stored in the file, so when * loading the index object it must be constructed associated to the same * source of data points used while building it. See the example: * examples/saveload_example.cpp \sa loadIndex */ void saveIndex_(Derived &obj, FILE *stream) { save_value(stream, obj.m_size); save_value(stream, obj.dim); save_value(stream, obj.root_bbox); save_value(stream, obj.m_leaf_max_size); save_value(stream, obj.vind); save_tree(obj, stream, obj.root_node); } /** Loads a previous index from a binary file. * IMPORTANT NOTE: The set of data points is NOT stored in the file, so the * index object must be constructed associated to the same source of data * points used while building the index. See the example: * examples/saveload_example.cpp \sa loadIndex */ void loadIndex_(Derived &obj, FILE *stream) { load_value(stream, obj.m_size); load_value(stream, obj.dim); load_value(stream, obj.root_bbox); load_value(stream, obj.m_leaf_max_size); load_value(stream, obj.vind); load_tree(obj, stream, obj.root_node); } }; /** @addtogroup kdtrees_grp KD-tree classes and adaptors * @{ */ /** kd-tree static index * * Contains the k-d trees and other information for indexing a set of points * for nearest-neighbor matching. * * The class "DatasetAdaptor" must provide the following interface (can be * non-virtual, inlined methods): * * \code * // Must return the number of data poins * inline size_t kdtree_get_point_count() const { ... } * * * // Must return the dim'th component of the idx'th point in the class: * inline T kdtree_get_pt(const size_t idx, const size_t dim) const { ... } * * // Optional bounding-box computation: return false to default to a standard * bbox computation loop. * // Return true if the BBOX was already computed by the class and returned * in "bb" so it can be avoided to redo it again. * // Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 * for point clouds) template <class BBOX> bool kdtree_get_bbox(BBOX &bb) const * { * bb[0].low = ...; bb[0].high = ...; // 0th dimension limits * bb[1].low = ...; bb[1].high = ...; // 1st dimension limits * ... * return true; * } * * \endcode * * \tparam DatasetAdaptor The user-provided adaptor (see comments above). * \tparam Distance The distance metric to use: nanoflann::metric_L1, * nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. \tparam DIM * Dimensionality of data points (e.g. 3 for 3D points) \tparam IndexType Will * be typically size_t or int */ template <typename Distance, class DatasetAdaptor, int DIM = -1, typename IndexType = size_t> class KDTreeSingleIndexAdaptor : public KDTreeBaseClass< KDTreeSingleIndexAdaptor<Distance, DatasetAdaptor, DIM, IndexType>, Distance, DatasetAdaptor, DIM, IndexType> { public: /** Deleted copy constructor*/ KDTreeSingleIndexAdaptor( const KDTreeSingleIndexAdaptor<Distance, DatasetAdaptor, DIM, IndexType> &) = delete; /** * The dataset used by this index */ const DatasetAdaptor &dataset; //!< The source of our data const KDTreeSingleIndexAdaptorParams index_params; Distance distance; typedef typename nanoflann::KDTreeBaseClass< nanoflann::KDTreeSingleIndexAdaptor<Distance, DatasetAdaptor, DIM, IndexType>, Distance, DatasetAdaptor, DIM, IndexType> BaseClassRef; typedef typename BaseClassRef::ElementType ElementType; typedef typename BaseClassRef::DistanceType DistanceType; typedef typename BaseClassRef::Node Node; typedef Node *NodePtr; typedef typename BaseClassRef::Interval Interval; /** Define "BoundingBox" as a fixed-size or variable-size container depending * on "DIM" */ typedef typename BaseClassRef::BoundingBox BoundingBox; /** Define "distance_vector_t" as a fixed-size or variable-size container * depending on "DIM" */ typedef typename BaseClassRef::distance_vector_t distance_vector_t; /** * KDTree constructor * * Refer to docs in README.md or online in * https://github.com/jlblancoc/nanoflann * * The KD-Tree point dimension (the length of each point in the datase, e.g. 3 * for 3D points) is determined by means of: * - The \a DIM template parameter if >0 (highest priority) * - Otherwise, the \a dimensionality parameter of this constructor. * * @param inputData Dataset with the input features * @param params Basically, the maximum leaf node size */ KDTreeSingleIndexAdaptor(const int dimensionality, const DatasetAdaptor &inputData, const KDTreeSingleIndexAdaptorParams &params = KDTreeSingleIndexAdaptorParams()) : dataset(inputData), index_params(params), distance(inputData) { BaseClassRef::root_node = NULL; BaseClassRef::m_size = dataset.kdtree_get_point_count(); BaseClassRef::m_size_at_index_build = BaseClassRef::m_size; BaseClassRef::dim = dimensionality; if (DIM > 0) BaseClassRef::dim = DIM; BaseClassRef::m_leaf_max_size = params.leaf_max_size; // Create a permutable array of indices to the input vectors. init_vind(); } /** * Builds the index */ void buildIndex() { BaseClassRef::m_size = dataset.kdtree_get_point_count(); BaseClassRef::m_size_at_index_build = BaseClassRef::m_size; init_vind(); this->freeIndex(*this); BaseClassRef::m_size_at_index_build = BaseClassRef::m_size; if (BaseClassRef::m_size == 0) return; computeBoundingBox(BaseClassRef::root_bbox); BaseClassRef::root_node = this->divideTree(*this, 0, BaseClassRef::m_size, BaseClassRef::root_bbox); // construct the tree } /** \name Query methods * @{ */ /** * Find set of nearest neighbors to vec[0:dim-1]. Their indices are stored * inside the result object. * * Params: * result = the result object in which the indices of the * nearest-neighbors are stored vec = the vector for which to search the * nearest neighbors * * \tparam RESULTSET Should be any ResultSet<DistanceType> * \return True if the requested neighbors could be found. * \sa knnSearch, radiusSearch */ template <typename RESULTSET> bool findNeighbors(RESULTSET &result, const ElementType *vec, const SearchParams &searchParams) const { assert(vec); if (this->size(*this) == 0) return false; if (!BaseClassRef::root_node) throw std::runtime_error( "[nanoflann] findNeighbors() called before building the index."); float epsError = 1 + searchParams.eps; distance_vector_t dists; // fixed or variable-sized container (depending on DIM) auto zero = static_cast<decltype(result.worstDist())>(0); assign(dists, (DIM > 0 ? DIM : BaseClassRef::dim), zero); // Fill it with zeros. DistanceType distsq = this->computeInitialDistances(*this, vec, dists); searchLevel(result, vec, BaseClassRef::root_node, distsq, dists, epsError); // "count_leaf" parameter removed since was neither // used nor returned to the user. return result.full(); } /** * Find the "num_closest" nearest neighbors to the \a query_point[0:dim-1]. * Their indices are stored inside the result object. \sa radiusSearch, * findNeighbors \note nChecks_IGNORED is ignored but kept for compatibility * with the original FLANN interface. \return Number `N` of valid points in * the result set. Only the first `N` entries in `out_indices` and * `out_distances_sq` will be valid. Return may be less than `num_closest` * only if the number of elements in the tree is less than `num_closest`. */ size_t knnSearch(const ElementType *query_point, const size_t num_closest, IndexType *out_indices, DistanceType *out_distances_sq, const int /* nChecks_IGNORED */ = 10) const { nanoflann::KNNResultSet<DistanceType, IndexType> resultSet(num_closest); resultSet.init(out_indices, out_distances_sq); this->findNeighbors(resultSet, query_point, nanoflann::SearchParams()); return resultSet.size(); } /** * Find all the neighbors to \a query_point[0:dim-1] within a maximum radius. * The output is given as a vector of pairs, of which the first element is a * point index and the second the corresponding distance. Previous contents of * \a IndicesDists are cleared. * * If searchParams.sorted==true, the output list is sorted by ascending * distances. * * For a better performance, it is advisable to do a .reserve() on the vector * if you have any wild guess about the number of expected matches. * * \sa knnSearch, findNeighbors, radiusSearchCustomCallback * \return The number of points within the given radius (i.e. indices.size() * or dists.size() ) */ size_t radiusSearch(const ElementType *query_point, const DistanceType &radius, std::vector<std::pair<IndexType, DistanceType>> &IndicesDists, const SearchParams &searchParams) const { RadiusResultSet<DistanceType, IndexType> resultSet(radius, IndicesDists); const size_t nFound = radiusSearchCustomCallback(query_point, resultSet, searchParams); if (searchParams.sorted) std::sort(IndicesDists.begin(), IndicesDists.end(), IndexDist_Sorter()); return nFound; } /** * Just like radiusSearch() but with a custom callback class for each point * found in the radius of the query. See the source of RadiusResultSet<> as a * start point for your own classes. \sa radiusSearch */ template <class SEARCH_CALLBACK> size_t radiusSearchCustomCallback( const ElementType *query_point, SEARCH_CALLBACK &resultSet, const SearchParams &searchParams = SearchParams()) const { this->findNeighbors(resultSet, query_point, searchParams); return resultSet.size(); } /** @} */ public: /** Make sure the auxiliary list \a vind has the same size than the current * dataset, and re-generate if size has changed. */ void init_vind() { // Create a permutable array of indices to the input vectors. BaseClassRef::m_size = dataset.kdtree_get_point_count(); if (BaseClassRef::vind.size() != BaseClassRef::m_size) BaseClassRef::vind.resize(BaseClassRef::m_size); for (size_t i = 0; i < BaseClassRef::m_size; i++) BaseClassRef::vind[i] = i; } void computeBoundingBox(BoundingBox &bbox) { resize(bbox, (DIM > 0 ? DIM : BaseClassRef::dim)); if (dataset.kdtree_get_bbox(bbox)) { // Done! It was implemented in derived class } else { const size_t N = dataset.kdtree_get_point_count(); if (!N) throw std::runtime_error("[nanoflann] computeBoundingBox() called but " "no data points found."); for (int i = 0; i < (DIM > 0 ? DIM : BaseClassRef::dim); ++i) { bbox[i].low = bbox[i].high = this->dataset_get(*this, 0, i); } for (size_t k = 1; k < N; ++k) { for (int i = 0; i < (DIM > 0 ? DIM : BaseClassRef::dim); ++i) { if (this->dataset_get(*this, k, i) < bbox[i].low) bbox[i].low = this->dataset_get(*this, k, i); if (this->dataset_get(*this, k, i) > bbox[i].high) bbox[i].high = this->dataset_get(*this, k, i); } } } } /** * Performs an exact search in the tree starting from a node. * \tparam RESULTSET Should be any ResultSet<DistanceType> * \return true if the search should be continued, false if the results are * sufficient */ template <class RESULTSET> bool searchLevel(RESULTSET &result_set, const ElementType *vec, const NodePtr node, DistanceType mindistsq, distance_vector_t &dists, const float epsError) const { /* If this is a leaf node, then do check and return. */ if ((node->child1 == NULL) && (node->child2 == NULL)) { // count_leaf += (node->lr.right-node->lr.left); // Removed since was // neither used nor returned to the user. DistanceType worst_dist = result_set.worstDist(); for (IndexType i = node->node_type.lr.left; i < node->node_type.lr.right; ++i) { const IndexType index = BaseClassRef::vind[i]; // reorder... : i; DistanceType dist = distance.evalMetric( vec, index, (DIM > 0 ? DIM : BaseClassRef::dim)); if (dist < worst_dist) { if (!result_set.addPoint(dist, BaseClassRef::vind[i])) { // the resultset doesn't want to receive any more points, we're done // searching! return false; } } } return true; } /* Which child branch should be taken first? */ int idx = node->node_type.sub.divfeat; ElementType val = vec[idx]; DistanceType diff1 = val - node->node_type.sub.divlow; DistanceType diff2 = val - node->node_type.sub.divhigh; NodePtr bestChild; NodePtr otherChild; DistanceType cut_dist; if ((diff1 + diff2) < 0) { bestChild = node->child1; otherChild = node->child2; cut_dist = distance.accum_dist(val, node->node_type.sub.divhigh, idx); } else { bestChild = node->child2; otherChild = node->child1; cut_dist = distance.accum_dist(val, node->node_type.sub.divlow, idx); } /* Call recursively to search next level down. */ if (!searchLevel(result_set, vec, bestChild, mindistsq, dists, epsError)) { // the resultset doesn't want to receive any more points, we're done // searching! return false; } DistanceType dst = dists[idx]; mindistsq = mindistsq + cut_dist - dst; dists[idx] = cut_dist; if (mindistsq * epsError <= result_set.worstDist()) { if (!searchLevel(result_set, vec, otherChild, mindistsq, dists, epsError)) { // the resultset doesn't want to receive any more points, we're done // searching! return false; } } dists[idx] = dst; return true; } public: /** Stores the index in a binary file. * IMPORTANT NOTE: The set of data points is NOT stored in the file, so when * loading the index object it must be constructed associated to the same * source of data points used while building it. See the example: * examples/saveload_example.cpp \sa loadIndex */ void saveIndex(FILE *stream) { this->saveIndex_(*this, stream); } /** Loads a previous index from a binary file. * IMPORTANT NOTE: The set of data points is NOT stored in the file, so the * index object must be constructed associated to the same source of data * points used while building the index. See the example: * examples/saveload_example.cpp \sa loadIndex */ void loadIndex(FILE *stream) { this->loadIndex_(*this, stream); } }; // class KDTree /** kd-tree dynamic index * * Contains the k-d trees and other information for indexing a set of points * for nearest-neighbor matching. * * The class "DatasetAdaptor" must provide the following interface (can be * non-virtual, inlined methods): * * \code * // Must return the number of data poins * inline size_t kdtree_get_point_count() const { ... } * * // Must return the dim'th component of the idx'th point in the class: * inline T kdtree_get_pt(const size_t idx, const size_t dim) const { ... } * * // Optional bounding-box computation: return false to default to a standard * bbox computation loop. * // Return true if the BBOX was already computed by the class and returned * in "bb" so it can be avoided to redo it again. * // Look at bb.size() to find out the expected dimensionality (e.g. 2 or 3 * for point clouds) template <class BBOX> bool kdtree_get_bbox(BBOX &bb) const * { * bb[0].low = ...; bb[0].high = ...; // 0th dimension limits * bb[1].low = ...; bb[1].high = ...; // 1st dimension limits * ... * return true; * } * * \endcode * * \tparam DatasetAdaptor The user-provided adaptor (see comments above). * \tparam Distance The distance metric to use: nanoflann::metric_L1, * nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. \tparam DIM * Dimensionality of data points (e.g. 3 for 3D points) \tparam IndexType Will * be typically size_t or int */ template <typename Distance, class DatasetAdaptor, int DIM = -1, typename IndexType = size_t> class KDTreeSingleIndexDynamicAdaptor_ : public KDTreeBaseClass<KDTreeSingleIndexDynamicAdaptor_< Distance, DatasetAdaptor, DIM, IndexType>, Distance, DatasetAdaptor, DIM, IndexType> { public: /** * The dataset used by this index */ const DatasetAdaptor &dataset; //!< The source of our data KDTreeSingleIndexAdaptorParams index_params; std::vector<int> &treeIndex; Distance distance; typedef typename nanoflann::KDTreeBaseClass< nanoflann::KDTreeSingleIndexDynamicAdaptor_<Distance, DatasetAdaptor, DIM, IndexType>, Distance, DatasetAdaptor, DIM, IndexType> BaseClassRef; typedef typename BaseClassRef::ElementType ElementType; typedef typename BaseClassRef::DistanceType DistanceType; typedef typename BaseClassRef::Node Node; typedef Node *NodePtr; typedef typename BaseClassRef::Interval Interval; /** Define "BoundingBox" as a fixed-size or variable-size container depending * on "DIM" */ typedef typename BaseClassRef::BoundingBox BoundingBox; /** Define "distance_vector_t" as a fixed-size or variable-size container * depending on "DIM" */ typedef typename BaseClassRef::distance_vector_t distance_vector_t; /** * KDTree constructor * * Refer to docs in README.md or online in * https://github.com/jlblancoc/nanoflann * * The KD-Tree point dimension (the length of each point in the datase, e.g. 3 * for 3D points) is determined by means of: * - The \a DIM template parameter if >0 (highest priority) * - Otherwise, the \a dimensionality parameter of this constructor. * * @param inputData Dataset with the input features * @param params Basically, the maximum leaf node size */ KDTreeSingleIndexDynamicAdaptor_( const int dimensionality, const DatasetAdaptor &inputData, std::vector<int> &treeIndex_, const KDTreeSingleIndexAdaptorParams &params = KDTreeSingleIndexAdaptorParams()) : dataset(inputData), index_params(params), treeIndex(treeIndex_), distance(inputData) { BaseClassRef::root_node = NULL; BaseClassRef::m_size = 0; BaseClassRef::m_size_at_index_build = 0; BaseClassRef::dim = dimensionality; if (DIM > 0) BaseClassRef::dim = DIM; BaseClassRef::m_leaf_max_size = params.leaf_max_size; } /** Assignment operator definiton */ KDTreeSingleIndexDynamicAdaptor_ operator=(const KDTreeSingleIndexDynamicAdaptor_ &rhs) { KDTreeSingleIndexDynamicAdaptor_ tmp(rhs); std::swap(BaseClassRef::vind, tmp.BaseClassRef::vind); std::swap(BaseClassRef::m_leaf_max_size, tmp.BaseClassRef::m_leaf_max_size); std::swap(index_params, tmp.index_params); std::swap(treeIndex, tmp.treeIndex); std::swap(BaseClassRef::m_size, tmp.BaseClassRef::m_size); std::swap(BaseClassRef::m_size_at_index_build, tmp.BaseClassRef::m_size_at_index_build); std::swap(BaseClassRef::root_node, tmp.BaseClassRef::root_node); std::swap(BaseClassRef::root_bbox, tmp.BaseClassRef::root_bbox); std::swap(BaseClassRef::pool, tmp.BaseClassRef::pool); return *this; } /** * Builds the index */ void buildIndex() { BaseClassRef::m_size = BaseClassRef::vind.size(); this->freeIndex(*this); BaseClassRef::m_size_at_index_build = BaseClassRef::m_size; if (BaseClassRef::m_size == 0) return; computeBoundingBox(BaseClassRef::root_bbox); BaseClassRef::root_node = this->divideTree(*this, 0, BaseClassRef::m_size, BaseClassRef::root_bbox); // construct the tree } /** \name Query methods * @{ */ /** * Find set of nearest neighbors to vec[0:dim-1]. Their indices are stored * inside the result object. * * Params: * result = the result object in which the indices of the * nearest-neighbors are stored vec = the vector for which to search the * nearest neighbors * * \tparam RESULTSET Should be any ResultSet<DistanceType> * \return True if the requested neighbors could be found. * \sa knnSearch, radiusSearch */ template <typename RESULTSET> bool findNeighbors(RESULTSET &result, const ElementType *vec, const SearchParams &searchParams) const { assert(vec); if (this->size(*this) == 0) return false; if (!BaseClassRef::root_node) return false; float epsError = 1 + searchParams.eps; // fixed or variable-sized container (depending on DIM) distance_vector_t dists; // Fill it with zeros. assign(dists, (DIM > 0 ? DIM : BaseClassRef::dim), static_cast<typename distance_vector_t::value_type>(0)); DistanceType distsq = this->computeInitialDistances(*this, vec, dists); searchLevel(result, vec, BaseClassRef::root_node, distsq, dists, epsError); // "count_leaf" parameter removed since was neither // used nor returned to the user. return result.full(); } /** * Find the "num_closest" nearest neighbors to the \a query_point[0:dim-1]. * Their indices are stored inside the result object. \sa radiusSearch, * findNeighbors \note nChecks_IGNORED is ignored but kept for compatibility * with the original FLANN interface. \return Number `N` of valid points in * the result set. Only the first `N` entries in `out_indices` and * `out_distances_sq` will be valid. Return may be less than `num_closest` * only if the number of elements in the tree is less than `num_closest`. */ size_t knnSearch(const ElementType *query_point, const size_t num_closest, IndexType *out_indices, DistanceType *out_distances_sq, const int /* nChecks_IGNORED */ = 10) const { nanoflann::KNNResultSet<DistanceType, IndexType> resultSet(num_closest); resultSet.init(out_indices, out_distances_sq); this->findNeighbors(resultSet, query_point, nanoflann::SearchParams()); return resultSet.size(); } /** * Find all the neighbors to \a query_point[0:dim-1] within a maximum radius. * The output is given as a vector of pairs, of which the first element is a * point index and the second the corresponding distance. Previous contents of * \a IndicesDists are cleared. * * If searchParams.sorted==true, the output list is sorted by ascending * distances. * * For a better performance, it is advisable to do a .reserve() on the vector * if you have any wild guess about the number of expected matches. * * \sa knnSearch, findNeighbors, radiusSearchCustomCallback * \return The number of points within the given radius (i.e. indices.size() * or dists.size() ) */ size_t radiusSearch(const ElementType *query_point, const DistanceType &radius, std::vector<std::pair<IndexType, DistanceType>> &IndicesDists, const SearchParams &searchParams) const { RadiusResultSet<DistanceType, IndexType> resultSet(radius, IndicesDists); const size_t nFound = radiusSearchCustomCallback(query_point, resultSet, searchParams); if (searchParams.sorted) std::sort(IndicesDists.begin(), IndicesDists.end(), IndexDist_Sorter()); return nFound; } /** * Just like radiusSearch() but with a custom callback class for each point * found in the radius of the query. See the source of RadiusResultSet<> as a * start point for your own classes. \sa radiusSearch */ template <class SEARCH_CALLBACK> size_t radiusSearchCustomCallback( const ElementType *query_point, SEARCH_CALLBACK &resultSet, const SearchParams &searchParams = SearchParams()) const { this->findNeighbors(resultSet, query_point, searchParams); return resultSet.size(); } /** @} */ public: void computeBoundingBox(BoundingBox &bbox) { resize(bbox, (DIM > 0 ? DIM : BaseClassRef::dim)); if (dataset.kdtree_get_bbox(bbox)) { // Done! It was implemented in derived class } else { const size_t N = BaseClassRef::m_size; if (!N) throw std::runtime_error("[nanoflann] computeBoundingBox() called but " "no data points found."); for (int i = 0; i < (DIM > 0 ? DIM : BaseClassRef::dim); ++i) { bbox[i].low = bbox[i].high = this->dataset_get(*this, BaseClassRef::vind[0], i); } for (size_t k = 1; k < N; ++k) { for (int i = 0; i < (DIM > 0 ? DIM : BaseClassRef::dim); ++i) { if (this->dataset_get(*this, BaseClassRef::vind[k], i) < bbox[i].low) bbox[i].low = this->dataset_get(*this, BaseClassRef::vind[k], i); if (this->dataset_get(*this, BaseClassRef::vind[k], i) > bbox[i].high) bbox[i].high = this->dataset_get(*this, BaseClassRef::vind[k], i); } } } } /** * Performs an exact search in the tree starting from a node. * \tparam RESULTSET Should be any ResultSet<DistanceType> */ template <class RESULTSET> void searchLevel(RESULTSET &result_set, const ElementType *vec, const NodePtr node, DistanceType mindistsq, distance_vector_t &dists, const float epsError) const { /* If this is a leaf node, then do check and return. */ if ((node->child1 == NULL) && (node->child2 == NULL)) { // count_leaf += (node->lr.right-node->lr.left); // Removed since was // neither used nor returned to the user. DistanceType worst_dist = result_set.worstDist(); for (IndexType i = node->node_type.lr.left; i < node->node_type.lr.right; ++i) { const IndexType index = BaseClassRef::vind[i]; // reorder... : i; if (treeIndex[index] == -1) continue; DistanceType dist = distance.evalMetric( vec, index, (DIM > 0 ? DIM : BaseClassRef::dim)); if (dist < worst_dist) { if (!result_set.addPoint( static_cast<typename RESULTSET::DistanceType>(dist), static_cast<typename RESULTSET::IndexType>( BaseClassRef::vind[i]))) { // the resultset doesn't want to receive any more points, we're done // searching! return; // false; } } } return; } /* Which child branch should be taken first? */ int idx = node->node_type.sub.divfeat; ElementType val = vec[idx]; DistanceType diff1 = val - node->node_type.sub.divlow; DistanceType diff2 = val - node->node_type.sub.divhigh; NodePtr bestChild; NodePtr otherChild; DistanceType cut_dist; if ((diff1 + diff2) < 0) { bestChild = node->child1; otherChild = node->child2; cut_dist = distance.accum_dist(val, node->node_type.sub.divhigh, idx); } else { bestChild = node->child2; otherChild = node->child1; cut_dist = distance.accum_dist(val, node->node_type.sub.divlow, idx); } /* Call recursively to search next level down. */ searchLevel(result_set, vec, bestChild, mindistsq, dists, epsError); DistanceType dst = dists[idx]; mindistsq = mindistsq + cut_dist - dst; dists[idx] = cut_dist; if (mindistsq * epsError <= result_set.worstDist()) { searchLevel(result_set, vec, otherChild, mindistsq, dists, epsError); } dists[idx] = dst; } public: /** Stores the index in a binary file. * IMPORTANT NOTE: The set of data points is NOT stored in the file, so when * loading the index object it must be constructed associated to the same * source of data points used while building it. See the example: * examples/saveload_example.cpp \sa loadIndex */ void saveIndex(FILE *stream) { this->saveIndex_(*this, stream); } /** Loads a previous index from a binary file. * IMPORTANT NOTE: The set of data points is NOT stored in the file, so the * index object must be constructed associated to the same source of data * points used while building the index. See the example: * examples/saveload_example.cpp \sa loadIndex */ void loadIndex(FILE *stream) { this->loadIndex_(*this, stream); } }; /** kd-tree dynaimic index * * class to create multiple static index and merge their results to behave as * single dynamic index as proposed in Logarithmic Approach. * * Example of usage: * examples/dynamic_pointcloud_example.cpp * * \tparam DatasetAdaptor The user-provided adaptor (see comments above). * \tparam Distance The distance metric to use: nanoflann::metric_L1, * nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. \tparam DIM * Dimensionality of data points (e.g. 3 for 3D points) \tparam IndexType Will * be typically size_t or int */ template <typename Distance, class DatasetAdaptor, int DIM = -1, typename IndexType = size_t> class KDTreeSingleIndexDynamicAdaptor { public: typedef typename Distance::ElementType ElementType; typedef typename Distance::DistanceType DistanceType; protected: size_t m_leaf_max_size; size_t treeCount; size_t pointCount; /** * The dataset used by this index */ const DatasetAdaptor &dataset; //!< The source of our data std::vector<int> treeIndex; //!< treeIndex[idx] is the index of tree in which //!< point at idx is stored. treeIndex[idx]=-1 //!< means that point has been removed. KDTreeSingleIndexAdaptorParams index_params; int dim; //!< Dimensionality of each data point typedef KDTreeSingleIndexDynamicAdaptor_<Distance, DatasetAdaptor, DIM> index_container_t; std::vector<index_container_t> index; public: /** Get a const ref to the internal list of indices; the number of indices is * adapted dynamically as the dataset grows in size. */ const std::vector<index_container_t> &getAllIndices() const { return index; } private: /** finds position of least significant unset bit */ int First0Bit(IndexType num) { int pos = 0; while (num & 1) { num = num >> 1; pos++; } return pos; } /** Creates multiple empty trees to handle dynamic support */ void init() { typedef KDTreeSingleIndexDynamicAdaptor_<Distance, DatasetAdaptor, DIM> my_kd_tree_t; std::vector<my_kd_tree_t> index_( treeCount, my_kd_tree_t(dim /*dim*/, dataset, treeIndex, index_params)); index = index_; } public: Distance distance; /** * KDTree constructor * * Refer to docs in README.md or online in * https://github.com/jlblancoc/nanoflann * * The KD-Tree point dimension (the length of each point in the datase, e.g. 3 * for 3D points) is determined by means of: * - The \a DIM template parameter if >0 (highest priority) * - Otherwise, the \a dimensionality parameter of this constructor. * * @param inputData Dataset with the input features * @param params Basically, the maximum leaf node size */ KDTreeSingleIndexDynamicAdaptor(const int dimensionality, const DatasetAdaptor &inputData, const KDTreeSingleIndexAdaptorParams &params = KDTreeSingleIndexAdaptorParams(), const size_t maximumPointCount = 1000000000U) : dataset(inputData), index_params(params), distance(inputData) { treeCount = static_cast<size_t>(std::log2(maximumPointCount)); pointCount = 0U; dim = dimensionality; treeIndex.clear(); if (DIM > 0) dim = DIM; m_leaf_max_size = params.leaf_max_size; init(); const size_t num_initial_points = dataset.kdtree_get_point_count(); if (num_initial_points > 0) { addPoints(0, num_initial_points - 1); } } /** Deleted copy constructor*/ KDTreeSingleIndexDynamicAdaptor( const KDTreeSingleIndexDynamicAdaptor<Distance, DatasetAdaptor, DIM, IndexType> &) = delete; /** Add points to the set, Inserts all points from [start, end] */ void addPoints(IndexType start, IndexType end) { size_t count = end - start + 1; treeIndex.resize(treeIndex.size() + count); for (IndexType idx = start; idx <= end; idx++) { int pos = First0Bit(pointCount); index[pos].vind.clear(); treeIndex[pointCount] = pos; for (int i = 0; i < pos; i++) { for (int j = 0; j < static_cast<int>(index[i].vind.size()); j++) { index[pos].vind.push_back(index[i].vind[j]); if (treeIndex[index[i].vind[j]] != -1) treeIndex[index[i].vind[j]] = pos; } index[i].vind.clear(); index[i].freeIndex(index[i]); } index[pos].vind.push_back(idx); index[pos].buildIndex(); pointCount++; } } /** Remove a point from the set (Lazy Deletion) */ void removePoint(size_t idx) { if (idx >= pointCount) return; treeIndex[idx] = -1; } /** * Find set of nearest neighbors to vec[0:dim-1]. Their indices are stored * inside the result object. * * Params: * result = the result object in which the indices of the * nearest-neighbors are stored vec = the vector for which to search the * nearest neighbors * * \tparam RESULTSET Should be any ResultSet<DistanceType> * \return True if the requested neighbors could be found. * \sa knnSearch, radiusSearch */ template <typename RESULTSET> bool findNeighbors(RESULTSET &result, const ElementType *vec, const SearchParams &searchParams) const { for (size_t i = 0; i < treeCount; i++) { index[i].findNeighbors(result, &vec[0], searchParams); } return result.full(); } }; /** An L2-metric KD-tree adaptor for working with data directly stored in an * Eigen Matrix, without duplicating the data storage. Each row in the matrix * represents a point in the state space. * * Example of usage: * \code * Eigen::Matrix<num_t,Dynamic,Dynamic> mat; * // Fill out "mat"... * * typedef KDTreeEigenMatrixAdaptor< Eigen::Matrix<num_t,Dynamic,Dynamic> > * my_kd_tree_t; const int max_leaf = 10; my_kd_tree_t mat_index(mat, max_leaf * ); mat_index.index->buildIndex(); mat_index.index->... \endcode * * \tparam DIM If set to >0, it specifies a compile-time fixed dimensionality * for the points in the data set, allowing more compiler optimizations. \tparam * Distance The distance metric to use: nanoflann::metric_L1, * nanoflann::metric_L2, nanoflann::metric_L2_Simple, etc. */ template <class MatrixType, int DIM = -1, class Distance = nanoflann::metric_L2> struct KDTreeEigenMatrixAdaptor { typedef KDTreeEigenMatrixAdaptor<MatrixType, DIM, Distance> self_t; typedef typename MatrixType::Scalar num_t; typedef typename MatrixType::Index IndexType; typedef typename Distance::template traits<num_t, self_t>::distance_t metric_t; typedef KDTreeSingleIndexAdaptor<metric_t, self_t, MatrixType::ColsAtCompileTime, IndexType> index_t; index_t *index; //! The kd-tree index for the user to call its methods as //! usual with any other FLANN index. /// Constructor: takes a const ref to the matrix object with the data points KDTreeEigenMatrixAdaptor(const size_t dimensionality, const std::reference_wrapper<const MatrixType> &mat, const int leaf_max_size = 10) : m_data_matrix(mat) { const auto dims = mat.get().cols(); if (size_t(dims) != dimensionality) throw std::runtime_error( "Error: 'dimensionality' must match column count in data matrix"); if (DIM > 0 && int(dims) != DIM) throw std::runtime_error( "Data set dimensionality does not match the 'DIM' template argument"); index = new index_t(static_cast<int>(dims), *this /* adaptor */, nanoflann::KDTreeSingleIndexAdaptorParams(leaf_max_size)); index->buildIndex(); } public: /** Deleted copy constructor */ KDTreeEigenMatrixAdaptor(const self_t &) = delete; ~KDTreeEigenMatrixAdaptor() { delete index; } const std::reference_wrapper<const MatrixType> m_data_matrix; /** Query for the \a num_closest closest points to a given point (entered as * query_point[0:dim-1]). Note that this is a short-cut method for * index->findNeighbors(). The user can also call index->... methods as * desired. \note nChecks_IGNORED is ignored but kept for compatibility with * the original FLANN interface. */ inline void query(const num_t *query_point, const size_t num_closest, IndexType *out_indices, num_t *out_distances_sq, const int /* nChecks_IGNORED */ = 10) const { nanoflann::KNNResultSet<num_t, IndexType> resultSet(num_closest); resultSet.init(out_indices, out_distances_sq); index->findNeighbors(resultSet, query_point, nanoflann::SearchParams()); } /** @name Interface expected by KDTreeSingleIndexAdaptor * @{ */ const self_t &derived() const { return *this; } self_t &derived() { return *this; } // Must return the number of data points inline size_t kdtree_get_point_count() const { return m_data_matrix.get().rows(); } // Returns the dim'th component of the idx'th point in the class: inline num_t kdtree_get_pt(const IndexType idx, size_t dim) const { return m_data_matrix.get().coeff(idx, IndexType(dim)); } // Optional bounding-box computation: return false to default to a standard // bbox computation loop. // Return true if the BBOX was already computed by the class and returned in // "bb" so it can be avoided to redo it again. Look at bb.size() to find out // the expected dimensionality (e.g. 2 or 3 for point clouds) template <class BBOX> bool kdtree_get_bbox(BBOX & /*bb*/) const { return false; } /** @} */ }; // end of KDTreeEigenMatrixAdaptor /** @} */ /** @} */ // end of grouping } // namespace nanoflann #endif /* NANOFLANN_HPP_ */
{ "pile_set_name": "Github" }
// Copyright (c) 2015 Amanieu d'Antras // // 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. #ifndef ASYNCXX_H_ # error "Do not include this header directly, include <async++.h> instead." #endif namespace async { namespace detail { // Pseudo-void type: it takes up no space but can be moved and copied struct fake_void {}; template<typename T> struct void_to_fake_void { typedef T type; }; template<> struct void_to_fake_void<void> { typedef fake_void type; }; template<typename T> T fake_void_to_void(T&& x) { return std::forward<T>(x); } inline void fake_void_to_void(fake_void) {} // Check if type is a task type, used to detect task unwraping template<typename T> struct is_task: public std::false_type {}; template<typename T> struct is_task<task<T>>: public std::true_type {}; template<typename T> struct is_task<const task<T>>: public std::true_type {}; template<typename T> struct is_task<shared_task<T>>: public std::true_type {}; template<typename T> struct is_task<const shared_task<T>>: public std::true_type {}; // Extract the result type of a task if T is a task, otherwise just return T template<typename T> struct remove_task { typedef T type; }; template<typename T> struct remove_task<task<T>> { typedef T type; }; template<typename T> struct remove_task<const task<T>> { typedef T type; }; template<typename T> struct remove_task<shared_task<T>> { typedef T type; }; template<typename T> struct remove_task<const shared_task<T>> { typedef T type; }; // Check if a type is callable with the given arguments typedef char one[1]; typedef char two[2]; template<typename Func, typename... Args, typename = decltype(std::declval<Func>()(std::declval<Args>()...))> two& is_callable_helper(int); template<typename Func, typename... Args> one& is_callable_helper(...); template<typename T> struct is_callable; template<typename Func, typename... Args> struct is_callable<Func(Args...)>: public std::integral_constant<bool, sizeof(is_callable_helper<Func, Args...>(0)) - 1> {}; // Wrapper to run a function object with an optional parameter: // - void returns are turned into fake_void // - fake_void parameter will invoke the function with no arguments template<typename Func, typename = typename std::enable_if<!std::is_void<decltype(std::declval<Func>()())>::value>::type> decltype(std::declval<Func>()()) invoke_fake_void(Func&& f) { return std::forward<Func>(f)(); } template<typename Func, typename = typename std::enable_if<std::is_void<decltype(std::declval<Func>()())>::value>::type> fake_void invoke_fake_void(Func&& f) { std::forward<Func>(f)(); return fake_void(); } template<typename Func, typename Param> typename void_to_fake_void<decltype(std::declval<Func>()(std::declval<Param>()))>::type invoke_fake_void(Func&& f, Param&& p) { return detail::invoke_fake_void([&f, &p] {return std::forward<Func>(f)(std::forward<Param>(p));}); } template<typename Func> typename void_to_fake_void<decltype(std::declval<Func>()())>::type invoke_fake_void(Func&& f, fake_void) { return detail::invoke_fake_void(std::forward<Func>(f)); } // Various properties of a continuation function template<typename Func, typename Parent, typename = decltype(std::declval<Func>()())> fake_void is_value_cont_helper(const Parent&, int, int); template<typename Func, typename Parent, typename = decltype(std::declval<Func>()(std::declval<Parent>().get()))> std::true_type is_value_cont_helper(const Parent&, int, int); template<typename Func, typename = decltype(std::declval<Func>()())> std::true_type is_value_cont_helper(const task<void>&, int, int); template<typename Func, typename = decltype(std::declval<Func>()())> std::true_type is_value_cont_helper(const shared_task<void>&, int, int); template<typename Func, typename Parent, typename = decltype(std::declval<Func>()(std::declval<Parent>()))> std::false_type is_value_cont_helper(const Parent&, int, ...); template<typename Func, typename Parent> void is_value_cont_helper(const Parent&, ...); template<typename Parent, typename Func> struct continuation_traits { typedef typename std::decay<Func>::type decay_func; typedef decltype(detail::is_value_cont_helper<decay_func>(std::declval<Parent>(), 0, 0)) is_value_cont; static_assert(!std::is_void<is_value_cont>::value, "Parameter type for continuation function is invalid for parent task type"); typedef typename std::conditional<std::is_same<is_value_cont, fake_void>::value, fake_void, typename std::conditional<std::is_same<is_value_cont, std::true_type>::value, typename void_to_fake_void<decltype(std::declval<Parent>().get())>::type, Parent>::type>::type param_type; typedef decltype(detail::fake_void_to_void(detail::invoke_fake_void(std::declval<decay_func>(), std::declval<param_type>()))) result_type; typedef task<typename remove_task<result_type>::type> task_type; }; } // namespace detail } // namespace async
{ "pile_set_name": "Github" }
<ion-header> <ion-toolbar> <ion-title>FLUSTER</ion-title> <ion-buttons slot="end"> <ion-button (click)="close()"> <ion-icon slot="icon-only" name="checkmark"></ion-icon> </ion-button> </ion-buttons> </ion-toolbar> </ion-header> <ion-content padding [attr.role]="isAdDisplay ? 'ad' : 'browse'"> <ion-searchbar (ionInput)="search($event)" autocomplete="on" autocorrect="on" spellcheck="true" debounce="300" placeholder="{{'SELECT_LANGUAGES.PLACEHOLDER' | translate}}" margin-bottom clearIcon="close-circle" searchIcon="search" ></ion-searchbar> <div padding text-center *ngIf="languages == null"> <ion-spinner ion-text color="primary"></ion-spinner> </div> <ion-list *ngIf="languages != null"> <ion-item *ngFor="let language of languages"> <ion-checkbox slot="start" [(ngModel)]="language.selected" (click)="selectLang(language)"></ion-checkbox> <ion-label>{{language.language.nativeName}}</ion-label> </ion-item> </ion-list> <ion-infinite-scroll *ngIf="languages != null && !isLastPageReached()" (ionInfinite)="nextLanguages($event)"> <ion-infinite-scroll-content></ion-infinite-scroll-content> </ion-infinite-scroll> </ion-content>
{ "pile_set_name": "Github" }
--- title: Jana Kinsman summary: Illustrator, beekeeper categories: - beekeeper - illustrator - mac --- ### Who are you, and what do you do? I am [Jana Kinsman](http://www.janakinsman.com/ "Jana's website.")! Freelance illustrator; the creator of [Doodlebooth](http://doodlebooth.me/ "A service providing hand-drawn portraits at events."), an in-person portraiture service; creator of [Bike a Bee](http://bikeabee.com/ "A beekeeping service in Chicago."), a beekeeping initiative that provides beehives to community gardens and urban farms in Chicago; and 1/5 of [Quite Strong](http://quitestrong.com/ "A design collaborative in Chicago."), an all-female design collaborative. [This is Where I Work](http://thisiswhereiwork.com/ "This is where Jana works.") with a lot of rad people. ### What hardware do you use? For design and illustration work, I use a 11" [MacBook Air][macbook-air]. I bought it because it's tiny and light. I do not do any illustration work on the computer; all of my drawings are hand-drawn and scanned at high resolution. For in-office scanning, I use an [Epson Perfection v600][perfection-v600]. For portable scanning when I am doodling folks at events, I use an [HP Scanjet Professional 1000][scanjet-professional-1000]. I love both scanners uncontrollably. For backing up work, I use a [G-Drive Mini][g-drive-mini]. The headphones I listen to jams on are usually iPod headphones I found on the ground. My dad got me a nice pair of Sennheisers for Christmas, which I leave at my desk. I drink water out of a 1/2 liter Ball jar, and take photos and tweet about general dickery on my [iPhone 4S][iphone-4s]. I use [0.3 Staedtler Pigment Liners][pigment-liner-308] almost exclusively, replacing them when the tip gets flat because of the weird way I hold my pens. I hate to throw them away, so I have a huge collection of flat-tipped pens with the labels scratched through, so I can tell them apart from the fresh ones. For brush and ink work, I use Pelikan india ink and a size 0 Kolinsky Sable brush. I draw on cover-stock Paper Source paper (in White or Soft White) because I got used to it at some point, and I do my brush work on various watercolor papers -- I still haven't found one that I like 100%. I use mechanical pencils for sketching, and a Staedtler Mars Plastic eraser for erasifying. For ink and water reservoirs, I use bottle caps that we collect at our office. My most important hardware is a collection of roughly 300,000 live bees. I keep Minnesota Hygienic bees, developed by [Marla Spivak](http://www.macfound.org/fellows/43/ "An article about Marla."), one of my personal heroes. I order my beekeeping equipment through Mann-Lake, a cooperatively owned beekeeping supplier in Minnesota. I keep bees in [Langstroth hives][langstroth-hive] because my hives are located far apart; I carry everything by bicycle and trailer, and Langstroth hives are ultra-modular. I use 10-frame [supers][honey-super] and use only medium supers (aka "Illinois supers"; REPRESENT) since keeping one size makes the whole process even simpler. I use plastic foundation in my frames; it's sturdier and can take a beating in the honey extractor. I prefer alexander veils and generally work on hives without gloves, unless I am doing a lot of work on a hive and they seem pissy. I wear a light blue button-down and light colored jeans or cutoffs, since bees interpret dark colors as predators like bears. I use a [Dadant smoker][m00926-smoker] and a generic hive tool that I inherited from another beekeeper friend. I extract honey in a 4-frame extractor that I share with the [Chicago Honey Co-Op](http://www.chicagohoneycoop.com/ "A honey and bee co-op."), and bottle it in 4, 8, and 12 oz canning-style jars. I use a Bikes At Work 32" trailer that I hitch to my [1974 Peugeot PX-10][px-10], which I bought offa Craigslist and lovingly built into a beautiful touring bike. It features a Stronglight randonneuring crankset and a vintage Brooks Professional S saddle, among other little nerdy bike parts. At one point it was all French and period-appropriate, but I upgraded a lot of its parts. I use an old Jim Blackburn rack with a custom smoker holster made by [Levi Borrenson](https://twitter.com/LJBike "Levi's Twitter account."), and carry junk in orange [Ortlieb Panniers][back-roller-classic]. I keep actual field notes in Field Notes. ### And what software? I work in [Adobe CS3][creative-suite] because I don't know any better, and most of my image processing and layout work requires little time. [Instagram][instagram-ios] makes my beekeeping and all of the stuff I pick up off the ground look good. I use [Gmail][] and [Google Drive][google-drive] as organizational tools, but I still use a Moleskine weekly planner. I play [Hundreds][hundreds-ios] and [Osmos][osmos-ios] to relieve anxiety. Quite Strong and I use [Basecamp][] for all of our collaboration and communication, though we frequently lament the loss of Google Wave, the most perfect collaboration tool created. YEAH, WHAT. As fuel for my bee smoker, I use newspaper or used paper bags to start, then a couple of 4x4-ish pieces of coffee bag burlap from my bicycle-business friend [Grinderman Coffee](http://grindermancoffee.com/ "Bicycle-delivered coffee in Chicago."). Once the fire is going strong, I throw in wood chips, which are usually plentiful at community gardens. To dampen the fire and prevent embers from flying out, I loosely pack the lid with grass, though I have been known to pack it with mint so the bees can enjoy a lovely minty smoke. All that and a loving and peaceful vibe is the only bee-related software I use. ### What would be your dream setup? I would love to get a piece of land in the city, sandwiched between Elston Avenue and the Chicago River. I'd grow a ton of milkweed to sustain a lot of monarch butterflies, and let the lot fill up with nectar-rich plants like white and yellow sweet clover, dutch clover, and dandelions. I'd keep beehives there and teach classes as often as I could. I'd love to keep more bees in public places like schools and churches, to encourage curiosity and an understanding of natural systems. I'd be a not-for-profit and throw big parties with lots of free beer to raise money for more hives -- and hiring a part-time helper. The setup I have for my illustration freelance work is already a dream. I work with many amazing friends, and have a fish tank with a [baby fish](https://twitter.com/someoffice/status/302835355617472513 "A photo of a baby fish.") right next to me every day. [back-roller-classic]: http://www.ortliebusa.com/prodInfo.asp?pid=31&cid=2 "Bags for the sides of the back wheel of a bike." [basecamp]: https://basecamp.com/ "Web-based project management." [creative-suite]: https://www.adobe.com/creativecloud.html "A collection of design tools." [g-drive-mini]: https://www.g-technology.com/products/g-drive-mini-1-tb-external-desktop-hard-drive "A portable hard drive." [gmail]: https://mail.google.com/mail/ "Web-based email." [google-drive]: https://drive.google.com/ "A cloud storage service." [honey-super]: https://en.wikipedia.org/wiki/Honey_super "A frame system used by beekeepers for collecting honey." [hundreds-ios]: http://playhundreds.com/ "A puzzle game." [instagram-ios]: https://itunes.apple.com/us/app/instagram/id389801252 "A photo taking/sharing app." [iphone-4s]: https://en.wikipedia.org/wiki/IPhone_4S "A smartphone." [langstroth-hive]: https://en.wikipedia.org/wiki/Langstroth_hive "A type of beehive." [m00926-smoker]: https://www.dadant.com/catalog/product_info.php?products_id=43 "A smoker for subduing bees." [macbook-air]: https://www.apple.com/macbook-air/ "A very thin laptop." [osmos-ios]: https://itunes.apple.com/us/app/osmos/id382991304 "A physics-based game." [perfection-v600]: https://www.amazon.com/Epson-B11B198011-Perfection-Photo-Scanner/dp/B002OEBMRU "A photo scanner." [pigment-liner-308]: https://www.staedtler.com/en/products/ink-writing-instruments/fineliners/pigment-liner-308-fineliner/ "A pen." [px-10]: http://www.classicrendezvous.com/France/bicycles/Peugeot/PX10_history "A fancy bicycle." [scanjet-professional-1000]: http://www.shopping.hp.com/en_US/home-office/-/products/Printers/HP-Scanjet-and-HP-Fax/L2722A?HP-Scanjet-Professional-1000-Mobile-Scanner "A portable scanner."
{ "pile_set_name": "Github" }
/*! * Bootstrap Grid v4.0.0-beta.2 (https://getbootstrap.com) * Copyright 2011-2017 The Bootstrap Authors * Copyright 2011-2017 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ @-ms-viewport { width: device-width; } html { box-sizing: border-box; -ms-overflow-style: scrollbar; } *, *::before, *::after { box-sizing: inherit; } .container { width: 100%; padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } @media (min-width: 576px) { .container { max-width: 540px; } } @media (min-width: 768px) { .container { max-width: 720px; } } @media (min-width: 992px) { .container { max-width: 960px; } } @media (min-width: 1200px) { .container { max-width: 1140px; } } .container-fluid { width: 100%; padding-right: 15px; padding-left: 15px; margin-right: auto; margin-left: auto; } .row { display: -ms-flexbox; display: flex; -ms-flex-wrap: wrap; flex-wrap: wrap; margin-right: -15px; margin-left: -15px; } .no-gutters { margin-right: 0; margin-left: 0; } .no-gutters > .col, .no-gutters > [class*="col-"] { padding-right: 0; padding-left: 0; } .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12, .col, .col-auto, .col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12, .col-sm, .col-sm-auto, .col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12, .col-md, .col-md-auto, .col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12, .col-lg, .col-lg-auto, .col-xl-1, .col-xl-2, .col-xl-3, .col-xl-4, .col-xl-5, .col-xl-6, .col-xl-7, .col-xl-8, .col-xl-9, .col-xl-10, .col-xl-11, .col-xl-12, .col-xl, .col-xl-auto { position: relative; width: 100%; min-height: 1px; padding-right: 15px; padding-left: 15px; } .col { -ms-flex-preferred-size: 0; flex-basis: 0; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-auto { -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; max-width: none; } .col-1 { -ms-flex: 0 0 8.333333%; flex: 0 0 8.333333%; max-width: 8.333333%; } .col-2 { -ms-flex: 0 0 16.666667%; flex: 0 0 16.666667%; max-width: 16.666667%; } .col-3 { -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-4 { -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-width: 33.333333%; } .col-5 { -ms-flex: 0 0 41.666667%; flex: 0 0 41.666667%; max-width: 41.666667%; } .col-6 { -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-7 { -ms-flex: 0 0 58.333333%; flex: 0 0 58.333333%; max-width: 58.333333%; } .col-8 { -ms-flex: 0 0 66.666667%; flex: 0 0 66.666667%; max-width: 66.666667%; } .col-9 { -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-10 { -ms-flex: 0 0 83.333333%; flex: 0 0 83.333333%; max-width: 83.333333%; } .col-11 { -ms-flex: 0 0 91.666667%; flex: 0 0 91.666667%; max-width: 91.666667%; } .col-12 { -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .order-first { -ms-flex-order: -1; order: -1; } .order-1 { -ms-flex-order: 1; order: 1; } .order-2 { -ms-flex-order: 2; order: 2; } .order-3 { -ms-flex-order: 3; order: 3; } .order-4 { -ms-flex-order: 4; order: 4; } .order-5 { -ms-flex-order: 5; order: 5; } .order-6 { -ms-flex-order: 6; order: 6; } .order-7 { -ms-flex-order: 7; order: 7; } .order-8 { -ms-flex-order: 8; order: 8; } .order-9 { -ms-flex-order: 9; order: 9; } .order-10 { -ms-flex-order: 10; order: 10; } .order-11 { -ms-flex-order: 11; order: 11; } .order-12 { -ms-flex-order: 12; order: 12; } .offset-1 { margin-left: 8.333333%; } .offset-2 { margin-left: 16.666667%; } .offset-3 { margin-left: 25%; } .offset-4 { margin-left: 33.333333%; } .offset-5 { margin-left: 41.666667%; } .offset-6 { margin-left: 50%; } .offset-7 { margin-left: 58.333333%; } .offset-8 { margin-left: 66.666667%; } .offset-9 { margin-left: 75%; } .offset-10 { margin-left: 83.333333%; } .offset-11 { margin-left: 91.666667%; } @media (min-width: 576px) { .col-sm { -ms-flex-preferred-size: 0; flex-basis: 0; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-sm-auto { -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; max-width: none; } .col-sm-1 { -ms-flex: 0 0 8.333333%; flex: 0 0 8.333333%; max-width: 8.333333%; } .col-sm-2 { -ms-flex: 0 0 16.666667%; flex: 0 0 16.666667%; max-width: 16.666667%; } .col-sm-3 { -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-sm-4 { -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-width: 33.333333%; } .col-sm-5 { -ms-flex: 0 0 41.666667%; flex: 0 0 41.666667%; max-width: 41.666667%; } .col-sm-6 { -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-sm-7 { -ms-flex: 0 0 58.333333%; flex: 0 0 58.333333%; max-width: 58.333333%; } .col-sm-8 { -ms-flex: 0 0 66.666667%; flex: 0 0 66.666667%; max-width: 66.666667%; } .col-sm-9 { -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-sm-10 { -ms-flex: 0 0 83.333333%; flex: 0 0 83.333333%; max-width: 83.333333%; } .col-sm-11 { -ms-flex: 0 0 91.666667%; flex: 0 0 91.666667%; max-width: 91.666667%; } .col-sm-12 { -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .order-sm-first { -ms-flex-order: -1; order: -1; } .order-sm-1 { -ms-flex-order: 1; order: 1; } .order-sm-2 { -ms-flex-order: 2; order: 2; } .order-sm-3 { -ms-flex-order: 3; order: 3; } .order-sm-4 { -ms-flex-order: 4; order: 4; } .order-sm-5 { -ms-flex-order: 5; order: 5; } .order-sm-6 { -ms-flex-order: 6; order: 6; } .order-sm-7 { -ms-flex-order: 7; order: 7; } .order-sm-8 { -ms-flex-order: 8; order: 8; } .order-sm-9 { -ms-flex-order: 9; order: 9; } .order-sm-10 { -ms-flex-order: 10; order: 10; } .order-sm-11 { -ms-flex-order: 11; order: 11; } .order-sm-12 { -ms-flex-order: 12; order: 12; } .offset-sm-0 { margin-left: 0; } .offset-sm-1 { margin-left: 8.333333%; } .offset-sm-2 { margin-left: 16.666667%; } .offset-sm-3 { margin-left: 25%; } .offset-sm-4 { margin-left: 33.333333%; } .offset-sm-5 { margin-left: 41.666667%; } .offset-sm-6 { margin-left: 50%; } .offset-sm-7 { margin-left: 58.333333%; } .offset-sm-8 { margin-left: 66.666667%; } .offset-sm-9 { margin-left: 75%; } .offset-sm-10 { margin-left: 83.333333%; } .offset-sm-11 { margin-left: 91.666667%; } } @media (min-width: 768px) { .col-md { -ms-flex-preferred-size: 0; flex-basis: 0; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-md-auto { -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; max-width: none; } .col-md-1 { -ms-flex: 0 0 8.333333%; flex: 0 0 8.333333%; max-width: 8.333333%; } .col-md-2 { -ms-flex: 0 0 16.666667%; flex: 0 0 16.666667%; max-width: 16.666667%; } .col-md-3 { -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-md-4 { -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-width: 33.333333%; } .col-md-5 { -ms-flex: 0 0 41.666667%; flex: 0 0 41.666667%; max-width: 41.666667%; } .col-md-6 { -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-md-7 { -ms-flex: 0 0 58.333333%; flex: 0 0 58.333333%; max-width: 58.333333%; } .col-md-8 { -ms-flex: 0 0 66.666667%; flex: 0 0 66.666667%; max-width: 66.666667%; } .col-md-9 { -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-md-10 { -ms-flex: 0 0 83.333333%; flex: 0 0 83.333333%; max-width: 83.333333%; } .col-md-11 { -ms-flex: 0 0 91.666667%; flex: 0 0 91.666667%; max-width: 91.666667%; } .col-md-12 { -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .order-md-first { -ms-flex-order: -1; order: -1; } .order-md-1 { -ms-flex-order: 1; order: 1; } .order-md-2 { -ms-flex-order: 2; order: 2; } .order-md-3 { -ms-flex-order: 3; order: 3; } .order-md-4 { -ms-flex-order: 4; order: 4; } .order-md-5 { -ms-flex-order: 5; order: 5; } .order-md-6 { -ms-flex-order: 6; order: 6; } .order-md-7 { -ms-flex-order: 7; order: 7; } .order-md-8 { -ms-flex-order: 8; order: 8; } .order-md-9 { -ms-flex-order: 9; order: 9; } .order-md-10 { -ms-flex-order: 10; order: 10; } .order-md-11 { -ms-flex-order: 11; order: 11; } .order-md-12 { -ms-flex-order: 12; order: 12; } .offset-md-0 { margin-left: 0; } .offset-md-1 { margin-left: 8.333333%; } .offset-md-2 { margin-left: 16.666667%; } .offset-md-3 { margin-left: 25%; } .offset-md-4 { margin-left: 33.333333%; } .offset-md-5 { margin-left: 41.666667%; } .offset-md-6 { margin-left: 50%; } .offset-md-7 { margin-left: 58.333333%; } .offset-md-8 { margin-left: 66.666667%; } .offset-md-9 { margin-left: 75%; } .offset-md-10 { margin-left: 83.333333%; } .offset-md-11 { margin-left: 91.666667%; } } @media (min-width: 992px) { .col-lg { -ms-flex-preferred-size: 0; flex-basis: 0; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-lg-auto { -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; max-width: none; } .col-lg-1 { -ms-flex: 0 0 8.333333%; flex: 0 0 8.333333%; max-width: 8.333333%; } .col-lg-2 { -ms-flex: 0 0 16.666667%; flex: 0 0 16.666667%; max-width: 16.666667%; } .col-lg-3 { -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-lg-4 { -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-width: 33.333333%; } .col-lg-5 { -ms-flex: 0 0 41.666667%; flex: 0 0 41.666667%; max-width: 41.666667%; } .col-lg-6 { -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-lg-7 { -ms-flex: 0 0 58.333333%; flex: 0 0 58.333333%; max-width: 58.333333%; } .col-lg-8 { -ms-flex: 0 0 66.666667%; flex: 0 0 66.666667%; max-width: 66.666667%; } .col-lg-9 { -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-lg-10 { -ms-flex: 0 0 83.333333%; flex: 0 0 83.333333%; max-width: 83.333333%; } .col-lg-11 { -ms-flex: 0 0 91.666667%; flex: 0 0 91.666667%; max-width: 91.666667%; } .col-lg-12 { -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .order-lg-first { -ms-flex-order: -1; order: -1; } .order-lg-1 { -ms-flex-order: 1; order: 1; } .order-lg-2 { -ms-flex-order: 2; order: 2; } .order-lg-3 { -ms-flex-order: 3; order: 3; } .order-lg-4 { -ms-flex-order: 4; order: 4; } .order-lg-5 { -ms-flex-order: 5; order: 5; } .order-lg-6 { -ms-flex-order: 6; order: 6; } .order-lg-7 { -ms-flex-order: 7; order: 7; } .order-lg-8 { -ms-flex-order: 8; order: 8; } .order-lg-9 { -ms-flex-order: 9; order: 9; } .order-lg-10 { -ms-flex-order: 10; order: 10; } .order-lg-11 { -ms-flex-order: 11; order: 11; } .order-lg-12 { -ms-flex-order: 12; order: 12; } .offset-lg-0 { margin-left: 0; } .offset-lg-1 { margin-left: 8.333333%; } .offset-lg-2 { margin-left: 16.666667%; } .offset-lg-3 { margin-left: 25%; } .offset-lg-4 { margin-left: 33.333333%; } .offset-lg-5 { margin-left: 41.666667%; } .offset-lg-6 { margin-left: 50%; } .offset-lg-7 { margin-left: 58.333333%; } .offset-lg-8 { margin-left: 66.666667%; } .offset-lg-9 { margin-left: 75%; } .offset-lg-10 { margin-left: 83.333333%; } .offset-lg-11 { margin-left: 91.666667%; } } @media (min-width: 1200px) { .col-xl { -ms-flex-preferred-size: 0; flex-basis: 0; -ms-flex-positive: 1; flex-grow: 1; max-width: 100%; } .col-xl-auto { -ms-flex: 0 0 auto; flex: 0 0 auto; width: auto; max-width: none; } .col-xl-1 { -ms-flex: 0 0 8.333333%; flex: 0 0 8.333333%; max-width: 8.333333%; } .col-xl-2 { -ms-flex: 0 0 16.666667%; flex: 0 0 16.666667%; max-width: 16.666667%; } .col-xl-3 { -ms-flex: 0 0 25%; flex: 0 0 25%; max-width: 25%; } .col-xl-4 { -ms-flex: 0 0 33.333333%; flex: 0 0 33.333333%; max-width: 33.333333%; } .col-xl-5 { -ms-flex: 0 0 41.666667%; flex: 0 0 41.666667%; max-width: 41.666667%; } .col-xl-6 { -ms-flex: 0 0 50%; flex: 0 0 50%; max-width: 50%; } .col-xl-7 { -ms-flex: 0 0 58.333333%; flex: 0 0 58.333333%; max-width: 58.333333%; } .col-xl-8 { -ms-flex: 0 0 66.666667%; flex: 0 0 66.666667%; max-width: 66.666667%; } .col-xl-9 { -ms-flex: 0 0 75%; flex: 0 0 75%; max-width: 75%; } .col-xl-10 { -ms-flex: 0 0 83.333333%; flex: 0 0 83.333333%; max-width: 83.333333%; } .col-xl-11 { -ms-flex: 0 0 91.666667%; flex: 0 0 91.666667%; max-width: 91.666667%; } .col-xl-12 { -ms-flex: 0 0 100%; flex: 0 0 100%; max-width: 100%; } .order-xl-first { -ms-flex-order: -1; order: -1; } .order-xl-1 { -ms-flex-order: 1; order: 1; } .order-xl-2 { -ms-flex-order: 2; order: 2; } .order-xl-3 { -ms-flex-order: 3; order: 3; } .order-xl-4 { -ms-flex-order: 4; order: 4; } .order-xl-5 { -ms-flex-order: 5; order: 5; } .order-xl-6 { -ms-flex-order: 6; order: 6; } .order-xl-7 { -ms-flex-order: 7; order: 7; } .order-xl-8 { -ms-flex-order: 8; order: 8; } .order-xl-9 { -ms-flex-order: 9; order: 9; } .order-xl-10 { -ms-flex-order: 10; order: 10; } .order-xl-11 { -ms-flex-order: 11; order: 11; } .order-xl-12 { -ms-flex-order: 12; order: 12; } .offset-xl-0 { margin-left: 0; } .offset-xl-1 { margin-left: 8.333333%; } .offset-xl-2 { margin-left: 16.666667%; } .offset-xl-3 { margin-left: 25%; } .offset-xl-4 { margin-left: 33.333333%; } .offset-xl-5 { margin-left: 41.666667%; } .offset-xl-6 { margin-left: 50%; } .offset-xl-7 { margin-left: 58.333333%; } .offset-xl-8 { margin-left: 66.666667%; } .offset-xl-9 { margin-left: 75%; } .offset-xl-10 { margin-left: 83.333333%; } .offset-xl-11 { margin-left: 91.666667%; } } .flex-row { -ms-flex-direction: row !important; flex-direction: row !important; } .flex-column { -ms-flex-direction: column !important; flex-direction: column !important; } .flex-row-reverse { -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-column-reverse { -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-wrap { -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-nowrap { -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-wrap-reverse { -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-start { -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-end { -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-center { -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-between { -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-around { -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-start { -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-end { -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-center { -ms-flex-align: center !important; align-items: center !important; } .align-items-baseline { -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-stretch { -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-start { -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-end { -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-center { -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-between { -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-around { -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-stretch { -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-auto { -ms-flex-item-align: auto !important; align-self: auto !important; } .align-self-start { -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-end { -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-center { -ms-flex-item-align: center !important; align-self: center !important; } .align-self-baseline { -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-stretch { -ms-flex-item-align: stretch !important; align-self: stretch !important; } @media (min-width: 576px) { .flex-sm-row { -ms-flex-direction: row !important; flex-direction: row !important; } .flex-sm-column { -ms-flex-direction: column !important; flex-direction: column !important; } .flex-sm-row-reverse { -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-sm-column-reverse { -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-sm-wrap { -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-sm-nowrap { -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-sm-wrap-reverse { -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-sm-start { -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-sm-end { -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-sm-center { -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-sm-between { -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-sm-around { -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-sm-start { -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-sm-end { -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-sm-center { -ms-flex-align: center !important; align-items: center !important; } .align-items-sm-baseline { -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-sm-stretch { -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-sm-start { -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-sm-end { -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-sm-center { -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-sm-between { -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-sm-around { -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-sm-stretch { -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-sm-auto { -ms-flex-item-align: auto !important; align-self: auto !important; } .align-self-sm-start { -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-sm-end { -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-sm-center { -ms-flex-item-align: center !important; align-self: center !important; } .align-self-sm-baseline { -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-sm-stretch { -ms-flex-item-align: stretch !important; align-self: stretch !important; } } @media (min-width: 768px) { .flex-md-row { -ms-flex-direction: row !important; flex-direction: row !important; } .flex-md-column { -ms-flex-direction: column !important; flex-direction: column !important; } .flex-md-row-reverse { -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-md-column-reverse { -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-md-wrap { -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-md-nowrap { -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-md-wrap-reverse { -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-md-start { -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-md-end { -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-md-center { -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-md-between { -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-md-around { -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-md-start { -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-md-end { -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-md-center { -ms-flex-align: center !important; align-items: center !important; } .align-items-md-baseline { -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-md-stretch { -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-md-start { -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-md-end { -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-md-center { -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-md-between { -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-md-around { -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-md-stretch { -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-md-auto { -ms-flex-item-align: auto !important; align-self: auto !important; } .align-self-md-start { -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-md-end { -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-md-center { -ms-flex-item-align: center !important; align-self: center !important; } .align-self-md-baseline { -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-md-stretch { -ms-flex-item-align: stretch !important; align-self: stretch !important; } } @media (min-width: 992px) { .flex-lg-row { -ms-flex-direction: row !important; flex-direction: row !important; } .flex-lg-column { -ms-flex-direction: column !important; flex-direction: column !important; } .flex-lg-row-reverse { -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-lg-column-reverse { -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-lg-wrap { -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-lg-nowrap { -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-lg-wrap-reverse { -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-lg-start { -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-lg-end { -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-lg-center { -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-lg-between { -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-lg-around { -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-lg-start { -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-lg-end { -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-lg-center { -ms-flex-align: center !important; align-items: center !important; } .align-items-lg-baseline { -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-lg-stretch { -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-lg-start { -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-lg-end { -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-lg-center { -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-lg-between { -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-lg-around { -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-lg-stretch { -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-lg-auto { -ms-flex-item-align: auto !important; align-self: auto !important; } .align-self-lg-start { -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-lg-end { -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-lg-center { -ms-flex-item-align: center !important; align-self: center !important; } .align-self-lg-baseline { -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-lg-stretch { -ms-flex-item-align: stretch !important; align-self: stretch !important; } } @media (min-width: 1200px) { .flex-xl-row { -ms-flex-direction: row !important; flex-direction: row !important; } .flex-xl-column { -ms-flex-direction: column !important; flex-direction: column !important; } .flex-xl-row-reverse { -ms-flex-direction: row-reverse !important; flex-direction: row-reverse !important; } .flex-xl-column-reverse { -ms-flex-direction: column-reverse !important; flex-direction: column-reverse !important; } .flex-xl-wrap { -ms-flex-wrap: wrap !important; flex-wrap: wrap !important; } .flex-xl-nowrap { -ms-flex-wrap: nowrap !important; flex-wrap: nowrap !important; } .flex-xl-wrap-reverse { -ms-flex-wrap: wrap-reverse !important; flex-wrap: wrap-reverse !important; } .justify-content-xl-start { -ms-flex-pack: start !important; justify-content: flex-start !important; } .justify-content-xl-end { -ms-flex-pack: end !important; justify-content: flex-end !important; } .justify-content-xl-center { -ms-flex-pack: center !important; justify-content: center !important; } .justify-content-xl-between { -ms-flex-pack: justify !important; justify-content: space-between !important; } .justify-content-xl-around { -ms-flex-pack: distribute !important; justify-content: space-around !important; } .align-items-xl-start { -ms-flex-align: start !important; align-items: flex-start !important; } .align-items-xl-end { -ms-flex-align: end !important; align-items: flex-end !important; } .align-items-xl-center { -ms-flex-align: center !important; align-items: center !important; } .align-items-xl-baseline { -ms-flex-align: baseline !important; align-items: baseline !important; } .align-items-xl-stretch { -ms-flex-align: stretch !important; align-items: stretch !important; } .align-content-xl-start { -ms-flex-line-pack: start !important; align-content: flex-start !important; } .align-content-xl-end { -ms-flex-line-pack: end !important; align-content: flex-end !important; } .align-content-xl-center { -ms-flex-line-pack: center !important; align-content: center !important; } .align-content-xl-between { -ms-flex-line-pack: justify !important; align-content: space-between !important; } .align-content-xl-around { -ms-flex-line-pack: distribute !important; align-content: space-around !important; } .align-content-xl-stretch { -ms-flex-line-pack: stretch !important; align-content: stretch !important; } .align-self-xl-auto { -ms-flex-item-align: auto !important; align-self: auto !important; } .align-self-xl-start { -ms-flex-item-align: start !important; align-self: flex-start !important; } .align-self-xl-end { -ms-flex-item-align: end !important; align-self: flex-end !important; } .align-self-xl-center { -ms-flex-item-align: center !important; align-self: center !important; } .align-self-xl-baseline { -ms-flex-item-align: baseline !important; align-self: baseline !important; } .align-self-xl-stretch { -ms-flex-item-align: stretch !important; align-self: stretch !important; } } /*# sourceMappingURL=bootstrap-grid.css.map */
{ "pile_set_name": "Github" }
/** * 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.pulsar.io.solr; import lombok.Data; import lombok.extern.slf4j.Slf4j; import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.schema.GenericRecord; import org.apache.pulsar.client.api.schema.GenericSchema; import org.apache.pulsar.client.impl.MessageImpl; import org.apache.pulsar.client.impl.schema.AutoConsumeSchema; import org.apache.pulsar.client.impl.schema.AvroSchema; import org.apache.pulsar.client.impl.schema.generic.GenericAvroSchema; import org.apache.pulsar.client.impl.schema.generic.GenericSchemaImpl; import org.apache.pulsar.functions.api.Record; import org.apache.pulsar.functions.source.PulsarRecord; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.util.HashMap; import java.util.Map; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * solr Sink test */ @Slf4j public class SolrGenericRecordSinkTest { private SolrServerUtil solrServerUtil; private Message<GenericRecord> message; /** * A Simple class to test solr class */ @Data public static class Foo { private String field1; private String field2; } @BeforeMethod public void setUp() throws Exception { solrServerUtil = new SolrServerUtil(8983); solrServerUtil.startStandaloneSolr(); } @AfterMethod public void tearDown() throws Exception { solrServerUtil.stopStandaloneSolr(); } @Test public void TestOpenAndWriteSink() throws Exception { message = mock(MessageImpl.class); Map<String, Object> configs = new HashMap<>(); configs.put("solrUrl", "http://localhost:8983/solr"); configs.put("solrMode", "Standalone"); configs.put("solrCollection", "techproducts"); configs.put("solrCommitWithinMs", "100"); configs.put("username", ""); configs.put("password", ""); GenericSchema<GenericRecord> genericAvroSchema; SolrGenericRecordSink sink = new SolrGenericRecordSink(); // prepare a foo Record Foo obj = new Foo(); obj.setField1("FakeFiled1"); obj.setField2("FakeFiled1"); AvroSchema<Foo> schema = AvroSchema.of(Foo.class); byte[] bytes = schema.encode(obj); AutoConsumeSchema autoConsumeSchema = new AutoConsumeSchema(); autoConsumeSchema.setSchema(GenericSchemaImpl.of(schema.getSchemaInfo())); Record<GenericRecord> record = PulsarRecord.<GenericRecord>builder() .message(message) .topicName("fake_topic_name") .build(); genericAvroSchema = new GenericAvroSchema(schema.getSchemaInfo()); when(message.getValue()) .thenReturn(genericAvroSchema.decode(bytes)); log.info("foo:{}, Message.getValue: {}, record.getValue: {}", obj.toString(), message.getValue().toString(), record.getValue().toString()); // open should success sink.open(configs, null); } }
{ "pile_set_name": "Github" }
/*! // Contents // ------------------------------------------------ 1. Mixins 2. Helper classes & resets 3. Loader 4. Colours 5. Typography 6. Spacing 7. Buttons 8. Navigation 9. Slider, Dividers 10. Speakers & Topics 11. Schedule 12. Galleries 13. Pricing & FAQ 14. Subscribe 15. Contact 16. Forms 17. Footers // --------------------------------------------------*/ /*! // 1. Useful Mixins // --------------------------------------------------*/ .vertical-align { position: relative; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); } .vertical-align-cancel { top: 0px; -webkit-transform: translateY(0px); -ms-transform: translateY(0px); transform: translateY(0px); } .preserve-3d { -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; transform-style: preserve-3d; } .transition-100 { transition: all 0.1s ease-out; -webkit-transition: all 0.1s ease-out; -moz-transition: all 0.1s ease-out; } .transition-300 { transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .transition-700 { transition: all 0.7s ease-out; -webkit-transition: all 0.7s ease-out; -moz-transition: all 0.7s ease-out; } .overlay:before { background-color: #333333; opacity: 0.5; position: absolute; content: ''; width: 100%; height: 100%; z-index: 1; top: 0px; } .overlay .container { position: relative; z-index: 2; } /*! // 2. Helper Classes & Resets // --------------------------------------------------*/ .go-right { right: 0px; } .go-left { left: 0px; } img { max-width: 100%; } .main-container { transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .main-container, .footer-container, .nav-container, nav { max-width: 1600px; margin: 0px auto; } .boxed-layout .main-container, .boxed-layout .nav-container, .boxed-layout nav, .boxed-layout .footer-container { max-width: 1366px; left: 0; right: 0; margin: 0 auto; } .no-loader .loader { display: none !important; } /*! // 3. Loader // --------------------------------------------------*/ .loader { position: fixed; top: 0px; left: 0px; width: 100%; height: 100%; z-index: 99; background: #fff; -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; transform-style: preserve-3d; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; opacity: 1; } .strip-holder { top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); left: 50%; margin-left: -50px; position: relative; } .strip-1, .strip-2, .strip-3 { width: 20px; height: 20px; background: #7300c2; position: relative; -webkit-animation: stripMove 2s ease infinite alternate; animation: stripMove 2s ease infinite alternate; -moz-animation: stripMove 2s ease infinite alternate; } .strip-2 { -webkit-animation-duration: 2.1s; animation-duration: 2.1s; background-color: #a829ff; } .strip-3 { -webkit-animation-duration: 2.2s; animation-duration: 2.2s; background-color: #d18fff; } @-webkit-keyframes stripMove { 0% { transform: translate3d(0px, 0px, 0px); -webkit-transform: translate3d(0px, 0px, 0px); -moz-transform: translate3d(0px, 0px, 0px); } 50% { transform: translate3d(0px, 0px, 0px); -webkit-transform: translate3d(0px, 0px, 0px); -moz-transform: translate3d(0px, 0px, 0px); transform: scale(4, 1); -webkit-transform: scale(4, 1); -moz-transform: scale(4, 1); } 100% { transform: translate3d(-50px, 0px, 0px); -webkit-transform: translate3d(-50px, 0px, 0px); -moz-transform: translate3d(-50px, 0px, 0px); } } @-moz-keyframes stripMove { 0% { transform: translate3d(-50px, 0px, 0px); -webkit-transform: translate3d(-50px, 0px, 0px); -moz-transform: translate3d(-50px, 0px, 0px); } 50% { transform: translate3d(0px, 0px, 0px); -webkit-transform: translate3d(0px, 0px, 0px); -moz-transform: translate3d(0px, 0px, 0px); transform: scale(4, 1); -webkit-transform: scale(4, 1); -moz-transform: scale(4, 1); } 100% { transform: translate3d(50px, 0px, 0px); -webkit-transform: translate3d(50px, 0px, 0px); -moz-transform: translate3d(50px, 0px, 0px); } } @keyframes stripMove { 0% { transform: translate3d(-50px, 0px, 0px); -webkit-transform: translate3d(-50px, 0px, 0px); -moz-transform: translate3d(-50px, 0px, 0px); } 50% { transform: translate3d(0px, 0px, 0px); -webkit-transform: translate3d(0px, 0px, 0px); -moz-transform: translate3d(0px, 0px, 0px); transform: scale(4, 1); -webkit-transform: scale(4, 1); -moz-transform: scale(4, 1); } 100% { transform: translate3d(50px, 0px, 0px); -webkit-transform: translate3d(50px, 0px, 0px); -moz-transform: translate3d(50px, 0px, 0px); } } .main-container { transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } nav { transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .show-content { opacity: 1 !important; } .hide-loader { opacity: 0 !important; } /*! // 4. Colours // --------------------------------------------------*/ .background-dark { background-color: #333333 !important; } .color-heading { color: #333333; } /*! // 5. Typography // --------------------------------------------------*/ .text-white { color: #fff; } body { font-family: 'Open Sans', "Helvetica Neue", Helvetica, Arial, sans-serif; font-smoothing: antialiased; -webkit-font-smoothing: antialiased; color: #777777; font-size: 14px; line-height: 24px; background: #eee; -moz-osx-font-smoothing: grayscale; } h1, h2, h3, h4, h5, h6 { font-family: 'Open Sans', "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 300; margin: 0px; color: #333333; } h1 { font-size: 30px; line-height: 36px; margin-bottom: 42px; } h3 { font-size: 20px; line-height: 28px; } .large-h1 { font-size: 42px; line-height: 48px; font-weight: 300; } p { font-size: 14px; line-height: 24px; } p:last-child { margin-bottom: 0px; } p.lead { font-size: 16px; line-height: 30px; font-weight: 400; } span.lead { font-weight: 400; } .uppercase { text-transform: uppercase; letter-spacing: 1px; display: inline-block; margin-right: -1px; } strong { font-weight: 600; } ul { list-style: none; margin: 0px; padding: 0px; } @media all and (max-width: 767px) { h1 { font-size: 24px; line-height: 28px; margin-bottom: 36px; } h2 { font-size: 20px; line-height: 26px; } .large-h1 { font-size: 24px; line-height: 28px; } p { font-size: 13px; line-height: 22px; } p.lead { font-size: 15px; line-height: 26px; } } /*! // Spacing Standards // --------------------------------------------------*/ section { padding: 72px 0px; background: #fff; } .duplicatable-content { padding-bottom: 36px; } /*! // 6. Buttons // --------------------------------------------------*/ a:hover { text-decoration: none; } h1 a, span a, p a, .text-link a { font-weight: 600; color: #fff; display: inline-block; border-bottom: 4px solid #fff; padding-bottom: 6px; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } span a, p a, .text-link a { padding-bottom: 4px; border-bottom: 3px solid #fff; } span a:hover { color: #fff; } p a, .text-link a { color: #7300c2 !important; border-color: #7300c2; padding-bottom: 2px; } p a, .text-link a:hover { color: #333333; } .btn { min-width: 180px; border-radius: 25px; background: #7300c2; text-align: center; padding: 13px 0px 14px 0px; color: #fff; font-size: 15px; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; font-weight: 600; line-height: 1; } .btn:hover { color: #fff; background: #6400a9; } .btn-hollow { background: none; border: 2px solid #7300c2; color: #7300c2; } .btn-hollow:hover { background: #7300c2; } .btn-white { background: #fff; color: #7300c2; } .btn-white:hover { background: #fff; color: #55008f; } .btn-hollow.btn-white { background: none; border-color: #fff; color: #fff; } .btn-hollow.btn-white:hover { background: #fff; color: #7300c2; } .btn-lg { padding: 20px 0px 21px 0px; text-transform: uppercase; min-width: 230px; border-radius: 35px; } /*! // Backgrounds & Parallax // --------------------------------------------------*/ .background-image-holder { position: absolute; width: 100%; height: 130%; top: -10%; background-size: cover !important; background-position: 50% 50% !important; } .background-image-holder img { display: none; } .image-holder { position: relative; overflow: hidden; } /*! // 7. Navigation // --------------------------------------------------*/ nav .logo { max-height: 45px; max-width: 110px; position: absolute; top: -6px; opacity: 1; } nav .text-right { position: relative; } nav .container { transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .overlay-nav { position: fixed; top: 0px; z-index: 10; width: 100%; padding-top: 24px; line-height: 1; background: none; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .overlay-nav .logo-dark { opacity: 0; } .overlay-nav.sticky-nav .logo-light { opacity: 0; } .overlay-nav.sticky-nav .logo-dark { opacity: 1; } .bottom-border { position: absolute; bottom: 2px; width: 100%; height: 2px; background: rgba(255, 255, 255, 0.3); } .sidebar-menu .bottom-border { position: relative; bottom: 0px; background: rgba(255, 255, 255, 0.2); display: block !important; } .menu { display: inline-block; text-align: left; line-height: 1; } .menu li { float: left; margin-right: 32px; font-size: 11px; text-transform: uppercase; letter-spacing: 1px; font-weight: 600; position: relative; top: 4px; } .menu li:last-child { margin-right: 0px; } .menu li:nth-las-child(2) { margin-right: 12px; } .menu li a { color: #fff; display: inline-block; padding-bottom: 24px; border-bottom: 2px solid rgba(0, 0, 0, 0); transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .menu li a:hover { border-bottom: 2px solid #fff; } .nav-dropdown { position: absolute; z-index: -1; display: none; background: rgba(255, 255, 255, 0.9); min-width: 200px; overflow: hidden; margin-top: -2px; } .nav-dropdown li:first-child { margin-top: 12px; } .nav-dropdown li { opacity: 0; margin-right: 0px; float: none; margin-bottom: 18px; } .nav-dropdown li a { padding-bottom: 0px; padding-left: 24px; color: #333333; } .nav-dropdown li a:hover { border-color: rgba(0, 0, 0, 0); } .has-dropdown:hover .nav-dropdown { z-index: 10; max-height: 300px; display: block; } .has-dropdown:hover .nav-dropdown li { opacity: 1; } .has-dropdown a { padding-left: 18px; } .has-dropdown:before { display: inline-block; font-family: 'Pe-icon-7-stroke'; speak: none; font-style: normal; font-weight: normal; font-variant: normal; text-transform: none; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; content: "\e688"; color: #fff; font-size: 24px; position: absolute; top: -6px; } .menu .social-link { font-size: 14px; top: 0px !important; margin-right: 18px !important; } .menu .social-link:nth-last-child(2) { margin-right: 18px; } .sticky-nav { background: rgba(255, 255, 255, 0.9); } .sticky-nav .menu li a { color: #333333; } .sticky-nav .bottom-border { display: none; } .sticky-nav .menu li a:hover { border-color: rgba(0, 0, 0, 0); } .sticky-nav .sidebar-menu-toggle, .sticky-nav .mobile-menu-toggle { color: #333333; } .sticky-nav .nav-dropdown { background: rgba(255, 255, 255, 0.9); } .sticky-nav .has-dropdown:before { color: #333333; } .sidebar-menu-toggle, .mobile-menu-toggle { position: absolute; color: #fff; font-size: 32px; right: 0px; top: -7px; cursor: pointer; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .mobile-menu-toggle { display: none; } .sidebar-menu, .instagram-sidebar { position: fixed; right: 0px; top: 0px; width: 300px; height: 100%; background: #333333; transform: translate3d(300px, 0px, 0px); -webkit-transform: translate3d(300px, 0px, 0px); -moz-transform: translate3d(300px, 0px, 0px); transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .show-sidebar { transform: translate3d(0px, 0px, 0px); -webkit-transform: translate3d(0px, 0px, 0px); -moz-transform: translate3d(0px, 0px, 0px); } .reveal-sidebar { transform: translate3d(-300px, 0px, 0px); -webkit-transform: translate3d(-300px, 0px, 0px); -moz-transform: translate3d(-300px, 0px, 0px); } .sidebar-content { padding: 0px 24px; margin-top: 24px; } .widget { margin-bottom: 24px; } .widget .title { font-size: 16px; font-weight: 600; display: inline-block; margin-bottom: 12px; } .widget .menu li { float: none; margin-bottom: 12px; } .widget .menu li a { padding-bottom: 0px; color: #fff !important; font-size: 12px; } .widget .menu li a:hover { border-color: rgba(0, 0, 0, 0); } .widget .menu .social-link { display: none; } .widget .social-profiles li { margin-right: 24px; } .widget .social-profiles li a { color: #fff; } .instagram-toggle { cursor: pointer; } .instagram-toggle-init { pointer-events: none; } .instagram-sidebar li { width: 100%; height: 250px; } .instagram-sidebar { overflow-y: auto; } .sidebar-content .copy-text { position: absolute; bottom: 32px; color: rgba(255, 255, 255, 0.5); font-size: 12px; } .text-panel { background: #474747; padding: 18px; } .relative-nav { position: relative; padding-top: 28px; background: #fff; } .relative-nav .menu li a { color: #333333; } .relative-nav .has-dropdown:before { color: #333333; } .relative-nav .nav-dropdown { background: rgba(53, 53, 53, 0.8); } .relative-nav .has-dropdown li a { color: #fff; } .relative-nav .sidebar-menu-toggle { color: #333333; } .relative-nav .logo-light { opacity: 0 !important; } .relative-nav .logo-dark { opacity: 1 !important; } .relative-nav .logo { top: -4px !important; } .sidebar-menu .logo { max-width: 110px; position: relative; top: 21px !important; margin-bottom: 32px; left: 24px; } @media all and (max-width: 768px) { nav { max-height: 67px; overflow: hidden; background: rgba(255, 255, 255, 0.9) !important; } nav .menu li { float: none; margin-bottom: 24px; } nav .menu li a { color: #333333 !important; padding-bottom: 0px; } nav .logo { max-width: 90px; top: -2px; } nav .logo-dark { opacity: 1 !important; } nav .logo-light { opacity: 0 !important; } nav .menu { width: 100%; display: block; margin-top: 67px; margin-right: 0px; } nav .social-link { float: left !important; } .sidebar-menu-toggle { display: none; } .mobile-menu-toggle { display: block; position: fixed; top: 17px; right: 24px; color: #333333 !important; } .open-menu { max-height: 800px !important; } .nav-dropdown { position: relative; display: none; } .has-dropdown:hover .nav-dropdown { display: block; } .has-dropdown:before { color: #333333; } } /*! // 8. Sliders & Dividers & Headers // --------------------------------------------------*/ .hero-slider { padding: 0px; position: relative; overflow: hidden; background: #2b2b2b; } .hero-slider .slides li { height: 780px; position: relative; overflow: hidden; -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; transform-style: preserve-3d; } .hero-slider .slides li:before { background-color: #333333; opacity: 0.4; position: absolute; content: ''; width: 100%; height: 100%; z-index: 1; top: 0px; } .hero-slider .container { position: relative; top: 50%; -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); transform: translateY(-50%); z-index: 2; } .hero-slider h1 { margin-bottom: 42px; } .hero-slider .btn-hollow { color: #fff; border-color: #fff; margin-left: 16px; } .hero-slider .btn-hollow:hover { background: #fff; color: #7300c2; } @media all and (max-width: 767px) { .hero-slider .btn-hollow { display: none; } } .register-header form.register { padding-top: 0px; background: rgba(0, 0, 0, 0.4); padding: 24px; } .register-header form input { width: 100% !important; } .register-header form.register span { color: #fff; } .register-header .logo, .hero-slide .logo { max-width: 150px; display: block; margin-bottom: 12px; } .register-header h1 { margin-bottom: 24px !important; } @media all and (max-width: 768px) { .register-header form.register .form-name, .register-header form.register .form-email { max-width: 100%; width: 100%; } } @media all and (min-width: 321px) and (max-width: 767px) and (orientation: landscape) { .register-header form.register .form-name, .register-header form.register .form-email { width: 50%; } } @media all and (max-width: 767px) { .hero-slide .logo { max-width: 100px; } .register-header .logo { display: none; } .register-header h1 { display: none; } .register-header form h1 { display: block; } .register-header span.lead { display: none; } .register-header input, .register-header .select-holder { max-width: 100% !important; } .hero-slider h1 { margin-bottom: 18px; } } .testimonials-slider { position: relative; margin-bottom: 48px; } .testimonials-slider .flex-control-nav a { background: rgba(0, 0, 0, 0.3); } .testimonials-slider .flex-control-nav a.flex-active { background: rgba(0, 0, 0, 0.8); } .testimonials-slider .flex-control-nav a:hover { background: rgba(0, 0, 0, 0.8); } .testimonials-slider .flex-control-nav { bottom: -48px; text-align: left; } .primary-overlay:before { background-color: #7300c2; opacity: 0.8; position: absolute; content: ''; width: 100%; height: 100%; z-index: 1; top: 0px; background-color: #7300c2 !important; } .strip-divider { padding: 216px 0px; position: relative; overflow: hidden; } .strip-divider .container { z-index: 2; position: relative; } .strip-divider h1 { margin: 0px; font-size: 36px; line-height: 48px; } .strip-divider a:hover { color: #fff !important; } @media all and (max-width: 767px) { .strip-divider { padding: 72px 0px; } } .countdown-divider { padding: 144px 0px; } .countdown-divider img, .countdown-header img, .video-header img { max-width: 300px; display: inline-block; margin-bottom: 12px; } .countdown-header h1 { margin-bottom: 0px; } .countdown-header:before { opacity: 0.8 !important; } .video-header:before { opacity: 0.5 !important; background: #000 !important; } .video-header .uppercase, .countdown-header .uppercase { display: block; font-weight: 600; margin-bottom: 24px; } @media all and (max-width: 768px) { .countdown-header img, .countdown-divider img, .video-header img { max-width: 150px; } } .countdown { text-align: center; margin-top: 72px; } .countdown-row { color: #fff; font-size: 80px; font-weight: 300; } .countdown-section { width: 20%; display: inline-block; } .countdown-amount { display: inline-block; margin-bottom: 48px; } .countdown-period { display: block; font-size: 24px; } .section-header { position: relative; overflow: hidden; height: 450px; } .section-header h1 { font-size: 32px; } .section-header.overlay:before { opacity: 0.2; } .section-header i { font-size: 40px; color: #fff; margin: 0px 24px 12px 0px; } .section-header i:last-of-type { margin-right: 0px; } @media all and (max-width: 767px) { .countdown { margin-top: 48px; } .countdown-row { font-size: 36px; } .countdown-period { font-size: 16px; } } .video-wrapper { position: absolute; width: 100%; height: 100%; top: 0px; left: 0px; z-index: 0; } .video-wrapper video { width: 100%; } @media all and (max-width: 1390px) { .video-wrapper video { width: 110%; } } @media all and (max-width: 1260px) { .video-wrapper video { width: 120%; } } @media all and (max-width: 1160px) { .video-wrapper video { width: 130%; } } @media all and (max-width: 1024px) { .video-wrapper { display: none; } } .call-to-action { padding: 144px 0px; } .call-to-action .uppercase { display: block; width: 100%; text-align: center; margin-bottom: 32px; } .call-to-action h1 { margin-bottom: 32px; } .call-to-action .btn { margin-bottom: 40px; } .call-to-action a i { display: inline-block; width: 60px; height: 60px; border-radius: 50%; color: #fff; margin-right: 12px; font-size: 24px; line-height: 60px; } .call-to-action .social_facebook { background-color: #3b5998; } .call-to-action .social_twitter { background-color: #00aced; } .call-to-action a:last-of-type i { margin-right: 0px; } @media all and (max-width: 768px) { .call-to-action { padding: 72px 0px; } } /*! // 9. Image with text // --------------------------------------------------*/ .image-with-text { overflow: hidden; position: relative; height: 600px; } .image-with-text h1 { margin-bottom: 24px; } .side-image { padding: 0px; position: absolute; top: 0px; height: 100%; } @media all and (max-width: 767px) { .image-with-text { height: auto; padding: 72px 0px; } .image-with-text .vertical-align { top: 0px; -webkit-transform: translateY(0px); -ms-transform: translateY(0px); transform: translateY(0px); } } /*! // Promo Blocks // --------------------------------------------------*/ .color-blocks { position: relative; overflow: hidden; color: #fff; } .color-block { position: absolute; top: 0px; height: 100%; padding: 0px; color: #fff; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .color-blocks h1, .color-blocks h2, .color-blocks h3, .color-blocks h4, .color-blocks h5, .color-blocks h6 { color: #fff; } .color-blocks h1 { margin-bottom: 12px; } .color-blocks a { color: #fff; pointer-events: auto; } .color-blocks a:hover i { transform: rotateZ(-10deg); } .color-blocks i, .contained-promo i { color: #7300c2; font-size: 70px; display: inline-block; border: 2px solid #fff; border-radius: 50%; width: 120px; height: 120px; line-height: 117px; background: #fff; text-align: center; transition: all 0.1s ease-out; -webkit-transition: all 0.1s ease-out; -moz-transition: all 0.1s ease-out; } .block-left { background-color: #7300c2; } .block-right { background-color: #5b0099; right: 0px; } @media all and (max-width: 768px) { .block-content { margin-bottom: 144px; overflow: hidden; display: block; } .block-content:last-of-type { margin-bottom: 0px; } .color-block { height: 50%; width: 100%; } .block-right { top: 50%; } } @media all and (max-width: 767px) { .block-content i { margin-bottom: 30px; } } /*! // 10. Speakers & Topics // --------------------------------------------------*/ .speakers-row { padding: 0px 15px; } .speaker-column { padding: 0px; } .speaker { position: relative; overflow: hidden; } .speaker, .topic { margin-bottom: 36px; } .speaker .hover-state { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2; opacity: 0; background: rgba(0, 0, 0, 0.5); transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .speaker .image-holder { margin-bottom: 12px; } .speaker span { display: block; font-size: 16px; } .speaker-name { color: #333333; } .speaker .social-links { width: 100%; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; transform: translate3d(0px, -200px, 0px); -webkit-transform: translate3d(0px, -200px, 0px); -moz-transform: translate3d(0px, -200px, 0px); } .speaker .social-links a { color: #fff; font-size: 24px; display: inline-block; margin-left: 6px; } .speaker .social-links a:last-child { margin-right: 0px; } .speaker .image-holder:hover .hover-state { opacity: 1; } .speaker .image-holder:hover .hover-state .social-links { transform: translate3d(0px, 0px, 0px); -webkit-transform: translate3d(0px, 0px, 0px); -moz-transform: translate3d(0px, 0px, 0px); } .speaker-with-bio { overflow: hidden; margin-bottom: 36px; } .speaker-with-bio .speaker { width: 50%; float: left; margin-bottom: 0px; } .speaker-with-bio .speaker-description { width: 50%; float: left; padding-left: 30px; } .speaker-description span { display: inline-block; margin-bottom: 18px; font-weight: 600; } @media all and (max-width: 767px) { .speaker-with-bio .speaker { width: 100%; } .speaker-with-bio .speaker-description { width: 100%; padding-left: 0px; } } .topics { position: relative; overflow: hidden; } .topics .container { position: relative; z-index: 2; } .topics.overlay .ruled-list li { border-color: rgba(255, 255, 255, 0.5); } .topics.overlay .topic i { color: #fff; } .topic h3 { margin-bottom: 18px; } .topic p.lead { margin-bottom: 32px; } .topic i { font-size: 60px; color: #7300c2; display: inline-block; margin-bottom: 32px; } @media all and (max-width: 767px) { .topic h3 { display: inline-block; position: relative; bottom: 18px; left: 12px; } .topic i { margin-bottom: 12px; } } .ruled-list li { border-top: 1px dotted rgba(0, 0, 0, 0.3); padding: 12px 0px; font-size: 16px; } @media all and (min-width: 321px) and (max-width: 767px) and (orientation: landscape) { .speakers-row .col-sm-6 { width: 50%; float: left !important; } } /*! // 11. Schedule // --------------------------------------------------*/ .inline-video { background: #f5f5f5; } .inline-video iframe { width: 100%; height: 300px; border: none; } .inline-video .btn { min-width: 150px; margin-top: 32px; margin-right: 16px; } @media all and (max-width: 768px) { .inline-video iframe { height: 350px; margin-top: 42px; } } @media all and (max-width: 767px) { .inline-video iframe { height: 200px; margin-top: 30px; } .inline-video .btn { margin-top: 18px; } } @media all and (min-width: 321px) and (max-width: 767px) and (orientation: landscape) { .inline-video iframe { height: 250px; } } .embedded-video-holder p { display: none; } .schedule-overview { border: 2px solid rgba(0, 0, 0, 0.2); margin-bottom: 36px; } .schedule-overview li { padding: 24px; position: relative; cursor: pointer; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .schedule-overview li:first-child .top { display: none; } .schedule-overview li:last-child .bottom { display: none; } .schedule-title span { display: block; font-size: 16px; } .schedule-title .title { color: #333333; } .schedule-text { max-height: 0px; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; opacity: 0; } .schedule-overview li:hover { background-color: #f5f5f5; } .schedule-overview li:hover .schedule-text { max-height: 300px; opacity: 1; padding-top: 18px; } .schedule-overview li:hover .top, .schedule-overview li:hover .bottom, .schedule-overview li:hover .middle { border-color: rgba(0, 0, 0, 0.4); } .schedule-overview li:hover .middle { background: #333333; } .schedule-with-text .btn, .contained-gallery .btn { margin-top: 24px; margin-right: 12px; } .schedule-with-text .schedule-overview li { padding-right: 48px; } @media all and (max-width: 1024px) { .schedule-overview li { padding-right: 48px; } } @media all and (max-width: 767px) { .schedule-with-text .btn, .contained-gallery .btn { margin-bottom: 32px; } } .marker-pin { position: absolute; right: 32px; top: 0px; height: 100%; } .marker-pin .top, .marker-pin .bottom { height: 50%; width: 2px; border-left: 2px solid rgba(0, 0, 0, 0.2); position: absolute; z-index: 1; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .marker-pin .top { top: 0px; } .marker-pin .bottom { bottom: 0px; } .marker-pin .middle { width: 18px; height: 18px; border: 2px solid rgba(0, 0, 0, 0.2); background: #fff; border-radius: 50%; position: absolute; right: -10px; top: 50%; margin-top: -9px; z-index: 2; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } /*! // 12. Galleries // --------------------------------------------------*/ .instagram, .lightbox-gallery { position: relative; padding: 216px 0px; } .gallery-header .logo { max-width: 400px; display: block; margin: 0px auto; margin-bottom: 12px; } @media screen and (max-width: 768px) { .gallery-header .logo { max-width: 200px; } .gallery-header h1 { font-size: 24px !important; line-height: 32px !important; } } .instagram, .lightbox-gallery { overflow: hidden; background: #000 !important; } .instagram ul, .lightbox-gallery ul { overflow: hidden; position: absolute; width: 100%; height: 100%; top: 0px; } .instagram li, .lightbox-gallery li { float: left; width: 20%; height: 50%; position: relative; cursor: pointer; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; overflow: hidden; background-size: cover !important; opacity: 0.5; } .instagram li:hover, .lightbox-gallery li:hover { opacity: 1 !important; } .instagram .container, .lightbox-gallery .container { position: relative; z-index: 3; } .instagram i, .lightbox-gallery i { font-size: 48px; display: inline-block; margin-bottom: 16px; } .instagram h1, .lightbox-gallery h1 { font-size: 42px; line-height: 48px; font-weight: 300; margin-bottom: 16px; } @media all and (max-width: 1200px) { .instagram li:nth-child(n+9), .lightbox-gallery li:nth-child(n+9) { display: none; } .instagram li, .lightbox-gallery li { width: 25%; } } @media all and (max-width: 900px) { .instagram li:nth-child(n+7), .lightbox-gallery li:nth-child(n+7) { display: none; } .instagram li, .lightbox-gallery li { width: 33.333333%; } } @media all and (max-width: 767px) { .instagram, .lightbox-gallery { padding: 144px 0px; } .instagram li:nth-child(n+5), .lightbox-gallery li:nth-child(n+5) { display: none; } .instagram li, .lightbox-gallery li { width: 50%; } } .testimonials { background: #f5f5f5; } .contained-gallery .instagram, .contained-gallery .lightbox-gallery { padding: 185px 0px; } .contained-gallery .instagram li:nth-child(n+9), .contained-gallery .lightbox-gallery li:nth-child(n+9) { display: none; } .contained-gallery .instagram li, .contained-gallery .lightbox-gallery li { width: 25%; opacity: 0.7; } @media all and (max-width: 1024px) { .contained-gallery .instagram li:nth-child(n+7) { display: none; } .contained-gallery .lightbox-gallery li:nth-child(n+7) { display: none; } .contained-gallery .instagram li, .contained-gallery .lightbox-gallery li { width: 33.33333%; } .contained-gallery .instagram, .contained-gallery .lightbox-gallery { padding: 200px 0px; } } @media all and (max-width: 768px) { .contained-gallery .instagram, .contained-gallery .lightbox-gallery { margin-bottom: 32px; } .contained-gallery .btn { margin-bottom: 0px; } .contained-gallery .instagram li:nth-child(n+5), .contained-gallery .lightbox-gallery li:nth-child(n+5) { display: block !important; } .contained-gallery .instagram li:nth-child(n+7), .contained-gallery .lightbox-gallery li:nth-child(n+7) { display: none !important; } .contained-gallery .instagram li, .contained-gallery .lightbox-gallery li { width: 33.33333% !important; } } /*! // 13. Pricing // --------------------------------------------------*/ .pricing-option { overflow: hidden; background: #f5f5f5; -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; transform-style: preserve-3d; position: relative; padding: 72px 0px; margin-bottom: 30px; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } .pricing-option .dot { position: absolute; top: 24px; right: 24px; width: 24px; height: 24px; border-radius: 50%; background: #fff; } .pricing-option:hover { background: #ededed; } @media all and (min-width: 321px) and (max-width: 767px) and (orientation: landscape) { .pricing-options .col-sm-6 { width: 50%; float: left; } } .dollar, .price, .type { font-weight: 600; color: #333333; font-size: 72px; } .dollar { font-size: 36px; position: relative; bottom: 22px; } .price { line-height: 1; } .type { display: block; font-size: 14px; text-transform: uppercase; letter-spacing: 1px; margin-top: 12px; } .plan-title { display: block; font-weight: 600; margin-bottom: 12px; font-size: 18px; color: #333333; } .pricing-option ul li { color: #777777; } .pricing-option.emphasis { background: #7300c2; color: #fff; } .pricing-option.emphasis .type, .pricing-option.emphasis .dollar, .pricing-option.emphasis .price, .pricing-option.emphasis .plan-title, .pricing-option.emphasis ul li { color: #fff !important; } @media all and (max-width: 991px) { .type { margin-bottom: 12px; } .pricing-option { text-align: center !important; } } /*! // Frequently Asked Questions // --------------------------------------------------*/ .faq-item { margin-bottom: 36px; } p.question { font-weight: 600; color: #333333; font-size: 16px; } /*! // Visitor Info // --------------------------------------------------*/ .info-box { margin-bottom: 36px; position: relative; overflow: hidden; } .info-box img { display: block; margin-bottom: 12px; } .info-box h3 { margin-bottom: 12px; } .info-box .text-link { position: absolute; bottom: 12px; right: 0px; } .text-link a { display: inline-block; margin-left: 12px; } @media all and (min-width: 321px) and (max-width: 767px) and (orientation: landscape) { .visitor-info .col-sm-4 { width: 50%; float: left; } } /*! // 14. Subscribe // --------------------------------------------------*/ .subscribe-1 { position: relative; overflow: hidden; padding-top: 144px; padding-bottom: 36px; } .subscribe-1:before { background-color: #333333; opacity: 0.4; position: absolute; content: ''; width: 100%; height: 100%; z-index: 1; top: 0px; } .subscribe-1 .container { position: relative; z-index: 2; } .subscribe-1 .email-subscribe { margin-bottom: 216px; } .subscribe-1 footer { border-top: 2px solid rgba(255, 255, 255, 0.3); padding-top: 36px; } .subscribe-1 .twitter-feed { margin-bottom: 72px; } .subscribe-1 h1 { margin-bottom: 30px; } .email-subscribe span { display: block; margin-top: 12px; } .twitter-feed i { font-size: 48px; display: inline-block; margin-bottom: 32px; } .twitter-feed span a { border-bottom: none; } .tweets-feed .user { display: none; } .tweets-feed .interact { display: none; } .tweets-feed .tweet { color: #fff; font-size: 30px; line-height: 36px; font-family: 'Open Sans', "Helvetica Neue", Helvetica, Arial, sans-serif; font-weight: 300; } .tweets-feed .tweet a { color: #fff !important; border-color: #fff !important; } .tweets-feed .timePosted { display: none; } @media all and (max-width: 767px) { .tweets-feed .tweet { font-size: 20px; line-height: 26px; } .subscribe-2 .form-email { margin-bottom: 24px; } } /*! // 15. Contact // --------------------------------------------------*/ .contact-tweets { background: #7300c2; color: #fff; position: relative; overflow: hidden; height: 600px; -webkit-transform-style: preserve-3d; -moz-transform-style: preserve-3d; transform-style: preserve-3d; } .contact-tweets .social_twitter { font-size: 42px; margin-bottom: 32px; display: inline-block; } .contact-tweets .map-holder { position: absolute; height: 100%; padding: 0px; top: 0px; right: 0px; } .contact-tweets .timePosted { display: block !important; } .map-holder:before { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2; opacity: 0; } .map-holder iframe { border: 0px; position: absolute; width: 100%; height: 100%; } .contact-tweets span a { border-bottom: 2px solid #fff; padding-bottom: 1px; } .contact-tweets form { padding-top: 0px !important; } .contact-tweets form .btn { background: #fff; color: #7300c2; } .contact-tweets form ::-webkit-input-placeholder { color: rgba(255, 255, 255, 0.9); } .contact-tweets form :-moz-placeholder { color: rgba(255, 255, 255, 0.9); } .contact-tweets form ::-moz-placeholder { color: rgba(255, 255, 255, 0.9); } .contact-tweets form :-ms-input-placeholder { color: rgba(255, 255, 255, 0.9); } .contact-tweets .icon { font-size: 60px; margin-bottom: 12px; } .contact-tweets .form-message { max-width: 95.5%; width: 95.5%; } .fullwidth-map { padding: 0px; position: relative; overflow: hidden; } .fullwidth-map .map-holder { width: 100%; height: 400px; overflow: hidden; } .fullwidth-map.screen:before { content: ''; position: absolute; width: 100%; height: 100%; z-index: 2; } /*! // Sponsors // --------------------------------------------------*/ .sponsors { background: #f5f5f5; } .sponsor { margin-bottom: 36px; height: 80px; line-height: 80px; } .sponsor img { max-width: 150px; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; max-height: 80px; } .sponsors span { display: inline-block; margin-top: 24px; } .sponsors span a { color: #7300c2; border-color: #7300c2; } @media all and (min-width: 321px) and (max-width: 767px) and (orientation: landscape) { .sponsors .col-sm-6 { width: 50%; float: left; } } /*! // 16. Forms // --------------------------------------------------*/ form.register { overflow: hidden; padding-top: 24px; display: block; } form.register div { padding: 0px; } input[type="text"], form.register .select-holder { margin-bottom: 32px; padding: 12px; border: none; background: rgba(255, 255, 255, 0.1); border-radius: 25px; font-size: 14px; max-width: 90%; color: #fff; padding-left: 24px; transition: all 0.3s ease-out; -webkit-transition: all 0.3s ease-out; -moz-transition: all 0.3s ease-out; } input[type="text"]:focus, form.register .select-holder:focus, input[type="text"]:hover, form.register .select-holder:hover { outline: none; background: rgba(255, 255, 255, 0.2); } form.register select { width: 90%; margin: 0px; background: none; border: none; cursor: pointer; } form.register select:focus { outline: none; } form.register input[type="submit"] { padding-bottom: 12px; width: 90%; margin-bottom: 12px; } input[type="submit"] { font-weight: normal; } .email-subscribe { overflow: hidden; } .email-subscribe input { margin: 0px auto; min-width: 100%; max-width: 100%; } .email-subscribe input[type="text"] { background: rgba(255, 255, 255, 0.3); } .email-subscribe input[type="text"]:hover, .email-subscribe input[type="text"]:focus { background: rgba(255, 255, 255, 0.4); } .email-subscribe ::-webkit-input-placeholder { color: rgba(255, 255, 255, 0.9); } .email-subscribe :-moz-placeholder { color: rgba(255, 255, 255, 0.9); } .email-subscribe ::-moz-placeholder { color: rgba(255, 255, 255, 0.9); } .email-subscribe :-ms-input-placeholder { color: rgba(255, 255, 255, 0.9); } .email-subscribe input[type="submit"] { min-height: 48px; } .subscribe-2 .email-subscribe input[type="text"] { background: rgba(0, 0, 0, 0.2); } .subscribe-2 i { color: #7300c2; font-size: 70px; display: inline-block; margin-right: 24px; margin-bottom: 18px; } .subscribe-2 i:last-of-type { margin-right: 0px; } input.error { color: #ff4532; } .mail-list-form { width: 0px; height: 0px; opacity: 0; overflow: hidden; } .form-success, .form-error { display: none; width: 100%; padding: 6px 18px 8px 18px !important; margin-top: 12px; color: #fff; background-color: #55c950; border-radius: 20px; } .form-error { background-color: #D74B4B; } form .field-error { background: #D74B4B !important; } @media all and (max-width: 767px) { form.register input, form.register .select-holder { width: 100% !important; max-width: 100%; } .subscribe-1 .email-subscribe input[type="text"] { margin-bottom: 24px; } } @media all and (min-width: 321px) and (max-width: 767px) and (orientation: landscape) { form.register .col-sm-6 { width: 50%; float: left; } form.register input, form.register .select-holder { max-width: 95% !important; } form.register input[type="submit"] { max-width: 100% !important; } } /*! // Utility Pages // --------------------------------------------------*/ .error-page { background: #7300c2; padding: 0px; } .error-page h1 { font-size: 84px; line-height: 96px; margin-bottom: 0px; margin-bottom: 12px; } .error-page p { font-size: 24px; line-height: 32px; } .error-page i { color: #fff; font-size: 84px; display: inline-block; margin-right: 24px; } .error-page i:last-of-type { margin-right: 0px; } .error-page .btn { margin-right: 24px; margin-top: 12px; } @media all and (max-width: 767px) { .error-page i { display: none; } } /*! // 17. Footers // --------------------------------------------------*/ .footer .top-border { height: 2px; width: 100%; background: rgba(255, 255, 255, 0.3); margin-bottom: 32px; } .footer .menu { overflow: visible; } .footer .menu li { top: 0px; } .footer .menu li a { padding-bottom: 0px; } .footer .menu li .btn { min-width: 0px; padding: 10px 18px; font-size: 14px; } .footer .menu li a { diplay: inline-block; position: relative; border: none; } .footer .menu li a:hover { border: none; } .footer .back-to-top { padding-right: 42px; } .footer .menu li a i { font-size: 36px; position: absolute; right: 0px; top: -12px; } @media all and (max-width: 767px) { .footer .text-right { text-align: left !important; } .footer .menu { margin-top: 24px; } .footer .menu li { float: none; margin-bottom: 12px; } } footer.classic { padding: 72px 0px 36px 0px; background: #f5f5f5; } footer.classic .menu li { float: none; margin-bottom: 12px; } footer.classic .menu li a { color: #333333; padding-bottom: 0px; font-weight: 600; } footer.classic span.lead { display: inline-block; margin-bottom: 12px; } footer.short { background: #333333; color: #fff; padding: 72px 0px; } footer.short .top-border { height: 1px !important; } @media all and (max-width: 767px) { footer.classic div { margin-bottom: 18px; } } .contact-methods li { margin-bottom: 12px; } .contact-methods li:last-child { margin-bottom: 0px; } .contact-methods i { font-size: 36px; color: #333333; } .contact-methods span { display: inline-block; position: relative; bottom: 10px; left: 8px; font-size: 16px; } footer.classic .social-profiles { margin-top: 36px; } .social-profiles { display: inline-block; overflow: hidden; } .social-profiles li { float: left; margin-right: 36px; } .social-profiles li:last-child { margin-right: 0px; } .social-profiles li a { color: #333333; font-size: 20px; }
{ "pile_set_name": "Github" }
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function() { "use strict"; var mode = CodeMirror.getMode({indentUnit: 2}, "text/x-less"); function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1), "less"); } MT("variable", "[variable-2 @base]: [atom #f04615];", "[qualifier .class] {", " [property width]: [variable percentage]([number 0.5]); [comment // returns `50%`]", " [property color]: [variable saturate]([variable-2 @base], [number 5%]);", "}"); MT("amp", "[qualifier .child], [qualifier .sibling] {", " [qualifier .parent] [atom &] {", " [property color]: [keyword black];", " }", " [atom &] + [atom &] {", " [property color]: [keyword red];", " }", "}"); MT("mixin", "[qualifier .mixin] ([variable dark]; [variable-2 @color]) {", " [property color]: [variable darken]([variable-2 @color], [number 10%]);", "}", "[qualifier .mixin] ([variable light]; [variable-2 @color]) {", " [property color]: [variable lighten]([variable-2 @color], [number 10%]);", "}", "[qualifier .mixin] ([variable-2 @_]; [variable-2 @color]) {", " [property display]: [atom block];", "}", "[variable-2 @switch]: [variable light];", "[qualifier .class] {", " [qualifier .mixin]([variable-2 @switch]; [atom #888]);", "}"); MT("nest", "[qualifier .one] {", " [def @media] ([property width]: [number 400px]) {", " [property font-size]: [number 1.2em];", " [def @media] [attribute print] [keyword and] [property color] {", " [property color]: [keyword blue];", " }", " }", "}"); })();
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>BuildMachineOSBuild</key> <string>12F45</string> <key>CFBundleDevelopmentRegion</key> <string>English</string> <key>CFBundleExecutable</key> <string>RealtekRTL8111</string> <key>CFBundleIdentifier</key> <string>com.insanelymac.RealtekRTL8111</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>RealtekRTL8111</string> <key>CFBundlePackageType</key> <string>KEXT</string> <key>CFBundleShortVersionString</key> <string>1.2.2</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1.2.2</string> <key>DTCompiler</key> <string>com.apple.compilers.llvm.clang.1_0</string> <key>DTPlatformBuild</key> <string>4H1503</string> <key>DTPlatformVersion</key> <string>GM</string> <key>DTSDKBuild</key> <string>12D75</string> <key>DTSDKName</key> <string>macosx10.8</string> <key>DTXcode</key> <string>0463</string> <key>DTXcodeBuild</key> <string>4H1503</string> <key>IOKitPersonalities</key> <dict> <key>RTL8111 PCIe Adapter</key> <dict> <key>CFBundleIdentifier</key> <string>com.insanelymac.RealtekRTL8111</string> <key>Driver_Version</key> <string>1.2.2</string> <key>IOClass</key> <string>RTL8111</string> <key>IOPCIMatch</key> <string>0x816810ec 0x81681186</string> <key>IOProbeScore</key> <integer>1000</integer> <key>IOProviderClass</key> <string>IOPCIDevice</string> <key>Model</key> <string>RTL8111</string> <key>Vendor</key> <string>Realtek</string> <key>disableASPM</key> <true/> <key>enableCSO6</key> <true/> <key>enableEEE</key> <true/> <key>enableTSO4</key> <true/> <key>intrMitigate</key> <integer>53080</integer> </dict> </dict> <key>NSHumanReadableCopyright</key> <string>Copyright © 2013 Laura Müller. All rights reserved.</string> <key>OSBundleLibraries</key> <dict> <key>com.apple.iokit.IONetworkingFamily</key> <string>1.5.0</string> <key>com.apple.iokit.IOPCIFamily</key> <string>1.7</string> <key>com.apple.kpi.bsd</key> <string>8.10.0</string> <key>com.apple.kpi.iokit</key> <string>8.10.0</string> <key>com.apple.kpi.libkern</key> <string>8.10.0</string> <key>com.apple.kpi.mach</key> <string>8.10.0</string> </dict> <key>OSBundleRequired</key> <string>Network-Root</string> </dict> </plist>
{ "pile_set_name": "Github" }
body { background-color: #EAEAEA; }
{ "pile_set_name": "Github" }
Type annotations for Python =========================== https://github.com/ceronman/typeannotations About ----- The ``typeannotations`` module provides a set of tools for type checking and type inference of Python code. It also a provides a set of types useful for annotating functions and objects. These tools are mainly designed to be used by static analyzers such as linters, code completion libraries and IDEs. Additionally, decorators for making run-time checks are provided. Run-time type checking is not always a good idea in Python, but in some cases it can be very useful. Run-time type checking. ----------------------- The ``typechecked`` decorator can be used to check types specified in function annotations. For example: .. code-block:: pycon >>> @typechecked ... def test(a: int) -> int: ... return a ... >>> test(1) 1 >>> test('string') Traceback (most recent call last): ... TypeError: Incorrect type for "a" Structural interfaces --------------------- The ``Interface`` class allows you to define interfaces that are checked dynamically. You don't have to explicitly indicate when an object or class implements a given ``Interface``. If an object provides the methods and attributes specified in the ``Interface``, it's considered a valid implementation. For example, let's define a simple interface: .. code-block:: pycon >>> class Person(Interface): ... name = str ... age = int ... def say_hello(name: str) -> str: ... pass Any object defining those the ``name``, ``age`` and ``say_hello()`` members is a valid implementation of that interface. For example: .. code-block:: pycon >>> class Developer: ... def __init__(self, name, age): ... self.name = name ... self.age = age ... def say_hello(self, name: str) -> str: ... return 'hello ' + name ... >>> isinstance(Developer('bill', 20), Person) True This also works with built-in types: .. code-block:: pycon >>> class IterableWithLen(Interface): ... def __iter__(): ... pass ... def __len__(): ... pass ... >>> isinstance([], IterableWithLen) True >>> isinstance({}, IterableWithLen) True >>> isinstance(1, IterableWithLen) False Typedefs '''''''' A ``typedef`` is similar to an ``Interface`` except that it defines a single function signature. This is useful for defining callbacks. For example: .. code-block:: pycon >>> @typedef ... def callback(event: Event) -> bool: ... pass ... Then it's possible to check if a function implements the same signature: .. code-block:: pycon >>> def handler(event: MouseEvent) -> bool: ... print('click') ... return True ... >>> isinstance(handler, callback) True >>> isinstance(lambda: True, callback) False Note that ``MouseEvent`` is a subclass of ``Event``. Type unions ----------- A ``union`` is a collection of types and it's a type itself. An object is an instance of a ``union`` if it's an instance of any of the elements in the union. For example: .. code-block:: pycon >>> NumberOrString = union(int, str) >>> isinstance(1, NumberOrString) True >>> isinstance('string', NumberOrString) True >>> issubclass(int, NumberOrString) True >>> issubclass(str, NumberOrString) True Predicates ---------- A ``predicate`` is a special type defined by a function that takes an object and returns ``True`` or ``False`` indicating if the object implements the type. For example: .. code-block:: pycon >>> Positive = predicate(lambda x: x > 0) >>> isinstance(1, Positive) True >>> isinstance(0, Positive) False Predicates can also be defined using a decorator: .. code-block:: pycon >>> @predicate ... def Even(object): ... return object % 2 == 0 Predicates can also be combined using the `&`` operator: .. code-block:: pycon >>> EvenAndPositive = Even & Positive Predicates are useful for defining contracts: .. code-block:: pycon >>> Positive = predicate(lambda x: x > 0) >>> @typechecked ... def sqrt(n: Positive): ... ... >>> sqrt(-1) Traceback (most recent call last): ... TypeError: Incorrect type for "n" The ``optional`` predicate '''''''''''''''''''''''''' The ``optional`` predicate indicates that the object must be from the given type or `None`. For example: .. code-block:: pycon >>> isinstance(1, optional(int)) True >>> isinstance(None, optional(int)) True And checking types at runtime: .. code-block:: pycon >>> @typechecked ... def greet(name: optional(str) = None): ... if name is None: ... print('hello stranger') ... else: ... print('hello {0}'.format(name)) ... >>> greet() hello stranger >>> greet('bill') hello bill The ``only`` predicate '''''''''''''''''''''' The ``only`` predicate indicates that an object can **only** be of the specified type, and not of any of its super classes. For example: .. code-block:: pycon >>> isinstance(True, only(bool)) True >>> isinstance(1, only(bool)) False Note that in Python `bool` is a sublcass of `int`. The ``options`` predicate ''''''''''''''''''''''''' The ``options`` predicate indicates that the value of an object must be one of the given options. For example: .. code-block:: pycon >>> FileMode = options('r', 'w', 'a', 'r+', 'w+', 'a+') >>> isinstance('w', FileMode) True >>> isinstance('x', FileMode) False This is useful when defining a function: .. code-block:: pycon >>> @typecheck ... def open(filename: str, mode: options('w', 'a')): ... ... Complex Types: '''''''''''''' Complex types are also accepted in both interfaces and type specifications. .. code-block:: pycon >>> @typechecked ... def test(a: { int: ( str, bool ) }) -> (bool, int): ... return isinstance(a, dict), len(a) ... >>> test({ 1: ('a', False) }) (True, 1) >>> test('string') Traceback (most recent call last): ... TypeError: Incorrect type for "a" The rules are: 1. A list of types. The value must be a list containing only the specified types. 2. A set of types. The value must be a set containing only the specified types. 3. A tuple of types. The value must be a tuple containing the specified types in the specified order. 4. A dict of types. The value must be a dict where each (key, value) pair is assocated with a (key, value) pair in the type dictionary. Any of the complex types can nest and contain any other type. To be implemented: ------------------ Function overloading '''''''''''''''''''' .. code-block:: python @overload def isinstance(object, t: type): ... @overload def isinstance(object, t: tuple): ... Annotate existing functions and libraries ''''''''''''''''''''''''''''''''''''''''' .. code-block:: python @annotate('builtins.open') def open_annotated(file: str, mode: options('r', 'w', 'a', 'r+', 'w+', 'a+'), buffering: optional(int)) -> IOBase: pass License ------- | 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.
{ "pile_set_name": "Github" }
package rfc /* * ZLint Copyright 2020 Regents of the University of Michigan * * 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. */ /************************************************************************ Restrictions are defined in terms of permitted or excluded name subtrees. Any name matching a restriction in the excludedSubtrees field is invalid regardless of information appearing in the permittedSubtrees. Conforming CAs MUST mark this extension as critical and SHOULD NOT impose name constraints on the x400Address, ediPartyName, or registeredID name forms. Conforming CAs MUST NOT issue certificates where name constraints is an empty sequence. That is, either the permittedSubtrees field or the excludedSubtrees MUST be present. ************************************************************************/ import ( "github.com/zmap/zcrypto/x509" "github.com/zmap/zlint/v2/lint" "github.com/zmap/zlint/v2/util" ) type nameConstraintCrit struct{} func (l *nameConstraintCrit) Initialize() error { return nil } func (l *nameConstraintCrit) CheckApplies(c *x509.Certificate) bool { return util.IsExtInCert(c, util.NameConstOID) } func (l *nameConstraintCrit) Execute(c *x509.Certificate) *lint.LintResult { e := util.GetExtFromCert(c, util.NameConstOID) if e.Critical { return &lint.LintResult{Status: lint.Pass} } else { return &lint.LintResult{Status: lint.Error} } } func init() { lint.RegisterLint(&lint.Lint{ Name: "e_ext_name_constraints_not_critical", Description: "If it is included, conforming CAs MUST mark the name constrains extension as critical", Citation: "RFC 5280: 4.2.1.10", Source: lint.RFC5280, EffectiveDate: util.RFC2459Date, Lint: &nameConstraintCrit{}, }) }
{ "pile_set_name": "Github" }
/* * ==================================================== * Copyright (C) 1998, 2002 by Red Hat Inc. All rights reserved. * * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ #if !defined(_SOFT_FLOAT) /* Fast version of tanf using Intel float instructions. float _f_tanf (float x); Function calculates the tangent of x. There is no error checking or setting of errno. */ #include "i386mach.h" .global SYM (_f_tanf) SOTYPE_FUNCTION(_f_tanf) SYM (_f_tanf): pushl ebp movl esp,ebp flds 8(ebp) fptan ffree %st(0) fincstp leave ret #endif
{ "pile_set_name": "Github" }
#' Split array, apply function, and return results in a data frame. #' #' For each slice of an array, apply function then combine results into a data #' frame. #' #' @template ply #' @template a- #' @template -d #' @param .id name(s) of the index column(s). #' Pass \code{NULL} to avoid creation of the index column(s). #' Omit or pass \code{NA} to use the default names #' \code{"X1"}, \code{"X2"}, \ldots. #' Otherwise, this argument must have the same length as #' \code{.margins}. #' @export adply <- function(.data, .margins, .fun = NULL, ..., .expand = TRUE, .progress = "none", .inform = FALSE, .parallel = FALSE, .paropts = NULL, .id = NA) { pieces <- splitter_a(.data, .margins, .expand, .id) .id <- NA if (is.null(attr(pieces, "split_labels"))) { .id <- NULL } ldply(.data = pieces, .fun = .fun, ..., .progress = .progress, .inform = .inform, .parallel = .parallel, .paropts = .paropts, .id = .id) }
{ "pile_set_name": "Github" }
# Modo estrito Para habilitar o modo estrito, simplesmente passe `strict: true` ao criar um _store_ Vuex: ``` js const store = new Vuex.Store({ // ... strict: true }) ``` Em modo estrito, sempre que o estado do Vuex é mutado fora dos manipuladores de mutação, um erro será lançado. Isso garante que todas as mutações do estado possam ser explicitamente rastreadas por ferramentas de depuração. ### Desenvolvimento vs. Produção **Não habilite o modo estrito ao implantar para a produção!** O modo estrito executa um observador profundo síncrono na árvore de estados para detectar mutações inapropriadas e pode ser bastante caro quando você faz grande quantidade de mutações no estado. Certifique-se de desligá-lo na produção para evitar o custo de desempenho. Semelhante aos plugins, podemos deixar as ferramentas de compilação lidar com isso: ``` js const store = new Vuex.Store({ // ... strict: process.env.NODE_ENV !== 'production' }) ```
{ "pile_set_name": "Github" }
--- http_interactions: - request: method: get uri: http://ps.pndsn.com/v2/subscribe/sub-a-mock-key/demo0,demo1,demo0-pnpres,demo1-pnpres,demo.*,demo.*-pnpres/0?auth=ruby-test-auth-client-one&pnsdk=PubNub-Ruby/4.1.0beta1&t=%7B%22r%22:0,%22t%22:0%7D&uuid=ruby-test-uuid-client-one body: encoding: UTF-8 string: '' headers: User-Agent: - HTTPClient/1.0 (2.8.0, ruby 2.3.0 (2015-12-25)) Accept: - "*/*" Date: - Wed, 08 Jun 2016 15:44:29 GMT response: status: code: 200 message: OK headers: Date: - Wed, 08 Jun 2016 15:44:29 GMT Content-Type: - text/javascript; charset="UTF-8" Content-Length: - '45' Connection: - keep-alive Cache-Control: - no-cache Access-Control-Allow-Origin: - "*" Access-Control-Allow-Methods: - GET body: encoding: UTF-8 string: '{"t":{"t":"14654006692380638","r":12},"m":[]}' http_version: recorded_at: Wed, 08 Jun 2016 15:44:29 GMT - request: method: get uri: http://ps.pndsn.com/v2/subscribe/sub-a-mock-key/demo0,demo1,demo0-pnpres,demo1-pnpres,demo.*,demo.*-pnpres/0?auth=ruby-test-auth-client-one&pnsdk=PubNub-Ruby/4.1.0beta1&t=%7B%22r%22:12,%22t%22:%2214654006692380638%22%7D&uuid=ruby-test-uuid-client-one body: encoding: UTF-8 string: '' headers: User-Agent: - HTTPClient/1.0 (2.8.0, ruby 2.3.0 (2015-12-25)) Accept: - "*/*" Date: - Wed, 08 Jun 2016 15:44:32 GMT response: status: code: 200 message: OK headers: Date: - Wed, 08 Jun 2016 15:44:32 GMT Content-Type: - text/javascript; charset="UTF-8" Content-Length: - '2369' Connection: - keep-alive Cache-Control: - no-cache Access-Control-Allow-Origin: - "*" Access-Control-Allow-Methods: - GET body: encoding: UTF-8 string: '{"t":{"t":"14654006723148918","r":12},"m":[{"a":"5","f":0,"p":{"t":"14654006708052570","r":1},"k":"sub-a-mock-key","c":"demo.*-pnpres","d":{"action": "leave", "timestamp": 1465400670, "uuid": "ruby-test-uuid-client-two", "occupancy": 1},"b":"demo.*"},{"a":"5","f":0,"i":"ruby-test-uuid-client-two","s":701,"o":{"t":"14654006710442932"},"p":{"t":"14654006710760852","r":12},"k":"sub-a-mock-key","c":"demo.ruby","d":"test_message","b":"demo.*"},{"a":"5","f":0,"p":{"t":"14654006708052570","r":1},"k":"sub-a-mock-key","c":"demo.*-pnpres","d":{"action": "leave", "timestamp": 1465400670, "uuid": "ruby-test-uuid-client-two", "occupancy": 1},"b":"demo.*"},{"a":"5","f":0,"i":"ruby-test-uuid-client-two","s":697,"o":{"t":"14654006709247190"},"p":{"t":"14654006709564237","r":12},"k":"sub-a-mock-key","c":"demo0","d":"test_message","b":"demo0"},{"a":"5","f":0,"p":{"t":"14654006698514460","r":1},"k":"sub-a-mock-key","c":"demo0-pnpres","d":{"action": "leave", "timestamp": 1465400669, "uuid": "ruby-test-uuid-client-two", "occupancy": 1},"b":"demo0-pnpres"},{"a":"5","f":0,"p":{"t":"14654006718521227","r":1},"k":"sub-a-mock-key","c":"demo0-pnpres","d":{"action": "join", "timestamp": 1465400671, "uuid": "ruby-test-uuid-client-two", "occupancy": 2},"b":"demo0-pnpres"},{"a":"5","f":0,"p":{"t":"14654006722331900","r":1},"k":"sub-a-mock-key","c":"demo0-pnpres","d":{"action": "leave", "timestamp": 1465400672, "uuid": "ruby-test-uuid-client-two", "occupancy": 1},"b":"demo0-pnpres"},{"a":"5","f":0,"i":"ruby-test-uuid-client-two","s":699,"o":{"t":"14654006709839920"},"p":{"t":"14654006710162607","r":12},"k":"sub-a-mock-key","c":"demo1","d":"test_message","b":"demo1"},{"a":"5","f":0,"p":{"t":"14654006705755452","r":1},"k":"sub-a-mock-key","c":"demo1-pnpres","d":{"action": "leave", "timestamp": 1465400670, "uuid": "ruby-test-uuid-client-two", "occupancy": 1},"b":"demo1-pnpres"},{"a":"5","f":0,"p":{"t":"14654006706448116","r":2},"k":"sub-a-mock-key","c":"demo1-pnpres","d":{"action": "join", "timestamp": 1465400670, "uuid": "ruby-test-uuid-client-two", "occupancy": 2},"b":"demo1-pnpres"}]}' http_version: recorded_at: Wed, 08 Jun 2016 15:44:32 GMT recorded_with: VCR 3.0.1
{ "pile_set_name": "Github" }
package org.zstack.network.service.portforwarding; import org.springframework.http.HttpMethod; import org.zstack.header.identity.Action; import org.zstack.header.message.APIEvent; import org.zstack.header.message.APIMessage; import org.zstack.header.message.APIParam; import org.zstack.header.rest.RestRequest; /** */ @Action(category = PortForwardingConstant.ACTION_CATEGORY) @RestRequest( path = "/port-forwarding/{uuid}/actions", method = HttpMethod.PUT, isAction = true, responseClass = APIChangePortForwardingRuleStateEvent.class ) public class APIChangePortForwardingRuleStateMsg extends APIMessage { @APIParam(resourceType = PortForwardingRuleVO.class, checkAccount = true, operationTarget = true) private String uuid; @APIParam(validValues = {"enable", "disable"}) private String stateEvent; public String getUuid() { return uuid; } public void setUuid(String uuid) { this.uuid = uuid; } public String getStateEvent() { return stateEvent; } public void setStateEvent(String stateEvent) { this.stateEvent = stateEvent; } public static APIChangePortForwardingRuleStateMsg __example__() { APIChangePortForwardingRuleStateMsg msg = new APIChangePortForwardingRuleStateMsg(); msg.setUuid(uuid()); msg.setStateEvent(PortForwardingRuleStateEvent.disable.toString()); return msg; } }
{ "pile_set_name": "Github" }
/* Machine-dependent ELF dynamic relocation inline functions. C-SKY version. Copyright (C) 2018-2020 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library. If not, see <https://www.gnu.org/licenses/>. */ #ifndef dl_machine_h #define dl_machine_h #define ELF_MACHINE_NAME "csky" #include <sys/param.h> #include <sysdep.h> #include <dl-tls.h> /* Return nonzero if ELF header is compatible with the running host. */ static inline int elf_machine_matches_host (const Elf32_Ehdr *ehdr) { return ehdr->e_machine == EM_CSKY; } /* Return the link-time address of _DYNAMIC. This must be inlined in a function which uses global data. */ static inline Elf32_Addr elf_machine_dynamic (void) { register Elf32_Addr *got __asm__ ("gb"); return *got; } /* Return the run-time load address ,of the shared object. */ static inline Elf32_Addr elf_machine_load_address (void) { extern Elf32_Addr __dl_start (void *) asm ("_dl_start"); Elf32_Addr got_addr = (Elf32_Addr) &__dl_start; Elf32_Addr pcrel_addr; asm ("grs %0,_dl_start\n" : "=r" (pcrel_addr)); return pcrel_addr - got_addr; } /* Set up the loaded object described by L so its unrelocated PLT entries will jump to the on-demand fixup code in dl-runtime.c. */ static inline int __attribute__ ((always_inline)) elf_machine_runtime_setup (struct link_map *l, int lazy, int profile) { Elf32_Addr *got; extern void _dl_runtime_resolve (Elf32_Word); if (l->l_info[DT_JMPREL] && lazy) { /* The GOT entries for functions in the PLT have not yet been filled in. Their initial contents will arrange when called to push an offset into the .rela.plt section, push _GLOBAL_OFFSET_TABLE_[1], and then jump to _GLOBAL_OFFSET_TABLE_[2]. */ got = (Elf32_Addr *) D_PTR (l, l_info[DT_PLTGOT]); if (got[1]) l->l_mach.plt = got[1] + l->l_addr; got[1] = (Elf32_Addr) l; /* Identify this shared object. */ /* The got[2] entry contains the address of a function which gets called to get the address of a so far unresolved function and jump to it. The profiling extension of the dynamic linker allows to intercept the calls to collect information. In this case we don't store the address in the GOT so that all future calls also end in this function. */ got[2] = (Elf32_Addr) &_dl_runtime_resolve; } return lazy; } /* Mask identifying addresses reserved for the user program, where the dynamic linker should not map anything. */ #define ELF_MACHINE_USER_ADDRESS_MASK 0x80000000UL /* Initial entry point code for the dynamic linker. The C function `_dl_start' is the real entry point; its return value is the user program's entry point. */ #define RTLD_START asm ("\ .text\n\ .globl _start\n\ .type _start, @function\n\ .globl _dl_start_user\n\ .type _dl_start_user, @function\n\ _start:\n\ grs gb, .Lgetpc1\n\ .Lgetpc1:\n\ lrw t0, .Lgetpc1@GOTPC\n\ addu gb, t0\n\ mov a0, sp\n\ lrw t1, _dl_start@GOTOFF\n\ addu t1, gb\n\ jsr t1\n\ _dl_start_user:\n\ /* get _dl_skip_args */ \n\ lrw r11, _dl_skip_args@GOTOFF\n\ addu r11, gb\n\ ldw r11, (r11, 0)\n\ /* store program entry address in r11 */ \n\ mov r10, a0\n\ /* Get argc */\n\ ldw a1, (sp, 0)\n\ /* Get **argv */\n\ mov a2, sp\n\ addi a2, 4\n\ cmpnei r11, 0\n\ bt .L_fixup_stack\n\ .L_done_fixup:\n\ mov a3, a1\n\ lsli a3, 2\n\ add a3, a2\n\ addi a3, 4\n\ lrw a0, _rtld_local@GOTOFF\n\ addu a0, gb\n\ ldw a0, (a0, 0)\n\ lrw t1, _dl_init@PLT\n\ addu t1, gb\n\ ldw t1, (t1)\n\ jsr t1\n\ lrw a0, _dl_fini@GOTOFF\n\ addu a0, gb\n\ jmp r10\n\ .L_fixup_stack:\n\ subu a1, r11\n\ lsli r11, 2\n\ addu sp, r11\n\ stw a1, (sp, 0)\n\ mov a2, sp\n\ addi a2, 4\n\ lrw a3, _dl_argv@GOTOFF\n\ addu a3, gb\n\ stw a2, (a3, 0)\n\ br .L_done_fixup\n\ "); /* ELF_RTYPE_CLASS_PLT iff TYPE describes relocation of a PLT entry or TLS variable, so undefined references should not be allowed to define the value. ELF_RTYPE_CLASS_NOCOPY iff TYPE should not be allowed to resolve to one of the main executable's symbols, as for a COPY reloc. */ #ifndef RTLD_BOOTSTRAP # define elf_machine_type_class(type) \ ((((type) == R_CKCORE_JUMP_SLOT || (type) == R_CKCORE_TLS_DTPMOD32 \ || (type) == R_CKCORE_TLS_DTPOFF32 || (type) == R_CKCORE_TLS_TPOFF32) \ * ELF_RTYPE_CLASS_PLT) \ | (((type) == R_CKCORE_COPY) * ELF_RTYPE_CLASS_COPY)) #else # define elf_machine_type_class(type) \ ((((type) == R_CKCORE_JUMP_SLOT \ | (((type) == R_CKCORE_COPY) * ELF_RTYPE_CLASS_COPY)) #endif /* A reloc type used for ld.so cmdline arg lookups to reject PLT entries. */ #define ELF_MACHINE_JMP_SLOT R_CKCORE_JUMP_SLOT /* C-SKY never uses Elf32_Rel relocations. */ #define ELF_MACHINE_NO_REL 1 #define ELF_MACHINE_NO_RELA 0 /* We define an initialization functions. This is called very early in _dl_sysdep_start. */ #define DL_PLATFORM_INIT dl_platform_init () static inline void __attribute__ ((unused)) dl_platform_init (void) { if (GLRO(dl_platform) != NULL && *GLRO(dl_platform) == '\0') /* Avoid an empty string which would disturb us. */ GLRO(dl_platform) = NULL; } static inline Elf32_Addr elf_machine_fixup_plt (struct link_map *map, lookup_t t, const ElfW(Sym) *refsym, const ElfW(Sym) *sym, const Elf32_Rela *reloc, Elf32_Addr *reloc_addr, Elf32_Addr value) { return *reloc_addr = value; } /* Return the final value of a plt relocation. On the csky the JMP_SLOT relocation ignores the addend. */ static inline Elf32_Addr elf_machine_plt_value (struct link_map *map, const Elf32_Rela *reloc, Elf32_Addr value) { return value; } /* Names of the architecture-specific auditing callback functions. */ #define ARCH_LA_PLTENTER csky_gnu_pltenter #define ARCH_LA_PLTEXIT csky_gnu_pltexit #endif /* !dl_machine_h */ #ifdef RESOLVE_MAP /* Perform the relocation specified by RELOC and SYM (which is fully resolved). MAP is the object containing the reloc. */ auto inline void __attribute__ ((unused, always_inline)) elf_machine_rela (struct link_map *map, const Elf32_Rela *reloc, const Elf32_Sym *sym, const struct r_found_version *version, void *const reloc_addr_arg, int skip_ifunc) { Elf32_Addr *const reloc_addr = reloc_addr_arg; const unsigned int r_type = ELF32_R_TYPE (reloc->r_info); unsigned short __attribute__ ((unused)) *opcode16_addr; Elf32_Addr __attribute__ ((unused)) insn_opcode = 0x0; if (__builtin_expect (r_type == R_CKCORE_RELATIVE, 0)) *reloc_addr = map->l_addr + reloc->r_addend; else { const Elf32_Sym *const refsym = sym; struct link_map *sym_map = RESOLVE_MAP (&sym, version, r_type); ElfW(Addr) value = SYMBOL_ADDRESS (sym_map, sym, true); opcode16_addr = (unsigned short *)reloc_addr; switch (r_type) { case R_CKCORE_COPY: if (sym == NULL) /* This can happen in trace mode if an object could not be found. */ break; if (sym->st_size > refsym->st_size || (sym->st_size < refsym->st_size && GLRO(dl_verbose))) { const char *strtab; strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]); _dl_error_printf ("\ %s: Symbol `%s' has different size in shared object, consider re-linking\n", rtld_progname ?: "<program name unknown>", strtab + refsym->st_name); } memcpy (reloc_addr_arg, (void *) value, MIN (sym->st_size, refsym->st_size)); break; case R_CKCORE_GLOB_DAT: case R_CKCORE_JUMP_SLOT: *reloc_addr = value; break; case R_CKCORE_ADDR32: *reloc_addr = value + reloc->r_addend; break; case R_CKCORE_PCREL32: *reloc_addr = value + reloc->r_addend - (Elf32_Addr) reloc_addr; break; #if defined(__CK810__) || defined(__CK807__) case R_CKCORE_ADDR_HI16: insn_opcode = (*opcode16_addr << 16) | (*(opcode16_addr + 1)); insn_opcode = (insn_opcode & 0xffff0000) | (((value + reloc->r_addend) >> 16) & 0xffff); *(opcode16_addr++) = (unsigned short)(insn_opcode >> 16); *opcode16_addr = (unsigned short)(insn_opcode & 0xffff); break; case R_CKCORE_ADDR_LO16: insn_opcode = (*opcode16_addr << 16) | (*(opcode16_addr + 1)); insn_opcode = (insn_opcode & 0xffff0000) | ((value + reloc->r_addend) & 0xffff); *(opcode16_addr++) = (unsigned short)(insn_opcode >> 16); *opcode16_addr = (unsigned short)(insn_opcode & 0xffff); break; case R_CKCORE_PCREL_IMM26BY2: { unsigned int offset = ((value + reloc->r_addend - (unsigned int)reloc_addr) >> 1); insn_opcode = (*opcode16_addr << 16) | (*(opcode16_addr + 1)); if (offset > 0x3ffffff){ const char *strtab; strtab = (const void *) D_PTR (map, l_info[DT_STRTAB]); _dl_error_printf ("\ %s:The reloc R_CKCORE_PCREL_IMM26BY2 cannot reach the symbol '%s'.\n", rtld_progname ?: "<program name unknown>", strtab + refsym->st_name); break; } insn_opcode = (insn_opcode & ~0x3ffffff) | offset; *(opcode16_addr++) = (unsigned short)(insn_opcode >> 16); *opcode16_addr = (unsigned short)(insn_opcode & 0xffff); break; } case R_CKCORE_PCREL_JSR_IMM26BY2: break; #endif #ifndef RTLD_BOOTSTRAP case R_CKCORE_TLS_DTPMOD32: /* Get the information from the link map returned by the resolv function. */ if (sym_map != NULL) *reloc_addr = sym_map->l_tls_modid; break; case R_CKCORE_TLS_DTPOFF32: if (sym != NULL) *reloc_addr =(sym == NULL ? 0 : sym->st_value) + reloc->r_addend; break; case R_CKCORE_TLS_TPOFF32: if (sym != NULL) { CHECK_STATIC_TLS (map, sym_map); *reloc_addr = (sym->st_value + sym_map->l_tls_offset + reloc->r_addend); } break; #endif /* !RTLD_BOOTSTRAP */ case R_CKCORE_NONE: break; default: break; } } } auto inline void __attribute__ ((unused, always_inline)) elf_machine_rela_relative (Elf32_Addr l_addr, const Elf32_Rela *reloc, void *const reloc_addr_arg) { Elf32_Addr *const reloc_addr = reloc_addr_arg; *reloc_addr = l_addr + reloc->r_addend; } auto inline void __attribute__ ((unused, always_inline)) elf_machine_lazy_rel (struct link_map *map, Elf32_Addr l_addr, const Elf32_Rela *reloc, int skip_ifunc) { Elf32_Addr *const reloc_addr = (void *) (l_addr + reloc->r_offset); const unsigned int r_type = ELF32_R_TYPE (reloc->r_info); if (ELF32_R_TYPE (reloc->r_info) == R_CKCORE_JUMP_SLOT) { /* Check for unexpected PLT reloc type. */ if (__builtin_expect (r_type == R_CKCORE_JUMP_SLOT, 1)) { if (__builtin_expect (map->l_mach.plt, 0) == 0) *reloc_addr = l_addr + reloc->r_addend; else *reloc_addr = map->l_mach.plt; } } } #endif /* RESOLVE_MAP */
{ "pile_set_name": "Github" }
/*========================================================================= Program: Visualization Toolkit Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkOpenGLFluidMapper.h" #include "vtkOpenGLHelper.h" #include "vtkCommand.h" #include "vtkExecutive.h" #include "vtkMath.h" #include "vtkMatrix3x3.h" #include "vtkMatrix4x4.h" #include "vtkObjectFactory.h" #include "vtkOpenGLActor.h" #include "vtkOpenGLCamera.h" #include "vtkOpenGLFramebufferObject.h" #include "vtkOpenGLIndexBufferObject.h" #include "vtkOpenGLQuadHelper.h" #include "vtkOpenGLRenderWindow.h" #include "vtkOpenGLRenderer.h" #include "vtkOpenGLShaderCache.h" #include "vtkOpenGLState.h" #include "vtkOpenGLTexture.h" #include "vtkOpenGLVertexArrayObject.h" #include "vtkOpenGLVertexBufferObject.h" #include "vtkOpenGLVertexBufferObjectGroup.h" #include "vtkPBRPrefilterTexture.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkProperty.h" #include "vtkShaderProgram.h" #include "vtkTextureObject.h" #include "vtkVolumeProperty.h" #include "vtkFluidMapperDepthFilterBiGaussFS.h" #include "vtkFluidMapperDepthFilterNarrowRangeFS.h" #include "vtkFluidMapperFS.h" #include "vtkFluidMapperFinalFS.h" #include "vtkFluidMapperGS.h" #include "vtkFluidMapperSurfaceNormalFS.h" #include "vtkFluidMapperThicknessAndVolumeColorFilterFS.h" #include "vtkFluidMapperVS.h" #include "vtk_glew.h" #include <cassert> #include <sstream> //------------------------------------------------------------------------------ vtkStandardNewMacro(vtkOpenGLFluidMapper); //------------------------------------------------------------------------------ vtkOpenGLFluidMapper::vtkOpenGLFluidMapper() : VBOs(vtkOpenGLVertexBufferObjectGroup::New()) , TempMatrix4(vtkMatrix4x4::New()) { for (int i = 0; i < NumTexBuffers; ++i) { this->TexBuffer[i] = vtkTextureObject::New(); } for (int i = 0; i < NumOptionalTexBuffers; ++i) { this->OptionalTexBuffer[i] = vtkTextureObject::New(); } this->CamDCVC = vtkMatrix4x4::New(); this->CamInvertedNorms = vtkMatrix3x3::New(); } //------------------------------------------------------------------------------ vtkOpenGLFluidMapper::~vtkOpenGLFluidMapper() { this->TempMatrix4->Delete(); this->VBOs->Delete(); for (int i = 0; i < NumTexBuffers; ++i) { this->TexBuffer[i]->Delete(); } for (int i = 0; i < NumOptionalTexBuffers; ++i) { this->OptionalTexBuffer[i]->Delete(); } this->CamDCVC->Delete(); this->CamInvertedNorms->Delete(); } //------------------------------------------------------------------------------ void vtkOpenGLFluidMapper::SetInputData(vtkPolyData* input) { this->SetInputDataInternal(0, input); } //------------------------------------------------------------------------------ // Specify the input data or filter. vtkPolyData* vtkOpenGLFluidMapper::GetInput() { return vtkPolyData::SafeDownCast(this->GetExecutive()->GetInputData(0, 0)); } //------------------------------------------------------------------------------ void vtkOpenGLFluidMapper::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "Particle radius: " << this->ParticleRadius << "\n"; } //------------------------------------------------------------------------------ void vtkOpenGLFluidMapper::UpdateDepthThicknessColorShaders( vtkOpenGLHelper& glHelper, vtkRenderer* renderer, vtkVolume* actor) { const auto renderWindow = vtkOpenGLRenderWindow::SafeDownCast(renderer->GetRenderWindow()); glHelper.VAO->Bind(); // Has something changed that would require us to recreate the shader? if (!glHelper.Program) { // Build the shader source code std::map<vtkShader::Type, vtkShader*> shaders; vtkShader* vertexShader = vtkShader::New(); vertexShader->SetType(vtkShader::Vertex); vertexShader->SetSource(vtkFluidMapperVS); shaders[vtkShader::Vertex] = vertexShader; vtkShader* geomShader = vtkShader::New(); geomShader->SetType(vtkShader::Geometry); geomShader->SetSource(vtkFluidMapperGS); shaders[vtkShader::Geometry] = geomShader; vtkShader* fragmentShader = vtkShader::New(); fragmentShader->SetType(vtkShader::Fragment); fragmentShader->SetSource(vtkFluidMapperFS); shaders[vtkShader::Fragment] = fragmentShader; // Compile and bind the program if needed vtkShaderProgram* newProgram = renderWindow->GetShaderCache()->ReadyShaderProgram(shaders); // Done with you, now you're thrown away fragmentShader->Delete(); geomShader->Delete(); vertexShader->Delete(); // If the shader changed, reinitialize the VAO if (newProgram != glHelper.Program) { glHelper.Program = newProgram; // reset the VAO as the shader has changed glHelper.VAO->ReleaseGraphicsResources(); } glHelper.ShaderSourceTime.Modified(); } else { renderWindow->GetShaderCache()->ReadyShaderProgram(glHelper.Program); } if (glHelper.Program) { this->SetDepthThicknessColorShaderParameters(glHelper, renderer, actor); // Allow the program to set what it wants this->InvokeEvent(vtkCommand::UpdateShaderEvent, glHelper.Program); } } //------------------------------------------------------------------------------ void vtkOpenGLFluidMapper::SetDepthThicknessColorShaderParameters( vtkOpenGLHelper& glHelper, vtkRenderer* ren, vtkVolume* actor) { if (glHelper.IBO->IndexCount && (this->VBOs->GetMTime() > glHelper.AttributeUpdateTime || glHelper.ShaderSourceTime > glHelper.AttributeUpdateTime)) { glHelper.VAO->Bind(); this->VBOs->AddAllAttributesToVAO(glHelper.Program, glHelper.VAO); glHelper.AttributeUpdateTime.Modified(); } const auto program = glHelper.Program; program->SetUniformi("outputEyeZ", this->InDepthPass); if (!this->InDepthPass) { // based on clipping range program->SetUniformf("minThickness", ren->GetActiveCamera()->GetClippingRange()[1] * 1.0e-9); } if (this->HasVertexColor) { program->SetUniformi("hasVertexColor", this->HasVertexColor); } // Set texture and particle radius program->SetUniformi("opaqueZTexture", this->TexBuffer[OpaqueZ]->GetTextureUnit()); program->SetUniformf("particleRadius", this->ParticleRadius); // Set camera if (program->IsUniformUsed("VCDCMatrix")) { program->SetUniformMatrix("VCDCMatrix", this->CamVCDC); } if (program->IsUniformUsed("MCVCMatrix")) { if (!actor->GetIsIdentity()) { vtkMatrix4x4* mcwc; vtkMatrix3x3* anorms; ((vtkOpenGLActor*)actor)->GetKeyMatrices(mcwc, anorms); vtkMatrix4x4::Multiply4x4(mcwc, this->CamWCVC, this->TempMatrix4); program->SetUniformMatrix("MCVCMatrix", this->TempMatrix4); } else { program->SetUniformMatrix("MCVCMatrix", this->CamWCVC); } } if (program->IsUniformUsed("cameraParallel")) { glHelper.Program->SetUniformi("cameraParallel", this->CamParallelProjection); } } void vtkOpenGLFluidMapper::SetupBuffers(vtkOpenGLRenderWindow* const renderWindow) { // create textures we need if not done already if (this->TexBuffer[0]->GetHandle() == 0) { for (int i = 0; i < NumTexBuffers; ++i) { this->TexBuffer[i]->SetContext(renderWindow); switch (i) { case OpaqueZ: case FluidZ: this->TexBuffer[i]->AllocateDepth(static_cast<unsigned int>(this->ViewportWidth), static_cast<unsigned int>(this->ViewportHeight), vtkTextureObject::Float32); break; case FluidEyeZ: case SmoothedFluidEyeZ: case FluidThickness: case SmoothedFluidThickness: this->TexBuffer[i]->SetInternalFormat(GL_R32F); this->TexBuffer[i]->SetFormat(GL_RED); this->TexBuffer[i]->Allocate2D(static_cast<unsigned int>(this->ViewportWidth), static_cast<unsigned int>(this->ViewportHeight), 1, VTK_FLOAT); break; case FluidNormal: this->TexBuffer[i]->Allocate2D(static_cast<unsigned int>(this->ViewportWidth), static_cast<unsigned int>(this->ViewportHeight), 3, VTK_FLOAT); break; case OpaqueRGBA: this->TexBuffer[i]->Allocate2D(static_cast<unsigned int>(this->ViewportWidth), static_cast<unsigned int>(this->ViewportHeight), 4, VTK_UNSIGNED_CHAR); break; default:; } this->TexBuffer[i]->SetMinificationFilter(vtkTextureObject::Nearest); this->TexBuffer[i]->SetMagnificationFilter(vtkTextureObject::Nearest); this->TexBuffer[i]->SetWrapS(vtkTextureObject::ClampToEdge); this->TexBuffer[i]->SetWrapT(vtkTextureObject::ClampToEdge); } } else { // make sure we handle size changes for (int i = 0; i < NumTexBuffers; ++i) { this->TexBuffer[i]->Resize(static_cast<unsigned int>(this->ViewportWidth), static_cast<unsigned int>(this->ViewportHeight)); } } // Allocate additional 2 texture bufferes for color data if (this->HasVertexColor) { if (this->OptionalTexBuffer[0]->GetHandle() == 0) { for (int i = 0; i < NumOptionalTexBuffers; ++i) { this->OptionalTexBuffer[i]->SetContext(renderWindow); this->OptionalTexBuffer[i]->Allocate2D(static_cast<unsigned int>(this->ViewportWidth), static_cast<unsigned int>(this->ViewportHeight), 3, VTK_FLOAT); this->OptionalTexBuffer[i]->SetMinificationFilter(vtkTextureObject::Nearest); this->OptionalTexBuffer[i]->SetMagnificationFilter(vtkTextureObject::Nearest); this->OptionalTexBuffer[i]->SetWrapS(vtkTextureObject::ClampToEdge); this->OptionalTexBuffer[i]->SetWrapT(vtkTextureObject::ClampToEdge); } } else { // make sure we handle size changes for (int i = 0; i < NumOptionalTexBuffers; ++i) { this->OptionalTexBuffer[i]->Resize(static_cast<unsigned int>(this->ViewportWidth), static_cast<unsigned int>(this->ViewportHeight)); } } } // copy the opaque buffers into textures this->TexBuffer[OpaqueZ]->CopyFromFrameBuffer(this->ViewportX, this->ViewportY, this->ViewportX, this->ViewportY, this->ViewportWidth, this->ViewportHeight); this->TexBuffer[OpaqueRGBA]->CopyFromFrameBuffer(this->ViewportX, this->ViewportY, this->ViewportX, this->ViewportY, this->ViewportWidth, this->ViewportHeight); if (!this->FBFluidEyeZ) { this->FBFluidEyeZ = vtkOpenGLFramebufferObject::New(); this->FBFluidEyeZ->SetContext(renderWindow); this->FBFluidEyeZ->AddDepthAttachment(this->TexBuffer[FluidZ]); // Must have a depth buffer } if (!this->FBThickness) { this->FBThickness = vtkOpenGLFramebufferObject::New(); this->FBThickness->SetContext(renderWindow); this->FBThickness->AddDepthAttachment(this->TexBuffer[FluidZ]); // Must have a depth buffer } if (!this->FBFilterThickness) { this->FBFilterThickness = vtkOpenGLFramebufferObject::New(); this->FBFilterThickness->SetContext(renderWindow); // Color attachment will be dynamically added later } if (!this->FBFilterDepth) { this->FBFilterDepth = vtkOpenGLFramebufferObject::New(); this->FBFilterDepth->SetContext(renderWindow); // Color attachment will be dynamically added later } if (!this->FBCompNormal) { this->FBCompNormal = vtkOpenGLFramebufferObject::New(); this->FBCompNormal->SetContext(renderWindow); this->FBCompNormal->AddColorAttachment(0, this->TexBuffer[FluidNormal]); } } //------------------------------------------------------------------------------ void vtkOpenGLFluidMapper::Render(vtkRenderer* renderer, vtkVolume* vol) { // make sure we have data vtkPolyData* input = vtkPolyData::SafeDownCast(GetInputDataObject(0, 0)); if (input == nullptr || input->GetPoints() == nullptr) { return; } // check to see if we are using vertex coloring int cellFlag = 0; vtkDataArray* scalars = this->GetScalars( input, this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, cellFlag); this->HasVertexColor = false; if (scalars && cellFlag == 0 && scalars->GetNumberOfComponents() == 3 && this->ScalarVisibility) { this->HasVertexColor = true; } // Get the viewport dimensions renderer->GetTiledSizeAndOrigin( &this->ViewportWidth, &this->ViewportHeight, &this->ViewportX, &this->ViewportY); // Get the camera parameters const auto cam = static_cast<vtkOpenGLCamera*>(renderer->GetActiveCamera()); vtkMatrix3x3* tmpNormMat; cam->GetKeyMatrices(renderer, this->CamWCVC, tmpNormMat, this->CamVCDC, this->CamWCDC); this->CamDCVC->DeepCopy(this->CamVCDC); this->CamDCVC->Invert(); this->CamInvertedNorms->DeepCopy(tmpNormMat); this->CamInvertedNorms->Invert(); this->CamParallelProjection = cam->GetParallelProjection(); // Prepare the texture and frame buffers const auto renderWindow = vtkOpenGLRenderWindow::SafeDownCast(renderer->GetRenderWindow()); this->SetupBuffers(renderWindow); const auto glState = renderWindow->GetState(); glState->vtkglViewport(0, 0, this->ViewportWidth, this->ViewportHeight); bool saveScissorTestState = glState->GetEnumState(GL_SCISSOR_TEST); #ifdef GL_MULTISAMPLE glState->vtkglDisable(GL_MULTISAMPLE); #endif double* crange = cam->GetClippingRange(); // Generate depth { // Attach texture every time, since it will be swapped out during smoothing this->FBFluidEyeZ->SetContext(renderWindow); glState->PushFramebufferBindings(); this->FBFluidEyeZ->Bind(); this->FBFluidEyeZ->AddColorAttachment(0U, this->TexBuffer[FluidEyeZ]); this->FBFluidEyeZ->ActivateDrawBuffers(1); this->FBFluidEyeZ->CheckFrameBufferStatus(GL_FRAMEBUFFER); glState->vtkglDisable(GL_SCISSOR_TEST); glState->vtkglClearDepth(1.0); glState->vtkglColorMask(GL_TRUE, GL_FALSE, GL_FALSE, GL_FALSE); // Set a clear color value to be slightly past the far clipping plane glState->vtkglClearColor(-1.1 * crange[1], 0.0, 0.0, 0.0); glState->vtkglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Render the spheres to get the eye coordinate z values this->TexBuffer[OpaqueZ]->Activate(); glState->vtkglDepthMask(GL_TRUE); glState->vtkglEnable(GL_DEPTH_TEST); glState->vtkglDepthFunc(GL_LEQUAL); this->InDepthPass = true; this->RenderParticles(renderer, vol); this->InDepthPass = false; this->TexBuffer[OpaqueZ]->Deactivate(); this->FBFluidEyeZ->DeactivateDrawBuffers(); this->FBFluidEyeZ->RemoveColorAttachment(0U); glState->PopFramebufferBindings(); } // Generate thickness and color (if applicable) { // Attache texture every time, since it will be swapped out during smoothing this->FBThickness->SetContext(renderWindow); glState->PushFramebufferBindings(); this->FBThickness->Bind(); this->FBThickness->AddColorAttachment(0U, this->TexBuffer[FluidThickness]); this->FBThickness->ActivateDrawBuffers(1); this->FBThickness->CheckFrameBufferStatus(GL_FRAMEBUFFER); if (this->HasVertexColor) { this->FBThickness->AddColorAttachment(1, this->OptionalTexBuffer[Color]); this->FBThickness->ActivateDrawBuffers(2); this->FBThickness->CheckFrameBufferStatus(GL_FRAMEBUFFER); } glState->vtkglDisable(GL_SCISSOR_TEST); glState->vtkglClearDepth(1.0); glState->vtkglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); glState->vtkglClearColor(0.0, 0.0, 0.0, 0.0); glState->vtkglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); vtkOpenGLState::ScopedglBlendFuncSeparate bf(glState); glState->vtkglBlendFuncSeparate(GL_ONE, GL_ONE, GL_ONE, GL_ONE); this->TexBuffer[OpaqueZ]->Activate(); glState->vtkglDepthMask(GL_FALSE); glState->vtkglDisable(GL_DEPTH_TEST); glState->vtkglDepthFunc(GL_ALWAYS); this->RenderParticles(renderer, vol); this->TexBuffer[OpaqueZ]->Deactivate(); this->FBThickness->DeactivateDrawBuffers(); if (this->HasVertexColor) { this->FBThickness->RemoveColorAttachment(1U); } this->FBThickness->RemoveColorAttachment(0U); glState->PopFramebufferBindings(); } // Filter fluid thickness and color (if applicable) if (true) { if (!this->QuadThicknessFilter) { this->QuadThicknessFilter = new vtkOpenGLQuadHelper( renderWindow, nullptr, vtkFluidMapperThicknessAndVolumeColorFilterFS, ""); } else { renderWindow->GetShaderCache()->ReadyShaderProgram(this->QuadThicknessFilter->Program); } const auto program = this->QuadThicknessFilter->Program; assert(program); // Attache texture every time, since it will be swapped out during smoothing this->FBFilterThickness->SetContext(renderWindow); glState->PushFramebufferBindings(); for (uint32_t iter = 0; iter < this->ThicknessAndVolumeColorFilterIterations; ++iter) { this->FBFilterThickness->Bind(); this->FBFilterThickness->AddColorAttachment(0U, this->TexBuffer[SmoothedFluidThickness]); this->FBFilterThickness->ActivateDrawBuffers(1); this->FBFilterThickness->CheckFrameBufferStatus(GL_FRAMEBUFFER); glState->vtkglClearDepth(1.0); glState->vtkglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); glState->vtkglClearColor(0.0, 0.0, 0.0, 0.0); glState->vtkglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); if (this->HasVertexColor) { this->FBFilterThickness->AddColorAttachment(1, this->OptionalTexBuffer[SmoothedColor]); this->FBFilterThickness->ActivateDrawBuffers(2); this->OptionalTexBuffer[Color]->Activate(); program->SetUniformi("hasVertexColor", this->HasVertexColor); program->SetUniformi("fluidColorTexture", this->OptionalTexBuffer[Color]->GetTextureUnit()); } this->TexBuffer[FluidThickness]->Activate(); program->SetUniformi( "fluidThicknessTexture", this->TexBuffer[FluidThickness]->GetTextureUnit()); program->SetUniformi("viewportHeight", this->ViewportHeight); program->SetUniformi("viewportWidth", this->ViewportWidth); program->SetUniformi( "filterRadius", static_cast<int>(this->ThicknessAndVolumeColorFilterRadius)); this->QuadThicknessFilter->Render(); this->TexBuffer[FluidThickness]->Deactivate(); this->FBFilterThickness->DeactivateDrawBuffers(); this->FBFilterThickness->RemoveColorAttachment(0U); std::swap(this->TexBuffer[FluidThickness], this->TexBuffer[SmoothedFluidThickness]); if (this->HasVertexColor) { this->OptionalTexBuffer[Color]->Deactivate(); std::swap(this->OptionalTexBuffer[Color], this->OptionalTexBuffer[SmoothedColor]); } } glState->PopFramebufferBindings(); } if (true) { // Filter depth surface if (DisplayMode != UnfilteredOpaqueSurface && DisplayMode != UnfilteredSurfaceNormal) { if (!this->QuadFluidDepthFilter[SurfaceFilterMethod]) { switch (this->SurfaceFilterMethod) { case BilateralGaussian: this->QuadFluidDepthFilter[SurfaceFilterMethod] = new vtkOpenGLQuadHelper( renderWindow, nullptr, vtkFluidMapperDepthFilterBiGaussFS, ""); break; case NarrowRange: this->QuadFluidDepthFilter[SurfaceFilterMethod] = new vtkOpenGLQuadHelper( renderWindow, nullptr, vtkFluidMapperDepthFilterNarrowRangeFS, ""); break; // New filter method is added here default: vtkErrorMacro("Invalid filter method"); } } else { renderWindow->GetShaderCache()->ReadyShaderProgram( this->QuadFluidDepthFilter[SurfaceFilterMethod]->Program); } const auto program = this->QuadFluidDepthFilter[SurfaceFilterMethod]->Program; assert(program); this->FBFilterDepth->SetContext(renderWindow); glState->PushFramebufferBindings(); program->SetUniformi("viewportHeight", this->ViewportHeight); program->SetUniformi("viewportWidth", this->ViewportWidth); program->SetUniformi("filterRadius", static_cast<int>(this->SurfaceFilterRadius)); program->SetUniformf("particleRadius", this->ParticleRadius); program->SetUniformf("farZValue", -crange[1]); for (uint32_t iter = 0; iter < this->SurfaceFilterIterations; ++iter) { this->FBFilterDepth->Bind(); this->FBFilterDepth->AddColorAttachment( 0U, this->TexBuffer[SmoothedFluidEyeZ]); // Replace color attachement this->FBFilterDepth->ActivateDrawBuffers(1); this->FBFilterDepth->CheckFrameBufferStatus(GL_FRAMEBUFFER); glState->vtkglClearDepth(1.0); glState->vtkglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); glState->vtkglClearColor(0.0, 0.0, 0.0, 0.0); glState->vtkglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); switch (SurfaceFilterMethod) { case BilateralGaussian: program->SetUniformf("sigmaDepth", this->BiGaussFilterSigmaDepth); break; case NarrowRange: program->SetUniformf("lambda", this->NRFilterLambda); program->SetUniformf("mu", this->NRFilterMu); break; // New filter method is added here default: vtkErrorMacro("Invalid filter method"); } glState->vtkglEnable(GL_DEPTH_TEST); this->TexBuffer[FluidEyeZ]->Activate(); program->SetUniformi("fluidZTexture", this->TexBuffer[FluidEyeZ]->GetTextureUnit()); this->QuadFluidDepthFilter[SurfaceFilterMethod]->Render(); this->TexBuffer[FluidEyeZ]->Deactivate(); this->FBFilterDepth->DeactivateDrawBuffers(); this->FBFilterDepth->RemoveColorAttachment(0); // Swap the filtered buffers std::swap(this->TexBuffer[FluidEyeZ], this->TexBuffer[SmoothedFluidEyeZ]); } glState->PopFramebufferBindings(); } } // Compute normal for the filtered depth surface if (true) { if (!this->QuadFluidNormal) { this->QuadFluidNormal = new vtkOpenGLQuadHelper(renderWindow, nullptr, vtkFluidMapperSurfaceNormalFS, ""); } else { renderWindow->GetShaderCache()->ReadyShaderProgram(this->QuadFluidNormal->Program); } const auto program = this->QuadFluidNormal->Program; assert(program); this->FBCompNormal->SetContext(renderWindow); glState->PushFramebufferBindings(); this->FBCompNormal->Bind(); this->FBCompNormal->AddColorAttachment(0, this->TexBuffer[FluidNormal]); this->FBCompNormal->ActivateDrawBuffers(1); this->FBCompNormal->CheckFrameBufferStatus(GL_FRAMEBUFFER); this->TexBuffer[FluidEyeZ]->Activate(); program->SetUniformi("fluidZTexture", this->TexBuffer[FluidEyeZ]->GetTextureUnit()); program->SetUniformi("viewportHeight", this->ViewportHeight); program->SetUniformi("viewportWidth", this->ViewportWidth); program->SetUniformMatrix("DCVCMatrix", this->CamDCVC); program->SetUniformMatrix("VCDCMatrix", this->CamVCDC); glState->vtkglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE); glState->vtkglDepthMask(GL_FALSE); glState->vtkglDisable(GL_DEPTH_TEST); glState->vtkglDepthFunc(GL_ALWAYS); glState->vtkglClearColor(0.0, 0.0, 0.0, 0.0); glState->vtkglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); this->QuadFluidNormal->Render(); this->TexBuffer[FluidEyeZ]->Deactivate(); this->FBCompNormal->DeactivateDrawBuffers(); glState->PopFramebufferBindings(); } vtkOpenGLRenderer* oren = static_cast<vtkOpenGLRenderer*>(renderer); // Restore the original viewport properties glState->vtkglColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glState->vtkglViewport( this->ViewportX, this->ViewportY, this->ViewportWidth, this->ViewportHeight); saveScissorTestState ? glState->vtkglEnable(GL_SCISSOR_TEST) : glState->vtkglDisable(GL_SCISSOR_TEST); { bool useIBL = oren->GetUseImageBasedLighting() && oren->GetEnvironmentTexture(); // Final blend, render everything if (!this->QuadFinalBlend) { std::ostringstream toString; // todo this needs to be done when the lighting code changes // if the light complexity changed then update the shader code std::string fssource = vtkFluidMapperFinalFS; vtkShaderProgram::Substitute(fssource, "//VTK::Light::Dec", oren->GetLightingUniforms()); switch (oren->GetLightingComplexity()) { // no lighting case 0: vtkShaderProgram::Substitute(fssource, "//VTK::Light::Impl", " accumulatedLightSpecularColor = vec3(1.0,1.0,1.0);", false); break; // headlight case 1: vtkShaderProgram::Substitute(fssource, "//VTK::Light::Impl", " float df = max(0.0,N.z);\n" " float sf = pow(df, fluidShininess);\n" " accumulatedLightDiffuseColor = df * lightColor0;\n" " accumulatedLightSpecularColor = sf * lightColor0;\n" " //VTK::Light::Impl\n", false); break; case 2: toString << " float df;\n" " float sf;\n"; for (int i = 0; i < oren->GetLightingCount(); ++i) { toString << " df = max(0.0, dot(N, -lightDirectionVC" << i << "));\n" " accumulatedLightDiffuseColor += (df * lightColor" << i << ");\n" << " sf = sign(df)*pow(max(0.0, dot( reflect(lightDirectionVC" << i << " , N), normalize(-position))), fluidShininess);\n" " accumulatedLightSpecularColor += (sf * lightColor" << i << ");\n"; } vtkShaderProgram::Substitute(fssource, "//VTK::Light::Impl", toString.str(), false); break; case 3: toString << " vec3 vertLightDirectionVC;\n" " float attenuation;\n" " float df;\n" " float sf;\n"; for (int i = 0; i < oren->GetLightingCount(); ++i) { toString << " attenuation = 1.0;\n" " if (lightPositional" << i << " == 0) {\n" " vertLightDirectionVC = lightDirectionVC" << i << "; }\n" " else {\n" " vertLightDirectionVC = position - lightPositionVC" << i << ";\n" " float distanceVC = length(vertLightDirectionVC);\n" " vertLightDirectionVC = " "normalize(vertLightDirectionVC);\n" " attenuation = 1.0 /\n" " (lightAttenuation" << i << ".x\n" " + lightAttenuation" << i << ".y * distanceVC\n" " + lightAttenuation" << i << ".z * distanceVC * distanceVC);\n" " // per OpenGL standard cone angle is 90 or less for a " "spot light\n" " if (lightConeAngle" << i << " <= 90.0) {\n" " float coneDot = dot(vertLightDirectionVC, " "lightDirectionVC" << i << ");\n" " // if inside the cone\n" " if (coneDot >= cos(radians(lightConeAngle" << i << "))) {\n" " attenuation = attenuation * pow(coneDot, " "lightExponent" << i << "); }\n" " else {\n" " attenuation = 0.0; }\n" " }\n" " }\n" << " df = max(0.0,attenuation*dot(N, " "-vertLightDirectionVC));\n" " accumulatedLightDiffuseColor += (df * lightColor" << i << ");\n" << " sf = sign(df)*attenuation*pow( max(0.0, dot( " "reflect(vertLightDirectionVC, N), normalize(-position))), " "fluidShininess);\n" " accumulatedLightSpecularColor += (sf * lightColor" << i << ");\n"; } vtkShaderProgram::Substitute(fssource, "//VTK::Light::Impl", toString.str(), false); break; } if (useIBL) { vtkShaderProgram::Substitute(fssource, "//VTK::UseIBL::Dec", "#define UseIBL", false); } this->QuadFinalBlend = new vtkOpenGLQuadHelper(renderWindow, nullptr, fssource.c_str(), ""); } else { renderWindow->GetShaderCache()->ReadyShaderProgram(this->QuadFinalBlend->Program); } const auto program = this->QuadFinalBlend->Program; assert(program); oren->UpdateLightingUniforms(program); // Add IBL textures if (useIBL) { program->SetUniformi("prefilterTex", oren->GetEnvMapPrefiltered()->GetTextureUnit()); program->SetUniformMatrix("invNormalMatrix", this->CamInvertedNorms); } this->TexBuffer[FluidEyeZ]->Activate(); program->SetUniformi("fluidZTexture", this->TexBuffer[FluidEyeZ]->GetTextureUnit()); this->TexBuffer[FluidThickness]->Activate(); program->SetUniformi( "fluidThicknessTexture", this->TexBuffer[FluidThickness]->GetTextureUnit()); this->TexBuffer[FluidNormal]->Activate(); program->SetUniformi("fluidNormalTexture", this->TexBuffer[FluidNormal]->GetTextureUnit()); this->TexBuffer[OpaqueRGBA]->Activate(); program->SetUniformi("opaqueRGBATexture", this->TexBuffer[OpaqueRGBA]->GetTextureUnit()); if (this->HasVertexColor) { this->OptionalTexBuffer[Color]->Activate(); program->SetUniformi("fluidColorTexture", this->OptionalTexBuffer[Color]->GetTextureUnit()); program->SetUniformi("hasVertexColor", this->HasVertexColor); program->SetUniformf("vertexColorPower", this->ParticleColorPower); program->SetUniformf("vertexColorScale", this->ParticleColorScale); } program->SetUniformMatrix("DCVCMatrix", this->CamDCVC); program->SetUniformMatrix("VCDCMatrix", this->CamVCDC); if (this->QuadFinalBlend->Program->IsUniformUsed("MCVCMatrix")) { if (!vol->GetIsIdentity()) { vtkMatrix4x4* mcwc; vtkMatrix3x3* anorms; ((vtkOpenGLActor*)vol)->GetKeyMatrices(mcwc, anorms); vtkMatrix4x4::Multiply4x4(mcwc, this->CamWCVC, this->TempMatrix4); this->QuadFinalBlend->Program->SetUniformMatrix("MCVCMatrix", this->TempMatrix4); } else { this->QuadFinalBlend->Program->SetUniformMatrix("MCVCMatrix", this->CamWCVC); } } program->SetUniformi("displayModeOpaqueSurface", this->DisplayMode == UnfilteredOpaqueSurface || this->DisplayMode == FilteredOpaqueSurface); program->SetUniformi("displayModeSurfaceNormal", this->DisplayMode == UnfilteredSurfaceNormal || this->DisplayMode == FilteredSurfaceNormal); program->SetUniformf("attenuationScale", this->AttenuationScale); program->SetUniformf("additionalReflection", this->AdditionalReflection); program->SetUniformf("refractiveIndex", this->RefractiveIndex); program->SetUniformf("refractionScale", this->RefractionScale); program->SetUniform3f("fluidOpaqueColor", this->OpaqueColor); program->SetUniform3f("fluidAttenuationColor", this->AttenuationColor); program->SetUniformf("farZValue", -crange[1]); program->SetUniformf("ambientValue", vol->GetProperty()->GetAmbient()); glState->vtkglEnable(GL_DEPTH_TEST); glState->vtkglDepthMask(GL_TRUE); glState->vtkglDepthFunc(GL_ALWAYS); this->QuadFinalBlend->Render(); this->TexBuffer[OpaqueZ]->Deactivate(); this->TexBuffer[OpaqueRGBA]->Deactivate(); this->TexBuffer[FluidEyeZ]->Deactivate(); this->TexBuffer[FluidThickness]->Deactivate(); this->TexBuffer[FluidNormal]->Deactivate(); if (this->HasVertexColor) { this->OptionalTexBuffer[Color]->Deactivate(); } glState->vtkglDepthFunc(GL_LEQUAL); } } //------------------------------------------------------------------------------ void vtkOpenGLFluidMapper::RenderParticles(vtkRenderer* renderer, vtkVolume* vol) { vtkPolyData* input = vtkPolyData::SafeDownCast(GetInputDataObject(0, 0)); if (input == nullptr || input->GetPoints() == nullptr) { return; } if (this->VBOBuildTime < input->GetPoints()->GetMTime()) { this->VBOs->CacheDataArray("vertexMC", input->GetPoints()->GetData(), renderer, VTK_FLOAT); if (this->HasVertexColor) { int cellFlag = 0; vtkDataArray* scalars = this->GetScalars( input, this->ScalarMode, this->ArrayAccessMode, this->ArrayId, this->ArrayName, cellFlag); this->VBOs->CacheDataArray("vertexColor", scalars, renderer, VTK_FLOAT); } this->VBOs->BuildAllVBOs(renderer); vtkIdType numPts = input->GetPoints()->GetNumberOfPoints(); this->GLHelperDepthThickness.IBO->IndexCount = static_cast<size_t>(numPts); this->VBOBuildTime.Modified(); } // draw polygons int numVerts = this->VBOs->GetNumberOfTuples("vertexMC"); if (numVerts) { // First we do the triangles, update the shader, set uniforms, etc. this->UpdateDepthThicknessColorShaders(this->GLHelperDepthThickness, renderer, vol); glDrawArrays(GL_POINTS, 0, static_cast<GLsizei>(numVerts)); } } //------------------------------------------------------------------------------ // Description: // Destructor. Delete SourceCode if any. void vtkOpenGLFluidMapper::ReleaseGraphicsResources(vtkWindow* w) { if (this->FBFluidEyeZ != nullptr) { this->FBFluidEyeZ->ReleaseGraphicsResources(w); this->FBFluidEyeZ->UnRegister(this); this->FBFluidEyeZ = nullptr; } if (this->FBThickness != nullptr) { this->FBThickness->ReleaseGraphicsResources(w); this->FBThickness->UnRegister(this); this->FBThickness = nullptr; } if (this->FBFilterThickness != nullptr) { this->FBFilterThickness->ReleaseGraphicsResources(w); this->FBFilterThickness->UnRegister(this); this->FBFilterThickness = nullptr; } if (this->FBCompNormal != nullptr) { this->FBCompNormal->ReleaseGraphicsResources(w); this->FBCompNormal->UnRegister(this); this->FBCompNormal = nullptr; } if (this->FBFilterDepth != nullptr) { this->FBFilterDepth->ReleaseGraphicsResources(w); this->FBFilterDepth->UnRegister(this); this->FBFilterDepth = nullptr; } if (this->QuadThicknessFilter != nullptr) { delete this->QuadThicknessFilter; this->QuadThicknessFilter = nullptr; } if (this->QuadFluidNormal != nullptr) { delete this->QuadFluidNormal; this->QuadFluidNormal = nullptr; } if (this->QuadFinalBlend != nullptr) { delete this->QuadFinalBlend; this->QuadFinalBlend = nullptr; } for (int i = 0; i < this->NumFilterMethods; ++i) { if (this->QuadFluidDepthFilter[i] != nullptr) { delete this->QuadFluidDepthFilter[i]; this->QuadFluidDepthFilter[i] = nullptr; } } this->VBOs->ReleaseGraphicsResources(w); for (int i = 0; i < NumTexBuffers; ++i) { this->TexBuffer[i]->ReleaseGraphicsResources(w); } for (int i = 0; i < NumOptionalTexBuffers; ++i) { this->OptionalTexBuffer[i]->ReleaseGraphicsResources(w); } this->GLHelperDepthThickness.ReleaseGraphicsResources(w); this->Modified(); }
{ "pile_set_name": "Github" }
// Code generated by protoc-gen-go. DO NOT EDIT. // source: google.golang.org/appengine/internal/base/api_base.proto package base import proto "github.com/golang/protobuf/proto" import fmt "fmt" import math "math" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package type StringProto struct { Value *string `protobuf:"bytes,1,req,name=value" json:"value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *StringProto) Reset() { *m = StringProto{} } func (m *StringProto) String() string { return proto.CompactTextString(m) } func (*StringProto) ProtoMessage() {} func (*StringProto) Descriptor() ([]byte, []int) { return fileDescriptor_api_base_9d49f8792e0c1140, []int{0} } func (m *StringProto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_StringProto.Unmarshal(m, b) } func (m *StringProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_StringProto.Marshal(b, m, deterministic) } func (dst *StringProto) XXX_Merge(src proto.Message) { xxx_messageInfo_StringProto.Merge(dst, src) } func (m *StringProto) XXX_Size() int { return xxx_messageInfo_StringProto.Size(m) } func (m *StringProto) XXX_DiscardUnknown() { xxx_messageInfo_StringProto.DiscardUnknown(m) } var xxx_messageInfo_StringProto proto.InternalMessageInfo func (m *StringProto) GetValue() string { if m != nil && m.Value != nil { return *m.Value } return "" } type Integer32Proto struct { Value *int32 `protobuf:"varint,1,req,name=value" json:"value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Integer32Proto) Reset() { *m = Integer32Proto{} } func (m *Integer32Proto) String() string { return proto.CompactTextString(m) } func (*Integer32Proto) ProtoMessage() {} func (*Integer32Proto) Descriptor() ([]byte, []int) { return fileDescriptor_api_base_9d49f8792e0c1140, []int{1} } func (m *Integer32Proto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Integer32Proto.Unmarshal(m, b) } func (m *Integer32Proto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Integer32Proto.Marshal(b, m, deterministic) } func (dst *Integer32Proto) XXX_Merge(src proto.Message) { xxx_messageInfo_Integer32Proto.Merge(dst, src) } func (m *Integer32Proto) XXX_Size() int { return xxx_messageInfo_Integer32Proto.Size(m) } func (m *Integer32Proto) XXX_DiscardUnknown() { xxx_messageInfo_Integer32Proto.DiscardUnknown(m) } var xxx_messageInfo_Integer32Proto proto.InternalMessageInfo func (m *Integer32Proto) GetValue() int32 { if m != nil && m.Value != nil { return *m.Value } return 0 } type Integer64Proto struct { Value *int64 `protobuf:"varint,1,req,name=value" json:"value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *Integer64Proto) Reset() { *m = Integer64Proto{} } func (m *Integer64Proto) String() string { return proto.CompactTextString(m) } func (*Integer64Proto) ProtoMessage() {} func (*Integer64Proto) Descriptor() ([]byte, []int) { return fileDescriptor_api_base_9d49f8792e0c1140, []int{2} } func (m *Integer64Proto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_Integer64Proto.Unmarshal(m, b) } func (m *Integer64Proto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_Integer64Proto.Marshal(b, m, deterministic) } func (dst *Integer64Proto) XXX_Merge(src proto.Message) { xxx_messageInfo_Integer64Proto.Merge(dst, src) } func (m *Integer64Proto) XXX_Size() int { return xxx_messageInfo_Integer64Proto.Size(m) } func (m *Integer64Proto) XXX_DiscardUnknown() { xxx_messageInfo_Integer64Proto.DiscardUnknown(m) } var xxx_messageInfo_Integer64Proto proto.InternalMessageInfo func (m *Integer64Proto) GetValue() int64 { if m != nil && m.Value != nil { return *m.Value } return 0 } type BoolProto struct { Value *bool `protobuf:"varint,1,req,name=value" json:"value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *BoolProto) Reset() { *m = BoolProto{} } func (m *BoolProto) String() string { return proto.CompactTextString(m) } func (*BoolProto) ProtoMessage() {} func (*BoolProto) Descriptor() ([]byte, []int) { return fileDescriptor_api_base_9d49f8792e0c1140, []int{3} } func (m *BoolProto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_BoolProto.Unmarshal(m, b) } func (m *BoolProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_BoolProto.Marshal(b, m, deterministic) } func (dst *BoolProto) XXX_Merge(src proto.Message) { xxx_messageInfo_BoolProto.Merge(dst, src) } func (m *BoolProto) XXX_Size() int { return xxx_messageInfo_BoolProto.Size(m) } func (m *BoolProto) XXX_DiscardUnknown() { xxx_messageInfo_BoolProto.DiscardUnknown(m) } var xxx_messageInfo_BoolProto proto.InternalMessageInfo func (m *BoolProto) GetValue() bool { if m != nil && m.Value != nil { return *m.Value } return false } type DoubleProto struct { Value *float64 `protobuf:"fixed64,1,req,name=value" json:"value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *DoubleProto) Reset() { *m = DoubleProto{} } func (m *DoubleProto) String() string { return proto.CompactTextString(m) } func (*DoubleProto) ProtoMessage() {} func (*DoubleProto) Descriptor() ([]byte, []int) { return fileDescriptor_api_base_9d49f8792e0c1140, []int{4} } func (m *DoubleProto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_DoubleProto.Unmarshal(m, b) } func (m *DoubleProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_DoubleProto.Marshal(b, m, deterministic) } func (dst *DoubleProto) XXX_Merge(src proto.Message) { xxx_messageInfo_DoubleProto.Merge(dst, src) } func (m *DoubleProto) XXX_Size() int { return xxx_messageInfo_DoubleProto.Size(m) } func (m *DoubleProto) XXX_DiscardUnknown() { xxx_messageInfo_DoubleProto.DiscardUnknown(m) } var xxx_messageInfo_DoubleProto proto.InternalMessageInfo func (m *DoubleProto) GetValue() float64 { if m != nil && m.Value != nil { return *m.Value } return 0 } type BytesProto struct { Value []byte `protobuf:"bytes,1,req,name=value" json:"value,omitempty"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *BytesProto) Reset() { *m = BytesProto{} } func (m *BytesProto) String() string { return proto.CompactTextString(m) } func (*BytesProto) ProtoMessage() {} func (*BytesProto) Descriptor() ([]byte, []int) { return fileDescriptor_api_base_9d49f8792e0c1140, []int{5} } func (m *BytesProto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_BytesProto.Unmarshal(m, b) } func (m *BytesProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_BytesProto.Marshal(b, m, deterministic) } func (dst *BytesProto) XXX_Merge(src proto.Message) { xxx_messageInfo_BytesProto.Merge(dst, src) } func (m *BytesProto) XXX_Size() int { return xxx_messageInfo_BytesProto.Size(m) } func (m *BytesProto) XXX_DiscardUnknown() { xxx_messageInfo_BytesProto.DiscardUnknown(m) } var xxx_messageInfo_BytesProto proto.InternalMessageInfo func (m *BytesProto) GetValue() []byte { if m != nil { return m.Value } return nil } type VoidProto struct { XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` XXX_sizecache int32 `json:"-"` } func (m *VoidProto) Reset() { *m = VoidProto{} } func (m *VoidProto) String() string { return proto.CompactTextString(m) } func (*VoidProto) ProtoMessage() {} func (*VoidProto) Descriptor() ([]byte, []int) { return fileDescriptor_api_base_9d49f8792e0c1140, []int{6} } func (m *VoidProto) XXX_Unmarshal(b []byte) error { return xxx_messageInfo_VoidProto.Unmarshal(m, b) } func (m *VoidProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return xxx_messageInfo_VoidProto.Marshal(b, m, deterministic) } func (dst *VoidProto) XXX_Merge(src proto.Message) { xxx_messageInfo_VoidProto.Merge(dst, src) } func (m *VoidProto) XXX_Size() int { return xxx_messageInfo_VoidProto.Size(m) } func (m *VoidProto) XXX_DiscardUnknown() { xxx_messageInfo_VoidProto.DiscardUnknown(m) } var xxx_messageInfo_VoidProto proto.InternalMessageInfo func init() { proto.RegisterType((*StringProto)(nil), "appengine.base.StringProto") proto.RegisterType((*Integer32Proto)(nil), "appengine.base.Integer32Proto") proto.RegisterType((*Integer64Proto)(nil), "appengine.base.Integer64Proto") proto.RegisterType((*BoolProto)(nil), "appengine.base.BoolProto") proto.RegisterType((*DoubleProto)(nil), "appengine.base.DoubleProto") proto.RegisterType((*BytesProto)(nil), "appengine.base.BytesProto") proto.RegisterType((*VoidProto)(nil), "appengine.base.VoidProto") } func init() { proto.RegisterFile("google.golang.org/appengine/internal/base/api_base.proto", fileDescriptor_api_base_9d49f8792e0c1140) } var fileDescriptor_api_base_9d49f8792e0c1140 = []byte{ // 199 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x6c, 0xcf, 0x3f, 0x4b, 0xc6, 0x30, 0x10, 0x06, 0x70, 0x5a, 0xad, 0xb4, 0x57, 0xe9, 0x20, 0x0e, 0x1d, 0xb5, 0x05, 0x71, 0x4a, 0x40, 0x45, 0x9c, 0x83, 0x8b, 0x9b, 0x28, 0x38, 0xb8, 0x48, 0x8a, 0xc7, 0x11, 0x08, 0xb9, 0x90, 0xa6, 0x82, 0xdf, 0x5e, 0xda, 0xd2, 0xfa, 0xc2, 0x9b, 0xed, 0xfe, 0xfc, 0xe0, 0xe1, 0x81, 0x27, 0x62, 0x26, 0x8b, 0x82, 0xd8, 0x6a, 0x47, 0x82, 0x03, 0x49, 0xed, 0x3d, 0x3a, 0x32, 0x0e, 0xa5, 0x71, 0x11, 0x83, 0xd3, 0x56, 0x0e, 0x7a, 0x44, 0xa9, 0xbd, 0xf9, 0x9a, 0x07, 0xe1, 0x03, 0x47, 0xbe, 0x68, 0x76, 0x27, 0xe6, 0x6b, 0xd7, 0x43, 0xfd, 0x1e, 0x83, 0x71, 0xf4, 0xba, 0xbc, 0x2f, 0xa1, 0xf8, 0xd1, 0x76, 0xc2, 0x36, 0xbb, 0xca, 0x6f, 0xab, 0xb7, 0x75, 0xe9, 0x6e, 0xa0, 0x79, 0x71, 0x11, 0x09, 0xc3, 0xfd, 0x5d, 0xc2, 0x15, 0xc7, 0xee, 0xf1, 0x21, 0xe1, 0x4e, 0x36, 0x77, 0x0d, 0x95, 0x62, 0xb6, 0x09, 0x52, 0x6e, 0xa4, 0x87, 0xfa, 0x99, 0xa7, 0xc1, 0x62, 0x02, 0x65, 0xff, 0x79, 0xa0, 0x7e, 0x23, 0x8e, 0xab, 0x69, 0x0f, 0xcd, 0xb9, 0xca, 0xcb, 0xdd, 0xd5, 0x50, 0x7d, 0xb0, 0xf9, 0x5e, 0x98, 0x3a, 0xfb, 0x3c, 0x9d, 0x9b, 0xff, 0x05, 0x00, 0x00, 0xff, 0xff, 0xba, 0x37, 0x25, 0xea, 0x44, 0x01, 0x00, 0x00, }
{ "pile_set_name": "Github" }
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !gccgo #include "textflag.h" // func getisar0() uint64 TEXT ·getisar0(SB),NOSPLIT,$0-8 // get Instruction Set Attributes 0 into x0 // mrs x0, ID_AA64ISAR0_EL1 = d5380600 WORD $0xd5380600 MOVD R0, ret+0(FP) RET // func getisar1() uint64 TEXT ·getisar1(SB),NOSPLIT,$0-8 // get Instruction Set Attributes 1 into x0 // mrs x0, ID_AA64ISAR1_EL1 = d5380620 WORD $0xd5380620 MOVD R0, ret+0(FP) RET // func getpfr0() uint64 TEXT ·getpfr0(SB),NOSPLIT,$0-8 // get Processor Feature Register 0 into x0 // mrs x0, ID_AA64PFR0_EL1 = d5380400 WORD $0xd5380400 MOVD R0, ret+0(FP) RET
{ "pile_set_name": "Github" }
name: range-v3 CI # Trigger on pushes to all branches and for all pull-requests on: [push, pull_request] env: CMAKE_VERSION: 3.16.2 NINJA_VERSION: 1.9.0 jobs: build: name: ${{ matrix.config.name }} runs-on: ${{ matrix.config.os }} strategy: fail-fast: false matrix: config: # GCC-6 - { name: "Linux GCC 6 Debug (C++14)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "gcc-6", cxx: "g++-6", cxx_standard: 14, cxx_concepts: false } - { name: "Linux GCC 6 Release (C++14)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-6", cxx: "g++-6", cxx_standard: 14, cxx_concepts: false } - { name: "Linux GCC 6 Debug (C++17)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "gcc-6", cxx: "g++-6", cxx_standard: 17, cxx_concepts: false } - { name: "Linux GCC 6 Release (C++17)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-6", cxx: "g++-6", cxx_standard: 17, cxx_concepts: false } - { name: "Linux GCC 6 Release (C++17, Concepts)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-6", cxx: "g++-6", cxx_standard: 17, } # GCC-7 - { name: "Linux GCC 7 Debug (C++14)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "gcc-7", cxx: "g++-7", cxx_standard: 14, cxx_concepts: false } - { name: "Linux GCC 7 Release (C++14)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-7", cxx: "g++-7", cxx_standard: 14, cxx_concepts: false } - { name: "Linux GCC 7 Debug (C++17)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "gcc-7", cxx: "g++-7", cxx_standard: 17, cxx_concepts: false } - { name: "Linux GCC 7 Release (C++17)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-7", cxx: "g++-7", cxx_standard: 17, cxx_concepts: false } - { name: "Linux GCC 7 Release (C++17, Concepts)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-7", cxx: "g++-7", cxx_standard: 17, } # GCC-8 - { name: "Linux GCC 8 Debug (C++14)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "gcc-8", cxx: "g++-8", cxx_standard: 14, cxx_concepts: false } - { name: "Linux GCC 8 Release (C++14)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-8", cxx: "g++-8", cxx_standard: 14, cxx_concepts: false } - { name: "Linux GCC 8 Debug (C++17)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "gcc-8", cxx: "g++-8", cxx_standard: 17, cxx_concepts: false } - { name: "Linux GCC 8 Release (C++17)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-8", cxx: "g++-8", cxx_standard: 17, cxx_concepts: false } - { name: "Linux GCC 8 Release (C++17, Concepts)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-8", cxx: "g++-8", cxx_standard: 17, } # GCC-9 - { name: "Linux GCC 9 Debug (C++17)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "gcc-9", cxx: "g++-9", cxx_standard: 17, cxx_concepts: false } - { name: "Linux GCC 9 Release (C++17)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-9", cxx: "g++-9", cxx_standard: 17, cxx_concepts: false } - { name: "Linux GCC 9 Debug (C++20)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "gcc-9", cxx: "g++-9", cxx_standard: 20, cxx_concepts: false } - { name: "Linux GCC 9 Release (C++20)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-9", cxx: "g++-9", cxx_standard: 20, cxx_concepts: false } - { name: "Linux GCC 9 Release (C++20, Concepts)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "gcc-9", cxx: "g++-9", cxx_standard: 20, } # Clang-5.0 - { name: "Linux Clang 5.0 Debug (C++14 / libc++ / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-5.0", cxx: "clang++-5.0", cxx_standard: 14, cxx_asan: true, libcxx: true } - { name: "Linux Clang 5.0 Debug (C++17 / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-5.0", cxx: "clang++-5.0", cxx_standard: 17, cxx_asan: true, } - { name: "Linux Clang 5.0 Debug (C++20 / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-5.0", cxx: "clang++-5.0", cxx_standard: 20, cxx_asan: true, } # Clang-6.0 - { name: "Linux Clang 6.0 Debug (C++14 / libc++ / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-6.0", cxx: "clang++-6.0", cxx_standard: 14, cxx_asan: true, libcxx: true } - { name: "Linux Clang 6.0 Debug (C++17 / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-6.0", cxx: "clang++-6.0", cxx_standard: 17, cxx_asan: true, } - { name: "Linux Clang 6.0 Debug (C++20 / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-6.0", cxx: "clang++-6.0", cxx_standard: 20, cxx_asan: true, } # Clang-8 - { name: "Linux Clang 8 Debug (C++14 / libc++ / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-8", cxx: "clang++-8", cxx_standard: 14, cxx_asan: true, libcxx: true } - { name: "Linux Clang 8 Debug (C++17 / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-8", cxx: "clang++-8", cxx_standard: 17, cxx_asan: true, } - { name: "Linux Clang 8 Debug (C++20 / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-8", cxx: "clang++-8", cxx_standard: 20, cxx_asan: true, } # Clang-9 - { name: "Linux Clang 9 Debug (C++17 / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-9", cxx: "clang++-9", cxx_standard: 17, cxx_asan: true, } - { name: "Linux Clang 9 Release (C++17)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "clang-9", cxx: "clang++-9", cxx_standard: 17, } - { name: "Linux Clang 9 Debug (C++20 / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-9", cxx: "clang++-9", cxx_standard: 20, cxx_asan: true, } - { name: "Linux Clang 9 Release (C++20)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "clang-9", cxx: "clang++-9", cxx_standard: 20, } # Clang-10 - { name: "Linux Clang 10 Debug (C++20 / ASAN)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: Debug, cc: "clang-10", cxx: "clang++-10", cxx_standard: 20, cxx_asan: true, cxx_concepts: false } - { name: "Linux Clang 10 Release (C++20 / Concepts)", artifact: "Linux.tar.xz", os: ubuntu-latest, build_type: RelWithDebInfo, cc: "clang-10", cxx: "clang++-10", cxx_standard: 20, } # AppleClang - { name: "macOS Clang Debug (C++17)", artifact: "macOS.tar.xz", os: macos-latest, build_type: Debug, cc: "clang", cxx: "clang++", cxx_standard: 17, cxx_asan: true, } - { name: "macOS Clang Release (C++17)", artifact: "macOS.tar.xz", os: macos-latest, build_type: RelWithDebInfo, cc: "clang", cxx: "clang++", cxx_standard: 17, } - { name: "macOS Clang Debug (C++20 / ASAN)", artifact: "macOS.tar.xz", os: macos-latest, build_type: Debug, cc: "clang", cxx: "clang++", cxx_standard: 20, cxx_asan: true, } - { name: "macOS Clang Release (C++20)", artifact: "macOS.tar.xz", os: macos-latest, build_type: RelWithDebInfo, cc: "clang", cxx: "clang++", cxx_standard: 20, } # MSVC 2019 - { name: "Windows MSVC 2019 Debug (C++17)", artifact: "Windows-MSVC.tar.xz", os: windows-latest, build_type: Debug, cc: "cl", cxx: "cl", environment_script: "C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build/vcvars64.bat", cxx_standard: 17, } - { name: "Windows MSVC 2019 Release (C++17)", artifact: "Windows-MSVC.tar.xz", os: windows-latest, build_type: RelWithDebInfo, cc: "cl", cxx: "cl", environment_script: "C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build/vcvars64.bat", cxx_standard: 17, } - { name: "Windows MSVC 2019 Debug (C++20)", artifact: "Windows-MSVC.tar.xz", os: windows-latest, build_type: Debug, cc: "cl", cxx: "cl", environment_script: "C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build/vcvars64.bat", cxx_standard: 20, } - { name: "Windows MSVC 2019 Release (C++20)", artifact: "Windows-MSVC.tar.xz", os: windows-latest, build_type: RelWithDebInfo, cc: "cl", cxx: "cl", environment_script: "C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build/vcvars64.bat", cxx_standard: 20, } steps: - uses: actions/checkout@v1 - name: Download Ninja and CMake id: cmake_and_ninja shell: cmake -P {0} run: | set(cmake_version $ENV{CMAKE_VERSION}) set(ninja_version $ENV{NINJA_VERSION}) message(STATUS "Using host CMake version: ${CMAKE_VERSION}") if ("${{ runner.os }}" STREQUAL "Windows") set(ninja_suffix "win.zip") set(cmake_suffix "win64-x64.zip") set(cmake_dir "cmake-${cmake_version}-win64-x64/bin") elseif ("${{ runner.os }}" STREQUAL "Linux") set(ninja_suffix "linux.zip") set(cmake_suffix "Linux-x86_64.tar.gz") set(cmake_dir "cmake-${cmake_version}-Linux-x86_64/bin") elseif ("${{ runner.os }}" STREQUAL "macOS") set(ninja_suffix "mac.zip") set(cmake_suffix "Darwin-x86_64.tar.gz") set(cmake_dir "cmake-${cmake_version}-Darwin-x86_64/CMake.app/Contents/bin") endif() set(ninja_url "https://github.com/ninja-build/ninja/releases/download/v${ninja_version}/ninja-${ninja_suffix}") file(DOWNLOAD "${ninja_url}" ./ninja.zip SHOW_PROGRESS) execute_process(COMMAND ${CMAKE_COMMAND} -E tar xvf ./ninja.zip) set(cmake_url "https://github.com/Kitware/CMake/releases/download/v${cmake_version}/cmake-${cmake_version}-${cmake_suffix}") file(DOWNLOAD "${cmake_url}" ./cmake.zip SHOW_PROGRESS) execute_process(COMMAND ${CMAKE_COMMAND} -E tar xvf ./cmake.zip) # Save the path for other steps file(TO_CMAKE_PATH "$ENV{GITHUB_WORKSPACE}/${cmake_dir}" cmake_dir) message("::set-output name=cmake_dir::${cmake_dir}") if (NOT "${{ runner.os }}" STREQUAL "Windows") execute_process( COMMAND chmod +x ninja COMMAND chmod +x ${cmake_dir}/cmake ) endif() - name: Install GCC 6 id: install_gcc_6 if: startsWith(matrix.config.os, 'ubuntu') && ( matrix.config.cxx == 'g++-6' ) shell: bash working-directory: ${{ env.HOME }} run: | sudo apt-get install -y gcc-6 g++-6 - name: Install Clang 5 id: install_clang_5 if: startsWith(matrix.config.os, 'ubuntu') && ( matrix.config.cxx == 'clang++-5.0' ) shell: bash working-directory: ${{ env.HOME }} run: | wget -O - https://apt.llvm.org/llvm-snapshot.gpg.key 2>/dev/null | sudo apt-key add - sudo add-apt-repository 'deb http://apt.llvm.org/bionic/ llvm-toolchain-bionic-5.0 main' -y sudo apt-get update -q sudo apt-get install -y clang-5.0 - name: Install Clang 10 id: install_clang_10 if: startsWith(matrix.config.os, 'ubuntu') && ( matrix.config.cxx == 'clang++-10' ) shell: bash working-directory: ${{ env.HOME }} run: | wget https://apt.llvm.org/llvm.sh chmod +x llvm.sh sudo ./llvm.sh 10 - name: Install libc++ id: install_libcxx if: matrix.config.libcxx shell: bash working-directory: ${{ env.HOME }} env: CC: ${{ matrix.config.cc }} CXX: ${{ matrix.config.cxx }} run: | $GITHUB_WORKSPACE/install_libcxx.sh - name: Configure shell: cmake -P {0} run: | set(ENV{CC} ${{ matrix.config.cc }}) set(ENV{CXX} ${{ matrix.config.cxx }}) if ("${{ runner.os }}" STREQUAL "Windows" AND NOT "x${{ matrix.config.environment_script }}" STREQUAL "x") execute_process( COMMAND "${{ matrix.config.environment_script }}" && set OUTPUT_FILE environment_script_output.txt ) set(cxx_flags "/permissive- /EHsc") file(STRINGS environment_script_output.txt output_lines) foreach(line IN LISTS output_lines) if (line MATCHES "^([a-zA-Z0-9_-]+)=(.*)$") set(ENV{${CMAKE_MATCH_1}} "${CMAKE_MATCH_2}") endif() endforeach() endif() set(path_separator ":") if ("${{ runner.os }}" STREQUAL "Windows") set(path_separator ";") endif() set(ENV{PATH} "$ENV{GITHUB_WORKSPACE}${path_separator}$ENV{PATH}") if ("x${{ matrix.config.libcxx }}" STREQUAL "xtrue") set(cxx_flags "${cxx_flags} -stdlib=libc++ -nostdinc++ -cxx-isystem $ENV{GITHUB_WORKSPACE}/llvm/include/c++/v1/ -Wno-unused-command-line-argument") set(link_flags "${link_flags} -L $ENV{GITHUB_WORKSPACE}/llvm/lib -Wl,-rpath,$ENV{GITHUB_WORKSPACE}/llvm/lib -lc++abi") endif() if ("x${{ matrix.config.cxx_asan }}" STREQUAL "xtrue") set(cxx_flags "${cxx_flags} -fsanitize=address -fno-omit-frame-pointer") endif() set(cxx_concepts ON) if ("x${{ matrix.config.cxx_concepts }}" STREQUAL "xfalse") set(cxx_concepts OFF) endif() execute_process( COMMAND ${{ steps.cmake_and_ninja.outputs.cmake_dir }}/cmake -S . -B build -G Ninja -D CMAKE_BUILD_TYPE=${{ matrix.config.build_type }} -D CMAKE_MAKE_PROGRAM:STRING=ninja -D CMAKE_CXX_STANDARD:STRING=${{ matrix.config.cxx_standard }} -D "CMAKE_CXX_FLAGS:STRING=${cxx_flags}" -D "CMAKE_EXE_LINKER_FLAGS:STRING=${link_flags}" -D CMAKE_VERBOSE_MAKEFILE:BOOL=ON -D RANGE_V3_HEADER_CHECKS:BOOL=ON -D RANGES_PREFER_REAL_CONCEPTS:BOOL=${cxx_concepts} ${{ matrix.config.cmake_args }} ${extra_cmake_args} RESULT_VARIABLE result ) if (NOT result EQUAL 0) message(FATAL_ERROR "Bad exit status") endif() - name: Build shell: cmake -P {0} continue-on-error: ${{ matrix.config.experimental || false }} run: | set(ENV{NINJA_STATUS} "[%f/%t %o/sec] ") if ("${{ runner.os }}" STREQUAL "Windows" AND NOT "x${{ matrix.config.environment_script }}" STREQUAL "x") file(STRINGS environment_script_output.txt output_lines) foreach(line IN LISTS output_lines) if (line MATCHES "^([a-zA-Z0-9_-]+)=(.*)$") set(ENV{${CMAKE_MATCH_1}} "${CMAKE_MATCH_2}") endif() endforeach() endif() set(path_separator ":") if ("${{ runner.os }}" STREQUAL "Windows") set(path_separator ";") endif() set(ENV{PATH} "$ENV{GITHUB_WORKSPACE}${path_separator}$ENV{PATH}") execute_process( COMMAND ${{ steps.cmake_and_ninja.outputs.cmake_dir }}/cmake --build build RESULT_VARIABLE result ) if (NOT result EQUAL 0) message(FATAL_ERROR "Bad exit status") endif() - name: Run tests shell: cmake -P {0} continue-on-error: ${{ matrix.config.experimental || false }} run: | include(ProcessorCount) ProcessorCount(N) set(ENV{CTEST_OUTPUT_ON_FAILURE} "ON") execute_process( COMMAND ${{ steps.cmake_and_ninja.outputs.cmake_dir }}/ctest --verbose -j ${N} WORKING_DIRECTORY build RESULT_VARIABLE result ) if (NOT result EQUAL 0) message(FATAL_ERROR "Running tests failed!") endif()
{ "pile_set_name": "Github" }
/*- * #%L * This file is part of QuPath. * %% * Copyright (C) 2014 - 2016 The Queen's University of Belfast, Northern Ireland * Contact: IP Management ([email protected]) * Copyright (C) 2018 - 2020 QuPath developers, The University of Edinburgh * %% * QuPath 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. * * QuPath 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 QuPath. If not, see <https://www.gnu.org/licenses/>. * #L% */ package qupath.lib.objects; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import qupath.lib.measurements.MeasurementList; import qupath.lib.objects.classes.PathClass; import qupath.lib.objects.classes.PathClassFactory; import qupath.lib.roi.interfaces.ROI; /** * Abstract class used for PathObjects that have ROIs associated with them. * <p> * In practice, this is almost all PathObjects (with the notable exception of PathRootObjects). * * @author Pete Bankhead * */ public abstract class PathROIObject extends PathObject { private static Logger logger = LoggerFactory.getLogger(PathROIObject.class); private static final long serialVersionUID = 1L; private PathClass pathClass = null; private ROI pathROI = null; private double classProbability = Double.NaN; private boolean lockedROI = false; //J Lock to determine whether ROI is locked (set by user) PathROIObject() { super(); } PathROIObject(ROI pathROI, PathClass pc) { super(); this.pathROI = pathROI; setPathClass(pc); } PathROIObject(MeasurementList measurements) { super(measurements); } PathROIObject(ROI pathROI, PathClass pc, MeasurementList measurements) { super(measurements); this.pathROI = pathROI; setPathClass(pc); } /** * Set the ROI for this object. If this is called, one should remember to update any associated * hierarchy to notify it of the change. * @param roi */ public void setROI(final ROI roi) { if (roi == null) throw new IllegalArgumentException("PathROIObject.setROI cannot be called with null!"); if (this.pathROI != roi) { this.pathROI = roi; if (hasMeasurements()) getMeasurementList().clear(); } } /** * Set locked flag, indicating that the object ROI should not be modified. * It directly impacts on {@link #isEditable()} * <p> * Note that this is only a hint that other code should pay attention to - it is not * enforced locally. * <p> * TODO: Consider shifting this method into PathObject rather than PathROIObject (even * if it doesn't really do anything there). * * @param locked */ @Override public void setLocked(final boolean locked) { this.lockedROI = locked; } /** * Query the locked status for the object, indicating whether it should be editable or not. * * @return */ @Override public boolean isLocked() { return this.lockedROI; } /** * Currently, a ROI is editable if it isn't locked. * * TODO: Consider whether this is a good basis on which to make the decision! */ @Override public boolean isEditable() { // Note on commented out code (Pete): // Previous code that attempted to automatically set locked status (effectively) without storing it in a variable // Kind of worked for common use cases, but not a great long-term solution //J return !PathObjectTools.containsChildOfClass(this, PathDetectionObject.class, false) || getParent() == null || !getParent().isRootObject(); return !this.lockedROI; } @Override public void setPathClass(PathClass pathClass, double classProbability) { if (pathClass != null && !pathClass.isValid()) { logger.warn("Classification {} is invalid! Will be set to null instead", pathClass); pathClass = null; } if (pathClass == null) { // if (pathROI != null && this.pathClass != null && this.pathClass.getName().equals(pathROI.getName())) // pathROI.setName(null); this.pathClass = pathClass; this.classProbability = classProbability; return; } // if (pathROI != null) { // pathROI.setName(pathClass.getName()); // } this.pathClass = pathClass; this.classProbability = classProbability; // Forget any previous color, if we have a PathClass if (this.pathClass != null) setColorRGB(null); } @Override public double getClassProbability() { return classProbability; } @Override public PathClass getPathClass() { return pathClass; } @Override public ROI getROI() { return pathROI; } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeObject(Boolean.valueOf(lockedROI)); out.writeObject(pathClass); out.writeObject(pathROI); out.writeDouble(classProbability); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); // Another example of trying to extend serialization without breaking something else... // Forgot to store locked status previously... which wasn't good Object firstObject = in.readObject(); if (firstObject instanceof Boolean) { lockedROI = ((Boolean)firstObject).booleanValue(); firstObject = in.readObject(); } if (firstObject instanceof PathClass) pathClass = (PathClass)firstObject; // TODO: STORE PATHCLASSES AS STRINGS OR SOMETHING BETTER THAN JUST USING SERIALIZATION! // Go via the factory to ensure that we don't end up with multiple classes with the same name if (pathClass != null) pathClass = PathClassFactory.getSingletonPathClass(pathClass); pathROI = (ROI)in.readObject(); classProbability = in.readDouble(); } // @Override // public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { // super.readExternal(in); // // Object pathClassObject = in.readObject(); // if (pathClassObject instanceof PathClass) // pathClass = (PathClass)pathClassObject; // // TODO: STORE PATHCLASSES AS STRINGS OR SOMETHING BETTER THAN JUST USING SERIALIZATION! // // // Go via the factory to ensure that we don't end up with multiple classes with the same name // if (pathClass != null) // pathClass = PathClassFactory.getSingletonPathClass(pathClass); // pathROI = (ROI)in.readObject(); // classProbability = in.readDouble(); // } }
{ "pile_set_name": "Github" }
/* * Copyright 2013-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudfoundry.client.v2.spaces; import org.junit.Test; public final class CreateSpaceRequestTest { @Test(expected = IllegalStateException.class) public void noName() { CreateSpaceRequest.builder() .organizationId("test-organization-id") .build(); } @Test(expected = IllegalStateException.class) public void noOrganizationId() { CreateSpaceRequest.builder() .name("test-name") .build(); } @Test public void valid() { CreateSpaceRequest.builder() .name("test-name") .organizationId("test-organization-id") .build(); } }
{ "pile_set_name": "Github" }
__all__ = [ 'alias', 'bdist_egg', 'bdist_rpm', 'build_ext', 'build_py', 'develop', 'easy_install', 'egg_info', 'install', 'install_lib', 'rotate', 'saveopts', 'sdist', 'setopt', 'test', 'install_egg_info', 'install_scripts', 'register', 'bdist_wininst', 'upload_docs', 'upload', 'build_clib', 'dist_info', ] from distutils.command.bdist import bdist import sys from setuptools.command import install_scripts if 'egg' not in bdist.format_commands: bdist.format_command['egg'] = ('bdist_egg', "Python .egg file") bdist.format_commands.append('egg') del bdist, sys
{ "pile_set_name": "Github" }
/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2015] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_UTIL_PLATFORM_INFO_HPP #define REALM_UTIL_PLATFORM_INFO_HPP #include <string> namespace realm { namespace util { /// Get a description of the current system platform. /// /// Returns a space-separated concatenation of `osname`, `sysname`, `release`, /// `version`, and `machine` as returned by get_platform_info(PlatformInfo&). std::string get_platform_info(); struct PlatformInfo { std::string osname; ///< Equivalent to `uname -o` (Linux). std::string sysname; ///< Equivalent to `uname -s`. std::string release; ///< Equivalent to `uname -r`. std::string version; ///< Equivalent to `uname -v`. std::string machine; ///< Equivalent to `uname -m`. }; /// Get a description of the current system platform. void get_platform_info(PlatformInfo&); // Implementation inline std::string get_platform_info() { PlatformInfo info; get_platform_info(info); // Throws return (info.osname + " " + info.sysname + " " + info.release + " " + info.version + " " + info.machine); // Throws } } // namespace util } // namespace realm #endif // REALM_UTIL_PLATFORM_INFO_HPP
{ "pile_set_name": "Github" }
/* * Stowaway keyboard driver for Linux */ /* * Copyright (c) 2006 Marek Vasut * * Based on Newton keyboard driver for Linux * by Justin Cormack */ /* * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Should you need to contact me, the author, you can do so either by * e-mail - mail your message to <[email protected]>, or by paper mail: * Marek Vasut, Liskovecka 559, Frydek-Mistek, 738 01 Czech Republic */ #include <linux/slab.h> #include <linux/module.h> #include <linux/input.h> #include <linux/init.h> #include <linux/serio.h> #define DRIVER_DESC "Stowaway keyboard driver" MODULE_AUTHOR("Marek Vasut <[email protected]>"); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL"); #define SKBD_KEY_MASK 0x7f #define SKBD_RELEASE 0x80 static unsigned char skbd_keycode[128] = { KEY_1, KEY_2, KEY_3, KEY_Z, KEY_4, KEY_5, KEY_6, KEY_7, 0, KEY_Q, KEY_W, KEY_E, KEY_R, KEY_T, KEY_Y, KEY_GRAVE, KEY_X, KEY_A, KEY_S, KEY_D, KEY_F, KEY_G, KEY_H, KEY_SPACE, KEY_CAPSLOCK, KEY_TAB, KEY_LEFTCTRL, 0, 0, 0, 0, 0, 0, 0, 0, KEY_LEFTALT, 0, 0, 0, 0, 0, 0, 0, 0, KEY_C, KEY_V, KEY_B, KEY_N, KEY_MINUS, KEY_EQUAL, KEY_BACKSPACE, KEY_HOME, KEY_8, KEY_9, KEY_0, KEY_ESC, KEY_LEFTBRACE, KEY_RIGHTBRACE, KEY_BACKSLASH, KEY_END, KEY_U, KEY_I, KEY_O, KEY_P, KEY_APOSTROPHE, KEY_ENTER, KEY_PAGEUP,0, KEY_J, KEY_K, KEY_L, KEY_SEMICOLON, KEY_SLASH, KEY_UP, KEY_PAGEDOWN, 0,KEY_M, KEY_COMMA, KEY_DOT, KEY_INSERT, KEY_DELETE, KEY_LEFT, KEY_DOWN, KEY_RIGHT, 0, 0, 0, KEY_LEFTSHIFT, KEY_RIGHTSHIFT, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, KEY_F1, KEY_F2, KEY_F3, KEY_F4, KEY_F5, KEY_F6, KEY_F7, KEY_F8, KEY_F9, KEY_F10, KEY_F11, KEY_F12, 0, 0, 0 }; struct skbd { unsigned char keycode[128]; struct input_dev *dev; struct serio *serio; char phys[32]; }; static irqreturn_t skbd_interrupt(struct serio *serio, unsigned char data, unsigned int flags) { struct skbd *skbd = serio_get_drvdata(serio); struct input_dev *dev = skbd->dev; if (skbd->keycode[data & SKBD_KEY_MASK]) { input_report_key(dev, skbd->keycode[data & SKBD_KEY_MASK], !(data & SKBD_RELEASE)); input_sync(dev); } return IRQ_HANDLED; } static int skbd_connect(struct serio *serio, struct serio_driver *drv) { struct skbd *skbd; struct input_dev *input_dev; int err = -ENOMEM; int i; skbd = kzalloc(sizeof(struct skbd), GFP_KERNEL); input_dev = input_allocate_device(); if (!skbd || !input_dev) goto fail1; skbd->serio = serio; skbd->dev = input_dev; snprintf(skbd->phys, sizeof(skbd->phys), "%s/input0", serio->phys); memcpy(skbd->keycode, skbd_keycode, sizeof(skbd->keycode)); input_dev->name = "Stowaway Keyboard"; input_dev->phys = skbd->phys; input_dev->id.bustype = BUS_RS232; input_dev->id.vendor = SERIO_STOWAWAY; input_dev->id.product = 0x0001; input_dev->id.version = 0x0100; input_dev->dev.parent = &serio->dev; input_dev->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REP); input_dev->keycode = skbd->keycode; input_dev->keycodesize = sizeof(unsigned char); input_dev->keycodemax = ARRAY_SIZE(skbd_keycode); for (i = 0; i < ARRAY_SIZE(skbd_keycode); i++) set_bit(skbd_keycode[i], input_dev->keybit); clear_bit(0, input_dev->keybit); serio_set_drvdata(serio, skbd); err = serio_open(serio, drv); if (err) goto fail2; err = input_register_device(skbd->dev); if (err) goto fail3; return 0; fail3: serio_close(serio); fail2: serio_set_drvdata(serio, NULL); fail1: input_free_device(input_dev); kfree(skbd); return err; } static void skbd_disconnect(struct serio *serio) { struct skbd *skbd = serio_get_drvdata(serio); serio_close(serio); serio_set_drvdata(serio, NULL); input_unregister_device(skbd->dev); kfree(skbd); } static struct serio_device_id skbd_serio_ids[] = { { .type = SERIO_RS232, .proto = SERIO_STOWAWAY, .id = SERIO_ANY, .extra = SERIO_ANY, }, { 0 } }; MODULE_DEVICE_TABLE(serio, skbd_serio_ids); static struct serio_driver skbd_drv = { .driver = { .name = "stowaway", }, .description = DRIVER_DESC, .id_table = skbd_serio_ids, .interrupt = skbd_interrupt, .connect = skbd_connect, .disconnect = skbd_disconnect, }; module_serio_driver(skbd_drv);
{ "pile_set_name": "Github" }
/* * Copyright (C) 2013 - 2020 Oracle and/or its affiliates. All rights reserved. */ package oracle.pgql.lang.ir; import static oracle.pgql.lang.ir.PgqlUtils.printIdentifier; public class SchemaQualifiedName { /** * The schema name. */ private String schemaName; /** * The local name; */ private String name; public SchemaQualifiedName(String schemaName, String name) { this.schemaName = schemaName; this.name = name; } public String getSchemaName() { return schemaName; } public void setSchemaName(String schemaName) { this.schemaName = schemaName; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String toString() { if (schemaName == null) { return printIdentifier(name); } else { return printIdentifier(schemaName) + "." + printIdentifier(name); } } @Override public int hashCode() { return 31; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SchemaQualifiedName other = (SchemaQualifiedName) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (schemaName == null) { if (other.schemaName != null) return false; } else if (!schemaName.equals(other.schemaName)) return false; return true; } }
{ "pile_set_name": "Github" }
#include "util/nowarnings.h" #ifdef AVH_SERVER #include "dlls/extdll.h" #include "dlls/util.h" #include "types.h" #endif #ifdef AVH_CLIENT #include "cl_dll/hud.h" #include "cl_dll/cl_util.h" #endif #include "mod/AvHSelectionHelper.h" #include "mod/AvHConstants.h" #ifdef AVH_SERVER #include "mod/AvHPlayer.h" #include "mod/AvHServerUtil.h" #include "mod/AvHEntities.h" #include "mod/AvHGamerules.h" #endif #include "pm_shared/pm_defs.h" #include "pm_shared/pm_shared.h" #ifdef AVH_CLIENT #include "pm_shared/pm_debug.h" extern DebugPointListType gTriDebugLocations; #endif #include "util/MathUtil.h" extern playermove_t *pmove; #include "mod/AvHSharedUtil.h" #include "common/vector_util.h" #ifdef AVH_CLIENT #include "cl_dll/eventscripts.h" #include "common/r_efx.h" #include "common/event_api.h" #include "common/event_args.h" #include "cl_dll/in_defs.h" #endif #include "mod/AvHSpecials.h" AvHSelectionHelper::AvHSelectionHelper() { this->mQueuedTeamNumber = TEAM_IND; this->mQueuedSelectionWaiting = false; this->mSelectionResultsWaiting = false; } void AvHSelectionHelper::ClearSelection() { ASSERT(this->mSelectionResults.size() == 0); this->mSelectionResults.clear(); this->mSelectionResultsWaiting = true; } void AvHSelectionHelper::GetAndClearSelection(EntityListType& outSelectedList) { ASSERT(this->mSelectionResultsWaiting); outSelectedList = this->mSelectionResults; this->mSelectionResults.clear(); this->mSelectionResultsWaiting = false; } void AvHSelectionHelper::ProcessPendingSelections() { if(this->mQueuedSelectionWaiting) { this->mSelectionResultsWaiting = this->SelectUnits(this->mQueuedPointOfView, this->mQueuedRayOne, this->mQueuedRayTwo, this->mQueuedTeamNumber, this->mSelectionResults); this->mQueuedSelectionWaiting = false; } } void AvHSelectionHelper::QueueSelection(const Vector& inPointOfView, const Vector& inStartRay, const Vector& inEndRay, AvHTeamNumber inTeamNumber) { this->mQueuedPointOfView = inPointOfView; this->mQueuedRayOne = inStartRay; this->mQueuedRayTwo = inEndRay; this->mQueuedTeamNumber = inTeamNumber; this->mQueuedSelectionWaiting = true; } bool AvHSelectionHelper::SelectionResultsWaiting() { return this->mSelectionResultsWaiting; } //#ifdef AVH_SERVER //void AvHSelectionHelper::SelectLocation(const Vector& inPointOfView, const Vector& inNormRay, Vector& outVector) //{ // TraceResult tr; // Vector theStartPos; // Vector theEndPos; // bool theSuccess = false; // bool theDone = false; // // VectorMA(inPointOfView, kSelectionStartRange, inNormRay, theStartPos); // VectorMA(inPointOfView, kSelectionEndRange, inNormRay, theEndPos); // // CBaseEntity* theEntityHit = NULL; // edict_t* theEdictToIgnore = NULL; // // do // { // UTIL_TraceLine(theStartPos, theEndPos, ignore_monsters, theEdictToIgnore, &tr); // //UTIL_TraceLine(theStartPos, theEndPos, dont_ignore_monsters, dont_ignore_glass, theEdictToIgnore, &tr); // //// theEntityHit = CBaseEntity::Instance(tr.pHit); //// AvHWaypoint* theGround = dynamic_cast<AvHWaypoint*>(theEntityHit); //// if(theGround) //// { //// VectorCopy(tr.vecEndPos, outVector); //// theSuccess = true; //// theDone = true; //// } // // if((tr.flFraction >= 1.0f) || (tr.flFraction < kFloatTolerance)) // { // theDone = true; // } // else // { // if(theEntityHit) // { // theEdictToIgnore = ENT(theEntityHit->pev); // } // VectorCopy(tr.vecEndPos, theStartPos); // } // } while(!theDone); //} //#endif //#ifdef AVH_CLIENT //void AvHSelectionHelper::SelectLocation(const Vector& inPointOfView, const Vector& inNormRay, Vector& outVector) //{ // // TODO: Change this to only return location when proper entity hit // pmtrace_t tr; // Vector theStartPos = inPointOfView; // Vector theEndPos = theStartPos + kSelectionEndRange*inNormRay; // Vector theResult; // // tr = *pmove->PM_TraceLine( (float *)&theStartPos, (float *)&theEndPos, PM_TRACELINE_ANYVISIBLE, 2 /*point sized hull*/, -1 ); // outVector = tr.endpos; //} //#endif bool AvHSelectionHelper::IsPositionInRegion(const Vector& inPosition, const Vector& inPointOfView, const Vector& inNormRayOne, const Vector& inNormRayTwo) { bool theSuccess = false; // Build normalized vector from eye to entity Vector theEyeToEntity; VectorSubtract(inPosition, inPointOfView, theEyeToEntity); VectorNormalize(theEyeToEntity); // Is vector between two other vectors? //if(IsVectorBetweenBoundingVectors(theEyeToEntity, inNormRayOne, inNormRayTwo)) //if(IsVectorBetweenBoundingVectors(inPosition, theEyeToEntity, inNormRayOne, inNormRayTwo, thePlaneABCD)) if(IsVectorBetweenBoundingVectors(inPosition, theEyeToEntity, inNormRayOne, inNormRayTwo)) { theSuccess = true; } return theSuccess; } void AvHSelectionHelper::ProcessEntityForSelection(const Vector& inOrigin, const Vector& inPointOfView, const Vector& inNormRayOne, const Vector& inNormRayTwo, int inIndex, bool inIsPlayer, bool inIsMarkedSelectable, bool inSameTeam, bool inIsVisible) { if(this->IsPositionInRegion(inOrigin, inPointOfView, inNormRayOne, inNormRayTwo)) { if(inIsPlayer || inIsMarkedSelectable) { bool theIsFriendly = inSameTeam; if(inIsPlayer) { if(theIsFriendly) { this->mFriendlyPlayers.push_back(inIndex); } else if(inIsVisible) { //this->mNonFriendlyPlayers.push_back(inIndex); } } else { if(theIsFriendly) { this->mFriendlyBuildings.push_back(inIndex); } else if(inIsVisible) { //this->mNonFriendlyBuildings.push_back(inIndex); } } } // else if(inIsSelectableWorldObject) // { // this->mWorldObjects.push_back(inIndex); // } } } bool AvHSelectionHelper::SelectUnitsInRegion(const Vector& inPointOfView, const Vector& inNormRayOne, const Vector& inNormRayTwo, AvHTeamNumber inTeamNumber, EntityListType& outEntIndexList) { #ifdef AVH_SERVER // Assumes that entities won't be too far away float theRadius = GetGameRules()->GetMapExtents().GetTopDownCullDistance()*2; CBaseEntity* theBaseEntity = NULL; while((theBaseEntity = UTIL_FindEntityInSphere(theBaseEntity, inPointOfView, theRadius)) != NULL) { const char* theClassName = STRING(theBaseEntity->pev->classname); if(!AvHSUGetIsExternalClassName(theClassName)) { // Check for EF_NODRAW so that recycled command stations cannot be selected. if(!GetHasUpgrade(theBaseEntity->pev->iuser4, MASK_TOPDOWN) && !(theBaseEntity->pev->effects & EF_NODRAW) ) { AvHPlayer* thePlayer = dynamic_cast<AvHPlayer*>(theBaseEntity); bool theIsPlayer = (thePlayer && thePlayer->GetIsRelevant() && (thePlayer->GetUser3() != AVH_USER3_COMMANDER_PLAYER)); bool theIsMarkedSelectable = GetHasUpgrade(theBaseEntity->pev->iuser4, MASK_SELECTABLE); bool theSameTeam = (theBaseEntity->pev->team == inTeamNumber); bool theIsVisible = (theSameTeam || GetHasUpgrade(theBaseEntity->pev->iuser4, MASK_VIS_SIGHTED)); Vector thePosition = theBaseEntity->pev->origin; if((thePosition.x == thePosition.y) && (thePosition.y == thePosition.z) && (thePosition.z == 0.0f)) { thePosition.x = (theBaseEntity->pev->mins.x + theBaseEntity->pev->maxs.x)/2.0f; thePosition.y = (theBaseEntity->pev->mins.y + theBaseEntity->pev->maxs.y)/2.0f; thePosition.z = (theBaseEntity->pev->mins.z + theBaseEntity->pev->maxs.z)/2.0f; } int theEntityIndex = theBaseEntity->entindex(); AvHSHUGetEntityLocation(theEntityIndex, thePosition); this->ProcessEntityForSelection(thePosition, inPointOfView, inNormRayOne, inNormRayTwo, theEntityIndex, theIsPlayer, theIsMarkedSelectable, theSameTeam, theIsVisible); } } } #endif #ifdef AVH_CLIENT gEngfuncs.pEventAPI->EV_SetUpPlayerPrediction( false, true ); // Store off the old count gEngfuncs.pEventAPI->EV_PushPMStates(); // Now add in all of the players. gEngfuncs.pEventAPI->EV_SetSolidPlayers (-1); physent_t* theEntity = NULL; int theNumEnts = pmove->numphysent; for (int i = 0; i < theNumEnts; i++) { theEntity = gEngfuncs.pEventAPI->EV_GetPhysent(i); if(theEntity && !GetHasUpgrade(theEntity->iuser4, MASK_TOPDOWN)) { int theEntityIndex = theEntity->info; bool theIsPlayer = ((theEntityIndex >= 1) && (theEntityIndex <= gEngfuncs.GetMaxClients())); bool theIsMarkedSelectable = GetHasUpgrade(theEntity->iuser4, MASK_SELECTABLE); bool theSameTeam = (theEntity->team == inTeamNumber); bool theIsVisible = (theSameTeam || GetHasUpgrade(theEntity->iuser4, MASK_VIS_SIGHTED)); Vector thePosition = theEntity->origin; if((thePosition.x == thePosition.y) && (thePosition.y == thePosition.z) && (thePosition.z == 0.0f)) { thePosition.x = (theEntity->mins.x + theEntity->maxs.x)/2.0f; thePosition.y = (theEntity->mins.y + theEntity->maxs.y)/2.0f; thePosition.z = (theEntity->mins.z + theEntity->maxs.z)/2.0f; } this->ProcessEntityForSelection(thePosition, inPointOfView, inNormRayOne, inNormRayTwo, theEntityIndex, theIsPlayer, theIsMarkedSelectable, theSameTeam, theIsVisible); } } gEngfuncs.pEventAPI->EV_PopPMStates(); #endif bool theSuccess = false; // Our own players if(this->mFriendlyPlayers.size() > 0) { outEntIndexList = this->mFriendlyPlayers; } // Our own buildings only one else if(this->mFriendlyBuildings.size() > 0) { outEntIndexList.push_back(*mFriendlyBuildings.begin()); } // Enemy players (only one) else if(this->mNonFriendlyPlayers.size() > 0) { outEntIndexList.push_back(*this->mNonFriendlyPlayers.begin()); } // Enemy buildings (only one) else if(this->mNonFriendlyBuildings.size() > 0) { outEntIndexList.push_back(*this->mNonFriendlyBuildings.begin()); } // World objects (only one) // else if(this->mWorldObjects.size() > 0) // { // outEntIndexList.push_back(*this->mWorldObjects.begin()); // } if(outEntIndexList.size() > 0) { theSuccess = true; } this->mFriendlyBuildings.clear(); this->mFriendlyPlayers.clear(); this->mNonFriendlyBuildings.clear(); this->mNonFriendlyPlayers.clear(); // this->mWorldObjects.clear(); return theSuccess; } bool AvHSelectionHelper::SelectUnits(const Vector& inPointOfView, const Vector& inStartRay, const Vector& inEndRay, AvHTeamNumber inTeamNumber, EntityListType& outEntIndexList) { bool theSuccess = false; // Select into new list EntityListType theNewSelection; Vector theStartRay = inStartRay; Vector theEndRay = inEndRay; // If inNormRayOne and inNormRayTwo are sufficiently close, just do a ray test const float theXTolerance = .1f; const float theYTolerance = .1f; if((fabs(theStartRay.x - theEndRay.x) < theXTolerance) && (fabs(theStartRay.y - theEndRay.y) < theYTolerance)) { // // Ignore team here, we're allowed to click select units on either team // int theEntIndex; // if(AvHSHUGetEntityAtRay(inPointOfView, inStartRay, theEntIndex)) // { // theNewSelection.push_back(theEntIndex); // theSuccess = true; // } // Select minimum around center Vector theCenter; theCenter.x = (inStartRay.x + inEndRay.x)/2.0f; theCenter.y = (inStartRay.y + inEndRay.y)/2.0f; // theCenter.z = (inStartRay.z + inEndRay.z)/2.0f; // Not perfect, but good enough theStartRay.x = theCenter.x - theXTolerance/2.0f; theStartRay.y = theCenter.y - theYTolerance/2.0f; VectorNormalize(theStartRay); theEndRay.x = theCenter.x + theXTolerance/2.0f; theEndRay.y = theCenter.y + theYTolerance/2.0f; VectorNormalize(theEndRay); } // else // { theSuccess = SelectUnitsInRegion(inPointOfView, theStartRay, theEndRay, inTeamNumber, theNewSelection); // } if(theSuccess) { // Set new selection outEntIndexList = theNewSelection; } return theSuccess; }
{ "pile_set_name": "Github" }
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
{ "pile_set_name": "Github" }
/* * Copyright (C) 2010-2020 Structr GmbH * * This file is part of Structr <http://structr.org>. * * Structr 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. * * Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.files.ssh.shell; import java.io.IOException; import org.structr.files.ssh.StructrShellCommand; /** * * */ public class LogoutCommand extends NonInteractiveShellCommand { @Override public void execute(final StructrShellCommand parent) throws IOException { term.stopEmulator(); } }
{ "pile_set_name": "Github" }
/* Copyright 2018 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package pdns import ( "context" "errors" "net/http" "strings" "testing" pgo "github.com/ffledgling/pdns-go" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/suite" "sigs.k8s.io/external-dns/endpoint" ) // FIXME: What do we do about labels? var ( // Simple RRSets that contain 1 A record and 1 TXT record RRSetSimpleARecord = pgo.RrSet{ Name: "example.com.", Type_: "A", Ttl: 300, Records: []pgo.Record{ {Content: "8.8.8.8", Disabled: false, SetPtr: false}, }, } RRSetSimpleTXTRecord = pgo.RrSet{ Name: "example.com.", Type_: "TXT", Ttl: 300, Records: []pgo.Record{ {Content: "\"heritage=external-dns,external-dns/owner=tower-pdns\"", Disabled: false, SetPtr: false}, }, } RRSetLongARecord = pgo.RrSet{ Name: "a.very.long.domainname.example.com.", Type_: "A", Ttl: 300, Records: []pgo.Record{ {Content: "8.8.8.8", Disabled: false, SetPtr: false}, }, } RRSetLongTXTRecord = pgo.RrSet{ Name: "a.very.long.domainname.example.com.", Type_: "TXT", Ttl: 300, Records: []pgo.Record{ {Content: "\"heritage=external-dns,external-dns/owner=tower-pdns\"", Disabled: false, SetPtr: false}, }, } // RRSet with one record disabled RRSetDisabledRecord = pgo.RrSet{ Name: "example.com.", Type_: "A", Ttl: 300, Records: []pgo.Record{ {Content: "8.8.8.8", Disabled: false, SetPtr: false}, {Content: "8.8.4.4", Disabled: true, SetPtr: false}, }, } RRSetCNAMERecord = pgo.RrSet{ Name: "cname.example.com.", Type_: "CNAME", Ttl: 300, Records: []pgo.Record{ {Content: "example.by.any.other.name.com", Disabled: false, SetPtr: false}, }, } RRSetTXTRecord = pgo.RrSet{ Name: "example.com.", Type_: "TXT", Ttl: 300, Records: []pgo.Record{ {Content: "'would smell as sweet'", Disabled: false, SetPtr: false}, }, } // Multiple PDNS records in an RRSet of a single type RRSetMultipleRecords = pgo.RrSet{ Name: "example.com.", Type_: "A", Ttl: 300, Records: []pgo.Record{ {Content: "8.8.8.8", Disabled: false, SetPtr: false}, {Content: "8.8.4.4", Disabled: false, SetPtr: false}, {Content: "4.4.4.4", Disabled: false, SetPtr: false}, }, } endpointsDisabledRecord = []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.8.8"), } endpointsSimpleRecord = []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.8.8"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), } endpointsLongRecord = []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL("a.very.long.domainname.example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.8.8"), endpoint.NewEndpointWithTTL("a.very.long.domainname.example.com", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), } endpointsNonexistantZone = []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL("does.not.exist.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.8.8"), endpoint.NewEndpointWithTTL("does.not.exist.com", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), } endpointsMultipleRecords = []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.8.8"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.4.4"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "4.4.4.4"), } endpointsMixedRecords = []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL("cname.example.com", endpoint.RecordTypeCNAME, endpoint.TTL(300), "example.by.any.other.name.com"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeTXT, endpoint.TTL(300), "'would smell as sweet'"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.8.8"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.4.4"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "4.4.4.4"), } endpointsMultipleZones = []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.8.8"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), endpoint.NewEndpointWithTTL("mock.test", endpoint.RecordTypeA, endpoint.TTL(300), "9.9.9.9"), endpoint.NewEndpointWithTTL("mock.test", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), } endpointsMultipleZones2 = []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.8.8"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), endpoint.NewEndpointWithTTL("abcd.mock.test", endpoint.RecordTypeA, endpoint.TTL(300), "9.9.9.9"), endpoint.NewEndpointWithTTL("abcd.mock.test", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), } endpointsMultipleZonesWithNoExist = []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.8.8"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), endpoint.NewEndpointWithTTL("abcd.mock.noexist", endpoint.RecordTypeA, endpoint.TTL(300), "9.9.9.9"), endpoint.NewEndpointWithTTL("abcd.mock.noexist", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), } endpointsMultipleZonesWithLongRecordNotInDomainFilter = []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.8.8"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), endpoint.NewEndpointWithTTL("a.very.long.domainname.example.com", endpoint.RecordTypeA, endpoint.TTL(300), "9.9.9.9"), endpoint.NewEndpointWithTTL("a.very.long.domainname.example.com", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), } endpointsMultipleZonesWithSimilarRecordNotInDomainFilter = []*endpoint.Endpoint{ endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeA, endpoint.TTL(300), "8.8.8.8"), endpoint.NewEndpointWithTTL("example.com", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), endpoint.NewEndpointWithTTL("test.simexample.com", endpoint.RecordTypeA, endpoint.TTL(300), "9.9.9.9"), endpoint.NewEndpointWithTTL("test.simexample.com", endpoint.RecordTypeTXT, endpoint.TTL(300), "\"heritage=external-dns,external-dns/owner=tower-pdns\""), } ZoneEmpty = pgo.Zone{ // Opaque zone id (string), assigned by the server, should not be interpreted by the application. Guaranteed to be safe for embedding in URLs. Id: "example.com.", // Name of the zone (e.g. “example.com.”) MUST have a trailing dot Name: "example.com.", // Set to “Zone” Type_: "Zone", // API endpoint for this zone Url: "/api/v1/servers/localhost/zones/example.com.", // Zone kind, one of “Native”, “Master”, “Slave” Kind: "Native", // RRSets in this zone Rrsets: []pgo.RrSet{}, } ZoneEmptySimilar = pgo.Zone{ Id: "simexample.com.", Name: "simexample.com.", Type_: "Zone", Url: "/api/v1/servers/localhost/zones/simexample.com.", Kind: "Native", Rrsets: []pgo.RrSet{}, } ZoneEmptyLong = pgo.Zone{ Id: "long.domainname.example.com.", Name: "long.domainname.example.com.", Type_: "Zone", Url: "/api/v1/servers/localhost/zones/long.domainname.example.com.", Kind: "Native", Rrsets: []pgo.RrSet{}, } ZoneEmpty2 = pgo.Zone{ Id: "mock.test.", Name: "mock.test.", Type_: "Zone", Url: "/api/v1/servers/localhost/zones/mock.test.", Kind: "Native", Rrsets: []pgo.RrSet{}, } ZoneMixed = pgo.Zone{ Id: "example.com.", Name: "example.com.", Type_: "Zone", Url: "/api/v1/servers/localhost/zones/example.com.", Kind: "Native", Rrsets: []pgo.RrSet{RRSetCNAMERecord, RRSetTXTRecord, RRSetMultipleRecords}, } ZoneEmptyToSimplePatch = pgo.Zone{ Id: "example.com.", Name: "example.com.", Type_: "Zone", Url: "/api/v1/servers/localhost/zones/example.com.", Kind: "Native", Rrsets: []pgo.RrSet{ { Name: "example.com.", Type_: "A", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "8.8.8.8", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, { Name: "example.com.", Type_: "TXT", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "\"heritage=external-dns,external-dns/owner=tower-pdns\"", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, }, } ZoneEmptyToSimplePatchLongRecordIgnoredInDomainFilter = pgo.Zone{ Id: "example.com.", Name: "example.com.", Type_: "Zone", Url: "/api/v1/servers/localhost/zones/example.com.", Kind: "Native", Rrsets: []pgo.RrSet{ { Name: "a.very.long.domainname.example.com.", Type_: "A", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "9.9.9.9", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, { Name: "a.very.long.domainname.example.com.", Type_: "TXT", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "\"heritage=external-dns,external-dns/owner=tower-pdns\"", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, { Name: "example.com.", Type_: "A", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "8.8.8.8", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, { Name: "example.com.", Type_: "TXT", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "\"heritage=external-dns,external-dns/owner=tower-pdns\"", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, }, } ZoneEmptyToLongPatch = pgo.Zone{ Id: "long.domainname.example.com.", Name: "long.domainname.example.com.", Type_: "Zone", Url: "/api/v1/servers/localhost/zones/long.domainname.example.com.", Kind: "Native", Rrsets: []pgo.RrSet{ { Name: "a.very.long.domainname.example.com.", Type_: "A", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "8.8.8.8", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, { Name: "a.very.long.domainname.example.com.", Type_: "TXT", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "\"heritage=external-dns,external-dns/owner=tower-pdns\"", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, }, } ZoneEmptyToSimplePatch2 = pgo.Zone{ Id: "mock.test.", Name: "mock.test.", Type_: "Zone", Url: "/api/v1/servers/localhost/zones/mock.test.", Kind: "Native", Rrsets: []pgo.RrSet{ { Name: "mock.test.", Type_: "A", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "9.9.9.9", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, { Name: "mock.test.", Type_: "TXT", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "\"heritage=external-dns,external-dns/owner=tower-pdns\"", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, }, } ZoneEmptyToSimplePatch3 = pgo.Zone{ Id: "mock.test.", Name: "mock.test.", Type_: "Zone", Url: "/api/v1/servers/localhost/zones/mock.test.", Kind: "Native", Rrsets: []pgo.RrSet{ { Name: "abcd.mock.test.", Type_: "A", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "9.9.9.9", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, { Name: "abcd.mock.test.", Type_: "TXT", Ttl: 300, Changetype: "REPLACE", Records: []pgo.Record{ { Content: "\"heritage=external-dns,external-dns/owner=tower-pdns\"", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, }, } ZoneEmptyToSimpleDelete = pgo.Zone{ Id: "example.com.", Name: "example.com.", Type_: "Zone", Url: "/api/v1/servers/localhost/zones/example.com.", Kind: "Native", Rrsets: []pgo.RrSet{ { Name: "example.com.", Type_: "A", Changetype: "DELETE", Records: []pgo.Record{ { Content: "8.8.8.8", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, { Name: "example.com.", Type_: "TXT", Changetype: "DELETE", Records: []pgo.Record{ { Content: "\"heritage=external-dns,external-dns/owner=tower-pdns\"", Disabled: false, SetPtr: false, }, }, Comments: []pgo.Comment(nil), }, }, } DomainFilterListSingle = endpoint.DomainFilter{ Filters: []string{ "example.com", }, } DomainFilterListMultiple = endpoint.DomainFilter{ Filters: []string{ "example.com", "mock.com", }, } DomainFilterListEmpty = endpoint.DomainFilter{ Filters: []string{}, } DomainFilterEmptyClient = &PDNSAPIClient{ dryRun: false, authCtx: context.WithValue(context.Background(), pgo.ContextAPIKey, pgo.APIKey{Key: "TEST-API-KEY"}), client: pgo.NewAPIClient(pgo.NewConfiguration()), domainFilter: DomainFilterListEmpty, } DomainFilterSingleClient = &PDNSAPIClient{ dryRun: false, authCtx: context.WithValue(context.Background(), pgo.ContextAPIKey, pgo.APIKey{Key: "TEST-API-KEY"}), client: pgo.NewAPIClient(pgo.NewConfiguration()), domainFilter: DomainFilterListSingle, } DomainFilterMultipleClient = &PDNSAPIClient{ dryRun: false, authCtx: context.WithValue(context.Background(), pgo.ContextAPIKey, pgo.APIKey{Key: "TEST-API-KEY"}), client: pgo.NewAPIClient(pgo.NewConfiguration()), domainFilter: DomainFilterListMultiple, } ) /******************************************************************************/ // API that returns a zone with multiple record types type PDNSAPIClientStub struct { } func (c *PDNSAPIClientStub) ListZones() ([]pgo.Zone, *http.Response, error) { return []pgo.Zone{ZoneMixed}, nil, nil } func (c *PDNSAPIClientStub) PartitionZones(zones []pgo.Zone) ([]pgo.Zone, []pgo.Zone) { return zones, nil } func (c *PDNSAPIClientStub) ListZone(zoneID string) (pgo.Zone, *http.Response, error) { return ZoneMixed, nil, nil } func (c *PDNSAPIClientStub) PatchZone(zoneID string, zoneStruct pgo.Zone) (*http.Response, error) { return nil, nil } /******************************************************************************/ // API that returns a zones with no records type PDNSAPIClientStubEmptyZones struct { // Keep track of all zones we receive via PatchZone patchedZones []pgo.Zone } func (c *PDNSAPIClientStubEmptyZones) ListZones() ([]pgo.Zone, *http.Response, error) { return []pgo.Zone{ZoneEmpty, ZoneEmptyLong, ZoneEmpty2}, nil, nil } func (c *PDNSAPIClientStubEmptyZones) PartitionZones(zones []pgo.Zone) ([]pgo.Zone, []pgo.Zone) { return zones, nil } func (c *PDNSAPIClientStubEmptyZones) ListZone(zoneID string) (pgo.Zone, *http.Response, error) { if strings.Contains(zoneID, "example.com") { return ZoneEmpty, nil, nil } else if strings.Contains(zoneID, "mock.test") { return ZoneEmpty2, nil, nil } else if strings.Contains(zoneID, "long.domainname.example.com") { return ZoneEmptyLong, nil, nil } return pgo.Zone{}, nil, nil } func (c *PDNSAPIClientStubEmptyZones) PatchZone(zoneID string, zoneStruct pgo.Zone) (*http.Response, error) { c.patchedZones = append(c.patchedZones, zoneStruct) return nil, nil } /******************************************************************************/ // API that returns error on PatchZone() type PDNSAPIClientStubPatchZoneFailure struct { // Anonymous struct for composition PDNSAPIClientStubEmptyZones } // Just overwrite the PatchZone method to introduce a failure func (c *PDNSAPIClientStubPatchZoneFailure) PatchZone(zoneID string, zoneStruct pgo.Zone) (*http.Response, error) { return nil, errors.New("Generic PDNS Error") } /******************************************************************************/ // API that returns error on ListZone() type PDNSAPIClientStubListZoneFailure struct { // Anonymous struct for composition PDNSAPIClientStubEmptyZones } // Just overwrite the ListZone method to introduce a failure func (c *PDNSAPIClientStubListZoneFailure) ListZone(zoneID string) (pgo.Zone, *http.Response, error) { return pgo.Zone{}, nil, errors.New("Generic PDNS Error") } /******************************************************************************/ // API that returns error on ListZones() (Zones - plural) type PDNSAPIClientStubListZonesFailure struct { // Anonymous struct for composition PDNSAPIClientStubEmptyZones } // Just overwrite the ListZones method to introduce a failure func (c *PDNSAPIClientStubListZonesFailure) ListZones() ([]pgo.Zone, *http.Response, error) { return []pgo.Zone{}, nil, errors.New("Generic PDNS Error") } /******************************************************************************/ // API that returns zone partitions given DomainFilter(s) type PDNSAPIClientStubPartitionZones struct { // Anonymous struct for composition PDNSAPIClientStubEmptyZones } func (c *PDNSAPIClientStubPartitionZones) ListZones() ([]pgo.Zone, *http.Response, error) { return []pgo.Zone{ZoneEmpty, ZoneEmptyLong, ZoneEmpty2, ZoneEmptySimilar}, nil, nil } func (c *PDNSAPIClientStubPartitionZones) ListZone(zoneID string) (pgo.Zone, *http.Response, error) { if strings.Contains(zoneID, "example.com") { return ZoneEmpty, nil, nil } else if strings.Contains(zoneID, "mock.test") { return ZoneEmpty2, nil, nil } else if strings.Contains(zoneID, "long.domainname.example.com") { return ZoneEmptyLong, nil, nil } else if strings.Contains(zoneID, "simexample.com") { return ZoneEmptySimilar, nil, nil } return pgo.Zone{}, nil, nil } // Just overwrite the ListZones method to introduce a failure func (c *PDNSAPIClientStubPartitionZones) PartitionZones(zones []pgo.Zone) ([]pgo.Zone, []pgo.Zone) { return []pgo.Zone{ZoneEmpty}, []pgo.Zone{ZoneEmptyLong, ZoneEmpty2} } /******************************************************************************/ type NewPDNSProviderTestSuite struct { suite.Suite } func (suite *NewPDNSProviderTestSuite) TestPDNSProviderCreate() { _, err := NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", DomainFilter: endpoint.NewDomainFilter([]string{""}), }) assert.Error(suite.T(), err, "--pdns-api-key should be specified") _, err = NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", APIKey: "foo", DomainFilter: endpoint.NewDomainFilter([]string{"example.com", "example.org"}), }) assert.Nil(suite.T(), err, "--domain-filter should raise no error") _, err = NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", APIKey: "foo", DomainFilter: endpoint.NewDomainFilter([]string{""}), DryRun: true, }) assert.Error(suite.T(), err, "--dry-run should raise an error") // This is our "regular" code path, no error should be thrown _, err = NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", APIKey: "foo", DomainFilter: endpoint.NewDomainFilter([]string{""}), }) assert.Nil(suite.T(), err, "Regular case should raise no error") } func (suite *NewPDNSProviderTestSuite) TestPDNSProviderCreateTLS() { _, err := NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", APIKey: "foo", DomainFilter: endpoint.NewDomainFilter([]string{""}), }) assert.Nil(suite.T(), err, "Omitted TLS Config case should raise no error") _, err = NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", APIKey: "foo", DomainFilter: endpoint.NewDomainFilter([]string{""}), TLSConfig: TLSConfig{ TLSEnabled: false, }, }) assert.Nil(suite.T(), err, "Disabled TLS Config should raise no error") _, err = NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", APIKey: "foo", DomainFilter: endpoint.NewDomainFilter([]string{""}), TLSConfig: TLSConfig{ TLSEnabled: false, CAFilePath: "/path/to/ca.crt", ClientCertFilePath: "/path/to/cert.pem", ClientCertKeyFilePath: "/path/to/cert-key.pem", }, }) assert.Nil(suite.T(), err, "Disabled TLS Config with additional flags should raise no error") _, err = NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", APIKey: "foo", DomainFilter: endpoint.NewDomainFilter([]string{""}), TLSConfig: TLSConfig{ TLSEnabled: true, }, }) assert.Error(suite.T(), err, "Enabled TLS Config without --tls-ca should raise an error") _, err = NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", APIKey: "foo", DomainFilter: endpoint.NewDomainFilter([]string{""}), TLSConfig: TLSConfig{ TLSEnabled: true, CAFilePath: "../../internal/testresources/ca.pem", }, }) assert.Nil(suite.T(), err, "Enabled TLS Config with --tls-ca should raise no error") _, err = NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", APIKey: "foo", DomainFilter: endpoint.NewDomainFilter([]string{""}), TLSConfig: TLSConfig{ TLSEnabled: true, CAFilePath: "../../internal/testresources/ca.pem", ClientCertFilePath: "../../internal/testresources/client-cert.pem", }, }) assert.Error(suite.T(), err, "Enabled TLS Config with --tls-client-cert only should raise an error") _, err = NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", APIKey: "foo", DomainFilter: endpoint.NewDomainFilter([]string{""}), TLSConfig: TLSConfig{ TLSEnabled: true, CAFilePath: "../../internal/testresources/ca.pem", ClientCertKeyFilePath: "../../internal/testresources/client-cert-key.pem", }, }) assert.Error(suite.T(), err, "Enabled TLS Config with --tls-client-cert-key only should raise an error") _, err = NewPDNSProvider( context.Background(), PDNSConfig{ Server: "http://localhost:8081", APIKey: "foo", DomainFilter: endpoint.NewDomainFilter([]string{""}), TLSConfig: TLSConfig{ TLSEnabled: true, CAFilePath: "../../internal/testresources/ca.pem", ClientCertFilePath: "../../internal/testresources/client-cert.pem", ClientCertKeyFilePath: "../../internal/testresources/client-cert-key.pem", }, }) assert.Nil(suite.T(), err, "Enabled TLS Config with all flags should raise no error") } func (suite *NewPDNSProviderTestSuite) TestPDNSRRSetToEndpoints() { // Function definition: convertRRSetToEndpoints(rr pgo.RrSet) (endpoints []*endpoint.Endpoint, _ error) // Create a new provider to run tests against p := &PDNSProvider{ client: &PDNSAPIClientStub{}, } /* given an RRSet with three records, we test: - We correctly create corresponding endpoints */ eps, err := p.convertRRSetToEndpoints(RRSetMultipleRecords) assert.Nil(suite.T(), err) assert.Equal(suite.T(), endpointsMultipleRecords, eps) /* Given an RRSet with two records, one of which is disabled, we test: - We can correctly convert the RRSet into a list of valid endpoints - We correctly discard/ignore the disabled record. */ eps, err = p.convertRRSetToEndpoints(RRSetDisabledRecord) assert.Nil(suite.T(), err) assert.Equal(suite.T(), endpointsDisabledRecord, eps) } func (suite *NewPDNSProviderTestSuite) TestPDNSRecords() { // Function definition: Records() (endpoints []*endpoint.Endpoint, _ error) // Create a new provider to run tests against p := &PDNSProvider{ client: &PDNSAPIClientStub{}, } ctx := context.Background() /* We test that endpoints are returned correctly for a Zone when Records() is called */ eps, err := p.Records(ctx) assert.Nil(suite.T(), err) assert.Equal(suite.T(), endpointsMixedRecords, eps) // Test failures are handled correctly // Create a new provider to run tests against p = &PDNSProvider{ client: &PDNSAPIClientStubListZoneFailure{}, } _, err = p.Records(ctx) assert.NotNil(suite.T(), err) p = &PDNSProvider{ client: &PDNSAPIClientStubListZonesFailure{}, } _, err = p.Records(ctx) assert.NotNil(suite.T(), err) } func (suite *NewPDNSProviderTestSuite) TestPDNSConvertEndpointsToZones() { // Function definition: ConvertEndpointsToZones(endpoints []*endpoint.Endpoint, changetype pdnsChangeType) (zonelist []pgo.Zone, _ error) // Create a new provider to run tests against p := &PDNSProvider{ client: &PDNSAPIClientStubEmptyZones{}, } // Check inserting endpoints from a single zone zlist, err := p.ConvertEndpointsToZones(endpointsSimpleRecord, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimplePatch}, zlist) // Check deleting endpoints from a single zone zlist, err = p.ConvertEndpointsToZones(endpointsSimpleRecord, PdnsDelete) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimpleDelete}, zlist) // Check endpoints from multiple zones #1 zlist, err = p.ConvertEndpointsToZones(endpointsMultipleZones, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimplePatch, ZoneEmptyToSimplePatch2}, zlist) // Check endpoints from multiple zones #2 zlist, err = p.ConvertEndpointsToZones(endpointsMultipleZones2, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimplePatch, ZoneEmptyToSimplePatch3}, zlist) // Check endpoints from multiple zones where some endpoints which don't exist zlist, err = p.ConvertEndpointsToZones(endpointsMultipleZonesWithNoExist, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimplePatch}, zlist) // Check endpoints from a zone that does not exist zlist, err = p.ConvertEndpointsToZones(endpointsNonexistantZone, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{}, zlist) // Check endpoints that match multiple zones (one longer than other), is assigned to the right zone zlist, err = p.ConvertEndpointsToZones(endpointsLongRecord, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToLongPatch}, zlist) // Check endpoints of type CNAME always have their target records end with a dot. zlist, err = p.ConvertEndpointsToZones(endpointsMixedRecords, PdnsReplace) assert.Nil(suite.T(), err) for _, z := range zlist { for _, rs := range z.Rrsets { if "CNAME" == rs.Type_ { for _, r := range rs.Records { assert.Equal(suite.T(), uint8(0x2e), r.Content[len(r.Content)-1]) } } } } } func (suite *NewPDNSProviderTestSuite) TestPDNSConvertEndpointsToZonesPartitionZones() { // Test DomainFilters p := &PDNSProvider{ client: &PDNSAPIClientStubPartitionZones{}, } // Check inserting endpoints from a single zone which is specified in DomainFilter zlist, err := p.ConvertEndpointsToZones(endpointsSimpleRecord, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimplePatch}, zlist) // Check deleting endpoints from a single zone which is specified in DomainFilter zlist, err = p.ConvertEndpointsToZones(endpointsSimpleRecord, PdnsDelete) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimpleDelete}, zlist) // Check endpoints from multiple zones # which one is specified in DomainFilter and one is not zlist, err = p.ConvertEndpointsToZones(endpointsMultipleZones, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimplePatch}, zlist) // Check endpoints from multiple zones where some endpoints which don't exist and one that does // and is part of DomainFilter zlist, err = p.ConvertEndpointsToZones(endpointsMultipleZonesWithNoExist, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimplePatch}, zlist) // Check endpoints from a zone that does not exist zlist, err = p.ConvertEndpointsToZones(endpointsNonexistantZone, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{}, zlist) // Check endpoints that match multiple zones (one longer than other), is assigned to the right zone when the longer // zone is not part of the DomainFilter zlist, err = p.ConvertEndpointsToZones(endpointsMultipleZonesWithLongRecordNotInDomainFilter, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimplePatchLongRecordIgnoredInDomainFilter}, zlist) // Check endpoints that match multiple zones (one longer than other and one is very similar) // is assigned to the right zone when the similar zone is not part of the DomainFilter zlist, err = p.ConvertEndpointsToZones(endpointsMultipleZonesWithSimilarRecordNotInDomainFilter, PdnsReplace) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimplePatch}, zlist) } func (suite *NewPDNSProviderTestSuite) TestPDNSmutateRecords() { // Function definition: mutateRecords(endpoints []*endpoint.Endpoint, changetype pdnsChangeType) error // Create a new provider to run tests against c := &PDNSAPIClientStubEmptyZones{} p := &PDNSProvider{ client: c, } // Check inserting endpoints from a single zone err := p.mutateRecords(endpointsSimpleRecord, pdnsChangeType("REPLACE")) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimplePatch}, c.patchedZones) // Reset the "patchedZones" c.patchedZones = []pgo.Zone{} // Check deleting endpoints from a single zone err = p.mutateRecords(endpointsSimpleRecord, pdnsChangeType("DELETE")) assert.Nil(suite.T(), err) assert.Equal(suite.T(), []pgo.Zone{ZoneEmptyToSimpleDelete}, c.patchedZones) // Check we fail correctly when patching fails for whatever reason p = &PDNSProvider{ client: &PDNSAPIClientStubPatchZoneFailure{}, } // Check inserting endpoints from a single zone err = p.mutateRecords(endpointsSimpleRecord, pdnsChangeType("REPLACE")) assert.NotNil(suite.T(), err) } func (suite *NewPDNSProviderTestSuite) TestPDNSClientPartitionZones() { zoneList := []pgo.Zone{ ZoneEmpty, ZoneEmpty2, } partitionResultFilteredEmptyFilter := []pgo.Zone{ ZoneEmpty, ZoneEmpty2, } partitionResultResidualEmptyFilter := ([]pgo.Zone)(nil) partitionResultFilteredSingleFilter := []pgo.Zone{ ZoneEmpty, } partitionResultResidualSingleFilter := []pgo.Zone{ ZoneEmpty2, } partitionResultFilteredMultipleFilter := []pgo.Zone{ ZoneEmpty, } partitionResultResidualMultipleFilter := []pgo.Zone{ ZoneEmpty2, } // Check filtered, residual zones when no domain filter specified filteredZones, residualZones := DomainFilterEmptyClient.PartitionZones(zoneList) assert.Equal(suite.T(), partitionResultFilteredEmptyFilter, filteredZones) assert.Equal(suite.T(), partitionResultResidualEmptyFilter, residualZones) // Check filtered, residual zones when a single domain filter specified filteredZones, residualZones = DomainFilterSingleClient.PartitionZones(zoneList) assert.Equal(suite.T(), partitionResultFilteredSingleFilter, filteredZones) assert.Equal(suite.T(), partitionResultResidualSingleFilter, residualZones) // Check filtered, residual zones when a multiple domain filter specified filteredZones, residualZones = DomainFilterMultipleClient.PartitionZones(zoneList) assert.Equal(suite.T(), partitionResultFilteredMultipleFilter, filteredZones) assert.Equal(suite.T(), partitionResultResidualMultipleFilter, residualZones) } func TestNewPDNSProviderTestSuite(t *testing.T) { suite.Run(t, new(NewPDNSProviderTestSuite)) }
{ "pile_set_name": "Github" }
/** * Copyright (c) 2013-2020 Nikita Koksharov * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.redisson.client; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import org.redisson.api.RFuture; import org.redisson.client.handler.RedisChannelInitializer; import org.redisson.client.handler.RedisChannelInitializer.Type; import org.redisson.misc.RPromise; import org.redisson.misc.RedisURI; import org.redisson.misc.RedissonPromise; import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelFutureListener; import io.netty.channel.ChannelOption; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.EpollDatagramChannel; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.group.ChannelGroup; import io.netty.channel.group.ChannelGroupFuture; import io.netty.channel.group.DefaultChannelGroup; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.nio.NioDatagramChannel; import io.netty.resolver.AddressResolver; import io.netty.resolver.dns.DnsAddressResolverGroup; import io.netty.resolver.dns.DnsServerAddressStreamProviders; import io.netty.util.HashedWheelTimer; import io.netty.util.NetUtil; import io.netty.util.Timer; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.FutureListener; /** * Low-level Redis client * * @author Nikita Koksharov * */ public final class RedisClient { private final AtomicReference<RFuture<InetSocketAddress>> resolvedAddrFuture = new AtomicReference<RFuture<InetSocketAddress>>(); private final Bootstrap bootstrap; private final Bootstrap pubSubBootstrap; private final RedisURI uri; private InetSocketAddress resolvedAddr; private final ChannelGroup channels; private ExecutorService executor; private final long commandTimeout; private Timer timer; private RedisClientConfig config; private boolean hasOwnTimer; private boolean hasOwnExecutor; private boolean hasOwnGroup; private boolean hasOwnResolver; public static RedisClient create(RedisClientConfig config) { return new RedisClient(config); } private RedisClient(RedisClientConfig config) { RedisClientConfig copy = new RedisClientConfig(config); if (copy.getTimer() == null) { copy.setTimer(new HashedWheelTimer()); hasOwnTimer = true; } if (copy.getGroup() == null) { copy.setGroup(new NioEventLoopGroup()); hasOwnGroup = true; } if (copy.getExecutor() == null) { copy.setExecutor(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2)); hasOwnExecutor = true; } if (copy.getResolverGroup() == null) { if (config.getSocketChannelClass() == EpollSocketChannel.class) { copy.setResolverGroup(new DnsAddressResolverGroup(EpollDatagramChannel.class, DnsServerAddressStreamProviders.platformDefault())); } else { copy.setResolverGroup(new DnsAddressResolverGroup(NioDatagramChannel.class, DnsServerAddressStreamProviders.platformDefault())); } hasOwnResolver = true; } this.config = copy; this.executor = copy.getExecutor(); this.timer = copy.getTimer(); uri = copy.getAddress(); resolvedAddr = copy.getAddr(); if (resolvedAddr != null) { resolvedAddrFuture.set(RedissonPromise.newSucceededFuture(resolvedAddr)); } channels = new DefaultChannelGroup(copy.getGroup().next()); bootstrap = createBootstrap(copy, Type.PLAIN); pubSubBootstrap = createBootstrap(copy, Type.PUBSUB); this.commandTimeout = copy.getCommandTimeout(); } private Bootstrap createBootstrap(RedisClientConfig config, Type type) { Bootstrap bootstrap = new Bootstrap() .resolver(config.getResolverGroup()) .channel(config.getSocketChannelClass()) .group(config.getGroup()); bootstrap.handler(new RedisChannelInitializer(bootstrap, config, this, channels, type)); bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, config.getConnectTimeout()); bootstrap.option(ChannelOption.SO_KEEPALIVE, config.isKeepAlive()); bootstrap.option(ChannelOption.TCP_NODELAY, config.isTcpNoDelay()); config.getNettyHook().afterBoostrapInitialization(bootstrap); return bootstrap; } public InetSocketAddress getAddr() { return resolvedAddr; } public long getCommandTimeout() { return commandTimeout; } public EventLoopGroup getEventLoopGroup() { return bootstrap.config().group(); } public RedisClientConfig getConfig() { return config; } public Timer getTimer() { return timer; } public RedisConnection connect() { try { return connectAsync().syncUninterruptibly().getNow(); } catch (Exception e) { throw new RedisConnectionException("Unable to connect to: " + uri, e); } } public RFuture<InetSocketAddress> resolveAddr() { if (resolvedAddrFuture.get() != null) { return resolvedAddrFuture.get(); } final RPromise<InetSocketAddress> promise = new RedissonPromise<InetSocketAddress>(); if (!resolvedAddrFuture.compareAndSet(null, promise)) { return resolvedAddrFuture.get(); } byte[] addr = NetUtil.createByteArrayFromIpAddressString(uri.getHost()); if (addr != null) { try { resolvedAddr = new InetSocketAddress(InetAddress.getByAddress(addr), uri.getPort()); } catch (UnknownHostException e) { // skip } promise.trySuccess(resolvedAddr); return promise; } AddressResolver<InetSocketAddress> resolver = (AddressResolver<InetSocketAddress>) bootstrap.config().resolver().getResolver(bootstrap.config().group().next()); Future<InetSocketAddress> resolveFuture = resolver.resolve(InetSocketAddress.createUnresolved(uri.getHost(), uri.getPort())); resolveFuture.addListener(new FutureListener<InetSocketAddress>() { @Override public void operationComplete(Future<InetSocketAddress> future) throws Exception { if (!future.isSuccess()) { promise.tryFailure(future.cause()); return; } InetSocketAddress resolved = future.getNow(); byte[] addr = resolved.getAddress().getAddress(); resolvedAddr = new InetSocketAddress(InetAddress.getByAddress(uri.getHost(), addr), resolved.getPort()); promise.trySuccess(resolvedAddr); } }); return promise; } public RFuture<RedisConnection> connectAsync() { final RPromise<RedisConnection> f = new RedissonPromise<RedisConnection>(); RFuture<InetSocketAddress> addrFuture = resolveAddr(); addrFuture.onComplete((res, e) -> { if (e != null) { f.tryFailure(e); return; } ChannelFuture channelFuture = bootstrap.connect(res); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (bootstrap.config().group().isShuttingDown()) { IllegalStateException cause = new IllegalStateException("RedisClient is shutdown"); f.tryFailure(cause); return; } if (future.isSuccess()) { final RedisConnection c = RedisConnection.getFrom(future.channel()); c.getConnectionPromise().onComplete((res, e) -> { bootstrap.config().group().execute(new Runnable() { @Override public void run() { if (e == null) { if (!f.trySuccess(c)) { c.closeAsync(); } } else { f.tryFailure(e); c.closeAsync(); } } }); }); } else { bootstrap.config().group().execute(new Runnable() { public void run() { f.tryFailure(future.cause()); } }); } } }); }); return f; } public RedisPubSubConnection connectPubSub() { try { return connectPubSubAsync().syncUninterruptibly().getNow(); } catch (Exception e) { throw new RedisConnectionException("Unable to connect to: " + uri, e); } } public RFuture<RedisPubSubConnection> connectPubSubAsync() { RPromise<RedisPubSubConnection> f = new RedissonPromise<RedisPubSubConnection>(); RFuture<InetSocketAddress> nameFuture = resolveAddr(); nameFuture.onComplete((res, e) -> { if (e != null) { f.tryFailure(e); return; } ChannelFuture channelFuture = pubSubBootstrap.connect(res); channelFuture.addListener(new ChannelFutureListener() { @Override public void operationComplete(final ChannelFuture future) throws Exception { if (bootstrap.config().group().isShuttingDown()) { IllegalStateException cause = new IllegalStateException("RedisClient is shutdown"); f.tryFailure(cause); return; } if (future.isSuccess()) { final RedisPubSubConnection c = RedisPubSubConnection.getFrom(future.channel()); c.<RedisPubSubConnection>getConnectionPromise().onComplete((res, e) -> { pubSubBootstrap.config().group().execute(new Runnable() { @Override public void run() { if (e == null) { if (!f.trySuccess(c)) { c.closeAsync(); } } else { f.tryFailure(e); c.closeAsync(); } } }); }); } else { pubSubBootstrap.config().group().execute(new Runnable() { public void run() { f.tryFailure(future.cause()); } }); } } }); }); return f; } public void shutdown() { shutdownAsync().syncUninterruptibly(); } public RFuture<Void> shutdownAsync() { RPromise<Void> result = new RedissonPromise<Void>(); if (channels.isEmpty()) { shutdown(result); return result; } ChannelGroupFuture channelsFuture = channels.newCloseFuture(); channelsFuture.addListener(new FutureListener<Void>() { @Override public void operationComplete(Future<Void> future) throws Exception { if (!future.isSuccess()) { result.tryFailure(future.cause()); return; } shutdown(result); } }); for (Channel channel : channels) { RedisConnection connection = RedisConnection.getFrom(channel); if (connection != null) { connection.closeAsync(); } } return result; } private void shutdown(RPromise<Void> result) { if (!hasOwnTimer && !hasOwnExecutor && !hasOwnResolver && !hasOwnGroup) { result.trySuccess(null); } else { Thread t = new Thread() { @Override public void run() { try { if (hasOwnTimer) { timer.stop(); } if (hasOwnExecutor) { executor.shutdown(); executor.awaitTermination(15, TimeUnit.SECONDS); } if (hasOwnResolver) { bootstrap.config().resolver().close(); } if (hasOwnGroup) { bootstrap.config().group().shutdownGracefully(); } } catch (Exception e) { result.tryFailure(e); return; } result.trySuccess(null); } }; t.start(); } } @Override public String toString() { return "[addr=" + uri + "]"; } }
{ "pile_set_name": "Github" }
# Translation pot file for the ET: Legacyclient # Copyright (C) 2012-2018 ET: Legacy Team # This file is distributed under the same license as the ET:Legacy package. # Translators: # redtide <[email protected]>, 2015 # redtide <[email protected]>, 2015 msgid "" msgstr "" "Project-Id-Version: ET:Legacy\n" "Report-Msgid-Bugs-To: [email protected]\n" "POT-Creation-Date: 2015-01-10 20:22+0100\n" "PO-Revision-Date: 2016-01-09 21:51+0000\n" "Last-Translator: Jacker <[email protected]>\n" "Language-Team: Italian (http://www.transifex.com/etlegacy/etlegacy/language/it/)\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" "Language: it\n" "Plural-Forms: nplurals=2; plural=(n != 1);\n" #: src/client/cl_console.c:674 msgid "say_team:" msgstr "messaggio_team:" #: src/client/cl_console.c:682 msgid "say_fireteam:" msgstr "messaggio_fireteam:" #: src/client/cl_console.c:690 msgid "say:" msgstr "messaggio:" #: src/client/cl_console.c:803 #, c-format msgid "%s (UPDATE AVAILABLE)" msgstr "%s (AGGIORNAMENTO DISPONIBILE)" msgid "MOUSE1" msgstr "MOUSE1" msgid "MOUSE2" msgstr "MOUSE2" msgid "SPACE" msgstr "SPAZIO"
{ "pile_set_name": "Github" }
module Aws module RailsProvisioner VERSION = '0.0.1.rc2' end end
{ "pile_set_name": "Github" }
package com.othershe.calendarview.weiget; import android.content.Context; import android.content.res.TypedArray; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.util.SparseArray; import com.othershe.calendarview.R; import com.othershe.calendarview.bean.AttrsBean; import com.othershe.calendarview.bean.DateBean; import com.othershe.calendarview.listener.CalendarViewAdapter; import com.othershe.calendarview.listener.OnMultiChooseListener; import com.othershe.calendarview.listener.OnSingleChooseListener; import com.othershe.calendarview.listener.OnPagerChangeListener; import com.othershe.calendarview.utils.CalendarUtil; import com.othershe.calendarview.utils.SolarUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Set; public class CalendarView extends ViewPager { //记录当前PagerAdapter的position private int currentPosition; private OnPagerChangeListener pagerChangeListener; private OnSingleChooseListener singleChooseListener; private OnMultiChooseListener multiChooseListener; private CalendarViewAdapter calendarViewAdapter; private int item_layout; private int[] initDate;//日历初始显示的年月 private int[] startDate;//日历的开始年、月 private int[] endDate;//日历的结束年、月 private int count;//ViewPager的页数 private int[] lastClickDate = new int[2];//记录单选的ViewPager position以及选中的日期 private SparseArray<HashSet<Integer>> chooseDate;//记录多选时全部选中的日期 private Set<Integer> positions;//多选时记录选中日期对应的ViewPager position private CalendarPagerAdapter calendarPagerAdapter; private AttrsBean mAttrsBean; public CalendarView(Context context) { this(context, null); } public CalendarView(Context context, AttributeSet attrs) { super(context, attrs); mAttrsBean = new AttrsBean(); initAttr(context, attrs); } private void initAttr(Context context, AttributeSet attrs) { TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CalendarView); for (int i = 0; i < ta.getIndexCount(); i++) { int attr = ta.getIndex(i); if (attr == R.styleable.CalendarView_show_last_next) { mAttrsBean.setShowLastNext(ta.getBoolean(attr, true)); } else if (attr == R.styleable.CalendarView_show_lunar) { mAttrsBean.setShowLunar(ta.getBoolean(attr, true)); } else if (attr == R.styleable.CalendarView_show_holiday) { mAttrsBean.setShowHoliday(ta.getBoolean(attr, true)); } else if (attr == R.styleable.CalendarView_show_term) { mAttrsBean.setShowTerm(ta.getBoolean(attr, true)); } else if (attr == R.styleable.CalendarView_switch_choose) { mAttrsBean.setSwitchChoose(ta.getBoolean(attr, true)); } else if (attr == R.styleable.CalendarView_solar_color) { mAttrsBean.setColorSolar(ta.getColor(attr, mAttrsBean.getColorSolar())); } else if (attr == R.styleable.CalendarView_solar_size) { mAttrsBean.setSizeSolar(CalendarUtil.getTextSize(context, ta.getInteger(attr, mAttrsBean.getSizeSolar()))); } else if (attr == R.styleable.CalendarView_lunar_color) { mAttrsBean.setColorLunar(ta.getColor(attr, mAttrsBean.getColorLunar())); } else if (attr == R.styleable.CalendarView_lunar_size) { mAttrsBean.setSizeLunar(CalendarUtil.getTextSize(context, ta.getInt(attr, mAttrsBean.getSizeLunar()))); } else if (attr == R.styleable.CalendarView_holiday_color) { mAttrsBean.setColorHoliday(ta.getColor(attr, mAttrsBean.getColorHoliday())); } else if (attr == R.styleable.CalendarView_choose_color) { mAttrsBean.setColorChoose(ta.getColor(attr, mAttrsBean.getColorChoose())); } else if (attr == R.styleable.CalendarView_day_bg) { mAttrsBean.setDayBg(ta.getResourceId(attr, mAttrsBean.getDayBg())); } else if (attr == R.styleable.CalendarView_choose_type) { mAttrsBean.setChooseType(ta.getInt(attr, 0)); } } ta.recycle(); startDate = new int[]{1900, 1}; endDate = new int[]{2049, 12}; mAttrsBean.setStartDate(startDate); mAttrsBean.setEndDate(endDate); } public void init() { //根据设定的日期范围计算日历的页数 count = (endDate[0] - startDate[0]) * 12 + endDate[1] - startDate[1] + 1; calendarPagerAdapter = new CalendarPagerAdapter(count); calendarPagerAdapter.setAttrsBean(mAttrsBean); calendarPagerAdapter.setOnCalendarViewAdapter(item_layout, calendarViewAdapter); setAdapter(calendarPagerAdapter); currentPosition = CalendarUtil.dateToPosition(initDate[0], initDate[1], startDate[0], startDate[1]); //单选 if (mAttrsBean.getChooseType() == 0) { int[] singleDate = mAttrsBean.getSingleDate(); if (singleDate != null) { lastClickDate[0] = CalendarUtil.dateToPosition(singleDate[0], singleDate[1], startDate[0], startDate[1]); lastClickDate[1] = singleDate[2]; } } //多选 if (mAttrsBean.getChooseType() == 1) { positions = new HashSet<>(); chooseDate = new SparseArray<>(); if (mAttrsBean.getMultiDates() != null) { for (int[] date : mAttrsBean.getMultiDates()) { if (isIllegal(date)) { int datePosition = CalendarUtil.dateToPosition(date[0], date[1], startDate[0], startDate[1]); positions.add(datePosition); setChooseDate(date[2], true, datePosition); } } } } setCurrentItem(currentPosition, false); addOnPageChangeListener(new SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { refreshMonthView(position); currentPosition = position; if (pagerChangeListener != null) { int[] date = CalendarUtil.positionToDate(position, startDate[0], startDate[1]); pagerChangeListener.onPagerChanged(new int[]{date[0], date[1], lastClickDate[1]}); } } }); } /** * 计算 ViewPager 高度 * * @param widthMeasureSpec * @param heightMeasureSpec */ @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int calendarHeight; if (getAdapter() != null) { MonthView view = (MonthView) getChildAt(0); if (view != null) { calendarHeight = view.getMeasuredHeight(); setMeasuredDimension(widthMeasureSpec, MeasureSpec.makeMeasureSpec(calendarHeight, MeasureSpec.EXACTLY)); } } } /** * 刷新MonthView * * @param position */ private void refreshMonthView(int position) { MonthView monthView = calendarPagerAdapter.getViews().get(position); if (mAttrsBean.getChooseType() == 1) {//多选 if (chooseDate.get(position) != null) monthView.multiChooseRefresh(chooseDate.get(position)); } else { //单选时,如果设置切换月份不选中上次选中的日期但如果切换回有选中日期的页则需要刷新选中,或者切换选中开启则需要刷新选中 boolean flag = (!mAttrsBean.isSwitchChoose() && lastClickDate[0] == position) || mAttrsBean.isSwitchChoose(); monthView.refresh(lastClickDate[1], flag); } } /** * 设置单选时选中的日期 * * @param day */ public void setLastClickDay(int day) { lastClickDate[0] = currentPosition; lastClickDate[1] = day; } /** * 设置多选时选中的日期 * * @param day * @param flag 多选时flag=true代表选中数据,flag=false代表取消选中 * @param position 代表记录viewpager哪一页的数据 */ public void setChooseDate(int day, boolean flag, int position) { if (position == -1) { position = currentPosition; } HashSet<Integer> days = chooseDate.get(position); if (flag) { if (days == null) { days = new HashSet<>(); chooseDate.put(position, days); } days.add(day); positions.add(position); } else { days.remove(day); } } /** * 检查初始化选中的日期,或者要跳转的日期是否合法 * * @param destDate * @return */ private boolean isIllegal(int[] destDate) { if (destDate[1] > 12 || destDate[1] < 1) { return false; } if (CalendarUtil.dateToMillis(destDate) < CalendarUtil.dateToMillis(startDate)) { return false; } if (CalendarUtil.dateToMillis(destDate) > CalendarUtil.dateToMillis(endDate)) { return false; } if (destDate[2] > SolarUtil.getMonthDays(destDate[0], destDate[1]) || destDate[2] < 1) { return false; } if (mAttrsBean.getDisableStartDate() != null) { if (CalendarUtil.dateToMillis(destDate) < CalendarUtil.dateToMillis(mAttrsBean.getDisableStartDate())) { return false; } } if (mAttrsBean.getDisableEndDate() != null) { if (CalendarUtil.dateToMillis(destDate) > CalendarUtil.dateToMillis(mAttrsBean.getDisableEndDate())) { return false; } } return true; } /** * 设置日期单选回调 * * @param singleChooseListener */ public void setOnSingleChooseListener(OnSingleChooseListener singleChooseListener) { this.singleChooseListener = singleChooseListener; } public OnMultiChooseListener getMultiChooseListener() { return multiChooseListener; } /** * 设置日期多选回调 * * @param multiChooseListener */ public void setOnMultiChooseListener(OnMultiChooseListener multiChooseListener) { this.multiChooseListener = multiChooseListener; } public OnSingleChooseListener getSingleChooseListener() { return singleChooseListener; } /** * 设置月份切换回调 * * @param pagerChangeListener */ public void setOnPagerChangeListener(OnPagerChangeListener pagerChangeListener) { this.pagerChangeListener = pagerChangeListener; } /** * 设置自定义日期样式 * * @param item_layout 自定义的日期item布局 * @param calendarViewAdapter 解析item的接口 */ public CalendarView setOnCalendarViewAdapter(int item_layout, CalendarViewAdapter calendarViewAdapter) { this.item_layout = item_layout; this.calendarViewAdapter = calendarViewAdapter; return this; } /** * 单选时跳转到今天 */ public void today() { int destPosition = CalendarUtil.dateToPosition(CalendarUtil.getCurrentDate()[0], CalendarUtil.getCurrentDate()[1], startDate[0], startDate[1]); lastClickDate[0] = destPosition; lastClickDate[1] = CalendarUtil.getCurrentDate()[2]; if (destPosition == currentPosition) { refreshMonthView(destPosition); } else { setCurrentItem(destPosition, false); } } /** * 单选时跳转到指定日期 * * @param year * @param month * @param day */ public boolean toSpecifyDate(int year, int month, int day) { if (!isIllegal(new int[]{year, month, day})) { return false; } toDestDate(year, month, day); return true; } private void toDestDate(int year, int month, int day) { int destPosition = CalendarUtil.dateToPosition(year, month, startDate[0], startDate[1]); if (!mAttrsBean.isSwitchChoose() && day != 0) { lastClickDate[0] = destPosition; } lastClickDate[1] = day != 0 ? day : lastClickDate[1]; if (destPosition == currentPosition) { //在当月进行日期跳转 refreshMonthView(destPosition); } else { setCurrentItem(destPosition, false); } } /** * 跳转到下个月 */ public void nextMonth() { if (currentPosition < count - 1) setCurrentItem(++currentPosition, false); } /** * 跳转到上个月 */ public void lastMonth() { if (currentPosition > 0) setCurrentItem(--currentPosition, false); } /** * 跳转到上一年的当前月 */ public void lastYear() { if (currentPosition - 12 >= 0) { setCurrentItem(currentPosition -= 12, false); } } /** * 跳转到下一年的当前月 */ public void nextYear() { if (currentPosition + 12 <= count) { setCurrentItem(currentPosition += 12, false); } } /** * 跳转到日历的开始年月 */ public void toStart() { toDestDate(startDate[0], startDate[1], 0); } /** * 跳转到日历的结束年月 */ public void toEnd() { toDestDate(endDate[0], endDate[1], 0); } /** * 将指定日期的农历替换成对应文字 */ public CalendarView setSpecifyMap(HashMap<String, String> map) { mAttrsBean.setSpecifyMap(map); return this; } /** * 设置日历初始显示的年月 * * @param date * @return */ public CalendarView setInitDate(String date) { initDate = CalendarUtil.strToArray(date); return this; } /** * 设置日历的开始年月、结束年月 * * @param startDate * @param endDate * @return */ public CalendarView setStartEndDate(String startDate, String endDate) { this.startDate = CalendarUtil.strToArray(startDate); if (startDate == null) { this.startDate = new int[]{1900, 1}; } this.endDate = CalendarUtil.strToArray(endDate); if (endDate == null) { this.endDate = new int[]{2049, 12}; } mAttrsBean.setStartDate(this.startDate); mAttrsBean.setEndDate(this.endDate); return this; } /** * 设置多选时默认选中的日期集合 * * @param dates * @return */ public CalendarView setMultiDate(List<String> dates) { List<int[]> multiDates = new ArrayList<>(); for (String date : dates) { int[] d = CalendarUtil.strToArray(date); if (isIllegal(d)) { multiDates.add(d); } } mAttrsBean.setMultiDates(multiDates); return this; } /** * 设置单选时默认选中的日期 * * @param date * @return */ public CalendarView setSingleDate(String date) { int[] singleDate = CalendarUtil.strToArray(date); if (!isIllegal(singleDate)) { singleDate = null; } mAttrsBean.setSingleDate(singleDate); return this; } /** * 设置日历禁用范围 * * @param startDate 禁用startDate之前的日期 * @param endDate 禁用endDate之后的日期 * @return */ public CalendarView setDisableStartEndDate(String startDate, String endDate) { mAttrsBean.setDisableStartDate(CalendarUtil.strToArray(startDate)); mAttrsBean.setDisableEndDate(CalendarUtil.strToArray(endDate)); return this; } /** * 得到单选时当前选中的日期 * * @return */ public DateBean getSingleDate() { int[] date = CalendarUtil.positionToDate(lastClickDate[0], startDate[0], startDate[1]); return CalendarUtil.getDateBean(date[0], date[1], lastClickDate[1]); } /** * 得到多选时选中的日期 * * @return */ public List<DateBean> getMultiDate() { List<DateBean> list = new ArrayList<>(); for (Integer position : positions) { HashSet<Integer> days = chooseDate.get(position); if (days.size() > 0) { int[] date = CalendarUtil.positionToDate(position, startDate[0], startDate[1]); for (Integer day : days) { list.add(CalendarUtil.getDateBean(date[0], date[1], day)); } } } return list; } }
{ "pile_set_name": "Github" }
# GHKD7D, GHKE7D, GHKF7D, GHKP7D, GHKS7D - The Hulk [Core] # Values set here will override the main Dolphin settings. SyncOnSkipIdle = False [OnLoad] # Add memory patches to be loaded once on boot here. [OnFrame] [ActionReplay] [Gecko]
{ "pile_set_name": "Github" }
[记录一下互联网日志实时收集和实时计算的简单方案](http://weekly.manong.io/bounce?url=http%3A%2F%2Flxw1234.com%2Farchives%2F2015%2F11%2F569.htm&aid=4488&nid=97) [HBase 优化实战](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwww.bitstech.net%2F2015%2F12%2F04%2Fhbase-optmization%2F&aid=4592&nid=98) [简单了解分布式系统](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwww.hollischuang.com%2Farchives%2F655&aid=4604&nid=98) [[PDF] 分布式系统原理介绍(2012)](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwww.valleytalk.org%2Fwp-content%2Fuploads%2F2012%2F07%2F%25E5%2588%2586%25E5%25B8%2583%25E5%25BC%258F%25E7%25B3%25BB%25E7%25BB%259F%25E5%258E%259F%25E7%2590%2586%25E4%25BB%258B%25E7%25BB%258D.pdf&aid=4668&nid=99) [[译] 当讨论分布式系统时,我们都会讨论些什么?](http://weekly.manong.io/bounce?url=http%3A%2F%2Fdockone.io%2Farticle%2F898&aid=4769&nid=100) [日志系统之基于 Zookeeper 的分布式协同设计](http://weekly.manong.io/bounce?url=http%3A%2F%2Fvinoyang.com%2F2015%2F12%2F26%2Flink-log-system-component-with-zookeeper%2F&aid=4864&nid=101) [分布式协调服务 ZooKeeper 工作原理](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzA4Nzc4MjI4MQ%3D%3D%26mid%3D402839281%26idx%3D1%26sn%3De46ab7a4865f94f7a2ade584621c62c3&aid=5319&nid=106) [[译] 数据处理平台架构中的 SMACK 组合](http://weekly.manong.io/bounce?url=http%3A%2F%2Fblog.dataman-inc.com%2Funtitled-23%2F&aid=5329&nid=106) [Apache Flink 官方文档翻译开源项目](http://weekly.manong.io/bounce?url=http%3A%2F%2Fblog.flink-china.org%2F2016%2F03%2F08%2Fflink-documentation-translation-project%2F&aid=5530&nid=109) [Fastdfs 分布式文件系统的应用](http://weekly.manong.io/bounce?url=http%3A%2F%2Fminirick.duapp.com%2Ffastdfsfen-bu-shi-wen-jian-xi-tong-shi-zhan%2F&aid=5700&nid=111) [一名分布式存储工程师的技能树是怎样的?](http://weekly.manong.io/bounce?url=https%3A%2F%2Fwww.zhihu.com%2Fquestion%2F43687427%2Fanswer%2F96677826&aid=6010&nid=115) [秒级处理海量数据,浙江移动大数据平台是怎么做到的?](http://weekly.manong.io/bounce?url=http%3A%2F%2Fdbaplus.cn%2Fnews-21-372-1.html&aid=6019&nid=115) [Zipkin:分布式追踪系统](http://weekly.manong.io/bounce?url=https%3A%2F%2Fgithub.com%2Fopenzipkin%2Fzipkin&aid=6047&nid=115) [分布式搜索引擎(二)](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMjM5ODczNTkwMA%3D%3D%26mid%3D2650107065%26idx%3D1%26sn%3D6dbe4d8bc13b93ac17a6dcef579a0cea%23rd&aid=6399&nid=120) [如果有 10000 台机器,你想怎么玩(二)](http://weekly.manong.io/bounce?url=http%3A%2F%2Finsights.thoughtworkers.org%2Fkubernetes-in-mesos-2%2F&aid=6423&nid=120) [分布式事务笔记](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwww.yangguo.info%2F2016%2F05%2F23%2F%25E5%2588%2586%25E5%25B8%2583%25E5%25BC%258F%25E4%25BA%258B%25E5%258A%25A1%25E7%25AC%2594%25E8%25AE%25B0%2F&aid=6438&nid=120) [Mesos + Zookeeper + Marathon + Docker 分布式集群管理最佳实践](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwww.xuliangwei.com%2Fxubusi%2F422.html&aid=6482&nid=121) [深入理解分布式系统的 2PC 和 3PC](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwww.hollischuang.com%2Farchives%2F1580&aid=6492&nid=121) [Swarm 和 Mesos 集成指南](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzA3MjY1MTQwNQ%3D%3D%26mid%3D2649822413%26idx%3D1%26sn%3D3cb613313a50fcfecc286420ae5f3533&aid=6572&nid=122) [基于 Dubbo 框架构建分布式服务](http://weekly.manong.io/bounce?url=http%3A%2F%2Fshiyanjun.cn%2Farchives%2F1075.html&aid=6661&nid=123) [[PPT] 一次重构引发的分布式服务管理](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwenku.baidu.com%2Fview%2Fae8adf90e518964bce847c43&aid=6724&nid=124) [分布式系统设计的求生之路](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwetest.qq.com%2Flab%2Fview%2F%3Fid%3D105&aid=6748&nid=125) [不懂点 CAP 理论,你好意思说你是做分布式的吗?](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzA4Nzg5Nzc5OA%3D%3D%26mid%3D2651660931%26idx%3D1%26sn%3D93cccfdcc5a474e92ffd673e7cd115ce%23rd&aid=6908&nid=127) [分布式队列编程:模型、实战](http://weekly.manong.io/bounce?url=http%3A%2F%2Ftech.meituan.com%2Fdistributed_queue_based_programming.html&aid=7035&nid=129) [大型项目程序配置管理演化之路](http://weekly.manong.io/bounce?url=http%3A%2F%2Finsights.thoughtworkers.org%2Flarge-project-configuration-management%2F&aid=7037&nid=129) [探秘阿里分布式任务调度服务 SchedulerX](http://weekly.manong.io/bounce?url=http%3A%2F%2Fjm.taobao.org%2F2016%2F07%2F28%2Fintroduce-SchedulerX%2F&aid=7046&nid=129) [Zookeeper:distributed process coordination 中文版](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmichael-j.net%2F2016%2F08%2F02%2FZookeeper-distributed-process-coordination%2F&aid=7136&nid=130) [分布式事务(一):两阶段提交及 JTA](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwww.jasongj.com%2Fbig_data%2Ftwo_phase_commit%2F&aid=7138&nid=130) [分布式队列编程(优化篇)](http://weekly.manong.io/bounce?url=http%3A%2F%2Ftech.meituan.com%2Fdistributed_queue_based_programming-optimization.html&aid=7094&nid=130) [ActiveMQ 高可用集群方案](http://weekly.manong.io/bounce?url=http%3A%2F%2Fwosyingjun.iteye.com%2Fblog%2F2314683&aid=7144&nid=130) [一文读懂 Hadoop、HBase、Hive、Spark 分布式系统架构](http://weekly.manong.io/bounce?url=http%3A%2F%2Ftoutiao.io%2Fj%2Fx79nnl&aid=7213&nid=131) [防雪崩利器:熔断器 Hystrix 的原理与使用](http://weekly.manong.io/bounce?url=http%3A%2F%2Ftoutiao.io%2Fj%2F3l1ugg&aid=7272&nid=132) [Zookeeper ZAB 协议分析](http://weekly.manong.io/bounce?url=http%3A%2F%2Ftoutiao.io%2Fj%2Ff13by4&aid=7341&nid=133) [Hive 原理及查询优化](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzI2MjE0MDUzNg%3D%3D%26mid%3D2652914310%26idx%3D1%26sn%3D4990335f0ec177c5e51af9a659f3aabe&aid=7355&nid=133) [GFS 原理](http://weekly.manong.io/bounce?url=http%3A%2F%2Ftoutiao.io%2Fj%2Fj97txk&aid=7438&nid=135) [分布式 RPC 框架性能大比拼](http://weekly.manong.io/bounce?url=http%3A%2F%2Ftoutiao.io%2Fj%2F7urt9y&aid=7487&nid=135) [分布式事务遇到的问题,以及如何解决?](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzA3MDA2MjE2OQ%3D%3D%26mid%3D2650096674%26idx%3D1%26sn%3Db67c5ca25e5d6e846e65471b584f0770&aid=7469&nid=135) [阿里、Facebook、Cloudera 等巨头的数据收集框架全攻略](http://weekly.manong.io/bounce?url=http%3A%2F%2Ftoutiao.io%2Fj%2Fy859w4&aid=7483&nid=135) [深入浅出 Zookeeper](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzIxMjAzMDA1MQ%3D%3D%26mid%3D2648945556%26idx%3D1%26sn%3D76fce0376e228ad6fb9eefc701c5228b&aid=7530&nid=136) [分布式缓存架构基础](http://weekly.manong.io/bounce?url=http%3A%2F%2Ftoutiao.io%2Fj%2Fnmbjqu&aid=7574&nid=137) [腾讯云分布式高可靠消息队列 CMQ 架构最佳实践](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzI5MDAzODY5OQ%3D%3D%26mid%3D2653095328%26idx%3D1%26sn%3Df05a8765ad4694ee1c8c9748ba39fbd8&aid=7575&nid=137) [分布式数据库模式与反模式](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzI3NDIxNTQyOQ%3D%3D%26mid%3D2247484004%26idx%3D1%26sn%3D36d30d0446f7ca16eb9ca7dced100ffc&aid=7649&nid=138) [分布式系统学习思路](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fj%2Fo1p0ie&aid=7666&nid=138) [Twitter zipkin 分布式跟踪系统的设计与实现](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fj%2Fr6n75h&aid=7647&nid=138) [一篇好 TM 长的关于配置中心的文章](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fj%2Fvvngad&aid=7680&nid=138) [运用 Aggregator 模式实现 MapReduce](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fj%2Fzmc74w&aid=7686&nid=138) [分布式会话跟踪系统架构设计与实践](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Ffmco5p&aid=7708&nid=139) [微信 PaxosStore 内存云揭秘:十亿 Paxos/分钟的挑战](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzI4NDMyNTU2Mw%3D%3D%26mid%3D2247483804%26idx%3D1%26sn%3Da6629ebdaefbc2470c2ecbf12577daff&aid=7855&nid=141) [RSF 分布式 RPC 服务框架的分层设计](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2F864at1&aid=7871&nid=141) [浅析分布式系统](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fjdlch0&aid=7914&nid=142) [ZooKeeper 的一致性算法赏析](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2F1pp1pw&aid=7939&nid=142) [IndexR,一个千亿级别的实时分析数据库](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzIyNjY1NDg5OA%3D%3D%26mid%3D2247483659%26idx%3D1%26sn%3D32807935dd79588a2e86e6dd7bacd673&aid=7944&nid=142) [分布式锁总结](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fcu6dnv&aid=7993&nid=143) [一名分布式存储工程师的技能树是怎样的?](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fttqk69&aid=7995&nid=143) [CAP 初窥](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fqziz1m&aid=8042&nid=144) [Ansible 超详细使用指南](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fklx70g&aid=8050&nid=144) [不妥协:分布式事务的一致性、可用性和性能](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fk0srwe&aid=8054&nid=144) [分布式系统本质论(3/3)](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fv1fi3e&aid=8118&nid=145) [聊聊分布式锁](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%3F__biz%3DMzIwNDU2MTI4NQ%3D%3D%26mid%3D2247483754%26idx%3D1%26sn%3D2164a80b98911f86dc8ffc9b112212ea&aid=8176&nid=146) [从 ACID 到 CAP/BASE](http://weekly.manong.io/bounce?url=http%3A%2F%2Fmp.weixin.qq.com%2Fs%2Fepksv_GNCTrZ5-3cGlxewA&aid=8310&nid=148) [Wormhole:可靠的发布-订阅系统](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fx6zk5k&aid=8299&nid=148) [分布式系统调用链监控](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fexoywq&aid=8356&nid=149) [HDFS NameNode 内存详解](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fx2x1jz&aid=8363&nid=149) [DCMP:基于 etcd 的配置管理系统](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fotuvj3&aid=8430&nid=150) [分布式系统入门笔记(五):ZooKeeper 之 ZAB 一致性协议](http://weekly.manong.io/bounce?url=https%3A%2F%2Ftoutiao.io%2Fk%2Fef7ldj&aid=8535&nid=152)
{ "pile_set_name": "Github" }