text
stringlengths 2
97.5k
| meta
dict |
|---|---|
From 5de183dc436bb647361ab641d891c113e6a7dadd Mon Sep 17 00:00:00 2001
From: Khem Raj <raj.khem@gmail.com>
Date: Sun, 8 Mar 2020 16:30:48 -0700
Subject: [PATCH] cmake: Use a regular expression to match x86 architectures
in OE we use i686 for qemux86 and this results in
-- INFO - Target arch is i686
CMake Error at CMakeLists.txt:191 (message):
Only x86, arm, mips, PERIPHERALMAN and mock platforms currently supported
So using a wildcard helps in using any x86 arch
Signed-off-by: Khem Raj <raj.khem@gmail.com>
---
CMakeLists.txt | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 250d9106..fb642722 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -176,8 +176,7 @@ else ()
message (STATUS "INFO - Override arch is ${DETECTED_ARCH}")
endif()
-if (DETECTED_ARCH STREQUAL "i586" OR DETECTED_ARCH STREQUAL "x86_64"
- OR DETECTED_ARCH STREQUAL "i386")
+if (DETECTED_ARCH MATCHES "i?86" OR DETECTED_ARCH STREQUAL "x86_64")
set (X86PLAT ON)
elseif (DETECTED_ARCH MATCHES "arm.*" OR DETECTED_ARCH MATCHES "aarch64")
set (ARMPLAT ON)
--
2.25.1
|
{
"pile_set_name": "Github"
}
|
Param($mgmtDomainAccountUserName, $mgmtDomainAccountPassword, $RemainingVMInstanceCount);
. ./Helpers.ps1
# Stops script execution on first error
$ErrorActionPreference = "stop";
# Exit Codes
$ErrorCode_Success = 0;
$ErrorCode_Failed = 1;
try
{
#-----------------------------------------------------------
# Trim Leading and Trailing Spaces of user input parameters
#-----------------------------------------------------------
if(-not [String]::IsNullOrEmpty($mgmtDomainAccountUserName))
{
$mgmtDomainAccountUserName = $mgmtDomainAccountUserName.Trim();
}
#------------------------------------------
# Get network controller node info
#------------------------------------------
try
{
Log "Discovering existing NC nodes.."
$ncNodes = Get-NetworkControllerNode
}
catch
{
Log "Existing Network Controller Nodes not found."
}
if($ncNodes -eq $null)
{
Log "No Network controller is configured for this machine. Exiting script.."
Exit $ErrorCode_Success
}
else
{
#------------------------------------------
# Find an on-line remote node.
#------------------------------------------
Log "Found existing nodes: $ncNodes"
$node = $ncNodes | where{$_.Server.ToLower().Split(".")[0].Equals($env:COMPUTERNAME.ToLower())}
$otherNodes = $ncNodes | where{-not $_.Equals($node)}
$vmNames = $otherNodes.Server
$remoteNodeName = TryGetNetworkControllerNodeRemote $vmNames $mgmtDomainAccountUserName $mgmtDomainAccountPassword
if($remoteNodeName -eq $null)
{
Log "Warning: Could not establish a connection with any other node in the network controller."
Log " Unable to remove this node from the network controller."
Exit $ErrorCode_Failed
}
#------------------------------------------
# Remove myself from the existing Network Controller
#------------------------------------------
# credential to access the network controller
$credential = CreateCredential $mgmtDomainAccountUserName $mgmtDomainAccountPassword
#Remove the node only if we have more than 3 VMs, else it throws exception
if($RemainingVMInstanceCount -gt 3)
{
# use a remote call to another node to remove this node
Log "Removing node from network controller.."
Log " -Name: $($node.Name)"
Log " -ComputerName: $remoteNodeName"
Log " -Credential: $($credential.UserName)"
Remove-NetworkControllerNode -Name $node.Name -ComputerName $remoteNodeName -Credential $credential -Force -Verbose
}
}
}
catch
{
Log "Caught an exception:";
Log " Exception Type: $($_.Exception.GetType().FullName)";
Log " Exception Message: $($_.Exception.Message)";
Log " Exception HResult: $($_.Exception.HResult)";
Exit $($_.Exception.HResult);
}
Log "Completed execution of script."
Exit $ErrorCode_Success
|
{
"pile_set_name": "Github"
}
|
SUMMARY="X.Org GL protocol headers"
DESCRIPTION="Headers for the X11 GL protocol."
HOMEPAGE="https://www.x.org/releases/individual/proto/"
COPYRIGHT="1991-2000 Silicon Graphics, Inc."
LICENSE="MIT"
REVISION="2"
SOURCE_URI="https://www.x.org/releases/individual/proto/glproto-$portVersion.tar.bz2"
CHECKSUM_SHA256="adaa94bded310a2bfcbb9deb4d751d965fcfe6fb3a2f6d242e2df2d6589dbe40"
ARCHITECTURES="!x86_gcc2 x86 x86_64"
SECONDARY_ARCHITECTURES="x86"
PROVIDES="
glproto$secondaryArchSuffix = $portVersion
devel:glproto$secondaryArchSuffix = $portVersion
"
REQUIRES="
haiku$secondaryArchSuffix
"
BUILD_REQUIRES="
haiku${secondaryArchSuffix}_devel
"
BUILD_PREREQUIRES="
cmd:aclocal
cmd:autoconf
cmd:gcc$secondaryArchSuffix
cmd:make
cmd:pkg_config$secondaryArchSuffix
devel:util_macros
"
BUILD()
{
autoreconf -vfi
runConfigure ./configure
}
INSTALL()
{
make install
fixPkgconfig
}
|
{
"pile_set_name": "Github"
}
|
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2010-2012 cocos2d-x.org
Copyright (c) 2011 Zynga Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "2d/CCActionInstant.h"
#include "2d/CCNode.h"
#include "2d/CCSprite.h"
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#elif _MSC_VER >= 1400 //vs 2005 or higher
#pragma warning (push)
#pragma warning (disable: 4996)
#endif
NS_CC_BEGIN
//
// InstantAction
//
void ActionInstant::startWithTarget(Node *target)
{
FiniteTimeAction::startWithTarget(target);
_done = false;
}
bool ActionInstant::isDone() const
{
return _done;
}
void ActionInstant::step(float /*dt*/)
{
float updateDt = 1;
#if CC_ENABLE_SCRIPT_BINDING
if (_scriptType == kScriptTypeJavascript)
{
if (ScriptEngineManager::sendActionEventToJS(this, kActionUpdate, (void *)&updateDt))
return;
}
#endif
update(updateDt);
}
void ActionInstant::update(float /*time*/)
{
_done = true;
}
//
// Show
//
Show* Show::create()
{
Show* ret = new (std::nothrow) Show();
if (ret)
{
ret->autorelease();
}
return ret;
}
void Show::update(float time)
{
ActionInstant::update(time);
_target->setVisible(true);
}
ActionInstant* Show::reverse() const
{
return Hide::create();
}
Show* Show::clone() const
{
// no copy constructor
return Show::create();
}
//
// Hide
//
Hide * Hide::create()
{
Hide *ret = new (std::nothrow) Hide();
if (ret)
{
ret->autorelease();
}
return ret;
}
void Hide::update(float time)
{
ActionInstant::update(time);
_target->setVisible(false);
}
ActionInstant *Hide::reverse() const
{
return Show::create();
}
Hide* Hide::clone() const
{
// no copy constructor
return Hide::create();
}
//
// ToggleVisibility
//
ToggleVisibility * ToggleVisibility::create()
{
ToggleVisibility *ret = new (std::nothrow) ToggleVisibility();
if (ret)
{
ret->autorelease();
}
return ret;
}
void ToggleVisibility::update(float time)
{
ActionInstant::update(time);
_target->setVisible(!_target->isVisible());
}
ToggleVisibility * ToggleVisibility::reverse() const
{
return ToggleVisibility::create();
}
ToggleVisibility * ToggleVisibility::clone() const
{
// no copy constructor
return ToggleVisibility::create();
}
//
// Remove Self
//
RemoveSelf * RemoveSelf::create(bool isNeedCleanUp /*= true*/)
{
RemoveSelf *ret = new (std::nothrow) RemoveSelf();
if (ret && ret->init(isNeedCleanUp))
{
ret->autorelease();
}
return ret;
}
bool RemoveSelf::init(bool isNeedCleanUp)
{
_isNeedCleanUp = isNeedCleanUp;
return true;
}
void RemoveSelf::update(float time)
{
ActionInstant::update(time);
_target->removeFromParentAndCleanup(_isNeedCleanUp);
}
RemoveSelf *RemoveSelf::reverse() const
{
return RemoveSelf::create(_isNeedCleanUp);
}
RemoveSelf * RemoveSelf::clone() const
{
// no copy constructor
return RemoveSelf::create(_isNeedCleanUp);
}
//
// FlipX
//
FlipX *FlipX::create(bool x)
{
FlipX *ret = new (std::nothrow) FlipX();
if (ret && ret->initWithFlipX(x))
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
bool FlipX::initWithFlipX(bool x)
{
_flipX = x;
return true;
}
void FlipX::update(float time)
{
ActionInstant::update(time);
static_cast<Sprite*>(_target)->setFlippedX(_flipX);
}
FlipX* FlipX::reverse() const
{
return FlipX::create(!_flipX);
}
FlipX * FlipX::clone() const
{
// no copy constructor
return FlipX::create(_flipX);
}
//
// FlipY
//
FlipY * FlipY::create(bool y)
{
FlipY *ret = new (std::nothrow) FlipY();
if (ret && ret->initWithFlipY(y))
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
bool FlipY::initWithFlipY(bool y)
{
_flipY = y;
return true;
}
void FlipY::update(float time)
{
ActionInstant::update(time);
static_cast<Sprite*>(_target)->setFlippedY(_flipY);
}
FlipY* FlipY::reverse() const
{
return FlipY::create(!_flipY);
}
FlipY * FlipY::clone() const
{
// no copy constructor
return FlipY::create(_flipY);
}
//
// Place
//
Place* Place::create(const Vec2& pos)
{
Place *ret = new (std::nothrow) Place();
if (ret && ret->initWithPosition(pos))
{
ret->autorelease();
return ret;
}
delete ret;
return nullptr;
}
bool Place::initWithPosition(const Vec2& pos)
{
_position = pos;
return true;
}
Place * Place::clone() const
{
// no copy constructor
return Place::create(_position);
}
Place * Place::reverse() const
{
// no reverse, just clone
return this->clone();
}
void Place::update(float time)
{
ActionInstant::update(time);
_target->setPosition(_position);
}
//
// CallFunc
//
CallFunc * CallFunc::create(const std::function<void()> &func)
{
CallFunc *ret = new (std::nothrow) CallFunc();
if (ret && ret->initWithFunction(func) )
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
CallFunc * CallFunc::create(Ref* selectorTarget, SEL_CallFunc selector)
{
CallFunc *ret = new (std::nothrow) CallFunc();
if (ret && ret->initWithTarget(selectorTarget))
{
ret->_callFunc = selector;
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
bool CallFunc::initWithFunction(const std::function<void()> &func)
{
_function = func;
return true;
}
bool CallFunc::initWithTarget(Ref* target)
{
if (target)
{
target->retain();
}
if (_selectorTarget)
{
_selectorTarget->release();
}
_selectorTarget = target;
return true;
}
CallFunc::~CallFunc()
{
CC_SAFE_RELEASE(_selectorTarget);
}
CallFunc * CallFunc::clone() const
{
// no copy constructor
auto a = new (std::nothrow) CallFunc();
if( _selectorTarget)
{
a->initWithTarget(_selectorTarget);
a->_callFunc = _callFunc;
}
else if( _function )
{
a->initWithFunction(_function);
}
a->autorelease();
return a;
}
CallFunc * CallFunc::reverse() const
{
// no reverse here, just return a clone
return this->clone();
}
void CallFunc::update(float time)
{
ActionInstant::update(time);
this->execute();
}
void CallFunc::execute()
{
if (_callFunc)
{
(_selectorTarget->*_callFunc)();
}
else if( _function )
{
_function();
}
}
//
// CallFuncN
//
CallFuncN * CallFuncN::create(const std::function<void(Node*)> &func)
{
auto ret = new (std::nothrow) CallFuncN();
if (ret && ret->initWithFunction(func) )
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
// FIXME: deprecated
CallFuncN * CallFuncN::create(Ref* selectorTarget, SEL_CallFuncN selector)
{
CallFuncN *ret = new (std::nothrow) CallFuncN();
if (ret && ret->initWithTarget(selectorTarget, selector))
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
void CallFuncN::execute()
{
if (_callFuncN)
{
(_selectorTarget->*_callFuncN)(_target);
}
else if (_functionN)
{
_functionN(_target);
}
}
bool CallFuncN::initWithFunction(const std::function<void (Node *)> &func)
{
_functionN = func;
return true;
}
bool CallFuncN::initWithTarget(Ref* selectorTarget, SEL_CallFuncN selector)
{
if (CallFunc::initWithTarget(selectorTarget))
{
_callFuncN = selector;
return true;
}
return false;
}
CallFuncN * CallFuncN::clone() const
{
// no copy constructor
auto a = new (std::nothrow) CallFuncN();
if( _selectorTarget)
{
a->initWithTarget(_selectorTarget, _callFuncN);
}
else if( _functionN ){
a->initWithFunction(_functionN);
}
a->autorelease();
return a;
}
//
// CallFuncND
//
__CCCallFuncND * __CCCallFuncND::create(Ref* selectorTarget, SEL_CallFuncND selector, void* d)
{
__CCCallFuncND* ret = new (std::nothrow) __CCCallFuncND();
if (ret && ret->initWithTarget(selectorTarget, selector, d))
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
bool __CCCallFuncND::initWithTarget(Ref* selectorTarget, SEL_CallFuncND selector, void* d)
{
if (CallFunc::initWithTarget(selectorTarget))
{
_data = d;
_callFuncND = selector;
return true;
}
return false;
}
void __CCCallFuncND::execute()
{
if (_callFuncND)
{
(_selectorTarget->*_callFuncND)(_target, _data);
}
}
__CCCallFuncND * __CCCallFuncND::clone() const
{
// no copy constructor
auto a = new (std::nothrow) __CCCallFuncND();
if( _selectorTarget)
{
a->initWithTarget(_selectorTarget, _callFuncND, _data);
}
a->autorelease();
return a;
}
//
// CallFuncO
//
__CCCallFuncO::__CCCallFuncO() :
_object(nullptr)
{
}
__CCCallFuncO::~__CCCallFuncO()
{
CC_SAFE_RELEASE(_object);
}
void __CCCallFuncO::execute()
{
if (_callFuncO)
{
(_selectorTarget->*_callFuncO)(_object);
}
}
__CCCallFuncO * __CCCallFuncO::create(Ref* selectorTarget, SEL_CallFuncO selector, Ref* object)
{
__CCCallFuncO *ret = new (std::nothrow) __CCCallFuncO();
if (ret && ret->initWithTarget(selectorTarget, selector, object))
{
ret->autorelease();
return ret;
}
CC_SAFE_DELETE(ret);
return nullptr;
}
bool __CCCallFuncO::initWithTarget(Ref* selectorTarget, SEL_CallFuncO selector, Ref* object)
{
if (CallFunc::initWithTarget(selectorTarget))
{
_object = object;
CC_SAFE_RETAIN(_object);
_callFuncO = selector;
return true;
}
return false;
}
__CCCallFuncO * __CCCallFuncO::clone() const
{
// no copy constructor
auto a = new (std::nothrow) __CCCallFuncO();
if( _selectorTarget)
{
a->initWithTarget(_selectorTarget, _callFuncO, _object);
}
a->autorelease();
return a;
}
Ref* __CCCallFuncO::getObject() const
{
return _object;
}
void __CCCallFuncO::setObject(Ref* obj)
{
if (obj != _object)
{
CC_SAFE_RELEASE(_object);
_object = obj;
CC_SAFE_RETAIN(_object);
}
}
NS_CC_END
#if defined(__GNUC__) && ((__GNUC__ >= 4) || ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1)))
#pragma GCC diagnostic warning "-Wdeprecated-declarations"
#elif _MSC_VER >= 1400 //vs 2005 or higher
#pragma warning (pop)
#endif
|
{
"pile_set_name": "Github"
}
|
(;GM[1]FF[4]CA[UTF-8]
RU[Chinese]SZ[19]KM[7.5]TM[900]
PW[xia_169]PB[Zen-15.7-1c0g]WR[3507?]BR[3220]DT[2018-04-05]PC[(CGOS) 19x19 Computer Go Server]RE[B+Time]GN[407581]
;B[pd]BL[895];W[dd]WL[896];B[qp]BL[892];W[dp]WL[892];B[fq]BL[887];W[op]WL[888];B[cn]BL[881];W[fp]WL[884]
;B[gp]BL[877];W[fo]WL[881];B[dq]BL[876];W[gq]WL[877];B[eq]BL[870];W[hp]WL[874];B[go]BL[865];W[hq]WL[868]
;B[cp]BL[858];W[gn]WL[864];B[ho]BL[853];W[do]WL[860];B[co]BL[851];W[cq]WL[857];B[fn]BL[845];W[en]WL[853]
;B[fm]BL[840];W[io]WL[849];B[hn]BL[838];W[hm]WL[845];B[in]BL[833];W[em]WL[841];B[eo]BL[829];W[ep]WL[838]
;B[dn]BL[824];W[eo]WL[834];B[el]BL[818];W[dm]WL[830];B[dl]BL[814];W[cm]WL[826];B[bm]BL[813];W[cl]WL[822]
;B[ck]BL[808];W[bl]WL[819];B[bk]BL[806];W[al]WL[814];B[ak]BL[802];W[jn]WL[810];B[am]BL[793];W[im]WL[806]
;B[jo]BL[786];W[ko]WL[802];B[ip]BL[780];W[jp]WL[798];B[io]BL[767];W[jq]WL[795];B[kn]BL[760];W[ln]WL[791]
;B[jm]BL[752];W[km]WL[787];B[jn]BL[737];W[lo]WL[783];B[pq]BL[722];W[oq]WL[779];B[qn]BL[717];W[pp]WL[775]
;B[qq]BL[707];W[qo]WL[772];B[ro]BL[699];W[po]WL[768];B[rm]BL[690];W[rp]WL[764];B[or]BL[671];W[so]WL[760]
;B[rn]BL[665];W[rq]WL[756];B[rr]BL[658];W[qr]WL[752];B[pr]BL[655];W[rs]WL[748];B[qs]BL[647];W[sr]WL[745]
;B[ss]BL[637];W[nf]WL[741];B[nq]BL[624];W[rs]WL[737];B[qr]BL[615];W[nr]WL[733];B[mr]BL[608];W[os]WL[729]
;B[ns]BL[601];W[ms]WL[724];B[ls]BL[595];W[mq]WL[720];B[np]BL[588];W[lh]WL[715];B[lm]BL[582];W[mm]WL[711]
;B[kl]BL[577];W[gi]WL[707];B[ml]BL[571];W[ha]WL[703];B[nc]BL[565];W[hf]WL[699];B[kc]BL[559];W[ll]WL[695]
;B[lk]BL[553];W[fk]WL[691];B[pf]BL[547];W[eh]WL[686];B[oh]BL[541];W[mf]WL[682];B[mi]BL[535];W[oa]WL[677]
;B[pb]BL[530];W[rh]WL[673];B[rf]BL[507];W[be]WL[668];B[hc]BL[502];W[ag]WL[663];B[ec]BL[497];W[pk]WL[659]
;B[mh]BL[491];W[ai]WL[654];B[dc]BL[486];W[ob]WL[650];B[oc]BL[481];W[ka]WL[645];B[ib]BL[476];W[ia]WL[641]
;B[jb]BL[471];W[cb]WL[637];B[cc]BL[465];W[cf]WL[632];B[bd]BL[460];W[ie]WL[629];B[fe]BL[456];W[qh]WL[625]
;B[rk]BL[451])
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#import "EC2DescribeImagesRequest.h"
@implementation EC2DescribeImagesRequest
@synthesize dryRun;
@synthesize dryRunIsSet;
@synthesize imageIds;
@synthesize owners;
@synthesize executableUsers;
@synthesize filters;
-(id)init
{
if (self = [super init]) {
dryRun = NO;
dryRunIsSet = NO;
imageIds = [[NSMutableArray alloc] initWithCapacity:1];
owners = [[NSMutableArray alloc] initWithCapacity:1];
executableUsers = [[NSMutableArray alloc] initWithCapacity:1];
filters = [[NSMutableArray alloc] initWithCapacity:1];
}
return self;
}
-(void)addImageId:(NSString *)imageIdObject
{
if (imageIds == nil) {
imageIds = [[NSMutableArray alloc] initWithCapacity:1];
}
[imageIds addObject:imageIdObject];
}
-(void)addOwner:(NSString *)ownerObject
{
if (owners == nil) {
owners = [[NSMutableArray alloc] initWithCapacity:1];
}
[owners addObject:ownerObject];
}
-(void)addExecutableUser:(NSString *)executableUserObject
{
if (executableUsers == nil) {
executableUsers = [[NSMutableArray alloc] initWithCapacity:1];
}
[executableUsers addObject:executableUserObject];
}
-(void)addFilter:(EC2Filter *)filterObject
{
if (filters == nil) {
filters = [[NSMutableArray alloc] initWithCapacity:1];
}
[filters addObject:filterObject];
}
-(NSString *)description
{
NSMutableString *buffer = [[NSMutableString alloc] initWithCapacity:256];
[buffer appendString:@"{"];
[buffer appendString:[[[NSString alloc] initWithFormat:@"DryRun: %d,", dryRun] autorelease]];
[buffer appendString:[[[NSString alloc] initWithFormat:@"ImageIds: %@,", imageIds] autorelease]];
[buffer appendString:[[[NSString alloc] initWithFormat:@"Owners: %@,", owners] autorelease]];
[buffer appendString:[[[NSString alloc] initWithFormat:@"ExecutableUsers: %@,", executableUsers] autorelease]];
[buffer appendString:[[[NSString alloc] initWithFormat:@"Filters: %@,", filters] autorelease]];
[buffer appendString:[super description]];
[buffer appendString:@"}"];
return [buffer autorelease];
}
-(void)setDryRun:(BOOL)theValue
{
dryRun = theValue;
dryRunIsSet = YES;
}
-(void)dealloc
{
[imageIds release];
[owners release];
[executableUsers release];
[filters release];
[super dealloc];
}
@end
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE HTML>
<html>
<body>
<!-- Too many separators: Excess is ignored -->
<math>
<mfenced separators=";;;;,,,,">
<mi>a</mi>
<mi>b</mi>
<mi>c</mi>
<mi>d</mi>
<mi>e</mi>
</mfenced>
</math>
<!-- Too few separators: Last separator is repeated -->
<math>
<mfenced separators=";;,">
<mi>a</mi>
<mi>b</mi>
<mi>c</mi>
<mi>d</mi>
<mi>e</mi>
</mfenced>
</math>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
var mkdirp = require('../');
var path = require('path');
var fs = require('fs');
var test = require('tap').test;
test('woo', function (t) {
t.plan(2);
var x = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var y = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var z = Math.floor(Math.random() * Math.pow(16,4)).toString(16);
var file = '/tmp/' + [x,y,z].join('/');
mkdirp(file, 0755, function (err) {
if (err) t.fail(err);
else path.exists(file, function (ex) {
if (!ex) t.fail('file not created')
else fs.stat(file, function (err, stat) {
if (err) t.fail(err)
else {
t.equal(stat.mode & 0777, 0755);
t.ok(stat.isDirectory(), 'target not a directory');
t.end();
}
})
})
});
});
|
{
"pile_set_name": "Github"
}
|
/*
byteorder.h (12.01.10)
Endianness stuff. exFAT uses little-endian byte order.
Free exFAT implementation.
Copyright (C) 2010-2018 Andrew Nayenko
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef BYTEORDER_H_INCLUDED
#define BYTEORDER_H_INCLUDED
#include "platform.h"
#include <stdint.h>
#include <stddef.h>
typedef struct { uint16_t __u16; } le16_t;
typedef struct { uint32_t __u32; } le32_t;
typedef struct { uint64_t __u64; } le64_t;
#if EXFAT_BYTE_ORDER == EXFAT_LITTLE_ENDIAN
static inline uint16_t le16_to_cpu(le16_t v) { return v.__u16; }
static inline uint32_t le32_to_cpu(le32_t v) { return v.__u32; }
static inline uint64_t le64_to_cpu(le64_t v) { return v.__u64; }
static inline le16_t cpu_to_le16(uint16_t v) { le16_t t = {v}; return t; }
static inline le32_t cpu_to_le32(uint32_t v) { le32_t t = {v}; return t; }
static inline le64_t cpu_to_le64(uint64_t v) { le64_t t = {v}; return t; }
typedef size_t bitmap_t;
#elif EXFAT_BYTE_ORDER == EXFAT_BIG_ENDIAN
static inline uint16_t le16_to_cpu(le16_t v)
{ return exfat_bswap16(v.__u16); }
static inline uint32_t le32_to_cpu(le32_t v)
{ return exfat_bswap32(v.__u32); }
static inline uint64_t le64_to_cpu(le64_t v)
{ return exfat_bswap64(v.__u64); }
static inline le16_t cpu_to_le16(uint16_t v)
{ le16_t t = {exfat_bswap16(v)}; return t; }
static inline le32_t cpu_to_le32(uint32_t v)
{ le32_t t = {exfat_bswap32(v)}; return t; }
static inline le64_t cpu_to_le64(uint64_t v)
{ le64_t t = {exfat_bswap64(v)}; return t; }
typedef unsigned char bitmap_t;
#else
#error Wow! You have a PDP machine?!
#endif
#endif /* ifndef BYTEORDER_H_INCLUDED */
|
{
"pile_set_name": "Github"
}
|
DEPS:=mochiweb-wrapper webmachine-wrapper
WITH_BROKER_TEST_COMMANDS:=rabbit_web_dispatch_test:test()
STANDALONE_TEST_COMMANDS:=rabbit_web_dispatch_test_unit:test()
|
{
"pile_set_name": "Github"
}
|
net\authorize\api\contract\v1\ARBGetSubscriptionStatusResponse:
xml_root_name: ARBGetSubscriptionStatusResponse
xml_root_namespace: AnetApi/xml/v1/schema/AnetApiSchema.xsd
properties:
status:
expose: true
access_type: public_method
serialized_name: status
xml_element:
namespace: AnetApi/xml/v1/schema/AnetApiSchema.xsd
accessor:
getter: getStatus
setter: setStatus
type: string
|
{
"pile_set_name": "Github"
}
|
<?php
// Get the PHP helper library from https://twilio.com/docs/libraries/php
require_once '/path/to/vendor/autoload.php'; // Loads the library
use Twilio\Rest\Client;
// Your Account Sid and Auth Token from twilio.com/user/account
$sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$token = "your_auth_token";
$client = new Client($sid, $token);
$client->messages("MM5ef8732a3c49700934481addd5ce1659")
->delete(); // Deletes entire message record
|
{
"pile_set_name": "Github"
}
|
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 2.8
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake
# The command to remove a file.
RM = /usr/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/ewenwan/ewenwan/catkin_ws/src
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/ewenwan/ewenwan/catkin_ws/build
# Utility rule file for ros_arduino_msgs_gencpp.
# Include the progress variables for this target.
include ros_arduino_bridge/ros_arduino_msgs/CMakeFiles/ros_arduino_msgs_gencpp.dir/progress.make
ros_arduino_bridge/ros_arduino_msgs/CMakeFiles/ros_arduino_msgs_gencpp:
ros_arduino_msgs_gencpp: ros_arduino_bridge/ros_arduino_msgs/CMakeFiles/ros_arduino_msgs_gencpp
ros_arduino_msgs_gencpp: ros_arduino_bridge/ros_arduino_msgs/CMakeFiles/ros_arduino_msgs_gencpp.dir/build.make
.PHONY : ros_arduino_msgs_gencpp
# Rule to build all files generated by this target.
ros_arduino_bridge/ros_arduino_msgs/CMakeFiles/ros_arduino_msgs_gencpp.dir/build: ros_arduino_msgs_gencpp
.PHONY : ros_arduino_bridge/ros_arduino_msgs/CMakeFiles/ros_arduino_msgs_gencpp.dir/build
ros_arduino_bridge/ros_arduino_msgs/CMakeFiles/ros_arduino_msgs_gencpp.dir/clean:
cd /home/ewenwan/ewenwan/catkin_ws/build/ros_arduino_bridge/ros_arduino_msgs && $(CMAKE_COMMAND) -P CMakeFiles/ros_arduino_msgs_gencpp.dir/cmake_clean.cmake
.PHONY : ros_arduino_bridge/ros_arduino_msgs/CMakeFiles/ros_arduino_msgs_gencpp.dir/clean
ros_arduino_bridge/ros_arduino_msgs/CMakeFiles/ros_arduino_msgs_gencpp.dir/depend:
cd /home/ewenwan/ewenwan/catkin_ws/build && $(CMAKE_COMMAND) -E cmake_depends "Unix Makefiles" /home/ewenwan/ewenwan/catkin_ws/src /home/ewenwan/ewenwan/catkin_ws/src/ros_arduino_bridge/ros_arduino_msgs /home/ewenwan/ewenwan/catkin_ws/build /home/ewenwan/ewenwan/catkin_ws/build/ros_arduino_bridge/ros_arduino_msgs /home/ewenwan/ewenwan/catkin_ws/build/ros_arduino_bridge/ros_arduino_msgs/CMakeFiles/ros_arduino_msgs_gencpp.dir/DependInfo.cmake --color=$(COLOR)
.PHONY : ros_arduino_bridge/ros_arduino_msgs/CMakeFiles/ros_arduino_msgs_gencpp.dir/depend
|
{
"pile_set_name": "Github"
}
|
---
redirect_to: upgrading_from_source.md
---
This document was moved to [another location](upgrading_from_source.md).
|
{
"pile_set_name": "Github"
}
|
HEADERS += \
IFeature.h \
IProjection.h \
IImageManager.h \
IMapAdapter.h \
IRenderer.h \
IMapAdapterFactory.h \
IMapWatermark.h \
IBackend.h \
ILayer.h \
IProgressWindow.h \
IMerkMainWindow.h \
../../../interfaces/IDocument.h
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "leveldb/env.h"
#include "port/port.h"
#include "util/testharness.h"
namespace leveldb {
static const int kDelayMicros = 100000;
class EnvPosixTest {
private:
port::Mutex mu_;
std::string events_;
public:
Env* env_;
EnvPosixTest() : env_(Env::Default()) { }
};
static void SetBool(void* ptr) {
reinterpret_cast<port::AtomicPointer*>(ptr)->NoBarrier_Store(ptr);
}
TEST(EnvPosixTest, RunImmediately) {
port::AtomicPointer called (NULL);
env_->Schedule(&SetBool, &called);
Env::Default()->SleepForMicroseconds(kDelayMicros);
ASSERT_TRUE(called.NoBarrier_Load() != NULL);
}
TEST(EnvPosixTest, RunMany) {
port::AtomicPointer last_id (NULL);
struct CB {
port::AtomicPointer* last_id_ptr; // Pointer to shared slot
uintptr_t id; // Order# for the execution of this callback
CB(port::AtomicPointer* p, int i) : last_id_ptr(p), id(i) { }
static void Run(void* v) {
CB* cb = reinterpret_cast<CB*>(v);
void* cur = cb->last_id_ptr->NoBarrier_Load();
ASSERT_EQ(cb->id-1, reinterpret_cast<uintptr_t>(cur));
cb->last_id_ptr->Release_Store(reinterpret_cast<void*>(cb->id));
}
};
// Schedule in different order than start time
CB cb1(&last_id, 1);
CB cb2(&last_id, 2);
CB cb3(&last_id, 3);
CB cb4(&last_id, 4);
env_->Schedule(&CB::Run, &cb1);
env_->Schedule(&CB::Run, &cb2);
env_->Schedule(&CB::Run, &cb3);
env_->Schedule(&CB::Run, &cb4);
Env::Default()->SleepForMicroseconds(kDelayMicros);
void* cur = last_id.Acquire_Load();
ASSERT_EQ(4, reinterpret_cast<uintptr_t>(cur));
}
struct State {
port::Mutex mu;
int val;
int num_running;
};
static void ThreadBody(void* arg) {
State* s = reinterpret_cast<State*>(arg);
s->mu.Lock();
s->val += 1;
s->num_running -= 1;
s->mu.Unlock();
}
TEST(EnvPosixTest, StartThread) {
State state;
state.val = 0;
state.num_running = 3;
for (int i = 0; i < 3; i++) {
env_->StartThread(&ThreadBody, &state);
}
while (true) {
state.mu.Lock();
int num = state.num_running;
state.mu.Unlock();
if (num == 0) {
break;
}
Env::Default()->SleepForMicroseconds(kDelayMicros);
}
ASSERT_EQ(state.val, 3);
}
} // namespace leveldb
int main(int argc, char** argv) {
return leveldb::test::RunAllTests();
}
|
{
"pile_set_name": "Github"
}
|
<!--
@license
Copyright (c) 2017 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="boot.html">
<link rel="import" href="../mixins/property-effects.html">
<link rel="import" href="../mixins/mutable-data.html">
<script>
(function() {
'use strict';
// Base class for HTMLTemplateElement extension that has property effects
// machinery for propagating host properties to children. This is an ES5
// class only because Babel (incorrectly) requires super() in the class
// constructor even though no `this` is used and it returns an instance.
let newInstance = null;
/**
* @constructor
* @extends {HTMLTemplateElement}
* @private
*/
function HTMLTemplateElementExtension() { return newInstance; }
HTMLTemplateElementExtension.prototype = Object.create(HTMLTemplateElement.prototype, {
constructor: {
value: HTMLTemplateElementExtension,
writable: true
}
});
/**
* @constructor
* @implements {Polymer_PropertyEffects}
* @extends {HTMLTemplateElementExtension}
* @private
*/
const DataTemplate = Polymer.PropertyEffects(HTMLTemplateElementExtension);
/**
* @constructor
* @implements {Polymer_MutableData}
* @extends {DataTemplate}
* @private
*/
const MutableDataTemplate = Polymer.MutableData(DataTemplate);
// Applies a DataTemplate subclass to a <template> instance
function upgradeTemplate(template, constructor) {
newInstance = template;
Object.setPrototypeOf(template, constructor.prototype);
new constructor();
newInstance = null;
}
/**
* Base class for TemplateInstance.
* @constructor
* @implements {Polymer_PropertyEffects}
* @private
*/
const base = Polymer.PropertyEffects(class {});
/**
* @polymer
* @customElement
* @appliesMixin Polymer.PropertyEffects
* @unrestricted
*/
class TemplateInstanceBase extends base {
constructor(props) {
super();
this._configureProperties(props);
this.root = this._stampTemplate(this.__dataHost);
// Save list of stamped children
let children = this.children = [];
for (let n = this.root.firstChild; n; n=n.nextSibling) {
children.push(n);
n.__templatizeInstance = this;
}
if (this.__templatizeOwner &&
this.__templatizeOwner.__hideTemplateChildren__) {
this._showHideChildren(true);
}
// Flush props only when props are passed if instance props exist
// or when there isn't instance props.
let options = this.__templatizeOptions;
if ((props && options.instanceProps) || !options.instanceProps) {
this._enableProperties();
}
}
/**
* Configure the given `props` by calling `_setPendingProperty`. Also
* sets any properties stored in `__hostProps`.
* @private
* @param {Object} props Object of property name-value pairs to set.
* @return {void}
*/
_configureProperties(props) {
let options = this.__templatizeOptions;
if (options.forwardHostProp) {
for (let hprop in this.__hostProps) {
this._setPendingProperty(hprop, this.__dataHost['_host_' + hprop]);
}
}
// Any instance props passed in the constructor will overwrite host props;
// normally this would be a user error but we don't specifically filter them
for (let iprop in props) {
this._setPendingProperty(iprop, props[iprop]);
}
}
/**
* Forwards a host property to this instance. This method should be
* called on instances from the `options.forwardHostProp` callback
* to propagate changes of host properties to each instance.
*
* Note this method enqueues the change, which are flushed as a batch.
*
* @param {string} prop Property or path name
* @param {*} value Value of the property to forward
* @return {void}
*/
forwardHostProp(prop, value) {
if (this._setPendingPropertyOrPath(prop, value, false, true)) {
this.__dataHost._enqueueClient(this);
}
}
/**
* Override point for adding custom or simulated event handling.
*
* @param {!Node} node Node to add event listener to
* @param {string} eventName Name of event
* @param {function(!Event):void} handler Listener function to add
* @return {void}
*/
_addEventListenerToNode(node, eventName, handler) {
if (this._methodHost && this.__templatizeOptions.parentModel) {
// If this instance should be considered a parent model, decorate
// events this template instance as `model`
this._methodHost._addEventListenerToNode(node, eventName, (e) => {
e.model = this;
handler(e);
});
} else {
// Otherwise delegate to the template's host (which could be)
// another template instance
let templateHost = this.__dataHost.__dataHost;
if (templateHost) {
templateHost._addEventListenerToNode(node, eventName, handler);
}
}
}
/**
* Shows or hides the template instance top level child elements. For
* text nodes, `textContent` is removed while "hidden" and replaced when
* "shown."
* @param {boolean} hide Set to true to hide the children;
* set to false to show them.
* @return {void}
* @protected
*/
_showHideChildren(hide) {
let c = this.children;
for (let i=0; i<c.length; i++) {
let n = c[i];
// Ignore non-changes
if (Boolean(hide) != Boolean(n.__hideTemplateChildren__)) {
if (n.nodeType === Node.TEXT_NODE) {
if (hide) {
n.__polymerTextContent__ = n.textContent;
n.textContent = '';
} else {
n.textContent = n.__polymerTextContent__;
}
// remove and replace slot
} else if (n.localName === 'slot') {
if (hide) {
n.__polymerReplaced__ = document.createComment('hidden-slot');
n.parentNode.replaceChild(n.__polymerReplaced__, n);
} else {
const replace = n.__polymerReplaced__;
if (replace) {
replace.parentNode.replaceChild(n, replace);
}
}
}
else if (n.style) {
if (hide) {
n.__polymerDisplay__ = n.style.display;
n.style.display = 'none';
} else {
n.style.display = n.__polymerDisplay__;
}
}
}
n.__hideTemplateChildren__ = hide;
if (n._showHideChildren) {
n._showHideChildren(hide);
}
}
}
/**
* Overrides default property-effects implementation to intercept
* textContent bindings while children are "hidden" and cache in
* private storage for later retrieval.
*
* @param {!Node} node The node to set a property on
* @param {string} prop The property to set
* @param {*} value The value to set
* @return {void}
* @protected
*/
_setUnmanagedPropertyToNode(node, prop, value) {
if (node.__hideTemplateChildren__ &&
node.nodeType == Node.TEXT_NODE && prop == 'textContent') {
node.__polymerTextContent__ = value;
} else {
super._setUnmanagedPropertyToNode(node, prop, value);
}
}
/**
* Find the parent model of this template instance. The parent model
* is either another templatize instance that had option `parentModel: true`,
* or else the host element.
*
* @return {!Polymer_PropertyEffects} The parent model of this instance
*/
get parentModel() {
let model = this.__parentModel;
if (!model) {
let options;
model = this;
do {
// A template instance's `__dataHost` is a <template>
// `model.__dataHost.__dataHost` is the template's host
model = model.__dataHost.__dataHost;
} while ((options = model.__templatizeOptions) && !options.parentModel);
this.__parentModel = model;
}
return model;
}
/**
* Stub of HTMLElement's `dispatchEvent`, so that effects that may
* dispatch events safely no-op.
*
* @param {Event} event Event to dispatch
* @return {boolean} Always true.
*/
dispatchEvent(event) { // eslint-disable-line no-unused-vars
return true;
}
}
/** @type {!DataTemplate} */
TemplateInstanceBase.prototype.__dataHost;
/** @type {!TemplatizeOptions} */
TemplateInstanceBase.prototype.__templatizeOptions;
/** @type {!Polymer_PropertyEffects} */
TemplateInstanceBase.prototype._methodHost;
/** @type {!Object} */
TemplateInstanceBase.prototype.__templatizeOwner;
/** @type {!Object} */
TemplateInstanceBase.prototype.__hostProps;
/**
* @constructor
* @extends {TemplateInstanceBase}
* @implements {Polymer_MutableData}
* @private
*/
const MutableTemplateInstanceBase = Polymer.MutableData(TemplateInstanceBase);
function findMethodHost(template) {
// Technically this should be the owner of the outermost template.
// In shadow dom, this is always getRootNode().host, but we can
// approximate this via cooperation with our dataHost always setting
// `_methodHost` as long as there were bindings (or id's) on this
// instance causing it to get a dataHost.
let templateHost = template.__dataHost;
return templateHost && templateHost._methodHost || templateHost;
}
/* eslint-disable valid-jsdoc */
/**
* @suppress {missingProperties} class.prototype is not defined for some reason
*/
function createTemplatizerClass(template, templateInfo, options) {
// Anonymous class created by the templatize
let base = options.mutableData ?
MutableTemplateInstanceBase : TemplateInstanceBase;
// Affordance for global mixins onto TemplatizeInstance
if (Polymer.Templatize.mixin) {
base = Polymer.Templatize.mixin(base);
}
/**
* @constructor
* @extends {base}
* @private
*/
let klass = class extends base { };
klass.prototype.__templatizeOptions = options;
klass.prototype._bindTemplate(template);
addNotifyEffects(klass, template, templateInfo, options);
return klass;
}
/**
* @suppress {missingProperties} class.prototype is not defined for some reason
*/
function addPropagateEffects(template, templateInfo, options) {
let userForwardHostProp = options.forwardHostProp;
if (userForwardHostProp) {
// Provide data API and property effects on memoized template class
let klass = templateInfo.templatizeTemplateClass;
if (!klass) {
let base = options.mutableData ? MutableDataTemplate : DataTemplate;
/** @private */
klass = templateInfo.templatizeTemplateClass =
class TemplatizedTemplate extends base {};
// Add template - >instances effects
// and host <- template effects
let hostProps = templateInfo.hostProps;
for (let prop in hostProps) {
klass.prototype._addPropertyEffect('_host_' + prop,
klass.prototype.PROPERTY_EFFECT_TYPES.PROPAGATE,
{fn: createForwardHostPropEffect(prop, userForwardHostProp)});
klass.prototype._createNotifyingProperty('_host_' + prop);
}
}
upgradeTemplate(template, klass);
// Mix any pre-bound data into __data; no need to flush this to
// instances since they pull from the template at instance-time
if (template.__dataProto) {
// Note, generally `__dataProto` could be chained, but it's guaranteed
// to not be since this is a vanilla template we just added effects to
Object.assign(template.__data, template.__dataProto);
}
// Clear any pending data for performance
template.__dataTemp = {};
template.__dataPending = null;
template.__dataOld = null;
template._enableProperties();
}
}
/* eslint-enable valid-jsdoc */
function createForwardHostPropEffect(hostProp, userForwardHostProp) {
return function forwardHostProp(template, prop, props) {
userForwardHostProp.call(template.__templatizeOwner,
prop.substring('_host_'.length), props[prop]);
};
}
function addNotifyEffects(klass, template, templateInfo, options) {
let hostProps = templateInfo.hostProps || {};
for (let iprop in options.instanceProps) {
delete hostProps[iprop];
let userNotifyInstanceProp = options.notifyInstanceProp;
if (userNotifyInstanceProp) {
klass.prototype._addPropertyEffect(iprop,
klass.prototype.PROPERTY_EFFECT_TYPES.NOTIFY,
{fn: createNotifyInstancePropEffect(iprop, userNotifyInstanceProp)});
}
}
if (options.forwardHostProp && template.__dataHost) {
for (let hprop in hostProps) {
klass.prototype._addPropertyEffect(hprop,
klass.prototype.PROPERTY_EFFECT_TYPES.NOTIFY,
{fn: createNotifyHostPropEffect()});
}
}
}
function createNotifyInstancePropEffect(instProp, userNotifyInstanceProp) {
return function notifyInstanceProp(inst, prop, props) {
userNotifyInstanceProp.call(inst.__templatizeOwner,
inst, prop, props[prop]);
};
}
function createNotifyHostPropEffect() {
return function notifyHostProp(inst, prop, props) {
inst.__dataHost._setPendingPropertyOrPath('_host_' + prop, props[prop], true, true);
};
}
/**
* Module for preparing and stamping instances of templates that utilize
* Polymer's data-binding and declarative event listener features.
*
* Example:
*
* // Get a template from somewhere, e.g. light DOM
* let template = this.querySelector('template');
* // Prepare the template
* let TemplateClass = Polymer.Templatize.templatize(template);
* // Instance the template with an initial data model
* let instance = new TemplateClass({myProp: 'initial'});
* // Insert the instance's DOM somewhere, e.g. element's shadow DOM
* this.shadowRoot.appendChild(instance.root);
* // Changing a property on the instance will propagate to bindings
* // in the template
* instance.myProp = 'new value';
*
* The `options` dictionary passed to `templatize` allows for customizing
* features of the generated template class, including how outer-scope host
* properties should be forwarded into template instances, how any instance
* properties added into the template's scope should be notified out to
* the host, and whether the instance should be decorated as a "parent model"
* of any event handlers.
*
* // Customize property forwarding and event model decoration
* let TemplateClass = Polymer.Templatize.templatize(template, this, {
* parentModel: true,
* forwardHostProp(property, value) {...},
* instanceProps: {...},
* notifyInstanceProp(instance, property, value) {...},
* });
*
* @namespace
* @memberof Polymer
* @summary Module for preparing and stamping instances of templates
* utilizing Polymer templating features.
*/
Polymer.Templatize = {
/**
* Returns an anonymous `Polymer.PropertyEffects` class bound to the
* `<template>` provided. Instancing the class will result in the
* template being stamped into a document fragment stored as the instance's
* `root` property, after which it can be appended to the DOM.
*
* Templates may utilize all Polymer data-binding features as well as
* declarative event listeners. Event listeners and inline computing
* functions in the template will be called on the host of the template.
*
* The constructor returned takes a single argument dictionary of initial
* property values to propagate into template bindings. Additionally
* host properties can be forwarded in, and instance properties can be
* notified out by providing optional callbacks in the `options` dictionary.
*
* Valid configuration in `options` are as follows:
*
* - `forwardHostProp(property, value)`: Called when a property referenced
* in the template changed on the template's host. As this library does
* not retain references to templates instanced by the user, it is the
* templatize owner's responsibility to forward host property changes into
* user-stamped instances. The `instance.forwardHostProp(property, value)`
* method on the generated class should be called to forward host
* properties into the template to prevent unnecessary property-changed
* notifications. Any properties referenced in the template that are not
* defined in `instanceProps` will be notified up to the template's host
* automatically.
* - `instanceProps`: Dictionary of property names that will be added
* to the instance by the templatize owner. These properties shadow any
* host properties, and changes within the template to these properties
* will result in `notifyInstanceProp` being called.
* - `mutableData`: When `true`, the generated class will skip strict
* dirty-checking for objects and arrays (always consider them to be
* "dirty").
* - `notifyInstanceProp(instance, property, value)`: Called when
* an instance property changes. Users may choose to call `notifyPath`
* on e.g. the owner to notify the change.
* - `parentModel`: When `true`, events handled by declarative event listeners
* (`on-event="handler"`) will be decorated with a `model` property pointing
* to the template instance that stamped it. It will also be returned
* from `instance.parentModel` in cases where template instance nesting
* causes an inner model to shadow an outer model.
*
* All callbacks are called bound to the `owner`. Any context
* needed for the callbacks (such as references to `instances` stamped)
* should be stored on the `owner` such that they can be retrieved via
* `this`.
*
* When `options.forwardHostProp` is declared as an option, any properties
* referenced in the template will be automatically forwarded from the host of
* the `<template>` to instances, with the exception of any properties listed in
* the `options.instanceProps` object. `instanceProps` are assumed to be
* managed by the owner of the instances, either passed into the constructor
* or set after the fact. Note, any properties passed into the constructor will
* always be set to the instance (regardless of whether they would normally
* be forwarded from the host).
*
* Note that `templatize()` can be run only once for a given `<template>`.
* Further calls will result in an error. Also, there is a special
* behavior if the template was duplicated through a mechanism such as
* `<dom-repeat>` or `<test-fixture>`. In this case, all calls to
* `templatize()` return the same class for all duplicates of a template.
* The class returned from `templatize()` is generated only once using
* the `options` from the first call. This means that any `options`
* provided to subsequent calls will be ignored. Therefore, it is very
* important not to close over any variables inside the callbacks. Also,
* arrow functions must be avoided because they bind the outer `this`.
* Inside the callbacks, any contextual information can be accessed
* through `this`, which points to the `owner`.
*
* @memberof Polymer.Templatize
* @param {!HTMLTemplateElement} template Template to templatize
* @param {Polymer_PropertyEffects=} owner Owner of the template instances;
* any optional callbacks will be bound to this owner.
* @param {Object=} options Options dictionary (see summary for details)
* @return {function(new:TemplateInstanceBase)} Generated class bound to the template
* provided
* @suppress {invalidCasts}
*/
templatize(template, owner, options) {
// Under strictTemplatePolicy, the templatized element must be owned
// by a (trusted) Polymer element, indicated by existence of _methodHost;
// e.g. for dom-if & dom-repeat in main document, _methodHost is null
if (Polymer.strictTemplatePolicy && !findMethodHost(template)) {
throw new Error('strictTemplatePolicy: template owner not trusted');
}
options = /** @type {!TemplatizeOptions} */(options || {});
if (template.__templatizeOwner) {
throw new Error('A <template> can only be templatized once');
}
template.__templatizeOwner = owner;
const ctor = owner ? owner.constructor : TemplateInstanceBase;
let templateInfo = ctor._parseTemplate(template);
// Get memoized base class for the prototypical template, which
// includes property effects for binding template & forwarding
let baseClass = templateInfo.templatizeInstanceClass;
if (!baseClass) {
baseClass = createTemplatizerClass(template, templateInfo, options);
templateInfo.templatizeInstanceClass = baseClass;
}
// Host property forwarding must be installed onto template instance
addPropagateEffects(template, templateInfo, options);
// Subclass base class and add reference for this specific template
/** @private */
let klass = class TemplateInstance extends baseClass {};
klass.prototype._methodHost = findMethodHost(template);
klass.prototype.__dataHost = template;
klass.prototype.__templatizeOwner = owner;
klass.prototype.__hostProps = templateInfo.hostProps;
klass = /** @type {function(new:TemplateInstanceBase)} */(klass); //eslint-disable-line no-self-assign
return klass;
},
/**
* Returns the template "model" associated with a given element, which
* serves as the binding scope for the template instance the element is
* contained in. A template model is an instance of
* `TemplateInstanceBase`, and should be used to manipulate data
* associated with this template instance.
*
* Example:
*
* let model = modelForElement(el);
* if (model.index < 10) {
* model.set('item.checked', true);
* }
*
* @memberof Polymer.Templatize
* @param {HTMLTemplateElement} template The model will be returned for
* elements stamped from this template
* @param {Node=} node Node for which to return a template model.
* @return {TemplateInstanceBase} Template instance representing the
* binding scope for the element
*/
modelForElement(template, node) {
let model;
while (node) {
// An element with a __templatizeInstance marks the top boundary
// of a scope; walk up until we find one, and then ensure that
// its __dataHost matches `this`, meaning this dom-repeat stamped it
if ((model = node.__templatizeInstance)) {
// Found an element stamped by another template; keep walking up
// from its __dataHost
if (model.__dataHost != template) {
node = model.__dataHost;
} else {
return model;
}
} else {
// Still in a template scope, keep going up until
// a __templatizeInstance is found
node = node.parentNode;
}
}
return null;
}
};
Polymer.TemplateInstanceBase = TemplateInstanceBase;
})();
</script>
|
{
"pile_set_name": "Github"
}
|
{% extends 'layouts/application.html' %}
{% block title %}{{title}}{% endblock %}
{% block content %}
<div class="container" style="max-width: 400px;">
<form action="/signup" method="POST">
<h2>Sign Up</h2>
<p><a href="/">Back</a></p>
<p>
<input type="text" name="email" class="form-control" placeholder="Email address" value="{{form.email}}" autofocus>
</p>
<p>
<input type="password" name="password" class="form-control" placeholder="Password">
</p>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign Up</button>
</form>
<hr>
</div>
{% endblock %}
|
{
"pile_set_name": "Github"
}
|
/**
* Copyright (c) 2013-2016 Angelo ZERR.
* 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:
* Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
*/
package tern.eclipse.jface.fieldassist;
import org.eclipse.jface.fieldassist.IContentProposal;
import tern.server.protocol.completions.TernCompletionItem;
import tern.server.protocol.completions.TernCompletionProposalRec;
public class TernContentProposal extends TernCompletionItem implements
IContentProposal {
private final String content;
private final String description;
public TernContentProposal(TernCompletionProposalRec proposal) {
super(proposal);
int pos = proposal.end - proposal.start;
this.content = getSignature().substring(pos, getSignature().length());
this.description = getDoc();
}
@Override
public String getContent() {
return content;
}
@Override
public int getCursorPosition() {
return 0;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getLabel() {
return getText();
}
}
|
{
"pile_set_name": "Github"
}
|
'use strict';
function cleanCal (cal) {
var clean = {
scale: parseFloat(cal.scale) || 0
, intercept: parseFloat(cal.intercept) || 0
, slope: parseFloat(cal.slope) || 0
};
clean.valid = ! (clean.slope === 0 || clean.unfiltered === 0 || clean.scale === 0);
return clean;
}
module.exports = function withRawGlucose (entry, cals, maxRaw) {
maxRaw = maxRaw || 200;
if ( entry.type === "mbg" || entry.type === "cal" ) {
return entry;
}
var egv = entry.glucose || entry.sgv || 0;
entry.unfiltered = parseInt(entry.unfiltered) || 0;
entry.filtered = parseInt(entry.filtered) || 0;
//TODO: add time check, but how recent should it be?
//TODO: currently assuming the first is the best (and that there is probably just 1 cal)
var cal = cals && cals.length > 0 && cleanCal(cals[0]);
if (cal && cal.valid) {
if (cal.filtered === 0 || egv < 40) {
entry.raw = Math.round(cal.scale * (entry.unfiltered - cal.intercept) / cal.slope);
} else {
var ratio = cal.scale * (entry.filtered - cal.intercept) / cal.slope / egv;
entry.raw = Math.round(cal.scale * (entry.unfiltered - cal.intercept) / cal.slope / ratio);
}
if ( egv < 40 ) {
if (entry.raw) {
entry.glucose = entry.raw;
entry.fromRaw = true;
if (entry.raw <= maxRaw) {
entry.noise = 2;
} else {
entry.noise = 3;
}
} else {
entry.noise = 3;
}
} else if (! entry.noise) {
entry.noise = 0;
}
}
return entry;
};
|
{
"pile_set_name": "Github"
}
|
{
"name": "cache/array-adapter",
"description": "A PSR-6 cache implementation using a php array. This implementation supports tags",
"type": "library",
"license": "MIT",
"minimum-stability": "dev",
"prefer-stable": true,
"keywords": [
"cache",
"psr-6",
"array",
"tag"
],
"homepage": "http://www.php-cache.com/en/latest/",
"authors": [
{
"name": "Aaron Scherer",
"email": "aequasi@gmail.com",
"homepage": "https://github.com/aequasi"
},
{
"name": "Tobias Nyholm",
"email": "tobias.nyholm@gmail.com",
"homepage": "https://github.com/nyholm"
}
],
"require": {
"php": "^5.6 || ^7.0",
"psr/cache": "^1.0",
"psr/simple-cache": "^1.0",
"cache/adapter-common": "^1.0",
"cache/hierarchical-cache": "^1.0"
},
"require-dev": {
"phpunit/phpunit": "^5.7.21",
"cache/integration-tests": "^0.16"
},
"provide": {
"psr/cache-implementation": "^1.0",
"psr/simple-cache-implementation": "^1.0"
},
"autoload": {
"psr-4": {
"Cache\\Adapter\\PHPArray\\": ""
},
"exclude-from-classmap": [
"/Tests/"
]
},
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
}
}
|
{
"pile_set_name": "Github"
}
|
# frozen_string_literal: true
require 'rubygems'
class InvalidErlangmkPackageError < ArgumentError
end
module LicenseFinder
class ErlangmkPackage < Package
attr_reader :dep_parent,
:dep_name,
:dep_fetch_method,
:dep_repo_unformatted,
:dep_version_unformatted,
:dep_absolute_path
def initialize(dep_string_from_query_deps)
@dep_parent,
@dep_name,
@dep_fetch_method,
@dep_repo_unformatted,
@dep_version_unformatted,
@dep_absolute_path = dep_string_from_query_deps.split
raise_invalid(dep_string_from_query_deps) unless all_parts_valid?
super(
dep_name,
dep_version,
homepage: dep_repo,
install_path: dep_absolute_path
)
end
def package_manager
'Erlangmk'
end
def dep_version
@dep_version ||= begin
dep_version_unformatted.sub(version_prefix_re, '')
end
end
def dep_repo
@dep_repo ||= dep_repo_unformatted
.chomp('.git')
.sub('git@github.com:', 'https://github.com/')
end
def raise_invalid(dep_string)
invalid_dep_message = "'#{dep_string}' does not look like a valid Erlank.mk dependency"
valid_dep_example = "A valid dependency example: 'lager: goldrush git https://github.com/DeadZen/goldrush.git 0.1.9 /absolute/path/to/dep'"
raise(InvalidErlangmkPackageError, "#{invalid_dep_message}. #{valid_dep_example}")
end
def all_parts_valid?
dep_part_valid?(dep_parent) &&
dep_part_valid?(dep_name) &&
set?(dep_fetch_method) &&
dep_repo_valid? &&
dep_version_valid? &&
set?(dep_absolute_path)
end
private
def dep_part_valid?(dep_part)
set?(dep_part) &&
word?(dep_part)
end
def set?(dep_part)
!dep_part.nil? &&
!dep_part.empty?
end
def word?(dep_part)
dep = dep_part.chomp(':')
dep =~ word_re
end
def dep_repo_valid?
set?(dep_repo_unformatted) &&
URI.parse(dep_repo)
end
def dep_version_valid?
return false unless set?(dep_version_unformatted)
if dep_version =~ version_re
Gem::Version.correct?(dep_version)
else
dep_version =~ word_dot_re
end
end
def version_re
@version_re ||= Regexp.new('\d+\.\d+\.\d+')
end
def version_prefix_re
@version_prefix_re ||= Regexp.new('^v')
end
def word_re
@word_re ||= Regexp.new('^\w+$')
end
def word_dot_re
@word_dot_re ||= Regexp.new('^[.\w]+$')
end
end
end
|
{
"pile_set_name": "Github"
}
|
TIMESTAMP = 1569854849
SHA256 (gnome2/gconfmm-2.28.3.tar.bz2) = a5e0092bb73371a3ca76b2ecae794778f3a9409056fee9b28ec1db072d8e6108
SIZE (gnome2/gconfmm-2.28.3.tar.bz2) = 471125
|
{
"pile_set_name": "Github"
}
|
package org.infinispan.cli.resources;
/**
* @author Tristan Tarrant <tristan@infinispan.org>
* @since 10.0
**/
public class NodeResource extends AbstractResource {
public NodeResource(ClusterResource parent, String name) {
super(parent, name);
}
@Override
public boolean isLeaf() {
return true;
}
}
|
{
"pile_set_name": "Github"
}
|
//
// DocumentType.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2006 Jb Evain
//
// 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.
//
namespace Mono.Cecil.Cil {
using System;
internal abstract class DocumentType {
public static readonly Guid Other = new Guid (0x00000000, 0x0000, 0x0000, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00);
public static readonly Guid Text = new Guid (0x5a869d0b, 0x6611, 0x11d3, 0xbd, 0x2a, 0x00, 0x00, 0xf8, 0x08, 0x49, 0xbd);
}
}
|
{
"pile_set_name": "Github"
}
|
{
"annotations": {
"list": [
{
"builtIn": 1,
"datasource": "-- Grafana --",
"enable": true,
"hide": true,
"iconColor": "rgba(0, 211, 255, 1)",
"name": "Annotations \u0026 Alerts",
"type": "dashboard"
},
{
"datasource": "psql",
"enable": true,
"hide": false,
"iconColor": "rgba(255, 96, 96, 1)",
"limit": 100,
"name": "Releases",
"query": "SELECT title, description from annotations WHERE $timeFilter order by time asc",
"rawQuery": "select extract(epoch from time) AS time, title as text, description as tags from sannotations where $__timeFilter(time)",
"showIn": 0,
"tagsColumn": "title,description",
"textColumn": "",
"titleColumn": "[[full_name]] release",
"type": "alert"
}
]
},
"editable": true,
"gnetId": null,
"graphTooltip": 0,
"id": 18,
"iteration": 1586176669852,
"links": [],
"panels": [
{
"aliasColors": {},
"bars": false,
"dashLength": 10,
"dashes": false,
"datasource": "psql",
"decimals": 0,
"description": "Displays number of new/episodic PRs and number of new/episodic PRs authors.\nThe episodic author is defined as someone who hasn't created PRs in the last 3 months and no more than 12 PRs overall.",
"fill": 1,
"fillGradient": 0,
"gridPos": {
"h": 22,
"w": 24,
"x": 0,
"y": 0
},
"hiddenSeries": false,
"id": 1,
"legend": {
"alignAsTable": false,
"avg": true,
"current": true,
"hideEmpty": false,
"hideZero": false,
"max": true,
"min": true,
"rightSide": false,
"show": true,
"total": false,
"values": true
},
"lines": true,
"linewidth": 1,
"links": [],
"nullPointMode": "null",
"options": {
"dataLinks": []
},
"percentage": false,
"pointradius": 1,
"points": false,
"renderer": "flot",
"seriesOverrides": [
{
"alias": "New contributors",
"yaxis": 2
},
{
"alias": "Episodic contributors",
"yaxis": 2
}
],
"spaceLength": 10,
"stack": false,
"steppedLine": false,
"targets": [
{
"alias": "",
"dsType": "influxdb",
"format": "time_series",
"groupBy": [],
"hide": false,
"measurement": "reviewers_d",
"orderByTime": "ASC",
"policy": "autogen",
"query": "SELECT \"value\" FROM \"new_contributors_[[repogroup]]_prs_[[period]]\" WHERE $timeFilter",
"rawQuery": true,
"rawSql": "select\n time,\n value as \"Number of issues from new contributors\"\nfrom\n snew_issues\nwhere\n $__timeFilter(time)\n and period = '[[period]]'\n and series = 'new_iss[[repogroup]]iss'\norder by\n time",
"refId": "A",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
}
]
],
"tags": []
},
{
"alias": "",
"dsType": "influxdb",
"format": "time_series",
"groupBy": [],
"hide": false,
"measurement": "reviewers_d",
"orderByTime": "ASC",
"policy": "autogen",
"query": "SELECT \"value\" FROM \"new_contributors_[[repogroup]]_contributors_[[period]]\" WHERE $timeFilter",
"rawQuery": true,
"rawSql": "select\n time,\n value as \"New issue creators\"\nfrom\n snew_issues\nwhere\n $__timeFilter(time)\n and period = '[[period]]'\n and series = 'new_iss[[repogroup]]contrib'\norder by\n time",
"refId": "B",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
}
]
],
"tags": []
},
{
"alias": "",
"dsType": "influxdb",
"format": "time_series",
"groupBy": [],
"hide": false,
"measurement": "reviewers_d",
"orderByTime": "ASC",
"policy": "autogen",
"query": "SELECT \"value\" FROM \"episodic_contributors_[[repogroup]]_prs_[[period]]\" WHERE $timeFilter",
"rawQuery": true,
"rawSql": "select\n time,\n value as \"Number of issues from episodic contributors\"\nfrom\n sepisodic_issues\nwhere\n $__timeFilter(time)\n and period = '[[period]]'\n and series = 'epis_iss[[repogroup]]iss'\norder by\n time",
"refId": "C",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
}
]
],
"tags": []
},
{
"alias": "",
"dsType": "influxdb",
"format": "time_series",
"groupBy": [],
"hide": false,
"measurement": "reviewers_d",
"orderByTime": "ASC",
"policy": "autogen",
"query": "SELECT \"value\" FROM \"episodic_contributors_[[repogroup]]_contributors_[[period]]\" WHERE $timeFilter",
"rawQuery": true,
"rawSql": "select\n time,\n value as \"Episodic issue creators\"\nfrom\n sepisodic_issues\nwhere\n $__timeFilter(time)\n and period = '[[period]]'\n and series = 'epis_iss[[repogroup]]contrib'\norder by\n time",
"refId": "D",
"resultFormat": "time_series",
"select": [
[
{
"params": [
"value"
],
"type": "field"
}
]
],
"tags": []
}
],
"thresholds": [],
"timeFrom": null,
"timeRegions": [],
"timeShift": null,
"title": "New/episodic contributors/contributions ([[repogroup_name]], [[period]])",
"tooltip": {
"shared": true,
"sort": 0,
"value_type": "individual"
},
"transparent": true,
"type": "graph",
"xaxis": {
"buckets": null,
"mode": "time",
"name": null,
"show": true,
"values": [
"total"
]
},
"yaxes": [
{
"format": "none",
"label": "PRs",
"logBase": 1,
"max": null,
"min": "0",
"show": true
},
{
"format": "none",
"label": "PR authors",
"logBase": 1,
"max": null,
"min": "0",
"show": true
}
],
"yaxis": {
"align": false,
"alignLevel": null
}
},
{
"content": "${docs:raw}",
"datasource": null,
"gridPos": {
"h": 11,
"w": 24,
"x": 0,
"y": 22
},
"id": 11,
"links": [],
"mode": "html",
"options": {},
"title": "Dashboard documentation",
"type": "text"
}
],
"refresh": false,
"schemaVersion": 21,
"style": "dark",
"tags": [
"dashboard",
"backstage",
"PRs"
],
"templating": {
"list": [
{
"allValue": null,
"current": {},
"datasource": "psql",
"definition": "",
"hide": 2,
"includeAll": false,
"label": null,
"multi": false,
"name": "full_name",
"options": [],
"query": "select value_s from gha_vars where name = 'full_name'",
"refresh": 1,
"regex": "",
"skipUrlSync": true,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": null,
"current": {
"tags": [],
"text": "28 Days MA",
"value": "d28"
},
"hide": 0,
"includeAll": false,
"label": "Period",
"multi": false,
"name": "period",
"options": [
{
"selected": true,
"text": "28 Days MA",
"value": "d28"
},
{
"selected": false,
"text": "Week",
"value": "w"
},
{
"selected": false,
"text": "Month",
"value": "m"
},
{
"selected": false,
"text": "Quarter",
"value": "q"
},
{
"selected": false,
"text": "Year",
"value": "y"
}
],
"query": "d,w,m,q,y",
"skipUrlSync": false,
"type": "custom"
},
{
"allValue": null,
"current": {},
"datasource": "psql",
"definition": "",
"hide": 0,
"includeAll": false,
"label": "Repository group",
"multi": false,
"name": "repogroup_name",
"options": [],
"query": "select all_repo_group_name from tall_repo_groups order by 1",
"refresh": 1,
"regex": "",
"skipUrlSync": false,
"sort": 1,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": null,
"current": {},
"datasource": "psql",
"definition": "",
"hide": 2,
"includeAll": false,
"label": null,
"multi": false,
"name": "repogroup",
"options": [],
"query": "select all_repo_group_value from tall_repo_groups where all_repo_group_name = '[[repogroup_name]]'",
"refresh": 1,
"regex": "",
"skipUrlSync": true,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
},
{
"allValue": null,
"current": {},
"datasource": "psql",
"definition": "",
"hide": 2,
"includeAll": false,
"label": null,
"multi": false,
"name": "docs",
"options": [],
"query": "select value_s from gha_vars where name = 'new_and_episodic_issues_docs_html'",
"refresh": 1,
"regex": "",
"skipUrlSync": true,
"sort": 0,
"tagValuesQuery": "",
"tags": [],
"tagsQuery": "",
"type": "query",
"useTags": false
}
]
},
"time": {
"from": "now-1y",
"to": "now-1M"
},
"timepicker": {
"refresh_intervals": [
"5s",
"10s",
"30s",
"1m",
"5m",
"15m",
"30m",
"1h",
"2h",
"1d"
],
"time_options": [
"5m",
"15m",
"1h",
"6h",
"12h",
"24h",
"2d",
"7d",
"30d"
]
},
"timezone": "",
"title": "New and Episodic Issue Creators",
"uid": "13",
"version": 2
}
|
{
"pile_set_name": "Github"
}
|
---
# Collection Types #############################################################
################################################################################
# http://yaml.org/type/map.html -----------------------------------------------#
map:
# Unordered set of key: value pairs.
Block style: !!map
Clark : Evans
Ingy : döt Net
Oren : Ben-Kiki
Flow style: !!map { Clark: Evans, Ingy: döt Net, Oren: Ben-Kiki }
# http://yaml.org/type/omap.html ----------------------------------------------#
omap:
# Explicitly typed ordered map (dictionary).
Bestiary: !!omap
- aardvark: African pig-like ant eater. Ugly.
- anteater: South-American ant eater. Two species.
- anaconda: South-American constrictor snake. Scaly.
# Etc.
# Flow style
Numbers: !!omap [ one: 1, two: 2, three : 3 ]
# http://yaml.org/type/pairs.html ---------------------------------------------#
pairs:
# Explicitly typed pairs.
Block tasks: !!pairs
- meeting: with team.
- meeting: with boss.
- break: lunch.
- meeting: with client.
Flow tasks: !!pairs [ meeting: with team, meeting: with boss ]
# http://yaml.org/type/set.html -----------------------------------------------#
set:
# Explicitly typed set.
baseball players: !!set
? Mark McGwire
? Sammy Sosa
? Ken Griffey
# Flow style
baseball teams: !!set { Boston Red Sox, Detroit Tigers, New York Yankees }
# http://yaml.org/type/seq.html -----------------------------------------------#
seq:
# Ordered sequence of nodes
Block style: !!seq
- Mercury # Rotates - no light/dark sides.
- Venus # Deadliest. Aptly named.
- Earth # Mostly dirt.
- Mars # Seems empty.
- Jupiter # The king.
- Saturn # Pretty.
- Uranus # Where the sun hardly shines.
- Neptune # Boring. No rings.
- Pluto # You call this a planet?
Flow style: !!seq [ Mercury, Venus, Earth, Mars, # Rocks
Jupiter, Saturn, Uranus, Neptune, # Gas
Pluto ] # Overrated
# Scalar Types #################################################################
################################################################################
# http://yaml.org/type/binary.html --------------------------------------------#
binary:
canonical: !!binary "\
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5\
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+\
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC\
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs="
generic: !!binary |
R0lGODlhDAAMAIQAAP//9/X17unp5WZmZgAAAOfn515eXvPz7Y6OjuDg4J+fn5
OTk6enp56enmlpaWNjY6Ojo4SEhP/++f/++f/++f/++f/++f/++f/++f/++f/+
+f/++f/++f/++f/++f/++SH+Dk1hZGUgd2l0aCBHSU1QACwAAAAADAAMAAAFLC
AgjoEwnuNAFOhpEMTRiggcz4BNJHrv/zCFcLiwMWYNG84BwwEeECcgggoBADs=
description:
The binary value above is a tiny arrow encoded as a gif image.
# http://yaml.org/type/bool.html ----------------------------------------------#
bool:
- true
- True
- TRUE
- false
- False
- FALSE
# http://yaml.org/type/float.html ---------------------------------------------#
float:
canonical: 6.8523015e+5
exponentioal: 685.230_15e+03
fixed: 685_230.15
sexagesimal: 190:20:30.15
negative infinity: -.inf
not a number: .NaN
# http://yaml.org/type/int.html -----------------------------------------------#
int:
canonical: 685230
decimal: +685_230
octal: 02472256
hexadecimal: 0x_0A_74_AE
binary: 0b1010_0111_0100_1010_1110
sexagesimal: 190:20:30
# http://yaml.org/type/merge.html ---------------------------------------------#
merge:
- &CENTER { x: 1, y: 2 }
- &LEFT { x: 0, y: 2 }
- &BIG { r: 10 }
- &SMALL { r: 1 }
# All the following maps are equal:
- # Explicit keys
x: 1
y: 2
r: 10
label: nothing
- # Merge one map
<< : *CENTER
r: 10
label: center
- # Merge multiple maps
<< : [ *CENTER, *BIG ]
label: center/big
- # Override
<< : [ *BIG, *LEFT, *SMALL ]
x: 1
label: big/left/small
# http://yaml.org/type/null.html ----------------------------------------------#
null:
# This mapping has four keys,
# one has a value.
empty:
canonical: ~
english: null
~: null key
# This sequence has five
# entries, two have values.
sparse:
- ~
- 2nd entry
-
- 4th entry
- Null
# http://yaml.org/type/str.html -----------------------------------------------#
string: abcd
# http://yaml.org/type/timestamp.html -----------------------------------------#
timestamp:
canonical: 2001-12-15T02:59:43.1Z
valid iso8601: 2001-12-14t21:59:43.10-05:00
space separated: 2001-12-14 21:59:43.10 -5
no time zone (Z): 2001-12-15 2:59:43.10
date (00:00:00Z): 2002-12-14
# JavaScript Specific Types ####################################################
################################################################################
# https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp
regexp:
simple: !!js/regexp foobar
modifiers: !!js/regexp /foobar/mi
# https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined
undefined: !!js/undefined ~
# https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function
function: !!js/function >
function foobar() {
return 'Wow! JS-YAML Rocks!';
}
|
{
"pile_set_name": "Github"
}
|
<script type="text/javascript">
var mpq = [];
mpq.push(["init", "{{ site.JB.analytics.mixpanel.token}}"]);
(function(){var b,a,e,d,c;b=document.createElement("script");b.type="text/javascript";
b.async=true;b.src=(document.location.protocol==="https:"?"https:":"http:")+
"//api.mixpanel.com/site_media/js/api/mixpanel.js";a=document.getElementsByTagName("script")[0];
a.parentNode.insertBefore(b,a);e=function(f){return function(){mpq.push(
[f].concat(Array.prototype.slice.call(arguments,0)))}};d=["init","track","track_links",
"track_forms","register","register_once","identify","name_tag","set_config"];for(c=0;c<
d.length;c++){mpq[d[c]]=e(d[c])}})();
</script>
|
{
"pile_set_name": "Github"
}
|
# Awesome Autocomplete for GitHub
By working every day on building the best search engine, we've become obsessed with our own search experience on the websites and mobile applications we use. GitHub is quite big for us, we use their search bar every day but it was not optimal for our needs: so we just re-built Github's search the way we thought it should be and we now share it with the community via this [Chrome](https://chrome.google.com/webstore/detail/github-awesome-autocomple/djkfdjpoelphhdclfjhnffmnlnoknfnd), [Firefox](https://addons.mozilla.org/en-US/firefox/addon/github-awesome-autocomplete/) and [Safari](https://github.algolia.com/github-awesome-autocomplete.safariextz) extensions.
Algolia provides a developer-friendly SaaS API for database search. It enables any website or mobile application to easily provide its end-users with an instant and relevant search. With Algolia's unique find as you type experience, users can find what they're looking for in just a few keystrokes. Feel free to give Algolia a try with our 14-days FREE trial at [Algolia](https://www.algolia.com).
At [Algolia](https://www.algolia.com), we're git *addicts* and love using GitHub to store every single idea or project we work on. We use it both for our private and public repositories ([12 API clients](https://www.algolia.com/doc), [DocSearch](https://community.algolia.com/docsearch), [HN Search](https://github.com/algolia/hn-search) or various [d](https://github.com/algolia/instant-search-demo) [e](https://community.algolia.com/instantsearch.js/examples/media/) [m](https://community.algolia.com/instantsearch.js/examples/e-commerce/) [o](https://community.algolia.com/instantsearch.js/examples/tourism/)).
### Installation
Install it from the stores:
[](https://chrome.google.com/webstore/detail/github-awesome-autocomple/djkfdjpoelphhdclfjhnffmnlnoknfnd)
[](https://addons.mozilla.org/en-US/firefox/addon/github-awesome-autocomplete/)
[](https://github.algolia.com/github-awesome-autocomplete.safariextz)
### Features
This extension replaces GitHub's search bar and add auto-completion (instant-search & suggestion) capabilities on:
* top public repositories
* last active users
* your private repositories
* default is without Algolia: done locally in your browser using vanilla JS search
* ability to use Algolia (typo-tolerant & relevance improved) through a "Connect with GitHub" (oauth2)
* your issues
* only available if you choose to "Connect with GitHub"

From version 1.6.0, you can now also find GitHub repositories directly from the address bar, by typing `aa<space>`.

*Address bar autocompletion does not work on Safari.*
### How does it work?
* We continuously retrieve active repositories and users using [GitHub Archive](http://www.githubarchive.org/)'s dataset
* Users and repositories are stored in 2 [Algolia](https://www.algolia.com/) indices: `users` and `repositories`
* The results are fetched using [Algolia's JavaScript API client](https://github.com/algolia/algoliasearch-client-js)
* The UI uses Twitter's [typeahead.js](http://twitter.github.io/typeahead.js/) library to display the auto-completion menu
### FAQ
#### Are my private repositories sent somewhere?
By default your list of private repositories remains in your local storage. You can allow us to crawl your private repositories with a "Connect with GitHub" (oauth2) action. Your private repositories are then stored securely in our index and only you will be able to search them.
#### My private repository is not searchable, what can I do?
You need to refresh your local list of private repositories:

## Development
### Installation
```sh
$ git clone https://github.com/algolia/chrome-awesome-autocomplete.git
# in case you don't have Grunt yet
$ sudo npm install -g grunt-cli
```
### Build instructions
```sh
$ cd chrome-awesome-autocomplete
# install dependencies
$ npm install
# generate your private key (required for Chrome)
$ openssl genrsa 2048 | openssl pkcs8 -topk8 -nocrypt > mykey.pem
# build it
$ grunt
```
When developing, write unit-tests, use `dev` Grunt task to check that your JS code passes linting tests and unit-tests.
When ready to try out the extension in the browser, use default Grunt task to build it. In `build` directory you'll find develop version of the extension in `unpacked-dev` subdirectory (with source maps), and production (uglified) version in `unpacked-prod` directory.
#### Chrome
The `.crx` packed version is created from `unpacked-prod` sources.
#### Firefox
The `.zip` archive is created from `build/firefox-unpacked-prod`.
#### Safari
The `safariextz` archive is created from Safari.
### Grunt tasks
* `clean`: clean `build` directory
* `test`: JS-lint and mocha test, single run
* `dev`: continuous `test` loop
* default: `clean`, `test`, build step (copy all necessary files to `build`
directory, browserify JS sources, prepare production version (using uglify),
pack the `crx` and `xpi`
### Publishing
All publishing instructions can be found in the [CONTRIBUTING.md file](CONTRIBUTING.md).
|
{
"pile_set_name": "Github"
}
|
#
# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation. Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
#
# COPYRIGHT AND PERMISSION NOTICE
#
# Copyright (C) 1991-2011 Unicode, Inc. All rights reserved.
# Distributed under the Terms of Use in http://www.unicode.org/copyright.html.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of the Unicode data files and any associated documentation (the
# "Data Files") or Unicode software and any associated documentation
# (the "Software") to deal in the Data Files or Software without
# restriction, including without limitation the rights to use, copy,
# modify, merge, publish, distribute, and/or sell copies of the Data
# Files or Software, and to permit persons to whom the Data Files or
# Software are furnished to do so, provided that (a) the above copyright
# notice(s) and this permission notice appear with all copies of the
# Data Files or Software, (b) both the above copyright notice(s) and
# this permission notice appear in associated documentation, and (c)
# there is clear notice in each modified Data File or in the Software as
# well as in the documentation associated with the Data File(s) or
# Software that the data or software has been modified.
#
# THE DATA FILES AND SOFTWARE ARE 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 OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR
# ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR
# SOFTWARE.
#
# Except as contained in this notice, the name of a copyright holder
# shall not be used in advertising or otherwise to promote the sale, use
# or other dealings in these Data Files or Software without prior
# written authorization of the copyright holder.
#
# Generated automatically from the Common Locale Data Repository. DO NOT EDIT!
#
EUR=\u20ac
eur=Evro
|
{
"pile_set_name": "Github"
}
|
/*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
*/
#include <Kokkos_Core.hpp>
#include <cuda/TestCuda_Category.hpp>
namespace Test {
__global__ void offset(int* p) {
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx < 100) {
p[idx] += idx;
}
}
// Test whether allocations survive Kokkos initialize/finalize if done via Raw
// Cuda.
TEST(cuda, raw_cuda_interop) {
int* p;
cudaMalloc(&p, sizeof(int) * 100);
Kokkos::InitArguments arguments{-1, -1, -1, false};
Kokkos::initialize(arguments);
Kokkos::View<int*, Kokkos::MemoryTraits<Kokkos::Unmanaged>> v(p, 100);
Kokkos::deep_copy(v, 5);
Kokkos::finalize();
offset<<<100, 64>>>(p);
CUDA_SAFE_CALL(cudaDeviceSynchronize());
int* h_p = new int[100];
cudaMemcpy(h_p, p, sizeof(int) * 100, cudaMemcpyDefault);
CUDA_SAFE_CALL(cudaDeviceSynchronize());
int64_t sum = 0;
int64_t sum_expect = 0;
for (int i = 0; i < 100; i++) {
sum += h_p[i];
sum_expect += 5 + i;
}
ASSERT_EQ(sum, sum_expect);
}
} // namespace Test
|
{
"pile_set_name": "Github"
}
|
// Copyright 2005, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Author: wan@google.com (Zhanyong Wan)
//
// The Google C++ Testing Framework (Google Test)
//
// This header file defines the public API for Google Test. It should be
// included by any test program that uses Google Test.
//
// IMPORTANT NOTE: Due to limitation of the C++ language, we have to
// leave some internal implementation details in this header file.
// They are clearly marked by comments like this:
//
// // INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
//
// Such code is NOT meant to be used by a user directly, and is subject
// to CHANGE WITHOUT NOTICE. Therefore DO NOT DEPEND ON IT in a user
// program!
//
// Acknowledgment: Google Test borrowed the idea of automatic test
// registration from Barthelemy Dagenais' (barthelemy@prologique.com)
// easyUnit framework.
#ifndef GTEST_INCLUDE_GTEST_GTEST_H_
#define GTEST_INCLUDE_GTEST_GTEST_H_
#include <limits>
#include <vector>
#include "gtest/internal/gtest-internal.h"
#include "gtest/internal/gtest-string.h"
#include "gtest/gtest-death-test.h"
#include "gtest/gtest-message.h"
#include "gtest/gtest-param-test.h"
#include "gtest/gtest-printers.h"
#include "gtest/gtest_prod.h"
#include "gtest/gtest-test-part.h"
#include "gtest/gtest-typed-test.h"
// Depending on the platform, different string classes are available.
// On Linux, in addition to ::std::string, Google also makes use of
// class ::string, which has the same interface as ::std::string, but
// has a different implementation.
//
// The user can define GTEST_HAS_GLOBAL_STRING to 1 to indicate that
// ::string is available AND is a distinct type to ::std::string, or
// define it to 0 to indicate otherwise.
//
// If the user's ::std::string and ::string are the same class due to
// aliasing, he should define GTEST_HAS_GLOBAL_STRING to 0.
//
// If the user doesn't define GTEST_HAS_GLOBAL_STRING, it is defined
// heuristically.
namespace testing {
// Declares the flags.
// This flag temporary enables the disabled tests.
GTEST_DECLARE_bool_(also_run_disabled_tests);
// This flag brings the debugger on an assertion failure.
GTEST_DECLARE_bool_(break_on_failure);
// This flag controls whether Google Test catches all test-thrown exceptions
// and logs them as failures.
GTEST_DECLARE_bool_(catch_exceptions);
// This flag enables using colors in terminal output. Available values are
// "yes" to enable colors, "no" (disable colors), or "auto" (the default)
// to let Google Test decide.
GTEST_DECLARE_string_(color);
// This flag sets up the filter to select by name using a glob pattern
// the tests to run. If the filter is not given all tests are executed.
GTEST_DECLARE_string_(filter);
// This flag causes the Google Test to list tests. None of the tests listed
// are actually run if the flag is provided.
GTEST_DECLARE_bool_(list_tests);
// This flag controls whether Google Test emits a detailed XML report to a file
// in addition to its normal textual output.
GTEST_DECLARE_string_(output);
// This flags control whether Google Test prints the elapsed time for each
// test.
GTEST_DECLARE_bool_(print_time);
// This flag specifies the random number seed.
GTEST_DECLARE_int32_(random_seed);
// This flag sets how many times the tests are repeated. The default value
// is 1. If the value is -1 the tests are repeating forever.
GTEST_DECLARE_int32_(repeat);
// This flag controls whether Google Test includes Google Test internal
// stack frames in failure stack traces.
GTEST_DECLARE_bool_(show_internal_stack_frames);
// When this flag is specified, tests' order is randomized on every iteration.
GTEST_DECLARE_bool_(shuffle);
// This flag specifies the maximum number of stack frames to be
// printed in a failure message.
GTEST_DECLARE_int32_(stack_trace_depth);
// When this flag is specified, a failed assertion will throw an
// exception if exceptions are enabled, or exit the program with a
// non-zero code otherwise.
GTEST_DECLARE_bool_(throw_on_failure);
// When this flag is set with a "host:port" string, on supported
// platforms test results are streamed to the specified port on
// the specified host machine.
GTEST_DECLARE_string_(stream_result_to);
// The upper limit for valid stack trace depths.
const int kMaxStackTraceDepth = 100;
namespace internal {
class AssertHelper;
class DefaultGlobalTestPartResultReporter;
class ExecDeathTest;
class NoExecDeathTest;
class FinalSuccessChecker;
class GTestFlagSaver;
class TestResultAccessor;
class TestEventListenersAccessor;
class TestEventRepeater;
class WindowsDeathTest;
class UnitTestImpl* GetUnitTestImpl();
void ReportFailureInUnknownLocation(TestPartResult::Type result_type,
const String& message);
// Converts a streamable value to a String. A NULL pointer is
// converted to "(null)". When the input value is a ::string,
// ::std::string, ::wstring, or ::std::wstring object, each NUL
// character in it is replaced with "\\0".
// Declared in gtest-internal.h but defined here, so that it has access
// to the definition of the Message class, required by the ARM
// compiler.
template <typename T>
String StreamableToString(const T& streamable) {
return (Message() << streamable).GetString();
}
} // namespace internal
// The friend relationship of some of these classes is cyclic.
// If we don't forward declare them the compiler might confuse the classes
// in friendship clauses with same named classes on the scope.
class Test;
class TestCase;
class TestInfo;
class UnitTest;
// A class for indicating whether an assertion was successful. When
// the assertion wasn't successful, the AssertionResult object
// remembers a non-empty message that describes how it failed.
//
// To create an instance of this class, use one of the factory functions
// (AssertionSuccess() and AssertionFailure()).
//
// This class is useful for two purposes:
// 1. Defining predicate functions to be used with Boolean test assertions
// EXPECT_TRUE/EXPECT_FALSE and their ASSERT_ counterparts
// 2. Defining predicate-format functions to be
// used with predicate assertions (ASSERT_PRED_FORMAT*, etc).
//
// For example, if you define IsEven predicate:
//
// testing::AssertionResult IsEven(int n) {
// if ((n % 2) == 0)
// return testing::AssertionSuccess();
// else
// return testing::AssertionFailure() << n << " is odd";
// }
//
// Then the failed expectation EXPECT_TRUE(IsEven(Fib(5)))
// will print the message
//
// Value of: IsEven(Fib(5))
// Actual: false (5 is odd)
// Expected: true
//
// instead of a more opaque
//
// Value of: IsEven(Fib(5))
// Actual: false
// Expected: true
//
// in case IsEven is a simple Boolean predicate.
//
// If you expect your predicate to be reused and want to support informative
// messages in EXPECT_FALSE and ASSERT_FALSE (negative assertions show up
// about half as often as positive ones in our tests), supply messages for
// both success and failure cases:
//
// testing::AssertionResult IsEven(int n) {
// if ((n % 2) == 0)
// return testing::AssertionSuccess() << n << " is even";
// else
// return testing::AssertionFailure() << n << " is odd";
// }
//
// Then a statement EXPECT_FALSE(IsEven(Fib(6))) will print
//
// Value of: IsEven(Fib(6))
// Actual: true (8 is even)
// Expected: false
//
// NB: Predicates that support negative Boolean assertions have reduced
// performance in positive ones so be careful not to use them in tests
// that have lots (tens of thousands) of positive Boolean assertions.
//
// To use this class with EXPECT_PRED_FORMAT assertions such as:
//
// // Verifies that Foo() returns an even number.
// EXPECT_PRED_FORMAT1(IsEven, Foo());
//
// you need to define:
//
// testing::AssertionResult IsEven(const char* expr, int n) {
// if ((n % 2) == 0)
// return testing::AssertionSuccess();
// else
// return testing::AssertionFailure()
// << "Expected: " << expr << " is even\n Actual: it's " << n;
// }
//
// If Foo() returns 5, you will see the following message:
//
// Expected: Foo() is even
// Actual: it's 5
//
class GTEST_API_ AssertionResult {
public:
// Copy constructor.
// Used in EXPECT_TRUE/FALSE(assertion_result).
AssertionResult(const AssertionResult& other);
// Used in the EXPECT_TRUE/FALSE(bool_expression).
explicit AssertionResult(bool success) : success_(success) {}
// Returns true iff the assertion succeeded.
operator bool() const { return success_; } // NOLINT
// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.
AssertionResult operator!() const;
// Returns the text streamed into this AssertionResult. Test assertions
// use it when they fail (i.e., the predicate's outcome doesn't match the
// assertion's expectation). When nothing has been streamed into the
// object, returns an empty string.
const char* message() const {
return message_.get() != NULL ? message_->c_str() : "";
}
// TODO(vladl@google.com): Remove this after making sure no clients use it.
// Deprecated; please use message() instead.
const char* failure_message() const { return message(); }
// Streams a custom failure message into this object.
template <typename T> AssertionResult& operator<<(const T& value) {
AppendMessage(Message() << value);
return *this;
}
// Allows streaming basic output manipulators such as endl or flush into
// this object.
AssertionResult& operator<<(
::std::ostream& (*basic_manipulator)(::std::ostream& stream)) {
AppendMessage(Message() << basic_manipulator);
return *this;
}
private:
// Appends the contents of message to message_.
void AppendMessage(const Message& a_message) {
if (message_.get() == NULL)
message_.reset(new ::std::string);
message_->append(a_message.GetString().c_str());
}
// Stores result of the assertion predicate.
bool success_;
// Stores the message describing the condition in case the expectation
// construct is not satisfied with the predicate's outcome.
// Referenced via a pointer to avoid taking too much stack frame space
// with test assertions.
internal::scoped_ptr< ::std::string> message_;
GTEST_DISALLOW_ASSIGN_(AssertionResult);
};
// Makes a successful assertion result.
GTEST_API_ AssertionResult AssertionSuccess();
// Makes a failed assertion result.
GTEST_API_ AssertionResult AssertionFailure();
// Makes a failed assertion result with the given failure message.
// Deprecated; use AssertionFailure() << msg.
GTEST_API_ AssertionResult AssertionFailure(const Message& msg);
// The abstract class that all tests inherit from.
//
// In Google Test, a unit test program contains one or many TestCases, and
// each TestCase contains one or many Tests.
//
// When you define a test using the TEST macro, you don't need to
// explicitly derive from Test - the TEST macro automatically does
// this for you.
//
// The only time you derive from Test is when defining a test fixture
// to be used a TEST_F. For example:
//
// class FooTest : public testing::Test {
// protected:
// virtual void SetUp() { ... }
// virtual void TearDown() { ... }
// ...
// };
//
// TEST_F(FooTest, Bar) { ... }
// TEST_F(FooTest, Baz) { ... }
//
// Test is not copyable.
class GTEST_API_ Test {
public:
friend class TestInfo;
// Defines types for pointers to functions that set up and tear down
// a test case.
typedef internal::SetUpTestCaseFunc SetUpTestCaseFunc;
typedef internal::TearDownTestCaseFunc TearDownTestCaseFunc;
// The d'tor is virtual as we intend to inherit from Test.
virtual ~Test();
// Sets up the stuff shared by all tests in this test case.
//
// Google Test will call Foo::SetUpTestCase() before running the first
// test in test case Foo. Hence a sub-class can define its own
// SetUpTestCase() method to shadow the one defined in the super
// class.
static void SetUpTestCase() {}
// Tears down the stuff shared by all tests in this test case.
//
// Google Test will call Foo::TearDownTestCase() after running the last
// test in test case Foo. Hence a sub-class can define its own
// TearDownTestCase() method to shadow the one defined in the super
// class.
static void TearDownTestCase() {}
// Returns true iff the current test has a fatal failure.
static bool HasFatalFailure();
// Returns true iff the current test has a non-fatal failure.
static bool HasNonfatalFailure();
// Returns true iff the current test has a (either fatal or
// non-fatal) failure.
static bool HasFailure() { return HasFatalFailure() || HasNonfatalFailure(); }
// Logs a property for the current test. Only the last value for a given
// key is remembered.
// These are public static so they can be called from utility functions
// that are not members of the test fixture.
// The arguments are const char* instead strings, as Google Test is used
// on platforms where string doesn't compile.
//
// Note that a driving consideration for these RecordProperty methods
// was to produce xml output suited to the Greenspan charting utility,
// which at present will only chart values that fit in a 32-bit int. It
// is the user's responsibility to restrict their values to 32-bit ints
// if they intend them to be used with Greenspan.
static void RecordProperty(const char* key, const char* value);
static void RecordProperty(const char* key, int value);
protected:
// Creates a Test object.
Test();
// Sets up the test fixture.
virtual void SetUp();
// Tears down the test fixture.
virtual void TearDown();
private:
// Returns true iff the current test has the same fixture class as
// the first test in the current test case.
static bool HasSameFixtureClass();
// Runs the test after the test fixture has been set up.
//
// A sub-class must implement this to define the test logic.
//
// DO NOT OVERRIDE THIS FUNCTION DIRECTLY IN A USER PROGRAM.
// Instead, use the TEST or TEST_F macro.
virtual void TestBody() = 0;
// Sets up, executes, and tears down the test.
void Run();
// Deletes self. We deliberately pick an unusual name for this
// internal method to avoid clashing with names used in user TESTs.
void DeleteSelf_() { delete this; }
// Uses a GTestFlagSaver to save and restore all Google Test flags.
const internal::GTestFlagSaver* const gtest_flag_saver_;
// Often a user mis-spells SetUp() as Setup() and spends a long time
// wondering why it is never called by Google Test. The declaration of
// the following method is solely for catching such an error at
// compile time:
//
// - The return type is deliberately chosen to be not void, so it
// will be a conflict if a user declares void Setup() in his test
// fixture.
//
// - This method is private, so it will be another compiler error
// if a user calls it from his test fixture.
//
// DO NOT OVERRIDE THIS FUNCTION.
//
// If you see an error about overriding the following function or
// about it being private, you have mis-spelled SetUp() as Setup().
struct Setup_should_be_spelled_SetUp {};
virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
// We disallow copying Tests.
GTEST_DISALLOW_COPY_AND_ASSIGN_(Test);
};
typedef internal::TimeInMillis TimeInMillis;
// A copyable object representing a user specified test property which can be
// output as a key/value string pair.
//
// Don't inherit from TestProperty as its destructor is not virtual.
class TestProperty {
public:
// C'tor. TestProperty does NOT have a default constructor.
// Always use this constructor (with parameters) to create a
// TestProperty object.
TestProperty(const char* a_key, const char* a_value) :
key_(a_key), value_(a_value) {
}
// Gets the user supplied key.
const char* key() const {
return key_.c_str();
}
// Gets the user supplied value.
const char* value() const {
return value_.c_str();
}
// Sets a new value, overriding the one supplied in the constructor.
void SetValue(const char* new_value) {
value_ = new_value;
}
private:
// The key supplied by the user.
internal::String key_;
// The value supplied by the user.
internal::String value_;
};
// The result of a single Test. This includes a list of
// TestPartResults, a list of TestProperties, a count of how many
// death tests there are in the Test, and how much time it took to run
// the Test.
//
// TestResult is not copyable.
class GTEST_API_ TestResult {
public:
// Creates an empty TestResult.
TestResult();
// D'tor. Do not inherit from TestResult.
~TestResult();
// Gets the number of all test parts. This is the sum of the number
// of successful test parts and the number of failed test parts.
int total_part_count() const;
// Returns the number of the test properties.
int test_property_count() const;
// Returns true iff the test passed (i.e. no test part failed).
bool Passed() const { return !Failed(); }
// Returns true iff the test failed.
bool Failed() const;
// Returns true iff the test fatally failed.
bool HasFatalFailure() const;
// Returns true iff the test has a non-fatal failure.
bool HasNonfatalFailure() const;
// Returns the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; }
// Returns the i-th test part result among all the results. i can range
// from 0 to test_property_count() - 1. If i is not in that range, aborts
// the program.
const TestPartResult& GetTestPartResult(int i) const;
// Returns the i-th test property. i can range from 0 to
// test_property_count() - 1. If i is not in that range, aborts the
// program.
const TestProperty& GetTestProperty(int i) const;
private:
friend class TestInfo;
friend class UnitTest;
friend class internal::DefaultGlobalTestPartResultReporter;
friend class internal::ExecDeathTest;
friend class internal::TestResultAccessor;
friend class internal::UnitTestImpl;
friend class internal::WindowsDeathTest;
// Gets the vector of TestPartResults.
const std::vector<TestPartResult>& test_part_results() const {
return test_part_results_;
}
// Gets the vector of TestProperties.
const std::vector<TestProperty>& test_properties() const {
return test_properties_;
}
// Sets the elapsed time.
void set_elapsed_time(TimeInMillis elapsed) { elapsed_time_ = elapsed; }
// Adds a test property to the list. The property is validated and may add
// a non-fatal failure if invalid (e.g., if it conflicts with reserved
// key names). If a property is already recorded for the same key, the
// value will be updated, rather than storing multiple values for the same
// key.
void RecordProperty(const TestProperty& test_property);
// Adds a failure if the key is a reserved attribute of Google Test
// testcase tags. Returns true if the property is valid.
// TODO(russr): Validate attribute names are legal and human readable.
static bool ValidateTestProperty(const TestProperty& test_property);
// Adds a test part result to the list.
void AddTestPartResult(const TestPartResult& test_part_result);
// Returns the death test count.
int death_test_count() const { return death_test_count_; }
// Increments the death test count, returning the new count.
int increment_death_test_count() { return ++death_test_count_; }
// Clears the test part results.
void ClearTestPartResults();
// Clears the object.
void Clear();
// Protects mutable state of the property vector and of owned
// properties, whose values may be updated.
internal::Mutex test_properites_mutex_;
// The vector of TestPartResults
std::vector<TestPartResult> test_part_results_;
// The vector of TestProperties
std::vector<TestProperty> test_properties_;
// Running count of death tests.
int death_test_count_;
// The elapsed time, in milliseconds.
TimeInMillis elapsed_time_;
// We disallow copying TestResult.
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestResult);
}; // class TestResult
// A TestInfo object stores the following information about a test:
//
// Test case name
// Test name
// Whether the test should be run
// A function pointer that creates the test object when invoked
// Test result
//
// The constructor of TestInfo registers itself with the UnitTest
// singleton such that the RUN_ALL_TESTS() macro knows which tests to
// run.
class GTEST_API_ TestInfo {
public:
// Destructs a TestInfo object. This function is not virtual, so
// don't inherit from TestInfo.
~TestInfo();
// Returns the test case name.
const char* test_case_name() const { return test_case_name_.c_str(); }
// Returns the test name.
const char* name() const { return name_.c_str(); }
// Returns the name of the parameter type, or NULL if this is not a typed
// or a type-parameterized test.
const char* type_param() const {
if (type_param_.get() != NULL)
return type_param_->c_str();
return NULL;
}
// Returns the text representation of the value parameter, or NULL if this
// is not a value-parameterized test.
const char* value_param() const {
if (value_param_.get() != NULL)
return value_param_->c_str();
return NULL;
}
// Returns true if this test should run, that is if the test is not disabled
// (or it is disabled but the also_run_disabled_tests flag has been specified)
// and its full name matches the user-specified filter.
//
// Google Test allows the user to filter the tests by their full names.
// The full name of a test Bar in test case Foo is defined as
// "Foo.Bar". Only the tests that match the filter will run.
//
// A filter is a colon-separated list of glob (not regex) patterns,
// optionally followed by a '-' and a colon-separated list of
// negative patterns (tests to exclude). A test is run if it
// matches one of the positive patterns and does not match any of
// the negative patterns.
//
// For example, *A*:Foo.* is a filter that matches any string that
// contains the character 'A' or starts with "Foo.".
bool should_run() const { return should_run_; }
// Returns true if the test was filtered out by --gtest_filter
bool filtered_out() const { return !matches_filter_; }
// Returns the result of the test.
const TestResult* result() const { return &result_; }
private:
#if GTEST_HAS_DEATH_TEST
friend class internal::DefaultDeathTestFactory;
#endif // GTEST_HAS_DEATH_TEST
friend class Test;
friend class TestCase;
friend class internal::UnitTestImpl;
friend TestInfo* internal::MakeAndRegisterTestInfo(
const char* test_case_name, const char* name,
const char* type_param,
const char* value_param,
internal::TypeId fixture_class_id,
Test::SetUpTestCaseFunc set_up_tc,
Test::TearDownTestCaseFunc tear_down_tc,
internal::TestFactoryBase* factory);
// Constructs a TestInfo object. The newly constructed instance assumes
// ownership of the factory object.
TestInfo(const char* test_case_name, const char* name,
const char* a_type_param,
const char* a_value_param,
internal::TypeId fixture_class_id,
internal::TestFactoryBase* factory);
// Increments the number of death tests encountered in this test so
// far.
int increment_death_test_count() {
return result_.increment_death_test_count();
}
// Creates the test object, runs it, records its result, and then
// deletes it.
void Run();
static void ClearTestResult(TestInfo* test_info) {
test_info->result_.Clear();
}
// These fields are immutable properties of the test.
const std::string test_case_name_; // Test case name
const std::string name_; // Test name
// Name of the parameter type, or NULL if this is not a typed or a
// type-parameterized test.
const internal::scoped_ptr<const ::std::string> type_param_;
// Text representation of the value parameter, or NULL if this is not a
// value-parameterized test.
const internal::scoped_ptr<const ::std::string> value_param_;
const internal::TypeId fixture_class_id_; // ID of the test fixture class
bool should_run_; // True iff this test should run
bool is_disabled_; // True iff this test is disabled
bool matches_filter_; // True if this test matches the
// user-specified filter.
internal::TestFactoryBase* const factory_; // The factory that creates
// the test object
// This field is mutable and needs to be reset before running the
// test for the second time.
TestResult result_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestInfo);
};
// A test case, which consists of a vector of TestInfos.
//
// TestCase is not copyable.
class GTEST_API_ TestCase {
public:
// Creates a TestCase with the given name.
//
// TestCase does NOT have a default constructor. Always use this
// constructor to create a TestCase object.
//
// Arguments:
//
// name: name of the test case
// a_type_param: the name of the test's type parameter, or NULL if
// this is not a type-parameterized test.
// set_up_tc: pointer to the function that sets up the test case
// tear_down_tc: pointer to the function that tears down the test case
TestCase(const char* name, const char* a_type_param,
Test::SetUpTestCaseFunc set_up_tc,
Test::TearDownTestCaseFunc tear_down_tc);
// Destructor of TestCase.
virtual ~TestCase();
// Gets the name of the TestCase.
const char* name() const { return name_.c_str(); }
// Returns the name of the parameter type, or NULL if this is not a
// type-parameterized test case.
const char* type_param() const {
if (type_param_.get() != NULL)
return type_param_->c_str();
return NULL;
}
// Returns true if any test in this test case should run.
bool should_run() const { return should_run_; }
// Returns true if this test case should be skipped in the report.
bool should_skip_report() const { return should_skip_report_; }
// Gets the number of successful tests in this test case.
int successful_test_count() const;
// Gets the number of failed tests in this test case.
int failed_test_count() const;
// Gets the number of disabled tests in this test case.
int disabled_test_count() const;
// Get the number of tests in this test case that should run.
int test_to_run_count() const;
// Gets the number of all tests in this test case.
int total_test_count() const;
// Returns true iff the test case passed.
bool Passed() const { return !Failed(); }
// Returns true iff the test case failed.
bool Failed() const { return failed_test_count() > 0; }
// Returns the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const { return elapsed_time_; }
// Returns the i-th test among all the tests. i can range from 0 to
// total_test_count() - 1. If i is not in that range, returns NULL.
const TestInfo* GetTestInfo(int i) const;
private:
friend class Test;
friend class internal::UnitTestImpl;
// Gets the (mutable) vector of TestInfos in this TestCase.
std::vector<TestInfo*>& test_info_list() { return test_info_list_; }
// Gets the (immutable) vector of TestInfos in this TestCase.
const std::vector<TestInfo*>& test_info_list() const {
return test_info_list_;
}
// Returns the i-th test among all the tests. i can range from 0 to
// total_test_count() - 1. If i is not in that range, returns NULL.
TestInfo* GetMutableTestInfo(int i);
// Sets the should_run member.
void set_should_run(bool should) { should_run_ = should; }
void set_should_skip_report(bool should) { should_skip_report_ = should; }
// Adds a TestInfo to this test case. Will delete the TestInfo upon
// destruction of the TestCase object.
void AddTestInfo(TestInfo * test_info);
// Clears the results of all tests in this test case.
void ClearResult();
// Clears the results of all tests in the given test case.
static void ClearTestCaseResult(TestCase* test_case) {
test_case->ClearResult();
}
// Runs every test in this TestCase.
void Run();
// Runs SetUpTestCase() for this TestCase. This wrapper is needed
// for catching exceptions thrown from SetUpTestCase().
void RunSetUpTestCase() { (*set_up_tc_)(); }
// Runs TearDownTestCase() for this TestCase. This wrapper is
// needed for catching exceptions thrown from TearDownTestCase().
void RunTearDownTestCase() { (*tear_down_tc_)(); }
// Returns true iff test passed.
static bool TestPassed(const TestInfo* test_info) {
return test_info->should_run() && test_info->result()->Passed();
}
// Returns true iff test failed.
static bool TestFailed(const TestInfo* test_info) {
return test_info->should_run() && test_info->result()->Failed();
}
// Returns true iff test is disabled.
static bool TestDisabled(const TestInfo* test_info) {
return test_info->is_disabled_;
}
// Returns true if the given test should run.
static bool ShouldRunTest(const TestInfo* test_info) {
return test_info->should_run();
}
// Shuffles the tests in this test case.
void ShuffleTests(internal::Random* random);
// Restores the test order to before the first shuffle.
void UnshuffleTests();
// Name of the test case.
internal::String name_;
// Name of the parameter type, or NULL if this is not a typed or a
// type-parameterized test.
const internal::scoped_ptr<const ::std::string> type_param_;
// The vector of TestInfos in their original order. It owns the
// elements in the vector.
std::vector<TestInfo*> test_info_list_;
// Provides a level of indirection for the test list to allow easy
// shuffling and restoring the test order. The i-th element in this
// vector is the index of the i-th test in the shuffled test list.
std::vector<int> test_indices_;
// Pointer to the function that sets up the test case.
Test::SetUpTestCaseFunc set_up_tc_;
// Pointer to the function that tears down the test case.
Test::TearDownTestCaseFunc tear_down_tc_;
// True iff any test in this test case should run.
bool should_run_;
// True if this test case should not be reported
bool should_skip_report_;
// Elapsed time, in milliseconds.
TimeInMillis elapsed_time_;
// We disallow copying TestCases.
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestCase);
};
// An Environment object is capable of setting up and tearing down an
// environment. The user should subclass this to define his own
// environment(s).
//
// An Environment object does the set-up and tear-down in virtual
// methods SetUp() and TearDown() instead of the constructor and the
// destructor, as:
//
// 1. You cannot safely throw from a destructor. This is a problem
// as in some cases Google Test is used where exceptions are enabled, and
// we may want to implement ASSERT_* using exceptions where they are
// available.
// 2. You cannot use ASSERT_* directly in a constructor or
// destructor.
class Environment {
public:
// The d'tor is virtual as we need to subclass Environment.
virtual ~Environment() {}
// Override this to define how to set up the environment.
virtual void SetUp() {}
// Override this to define how to tear down the environment.
virtual void TearDown() {}
private:
// If you see an error about overriding the following function or
// about it being private, you have mis-spelled SetUp() as Setup().
struct Setup_should_be_spelled_SetUp {};
virtual Setup_should_be_spelled_SetUp* Setup() { return NULL; }
};
// The interface for tracing execution of tests. The methods are organized in
// the order the corresponding events are fired.
class TestEventListener {
public:
virtual ~TestEventListener() {}
// Fired before any test activity starts.
virtual void OnTestProgramStart(const UnitTest& unit_test) = 0;
// Fired before each iteration of tests starts. There may be more than
// one iteration if GTEST_FLAG(repeat) is set. iteration is the iteration
// index, starting from 0.
virtual void OnTestIterationStart(const UnitTest& unit_test,
int iteration) = 0;
// Fired before environment set-up for each iteration of tests starts.
virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test) = 0;
// Fired after environment set-up for each iteration of tests ends.
virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test) = 0;
// Fired before the test case starts.
virtual void OnTestCaseStart(const TestCase& test_case) = 0;
// Fired before the test starts.
virtual void OnTestStart(const TestInfo& test_info) = 0;
// Fired after a failed assertion or a SUCCEED() invocation.
virtual void OnTestPartResult(const TestPartResult& test_part_result) = 0;
// Fired after the test ends.
virtual void OnTestEnd(const TestInfo& test_info) = 0;
// Fired after the test case ends.
virtual void OnTestCaseEnd(const TestCase& test_case) = 0;
// Fired before environment tear-down for each iteration of tests starts.
virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test) = 0;
// Fired after environment tear-down for each iteration of tests ends.
virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test) = 0;
// Fired after each iteration of tests finishes.
virtual void OnTestIterationEnd(const UnitTest& unit_test,
int iteration) = 0;
// Fired after all test activities have ended.
virtual void OnTestProgramEnd(const UnitTest& unit_test) = 0;
};
// The convenience class for users who need to override just one or two
// methods and are not concerned that a possible change to a signature of
// the methods they override will not be caught during the build. For
// comments about each method please see the definition of TestEventListener
// above.
class EmptyTestEventListener : public TestEventListener {
public:
virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}
virtual void OnTestIterationStart(const UnitTest& /*unit_test*/,
int /*iteration*/) {}
virtual void OnEnvironmentsSetUpStart(const UnitTest& /*unit_test*/) {}
virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}
virtual void OnTestCaseStart(const TestCase& /*test_case*/) {}
virtual void OnTestStart(const TestInfo& /*test_info*/) {}
virtual void OnTestPartResult(const TestPartResult& /*test_part_result*/) {}
virtual void OnTestEnd(const TestInfo& /*test_info*/) {}
virtual void OnTestCaseEnd(const TestCase& /*test_case*/) {}
virtual void OnEnvironmentsTearDownStart(const UnitTest& /*unit_test*/) {}
virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}
virtual void OnTestIterationEnd(const UnitTest& /*unit_test*/,
int /*iteration*/) {}
virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}
};
// TestEventListeners lets users add listeners to track events in Google Test.
class GTEST_API_ TestEventListeners {
public:
TestEventListeners();
~TestEventListeners();
// Appends an event listener to the end of the list. Google Test assumes
// the ownership of the listener (i.e. it will delete the listener when
// the test program finishes).
void Append(TestEventListener* listener);
// Removes the given event listener from the list and returns it. It then
// becomes the caller's responsibility to delete the listener. Returns
// NULL if the listener is not found in the list.
TestEventListener* Release(TestEventListener* listener);
// Returns the standard listener responsible for the default console
// output. Can be removed from the listeners list to shut down default
// console output. Note that removing this object from the listener list
// with Release transfers its ownership to the caller and makes this
// function return NULL the next time.
TestEventListener* default_result_printer() const {
return default_result_printer_;
}
// Returns the standard listener responsible for the default XML output
// controlled by the --gtest_output=xml flag. Can be removed from the
// listeners list by users who want to shut down the default XML output
// controlled by this flag and substitute it with custom one. Note that
// removing this object from the listener list with Release transfers its
// ownership to the caller and makes this function return NULL the next
// time.
TestEventListener* default_xml_generator() const {
return default_xml_generator_;
}
private:
friend class TestCase;
friend class TestInfo;
friend class internal::DefaultGlobalTestPartResultReporter;
friend class internal::NoExecDeathTest;
friend class internal::TestEventListenersAccessor;
friend class internal::UnitTestImpl;
// Returns repeater that broadcasts the TestEventListener events to all
// subscribers.
TestEventListener* repeater();
// Sets the default_result_printer attribute to the provided listener.
// The listener is also added to the listener list and previous
// default_result_printer is removed from it and deleted. The listener can
// also be NULL in which case it will not be added to the list. Does
// nothing if the previous and the current listener objects are the same.
void SetDefaultResultPrinter(TestEventListener* listener);
// Sets the default_xml_generator attribute to the provided listener. The
// listener is also added to the listener list and previous
// default_xml_generator is removed from it and deleted. The listener can
// also be NULL in which case it will not be added to the list. Does
// nothing if the previous and the current listener objects are the same.
void SetDefaultXmlGenerator(TestEventListener* listener);
// Controls whether events will be forwarded by the repeater to the
// listeners in the list.
bool EventForwardingEnabled() const;
void SuppressEventForwarding();
// The actual list of listeners.
internal::TestEventRepeater* repeater_;
// Listener responsible for the standard result output.
TestEventListener* default_result_printer_;
// Listener responsible for the creation of the XML output file.
TestEventListener* default_xml_generator_;
// We disallow copying TestEventListeners.
GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventListeners);
};
// A UnitTest consists of a vector of TestCases.
//
// This is a singleton class. The only instance of UnitTest is
// created when UnitTest::GetInstance() is first called. This
// instance is never deleted.
//
// UnitTest is not copyable.
//
// This class is thread-safe as long as the methods are called
// according to their specification.
class GTEST_API_ UnitTest {
public:
// Gets the singleton UnitTest object. The first time this method
// is called, a UnitTest object is constructed and returned.
// Consecutive calls will return the same object.
static UnitTest* GetInstance();
// Runs all tests in this UnitTest object and prints the result.
// Returns 0 if successful, or 1 otherwise.
//
// This method can only be called from the main thread.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
int Run() GTEST_MUST_USE_RESULT_;
// Returns the working directory when the first TEST() or TEST_F()
// was executed. The UnitTest object owns the string.
const char* original_working_dir() const;
// Returns the TestCase object for the test that's currently running,
// or NULL if no test is running.
const TestCase* current_test_case() const;
// Returns the TestInfo object for the test that's currently running,
// or NULL if no test is running.
const TestInfo* current_test_info() const;
// Returns the random seed used at the start of the current test run.
int random_seed() const;
#if GTEST_HAS_PARAM_TEST
// Returns the ParameterizedTestCaseRegistry object used to keep track of
// value-parameterized tests and instantiate and register them.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
internal::ParameterizedTestCaseRegistry& parameterized_test_registry();
#endif // GTEST_HAS_PARAM_TEST
// Gets the number of successful test cases.
int successful_test_case_count() const;
// Gets the number of failed test cases.
int failed_test_case_count() const;
// Gets the number of all test cases.
int total_test_case_count() const;
// Gets the number of all test cases that contain at least one test
// that should run.
int test_case_to_run_count() const;
// Gets the number of successful tests.
int successful_test_count() const;
// Gets the number of failed tests.
int failed_test_count() const;
// Gets the number of disabled tests.
int disabled_test_count() const;
// Gets the number of all tests.
int total_test_count() const;
// Gets the number of tests that should run.
int test_to_run_count() const;
// Gets the elapsed time, in milliseconds.
TimeInMillis elapsed_time() const;
// Returns true iff the unit test passed (i.e. all test cases passed).
bool Passed() const;
// Returns true iff the unit test failed (i.e. some test case failed
// or something outside of all tests failed).
bool Failed() const;
// Gets the i-th test case among all the test cases. i can range from 0 to
// total_test_case_count() - 1. If i is not in that range, returns NULL.
const TestCase* GetTestCase(int i) const;
// Returns the list of event listeners that can be used to track events
// inside Google Test.
TestEventListeners& listeners();
private:
// Registers and returns a global test environment. When a test
// program is run, all global test environments will be set-up in
// the order they were registered. After all tests in the program
// have finished, all global test environments will be torn-down in
// the *reverse* order they were registered.
//
// The UnitTest object takes ownership of the given environment.
//
// This method can only be called from the main thread.
Environment* AddEnvironment(Environment* env);
// Adds a TestPartResult to the current TestResult object. All
// Google Test assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc)
// eventually call this to report their results. The user code
// should use the assertion macros instead of calling this directly.
void AddTestPartResult(TestPartResult::Type result_type,
const char* file_name,
int line_number,
const internal::String& message,
const internal::String& os_stack_trace);
// Adds a TestProperty to the current TestResult object. If the result already
// contains a property with the same key, the value will be updated.
void RecordPropertyForCurrentTest(const char* key, const char* value);
// Gets the i-th test case among all the test cases. i can range from 0 to
// total_test_case_count() - 1. If i is not in that range, returns NULL.
TestCase* GetMutableTestCase(int i);
// Accessors for the implementation object.
internal::UnitTestImpl* impl() { return impl_; }
const internal::UnitTestImpl* impl() const { return impl_; }
// These classes and funcions are friends as they need to access private
// members of UnitTest.
friend class Test;
friend class internal::AssertHelper;
friend class internal::ScopedTrace;
friend Environment* AddGlobalTestEnvironment(Environment* env);
friend internal::UnitTestImpl* internal::GetUnitTestImpl();
friend void internal::ReportFailureInUnknownLocation(
TestPartResult::Type result_type,
const internal::String& message);
// Creates an empty UnitTest.
UnitTest();
// D'tor
virtual ~UnitTest();
// Pushes a trace defined by SCOPED_TRACE() on to the per-thread
// Google Test trace stack.
void PushGTestTrace(const internal::TraceInfo& trace);
// Pops a trace from the per-thread Google Test trace stack.
void PopGTestTrace();
// Protects mutable state in *impl_. This is mutable as some const
// methods need to lock it too.
mutable internal::Mutex mutex_;
// Opaque implementation object. This field is never changed once
// the object is constructed. We don't mark it as const here, as
// doing so will cause a warning in the constructor of UnitTest.
// Mutable state in *impl_ is protected by mutex_.
internal::UnitTestImpl* impl_;
// We disallow copying UnitTest.
GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTest);
};
// A convenient wrapper for adding an environment for the test
// program.
//
// You should call this before RUN_ALL_TESTS() is called, probably in
// main(). If you use gtest_main, you need to call this before main()
// starts for it to take effect. For example, you can define a global
// variable like this:
//
// testing::Environment* const foo_env =
// testing::AddGlobalTestEnvironment(new FooEnvironment);
//
// However, we strongly recommend you to write your own main() and
// call AddGlobalTestEnvironment() there, as relying on initialization
// of global variables makes the code harder to read and may cause
// problems when you register multiple environments from different
// translation units and the environments have dependencies among them
// (remember that the compiler doesn't guarantee the order in which
// global variables from different translation units are initialized).
inline Environment* AddGlobalTestEnvironment(Environment* env) {
return UnitTest::GetInstance()->AddEnvironment(env);
}
// Initializes Google Test. This must be called before calling
// RUN_ALL_TESTS(). In particular, it parses a command line for the
// flags that Google Test recognizes. Whenever a Google Test flag is
// seen, it is removed from argv, and *argc is decremented.
//
// No value is returned. Instead, the Google Test flag variables are
// updated.
//
// Calling the function for the second time has no user-visible effect.
GTEST_API_ void InitGoogleTest(int* argc, char** argv);
// This overloaded version can be used in Windows programs compiled in
// UNICODE mode.
GTEST_API_ void InitGoogleTest(int* argc, wchar_t** argv);
namespace internal {
// Formats a comparison assertion (e.g. ASSERT_EQ, EXPECT_LT, and etc)
// operand to be used in a failure message. The type (but not value)
// of the other operand may affect the format. This allows us to
// print a char* as a raw pointer when it is compared against another
// char*, and print it as a C string when it is compared against an
// std::string object, for example.
//
// The default implementation ignores the type of the other operand.
// Some specialized versions are used to handle formatting wide or
// narrow C strings.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
template <typename T1, typename T2>
String FormatForComparisonFailureMessage(const T1& value,
const T2& /* other_operand */) {
// C++Builder compiles this incorrectly if the namespace isn't explicitly
// given.
return ::testing::PrintToString(value);
}
// The helper function for {ASSERT|EXPECT}_EQ.
template <typename T1, typename T2>
AssertionResult CmpHelperEQ(const char* expected_expression,
const char* actual_expression,
const T1& expected,
const T2& actual) {
#ifdef _MSC_VER
# pragma warning(push) // Saves the current warning state.
# pragma warning(disable:4389) // Temporarily disables warning on
// signed/unsigned mismatch.
#endif
if (expected == actual) {
return AssertionSuccess();
}
#ifdef _MSC_VER
# pragma warning(pop) // Restores the warning state.
#endif
return EqFailure(expected_expression,
actual_expression,
FormatForComparisonFailureMessage(expected, actual),
FormatForComparisonFailureMessage(actual, expected),
false);
}
// With this overloaded version, we allow anonymous enums to be used
// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous enums
// can be implicitly cast to BiggestInt.
GTEST_API_ AssertionResult CmpHelperEQ(const char* expected_expression,
const char* actual_expression,
BiggestInt expected,
BiggestInt actual);
// The helper class for {ASSERT|EXPECT}_EQ. The template argument
// lhs_is_null_literal is true iff the first argument to ASSERT_EQ()
// is a null pointer literal. The following default implementation is
// for lhs_is_null_literal being false.
template <bool lhs_is_null_literal>
class EqHelper {
public:
// This templatized version is for the general case.
template <typename T1, typename T2>
static AssertionResult Compare(const char* expected_expression,
const char* actual_expression,
const T1& expected,
const T2& actual) {
return CmpHelperEQ(expected_expression, actual_expression, expected,
actual);
}
// With this overloaded version, we allow anonymous enums to be used
// in {ASSERT|EXPECT}_EQ when compiled with gcc 4, as anonymous
// enums can be implicitly cast to BiggestInt.
//
// Even though its body looks the same as the above version, we
// cannot merge the two, as it will make anonymous enums unhappy.
static AssertionResult Compare(const char* expected_expression,
const char* actual_expression,
BiggestInt expected,
BiggestInt actual) {
return CmpHelperEQ(expected_expression, actual_expression, expected,
actual);
}
};
// This specialization is used when the first argument to ASSERT_EQ()
// is a null pointer literal, like NULL, false, or 0.
template <>
class EqHelper<true> {
public:
// We define two overloaded versions of Compare(). The first
// version will be picked when the second argument to ASSERT_EQ() is
// NOT a pointer, e.g. ASSERT_EQ(0, AnIntFunction()) or
// EXPECT_EQ(false, a_bool).
template <typename T1, typename T2>
static AssertionResult Compare(
const char* expected_expression,
const char* actual_expression,
const T1& expected,
const T2& actual,
// The following line prevents this overload from being considered if T2
// is not a pointer type. We need this because ASSERT_EQ(NULL, my_ptr)
// expands to Compare("", "", NULL, my_ptr), which requires a conversion
// to match the Secret* in the other overload, which would otherwise make
// this template match better.
typename EnableIf<!is_pointer<T2>::value>::type* = 0) {
return CmpHelperEQ(expected_expression, actual_expression, expected,
actual);
}
// This version will be picked when the second argument to ASSERT_EQ() is a
// pointer, e.g. ASSERT_EQ(NULL, a_pointer).
template <typename T>
static AssertionResult Compare(
const char* expected_expression,
const char* actual_expression,
// We used to have a second template parameter instead of Secret*. That
// template parameter would deduce to 'long', making this a better match
// than the first overload even without the first overload's EnableIf.
// Unfortunately, gcc with -Wconversion-null warns when "passing NULL to
// non-pointer argument" (even a deduced integral argument), so the old
// implementation caused warnings in user code.
Secret* /* expected (NULL) */,
T* actual) {
// We already know that 'expected' is a null pointer.
return CmpHelperEQ(expected_expression, actual_expression,
static_cast<T*>(NULL), actual);
}
};
// A macro for implementing the helper functions needed to implement
// ASSERT_?? and EXPECT_??. It is here just to avoid copy-and-paste
// of similar code.
//
// For each templatized helper function, we also define an overloaded
// version for BiggestInt in order to reduce code bloat and allow
// anonymous enums to be used with {ASSERT|EXPECT}_?? when compiled
// with gcc 4.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
#define GTEST_IMPL_CMP_HELPER_(op_name, op)\
template <typename T1, typename T2>\
AssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \
const T1& val1, const T2& val2) {\
if (val1 op val2) {\
return AssertionSuccess();\
} else {\
return AssertionFailure() \
<< "Expected: (" << expr1 << ") " #op " (" << expr2\
<< "), actual: " << FormatForComparisonFailureMessage(val1, val2)\
<< " vs " << FormatForComparisonFailureMessage(val2, val1);\
}\
}\
GTEST_API_ AssertionResult CmpHelper##op_name(\
const char* expr1, const char* expr2, BiggestInt val1, BiggestInt val2)
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
// Implements the helper function for {ASSERT|EXPECT}_NE
GTEST_IMPL_CMP_HELPER_(NE, !=);
// Implements the helper function for {ASSERT|EXPECT}_LE
GTEST_IMPL_CMP_HELPER_(LE, <=);
// Implements the helper function for {ASSERT|EXPECT}_LT
GTEST_IMPL_CMP_HELPER_(LT, < );
// Implements the helper function for {ASSERT|EXPECT}_GE
GTEST_IMPL_CMP_HELPER_(GE, >=);
// Implements the helper function for {ASSERT|EXPECT}_GT
GTEST_IMPL_CMP_HELPER_(GT, > );
#undef GTEST_IMPL_CMP_HELPER_
// The helper function for {ASSERT|EXPECT}_STREQ.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression,
const char* actual_expression,
const char* expected,
const char* actual);
// The helper function for {ASSERT|EXPECT}_STRCASEEQ.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRCASEEQ(const char* expected_expression,
const char* actual_expression,
const char* expected,
const char* actual);
// The helper function for {ASSERT|EXPECT}_STRNE.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression,
const char* s1,
const char* s2);
// The helper function for {ASSERT|EXPECT}_STRCASENE.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRCASENE(const char* s1_expression,
const char* s2_expression,
const char* s1,
const char* s2);
// Helper function for *_STREQ on wide strings.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTREQ(const char* expected_expression,
const char* actual_expression,
const wchar_t* expected,
const wchar_t* actual);
// Helper function for *_STRNE on wide strings.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult CmpHelperSTRNE(const char* s1_expression,
const char* s2_expression,
const wchar_t* s1,
const wchar_t* s2);
} // namespace internal
// IsSubstring() and IsNotSubstring() are intended to be used as the
// first argument to {EXPECT,ASSERT}_PRED_FORMAT2(), not by
// themselves. They check whether needle is a substring of haystack
// (NULL is considered a substring of itself only), and return an
// appropriate error message when they fail.
//
// The {needle,haystack}_expr arguments are the stringified
// expressions that generated the two real arguments.
GTEST_API_ AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const char* needle, const char* haystack);
GTEST_API_ AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const wchar_t* needle, const wchar_t* haystack);
GTEST_API_ AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const char* needle, const char* haystack);
GTEST_API_ AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const wchar_t* needle, const wchar_t* haystack);
GTEST_API_ AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::string& needle, const ::std::string& haystack);
GTEST_API_ AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::string& needle, const ::std::string& haystack);
#if GTEST_HAS_STD_WSTRING
GTEST_API_ AssertionResult IsSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::wstring& needle, const ::std::wstring& haystack);
GTEST_API_ AssertionResult IsNotSubstring(
const char* needle_expr, const char* haystack_expr,
const ::std::wstring& needle, const ::std::wstring& haystack);
#endif // GTEST_HAS_STD_WSTRING
namespace internal {
// Helper template function for comparing floating-points.
//
// Template parameter:
//
// RawType: the raw floating-point type (either float or double)
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
template <typename RawType>
AssertionResult CmpHelperFloatingPointEQ(const char* expected_expression,
const char* actual_expression,
RawType expected,
RawType actual) {
const FloatingPoint<RawType> lhs(expected), rhs(actual);
if (lhs.AlmostEquals(rhs)) {
return AssertionSuccess();
}
::std::stringstream expected_ss;
expected_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< expected;
::std::stringstream actual_ss;
actual_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)
<< actual;
return EqFailure(expected_expression,
actual_expression,
StringStreamToString(&expected_ss),
StringStreamToString(&actual_ss),
false);
}
// Helper function for implementing ASSERT_NEAR.
//
// INTERNAL IMPLEMENTATION - DO NOT USE IN A USER PROGRAM.
GTEST_API_ AssertionResult DoubleNearPredFormat(const char* expr1,
const char* expr2,
const char* abs_error_expr,
double val1,
double val2,
double abs_error);
// INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE.
// A class that enables one to stream messages to assertion macros
class GTEST_API_ AssertHelper {
public:
// Constructor.
AssertHelper(TestPartResult::Type type,
const char* file,
int line,
const char* message);
~AssertHelper();
// Message assignment is a semantic trick to enable assertion
// streaming; see the GTEST_MESSAGE_ macro below.
void operator=(const Message& message) const;
private:
// We put our data in a struct so that the size of the AssertHelper class can
// be as small as possible. This is important because gcc is incapable of
// re-using stack space even for temporary variables, so every EXPECT_EQ
// reserves stack space for another AssertHelper.
struct AssertHelperData {
AssertHelperData(TestPartResult::Type t,
const char* srcfile,
int line_num,
const char* msg)
: type(t), file(srcfile), line(line_num), message(msg) { }
TestPartResult::Type const type;
const char* const file;
int const line;
String const message;
private:
GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelperData);
};
AssertHelperData* const data_;
GTEST_DISALLOW_COPY_AND_ASSIGN_(AssertHelper);
};
} // namespace internal
#if GTEST_HAS_PARAM_TEST
// The pure interface class that all value-parameterized tests inherit from.
// A value-parameterized class must inherit from both ::testing::Test and
// ::testing::WithParamInterface. In most cases that just means inheriting
// from ::testing::TestWithParam, but more complicated test hierarchies
// may need to inherit from Test and WithParamInterface at different levels.
//
// This interface has support for accessing the test parameter value via
// the GetParam() method.
//
// Use it with one of the parameter generator defining functions, like Range(),
// Values(), ValuesIn(), Bool(), and Combine().
//
// class FooTest : public ::testing::TestWithParam<int> {
// protected:
// FooTest() {
// // Can use GetParam() here.
// }
// virtual ~FooTest() {
// // Can use GetParam() here.
// }
// virtual void SetUp() {
// // Can use GetParam() here.
// }
// virtual void TearDown {
// // Can use GetParam() here.
// }
// };
// TEST_P(FooTest, DoesBar) {
// // Can use GetParam() method here.
// Foo foo;
// ASSERT_TRUE(foo.DoesBar(GetParam()));
// }
// INSTANTIATE_TEST_CASE_P(OneToTenRange, FooTest, ::testing::Range(1, 10));
template <typename T>
class WithParamInterface {
public:
typedef T ParamType;
virtual ~WithParamInterface() {}
// The current parameter value. Is also available in the test fixture's
// constructor. This member function is non-static, even though it only
// references static data, to reduce the opportunity for incorrect uses
// like writing 'WithParamInterface<bool>::GetParam()' for a test that
// uses a fixture whose parameter type is int.
const ParamType& GetParam() const { return *parameter_; }
private:
// Sets parameter value. The caller is responsible for making sure the value
// remains alive and unchanged throughout the current test.
static void SetParam(const ParamType* parameter) {
parameter_ = parameter;
}
// Static value used for accessing parameter during a test lifetime.
static const ParamType* parameter_;
// TestClass must be a subclass of WithParamInterface<T> and Test.
template <class TestClass> friend class internal::ParameterizedTestFactory;
};
template <typename T>
const T* WithParamInterface<T>::parameter_ = NULL;
// Most value-parameterized classes can ignore the existence of
// WithParamInterface, and can just inherit from ::testing::TestWithParam.
template <typename T>
class TestWithParam : public Test, public WithParamInterface<T> {
};
#endif // GTEST_HAS_PARAM_TEST
// Macros for indicating success/failure in test code.
// ADD_FAILURE unconditionally adds a failure to the current test.
// SUCCEED generates a success - it doesn't automatically make the
// current test successful, as a test is only successful when it has
// no failure.
//
// EXPECT_* verifies that a certain condition is satisfied. If not,
// it behaves like ADD_FAILURE. In particular:
//
// EXPECT_TRUE verifies that a Boolean condition is true.
// EXPECT_FALSE verifies that a Boolean condition is false.
//
// FAIL and ASSERT_* are similar to ADD_FAILURE and EXPECT_*, except
// that they will also abort the current function on failure. People
// usually want the fail-fast behavior of FAIL and ASSERT_*, but those
// writing data-driven tests often find themselves using ADD_FAILURE
// and EXPECT_* more.
//
// Examples:
//
// EXPECT_TRUE(server.StatusIsOK());
// ASSERT_FALSE(server.HasPendingRequest(port))
// << "There are still pending requests " << "on port " << port;
// Generates a nonfatal failure with a generic message.
#define ADD_FAILURE() GTEST_NONFATAL_FAILURE_("Failed")
// Generates a nonfatal failure at the given source file location with
// a generic message.
#define ADD_FAILURE_AT(file, line) \
GTEST_MESSAGE_AT_(file, line, "Failed", \
::testing::TestPartResult::kNonFatalFailure)
// Generates a fatal failure with a generic message.
#define GTEST_FAIL() GTEST_FATAL_FAILURE_("Failed")
// Define this macro to 1 to omit the definition of FAIL(), which is a
// generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_FAIL
# define FAIL() GTEST_FAIL()
#endif
// Generates a success with a generic message.
#define GTEST_SUCCEED() GTEST_SUCCESS_("Succeeded")
// Define this macro to 1 to omit the definition of SUCCEED(), which
// is a generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_SUCCEED
# define SUCCEED() GTEST_SUCCEED()
#endif
// Macros for testing exceptions.
//
// * {ASSERT|EXPECT}_THROW(statement, expected_exception):
// Tests that the statement throws the expected exception.
// * {ASSERT|EXPECT}_NO_THROW(statement):
// Tests that the statement doesn't throw any exception.
// * {ASSERT|EXPECT}_ANY_THROW(statement):
// Tests that the statement throws an exception.
#define EXPECT_THROW(statement, expected_exception) \
GTEST_TEST_THROW_(statement, expected_exception, GTEST_NONFATAL_FAILURE_)
#define EXPECT_NO_THROW(statement) \
GTEST_TEST_NO_THROW_(statement, GTEST_NONFATAL_FAILURE_)
#define EXPECT_ANY_THROW(statement) \
GTEST_TEST_ANY_THROW_(statement, GTEST_NONFATAL_FAILURE_)
#define ASSERT_THROW(statement, expected_exception) \
GTEST_TEST_THROW_(statement, expected_exception, GTEST_FATAL_FAILURE_)
#define ASSERT_NO_THROW(statement) \
GTEST_TEST_NO_THROW_(statement, GTEST_FATAL_FAILURE_)
#define ASSERT_ANY_THROW(statement) \
GTEST_TEST_ANY_THROW_(statement, GTEST_FATAL_FAILURE_)
// Boolean assertions. Condition can be either a Boolean expression or an
// AssertionResult. For more information on how to use AssertionResult with
// these macros see comments on that class.
#define EXPECT_TRUE(condition) \
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_NONFATAL_FAILURE_)
#define EXPECT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_NONFATAL_FAILURE_)
#define ASSERT_TRUE(condition) \
GTEST_TEST_BOOLEAN_(condition, #condition, false, true, \
GTEST_FATAL_FAILURE_)
#define ASSERT_FALSE(condition) \
GTEST_TEST_BOOLEAN_(!(condition), #condition, true, false, \
GTEST_FATAL_FAILURE_)
// Includes the auto-generated header that implements a family of
// generic predicate assertion macros.
#include "gtest/gtest_pred_impl.h"
// Macros for testing equalities and inequalities.
//
// * {ASSERT|EXPECT}_EQ(expected, actual): Tests that expected == actual
// * {ASSERT|EXPECT}_NE(v1, v2): Tests that v1 != v2
// * {ASSERT|EXPECT}_LT(v1, v2): Tests that v1 < v2
// * {ASSERT|EXPECT}_LE(v1, v2): Tests that v1 <= v2
// * {ASSERT|EXPECT}_GT(v1, v2): Tests that v1 > v2
// * {ASSERT|EXPECT}_GE(v1, v2): Tests that v1 >= v2
//
// When they are not, Google Test prints both the tested expressions and
// their actual values. The values must be compatible built-in types,
// or you will get a compiler error. By "compatible" we mean that the
// values can be compared by the respective operator.
//
// Note:
//
// 1. It is possible to make a user-defined type work with
// {ASSERT|EXPECT}_??(), but that requires overloading the
// comparison operators and is thus discouraged by the Google C++
// Usage Guide. Therefore, you are advised to use the
// {ASSERT|EXPECT}_TRUE() macro to assert that two objects are
// equal.
//
// 2. The {ASSERT|EXPECT}_??() macros do pointer comparisons on
// pointers (in particular, C strings). Therefore, if you use it
// with two C strings, you are testing how their locations in memory
// are related, not how their content is related. To compare two C
// strings by content, use {ASSERT|EXPECT}_STR*().
//
// 3. {ASSERT|EXPECT}_EQ(expected, actual) is preferred to
// {ASSERT|EXPECT}_TRUE(expected == actual), as the former tells you
// what the actual value is when it fails, and similarly for the
// other comparisons.
//
// 4. Do not depend on the order in which {ASSERT|EXPECT}_??()
// evaluate their arguments, which is undefined.
//
// 5. These macros evaluate their arguments exactly once.
//
// Examples:
//
// EXPECT_NE(5, Foo());
// EXPECT_EQ(NULL, a_pointer);
// ASSERT_LT(i, array_size);
// ASSERT_GT(records.size(), 0) << "There is no record left.";
#define EXPECT_EQ(expected, actual) \
EXPECT_PRED_FORMAT2(::testing::internal:: \
EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \
expected, actual)
#define EXPECT_NE(expected, actual) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperNE, expected, actual)
#define EXPECT_LE(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
#define EXPECT_LT(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
#define EXPECT_GE(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
#define EXPECT_GT(val1, val2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
#define GTEST_ASSERT_EQ(expected, actual) \
ASSERT_PRED_FORMAT2(::testing::internal:: \
EqHelper<GTEST_IS_NULL_LITERAL_(expected)>::Compare, \
expected, actual)
#define GTEST_ASSERT_NE(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperNE, val1, val2)
#define GTEST_ASSERT_LE(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLE, val1, val2)
#define GTEST_ASSERT_LT(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperLT, val1, val2)
#define GTEST_ASSERT_GE(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGE, val1, val2)
#define GTEST_ASSERT_GT(val1, val2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperGT, val1, val2)
// Define macro GTEST_DONT_DEFINE_ASSERT_XY to 1 to omit the definition of
// ASSERT_XY(), which clashes with some users' own code.
#if !GTEST_DONT_DEFINE_ASSERT_EQ
# define ASSERT_EQ(val1, val2) GTEST_ASSERT_EQ(val1, val2)
#endif
#if !GTEST_DONT_DEFINE_ASSERT_NE
# define ASSERT_NE(val1, val2) GTEST_ASSERT_NE(val1, val2)
#endif
#if !GTEST_DONT_DEFINE_ASSERT_LE
# define ASSERT_LE(val1, val2) GTEST_ASSERT_LE(val1, val2)
#endif
#if !GTEST_DONT_DEFINE_ASSERT_LT
# define ASSERT_LT(val1, val2) GTEST_ASSERT_LT(val1, val2)
#endif
#if !GTEST_DONT_DEFINE_ASSERT_GE
# define ASSERT_GE(val1, val2) GTEST_ASSERT_GE(val1, val2)
#endif
#if !GTEST_DONT_DEFINE_ASSERT_GT
# define ASSERT_GT(val1, val2) GTEST_ASSERT_GT(val1, val2)
#endif
// C String Comparisons. All tests treat NULL and any non-NULL string
// as different. Two NULLs are equal.
//
// * {ASSERT|EXPECT}_STREQ(s1, s2): Tests that s1 == s2
// * {ASSERT|EXPECT}_STRNE(s1, s2): Tests that s1 != s2
// * {ASSERT|EXPECT}_STRCASEEQ(s1, s2): Tests that s1 == s2, ignoring case
// * {ASSERT|EXPECT}_STRCASENE(s1, s2): Tests that s1 != s2, ignoring case
//
// For wide or narrow string objects, you can use the
// {ASSERT|EXPECT}_??() macros.
//
// Don't depend on the order in which the arguments are evaluated,
// which is undefined.
//
// These macros evaluate their arguments exactly once.
#define EXPECT_STREQ(expected, actual) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual)
#define EXPECT_STRNE(s1, s2) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
#define EXPECT_STRCASEEQ(expected, actual) \
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual)
#define EXPECT_STRCASENE(s1, s2)\
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
#define ASSERT_STREQ(expected, actual) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTREQ, expected, actual)
#define ASSERT_STRNE(s1, s2) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRNE, s1, s2)
#define ASSERT_STRCASEEQ(expected, actual) \
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASEEQ, expected, actual)
#define ASSERT_STRCASENE(s1, s2)\
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperSTRCASENE, s1, s2)
// Macros for comparing floating-point numbers.
//
// * {ASSERT|EXPECT}_FLOAT_EQ(expected, actual):
// Tests that two float values are almost equal.
// * {ASSERT|EXPECT}_DOUBLE_EQ(expected, actual):
// Tests that two double values are almost equal.
// * {ASSERT|EXPECT}_NEAR(v1, v2, abs_error):
// Tests that v1 and v2 are within the given distance to each other.
//
// Google Test uses ULP-based comparison to automatically pick a default
// error bound that is appropriate for the operands. See the
// FloatingPoint template class in gtest-internal.h if you are
// interested in the implementation details.
#define EXPECT_FLOAT_EQ(expected, actual)\
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
expected, actual)
#define EXPECT_DOUBLE_EQ(expected, actual)\
EXPECT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
expected, actual)
#define ASSERT_FLOAT_EQ(expected, actual)\
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<float>, \
expected, actual)
#define ASSERT_DOUBLE_EQ(expected, actual)\
ASSERT_PRED_FORMAT2(::testing::internal::CmpHelperFloatingPointEQ<double>, \
expected, actual)
#define EXPECT_NEAR(val1, val2, abs_error)\
EXPECT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
val1, val2, abs_error)
#define ASSERT_NEAR(val1, val2, abs_error)\
ASSERT_PRED_FORMAT3(::testing::internal::DoubleNearPredFormat, \
val1, val2, abs_error)
// These predicate format functions work on floating-point values, and
// can be used in {ASSERT|EXPECT}_PRED_FORMAT2*(), e.g.
//
// EXPECT_PRED_FORMAT2(testing::DoubleLE, Foo(), 5.0);
// Asserts that val1 is less than, or almost equal to, val2. Fails
// otherwise. In particular, it fails if either val1 or val2 is NaN.
GTEST_API_ AssertionResult FloatLE(const char* expr1, const char* expr2,
float val1, float val2);
GTEST_API_ AssertionResult DoubleLE(const char* expr1, const char* expr2,
double val1, double val2);
#if GTEST_OS_WINDOWS
// Macros that test for HRESULT failure and success, these are only useful
// on Windows, and rely on Windows SDK macros and APIs to compile.
//
// * {ASSERT|EXPECT}_HRESULT_{SUCCEEDED|FAILED}(expr)
//
// When expr unexpectedly fails or succeeds, Google Test prints the
// expected result and the actual result with both a human-readable
// string representation of the error, if available, as well as the
// hex result code.
# define EXPECT_HRESULT_SUCCEEDED(expr) \
EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
# define ASSERT_HRESULT_SUCCEEDED(expr) \
ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTSuccess, (expr))
# define EXPECT_HRESULT_FAILED(expr) \
EXPECT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
# define ASSERT_HRESULT_FAILED(expr) \
ASSERT_PRED_FORMAT1(::testing::internal::IsHRESULTFailure, (expr))
#endif // GTEST_OS_WINDOWS
// Macros that execute statement and check that it doesn't generate new fatal
// failures in the current thread.
//
// * {ASSERT|EXPECT}_NO_FATAL_FAILURE(statement);
//
// Examples:
//
// EXPECT_NO_FATAL_FAILURE(Process());
// ASSERT_NO_FATAL_FAILURE(Process()) << "Process() failed";
//
#define ASSERT_NO_FATAL_FAILURE(statement) \
GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_FATAL_FAILURE_)
#define EXPECT_NO_FATAL_FAILURE(statement) \
GTEST_TEST_NO_FATAL_FAILURE_(statement, GTEST_NONFATAL_FAILURE_)
// Causes a trace (including the source file path, the current line
// number, and the given message) to be included in every test failure
// message generated by code in the current scope. The effect is
// undone when the control leaves the current scope.
//
// The message argument can be anything streamable to std::ostream.
//
// In the implementation, we include the current line number as part
// of the dummy variable name, thus allowing multiple SCOPED_TRACE()s
// to appear in the same block - as long as they are on different
// lines.
#define SCOPED_TRACE(message) \
::testing::internal::ScopedTrace GTEST_CONCAT_TOKEN_(gtest_trace_, __LINE__)(\
__FILE__, __LINE__, ::testing::Message() << (message))
// Compile-time assertion for type equality.
// StaticAssertTypeEq<type1, type2>() compiles iff type1 and type2 are
// the same type. The value it returns is not interesting.
//
// Instead of making StaticAssertTypeEq a class template, we make it a
// function template that invokes a helper class template. This
// prevents a user from misusing StaticAssertTypeEq<T1, T2> by
// defining objects of that type.
//
// CAVEAT:
//
// When used inside a method of a class template,
// StaticAssertTypeEq<T1, T2>() is effective ONLY IF the method is
// instantiated. For example, given:
//
// template <typename T> class Foo {
// public:
// void Bar() { testing::StaticAssertTypeEq<int, T>(); }
// };
//
// the code:
//
// void Test1() { Foo<bool> foo; }
//
// will NOT generate a compiler error, as Foo<bool>::Bar() is never
// actually instantiated. Instead, you need:
//
// void Test2() { Foo<bool> foo; foo.Bar(); }
//
// to cause a compiler error.
template <typename T1, typename T2>
bool StaticAssertTypeEq() {
(void)internal::StaticAssertTypeEqHelper<T1, T2>();
return true;
}
// Defines a test.
//
// The first parameter is the name of the test case, and the second
// parameter is the name of the test within the test case.
//
// The convention is to end the test case name with "Test". For
// example, a test case for the Foo class can be named FooTest.
//
// The user should put his test code between braces after using this
// macro. Example:
//
// TEST(FooTest, InitializesCorrectly) {
// Foo foo;
// EXPECT_TRUE(foo.StatusIsOK());
// }
// Note that we call GetTestTypeId() instead of GetTypeId<
// ::testing::Test>() here to get the type ID of testing::Test. This
// is to work around a suspected linker bug when using Google Test as
// a framework on Mac OS X. The bug causes GetTypeId<
// ::testing::Test>() to return different values depending on whether
// the call is from the Google Test framework itself or from user test
// code. GetTestTypeId() is guaranteed to always return the same
// value, as it always calls GetTypeId<>() from the Google Test
// framework.
#define GTEST_TEST(test_case_name, test_name)\
GTEST_TEST_(test_case_name, test_name, \
::testing::Test, ::testing::internal::GetTestTypeId())
// Define this macro to 1 to omit the definition of TEST(), which
// is a generic name and clashes with some other libraries.
#if !GTEST_DONT_DEFINE_TEST
# define TEST(test_case_name, test_name) GTEST_TEST(test_case_name, test_name)
#endif
// Defines a test that uses a test fixture.
//
// The first parameter is the name of the test fixture class, which
// also doubles as the test case name. The second parameter is the
// name of the test within the test case.
//
// A test fixture class must be declared earlier. The user should put
// his test code between braces after using this macro. Example:
//
// class FooTest : public testing::Test {
// protected:
// virtual void SetUp() { b_.AddElement(3); }
//
// Foo a_;
// Foo b_;
// };
//
// TEST_F(FooTest, InitializesCorrectly) {
// EXPECT_TRUE(a_.StatusIsOK());
// }
//
// TEST_F(FooTest, ReturnsElementCountCorrectly) {
// EXPECT_EQ(0, a_.size());
// EXPECT_EQ(1, b_.size());
// }
#define TEST_F(test_fixture, test_name)\
GTEST_TEST_(test_fixture, test_name, test_fixture, \
::testing::internal::GetTypeId<test_fixture>())
// Use this macro in main() to run all tests. It returns 0 if all
// tests are successful, or 1 otherwise.
//
// RUN_ALL_TESTS() should be invoked after the command line has been
// parsed by InitGoogleTest().
#define RUN_ALL_TESTS()\
(::testing::UnitTest::GetInstance()->Run())
} // namespace testing
#endif // GTEST_INCLUDE_GTEST_GTEST_H_
|
{
"pile_set_name": "Github"
}
|
# Try to find the GNU Multiple Precision Arithmetic Library (GMP)
# See http://gmplib.org/
if (GMP_INCLUDES AND GMP_LIBRARIES)
set(GMP_FIND_QUIETLY TRUE)
endif (GMP_INCLUDES AND GMP_LIBRARIES)
find_path(GMP_INCLUDES
NAMES
gmp.h
PATHS
$ENV{GMPDIR}
${INCLUDE_INSTALL_DIR}
)
find_library(GMP_LIBRARIES gmp PATHS $ENV{GMPDIR} ${LIB_INSTALL_DIR})
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(GMP DEFAULT_MSG
GMP_INCLUDES GMP_LIBRARIES)
mark_as_advanced(GMP_INCLUDES GMP_LIBRARIES)
|
{
"pile_set_name": "Github"
}
|
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html#License
es_SV{
%%Parent{"es_419"}
Version{"2.1.47.70"}
calendar{
gregorian{
AmPmMarkers{
"a. m.",
"p. m.",
}
AmPmMarkersAbbr{
"a. m.",
"p. m.",
}
dayPeriod{
stand-alone{
abbreviated{
am{"a. m."}
pm{"p. m."}
}
narrow{
am{"a. m."}
pm{"p. m."}
}
wide{
am{"a. m."}
pm{"p. m."}
}
}
}
}
}
fields{
day{
relative{
"-1"{"ayer"}
"-2"{"antier"}
"0"{"hoy"}
"1"{"mañana"}
"2"{"pasado mañana"}
}
}
dayperiod{
dn{"a. m./p. m."}
}
}
}
|
{
"pile_set_name": "Github"
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:ce436a9f4d3fca4e0363a0e8917b9a686fbbe708005bf2a2bf7ebfb3b77fad18
size 1606
|
{
"pile_set_name": "Github"
}
|
/*
This file is part of LilyPond, the GNU music typesetter.
Copyright (C) 2008--2020 Han-Wen Nienhuys <hanwen@lilypond.org>
LilyPond 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.
LilyPond 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 LilyPond. If not, see <http://www.gnu.org/licenses/>.
*/
#include "skyline-pair.hh"
#include "international.hh"
using std::vector;
Skyline_pair::Skyline_pair ()
: skylines_ (Skyline (DOWN), Skyline (UP))
{
}
Skyline_pair::Skyline_pair (vector<Box> const &boxes, Axis a)
: skylines_ (Skyline (boxes, a, DOWN), Skyline (boxes, a, UP))
{
// TODO: The boxes sort equally for up & down,
// so we can save ourselves one sort step.
}
Skyline_pair::Skyline_pair (vector<Drul_array<Offset> > const &buildings, Axis a)
: skylines_ (Skyline (buildings, a, DOWN), Skyline (buildings, a, UP))
{
}
Skyline_pair::Skyline_pair (vector<Skyline_pair> const &skypairs)
: skylines_ (Skyline (skypairs, DOWN), Skyline (skypairs, UP))
{
}
Skyline_pair::Skyline_pair (Box const &b, Axis a)
: skylines_ (Skyline (b, a, DOWN), Skyline (b, a, UP))
{
}
void
Skyline_pair::raise (Real r)
{
skylines_[UP].raise (r);
skylines_[DOWN].raise (r);
}
void
Skyline_pair::pad (Real r)
{
if (!r)
return;
for (UP_and_DOWN (d))
skylines_[d] = skylines_[d].padded (r);
}
void
Skyline_pair::shift (Real r)
{
skylines_[UP].shift (r);
skylines_[DOWN].shift (r);
}
void
Skyline_pair::merge (Skyline_pair const &other)
{
skylines_[UP].merge (other[UP]);
skylines_[DOWN].merge (other[DOWN]);
}
void
Skyline_pair::print () const
{
skylines_[UP].print ();
skylines_[DOWN].print ();
}
Real
Skyline_pair::left () const
{
return std::min (skylines_[UP].left (), skylines_[DOWN].left ());
}
Real
Skyline_pair::right () const
{
return std::max (skylines_[UP].right (), skylines_[DOWN].right ());
}
void
Skyline_pair::print_points () const
{
skylines_[UP].print_points ();
skylines_[DOWN].print_points ();
}
bool
Skyline_pair::is_empty () const
{
return skylines_[UP].is_empty ()
&& skylines_[DOWN].is_empty ();
}
Skyline &
Skyline_pair::operator [] (Direction d)
{
return skylines_[d];
}
Skyline const &
Skyline_pair::operator [] (Direction d) const
{
return skylines_[d];
}
const char *const Skyline_pair::type_p_name_ = "ly:skyline-pair?";
MAKE_SCHEME_CALLBACK (Skyline_pair, skyline, 2);
SCM
Skyline_pair::skyline (SCM smob, SCM dir_scm)
{
Skyline_pair *sp = unsmob<Skyline_pair> (smob);
Direction dir = from_scm (dir_scm, UP);
if (dir == CENTER)
{
warning (_f ("direction must not be CENTER in ly:skyline-pair::skyline"));
dir = UP;
}
return (*sp)[dir].smobbed_copy ();
}
|
{
"pile_set_name": "Github"
}
|
H
1534232150
tags: Tree, DFS, Union Find, Graph
#### Union Find
- 讨论3种情况
- http://www.cnblogs.com/grandyang/p/8445733.html
```
/*
In this problem, a rooted tree is a directed graph such that,
there is exactly one node (the root) for which all other nodes are descendants of this node,
plus every node has exactly one parent, except for the root node which has no parents.
The given input is a directed graph that started as a rooted tree with N nodes (with distinct values 1, 2, ..., N),
with one additional directed edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed.
The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] that
represents a directed edge connecting nodes u and v, where u is a parent of child v.
Return an edge that can be removed so that the resulting graph is a rooted tree of N nodes.
If there are multiple answers, return the answer that occurs last in the given 2D-array.
Example 1:
Input: [[1,2], [1,3], [2,3]]
Output: [2,3]
Explanation: The given directed graph will be like this:
1
/ \
v v
2-->3
Example 2:
Input: [[1,2], [2,3], [3,4], [4,1], [1,5]]
Output: [4,1]
Explanation: The given directed graph will be like this:
5 <- 1 -> 2
^ |
| v
4 <- 3
Note:
The size of the input 2D-array will be between 3 and 1000.
Every integer represented in the 2D-array will be between 1 and N, where N is the size of the input array.
*/
/*
- find inDegree == 2
- union and return cycle item
- if cycle not exist, return the inDegree==2 edge
*/
class Solution {
int[] parent;
public int[] findRedundantDirectedConnection(int[][] edges) {
int n = edges.length;
parent = new int[n + 1];
// find the edges where inDegree == 2
int[] first = null, second = null;
for (int[] edge : edges) {
int x = edge[0], y = edge[1];
if (parent[y] == 0) {
parent[y] = x;
} else {
first = new int[]{parent[y], y};
second = new int[]{edge[0], edge[1]};
edge[1] = 0; // why?
}
}
// re-init unionFind
for (int i = 0; i <= n; i++) parent[i] = i;
// Union
for (int[] edge : edges) {
int x = edge[0], y = edge[1];
if (y == 0) continue;
int parentX = find(x), parentY = find(y);
if (parentX == parentY) return first == null ? edge : first;
parent[parentX] = parentY;
}
return second;
}
public int find(int x) {
int parentX = parent[x];
if (parentX == x) return parentX;
return parent[x] = find(parentX);
}
}
```
|
{
"pile_set_name": "Github"
}
|
dojo.provide("dojox.rails.tests.module");
try{
doh.registerUrl("dojox.rails", dojo.moduleUrl("dojox.rails", "tests/test_rails.html"));
}catch(e){
doh.debug(e);
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "self:SwipeCellKit.xcodeproj">
</FileRef>
</Workspace>
|
{
"pile_set_name": "Github"
}
|
<!doctype html>
<title>CodeMirror: Pascal mode</title>
<meta charset="utf-8"/>
<link rel=stylesheet href="../../doc/docs.css">
<link rel="stylesheet" href="../../lib/codemirror.css">
<script src="../../lib/codemirror.js"></script>
<script src="pascal.js"></script>
<style type="text/css">.CodeMirror {border-top: 1px solid black; border-bottom: 1px solid black;}</style>
<div id=nav>
<a href="http://codemirror.net"><img id=logo src="../../doc/logo.png"></a>
<ul>
<li><a href="../../index.html">Home</a>
<li><a href="../../doc/manual.html">Manual</a>
<li><a href="https://github.com/marijnh/codemirror">Code</a>
</ul>
<ul>
<li><a href="../index.html">Language modes</a>
<li><a class=active href="#">Pascal</a>
</ul>
</div>
<article>
<h2>Pascal mode</h2>
<div><textarea id="code" name="code">
(* Example Pascal code *)
while a <> b do writeln('Waiting');
if a > b then
writeln('Condition met')
else
writeln('Condition not met');
for i := 1 to 10 do
writeln('Iteration: ', i:1);
repeat
a := a + 1
until a = 10;
case i of
0: write('zero');
1: write('one');
2: write('two')
end;
</textarea></div>
<script>
var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
mode: "text/x-pascal"
});
</script>
<p><strong>MIME types defined:</strong> <code>text/x-pascal</code>.</p>
</article>
|
{
"pile_set_name": "Github"
}
|
<?xml version='1.0' encoding='UTF-8'?>
<osm version="0.6" upload="false" generator="testdata">
<node id="10" version="1" timestamp="2015-01-01T01:00:00Z" uid="1" user="test" changeset="1" lat="1" lon="1"/>
<node id="11" version="1" timestamp="2015-01-01T01:00:00Z" uid="1" user="test" changeset="1" lat="2" lon="1"/>
<node id="12" version="1" timestamp="2015-01-01T01:00:00Z" uid="1" user="test" changeset="1" lat="3" lon="1"/>
<node id="12" version="2" timestamp="2015-01-01T01:00:01Z" uid="1" user="test" changeset="1" lat="3" lon="2"/>
<node id="13" version="1" timestamp="2015-01-01T01:00:00Z" uid="1" user="test" changeset="1" lat="4" lon="1"/>
<way id="20" version="1" timestamp="2015-01-01T01:00:00Z" uid="1" user="test" changeset="1">
<nd ref="10"/>
<nd ref="11"/>
<nd ref="12"/>
<tag k="foo" v="bar"/>
</way>
<way id="21" version="1" timestamp="2015-01-01T01:00:00Z" uid="1" user="test" changeset="1">
<nd ref="12"/>
<nd ref="13"/>
<tag k="xyz" v="abc"/>
</way>
<relation id="30" version="1" timestamp="2015-01-01T01:00:00Z" uid="1" user="test" changeset="1">
<member type="node" ref="12" role="m1"/>
<member type="way" ref="20" role="m2"/>
</relation>
</osm>
|
{
"pile_set_name": "Github"
}
|
{
"type": "bundle",
"id": "bundle--8b68ac97-3e22-4a58-9abc-8edf20b9446c",
"spec_version": "2.0",
"objects": [
{
"created_by_ref": "identity--c78cb6e5-0c4b-4611-8297-d1b8b55e40b5",
"object_marking_refs": [
"marking-definition--fa42a846-8d90-4e51-bc29-71d5b4802168"
],
"source_ref": "attack-pattern--f6dacc85-b37d-458e-b58d-74fc4bbf5755",
"target_ref": "attack-pattern--731f4f55-b6d0-41d1-a7a9-072a66389aea",
"relationship_type": "subtechnique-of",
"id": "relationship--284aadab-ec10-4869-8bdb-7258c19432c4",
"type": "relationship",
"modified": "2020-03-14T23:08:20.407Z",
"created": "2020-03-14T23:08:20.407Z"
}
]
}
|
{
"pile_set_name": "Github"
}
|
export const readAsArrayBuffer = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = (e) =>
reject(new Error(`File ${file.name} is unreadable: ${e.target.result}`));
reader.readAsArrayBuffer(file);
});
export const readAsText = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = (e) =>
reject(new Error(`File ${file.name} is unreadable: ${e.target.result}`));
reader.readAsText(file);
});
|
{
"pile_set_name": "Github"
}
|
// ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2020
// MIT License
#include <ArduinoJson.h>
#include <catch.hpp>
TEST_CASE("Gbathree") {
DynamicJsonDocument doc(4096);
DeserializationError error = deserializeJson(
doc,
"{\"protocol_name\":\"fluorescence\",\"repeats\":1,\"wait\":0,"
"\"averages\":1,\"measurements\":3,\"meas2_light\":15,\"meas1_"
"baseline\":0,\"act_light\":20,\"pulsesize\":25,\"pulsedistance\":"
"10000,\"actintensity1\":50,\"actintensity2\":255,\"measintensity\":"
"255,\"calintensity\":255,\"pulses\":[50,50,50],\"act\":[2,1,2,2],"
"\"red\":[2,2,2,2],\"detectors\":[[34,34,34,34],[34,34,34,34],[34,"
"34,34,34],[34,34,34,34]],\"alta\":[2,2,2,2],\"altb\":[2,2,2,2],"
"\"measlights\":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,"
"15,15]],\"measlights2\":[[15,15,15,15],[15,15,15,15],[15,15,15,15],"
"[15,15,15,15]],\"altc\":[2,2,2,2],\"altd\":[2,2,2,2]}");
JsonObject root = doc.as<JsonObject>();
SECTION("Success") {
REQUIRE(error == DeserializationError::Ok);
}
SECTION("ProtocolName") {
REQUIRE("fluorescence" == root["protocol_name"]);
}
SECTION("Repeats") {
REQUIRE(1 == root["repeats"]);
}
SECTION("Wait") {
REQUIRE(0 == root["wait"]);
}
SECTION("Measurements") {
REQUIRE(3 == root["measurements"]);
}
SECTION("Meas2_Light") {
REQUIRE(15 == root["meas2_light"]);
}
SECTION("Meas1_Baseline") {
REQUIRE(0 == root["meas1_baseline"]);
}
SECTION("Act_Light") {
REQUIRE(20 == root["act_light"]);
}
SECTION("Pulsesize") {
REQUIRE(25 == root["pulsesize"]);
}
SECTION("Pulsedistance") {
REQUIRE(10000 == root["pulsedistance"]);
}
SECTION("Actintensity1") {
REQUIRE(50 == root["actintensity1"]);
}
SECTION("Actintensity2") {
REQUIRE(255 == root["actintensity2"]);
}
SECTION("Measintensity") {
REQUIRE(255 == root["measintensity"]);
}
SECTION("Calintensity") {
REQUIRE(255 == root["calintensity"]);
}
SECTION("Pulses") {
// "pulses":[50,50,50]
JsonArray array = root["pulses"];
REQUIRE(array.isNull() == false);
REQUIRE(3 == array.size());
for (size_t i = 0; i < 3; i++) {
REQUIRE(50 == array[i]);
}
}
SECTION("Act") {
// "act":[2,1,2,2]
JsonArray array = root["act"];
REQUIRE(array.isNull() == false);
REQUIRE(4 == array.size());
REQUIRE(2 == array[0]);
REQUIRE(1 == array[1]);
REQUIRE(2 == array[2]);
REQUIRE(2 == array[3]);
}
SECTION("Detectors") {
// "detectors":[[34,34,34,34],[34,34,34,34],[34,34,34,34],[34,34,34,34]]
JsonArray array = root["detectors"];
REQUIRE(array.isNull() == false);
REQUIRE(4 == array.size());
for (size_t i = 0; i < 4; i++) {
JsonArray nestedArray = array[i];
REQUIRE(4 == nestedArray.size());
for (size_t j = 0; j < 4; j++) {
REQUIRE(34 == nestedArray[j]);
}
}
}
SECTION("Alta") {
// alta:[2,2,2,2]
JsonArray array = root["alta"];
REQUIRE(array.isNull() == false);
REQUIRE(4 == array.size());
for (size_t i = 0; i < 4; i++) {
REQUIRE(2 == array[i]);
}
}
SECTION("Altb") {
// altb:[2,2,2,2]
JsonArray array = root["altb"];
REQUIRE(array.isNull() == false);
REQUIRE(4 == array.size());
for (size_t i = 0; i < 4; i++) {
REQUIRE(2 == array[i]);
}
}
SECTION("Measlights") {
// "measlights":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]]
JsonArray array = root["measlights"];
REQUIRE(array.isNull() == false);
REQUIRE(4 == array.size());
for (size_t i = 0; i < 4; i++) {
JsonArray nestedArray = array[i];
REQUIRE(4 == nestedArray.size());
for (size_t j = 0; j < 4; j++) {
REQUIRE(15 == nestedArray[j]);
}
}
}
SECTION("Measlights2") {
// "measlights2":[[15,15,15,15],[15,15,15,15],[15,15,15,15],[15,15,15,15]]
JsonArray array = root["measlights2"];
REQUIRE(array.isNull() == false);
REQUIRE(4 == array.size());
for (size_t i = 0; i < 4; i++) {
JsonArray nestedArray = array[i];
REQUIRE(4 == nestedArray.size());
for (size_t j = 0; j < 4; j++) {
REQUIRE(15 == nestedArray[j]);
}
}
}
SECTION("Altc") {
// altc:[2,2,2,2]
JsonArray array = root["altc"];
REQUIRE(array.isNull() == false);
REQUIRE(4 == array.size());
for (size_t i = 0; i < 4; i++) {
REQUIRE(2 == array[i]);
}
}
SECTION("Altd") {
// altd:[2,2,2,2]
JsonArray array = root["altd"];
REQUIRE(array.isNull() == false);
REQUIRE(4 == array.size());
for (size_t i = 0; i < 4; i++) {
REQUIRE(2 == array[i]);
}
}
}
|
{
"pile_set_name": "Github"
}
|
{
"translatorID": "1f40baef-eece-43e4-a1cc-27d20c0ce086",
"label": "Engineering Village",
"creator": "Ben Parr, Sebastian Karcher",
"target": "^https?://(www\\.)?engineeringvillage(2)?\\.(com|org)",
"minVersion": "3.0",
"maxVersion": "",
"priority": 100,
"inRepository": true,
"translatorType": 4,
"browserSupport": "gcsibv",
"lastUpdated": "2018-10-07 10:02:04"
}
/*
***** BEGIN LICENSE BLOCK *****
Engineering Village Translator - Copyright © 2018 Sebastian Karcher
This file is part of Zotero.
Zotero 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.
Zotero 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 Zotero. If not, see <http://www.gnu.org/licenses/>.
***** END LICENSE BLOCK *****
*/
function detectWeb(doc, url) {
Z.monitorDOMChanges(doc.getElementById("ev-application"), {childList: true});
var printlink = doc.getElementById('printlink');
if (url.includes("/search/doc/") && printlink && getDocIDs(printlink.href)) {
return "journalArticle";
}
if ((url.includes("quick.url?") || url.includes("expert.url?") || url.includes("thesaurus.url?")) && getSearchResults(doc, true)) {
return "multiple";
}
}
function getDocIDs(url) {
var m = url.match(/\bdocidlist=([^&#]+)/);
if (!m) return false;
return decodeURIComponent(m[1]).split(',');
}
function getSearchResults(doc, checkOnly) {
var rows = doc.querySelectorAll('div[class*=result-row]'),
items = {},
found = false;
for (var i=0; i<rows.length; i++) {
var checkbox = rows[i].querySelector('input[name="cbresult"]');
if (!checkbox) continue;
var docid = checkbox.getAttribute('docid');
if (!docid) continue;
var title = rows[i].querySelector('h3.result-title');
if (!title) continue;
if (checkOnly) return true;
found = true;
items[docid] = ZU.trimInternal(title.textContent);
}
return found ? items : false;
}
function doWeb(doc, url) {
if (detectWeb(doc, url) == 'multiple') {
Zotero.selectItems(getSearchResults(doc), function (items) {
if (!items) return true;
var ids = [];
for (var i in items) {
ids.push(i);
}
fetchRIS(doc, ids);
});
} else {
var printlink = doc.getElementById('printlink');
fetchRIS(doc, getDocIDs(printlink.href));
}
}
function fetchRIS(doc, docIDs) {
Z.debug(docIDs);
// handlelist to accompany the docidlist. Seems like it just has to be a
// list of numbers the same size as the docid list.
var handleList = new Array(docIDs.length);
for (var i=0; i<docIDs.length; i++) {
handleList[i] = i+1;
}
var db = doc.getElementsByName('database')[0];
if (db) db = db.value;
if (!db) db = "1";
var url = '/delivery/download/submit.url?downloadformat=ris'
+ '&filenameprefix=Engineering_Village&displayformat=abstract'
+ '&database=' + encodeURIComponent(db)
+ '&docidlist=' + encodeURIComponent(docIDs.join(','))
+ '&handlelist=' + encodeURIComponent(handleList.join(','));
// This is what their web page does. It also sends Content-type and
// Content-length parameters in the body, but seems like we can skip that
// part
ZU.doPost(url, "", function(text) {
// Z.debug(text);
var translator = Zotero.loadTranslator("import");
// RIS
translator.setTranslator("32d59d2d-b65a-4da4-b0a3-bdd3cfb979e7");
translator.setString(text);
translator.setHandler('itemDone', function(obj, item) {
item.attachments = [];
item.notes = [];
item.complete();
});
translator.translate();
});
}
/** BEGIN TEST CASES **/
var testCases = []
/** END TEST CASES **/
|
{
"pile_set_name": "Github"
}
|
# Lint as: python2, python3
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""SSDFeatureExtractor for InceptionV2 features."""
import tensorflow.compat.v1 as tf
import tf_slim as slim
from object_detection.meta_architectures import ssd_meta_arch
from object_detection.models import feature_map_generators
from object_detection.utils import ops
from object_detection.utils import shape_utils
from nets import inception_v2
class SSDInceptionV2FeatureExtractor(ssd_meta_arch.SSDFeatureExtractor):
"""SSD Feature Extractor using InceptionV2 features."""
def __init__(self,
is_training,
depth_multiplier,
min_depth,
pad_to_multiple,
conv_hyperparams_fn,
reuse_weights=None,
use_explicit_padding=False,
use_depthwise=False,
num_layers=6,
override_base_feature_extractor_hyperparams=False):
"""InceptionV2 Feature Extractor for SSD Models.
Args:
is_training: whether the network is in training mode.
depth_multiplier: float depth multiplier for feature extractor.
min_depth: minimum feature extractor depth.
pad_to_multiple: the nearest multiple to zero pad the input height and
width dimensions to.
conv_hyperparams_fn: A function to construct tf slim arg_scope for conv2d
and separable_conv2d ops in the layers that are added on top of the
base feature extractor.
reuse_weights: Whether to reuse variables. Default is None.
use_explicit_padding: Whether to use explicit padding when extracting
features. Default is False.
use_depthwise: Whether to use depthwise convolutions. Default is False.
num_layers: Number of SSD layers.
override_base_feature_extractor_hyperparams: Whether to override
hyperparameters of the base feature extractor with the one from
`conv_hyperparams_fn`.
Raises:
ValueError: If `override_base_feature_extractor_hyperparams` is False.
"""
super(SSDInceptionV2FeatureExtractor, self).__init__(
is_training=is_training,
depth_multiplier=depth_multiplier,
min_depth=min_depth,
pad_to_multiple=pad_to_multiple,
conv_hyperparams_fn=conv_hyperparams_fn,
reuse_weights=reuse_weights,
use_explicit_padding=use_explicit_padding,
use_depthwise=use_depthwise,
num_layers=num_layers,
override_base_feature_extractor_hyperparams=
override_base_feature_extractor_hyperparams)
if not self._override_base_feature_extractor_hyperparams:
raise ValueError('SSD Inception V2 feature extractor always uses'
'scope returned by `conv_hyperparams_fn` for both the '
'base feature extractor and the additional layers '
'added since there is no arg_scope defined for the base '
'feature extractor.')
def preprocess(self, resized_inputs):
"""SSD preprocessing.
Maps pixel values to the range [-1, 1].
Args:
resized_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.
Returns:
preprocessed_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.
"""
return (2.0 / 255.0) * resized_inputs - 1.0
def extract_features(self, preprocessed_inputs):
"""Extract features from preprocessed inputs.
Args:
preprocessed_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.
Returns:
feature_maps: a list of tensors where the ith tensor has shape
[batch, height_i, width_i, depth_i]
"""
preprocessed_inputs = shape_utils.check_min_image_dim(
33, preprocessed_inputs)
feature_map_layout = {
'from_layer': ['Mixed_4c', 'Mixed_5c', '', '', '', ''
][:self._num_layers],
'layer_depth': [-1, -1, 512, 256, 256, 128][:self._num_layers],
'use_explicit_padding': self._use_explicit_padding,
'use_depthwise': self._use_depthwise,
}
with slim.arg_scope(self._conv_hyperparams_fn()):
with tf.variable_scope('InceptionV2',
reuse=self._reuse_weights) as scope:
_, image_features = inception_v2.inception_v2_base(
ops.pad_to_multiple(preprocessed_inputs, self._pad_to_multiple),
final_endpoint='Mixed_5c',
min_depth=self._min_depth,
depth_multiplier=self._depth_multiplier,
scope=scope)
feature_maps = feature_map_generators.multi_resolution_feature_maps(
feature_map_layout=feature_map_layout,
depth_multiplier=self._depth_multiplier,
min_depth=self._min_depth,
insert_1x1_conv=True,
image_features=image_features)
return list(feature_maps.values())
|
{
"pile_set_name": "Github"
}
|
/*
* mxl111sf-demod.c - driver for the MaxLinear MXL111SF DVB-T demodulator
*
* Copyright (C) 2010 Michael Krufky <mkrufky@kernellabs.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "mxl111sf-demod.h"
#include "mxl111sf-reg.h"
/* debug */
static int mxl111sf_demod_debug;
module_param_named(debug, mxl111sf_demod_debug, int, 0644);
MODULE_PARM_DESC(debug, "set debugging level (1=info (or-able)).");
#define mxl_dbg(fmt, arg...) \
if (mxl111sf_demod_debug) \
mxl_printk(KERN_DEBUG, fmt, ##arg)
/* ------------------------------------------------------------------------ */
struct mxl111sf_demod_state {
struct mxl111sf_state *mxl_state;
struct mxl111sf_demod_config *cfg;
struct dvb_frontend fe;
};
/* ------------------------------------------------------------------------ */
static int mxl111sf_demod_read_reg(struct mxl111sf_demod_state *state,
u8 addr, u8 *data)
{
return (state->cfg->read_reg) ?
state->cfg->read_reg(state->mxl_state, addr, data) :
-EINVAL;
}
static int mxl111sf_demod_write_reg(struct mxl111sf_demod_state *state,
u8 addr, u8 data)
{
return (state->cfg->write_reg) ?
state->cfg->write_reg(state->mxl_state, addr, data) :
-EINVAL;
}
static
int mxl111sf_demod_program_regs(struct mxl111sf_demod_state *state,
struct mxl111sf_reg_ctrl_info *ctrl_reg_info)
{
return (state->cfg->program_regs) ?
state->cfg->program_regs(state->mxl_state, ctrl_reg_info) :
-EINVAL;
}
/* ------------------------------------------------------------------------ */
/* TPS */
static
int mxl1x1sf_demod_get_tps_code_rate(struct mxl111sf_demod_state *state,
fe_code_rate_t *code_rate)
{
u8 val;
int ret = mxl111sf_demod_read_reg(state, V6_CODE_RATE_TPS_REG, &val);
/* bit<2:0> - 000:1/2, 001:2/3, 010:3/4, 011:5/6, 100:7/8 */
if (mxl_fail(ret))
goto fail;
switch (val & V6_CODE_RATE_TPS_MASK) {
case 0:
*code_rate = FEC_1_2;
break;
case 1:
*code_rate = FEC_2_3;
break;
case 2:
*code_rate = FEC_3_4;
break;
case 3:
*code_rate = FEC_5_6;
break;
case 4:
*code_rate = FEC_7_8;
break;
}
fail:
return ret;
}
static
int mxl1x1sf_demod_get_tps_modulation(struct mxl111sf_demod_state *state,
fe_modulation_t *modulation)
{
u8 val;
int ret = mxl111sf_demod_read_reg(state, V6_MODORDER_TPS_REG, &val);
/* Constellation, 00 : QPSK, 01 : 16QAM, 10:64QAM */
if (mxl_fail(ret))
goto fail;
switch ((val & V6_PARAM_CONSTELLATION_MASK) >> 4) {
case 0:
*modulation = QPSK;
break;
case 1:
*modulation = QAM_16;
break;
case 2:
*modulation = QAM_64;
break;
}
fail:
return ret;
}
static
int mxl1x1sf_demod_get_tps_guard_fft_mode(struct mxl111sf_demod_state *state,
fe_transmit_mode_t *fft_mode)
{
u8 val;
int ret = mxl111sf_demod_read_reg(state, V6_MODE_TPS_REG, &val);
/* FFT Mode, 00:2K, 01:8K, 10:4K */
if (mxl_fail(ret))
goto fail;
switch ((val & V6_PARAM_FFT_MODE_MASK) >> 2) {
case 0:
*fft_mode = TRANSMISSION_MODE_2K;
break;
case 1:
*fft_mode = TRANSMISSION_MODE_8K;
break;
case 2:
*fft_mode = TRANSMISSION_MODE_4K;
break;
}
fail:
return ret;
}
static
int mxl1x1sf_demod_get_tps_guard_interval(struct mxl111sf_demod_state *state,
fe_guard_interval_t *guard)
{
u8 val;
int ret = mxl111sf_demod_read_reg(state, V6_CP_TPS_REG, &val);
/* 00:1/32, 01:1/16, 10:1/8, 11:1/4 */
if (mxl_fail(ret))
goto fail;
switch ((val & V6_PARAM_GI_MASK) >> 4) {
case 0:
*guard = GUARD_INTERVAL_1_32;
break;
case 1:
*guard = GUARD_INTERVAL_1_16;
break;
case 2:
*guard = GUARD_INTERVAL_1_8;
break;
case 3:
*guard = GUARD_INTERVAL_1_4;
break;
}
fail:
return ret;
}
static
int mxl1x1sf_demod_get_tps_hierarchy(struct mxl111sf_demod_state *state,
fe_hierarchy_t *hierarchy)
{
u8 val;
int ret = mxl111sf_demod_read_reg(state, V6_TPS_HIERACHY_REG, &val);
/* bit<6:4> - 000:Non hierarchy, 001:1, 010:2, 011:4 */
if (mxl_fail(ret))
goto fail;
switch ((val & V6_TPS_HIERARCHY_INFO_MASK) >> 6) {
case 0:
*hierarchy = HIERARCHY_NONE;
break;
case 1:
*hierarchy = HIERARCHY_1;
break;
case 2:
*hierarchy = HIERARCHY_2;
break;
case 3:
*hierarchy = HIERARCHY_4;
break;
}
fail:
return ret;
}
/* ------------------------------------------------------------------------ */
/* LOCKS */
static
int mxl1x1sf_demod_get_sync_lock_status(struct mxl111sf_demod_state *state,
int *sync_lock)
{
u8 val = 0;
int ret = mxl111sf_demod_read_reg(state, V6_SYNC_LOCK_REG, &val);
if (mxl_fail(ret))
goto fail;
*sync_lock = (val & SYNC_LOCK_MASK) >> 4;
fail:
return ret;
}
static
int mxl1x1sf_demod_get_rs_lock_status(struct mxl111sf_demod_state *state,
int *rs_lock)
{
u8 val = 0;
int ret = mxl111sf_demod_read_reg(state, V6_RS_LOCK_DET_REG, &val);
if (mxl_fail(ret))
goto fail;
*rs_lock = (val & RS_LOCK_DET_MASK) >> 3;
fail:
return ret;
}
static
int mxl1x1sf_demod_get_tps_lock_status(struct mxl111sf_demod_state *state,
int *tps_lock)
{
u8 val = 0;
int ret = mxl111sf_demod_read_reg(state, V6_TPS_LOCK_REG, &val);
if (mxl_fail(ret))
goto fail;
*tps_lock = (val & V6_PARAM_TPS_LOCK_MASK) >> 6;
fail:
return ret;
}
static
int mxl1x1sf_demod_get_fec_lock_status(struct mxl111sf_demod_state *state,
int *fec_lock)
{
u8 val = 0;
int ret = mxl111sf_demod_read_reg(state, V6_IRQ_STATUS_REG, &val);
if (mxl_fail(ret))
goto fail;
*fec_lock = (val & IRQ_MASK_FEC_LOCK) >> 4;
fail:
return ret;
}
#if 0
static
int mxl1x1sf_demod_get_cp_lock_status(struct mxl111sf_demod_state *state,
int *cp_lock)
{
u8 val = 0;
int ret = mxl111sf_demod_read_reg(state, V6_CP_LOCK_DET_REG, &val);
if (mxl_fail(ret))
goto fail;
*cp_lock = (val & V6_CP_LOCK_DET_MASK) >> 2;
fail:
return ret;
}
#endif
static int mxl1x1sf_demod_reset_irq_status(struct mxl111sf_demod_state *state)
{
return mxl111sf_demod_write_reg(state, 0x0e, 0xff);
}
/* ------------------------------------------------------------------------ */
static int mxl111sf_demod_set_frontend(struct dvb_frontend *fe)
{
struct mxl111sf_demod_state *state = fe->demodulator_priv;
int ret = 0;
struct mxl111sf_reg_ctrl_info phy_pll_patch[] = {
{0x00, 0xff, 0x01}, /* change page to 1 */
{0x40, 0xff, 0x05},
{0x40, 0xff, 0x01},
{0x41, 0xff, 0xca},
{0x41, 0xff, 0xc0},
{0x00, 0xff, 0x00}, /* change page to 0 */
{0, 0, 0}
};
mxl_dbg("()");
if (fe->ops.tuner_ops.set_params) {
ret = fe->ops.tuner_ops.set_params(fe);
if (mxl_fail(ret))
goto fail;
msleep(50);
}
ret = mxl111sf_demod_program_regs(state, phy_pll_patch);
mxl_fail(ret);
msleep(50);
ret = mxl1x1sf_demod_reset_irq_status(state);
mxl_fail(ret);
msleep(100);
fail:
return ret;
}
/* ------------------------------------------------------------------------ */
#if 0
/* resets TS Packet error count */
/* After setting 7th bit of V5_PER_COUNT_RESET_REG, it should be reset to 0. */
static
int mxl1x1sf_demod_reset_packet_error_count(struct mxl111sf_demod_state *state)
{
struct mxl111sf_reg_ctrl_info reset_per_count[] = {
{0x20, 0x01, 0x01},
{0x20, 0x01, 0x00},
{0, 0, 0}
};
return mxl111sf_demod_program_regs(state, reset_per_count);
}
#endif
/* returns TS Packet error count */
/* PER Count = FEC_PER_COUNT * (2 ** (FEC_PER_SCALE * 4)) */
static int mxl111sf_demod_read_ucblocks(struct dvb_frontend *fe, u32 *ucblocks)
{
struct mxl111sf_demod_state *state = fe->demodulator_priv;
u32 fec_per_count, fec_per_scale;
u8 val;
int ret;
*ucblocks = 0;
/* FEC_PER_COUNT Register */
ret = mxl111sf_demod_read_reg(state, V6_FEC_PER_COUNT_REG, &val);
if (mxl_fail(ret))
goto fail;
fec_per_count = val;
/* FEC_PER_SCALE Register */
ret = mxl111sf_demod_read_reg(state, V6_FEC_PER_SCALE_REG, &val);
if (mxl_fail(ret))
goto fail;
val &= V6_FEC_PER_SCALE_MASK;
val *= 4;
fec_per_scale = 1 << val;
fec_per_count *= fec_per_scale;
*ucblocks = fec_per_count;
fail:
return ret;
}
#ifdef MXL111SF_DEMOD_ENABLE_CALCULATIONS
/* FIXME: leaving this enabled breaks the build on some architectures,
* and we shouldn't have any floating point math in the kernel, anyway.
*
* These macros need to be re-written, but it's harmless to simply
* return zero for now. */
#define CALCULATE_BER(avg_errors, count) \
((u32)(avg_errors * 4)/(count*64*188*8))
#define CALCULATE_SNR(data) \
((u32)((10 * (u32)data / 64) - 2.5))
#else
#define CALCULATE_BER(avg_errors, count) 0
#define CALCULATE_SNR(data) 0
#endif
static int mxl111sf_demod_read_ber(struct dvb_frontend *fe, u32 *ber)
{
struct mxl111sf_demod_state *state = fe->demodulator_priv;
u8 val1, val2, val3;
int ret;
*ber = 0;
ret = mxl111sf_demod_read_reg(state, V6_RS_AVG_ERRORS_LSB_REG, &val1);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_demod_read_reg(state, V6_RS_AVG_ERRORS_MSB_REG, &val2);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_demod_read_reg(state, V6_N_ACCUMULATE_REG, &val3);
if (mxl_fail(ret))
goto fail;
*ber = CALCULATE_BER((val1 | (val2 << 8)), val3);
fail:
return ret;
}
static int mxl111sf_demod_calc_snr(struct mxl111sf_demod_state *state,
u16 *snr)
{
u8 val1, val2;
int ret;
*snr = 0;
ret = mxl111sf_demod_read_reg(state, V6_SNR_RB_LSB_REG, &val1);
if (mxl_fail(ret))
goto fail;
ret = mxl111sf_demod_read_reg(state, V6_SNR_RB_MSB_REG, &val2);
if (mxl_fail(ret))
goto fail;
*snr = CALCULATE_SNR(val1 | ((val2 & 0x03) << 8));
fail:
return ret;
}
static int mxl111sf_demod_read_snr(struct dvb_frontend *fe, u16 *snr)
{
struct mxl111sf_demod_state *state = fe->demodulator_priv;
int ret = mxl111sf_demod_calc_snr(state, snr);
if (mxl_fail(ret))
goto fail;
*snr /= 10; /* 0.1 dB */
fail:
return ret;
}
static int mxl111sf_demod_read_status(struct dvb_frontend *fe,
fe_status_t *status)
{
struct mxl111sf_demod_state *state = fe->demodulator_priv;
int ret, locked, cr_lock, sync_lock, fec_lock;
*status = 0;
ret = mxl1x1sf_demod_get_rs_lock_status(state, &locked);
if (mxl_fail(ret))
goto fail;
ret = mxl1x1sf_demod_get_tps_lock_status(state, &cr_lock);
if (mxl_fail(ret))
goto fail;
ret = mxl1x1sf_demod_get_sync_lock_status(state, &sync_lock);
if (mxl_fail(ret))
goto fail;
ret = mxl1x1sf_demod_get_fec_lock_status(state, &fec_lock);
if (mxl_fail(ret))
goto fail;
if (locked)
*status |= FE_HAS_SIGNAL;
if (cr_lock)
*status |= FE_HAS_CARRIER;
if (sync_lock)
*status |= FE_HAS_SYNC;
if (fec_lock) /* false positives? */
*status |= FE_HAS_VITERBI;
if ((locked) && (cr_lock) && (sync_lock))
*status |= FE_HAS_LOCK;
fail:
return ret;
}
static int mxl111sf_demod_read_signal_strength(struct dvb_frontend *fe,
u16 *signal_strength)
{
struct mxl111sf_demod_state *state = fe->demodulator_priv;
fe_modulation_t modulation;
u16 snr;
mxl111sf_demod_calc_snr(state, &snr);
mxl1x1sf_demod_get_tps_modulation(state, &modulation);
switch (modulation) {
case QPSK:
*signal_strength = (snr >= 1300) ?
min(65535, snr * 44) : snr * 38;
break;
case QAM_16:
*signal_strength = (snr >= 1500) ?
min(65535, snr * 38) : snr * 33;
break;
case QAM_64:
*signal_strength = (snr >= 2000) ?
min(65535, snr * 29) : snr * 25;
break;
default:
*signal_strength = 0;
return -EINVAL;
}
return 0;
}
static int mxl111sf_demod_get_frontend(struct dvb_frontend *fe)
{
struct dtv_frontend_properties *p = &fe->dtv_property_cache;
struct mxl111sf_demod_state *state = fe->demodulator_priv;
mxl_dbg("()");
#if 0
p->inversion = /* FIXME */ ? INVERSION_ON : INVERSION_OFF;
#endif
if (fe->ops.tuner_ops.get_bandwidth)
fe->ops.tuner_ops.get_bandwidth(fe, &p->bandwidth_hz);
if (fe->ops.tuner_ops.get_frequency)
fe->ops.tuner_ops.get_frequency(fe, &p->frequency);
mxl1x1sf_demod_get_tps_code_rate(state, &p->code_rate_HP);
mxl1x1sf_demod_get_tps_code_rate(state, &p->code_rate_LP);
mxl1x1sf_demod_get_tps_modulation(state, &p->modulation);
mxl1x1sf_demod_get_tps_guard_fft_mode(state,
&p->transmission_mode);
mxl1x1sf_demod_get_tps_guard_interval(state,
&p->guard_interval);
mxl1x1sf_demod_get_tps_hierarchy(state,
&p->hierarchy);
return 0;
}
static
int mxl111sf_demod_get_tune_settings(struct dvb_frontend *fe,
struct dvb_frontend_tune_settings *tune)
{
tune->min_delay_ms = 1000;
return 0;
}
static void mxl111sf_demod_release(struct dvb_frontend *fe)
{
struct mxl111sf_demod_state *state = fe->demodulator_priv;
mxl_dbg("()");
kfree(state);
fe->demodulator_priv = NULL;
}
static struct dvb_frontend_ops mxl111sf_demod_ops = {
.delsys = { SYS_DVBT },
.info = {
.name = "MaxLinear MxL111SF DVB-T demodulator",
.frequency_min = 177000000,
.frequency_max = 858000000,
.frequency_stepsize = 166666,
.caps = FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 | FE_CAN_FEC_3_4 |
FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 | FE_CAN_FEC_AUTO |
FE_CAN_QPSK | FE_CAN_QAM_16 | FE_CAN_QAM_64 |
FE_CAN_QAM_AUTO |
FE_CAN_HIERARCHY_AUTO | FE_CAN_GUARD_INTERVAL_AUTO |
FE_CAN_TRANSMISSION_MODE_AUTO | FE_CAN_RECOVER
},
.release = mxl111sf_demod_release,
#if 0
.init = mxl111sf_init,
.i2c_gate_ctrl = mxl111sf_i2c_gate_ctrl,
#endif
.set_frontend = mxl111sf_demod_set_frontend,
.get_frontend = mxl111sf_demod_get_frontend,
.get_tune_settings = mxl111sf_demod_get_tune_settings,
.read_status = mxl111sf_demod_read_status,
.read_signal_strength = mxl111sf_demod_read_signal_strength,
.read_ber = mxl111sf_demod_read_ber,
.read_snr = mxl111sf_demod_read_snr,
.read_ucblocks = mxl111sf_demod_read_ucblocks,
};
struct dvb_frontend *mxl111sf_demod_attach(struct mxl111sf_state *mxl_state,
struct mxl111sf_demod_config *cfg)
{
struct mxl111sf_demod_state *state = NULL;
mxl_dbg("()");
state = kzalloc(sizeof(struct mxl111sf_demod_state), GFP_KERNEL);
if (state == NULL)
return NULL;
state->mxl_state = mxl_state;
state->cfg = cfg;
memcpy(&state->fe.ops, &mxl111sf_demod_ops,
sizeof(struct dvb_frontend_ops));
state->fe.demodulator_priv = state;
return &state->fe;
}
EXPORT_SYMBOL_GPL(mxl111sf_demod_attach);
MODULE_DESCRIPTION("MaxLinear MxL111SF DVB-T demodulator driver");
MODULE_AUTHOR("Michael Krufky <mkrufky@kernellabs.com>");
MODULE_LICENSE("GPL");
MODULE_VERSION("0.1");
/*
* Local variables:
* c-basic-offset: 8
* End:
*/
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Header Files">
<UniqueIdentifier>{5017154f-1d9b-4ac0-a68d-da258e7023d1}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{c21851de-9a4f-41bb-a761-4a324c124407}</UniqueIdentifier>
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="src\dir.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
|
{
"pile_set_name": "Github"
}
|
{\rtf1\ansi\ansicpg936\cocoartf1404\cocoasubrtf460
{\fonttbl\f0\fswiss\fcharset0 Helvetica;\f1\fnil\fcharset134 PingFangSC-Regular;}
{\colortbl;\red255\green255\blue255;}
\paperw11900\paperh16840\margl1440\margr1440\vieww10800\viewh7040\viewkind0
\pard\tx566\tx1133\tx1700\tx2267\tx2834\tx3401\tx3968\tx4535\tx5102\tx5669\tx6236\tx6803\pardirnatural\partightenfactor0
\f0\fs24 \cf0 UIView+LXExtension
\f1 \'a3\'ba\
1.\'bf\'ec\'cb\'d9\'c9\'e8\'d6\'c3\'bf\'d8\'bc\'feframe\
2.\'bf\'ec\'cb\'d9\'b8\'f9\'be\'ddxib\'c9\'fa\'b3\'c9View\
3.\'c5\'d0\'b6\'cf\'c1\'bd\'b8\'f6view\'ca\'c7\'b7\'f1\'d6\'d8\'b5\'fe\
\
UITextField+LXExtension\'a3\'ba\
1.\'c9\'e8\'d6\'c3textField\'b5\'c4\'d5\'bc\'ce\'bb\'ce\'c4\'d7\'d6\'d1\'d5\'c9\'ab\
\
UIBarButtonItem+LXExtension\'a3\'ba\
1.\'bf\'ec\'cb\'d9\'d7\'d4\'b6\'a8\'d2\'e5\'b5\'bc\'ba\'bd\'c0\'b8\'c9\'cf\'b5\'c4\'b0\'b4\'c5\'a5\
\
UIImage+LXExtension\'a3\'ba\
1.\'bf\'ec\'cb\'d9\'c9\'fa\'b3\'c9\'d4\'b2\'d0\'ce\'cd\'bc\'c6\'ac\
2.\'b8\'f8\'b6\'a8\'d2\'bb\'b8\'f6\'b2\'bb\'d2\'aa\'e4\'d6\'c8\'be\'b5\'c4\'cd\'bc\'c6\'ac\'c3\'fb\'b3\'c6\'a3\'ac\'c9\'fa\'b3\'c9\'d2\'bb\'b8\'f6\'d7\'ee\'d4\'ad\'ca\'bc\'b5\'c4\'cd\'bc\'c6\'ac\
3.\'c4\'a3\'ba\'fd\'d0\'a7\'b9\'fb\
4.\'b9\'cc\'b6\'a8\'bf\'ed\'b8\'df\
5.\'bc\'f4\'c7\'d0\'cd\'bc\'c6\'ac\'c4\'b3\'d2\'bb\'b2\'bf\'b7\'d6\
6.\'bd\'ab\'d7\'d4\'c9\'ed\'cc\'ee\'b3\'e4\'b5\'bd\'d6\'b8\'b6\'a8\'b5\'c4size\
\
NSString+LXExtension\'a3\'ba\
1.\'b8\'f9\'be\'dd\'ce\'c4\'bc\'fe\'c3\'fb\'bc\'c6\'cb\'e3\'ce\'c4\'bc\'fe\'b4\'f3\'d0\'a1\
2.\'bf\'ec\'cb\'d9\'c9\'fa\'b3\'c9\'bb\'ba\'b4\'e6/\'ce\'c4\'b5\'b5/\'c1\'d9\'ca\'b1\'c4\'bf\'c2\'bc\'c2\'b7\'be\'b6\
3.\'b8\'f9\'be\'dd\'ce\'c4\'d7\'d6\'b7\'b5\'bb\'d8\'ce\'c4\'b1\'be\'d5\'bc\'d3\'c3\'b5\'c4\'b8\'df\'b6\'c8/\'bf\'ed\'b6\'c8\
\
NSDate+LXExtension\
1.\'c1\'bd\'b8\'f6\'ca\'b1\'bc\'e4\'d6\'ae\'bc\'e4\'b5\'c4\'ca\'b1\'bc\'e4\'bc\'e4\'b8\'f4\
2.\'ca\'c7\'b7\'f1\'ce\'aa\'bd\'f1\'cc\'ec\'a3\'ac\'d7\'f2\'cc\'ec\'a3\'ac\'c3\'f7\'cc\'ec\
3.\'b5\'b1\'c7\'b0\'ca\'c7\'d6\'dc\'bc\'b8\
\
NSDictionary+PropertyCode\
1.\'b8\'f9\'be\'dd\'d7\'d6\'b5\'e4\'bf\'ec\'cb\'d9\'c9\'fa\'b3\'c9Property\'ca\'f4\'d0\'d4\
\'ca\'b9\'d3\'c3\'b3\'a1\'be\'b0\'a3\'ba\'b8\'f9\'be\'dd\'cd\'f8\'c2\'e7\'c7\'eb\'c7\'f3\'b7\'b5\'bb\'d8\'b5\'c4\'d7\'d6\'b5\'e4\'ca\'fd\'be\'dd\'a3\'ac\'d0\'b4\'b6\'d4\'d3\'a6\'b5\'c4\'c4\'a3\'d0\'cd\'a1\'a3\'b5\'b1\'ca\'f4\'d0\'d4\'b6\'e0\'ca\'b1\'a3\'ac\'d3\'c3\'ca\'d6\'d0\'b4\'ba\'dc\'b7\'d1\'b9\'a6\'b7\'f2\'a3\'ac\'bf\'c9\'d3\'c3\'d5\'e2\'b8\'f6\'c0\'e0\'bf\'ec\'cb\'d9\'b4\'f2\'d3\'a1\'b3\'f6\'cb\'f9\'d3\'d0\'b5\'c4\'c4\'a3\'d0\'cd\'ca\'f4\'d0\'d4\'a3\'ac\'d6\'b1\'bd\'d3\'d5\'b3\'cc\'f9\'bc\'b4\'bf\'c9\
\
NSObject+JSON\
\pard\tx866\pardeftab866\pardirnatural\partightenfactor0
\cf0 1.\'d7\'d6\'b5\'e4\'bb\'f2\'b6\'d4\'cf\'f3\'d7\'aa\'b3\'c9JSON\'d7\'d6\'b7\'fb\'b4\'ae\'ca\'fd\'be\'dd\
\
}
|
{
"pile_set_name": "Github"
}
|
module.exports = require('./lib/from');
|
{
"pile_set_name": "Github"
}
|
/*
* Generated by confdc --mib2yang-std
* Source: mgmt/dmi/model/common/mib-source/BGP4-MIB.mib
*/
/*
* This YANG module has been generated by smidump 0.5.0:
*
* smidump -f yang BGP4-MIB
*
* Do not edit. Edit the source file instead!
*/
module BGP4-MIB {
namespace "urn:ietf:params:xml:ns:yang:smiv2:BGP4-MIB";
prefix BGP4-MIB;
import ietf-inet-types {
prefix "inet";
}
import ietf-yang-smiv2 {
prefix "smiv2";
}
import ietf-yang-types {
prefix "yang";
}
organization
"IETF BGP Working Group";
contact
" John Chu (Editor)
Postal: IBM Corp.
P.O.Box 218
Yorktown Heights, NY 10598
US
Tel: +1 914 945 3156
Fax: +1 914 945 2141
E-mail: jychu@watson.ibm.com";
description
"The MIB module for BGP-4.";
revision 1994-05-05 {
description
"[Revision added by libsmi due to a LAST-UPDATED clause.]";
}
container BGP4-MIB {
config false;
container bgp {
smiv2:oid "1.3.6.1.2.1.15";
leaf bgpVersion {
type binary {
length "1..255";
}
description
"Vector of supported BGP protocol version
numbers. Each peer negotiates the version
from this vector. Versions are identified
via the string of bits contained within this
object. The first octet contains bits 0 to
7, the second octet contains bits 8 to 15,
and so on, with the most significant bit
referring to the lowest bit number in the
octet (e.g., the MSB of the first octet
refers to bit 0). If a bit, i, is present
and set, then the version (i+1) of the BGP
is supported.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.1";
}
leaf bgpLocalAs {
type int32 {
range "0..65535";
}
description
"The local autonomous system number.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.2";
}
leaf bgpIdentifier {
type inet:ipv4-address;
description
"The BGP Identifier of local system.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.4";
}
}
container bgpPeerTable {
description
"BGP peer table. This table contains,
one entry per BGP peer, information about
the connections with BGP peers.";
smiv2:oid "1.3.6.1.2.1.15.3";
list bgpPeerEntry {
key "bgpPeerRemoteAddr";
description
"Entry containing information about the
connection with a BGP peer.";
smiv2:oid "1.3.6.1.2.1.15.3.1";
leaf bgpPeerIdentifier {
type inet:ipv4-address;
description
"The BGP Identifier of this entry's BGP
peer.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.1";
}
leaf bgpPeerState {
type enumeration {
enum "idle" {
value "1";
}
enum "connect" {
value "2";
}
enum "active" {
value "3";
}
enum "opensent" {
value "4";
}
enum "openconfirm" {
value "5";
}
enum "established" {
value "6";
}
}
description
"The BGP peer connection state.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.2";
}
leaf bgpPeerAdminStatus {
type enumeration {
enum "stop" {
value "1";
}
enum "start" {
value "2";
}
}
description
"The desired state of the BGP connection.
A transition from 'stop' to 'start' will
cause the BGP Start Event to be generated.
A transition from 'start' to 'stop' will
cause the BGP Stop Event to be generated.
This parameter can be used to restart BGP
peer connections. Care should be used in
providing write access to this object
without adequate authentication.";
smiv2:max-access "read-write";
smiv2:oid "1.3.6.1.2.1.15.3.1.3";
}
leaf bgpPeerNegotiatedVersion {
type int32;
description
"The negotiated version of BGP running
between the two peers.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.4";
}
leaf bgpPeerLocalAddr {
type inet:ipv4-address;
description
"The local IP address of this entry's BGP
connection.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.5";
}
leaf bgpPeerLocalPort {
type int32 {
range "0..65535";
}
description
"The local port for the TCP connection
between the BGP peers.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.6";
}
leaf bgpPeerRemoteAddr {
type inet:ipv4-address;
description
"The remote IP address of this entry's BGP
peer.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.7";
}
leaf bgpPeerRemotePort {
type int32 {
range "0..65535";
}
description
"The remote port for the TCP connection
between the BGP peers. Note that the
objects bgpPeerLocalAddr,
bgpPeerLocalPort, bgpPeerRemoteAddr and
bgpPeerRemotePort provide the appropriate
reference to the standard MIB TCP
connection table.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.8";
}
leaf bgpPeerRemoteAs {
type int32 {
range "0..65535";
}
description
"The remote autonomous system number.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.9";
}
leaf bgpPeerInUpdates {
type yang:counter32;
description
"The number of BGP UPDATE messages
received on this connection. This object
should be initialized to zero (0) when the
connection is established.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.10";
}
leaf bgpPeerOutUpdates {
type yang:counter32;
description
"The number of BGP UPDATE messages
transmitted on this connection. This
object should be initialized to zero (0)
when the connection is established.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.11";
}
leaf bgpPeerInTotalMessages {
type yang:counter32;
description
"The total number of messages received
from the remote peer on this connection.
This object should be initialized to zero
when the connection is established.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.12";
}
leaf bgpPeerOutTotalMessages {
type yang:counter32;
description
"The total number of messages transmitted to
the remote peer on this connection. This
object should be initialized to zero when
the connection is established.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.13";
}
leaf bgpPeerLastError {
type binary {
length "2";
}
description
"The last error code and subcode seen by this
peer on this connection. If no error has
occurred, this field is zero. Otherwise, the
first byte of this two byte OCTET STRING
contains the error code, and the second byte
contains the subcode.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.14";
}
leaf bgpPeerFsmEstablishedTransitions {
type yang:counter32;
description
"The total number of times the BGP FSM
transitioned into the established state.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.15";
}
leaf bgpPeerFsmEstablishedTime {
type yang:gauge32;
description
"This timer indicates how long (in
seconds) this peer has been in the
Established state or how long
since this peer was last in the
Established state. It is set to zero when
a new peer is configured or the router is
booted.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.16";
}
leaf bgpPeerConnectRetryInterval {
type int32 {
range "1..65535";
}
description
"Time interval in seconds for the
ConnectRetry timer. The suggested value
for this timer is 120 seconds.";
smiv2:max-access "read-write";
smiv2:oid "1.3.6.1.2.1.15.3.1.17";
}
leaf bgpPeerHoldTime {
type int32 {
range "0|3..65535";
}
description
"Time interval in seconds for the Hold
Timer established with the peer. The
value of this object is calculated by this
BGP speaker by using the smaller of the
value in bgpPeerHoldTimeConfigured and the
Hold Time received in the OPEN message.
This value must be at lease three seconds
if it is not zero (0) in which case the
Hold Timer has not been established with
the peer, or, the value of
bgpPeerHoldTimeConfigured is zero (0).";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.18";
}
leaf bgpPeerKeepAlive {
type int32 {
range "0..21845";
}
description
"Time interval in seconds for the KeepAlive
timer established with the peer. The value
of this object is calculated by this BGP
speaker such that, when compared with
bgpPeerHoldTime, it has the same
proportion as what
bgpPeerKeepAliveConfigured has when
compared with bgpPeerHoldTimeConfigured.
If the value of this object is zero (0),
it indicates that the KeepAlive timer has
not been established with the peer, or,
the value of bgpPeerKeepAliveConfigured is
zero (0).";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.19";
}
leaf bgpPeerHoldTimeConfigured {
type int32 {
range "0|3..65535";
}
description
"Time interval in seconds for the Hold Time
configured for this BGP speaker with this
peer. This value is placed in an OPEN
message sent to this peer by this BGP
speaker, and is compared with the Hold
Time field in an OPEN message received
from the peer when determining the Hold
Time (bgpPeerHoldTime) with the peer.
This value must not be less than three
seconds if it is not zero (0) in which
case the Hold Time is NOT to be
established with the peer. The suggested
value for this timer is 90 seconds.";
smiv2:max-access "read-write";
smiv2:oid "1.3.6.1.2.1.15.3.1.20";
}
leaf bgpPeerKeepAliveConfigured {
type int32 {
range "0..21845";
}
description
"Time interval in seconds for the
KeepAlive timer configured for this BGP
speaker with this peer. The value of this
object will only determine the
KEEPALIVE messages' frequency relative to
the value specified in
bgpPeerHoldTimeConfigured; the actual
time interval for the KEEPALIVE messages
is indicated by bgpPeerKeepAlive. A
reasonable maximum value for this timer
would be configured to be one
third of that of
bgpPeerHoldTimeConfigured.
If the value of this object is zero (0),
no periodical KEEPALIVE messages are sent
to the peer after the BGP connection has
been established. The suggested value for
this timer is 30 seconds.";
smiv2:max-access "read-write";
smiv2:oid "1.3.6.1.2.1.15.3.1.21";
}
leaf bgpPeerMinASOriginationInterval {
type int32 {
range "1..65535";
}
description
"Time interval in seconds for the
MinASOriginationInterval timer.
The suggested value for this timer is 15
seconds.";
smiv2:max-access "read-write";
smiv2:oid "1.3.6.1.2.1.15.3.1.22";
}
leaf bgpPeerMinRouteAdvertisementInterval {
type int32 {
range "1..65535";
}
description
"Time interval in seconds for the
MinRouteAdvertisementInterval timer.
The suggested value for this timer is 30
seconds.";
smiv2:max-access "read-write";
smiv2:oid "1.3.6.1.2.1.15.3.1.23";
}
leaf bgpPeerInUpdateElapsedTime {
type yang:gauge32;
description
"Elapsed time in seconds since the last BGP
UPDATE message was received from the peer.
Each time bgpPeerInUpdates is incremented,
the value of this object is set to zero
(0).";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.3.1.24";
}
}
}
container bgpRcvdPathAttrTable {
status obsolete;
description
"The BGP Received Path Attribute Table
contains information about paths to
destination networks received from all
peers running BGP version 3 or less.";
smiv2:oid "1.3.6.1.2.1.15.5";
list bgpPathAttrEntry {
key "bgpPathAttrDestNetwork bgpPathAttrPeer";
status obsolete;
description
"Information about a path to a network.";
smiv2:oid "1.3.6.1.2.1.15.5.1";
leaf bgpPathAttrPeer {
type inet:ipv4-address;
status obsolete;
description
"The IP address of the peer where the path
information was learned.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.5.1.1";
}
leaf bgpPathAttrDestNetwork {
type inet:ipv4-address;
status obsolete;
description
"The address of the destination network.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.5.1.2";
}
leaf bgpPathAttrOrigin {
type enumeration {
enum "igp" {
value "1";
}
enum "egp" {
value "2";
}
enum "incomplete" {
value "3";
}
}
status obsolete;
description
"The ultimate origin of the path information.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.5.1.3";
}
leaf bgpPathAttrASPath {
type binary {
length "2..255";
}
status obsolete;
description
"The set of ASs that must be traversed to
reach the network. This object is
probably best represented as SEQUENCE OF
INTEGER. For SMI compatibility, though,
it is represented as OCTET STRING. Each
AS is represented as a pair of octets
according to the following algorithm:
first-byte-of-pair = ASNumber / 256;
second-byte-of-pair = ASNumber & 255;";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.5.1.4";
}
leaf bgpPathAttrNextHop {
type inet:ipv4-address;
status obsolete;
description
"The address of the border router that
should be used for the destination
network.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.5.1.5";
}
leaf bgpPathAttrInterASMetric {
type int32;
status obsolete;
description
"The optional inter-AS metric. If this
attribute has not been provided for this
route, the value for this object is 0.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.5.1.6";
}
}
}
container bgp4PathAttrTable {
description
"The BGP-4 Received Path Attribute Table
contains information about paths to
destination networks received from all
BGP4 peers.";
smiv2:oid "1.3.6.1.2.1.15.6";
list bgp4PathAttrEntry {
key "bgp4PathAttrIpAddrPrefix bgp4PathAttrIpAddrPrefixLen bgp4PathAttrPeer";
description
"Information about a path to a network.";
smiv2:oid "1.3.6.1.2.1.15.6.1";
leaf bgp4PathAttrPeer {
type inet:ipv4-address;
description
"The IP address of the peer where the path
information was learned.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.1";
}
leaf bgp4PathAttrIpAddrPrefixLen {
type int32 {
range "0..32";
}
description
"Length in bits of the IP address prefix
in the Network Layer Reachability
Information field.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.2";
}
leaf bgp4PathAttrIpAddrPrefix {
type inet:ipv4-address;
description
"An IP address prefix in the Network Layer
Reachability Information field. This object
is an IP address containing the prefix with
length specified by
bgp4PathAttrIpAddrPrefixLen.
Any bits beyond the length specified by
bgp4PathAttrIpAddrPrefixLen are zeroed.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.3";
}
leaf bgp4PathAttrOrigin {
type enumeration {
enum "igp" {
value "1";
}
enum "egp" {
value "2";
}
enum "incomplete" {
value "3";
}
}
description
"The ultimate origin of the path
information.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.4";
}
leaf bgp4PathAttrASPathSegment {
type binary {
length "2..255";
}
description
"The sequence of AS path segments. Each AS
path segment is represented by a triple
<type, length, value>.
The type is a 1-octet field which has two
possible values:
1 AS_SET: unordered set of ASs a
route in the UPDATE
message has traversed
2 AS_SEQUENCE: ordered set of ASs
a route in the UPDATE
message has traversed.
The length is a 1-octet field containing the
number of ASs in the value field.
The value field contains one or more AS
numbers, each AS is represented in the octet
string as a pair of octets according to the
following algorithm:
first-byte-of-pair = ASNumber / 256;
second-byte-of-pair = ASNumber & 255;";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.5";
}
leaf bgp4PathAttrNextHop {
type inet:ipv4-address;
description
"The address of the border router that
should be used for the destination
network.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.6";
}
leaf bgp4PathAttrMultiExitDisc {
type int32 {
range "-1..2147483647";
}
description
"This metric is used to discriminate
between multiple exit points to an
adjacent autonomous system. A value of -1
indicates the absence of this attribute.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.7";
}
leaf bgp4PathAttrLocalPref {
type int32 {
range "-1..2147483647";
}
description
"The originating BGP4 speaker's degree of
preference for an advertised route. A
value of -1 indicates the absence of this
attribute.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.8";
}
leaf bgp4PathAttrAtomicAggregate {
type enumeration {
enum "lessSpecificRrouteNotSelected" {
value "1";
}
enum "lessSpecificRouteSelected" {
value "2";
}
}
description
"Whether or not the local system has
selected a less specific route without
selecting a more specific route.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.9";
}
leaf bgp4PathAttrAggregatorAS {
type int32 {
range "0..65535";
}
description
"The AS number of the last BGP4 speaker that
performed route aggregation. A value of
zero (0) indicates the absence of this
attribute.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.10";
}
leaf bgp4PathAttrAggregatorAddr {
type inet:ipv4-address;
description
"The IP address of the last BGP4 speaker
that performed route aggregation. A value
of 0.0.0.0 indicates the absence of this
attribute.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.11";
}
leaf bgp4PathAttrCalcLocalPref {
type int32 {
range "-1..2147483647";
}
description
"The degree of preference calculated by the
receiving BGP4 speaker for an advertised
route. A value of -1 indicates the
absence of this attribute.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.12";
}
leaf bgp4PathAttrBest {
type enumeration {
enum "false" {
value "1";
}
enum "true" {
value "2";
}
}
description
"An indication of whether or not this route
was chosen as the best BGP4 route.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.13";
}
leaf bgp4PathAttrUnknown {
type binary {
length "0..255";
}
description
"One or more path attributes not understood
by this BGP4 speaker. Size zero (0)
indicates the absence of such
attribute(s). Octets beyond the maximum
size, if any, are not recorded by this
object.";
smiv2:max-access "read-only";
smiv2:oid "1.3.6.1.2.1.15.6.1.14";
}
}
}
}
notification bgpEstablished {
description
"The BGP Established event is generated when
the BGP FSM enters the ESTABLISHED state.";
smiv2:oid "1.3.6.1.2.1.15.7.1";
container object-1 {
leaf bgpPeerRemoteAddr {
type leafref {
path "/BGP4-MIB:BGP4-MIB/BGP4-MIB:bgpPeerTable/BGP4-MIB:bgpPeerEntry/BGP4-MIB:bgpPeerRemoteAddr";
}
}
leaf bgpPeerLastError {
type leafref {
path "/BGP4-MIB:BGP4-MIB/BGP4-MIB:bgpPeerTable/BGP4-MIB:bgpPeerEntry/BGP4-MIB:bgpPeerLastError";
}
}
}
container object-2 {
leaf bgpPeerRemoteAddr {
type leafref {
path "/BGP4-MIB:BGP4-MIB/BGP4-MIB:bgpPeerTable/BGP4-MIB:bgpPeerEntry/BGP4-MIB:bgpPeerRemoteAddr";
}
}
leaf bgpPeerState {
type leafref {
path "/BGP4-MIB:BGP4-MIB/BGP4-MIB:bgpPeerTable/BGP4-MIB:bgpPeerEntry/BGP4-MIB:bgpPeerState";
}
}
}
}
notification bgpBackwardTransition {
description
"The BGPBackwardTransition Event is generated
when the BGP FSM moves from a higher numbered
state to a lower numbered state.";
smiv2:oid "1.3.6.1.2.1.15.7.2";
container object-1 {
leaf bgpPeerRemoteAddr {
type leafref {
path "/BGP4-MIB:BGP4-MIB/BGP4-MIB:bgpPeerTable/BGP4-MIB:bgpPeerEntry/BGP4-MIB:bgpPeerRemoteAddr";
}
}
leaf bgpPeerLastError {
type leafref {
path "/BGP4-MIB:BGP4-MIB/BGP4-MIB:bgpPeerTable/BGP4-MIB:bgpPeerEntry/BGP4-MIB:bgpPeerLastError";
}
}
}
container object-2 {
leaf bgpPeerRemoteAddr {
type leafref {
path "/BGP4-MIB:BGP4-MIB/BGP4-MIB:bgpPeerTable/BGP4-MIB:bgpPeerEntry/BGP4-MIB:bgpPeerRemoteAddr";
}
}
leaf bgpPeerState {
type leafref {
path "/BGP4-MIB:BGP4-MIB/BGP4-MIB:bgpPeerTable/BGP4-MIB:bgpPeerEntry/BGP4-MIB:bgpPeerState";
}
}
}
}
smiv2:alias "bgp" {
smiv2:oid "1.3.6.1.2.1.15";
}
smiv2:alias "bgpTraps" {
smiv2:oid "1.3.6.1.2.1.15.7";
}
}
|
{
"pile_set_name": "Github"
}
|
package com.ok.okhelper.pojo.dto;
import lombok.Data;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.util.Date;
/**
* Author: zc
* Date: 2018/4/30
* Description:
*/
@Data
public class HotSaleVo {
/**
* 主键
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "SELECT LAST_INSERT_ID()")
private Long id;
/**
* 商品名
*/
@Column(name = "product_name")
private String productName;
/**
* 商品标题
*/
@Column(name = "product_title")
private String productTitle;
/**
* 商品属性(使用json存储)
*/
@Column(name = "product_attribute")
private String productAttribute;
/**
* 类别Id
*/
@Column(name = "category_id")
private Long categoryId;
/**
* 可销售库存(小于等于真是库存)
*/
@Column(name = "sales_stock")
private Integer salesStock;
/**
* 规格
*/
private String specification;
/**
* 规格单位
*/
private String unit;
/**
* 零售价
*/
@Column(name = "retail_price")
private BigDecimal retailPrice;
/**
* 主图
*/
@Column(name = "main_img")
private String mainImg;
/**
* 副图(数组)
*/
@Column(name = "sub_imgs")
private String subImgs;
/**
* 货号
*/
@Column(name = "article_number")
private String articleNumber;
/**
* 条码
*/
@Column(name = "bar_code")
private String barCode;
/**
* 操作者
*/
private Long operator;
/**
* 创建日期
*/
@Column(name = "create_time")
private Date createTime;
/**
* 更新日期
*/
@Column(name = "update_time")
private Date updateTime;
/**
* 状态 0下架,1上架
*/
@Column(name = "delete_status")
private Integer deleteStatus;
/**
* 所属商店Id
*/
@Column(name = "store_id")
private Long storeId;
/**
* 销量
*/
private Integer salesVolume;
}
|
{
"pile_set_name": "Github"
}
|
/* __ *\
** ________ ___ / / ___ Scala API **
** / __/ __// _ | / / / _ | (c) 2006-2016, LAMP/EPFL **
** __\ \/ /__/ __ |/ /__/ __ | http://www.scala-lang.org/ **
** /____/\___/_/ |_/____/_/ | | **
** |/ **
\* */
package scala
package collection
import convert._
/** A variety of implicit conversions supporting interoperability between
* Scala and Java collections.
*
* The following conversions are supported:
*{{{
* scala.collection.Iterable <=> java.lang.Iterable
* scala.collection.Iterable <=> java.util.Collection
* scala.collection.Iterator <=> java.util.{ Iterator, Enumeration }
* scala.collection.mutable.Buffer <=> java.util.List
* scala.collection.mutable.Set <=> java.util.Set
* scala.collection.mutable.Map <=> java.util.{ Map, Dictionary }
* scala.collection.concurrent.Map <=> java.util.concurrent.ConcurrentMap
*}}}
* In all cases, converting from a source type to a target type and back
* again will return the original source object:
*
*{{{
* import scala.collection.JavaConversions._
*
* val sl = new scala.collection.mutable.ListBuffer[Int]
* val jl : java.util.List[Int] = sl
* val sl2 : scala.collection.mutable.Buffer[Int] = jl
* assert(sl eq sl2)
*}}}
* In addition, the following one way conversions are provided:
*
*{{{
* scala.collection.Seq => java.util.List
* scala.collection.mutable.Seq => java.util.List
* scala.collection.Set => java.util.Set
* scala.collection.Map => java.util.Map
* java.util.Properties => scala.collection.mutable.Map[String, String]
*}}}
*
* The transparent conversions provided here are considered
* fragile because they can result in unexpected behavior and performance.
*
* Therefore, this API has been deprecated and `JavaConverters` should be
* used instead. `JavaConverters` provides the same conversions, but through
* extension methods.
*
* @author Miles Sabin
* @author Martin Odersky
* @since 2.8
*/
@deprecated("use JavaConverters", since="2.12.0")
object JavaConversions extends WrapAsScala with WrapAsJava
|
{
"pile_set_name": "Github"
}
|
# json-schema-traverse
Traverse JSON Schema passing each schema object to callback
[](https://travis-ci.org/epoberezkin/json-schema-traverse)
[](https://www.npmjs.com/package/json-schema-traverse)
[](https://coveralls.io/github/epoberezkin/json-schema-traverse?branch=master)
## Install
```
npm install json-schema-traverse
```
## Usage
```javascript
const traverse = require('json-schema-traverse');
const schema = {
properties: {
foo: {type: 'string'},
bar: {type: 'integer'}
}
};
traverse(schema, cb);
// cb is called 3 times with:
// 1. root schema
// 2. {type: 'string'}
// 3. {type: 'integer'}
```
Callback function is called for each schema object (not including draft-06 boolean schemas), including the root schema. Schema references ($ref) are not resolved, they are passed as is.
Callback is passed these parameters:
- _schema_: the current schema object
- _JSON pointer_: from the root schema to the current schema object
- _root schema_: the schema passed to `traverse` object
- _parent JSON pointer_: from the root schema to the parent schema object (see below)
- _parent keyword_: the keyword inside which this schema appears (e.g. `properties`, `anyOf`, etc.)
- _parent schema_: not necessarily parent object/array; in the example above the parent schema for `{type: 'string'}` is the root schema
- _index/property_: index or property name in the array/object containing multiple schemas; in the example above for `{type: 'string'}` the property name is `'foo'`
## Traverse objects in all unknown keywords
```javascript
const traverse = require('json-schema-traverse');
const schema = {
mySchema: {
minimum: 1,
maximum: 2
}
};
traverse(schema, {allKeys: true}, cb);
// cb is called 2 times with:
// 1. root schema
// 2. mySchema
```
Without option `allKeys: true` callback will be called only with root schema.
## License
[MIT](https://github.com/epoberezkin/json-schema-traverse/blob/master/LICENSE)
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* @package Joomla.Administrator
* @subpackage com_languages
*
* @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
/**
* Utility class working with languages
*
* @since 1.6
*/
abstract class JHtmlLanguages
{
/**
* Method to generate an information about the default language.
*
* @param boolean $published True if the language is the default.
*
* @return string HTML code.
*/
public static function published($published)
{
if (!$published)
{
return ' ';
}
return JHtml::_('image', 'menu/icon-16-default.png', JText::_('COM_LANGUAGES_HEADING_DEFAULT'), null, true);
}
/**
* Method to generate an input radio button.
*
* @param integer $rowNum The row number.
* @param string $language Language tag.
*
* @return string HTML code.
*/
public static function id($rowNum, $language)
{
return '<input'
. ' type="radio"'
. ' id="cb' . $rowNum . '"'
. ' name="cid"'
. ' value="' . htmlspecialchars($language) . '"'
. ' onclick="Joomla.isChecked(this.checked);"'
. ' title="' . ($rowNum + 1) . '"'
. '/>';
}
/**
* Method to generate an array of clients.
*
* @return array of client objects.
*/
public static function clients()
{
return array(
JHtml::_('select.option', 0, JText::_('JSITE')),
JHtml::_('select.option', 1, JText::_('JADMINISTRATOR'))
);
}
/**
* Returns an array of published state filter options.
*
* @return string The HTML code for the select tag.
*
* @since 1.6
*/
public static function publishedOptions()
{
// Build the active state filter options.
$options = array();
$options[] = JHtml::_('select.option', '1', 'JPUBLISHED');
$options[] = JHtml::_('select.option', '0', 'JUNPUBLISHED');
$options[] = JHtml::_('select.option', '-2', 'JTRASHED');
$options[] = JHtml::_('select.option', '*', 'JALL');
return $options;
}
}
|
{
"pile_set_name": "Github"
}
|
Feed: http://blog.maartenballiauw.be/syndication.axd
DiscoveryDate: 10/31/2018
|
{
"pile_set_name": "Github"
}
|
/*
* app_csm.h
*
* Copyright(c) 2016-2019 Nephos/Estinet.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, see <http://www.gnu.org/licenses/>.
*
* The full GNU General Public License is included in this distribution in
* the file called "COPYING".
*
* Maintainer: jianjun, grace Li from nephos
*/
#ifndef APP_CSM_H_
#define APP_CSM_H_
#include <sys/queue.h>
#include "../include/mlacp_fsm.h"
struct CSM;
enum APP_CONNECTION_STATE
{
APP_NONEXISTENT,
APP_RESET,
APP_CONNSENT,
APP_CONNREC,
APP_CONNECTING,
APP_OPERATIONAL
};
typedef enum APP_CONNECTION_STATE APP_CONNECTION_STATE_E;
struct AppCSM
{
struct mLACP mlacp;
APP_CONNECTION_STATE_E current_state;
uint32_t rx_connect_msg_id;
uint32_t tx_connect_msg_id;
uint32_t invalid_msg_id;
TAILQ_HEAD(app_msg_list, Msg) app_msg_list;
uint8_t invalid_msg : 1;
uint8_t nak_msg : 1;
};
void app_csm_init(struct CSM*, int all);
void app_csm_finalize(struct CSM*);
void app_csm_transit(struct CSM*);
int app_csm_prepare_iccp_msg(struct CSM*, char*, size_t);
void app_csm_enqueue_msg(struct CSM*, struct Msg*);
struct Msg* app_csm_dequeue_msg(struct CSM*);
void app_csm_correspond_from_msg(struct CSM*, struct Msg*);
void app_csm_correspond_from_connect_msg(struct CSM*, struct Msg*);
void app_csm_correspond_from_connect_ack_msg(struct CSM*, struct Msg*);
int app_csm_prepare_nak_msg(struct CSM*, char*, size_t);
int app_csm_prepare_connect_msg(struct CSM*, char*, size_t);
int app_csm_prepare_connect_ack_msg(struct CSM*, char*, size_t);
#endif /* APP_CSM_H_ */
|
{
"pile_set_name": "Github"
}
|
{
"icon": "maki-school",
"geometry": [
"point",
"area"
],
"tags": {
"office": "educational_institution"
},
"terms": [],
"name": "Educational Institution"
}
|
{
"pile_set_name": "Github"
}
|
#define PROGRAM hist2
#define MODULE_LIST hist2.f
#define MAIN_LANG_FORTRAN
#define R3LIB
#define USES_FORTRAN
#define LIB_RTL
#define LIB_TAE
#define LIB_P2SUB
#define LIB_P3SUB
|
{
"pile_set_name": "Github"
}
|
///////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2002, Industrial Light & Magic, a division of Lucas
// Digital Ltd. LLC
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Industrial Light & Magic nor the names of
// its contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_IMF_ARRAY_H
#define INCLUDED_IMF_ARRAY_H
//-------------------------------------------------------------------------
//
// class Array
// class Array2D
//
// "Arrays of T" whose sizes are not known at compile time.
// When an array goes out of scope, its elements are automatically
// deleted.
//
// Usage example:
//
// struct C
// {
// C () {std::cout << "C::C (" << this << ")\n";};
// virtual ~C () {std::cout << "C::~C (" << this << ")\n";};
// };
//
// int
// main ()
// {
// Array <C> a(3);
//
// C &b = a[1];
// const C &c = a[1];
// C *d = a + 2;
// const C *e = a;
//
// return 0;
// }
//
//-------------------------------------------------------------------------
namespace Imf {
template <class T>
class Array
{
public:
//-----------------------------
// Constructors and destructors
//-----------------------------
Array () {_data = 0;}
Array (long size) {_data = new T[size];}
~Array () {delete [] _data;}
//-----------------------------
// Access to the array elements
//-----------------------------
operator T * () {return _data;}
operator const T * () const {return _data;}
//------------------------------------------------------
// Resize and clear the array (the contents of the array
// are not preserved across the resize operation).
//
// resizeEraseUnsafe() is more memory efficient than
// resizeErase() because it deletes the old memory block
// before allocating a new one, but if allocating the
// new block throws an exception, resizeEraseUnsafe()
// leaves the array in an unusable state.
//
//------------------------------------------------------
void resizeErase (long size);
void resizeEraseUnsafe (long size);
private:
Array (const Array &); // Copying and assignment
Array & operator = (const Array &); // are not implemented
T * _data;
};
template <class T>
class Array2D
{
public:
//-----------------------------
// Constructors and destructors
//-----------------------------
Array2D (); // empty array, 0 by 0 elements
Array2D (long sizeX, long sizeY); // sizeX by sizeY elements
~Array2D ();
//-----------------------------
// Access to the array elements
//-----------------------------
T * operator [] (long x);
const T * operator [] (long x) const;
//------------------------------------------------------
// Resize and clear the array (the contents of the array
// are not preserved across the resize operation).
//
// resizeEraseUnsafe() is more memory efficient than
// resizeErase() because it deletes the old memory block
// before allocating a new one, but if allocating the
// new block throws an exception, resizeEraseUnsafe()
// leaves the array in an unusable state.
//
//------------------------------------------------------
void resizeErase (long sizeX, long sizeY);
void resizeEraseUnsafe (long sizeX, long sizeY);
private:
Array2D (const Array2D &); // Copying and assignment
Array2D & operator = (const Array2D &); // are not implemented
long _sizeY;
T * _data;
};
//---------------
// Implementation
//---------------
template <class T>
inline void
Array<T>::resizeErase (long size)
{
T *tmp = new T[size];
delete [] _data;
_data = tmp;
}
template <class T>
inline void
Array<T>::resizeEraseUnsafe (long size)
{
delete [] _data;
_data = 0;
_data = new T[size];
}
template <class T>
inline
Array2D<T>::Array2D ():
_sizeY (0), _data (0)
{
// emtpy
}
template <class T>
inline
Array2D<T>::Array2D (long sizeX, long sizeY):
_sizeY (sizeY), _data (new T[sizeX * sizeY])
{
// emtpy
}
template <class T>
inline
Array2D<T>::~Array2D ()
{
delete [] _data;
}
template <class T>
inline T *
Array2D<T>::operator [] (long x)
{
return _data + x * _sizeY;
}
template <class T>
inline const T *
Array2D<T>::operator [] (long x) const
{
return _data + x * _sizeY;
}
template <class T>
inline void
Array2D<T>::resizeErase (long sizeX, long sizeY)
{
T *tmp = new T[sizeX * sizeY];
delete [] _data;
_sizeY = sizeY;
_data = tmp;
}
template <class T>
inline void
Array2D<T>::resizeEraseUnsafe (long sizeX, long sizeY)
{
delete [] _data;
_data = 0;
_sizeY = 0;
_data = new T[sizeX * sizeY];
_sizeY = sizeY;
}
} // namespace Imf
#endif
|
{
"pile_set_name": "Github"
}
|
---
# Defines interface used for cluster
corosync_bindnet_interface: '{{ openstack_management_interface }}'
corosync_cluster_name: 'openstack'
# Defines if unicast mode should be used rather than multicast
corosync_unicast_mode: true
pacemaker_cluster_constraints:
- constraint: 'colocation'
action: 'add'
source_resource_id: 'lb-haproxy-clone'
target_resource_id: 'vip'
# score: 'INFINITY'
- constraint: 'order'
order:
first_resource: 'vip'
first_resource_action: 'start'
second_resource: 'lb-haproxy-clone'
# second_resource_action: 'start'
op_options:
- 'kind=Optional'
pacemaker_cluster_group: '{{ openstack_controllers_group }}'
pacemaker_cluster_resources:
- resource_id: 'vip'
action: 'create'
provider: 'ocf:heartbeat:IPaddr2'
options:
- 'ip={{ openstack_vip }}'
- 'cidr_netmask=24'
op: 'monitor'
op_options:
- 'interval=30s'
- resource_id: 'lb-haproxy'
action: 'create'
provider: 'systemd:haproxy'
options:
- '--clone'
- '--force'
# - resource_id: 'openstack-keystone'
# action: 'create'
# provider: 'systemd:openstack-keystone'
# options:
# - '--clone'
# - 'interleave=true'
# - '--force'
# Define specific cluster settings to configure
pacemaker_cluster_settings:
# - property: 'start-failure-is-fatal'
# value: 'false'
- property: 'pe-warn-series-max'
value: 1000
- property: 'pe-input-series-max'
value: 1000
- property: 'pe-error-series-max'
value: 1000
- property: 'cluster-recheck-interval'
value: 5min
|
{
"pile_set_name": "Github"
}
|
<?php
/*
* This file is part of the API Platform project.
*
* (c) Kévin Dunglas <dunglas@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
namespace ApiPlatform\Core\Tests\Fixtures\TestBundle\Entity;
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ApiResource(mercure=true)
*
* @author Kévin Dunglas <dunglas@gmail.com>
*/
class DummyMercure
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @ORM\Column
*/
public $name;
/**
* @ORM\Column
*/
public $description;
/**
* @ORM\ManyToOne(targetEntity="RelatedDummy")
*/
public $relatedDummy;
}
|
{
"pile_set_name": "Github"
}
|
package request
import (
"reflect"
"sync/atomic"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awsutil"
)
// A Pagination provides paginating of SDK API operations which are paginatable.
// Generally you should not use this type directly, but use the "Pages" API
// operations method to automatically perform pagination for you. Such as,
// "S3.ListObjectsPages", and "S3.ListObjectsPagesWithContext" methods.
//
// Pagination differs from a Paginator type in that pagination is the type that
// does the pagination between API operations, and Paginator defines the
// configuration that will be used per page request.
//
// cont := true
// for p.Next() && cont {
// data := p.Page().(*s3.ListObjectsOutput)
// // process the page's data
// }
// return p.Err()
//
// See service client API operation Pages methods for examples how the SDK will
// use the Pagination type.
type Pagination struct {
// Function to return a Request value for each pagination request.
// Any configuration or handlers that need to be applied to the request
// prior to getting the next page should be done here before the request
// returned.
//
// NewRequest should always be built from the same API operations. It is
// undefined if different API operations are returned on subsequent calls.
NewRequest func() (*Request, error)
// EndPageOnSameToken, when enabled, will allow the paginator to stop on
// token that are the same as its previous tokens.
EndPageOnSameToken bool
started bool
prevTokens []interface{}
nextTokens []interface{}
err error
curPage interface{}
}
// HasNextPage will return true if Pagination is able to determine that the API
// operation has additional pages. False will be returned if there are no more
// pages remaining.
//
// Will always return true if Next has not been called yet.
func (p *Pagination) HasNextPage() bool {
if !p.started {
return true
}
hasNextPage := len(p.nextTokens) != 0
if p.EndPageOnSameToken {
return hasNextPage && !awsutil.DeepEqual(p.nextTokens, p.prevTokens)
}
return hasNextPage
}
// Err returns the error Pagination encountered when retrieving the next page.
func (p *Pagination) Err() error {
return p.err
}
// Page returns the current page. Page should only be called after a successful
// call to Next. It is undefined what Page will return if Page is called after
// Next returns false.
func (p *Pagination) Page() interface{} {
return p.curPage
}
// Next will attempt to retrieve the next page for the API operation. When a page
// is retrieved true will be returned. If the page cannot be retrieved, or there
// are no more pages false will be returned.
//
// Use the Page method to retrieve the current page data. The data will need
// to be cast to the API operation's output type.
//
// Use the Err method to determine if an error occurred if Page returns false.
func (p *Pagination) Next() bool {
if !p.HasNextPage() {
return false
}
req, err := p.NewRequest()
if err != nil {
p.err = err
return false
}
if p.started {
for i, intok := range req.Operation.InputTokens {
awsutil.SetValueAtPath(req.Params, intok, p.nextTokens[i])
}
}
p.started = true
err = req.Send()
if err != nil {
p.err = err
return false
}
p.prevTokens = p.nextTokens
p.nextTokens = req.nextPageTokens()
p.curPage = req.Data
return true
}
// A Paginator is the configuration data that defines how an API operation
// should be paginated. This type is used by the API service models to define
// the generated pagination config for service APIs.
//
// The Pagination type is what provides iterating between pages of an API. It
// is only used to store the token metadata the SDK should use for performing
// pagination.
type Paginator struct {
InputTokens []string
OutputTokens []string
LimitToken string
TruncationToken string
}
// nextPageTokens returns the tokens to use when asking for the next page of data.
func (r *Request) nextPageTokens() []interface{} {
if r.Operation.Paginator == nil {
return nil
}
if r.Operation.TruncationToken != "" {
tr, _ := awsutil.ValuesAtPath(r.Data, r.Operation.TruncationToken)
if len(tr) == 0 {
return nil
}
switch v := tr[0].(type) {
case *bool:
if !aws.BoolValue(v) {
return nil
}
case bool:
if v == false {
return nil
}
}
}
tokens := []interface{}{}
tokenAdded := false
for _, outToken := range r.Operation.OutputTokens {
vs, _ := awsutil.ValuesAtPath(r.Data, outToken)
if len(vs) == 0 {
tokens = append(tokens, nil)
continue
}
v := vs[0]
switch tv := v.(type) {
case *string:
if len(aws.StringValue(tv)) == 0 {
tokens = append(tokens, nil)
continue
}
case string:
if len(tv) == 0 {
tokens = append(tokens, nil)
continue
}
}
tokenAdded = true
tokens = append(tokens, v)
}
if !tokenAdded {
return nil
}
return tokens
}
// Ensure a deprecated item is only logged once instead of each time its used.
func logDeprecatedf(logger aws.Logger, flag *int32, msg string) {
if logger == nil {
return
}
if atomic.CompareAndSwapInt32(flag, 0, 1) {
logger.Log(msg)
}
}
var (
logDeprecatedHasNextPage int32
logDeprecatedNextPage int32
logDeprecatedEachPage int32
)
// HasNextPage returns true if this request has more pages of data available.
//
// Deprecated Use Pagination type for configurable pagination of API operations
func (r *Request) HasNextPage() bool {
logDeprecatedf(r.Config.Logger, &logDeprecatedHasNextPage,
"Request.HasNextPage deprecated. Use Pagination type for configurable pagination of API operations")
return len(r.nextPageTokens()) > 0
}
// NextPage returns a new Request that can be executed to return the next
// page of result data. Call .Send() on this request to execute it.
//
// Deprecated Use Pagination type for configurable pagination of API operations
func (r *Request) NextPage() *Request {
logDeprecatedf(r.Config.Logger, &logDeprecatedNextPage,
"Request.NextPage deprecated. Use Pagination type for configurable pagination of API operations")
tokens := r.nextPageTokens()
if len(tokens) == 0 {
return nil
}
data := reflect.New(reflect.TypeOf(r.Data).Elem()).Interface()
nr := New(r.Config, r.ClientInfo, r.Handlers, r.Retryer, r.Operation, awsutil.CopyOf(r.Params), data)
for i, intok := range nr.Operation.InputTokens {
awsutil.SetValueAtPath(nr.Params, intok, tokens[i])
}
return nr
}
// EachPage iterates over each page of a paginated request object. The fn
// parameter should be a function with the following sample signature:
//
// func(page *T, lastPage bool) bool {
// return true // return false to stop iterating
// }
//
// Where "T" is the structure type matching the output structure of the given
// operation. For example, a request object generated by
// DynamoDB.ListTablesRequest() would expect to see dynamodb.ListTablesOutput
// as the structure "T". The lastPage value represents whether the page is
// the last page of data or not. The return value of this function should
// return true to keep iterating or false to stop.
//
// Deprecated Use Pagination type for configurable pagination of API operations
func (r *Request) EachPage(fn func(data interface{}, isLastPage bool) (shouldContinue bool)) error {
logDeprecatedf(r.Config.Logger, &logDeprecatedEachPage,
"Request.EachPage deprecated. Use Pagination type for configurable pagination of API operations")
for page := r; page != nil; page = page.NextPage() {
if err := page.Send(); err != nil {
return err
}
if getNextPage := fn(page.Data, !page.HasNextPage()); !getNextPage {
return page.Error
}
}
return nil
}
|
{
"pile_set_name": "Github"
}
|
40--Gymnastics/40_Gymnastics_Gymnastics_40_242.jpg
0
|
{
"pile_set_name": "Github"
}
|
<hkobject name="#tkuc$10" class="hkbClipGenerator" signature="0x333b85b9">
<hkparam name="variableBindingSet">null</hkparam>
<hkparam name="userData">0</hkparam>
<hkparam name="name">TKDodgeRight</hkparam>
<hkparam name="animationName">Animations\DodgeRight.hkx</hkparam>
<hkparam name="triggers">#tkuc$9</hkparam>
<hkparam name="cropStartAmountLocalTime">0.000000</hkparam>
<hkparam name="cropEndAmountLocalTime">0.000000</hkparam>
<hkparam name="startTime">0.000000</hkparam>
<hkparam name="playbackSpeed">1.000000</hkparam>
<hkparam name="enforcedDuration">0.000000</hkparam>
<hkparam name="userControlledTimeFraction">0.000000</hkparam>
<hkparam name="animationBindingIndex">-1</hkparam>
<hkparam name="mode">MODE_SINGLE_PLAY</hkparam>
<hkparam name="flags">0</hkparam>
</hkobject>
|
{
"pile_set_name": "Github"
}
|
# Retrowrite
Code repository for "Retrowrite: Statically Instrumenting COTS Binaries for
Fuzzing and Sanitization" (in *IEEE S&P'20*). Please refer to the
[paper](https://nebelwelt.net/publications/files/20Oakland.pdf) for
technical details. There's also a
[36c3 presentation](http://nebelwelt.net/publications/files/19CCC-presentation.pdf)
and [36c3 video](https://media.ccc.de/v/36c3-10880-no_source_no_problem_high_speed_binary_fuzzing)
to get you started.
This project contains 2 different version of retrowrite :
* [Retrowrite](#retrowrite-1) to rewrite classic userspace binaries, and
* [KRetrowrite](#kretrowrite) to rewrite and fuzz kernel modules.
The two versions can be used independently of each other or at the same time.
In case you want to use both please follow the instructions for KRetrowrite.
## General setup
Retrowrite is implemented in python3 (3.6). Make sure python3 and python3-venv
is installed on system. Retrowrite depends on
[capstone](https://github.com/aquynh/capstone). The version
available from the Ubuntu 18.04 repositories
is not compatible with this version. The setup
script pulls the latest version of capstone from the repository and builds it.
Make sure that your system meets the requirements to build capstone.
#### Requirements for target binary
The target binary
* must be compiled as position independent code (PIC/PIE)
* must be x86_64 (32 bit at your own risk)
* must contain symbols (i.e., not stripped; if stripped, please recover
symbols first)
* must not contain C++ exceptions (i.e., C++ exception tables are not
recovered and simply stripped during lifting)
#### Command line helper
The individual tools also have command line help which describes all the
options, and may be accessed with `-h`.
To start with use retrowrite command:
```bash
(retro) $ retrowrite --help
usage: retrowrite [-h] [-a] [-s] [-k] [--kcov] [-c] bin outfile
positional arguments:
bin Input binary to load
outfile Symbolized ASM output
optional arguments:
-h, --help show this help message and exit
-a, --asan Add binary address sanitizer instrumentation
-s, --assembly Generate Symbolized Assembly
-k, --kernel Instrument a kernel module
--kcov Instrument the kernel module with kcov
-c, --cache Save/load register analysis cache (only used with --asan)
--ignorepie Ignore position-independent-executable check (use with
caution)
```
In case you load a non position independent code you will get the following message:
```
(retro) $ retrowrite stack stack.c
***** RetroWrite requires a position-independent executable. *****
It looks like stack is not position independent
If you really want to continue, because you think retrowrite has made a mistake, pass --ignorepie.
```
In the case you think retrowrite is mistaking you can use the argument `--ignorepie`.
## Retrowrite
### Quick Usage Guide
This section highlights the steps to get you up to speed to use userspace retrowrite for rewriting PIC binaries.
Retrowrite ships with an utility with the following features:
* Generate symbolized assembly files from binaries without source code
* BASan: Instrument binary with binary-only Address Sanitizer
* Support for symbolizing (linux) kernel modules
* KCovariance instrumentation support
### Setup
Run `setup.sh`:
* `./setup.sh user`
Activate the virtualenv (from root of the repository):
* `source retro/bin/activate`
(Bonus) To exit virtualenv when you're done with retrowrite:
* `deactivate`
### Usage
#### Commands
##### a. Instrument Binary with Binary-Address Sanitizer (BASan)
`retrowrite --asan </path/to/binary/> </path/to/output/binary>`
Note: Make sure that the binary is position-independent and is not stripped.
This can be checked using `file` command (the output should say `ELF shared object`).
Example, create an instrumented version of `/bin/ls`:
`retrowrite --asan /bin/ls ls-basan-instrumented`
This will generate an assembly (`.s`) file that can be assembled and linked
using any compiler, example:
`gcc ls-basan-instrumented.s -lasan -o ls-basan-instrumented`
**debug** in case you get the error ```undefined reference to `__asan_init_v4'``` ,
replace "asan_init_v4" by "asan_init" in the assembly file, the following command can help you do that:
```sed -i 's/asan_init_v4/asan_init/g' ls-basan-instrumented.s```
##### b. Generate Symbolized Assembly
To generate symbolized assembly that may be modified by hand or post-processed
by existing tools:
`retrowrite </path/to/binary> <path/to/output/asm/files>`
Post-modification, the asm files may be assembled to working binaries as
described above.
While retrowrite is interoperable with other tools, we
strongly encourage researchers to use the retrowrite API for their binary
instrumentation / modification needs! This saves the additional effort of
having to load and parse binaries or assembly files. Check the developer
sections for more details on getting started.
##### c. Instrument Binary with AFL
To generate an AFL instrumented binary, first generate the symbolized assembly
as described above. Then, recompile the symbolized assembly with `afl-gcc` from
[afl++](https://github.com/vanhauser-thc/AFLplusplus) like this:
```
$ AFL_AS_FORCE_INSTRUMENT=1 afl-gcc foo.s -o foo
```
or `afl-clang`.
## Docker / Reproducing Results
See [fuzzing/docker](fuzzing/docker) for more information on building a docker image for
fuzzing and reproducing results.
# KRetrowrite
### Quick Usage Guide
### Setup
Run `setup.sh`:
* `./setup.sh kernel`
Activate the virtualenv (from root of the repository):
* `source retro/bin/activate`
(Bonus) To exit virtualenv when you're done with retrowrite:
* `deactivate`
### Usage
#### Commands
##### Classic instrumentation
* Instrument Binary with Binary-Address Sanitizer (BASan) :`retrowrite --asan --kernel </path/to/module.ko> </path/to/output/module_asan.ko>`
* Generate Symbolized Assembly that may be modified by hand or post-processed by existing tools: `retrowrite </path/to/module.ko> <path/to/output/asm/files>`
##### Fuzzing
For fuzzing campaign please see [fuzzing/](fuzzing/) folder.
# Developer Guide
In general, `librw/` contains the code for loading, disassembly, and
symbolization of binaries and forms the core of all transformations.
Individual transformation passes that build on top this rewriting framework,
such as our binary-only Address Sanitizer (BASan) is contained as individual
tools in `rwtools/`.
The files and folder starting with `k` are linked with the kernel retrowrite version.
# Demos
In the [demos/](demos/) folder, you will find examples for userspace and kernel retrowrite
([demos/user_demo](demos/user_demo) and [demos/kernel_demo](demos/kernel_demo) respectively).
## Cite
The following publications cover different parts of the RetroWrite project:
* *RetroWrite: Statically Instrumenting COTS Binaries for Fuzzing and Sanitization*
Sushant Dinesh, Nathan Burow, Dongyan Xu, and Mathias Payer.
**In Oakland'20: IEEE International Symposium on Security and Privacy, 2020**
* *No source, no problem! High speed binary fuzzing*
Matteo Rizzo, and Mathias Payer.
**In 36c3'19: Chaos Communication Congress, 2019**
# License -- MIT
The MIT License
Copyright (c) 2019 HexHive Group,
Sushant Dinesh <sushant.dinesh94@gmail.com>,
Matteo Rizzo <matteorizzo.personal@gmail.com>,
Mathias Payer <mathias.payer@nebelwelt.net>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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.
|
{
"pile_set_name": "Github"
}
|
/*
* symbolNameUtils.ts
* Copyright (c) Microsoft Corporation.
* Licensed under the MIT license.
* Author: Eric Traut
*
* Static methods that apply to symbols or symbol names.
*/
const _constantRegEx = /^[A-Z0-9_]+$/;
const _underscoreOnlyRegEx = /^[_]+$/;
// Private symbol names start with a double underscore.
export function isPrivateName(name: string) {
return name.length > 2 && name.startsWith('__') && !name.endsWith('__');
}
// Protected symbol names start with a single underscore.
export function isProtectedName(name: string) {
return name.length > 1 && name.startsWith('_') && !name.startsWith('__');
}
export function isPrivateOrProtectedName(name: string) {
return isPrivateName(name) || isProtectedName(name);
}
// "Dunder" names start and end with two underscores.
export function isDunderName(name: string) {
return name.length > 4 && name.startsWith('__') && name.endsWith('__');
}
// Constants are all-caps with possible numbers and underscores.
export function isConstantName(name: string) {
return !!name.match(_constantRegEx) && !name.match(_underscoreOnlyRegEx);
}
|
{
"pile_set_name": "Github"
}
|
b03741c69037cbdcd2809278c00c0350 *tests/data/fate/vsynth2-prores_ks.mov
3884596 tests/data/fate/vsynth2-prores_ks.mov
6cfe987de99cf8ac9d43bdc5cd150838 *tests/data/fate/vsynth2-prores_ks.out.rawvideo
stddev: 0.92 PSNR: 48.78 MAXDIFF: 10 bytes: 7603200/ 7603200
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2019 Naman Dwivedi.
*
* Licensed under the GNU General Public License v3
*
* This is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This software 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.
*
*/
package com.naman14.timberx.playback
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.media.AudioManager
import android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.MediaSessionCompat
/**
* Helper class for listening for when headphones are unplugged (or the audio
* will otherwise cause playback to become "noisy").
*/
class BecomingNoisyReceiver(
private val context: Context,
sessionToken: MediaSessionCompat.Token
) : BroadcastReceiver() {
private val noisyIntentFilter = IntentFilter(ACTION_AUDIO_BECOMING_NOISY)
private val controller = MediaControllerCompat(context, sessionToken)
private var registered = false
fun register() {
if (!registered) {
context.registerReceiver(this, noisyIntentFilter)
registered = true
}
}
fun unregister() {
if (registered) {
context.unregisterReceiver(this)
registered = false
}
}
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == AudioManager.ACTION_AUDIO_BECOMING_NOISY) {
controller.transportControls.pause()
}
}
}
|
{
"pile_set_name": "Github"
}
|
/*
+----------------------------------------------------------------------+
| Zend Engine |
+----------------------------------------------------------------------+
| Copyright (c) Zend Technologies Ltd. (http://www.zend.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 2.00 of the Zend license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.zend.com/license/2_00.txt. |
| If you did not receive a copy of the Zend license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@zend.com so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andi Gutmans <andi@php.net> |
| Zeev Suraski <zeev@php.net> |
+----------------------------------------------------------------------+
*/
#ifndef ZEND_OBJECT_HANDLERS_H
#define ZEND_OBJECT_HANDLERS_H
struct _zend_property_info;
#define ZEND_WRONG_PROPERTY_INFO \
((struct _zend_property_info*)((intptr_t)-1))
#define ZEND_DYNAMIC_PROPERTY_OFFSET ((uintptr_t)(intptr_t)(-1))
#define IS_VALID_PROPERTY_OFFSET(offset) ((intptr_t)(offset) > 0)
#define IS_WRONG_PROPERTY_OFFSET(offset) ((intptr_t)(offset) == 0)
#define IS_DYNAMIC_PROPERTY_OFFSET(offset) ((intptr_t)(offset) < 0)
#define IS_UNKNOWN_DYNAMIC_PROPERTY_OFFSET(offset) (offset == ZEND_DYNAMIC_PROPERTY_OFFSET)
#define ZEND_DECODE_DYN_PROP_OFFSET(offset) ((uintptr_t)(-(intptr_t)(offset) - 2))
#define ZEND_ENCODE_DYN_PROP_OFFSET(offset) ((uintptr_t)(-((intptr_t)(offset) + 2)))
/* The following rule applies to read_property() and read_dimension() implementations:
If you return a zval which is not otherwise referenced by the extension or the engine's
symbol table, its reference count should be 0.
*/
/* Used to fetch property from the object, read-only */
typedef zval *(*zend_object_read_property_t)(zend_object *object, zend_string *member, int type, void **cache_slot, zval *rv);
/* Used to fetch dimension from the object, read-only */
typedef zval *(*zend_object_read_dimension_t)(zend_object *object, zval *offset, int type, zval *rv);
/* The following rule applies to write_property() and write_dimension() implementations:
If you receive a value zval in write_property/write_dimension, you may only modify it if
its reference count is 1. Otherwise, you must create a copy of that zval before making
any changes. You should NOT modify the reference count of the value passed to you.
You must return the final value of the assigned property.
*/
/* Used to set property of the object */
typedef zval *(*zend_object_write_property_t)(zend_object *object, zend_string *member, zval *value, void **cache_slot);
/* Used to set dimension of the object */
typedef void (*zend_object_write_dimension_t)(zend_object *object, zval *offset, zval *value);
/* Used to create pointer to the property of the object, for future direct r/w access.
* May return one of:
* * A zval pointer, without incrementing the reference count.
* * &EG(error_zval), if an exception has been thrown.
* * NULL, if acquiring a direct pointer is not possible.
* In this case, the VM will fall back to using read_property and write_property.
*/
typedef zval *(*zend_object_get_property_ptr_ptr_t)(zend_object *object, zend_string *member, int type, void **cache_slot);
/* Used to check if a property of the object exists */
/* param has_set_exists:
* 0 (has) whether property exists and is not NULL
* 1 (set) whether property exists and is true
* 2 (exists) whether property exists
*/
typedef int (*zend_object_has_property_t)(zend_object *object, zend_string *member, int has_set_exists, void **cache_slot);
/* Used to check if a dimension of the object exists */
typedef int (*zend_object_has_dimension_t)(zend_object *object, zval *member, int check_empty);
/* Used to remove a property of the object */
typedef void (*zend_object_unset_property_t)(zend_object *object, zend_string *member, void **cache_slot);
/* Used to remove a dimension of the object */
typedef void (*zend_object_unset_dimension_t)(zend_object *object, zval *offset);
/* Used to get hash of the properties of the object, as hash of zval's */
typedef HashTable *(*zend_object_get_properties_t)(zend_object *object);
typedef HashTable *(*zend_object_get_debug_info_t)(zend_object *object, int *is_temp);
typedef enum _zend_prop_purpose {
/* Used for debugging. Supersedes get_debug_info handler. */
ZEND_PROP_PURPOSE_DEBUG,
/* Used for (array) casts. */
ZEND_PROP_PURPOSE_ARRAY_CAST,
/* Used for serialization using the "O" scheme.
* Unserialization will use __wakeup(). */
ZEND_PROP_PURPOSE_SERIALIZE,
/* Used for var_export().
* The data will be passed to __set_state() when evaluated. */
ZEND_PROP_PURPOSE_VAR_EXPORT,
/* Used for json_encode(). */
ZEND_PROP_PURPOSE_JSON,
/* Dummy member to ensure that "default" is specified. */
_ZEND_PROP_PURPOSE_NON_EXHAUSTIVE_ENUM
} zend_prop_purpose;
/* The return value must be released using zend_release_properties(). */
typedef zend_array *(*zend_object_get_properties_for_t)(zend_object *object, zend_prop_purpose purpose);
/* Used to call methods */
/* args on stack! */
/* Andi - EX(fbc) (function being called) needs to be initialized already in the INIT fcall opcode so that the parameters can be parsed the right way. We need to add another callback for this.
*/
typedef zend_function *(*zend_object_get_method_t)(zend_object **object, zend_string *method, const zval *key);
typedef zend_function *(*zend_object_get_constructor_t)(zend_object *object);
/* Object maintenance/destruction */
typedef void (*zend_object_dtor_obj_t)(zend_object *object);
typedef void (*zend_object_free_obj_t)(zend_object *object);
typedef zend_object* (*zend_object_clone_obj_t)(zend_object *object);
/* Get class name for display in var_dump and other debugging functions.
* Must be defined and must return a non-NULL value. */
typedef zend_string *(*zend_object_get_class_name_t)(const zend_object *object);
typedef int (*zend_object_compare_t)(zval *object1, zval *object2);
/* Cast an object to some other type.
* readobj and retval must point to distinct zvals.
*/
typedef int (*zend_object_cast_t)(zend_object *readobj, zval *retval, int type);
/* updates *count to hold the number of elements present and returns SUCCESS.
* Returns FAILURE if the object does not have any sense of overloaded dimensions */
typedef int (*zend_object_count_elements_t)(zend_object *object, zend_long *count);
typedef int (*zend_object_get_closure_t)(zend_object *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zend_object **obj_ptr, zend_bool check_only);
typedef HashTable *(*zend_object_get_gc_t)(zend_object *object, zval **table, int *n);
typedef int (*zend_object_do_operation_t)(zend_uchar opcode, zval *result, zval *op1, zval *op2);
struct _zend_object_handlers {
/* offset of real object header (usually zero) */
int offset;
/* object handlers */
zend_object_free_obj_t free_obj; /* required */
zend_object_dtor_obj_t dtor_obj; /* required */
zend_object_clone_obj_t clone_obj; /* optional */
zend_object_read_property_t read_property; /* required */
zend_object_write_property_t write_property; /* required */
zend_object_read_dimension_t read_dimension; /* required */
zend_object_write_dimension_t write_dimension; /* required */
zend_object_get_property_ptr_ptr_t get_property_ptr_ptr; /* required */
zend_object_has_property_t has_property; /* required */
zend_object_unset_property_t unset_property; /* required */
zend_object_has_dimension_t has_dimension; /* required */
zend_object_unset_dimension_t unset_dimension; /* required */
zend_object_get_properties_t get_properties; /* required */
zend_object_get_method_t get_method; /* required */
zend_object_get_constructor_t get_constructor; /* required */
zend_object_get_class_name_t get_class_name; /* required */
zend_object_cast_t cast_object; /* required */
zend_object_count_elements_t count_elements; /* optional */
zend_object_get_debug_info_t get_debug_info; /* optional */
zend_object_get_closure_t get_closure; /* optional */
zend_object_get_gc_t get_gc; /* required */
zend_object_do_operation_t do_operation; /* optional */
zend_object_compare_t compare; /* required */
zend_object_get_properties_for_t get_properties_for; /* optional */
};
BEGIN_EXTERN_C()
extern const ZEND_API zend_object_handlers std_object_handlers;
#define zend_get_std_object_handlers() \
(&std_object_handlers)
#define zend_get_function_root_class(fbc) \
((fbc)->common.prototype ? (fbc)->common.prototype->common.scope : (fbc)->common.scope)
#define ZEND_PROPERTY_ISSET 0x0 /* Property exists and is not NULL */
#define ZEND_PROPERTY_NOT_EMPTY ZEND_ISEMPTY /* Property is not empty */
#define ZEND_PROPERTY_EXISTS 0x2 /* Property exists */
ZEND_API void zend_class_init_statics(zend_class_entry *ce);
ZEND_API zend_function *zend_std_get_static_method(zend_class_entry *ce, zend_string *function_name_strval, const zval *key);
ZEND_API zval *zend_std_get_static_property_with_info(zend_class_entry *ce, zend_string *property_name, int type, struct _zend_property_info **prop_info);
ZEND_API zval *zend_std_get_static_property(zend_class_entry *ce, zend_string *property_name, int type);
ZEND_API ZEND_COLD zend_bool zend_std_unset_static_property(zend_class_entry *ce, zend_string *property_name);
ZEND_API zend_function *zend_std_get_constructor(zend_object *object);
ZEND_API struct _zend_property_info *zend_get_property_info(zend_class_entry *ce, zend_string *member, int silent);
ZEND_API HashTable *zend_std_get_properties(zend_object *object);
ZEND_API HashTable *zend_std_get_gc(zend_object *object, zval **table, int *n);
ZEND_API HashTable *zend_std_get_debug_info(zend_object *object, int *is_temp);
ZEND_API int zend_std_cast_object_tostring(zend_object *object, zval *writeobj, int type);
ZEND_API zval *zend_std_get_property_ptr_ptr(zend_object *object, zend_string *member, int type, void **cache_slot);
ZEND_API zval *zend_std_read_property(zend_object *object, zend_string *member, int type, void **cache_slot, zval *rv);
ZEND_API zval *zend_std_write_property(zend_object *object, zend_string *member, zval *value, void **cache_slot);
ZEND_API int zend_std_has_property(zend_object *object, zend_string *member, int has_set_exists, void **cache_slot);
ZEND_API void zend_std_unset_property(zend_object *object, zend_string *member, void **cache_slot);
ZEND_API zval *zend_std_read_dimension(zend_object *object, zval *offset, int type, zval *rv);
ZEND_API void zend_std_write_dimension(zend_object *object, zval *offset, zval *value);
ZEND_API int zend_std_has_dimension(zend_object *object, zval *offset, int check_empty);
ZEND_API void zend_std_unset_dimension(zend_object *object, zval *offset);
ZEND_API zend_function *zend_std_get_method(zend_object **obj_ptr, zend_string *method_name, const zval *key);
ZEND_API zend_string *zend_std_get_class_name(const zend_object *zobj);
ZEND_API int zend_std_compare_objects(zval *o1, zval *o2);
ZEND_API int zend_std_get_closure(zend_object *obj, zend_class_entry **ce_ptr, zend_function **fptr_ptr, zend_object **obj_ptr, zend_bool check_only);
ZEND_API void rebuild_object_properties(zend_object *zobj);
ZEND_API int zend_check_protected(zend_class_entry *ce, zend_class_entry *scope);
ZEND_API int zend_check_property_access(zend_object *zobj, zend_string *prop_info_name, zend_bool is_dynamic);
ZEND_API zend_function *zend_get_call_trampoline_func(zend_class_entry *ce, zend_string *method_name, int is_static);
ZEND_API uint32_t *zend_get_property_guard(zend_object *zobj, zend_string *member);
/* Default behavior for get_properties_for. For use as a fallback in custom
* get_properties_for implementations. */
ZEND_API HashTable *zend_std_get_properties_for(zend_object *obj, zend_prop_purpose purpose);
/* Will call get_properties_for handler or use default behavior. For use by
* consumers of the get_properties_for API. */
ZEND_API HashTable *zend_get_properties_for(zval *obj, zend_prop_purpose purpose);
#define zend_release_properties(ht) do { \
if ((ht) && !(GC_FLAGS(ht) & GC_IMMUTABLE) && !GC_DELREF(ht)) { \
zend_array_destroy(ht); \
} \
} while (0)
#define zend_free_trampoline(func) do { \
if ((func) == &EG(trampoline)) { \
EG(trampoline).common.function_name = NULL; \
} else { \
efree(func); \
} \
} while (0)
/* Fallback to default comparison implementation if the arguments aren't both objects
* and have the same compare() handler. You'll likely want to use this unless you
* explicitly wish to support comparisons between objects and non-objects. */
#define ZEND_COMPARE_OBJECTS_FALLBACK(op1, op2) \
if (Z_TYPE_P(op1) != IS_OBJECT || \
Z_TYPE_P(op2) != IS_OBJECT || \
Z_OBJ_HT_P(op1)->compare != Z_OBJ_HT_P(op2)->compare) { \
return zend_std_compare_objects(op1, op2); \
}
END_EXTERN_C()
#endif
|
{
"pile_set_name": "Github"
}
|
/*******************************************************************************
* Copyright (c) 2014 Salesforce.com, inc..
* 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:
* Salesforce.com, inc. - initial API and implementation
******************************************************************************/
package com.salesforce.ide.api.metadata.types;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.util.ValidationEventCollector;
import org.apache.log4j.Logger;
public class MetadataValidationEventCollector extends ValidationEventCollector {
private static final Logger logger = Logger.getLogger(MetadataValidationEventCollector.class);
private boolean failOnValidateError = false;
public MetadataValidationEventCollector() {
super();
}
public MetadataValidationEventCollector(boolean failOnValidateError) {
super();
this.failOnValidateError = failOnValidateError;
}
public boolean hasValidationIssues() {
return hasFatals() || hasErrors() || hasWarnings();
}
public boolean hasFatals() {
return hasSeverity(ValidationEvent.FATAL_ERROR);
}
public boolean hasErrors() {
return hasSeverity(ValidationEvent.ERROR);
}
public boolean hasWarnings() {
return hasSeverity(ValidationEvent.WARNING);
}
public boolean hasSeverity(int severity) {
if (!hasEvents()) {
return false;
}
for (ValidationEvent validationEvent : getEvents()) {
if (validationEvent.getSeverity() == severity) {
return true;
}
}
return false;
}
public List<String> getValidationMessages() {
if (!hasEvents()) {
return null;
}
List<String> messages = new ArrayList<>(getEvents().length);
for (ValidationEvent validationEvent : getEvents()) {
messages.add(getSeverity(validationEvent.getSeverity()) + ": " + validationEvent.getMessage());
}
return messages;
}
public void logValidationMessages(String name) {
List<String> validationMessages = getValidationMessages();
if (validationMessages == null || validationMessages.isEmpty()) {
if (logger.isInfoEnabled()) {
logger.info(name + " has no validation issues");
}
} else {
StringBuffer strBuff =
new StringBuffer("Found following validation issues [" + validationMessages.size() + "] for "
+ name);
int cnt = 0;
for (String validationMessage : validationMessages) {
strBuff.append("\n (").append(++cnt).append(") ").append(validationMessage);
}
logger.warn(strBuff.toString());
}
}
private static String getSeverity(int severity) {
switch (severity) {
case ValidationEvent.FATAL_ERROR:
return "FATAL";
case ValidationEvent.ERROR:
return "FATAL";
case ValidationEvent.WARNING:
return "WARNING";
default:
return "";
}
}
@Override
public boolean handleEvent(ValidationEvent event) {
// failOnValidateError determines whether super class determines recovery or this impl
// when false, we always recover from parse errors/failures
if (failOnValidateError) {
return super.handleEvent(event);
}
super.handleEvent(event);
return true;
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.text;
/**
* SupplementaryCharacterData is an SMI-private class which was written for
* RuleBasedBreakIterator and BreakDictionary.
*/
public final class SupplementaryCharacterData implements Cloneable {
/**
* A token used as a character-category value to identify ignore characters
*/
private static final byte IGNORE = -1;
/**
* An array for supplementary characters and values.
* Lower one byte is used to keep a byte-value.
* Upper three bytes are used to keep the first supplementary character
* which has the value. The value is also valid for the following
* supplementary characters until the next supplementary character in
* the array <code>dataTable</code>.
* For example, if the value of <code>dataTable[2]</code> is
* <code>0x01000123</code> and the value of <code>dataTable[3]</code> is
* <code>0x01000567</code>, supplementary characters from
* <code>0x10001</code> to <code>0x10004</code> has the value
* <code>0x23</code>. And, <code>getValue(0x10003)</code> returns the value.
*/
private int[] dataTable;
/**
* Creates a new SupplementaryCharacterData object with the given table.
*/
public SupplementaryCharacterData(int[] table) {
dataTable = table;
}
/**
* Returns a corresponding value for the given supplementary code-point.
*/
public int getValue(int index) {
// Index should be a valid supplementary character.
assert index >= Character.MIN_SUPPLEMENTARY_CODE_POINT &&
index <= Character.MAX_CODE_POINT :
"Invalid code point:" + Integer.toHexString(index);
int i = 0;
int j = dataTable.length - 1;
int k;
for (;;) {
k = (i + j) / 2;
int start = dataTable[k] >> 8;
int end = dataTable[k+1] >> 8;
if (index < start) {
j = k;
} else if (index > (end-1)) {
i = k;
} else {
int v = dataTable[k] & 0xFF;
return (v == 0xFF) ? IGNORE : v;
}
}
}
/**
* Returns the data array.
*/
public int[] getArray() {
return dataTable;
}
}
|
{
"pile_set_name": "Github"
}
|
{{/* This file is combined with the root.tmpl to display the blog index. */}}
{{define "title"}}文章索引 - Go 语言博客{{end}}
{{define "content"}}
<h1 class="title">文章索引</h1>
{{range .Data}}
<p class="blogtitle">
<a href="{{.Path}}">{{.Title}}</a><br>
<span class="date">{{.Time.Format "2006/01/02"}}</span><br>
{{with .Tags}}<span class="tags">{{range .}}{{.}} {{end}}</span>{{end}}
</p>
{{end}}
{{end}}
|
{
"pile_set_name": "Github"
}
|
_LavenderHouse1Text_1d8d1::
text "That's odd, MR.FUJI"
line "isn't here."
cont "Where'd he go?"
done
_LavenderHouse1Text_1d8d6::
text "MR.FUJI had been"
line "praying alone for"
cont "CUBONE's mother."
done
_LavenderHouse1Text_1d8f4::
text "This is really"
line "MR.FUJI's house."
para "He's really kind!"
para "He looks after"
line "abandoned and"
cont "orphaned #MON!"
done
_LavenderHouse1Text_1d8f9::
text "It's so warm!"
line "#MON are so"
cont "nice to hug!"
done
_LavenderHouse1Text3::
text "PSYDUCK: Gwappa!@"
text_end
_LavenderHouse1Text4::
text "NIDORINO: Gaoo!@"
text_end
_LavenderHouse1Text_1d94c::
text "MR.FUJI: <PLAYER>."
para "Your #DEX quest"
line "may fail without"
cont "love for your"
cont "#MON."
para "I think this may"
line "help your quest."
prompt
_ReceivedFluteText::
text "<PLAYER> received"
line "a @"
text_ram wcf4b
text "!@"
text_end
_FluteExplanationText::
text_start
para "Upon hearing #"
line "FLUTE, sleeping"
cont "#MON will"
cont "spring awake."
para "It works on all"
line "sleeping #MON."
done
_FluteNoRoomText::
text "You must make"
line "room for this!"
done
_MrFujiAfterFluteText::
text "MR.FUJI: Has my"
line "FLUTE helped you?"
done
_LavenderHouse1Text6::
text "#MON Monthly"
line "Grand Prize"
cont "Drawing!"
para "The application"
line "form is..."
para "Gone! It's been"
line "clipped out!"
done
|
{
"pile_set_name": "Github"
}
|
// Copyright 2012-present Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.
package elastic
// MatchPhraseQuery analyzes the text and creates a phrase query out of
// the analyzed text.
//
// For more details, see
// https://www.elastic.co/guide/en/elasticsearch/reference/6.8/query-dsl-match-query-phrase.html
type MatchPhraseQuery struct {
name string
value interface{}
analyzer string
slop *int
boost *float64
queryName string
}
// NewMatchPhraseQuery creates and initializes a new MatchPhraseQuery.
func NewMatchPhraseQuery(name string, value interface{}) *MatchPhraseQuery {
return &MatchPhraseQuery{name: name, value: value}
}
// Analyzer explicitly sets the analyzer to use. It defaults to use explicit
// mapping config for the field, or, if not set, the default search analyzer.
func (q *MatchPhraseQuery) Analyzer(analyzer string) *MatchPhraseQuery {
q.analyzer = analyzer
return q
}
// Slop sets the phrase slop if evaluated to a phrase query type.
func (q *MatchPhraseQuery) Slop(slop int) *MatchPhraseQuery {
q.slop = &slop
return q
}
// Boost sets the boost to apply to this query.
func (q *MatchPhraseQuery) Boost(boost float64) *MatchPhraseQuery {
q.boost = &boost
return q
}
// QueryName sets the query name for the filter that can be used when
// searching for matched filters per hit.
func (q *MatchPhraseQuery) QueryName(queryName string) *MatchPhraseQuery {
q.queryName = queryName
return q
}
// Source returns JSON for the function score query.
func (q *MatchPhraseQuery) Source() (interface{}, error) {
// {"match_phrase":{"name":{"query":"value","analyzer":"my_analyzer"}}}
source := make(map[string]interface{})
match := make(map[string]interface{})
source["match_phrase"] = match
query := make(map[string]interface{})
match[q.name] = query
query["query"] = q.value
if q.analyzer != "" {
query["analyzer"] = q.analyzer
}
if q.slop != nil {
query["slop"] = *q.slop
}
if q.boost != nil {
query["boost"] = *q.boost
}
if q.queryName != "" {
query["_name"] = q.queryName
}
return source, nil
}
|
{
"pile_set_name": "Github"
}
|
// Set your language/locale codes here.
//
// Locale can be blank, in which case it will be used as the default for the
// language.
//
// if you don't know your language/local codes, fine them here:
// https://www.science.co.il/language/Locale-codes.php
var language = 'ru';
var locale = 'ru';
// Do your translation here!
var translation = {
"(empty note)": "(Пустая заметка)",
"(This process can take a while because we need to re-encrypt your keychain)": "(Этот процесс может занять некоторое время, потому что мы должны перешифровать вашу цепочку ключей)",
", however you have {{length}} changes waiting to be synced that will be lost if you do this": ", однако у вас есть изменения ({{length}}), ожидающие синхронизации, которые будут утеряны, если вы сделаете это",
"[Making links](https://turtlapp.com) is easy!": "[Cсылки](https://turtlapp.com) это просто!",
"{{email}} has a confirmed account and this invite will be encrypted using their public key.": "{{email}} связан с аккаунтом и подтверждён, это приглашение будет зашифровано используя его публичный ключ.",
"{{email}} has a Turtl account, but it is not confirmed. You may want protect the invite with a passphrase to keep it private.": "{{email}} связан с аккаунтом Turtl, но не подтверждён. Возможно вы захотите защитить приглашение с помощью парольной фразы, чтобы сохранить его приватность.",
"{{email}} isn't registered with Turtl. It's recommended to protect the invite with a passphrase to keep it private.": "{{email}} не зарегистрирован в Turtl. Рекомендуется защитить приглашение парольной фразой, чтобы оно было приватным.",
"{{n}} days ago": "{{n}} дней назад",
"{{n}} hours ago": "{{n}} часов назад",
"{{n}} minutes ago": "{{n}} минут назад",
"{{n}} seconds ago": "{{n}} секунд назад",
"<strong>Error:</strong> {{errmsg}} ({{errcode}})": "<strong>Ошибка:</strong> {{errmsg}} ({{errcode}})",
"A note on how Turtl works": "Заметка о том, как работает Turtl",
"Accept": "Принять",
"Add": "Добавить",
"Add a new bookmark": "Добавить новую закладку",
"Add a new file": "Добавить новый файл",
"Add a new image": "Добавить новое изображение",
"Add a new note": "Добавить новую заметку",
"Add a new password": "Добавить новый пароль",
"Add a new text note": "Добавить новую текстовую заметку",
"Advanced settings": "Расширенные настройки",
"All notes": "Все заметки",
"Are you sure you want to delete your account and all your data <em>forever</em>?": "Вы уверены, что хотите удалить свой аккаунт и все свои данные <em>навсегда</em>?",
"Attach a file": "Прикрепить файл",
"Back to my notes": "Назад к моим заметкам",
"Blocked by frozen syncs.": "Заблокировано замороженными синхронизациями.",
"Board title": "Название доски",
"Boards": "Доски",
"bookmark": "закладка",
"Bookmark": "Закладка",
"Cancel": "Отмена",
"Change login": "Изменить логин",
"Change password": "Изменить пароль",
"Changing your password requires being connected.": "Изменение пароля требует подключения.",
"Clear all current filters (show all notes in the board)": "Снять текущие фильтры (показать все заметки на доске)",
"Clear local data": "Стереть локальные данные",
"Clear local data and log out": "Стереть локальные данные и выйти",
"Client version: <em>{{version}}</em>": "Версия клиента: <em>{{version}}</em>",
"comma, separate, tags": "теги, через, запятую",
"Completely wipe current profile before importing": "Полностью стереть текущий профиль перед импортом",
"Confirm passphrase": "Подтвердите парольную фразу",
"Confirm your current login": "Подтвердите ваш текущий логин",
"Confirmation email resent": "Запрос подтверждения отправлен на email",
"Connected": "Подключен",
"Connected to the Turtl service! Disengaging offline mode. Syncing your profile.": "Подключен к сервису Turtl! Выход из автономного режима. Синхронизация вашего профиля.",
"Couldn't connect to the server": "Не удалось подключиться к серверу",
"Create": "Создать",
"Create a new account to migrate your data into.": "Создайте новый аккаунт для переноса ваших данных.",
"Create a space": "Создать пространство",
"Create an account": "Создать аккаунт",
"Create board in {{space}}": "Создать доску в {{space}}",
"Create date": "Дата создания",
"Current email": "Текущий email",
"Current passphrase": "Текущая парольная фраза",
"dashes</li><li>make</li><li>bullets": "дефисы</li><li>формируют</li><li>маркеры",
"dashes<br>- make<br>- bullets": "дефисы<br>- формируют<br>- маркеры",
"Debug log": "Журнал отладки",
"Decrypted {{percent}} of items": "Расшифровано {{percent}} элементов",
"Delete": "Удалить",
"Delete account": "Удалить аккаунт",
"Delete current note": "Удалить текущую заметку",
"Delete my account": "Удалите мой аккаунт",
"Delete sync item": "Удалить синхронизацию",
"Delete this board": "Удалить эту доску",
"Delete this space »": "Удалить это пространство »",
"Disconnected from the Turtl service. Engaging offline mode. Your changes will be saved and synced once back online!": "Отключен от сервиса Turtl. Переход в автономный режим. Ваши изменения будут сохраняться и синхронизируются, как только вернёмся в онлайн!",
"Downloading files...": "Загрузка файлов...",
"Edit": "Редактировать",
"Edit board": "Редактировать доску",
"Edit current note": "Изменить текущую заметку",
"Edit note": "Редактировать заметку",
"Editing {{title}}": "Редактирование {{title}}",
"Editing in markdown": "Редактирование с markdown",
"Email": "Email",
"Email address": "Email адрес",
"Enter a new email/password": "Введите новый email/пароль",
"Error": "Error",
"Error loading profile": "Ошибка при загрузке профиля",
"excellent": "превосходно",
"Export": "Экспорт",
"Feedback": "Обратная связь",
"file": "файл",
"File": "Файл",
"File saved to Download/{{filename}}": "Файл сохранен в Загрузки/{{filename}}",
"Files downloaded, decrypting profile...": "Файлы загружены, расшифровка профиля...",
"Find a note by hitting <kbd>/</kbd> and typing your search followed by <kbd>Enter</kbd>. The note search box supports <a href=\"https://sqlite.org/fts3.html#full_text_index_queries\" target=\"_blank\">Sqlite's FTS3 syntax</a>.": "Найти заметку, нажав <kbd>/</kbd>, введя текст и подтвердив нажатием <kbd>Enter</kbd>. Поле поиска заметки поддерживает синтаксис <a href=\"https://sqlite.org/fts3.html#full_text_index_queries\" target=\"_blank\">Sqlite FTS3.</a>.",
"Formatting help": "Как форматировать",
"From {{user}}": "От {{user}}",
"Frozen - This item is blocking syncing. Fix by unfreezing or deleting.": "Заморожено - Этот элемент блокирует синхронизацию. Исправьте разморозив или удалив.",
"Give us feedback": "Оставьте отзыв",
"Give your feedback": "Оставьте свой отзыв",
"good": "хорошо",
"Grabbed {{num_keychain}} keychain entries, {{num_boards}} boards, {{num_notes}} notes, {{num_files}} files from old server": "Получено {{num_keychain}} цепочки ключей, {{num_boards}} доски, {{num_notes}} заметки, {{num_files}} файлы со старого сервера",
"great": "великолепно",
"Have an idea? A problem?": "Есть предложение? Или проблема?",
"Here's an image: ": "Вот изображение: ",
"Here's an image:<br>": "Вот изображение:<br>",
"I will remember my login!": "Я запомню свой логин!",
"image": "изображение",
"Image": "Изображение",
"Image URL": "URL изображения",
"Import & export": "Импорт & экспорт",
"Import everything, overwriting current items": "Импортировать всё, перезаписав текущие элементы",
"Imported {{count}} items": "Импортировано {{count}} элементов",
"Indexing notes": "Индексирование заметок",
"Initializing Turtl": "Запуск Turtl",
"Invite": "Приглашение",
"Invite passphrase": "Парольная фраза приглашения",
"Invite title (shared with invitee)": "Заголовок приглашения (доступно приглашенному)",
"Invite to "{{board_title}}"": "Пригласить в "{{board_title}}"",
"Invitee's email address": "Email приглашенного",
"It looks like you had some problems during migration. Don't worry, your data is still safe on the old Turtl server and you can try again at any time. Please send this log to the turtl team at {{email}}": "Похоже, у вас были некоторые проблемы во время миграции. Не беспокойтесь, ваши данные все еще в безопасности на старом сервере Turtl, и вы можете повторить попытку в любое время. Пожалуйста, отправьте этот журнал команде Turtl по адресу {{email}}",
"Join": "Присоединиться",
"Just making sure...do you really want to delete your account?": "Хотим убедиться ...вы действительно хотите удалить свой аккаунт?",
"Keyboard shortcuts": "Горячие клавиши",
"Last edited": "Дата изменения",
"Leave this space": "Покинуть это пространство",
"Leave this space »": "Покинуть это пространство »",
"Leaving a space requires a connection to the Turtl server": "Для того чтобы покинуть пространство требуется подключение к серверу Turtl",
"Load everything (may be slow)": "Загрузить всё (может быть долго)",
"Load last {{lines}} lines": "Загрузить последние {{lines}} строки",
"Loading notes...": "Загрузка заметок",
"Loading profile": "Загрузка профиля",
"Log out": "Выйти",
"Logged in as <em>{{username}}</em> <small>(on {{server}})</small>": "Вы вошли как <em>{{username}}</em> <small>(в {{server}})</small>",
"Login": "Авторизоваться",
"Login failed": "Ошибка авторизации",
"Login to an existing account": "Войти в существующий аккаунт",
"Logout": "Выйти",
"Making links</a> is easy!": "Ссылки</a> это просто!",
"Malformed note": "Повреждённая заметка",
"Members": "Участники",
"Migrate": "Перенести",
"Migrate your account": "Перенести свой аккаунт",
"Migration error...": "Ошибка переноса...",
"Migration report": "Отчёт о переносе",
"Migration started. This can take a few minutes! Please be patient.": "Перенос начался. Это может занять несколько минут! Пожалуйста, будьте терпеливы.",
"Move": "Переместить",
"Move board to another space": "Переместить доску в другое пространство",
"Move note to another space": "Переместить заметку в другое пространство",
"Move space": "Переместить пространство",
"New bookmark": "Новая закладка",
"New email": "Новый email",
"New email address": "Новый email-адрес",
"New invite": "Новое приглашение",
"New passphrase": "Новая парольная фраза",
"Next": "След.",
"No board selected": "Доска не выбрана",
"No notes found.": "Заметки не найдены",
"No notes here!": "Здесь нет заметок!",
"None": "Нет",
"Note moved successfully.": "Заметка успешно перемещена.",
"Note preview": "Просмотр заметки",
"Note text": "Текст заметки",
"Note that when you move a board to another space, all of its notes will be moved with it.": "Обратите внимание, когда вы перемещаете доску в другое пространство, все ее заметки будут премещены вместе с ней.",
"Offline mode": "Автономный режим",
"ok": "ok",
"Old profile loaded, converting to new format...": "Старый профиль загружен, конвертируется в новый формат...",
"Old Turtl server": "Старый сервер Turtl",
"One hash makes a large title": "Один хэш для большого заголовка",
"Only import items missing from current profile": "Импортировать только те элементы, которые отсутствуют в текущем профиле",
"Open a space easily by hitting <kbd>s</kbd>, typing the name of the space you want, and hitting <kbd>Enter</kbd>. You will then be taken to the board selector. Hit <kbd>Enter</kbd> again for \"All notes\" or type the name of the board you want to open and hit <kbd>Enter</kbd> to open it.": "Перейдите в пространство, нажав <kbd>s</kbd>, введя имя пространства, и нажав <kbd>Enter</kbd>. Вы окажетесь у выбора доски. Снова нажмите <kbd>Enter</kbd> для перехода во \"Все заметки\" или введите название доски, которую хотите открыть и нажмите <kbd>Enter</kbd>, чтобы перейти к ней.",
"Open boards menu": "Открыть меню досок",
"Open current note": "Открыть текущую заметку",
"Open spaces menu": "Открыть меню пространств",
"Open the board selector by hitting <kbd>b</kbd>. You can hit <kbd>Enter</kbd> with the search box blank to open \"All notes\" or you can type the name of the board you want and hit <kbd>Enter</kbd> to open it.": "Откройте вобор доски, нажав <kbd>b</kbd>. Вы можете нажать <kbd>Enter</kbd> с пустым полем, чтобы перейти во \"Все заметки\" или ввести имя требуемой доски и нажать <kbd>Enter</kbd>, чтобы перейти к ней.",
"OR": "ИЛИ",
"Passphrase": "Парольная фраза",
"Passphrase (optional)": "Парольная фраза (не обязательно)",
"Passphrase (optional, but recommended)": "Парольная фраза (не обязательно, но желательно)",
"Passphrase strength: ": "Надёжность парольной фразы: ",
"password": "пароль",
"Password": "Пароль",
"Pending invites": "Ожидающие приглашения",
"Please enter some feedback": "Пожалуйста, введите отзыв",
"Please give your invite a title.": "Пожалуйста, озаглавьте ваше приглашение.",
"Please select a role for this user.": "Пожалуйста, укажите роль этого пользователя.",
"Prev": "Пред.",
"Quote text with a caret": "Цитируйте текст кареткой",
"Read more »": "Узнать больше »",
"Read more about <a href=\"https://guides.github.com/features/mastering-markdown/\" target=\"_blank\">markdown</a>.": "Узнать больше о <a href=\"https://guides.github.com/features/mastering-markdown/\" target=\"_blank\">markdown</a>.",
"Ready to sync": "Готов к синхронизации",
"Really delete this board and all of its notes?": "Действительно удалить эту доску и все её заметки?",
"Really delete this invite?": "Действительно удалить это приглашение?",
"Really delete this note?": "Действительно удалить эту заметку?",
"Really delete this space and all of its data (boards and notes)?": "Действительно удалить это пространство и все его данные (доски и заметки)?",
"Really delete this sync item? Doing this will undo a change you've made locally (try unfreezing first).": "Действительно удалить этот элемент синхронизации? Это приведет к отмене изменений, которые вы сделали локально (попробуйте сначала разморозить).",
"Really delete this user from this space?": "Действительно удалить этого пользователя из этого пространства?",
"Really hand ownership of this space to another member? (You will be demoted to admin)": "Действительно передать право владения этим пространством другому участнику? (Вы будете понижены до администратора)",
"Really leave this space?": "Действительно покинуть это простарнство?",
"Remove attachment": "Удалить вложение",
"Resend confirmation": "Послать подтверждение повторно",
"Reset search": "Сбросить поиск",
"Retry": "Попробовать снова",
"Save": "Сохранить",
"Search for boards": "Поиск досок",
"Search for spaces": "Поиск пространств",
"Search notes": "Поиск заметок",
"Search notes ({{num}})": "Поиск заметок ({{num}})",
"Select a board": "Выберите доску",
"Select the color for this space": "Выберите цвет этого пространства",
"Select the space to move to:": "Выберите пространство куда перемещаете:",
"Send": "Отправить",
"Sending an invite requires a connection to the Turtl server.": "Для отправки приглашения требуется подключение к серверу Turtl.",
"Sending feedback requires a connection to the Turtl server.": "Для отправки отзыва требуется подключение к серверу Turtl.",
"Set as owner": "Пометить как владельца",
"Set this as your default space": "Установите это вашим пространством по умолчанию",
"Settings": "Настройки",
"Share this space": "Поделиться этим пространством",
"Share this space »": "Поделиться этим пространством »",
"Sharing": "Доступ",
"Show all tags": "Показать все теги",
"Show this help": "Показывать такие подсказки",
"Space title": "Имя пространства",
"Stay logged in": "Оставаться в системе",
"Staying logged in may compromise the security of your account.": "Оставайясь в системе вы можете поставить под угрозу безопасность вашего аккаунта.",
"Successfully imported {{count}} items!": "Успешно импортировано {{count}} элементов!",
"Sync info": "Информация о синхронизации",
"Tag note": "Теги заметки",
"Tap <em>+</em> to start": "Нажмите <em>+</em> чтобы начать",
"text note": "текстовая заметка",
"Text note": "Текстовая заметка",
"Text search": "Поиск текста",
"Thanks!": "Спасибо!",
"That board doesn't seem to exist": "Такой доски, похоже, не существует",
"That passphrase is making me cringe.": "Эта парольная фраза making me cringe",
"The email given is invalid.": "Указанный email недействителен.",
"The specified role does not exist.": "Указанная роль не существует.",
"There was a problem accepting the invite. Most likely, the passphrase given was incorrect.": "Не удалось принять приглашение. Скорее всего, парольная фраза была неверной.",
"There was a problem changing your login. We are undoing the changes": "При смене логина произошла ошибка. Мы отменяем изменения",
"There was a problem clearing your profile": "При очистке вашего профиля произошла ошибка",
"There was a problem deleting that invite": "Не удалось удалить это приглашение",
"There was a problem deleting that sync item": "При удалении этого элемента синхронизации произошла ошибка",
"There was a problem deleting the user": "При удалении пользователя возникла проблема",
"There was a problem deleting your account. Please try again.": "При удалении вашего аккаунта возникла проблема. Пожалуйста, попробуйте еще раз.",
"There was a problem deleting your board: {{message}}": "При удалении вашей доски произошла ошибка: {{message}}",
"There was a problem deleting your note: {{err}}": "При удалении заметки возникла проблема: {{err}}",
"There was a problem deleting your space: {{message}}": "При удалении вашего пространства произошла ошибка: {{message}}",
"There was a problem editing the user": "При редактировании пользователя возникла проблема",
"There was a problem leaving the space": "При покидании пространства возникла проблема",
"There was a problem loading the debug log": "При загрузке журнала отладки возникла проблема",
"There was a problem loading:": "Возникла проблема с загрузкой:",
"There was a problem migrating that account": "При переносе этого аккаунта возникла проблема",
"There was a problem moving that board.": "При перемещении этой доски возникла проблема.",
"There was a problem moving that note.": "При перемещении этой заметки возникла проблема.",
"There was a problem opening that file": "При открытии этого файла возникла проблема",
"There was a problem resending your confirmation email": "Не удалось отправить письмо с подтверждением",
"There was a problem saving that account": "При сохранении этого аккаунта возникла проблема",
"There was a problem saving the file {{filename}}.": "Возникла проблема при сохранении файла {{filename}}.",
"There was a problem sending that feedback": "Возникла проблема с отправкой этого отзыва",
"There was a problem sending that invite": "Возникла проблема с отправкой этого приглашения",
"There was a problem setting the API endpoint. Try restarting the app.": "При настройке конечной точки API возникла проблема. Попробуйте перезапустить приложение.",
"There was a problem setting the new owner": "Возникла проблема с установкой нового владельца",
"There was a problem unfreezing that sync item": "Не удалось разморозить этот элемент синхронизации",
"There was a problem updating that board": "Возникла проблема при обновлении этой доски",
"There was a problem updating that note": "При обновлении этой заметки возникла проблема",
"There was a problem updating that space": "При обновлением этого пространства возникла проблема",
"There was a problem with the initial load of your profile. Please try again.": "Возникла проблема с начальной загрузкой вашего профиля. Пожалуйста, попробуйте еще раз.",
"There was an error syncing a local change and syncing is paused. Click to open your sync settings and fix »": "Произошла ошибка синхронизации локального изменения, и синхронизация приостановлена. Нажмите, чтобы открыть настройки синхронизации и исправить »",
"This invite is passphrase-protected. You must enter the correct passphrase to unlock it.": "Это приглашение защищено парольной фразой. Вы должны ввести правильную парольную фразу, чтобы разблокировать его.",
"This is your last space, and cannot be deleted.": "Это ваше последнее пространство, его нельзя удалить.",
"This note has unsaved changes. Really leave?": "Эта заметка имеет несохраненные изменения. Действительно закрыть?",
"This note was saved incorrectly and cannot be displayed.\n\n```\n{{-note_data}}\n```\n": "Эта заметка была сохранена неправильно и не может быть отображена.\n\n```\n{{-note_data}}\n```\n",
"This passphrase is used to encrypt the invite. You can communicate it to the invitee via a secure channel (in-person, encrypted email, encrypted chat, etc).": "Эта парольная фраза используется для шифрования приглашения. Вы можете сообщить её приглашенному по защищенному каналу (лично, зашифрованную электронную почту, зашифрованный чат и т. д.).",
"This process can take a while.": "Этот процесс может занять некоторое время.",
"This space is shared with you": "Это пространство разделено с вами",
"This URL is already bookmarked in {{ids_length}} notes": "Этот URL уже добавлен в {{ids_length}} заметках",
"This URL is already bookmarked in another note": "Этот URL уже добавлен в другую заметку",
"This will erase all your local data and log you out. Your profile will be downloaded again next time you log in{{msg}}. Continue?": "Это сотрет все ваши локальные данные и выведет вас из системы. Ваш профиль будет загружен снова при следующем входе{{msg}}. Продолжить?",
"Tips on keyboard navigation": "Советы по навигации с клавиатуры",
"Title": "Заголовок",
"todo lists": "списки дел",
"too short": "слишком короткая",
"Trouble logging in?": "Проблемы с авторизацией?",
"Turtl has no \"Lost password\" feature. If you lose your password, your profile is gone forever!": "У Turtl нет функции \"Напомнить пароль\". Если вы потеряете свой пароль, ваш профиль исчезнет навсегда!",
"Turtl notes use Markdown, a format that's easy to read and write and doesn't require a clunky editor.": "В заметках Turtl используется Markdown — формат, который легко читать и использовать, не требующий громоздкого редактора.",
"Turtl now also supports TeX math. Begin and end your equation(s) with <code>$$</code>:": "Turtl теперь также поддерживает математику TeX. Начните и завершите свое уравнение(я) с помощью <code>$$</code>:",
"Turtl server": "Сервер Turtl",
"Two hashes for a smaller header": "Два хэша для заголовка поменьше",
"Unfreeze sync item": "Разморозить элемент синхронизации",
"Unlock": "Разблокировать",
"Updating your login. Please be patient (and DO NOT close the app)!": "Обновление вашего логина. Пожалуйста, будьте терпеливы (и НЕ ЗАКРЫВАЙТЕ приложение)!",
"URL": "URL",
"Use backticks for `inline_code()`": "Используйте грависы для `vstavka_koda()`",
"Use backticks for <code>inline_code()</code>": "Используйте грависы для <code>vstavka_koda()</code>",
"Username": "Имя пользователя",
"We appreciate you taking the time to help make Turtl better.": "Мы ценим, что вы нашли время, чтобы помочь сделать Turtl лучше.",
"We don't store your password anywhere, so <em class=\"error\">you need to remember your password</em> or keep it in a safe place (like a password manager).": "Мы нигде не храним ваш пароль, поэтому <em class=\"error\">вам нужно запомнить свой пароль</em> или хранить его в надежном месте (например, в диспетчере паролей).",
"weak": "слабая",
"Welcome!": "Добро пожаловать!",
"works too": "тоже есть",
"Yes, delete my account": "Да, удалить мой аккаунт",
"You": "Вы",
"You are currently in offline mode.": "Сейчас вы в автономном режиме.",
"You can also make text __bold__, *italic* or ~~strikethrough~~.": "Вы также можете сделать текст __жирным__, *курсивным* или ~~зачёркнутым~~.",
"You can also make text <strong>bold</strong>, <em>italic</em> or <strike>strikethrough</strike>.": "Вы также можете сделать текст <strong>жирным</strong>, <em>курсивным</em> или <strike>зачёркнутым</strike>.",
"you can make</li><li>numbered bullets</li><li>as well": "также можно</li><li>использовать</li><li>цифровые маркеры",
"you can make<br>1. numbered bullets<br>1. as well": "также можно<br>2. использовать<br>3. цифровые маркеры",
"You do not have permissions to move boards/notes to that space.": "У вас нет прав для перемещения досок/заметок в это пространство.",
"You do not have permissions to move notes to that space.": "У вас нет прав для перемещения заметок в это пространство.",
"You do not have the needed permission to do that on this space: {{perm}}": "У вас нет необходимого разрешения для этого в этом пространстве: {{perm}}",
"You have {{num}} pending sync item(s)": "У вас {{num}} элементов, ожидающих синхронизации",
"You have no pending invitations": "У вас нет приглашений",
"You have one or more frozen sync items. Syncing will be stuck until you fix them. Try unfreezing first, and if that doesn't work, you can delete the frozen sync item(s).": "У вас есть один или несколько замороженных элементов синхронизации. Синхронизация будет зависать, пока вы не исправите их. Сначала попробуйте разморозить, и если это не сработает, вы можете удалить замороженные элементы синхронизации.",
"You must be connected to the Turtl service to accept invites.": "Вы должны быть подключены к серверу Turtl, чтобы принимать приглашения.",
"You must be connected to the Turtl service to delete invites.": "Вы должны быть подключены к серверу Turtl, чтобы удалять приглашения.",
"You must be logged in to perform this action.": "Вы должны войти в систему, чтобы выполнить это действие.",
"You must confirm your account before accepting invites.": "Вы должны подтвердить свой аккаунт, прежде чем принимать приглашения.",
"You must confirm your account before accepting invites. If you no longer have your confirmation email, you can resend it from the Settings menu.": "Вы должны подтвердить свой аккаунт, прежде чем принимать приглашения. Если у вас не сохранилось письмо с подтверждением, вы можете повторно отправить его из меню «Настройки».",
"You must confirm your email to share spaces.": "Вы должны подтвердить свой адрес электронной почты, чтобы делиться пространствами.",
"You must log in": "Вы должны войти в систему",
"Your account has been deleted.": "Ваш аккаунт был удален.",
"Your account needs to be upgraded! Please enter your Turtl login info.": "Ваш аккаунт должен быть обновлён! Пожалуйста, введите ваши данные авторизации Turtl.",
"Your account password acts as the \"key\" that locks and unlocks your data.": "Пароль вашего аккаунта действует как \"ключ\", который запирает и отпирает ваши данные.",
"Your invites": "Ваши приглашения",
"Your login was changed successfully!": "Ваш логин был успешно изменен!",
"Your login was changed successfully! Logging you out...": "Ваш логин был успешно изменен! Выход из системы...",
"Your passphrase does not match the confirmation.": "Ваша парольная фраза не совпадает с проверочной",
"Your settings": "Ваши настройки",
"Your spaces": "Ваши пространства",
};
|
{
"pile_set_name": "Github"
}
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr>
//
// 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/.
#ifndef EIGEN_ARRAY_H
#define EIGEN_ARRAY_H
namespace Eigen {
namespace internal {
template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
struct traits<Array<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> > : traits<Matrix<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> >
{
typedef ArrayXpr XprKind;
typedef ArrayBase<Array<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> > XprBase;
};
}
/** \class Array
* \ingroup Core_Module
*
* \brief General-purpose arrays with easy API for coefficient-wise operations
*
* The %Array class is very similar to the Matrix class. It provides
* general-purpose one- and two-dimensional arrays. The difference between the
* %Array and the %Matrix class is primarily in the API: the API for the
* %Array class provides easy access to coefficient-wise operations, while the
* API for the %Matrix class provides easy access to linear-algebra
* operations.
*
* See documentation of class Matrix for detailed information on the template parameters
* storage layout.
*
* This class can be extended with the help of the plugin mechanism described on the page
* \ref TopicCustomizing_Plugins by defining the preprocessor symbol \c EIGEN_ARRAY_PLUGIN.
*
* \sa \blank \ref TutorialArrayClass, \ref TopicClassHierarchy
*/
template<typename _Scalar, int _Rows, int _Cols, int _Options, int _MaxRows, int _MaxCols>
class Array
: public PlainObjectBase<Array<_Scalar, _Rows, _Cols, _Options, _MaxRows, _MaxCols> >
{
public:
typedef PlainObjectBase<Array> Base;
EIGEN_DENSE_PUBLIC_INTERFACE(Array)
enum { Options = _Options };
typedef typename Base::PlainObject PlainObject;
protected:
template <typename Derived, typename OtherDerived, bool IsVector>
friend struct internal::conservative_resize_like_impl;
using Base::m_storage;
public:
using Base::base;
using Base::coeff;
using Base::coeffRef;
/**
* The usage of
* using Base::operator=;
* fails on MSVC. Since the code below is working with GCC and MSVC, we skipped
* the usage of 'using'. This should be done only for operator=.
*/
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Array& operator=(const EigenBase<OtherDerived> &other)
{
return Base::operator=(other);
}
/** Set all the entries to \a value.
* \sa DenseBase::setConstant(), DenseBase::fill()
*/
/* This overload is needed because the usage of
* using Base::operator=;
* fails on MSVC. Since the code below is working with GCC and MSVC, we skipped
* the usage of 'using'. This should be done only for operator=.
*/
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Array& operator=(const Scalar &value)
{
Base::setConstant(value);
return *this;
}
/** Copies the value of the expression \a other into \c *this with automatic resizing.
*
* *this might be resized to match the dimensions of \a other. If *this was a null matrix (not already initialized),
* it will be initialized.
*
* Note that copying a row-vector into a vector (and conversely) is allowed.
* The resizing, if any, is then done in the appropriate way so that row-vectors
* remain row-vectors and vectors remain vectors.
*/
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Array& operator=(const DenseBase<OtherDerived>& other)
{
return Base::_set(other);
}
/** This is a special case of the templated operator=. Its purpose is to
* prevent a default operator= from hiding the templated operator=.
*/
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Array& operator=(const Array& other)
{
return Base::_set(other);
}
/** Default constructor.
*
* For fixed-size matrices, does nothing.
*
* For dynamic-size matrices, creates an empty matrix of size 0. Does not allocate any array. Such a matrix
* is called a null matrix. This constructor is the unique way to create null matrices: resizing
* a matrix to 0 is not supported.
*
* \sa resize(Index,Index)
*/
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Array() : Base()
{
Base::_check_template_params();
EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED
}
#ifndef EIGEN_PARSED_BY_DOXYGEN
// FIXME is it still needed ??
/** \internal */
EIGEN_DEVICE_FUNC
Array(internal::constructor_without_unaligned_array_assert)
: Base(internal::constructor_without_unaligned_array_assert())
{
Base::_check_template_params();
EIGEN_INITIALIZE_COEFFS_IF_THAT_OPTION_IS_ENABLED
}
#endif
#if EIGEN_HAS_RVALUE_REFERENCES
EIGEN_DEVICE_FUNC
Array(Array&& other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_constructible<Scalar>::value)
: Base(std::move(other))
{
Base::_check_template_params();
}
EIGEN_DEVICE_FUNC
Array& operator=(Array&& other) EIGEN_NOEXCEPT_IF(std::is_nothrow_move_assignable<Scalar>::value)
{
other.swap(*this);
return *this;
}
#endif
#if EIGEN_HAS_CXX11
/** \copydoc PlainObjectBase(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args)
*
* Example: \include Array_variadic_ctor_cxx11.cpp
* Output: \verbinclude Array_variadic_ctor_cxx11.out
*
* \sa Array(const std::initializer_list<std::initializer_list<Scalar>>&)
* \sa Array(const Scalar&), Array(const Scalar&,const Scalar&)
*/
template <typename... ArgTypes>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args)
: Base(a0, a1, a2, a3, args...) {}
/** \brief Constructs an array and initializes it from the coefficients given as initializer-lists grouped by row. \cpp11
*
* In the general case, the constructor takes a list of rows, each row being represented as a list of coefficients:
*
* Example: \include Array_initializer_list_23_cxx11.cpp
* Output: \verbinclude Array_initializer_list_23_cxx11.out
*
* Each of the inner initializer lists must contain the exact same number of elements, otherwise an assertion is triggered.
*
* In the case of a compile-time column 1D array, implicit transposition from a single row is allowed.
* Therefore <code> Array<int,Dynamic,1>{{1,2,3,4,5}}</code> is legal and the more verbose syntax
* <code>Array<int,Dynamic,1>{{1},{2},{3},{4},{5}}</code> can be avoided:
*
* Example: \include Array_initializer_list_vector_cxx11.cpp
* Output: \verbinclude Array_initializer_list_vector_cxx11.out
*
* In the case of fixed-sized arrays, the initializer list sizes must exactly match the array sizes,
* and implicit transposition is allowed for compile-time 1D arrays only.
*
* \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args)
*/
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Array(const std::initializer_list<std::initializer_list<Scalar>>& list) : Base(list) {}
#endif // end EIGEN_HAS_CXX11
#ifndef EIGEN_PARSED_BY_DOXYGEN
template<typename T>
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE explicit Array(const T& x)
{
Base::_check_template_params();
Base::template _init1<T>(x);
}
template<typename T0, typename T1>
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Array(const T0& val0, const T1& val1)
{
Base::_check_template_params();
this->template _init2<T0,T1>(val0, val1);
}
#else
/** \brief Constructs a fixed-sized array initialized with coefficients starting at \a data */
EIGEN_DEVICE_FUNC explicit Array(const Scalar *data);
/** Constructs a vector or row-vector with given dimension. \only_for_vectors
*
* Note that this is only useful for dynamic-size vectors. For fixed-size vectors,
* it is redundant to pass the dimension here, so it makes more sense to use the default
* constructor Array() instead.
*/
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE explicit Array(Index dim);
/** constructs an initialized 1x1 Array with the given coefficient
* \sa const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args */
Array(const Scalar& value);
/** constructs an uninitialized array with \a rows rows and \a cols columns.
*
* This is useful for dynamic-size arrays. For fixed-size arrays,
* it is redundant to pass these parameters, so one should use the default constructor
* Array() instead. */
Array(Index rows, Index cols);
/** constructs an initialized 2D vector with given coefficients
* \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args) */
Array(const Scalar& val0, const Scalar& val1);
#endif // end EIGEN_PARSED_BY_DOXYGEN
/** constructs an initialized 3D vector with given coefficients
* \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args)
*/
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Array(const Scalar& val0, const Scalar& val1, const Scalar& val2)
{
Base::_check_template_params();
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Array, 3)
m_storage.data()[0] = val0;
m_storage.data()[1] = val1;
m_storage.data()[2] = val2;
}
/** constructs an initialized 4D vector with given coefficients
* \sa Array(const Scalar& a0, const Scalar& a1, const Scalar& a2, const Scalar& a3, const ArgTypes&... args)
*/
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Array(const Scalar& val0, const Scalar& val1, const Scalar& val2, const Scalar& val3)
{
Base::_check_template_params();
EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Array, 4)
m_storage.data()[0] = val0;
m_storage.data()[1] = val1;
m_storage.data()[2] = val2;
m_storage.data()[3] = val3;
}
/** Copy constructor */
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Array(const Array& other)
: Base(other)
{ }
private:
struct PrivateType {};
public:
/** \sa MatrixBase::operator=(const EigenBase<OtherDerived>&) */
template<typename OtherDerived>
EIGEN_DEVICE_FUNC
EIGEN_STRONG_INLINE Array(const EigenBase<OtherDerived> &other,
typename internal::enable_if<internal::is_convertible<typename OtherDerived::Scalar,Scalar>::value,
PrivateType>::type = PrivateType())
: Base(other.derived())
{ }
EIGEN_DEVICE_FUNC inline Index innerStride() const { return 1; }
EIGEN_DEVICE_FUNC inline Index outerStride() const { return this->innerSize(); }
#ifdef EIGEN_ARRAY_PLUGIN
#include EIGEN_ARRAY_PLUGIN
#endif
private:
template<typename MatrixType, typename OtherDerived, bool SwapPointers>
friend struct internal::matrix_swap_impl;
};
/** \defgroup arraytypedefs Global array typedefs
* \ingroup Core_Module
*
* %Eigen defines several typedef shortcuts for most common 1D and 2D array types.
*
* The general patterns are the following:
*
* \c ArrayRowsColsType where \c Rows and \c Cols can be \c 2,\c 3,\c 4 for fixed size square matrices or \c X for dynamic size,
* and where \c Type can be \c i for integer, \c f for float, \c d for double, \c cf for complex float, \c cd
* for complex double.
*
* For example, \c Array33d is a fixed-size 3x3 array type of doubles, and \c ArrayXXf is a dynamic-size matrix of floats.
*
* There are also \c ArraySizeType which are self-explanatory. For example, \c Array4cf is
* a fixed-size 1D array of 4 complex floats.
*
* With \cpp11, template alias are also defined for common sizes.
* They follow the same pattern as above except that the scalar type suffix is replaced by a
* template parameter, i.e.:
* - `ArrayRowsCols<Type>` where `Rows` and `Cols` can be \c 2,\c 3,\c 4, or \c X for fixed or dynamic size.
* - `ArraySize<Type>` where `Size` can be \c 2,\c 3,\c 4 or \c X for fixed or dynamic size 1D arrays.
*
* \sa class Array
*/
#define EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, Size, SizeSuffix) \
/** \ingroup arraytypedefs */ \
typedef Array<Type, Size, Size> Array##SizeSuffix##SizeSuffix##TypeSuffix; \
/** \ingroup arraytypedefs */ \
typedef Array<Type, Size, 1> Array##SizeSuffix##TypeSuffix;
#define EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, Size) \
/** \ingroup arraytypedefs */ \
typedef Array<Type, Size, Dynamic> Array##Size##X##TypeSuffix; \
/** \ingroup arraytypedefs */ \
typedef Array<Type, Dynamic, Size> Array##X##Size##TypeSuffix;
#define EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(Type, TypeSuffix) \
EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 2, 2) \
EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 3, 3) \
EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, 4, 4) \
EIGEN_MAKE_ARRAY_TYPEDEFS(Type, TypeSuffix, Dynamic, X) \
EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 2) \
EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 3) \
EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Type, TypeSuffix, 4)
EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(int, i)
EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(float, f)
EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(double, d)
EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(std::complex<float>, cf)
EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES(std::complex<double>, cd)
#undef EIGEN_MAKE_ARRAY_TYPEDEFS_ALL_SIZES
#undef EIGEN_MAKE_ARRAY_TYPEDEFS
#undef EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS
#if EIGEN_HAS_CXX11
#define EIGEN_MAKE_ARRAY_TYPEDEFS(Size, SizeSuffix) \
/** \ingroup arraytypedefs */ \
/** \brief \cpp11 */ \
template <typename Type> \
using Array##SizeSuffix##SizeSuffix = Array<Type, Size, Size>; \
/** \ingroup arraytypedefs */ \
/** \brief \cpp11 */ \
template <typename Type> \
using Array##SizeSuffix = Array<Type, Size, 1>;
#define EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(Size) \
/** \ingroup arraytypedefs */ \
/** \brief \cpp11 */ \
template <typename Type> \
using Array##Size##X = Array<Type, Size, Dynamic>; \
/** \ingroup arraytypedefs */ \
/** \brief \cpp11 */ \
template <typename Type> \
using Array##X##Size = Array<Type, Dynamic, Size>;
EIGEN_MAKE_ARRAY_TYPEDEFS(2, 2)
EIGEN_MAKE_ARRAY_TYPEDEFS(3, 3)
EIGEN_MAKE_ARRAY_TYPEDEFS(4, 4)
EIGEN_MAKE_ARRAY_TYPEDEFS(Dynamic, X)
EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(2)
EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(3)
EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS(4)
#undef EIGEN_MAKE_ARRAY_TYPEDEFS
#undef EIGEN_MAKE_ARRAY_FIXED_TYPEDEFS
#endif // EIGEN_HAS_CXX11
#define EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, SizeSuffix) \
using Eigen::Matrix##SizeSuffix##TypeSuffix; \
using Eigen::Vector##SizeSuffix##TypeSuffix; \
using Eigen::RowVector##SizeSuffix##TypeSuffix;
#define EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(TypeSuffix) \
EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 2) \
EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 3) \
EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, 4) \
EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE_AND_SIZE(TypeSuffix, X) \
#define EIGEN_USING_ARRAY_TYPEDEFS \
EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(i) \
EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(f) \
EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(d) \
EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(cf) \
EIGEN_USING_ARRAY_TYPEDEFS_FOR_TYPE(cd)
} // end namespace Eigen
#endif // EIGEN_ARRAY_H
|
{
"pile_set_name": "Github"
}
|
/*
You are given two 32-bit numbers,N andM, andtwobitpositions, i andj. Write a method to insert Minto Nsuch that Mstarts at bit j and ends at bit i. Youcan assume that the bits j through i have enough space to fit all ofM. That is,ifM= 10011, you can assume that there are at least 5 bits between j and i. You would not, for example,havej-3 andi=2,becauseMcouldnotfully fitbetweenbit3andbit2.
EXAMPLE:
Input:N=16000000000, M=10011, i =2, j =6 Output: N = 10001001100
*/
import Cocoa
/*
@param: n:Int
@param: bitPosition:Int
@return: Int bits cleared at position bitPosition
*/
func clearBit(n:Int, bitPosition:Int) -> Int {
var mask = ~(1 << (bitPosition))
return ((n) & (mask))
}
/*
@param: m:Int value which has to be changed
@param: i:Int Ending position of replacement
@param: j:Int Starting position of replacement
@return: Int result with bits cleared from j to i(including)
*/
func clearBitsBetweenIandJ(var m:Int,var i:Int, j:Int) -> Int{
if(i >= j) {return m } //base case
for var count = i; count <= j; count++ {
m = clearBit(m, count)
}
return m
}
/*
@param: m:Int value which has to be changed
@param: n:Int value which has to be inserted
@param: i:Int Ending position of replacement
@param: j:Int Starting position of replacement
@return: result with the elements cleared and replaced
*/
func setAllBits(n:Int, var m:Int,var i:Int, j:Int) -> Int {
//clear bits for n
var result = clearBitsBetweenIandJ(n,i,j)
return (result | (m << (i))) //Or with n to get the correct value
}
var r = setAllBits(1023, 0b00010011, 2, 6) //1111001111
println(String(r, radix:2))
r = setAllBits(1024, 0b00010011, 2, 6) //10001001100
println(String(r, radix:2))
|
{
"pile_set_name": "Github"
}
|
#!/bin/sh
# SPDX-License-Identifier: BSD-3-Clause
# Copyright Contributors to the OpenColorIO Project.
OCIO_ROOT="@CMAKE_INSTALL_PREFIX@"
OCIO_EXECROOT="@CMAKE_INSTALL_EXEC_PREFIX@"
# For OS X
export DYLD_LIBRARY_PATH="${OCIO_EXECROOT}/lib:${DYLD_LIBRARY_PATH}"
# For Linux
export LD_LIBRARY_PATH="${OCIO_EXECROOT}/lib:${LD_LIBRARY_PATH}"
export PATH="${OCIO_EXECROOT}/bin:${PATH}"
export PYTHONPATH="${OCIO_EXECROOT}/@_Python_VARIANT_PATH@:${PYTHONPATH}"
export NUKE_PATH="${OCIO_EXECROOT}/lib/nuke@Nuke_API_VERSION@:${NUKE_PATH}"
export NUKE_PATH="${OCIO_ROOT}/share/nuke:${NUKE_PATH}";
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.CodeAnalysis.Razor
{
// Provides access to Razor language and workspace services that are avialable in the OOP host.
//
// Since we don't have access to the workspace we only have access to some specific things
// that we can construct directly.
internal class RazorServices
{
public RazorServices()
{
FallbackProjectEngineFactory = new FallbackProjectEngineFactory();
TagHelperResolver = new RemoteTagHelperResolver(FallbackProjectEngineFactory);
}
public IFallbackProjectEngineFactory FallbackProjectEngineFactory { get; }
public RemoteTagHelperResolver TagHelperResolver { get; }
}
}
|
{
"pile_set_name": "Github"
}
|
<?xml version="1.0" encoding="UTF-8"?>
<item>
<title>install</title>
<external>http://api.drupal.org/api/search/7/hook_install</external>
<group>hook</group>
<template><![CDATA[
/**
* Implementation of hook_install();
*/
function ${file_name}_install() {
${set_cursor}
}
]]></template>
<help><![CDATA[<h2>hook_install()</h2>
<p>Install the current version of the database schema, and any other setup tasks.</p>
<p>The hook will be called the first time a module is installed, and the
module's schema version will be set to the module's greatest numbered update
hook. Because of this, anytime a hook_update_N() is added to the module, this
function needs to be updated to reflect the current version of the database
schema.</p>
<p>See the Schema API documentation at http://drupal.org/node/146843 for
details on hook_schema, where a database tables are defined.</p>
<p>Note that functions declared in the module being installed are not yet
available. The implementation of hook_install() will need to explicitly load
the module before any declared functions may be invoked.</p>
<p>Anything added or modified in this function that can be removed during
uninstall should be removed with hook_uninstall().</p>
]]></help>
</item>
|
{
"pile_set_name": "Github"
}
|
from django.db import models
from django.contrib.auth.models import User
from django.contrib.contenttypes.fields import GenericRelation
from ckeditor_uploader.fields import RichTextUploadingField
from read_statistics.models import ReadNumExpandMethod, ReadDetail
class BlogType(models.Model):
type_name = models.CharField(max_length=15)
def __str__(self):
return self.type_name
class Blog(models.Model, ReadNumExpandMethod):
title = models.CharField(max_length=50)
blog_type = models.ForeignKey(BlogType, on_delete=models.DO_NOTHING)
content = RichTextUploadingField()
author = models.ForeignKey(User, on_delete=models.DO_NOTHING)
read_details = GenericRelation(ReadDetail)
created_time = models.DateTimeField(auto_now_add=True)
last_updated_time = models.DateTimeField(auto_now=True)
def __str__(self):
return "<Blog: %s>" % self.title
class Meta:
ordering = ['-created_time']
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html>
<html lang="en" prefix="og: http://ogp.me/ns#">
<head>
<meta charset="UTF-8">
<title>Kanji Practice: 雨, 書, and 友 - Lesson 9 | Genki Study Resources - 2nd Edition</title>
<meta name="title" content="Kanji Practice: 雨, 書, and 友 - Lesson 9 | Genki Study Resources - 2nd Edition">
<meta name="twitter:title" content="Kanji Practice: 雨, 書, and 友 - Lesson 9 | Genki Study Resources - 2nd Edition">
<meta property="og:title" content="Kanji Practice: 雨, 書, and 友 - Lesson 9 | Genki Study Resources - 2nd Edition">
<meta name="description" content="Turn to page 328 of Genki I and study the readings and compounds for the kanji 雨, 書, and 友, then match the English expressions to the correct kanji.">
<meta property="og:description" content="Turn to page 328 of Genki I and study the readings and compounds for the kanji 雨, 書, and 友, then match the English expressions to the correct kanji.">
<link rel="shortcut icon" type="image/x-icon" href="../../../resources/images/genkico.ico">
<meta name="keywords" content="Genki I, Reading and Writing, page 328, japanese, quizzes, exercises, 2nd Edition" lang="en">
<meta name="language" content="en">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta property="og:site_name" content="sethclydesdale.github.io">
<meta property="og:url" content="https://sethclydesdale.github.io/genki-study-resources/lessons/lesson-9/literacy-3/">
<meta property="og:type" content="website">
<meta property="og:image" content="https://sethclydesdale.github.io/genki-study-resources/resources/images/genki-thumb.png">
<meta name="twitter:card" content="summary">
<meta name="twitter:creator" content="@SethC1995">
<link rel="stylesheet" href="../../../resources/css/stylesheet.min.css">
<script src="../../../resources/javascript/head.min.js"></script>
<script src="../../../resources/javascript/ga.js" async></script>
</head>
<body>
<header>
<h1><a href="../../../" id="home-link" class="edition-icon second-ed">Genki Study Resources</a></h1>
<a id="fork-me" href="https://github.com/SethClydesdale/genki-study-resources">Fork Me</a>
</header>
<div id="content">
<div id="exercise" class="content-block">
<div id="quiz-result"></div>
<div id="quiz-zone" class="clear"></div>
<div id="quiz-timer" class="center"></div>
</div>
</div>
<footer class="clear">
<ul class="footer-left">
<li><a href="../../../" id="footer-home">Home</a></li>
<li><a href="../../../privacy/">Privacy</a></li>
<li><a href="../../../report/">Report a Bug</a></li>
<li><a href="../../../help/">Help</a></li>
<li><a href="../../../donate/">Donate</a></li>
</ul>
<ul class="footer-right">
<li>Created by <a href="https://github.com/SethClydesdale">Seth Clydesdale</a> and the <a href="https://github.com/SethClydesdale/genki-study-resources/graphs/contributors">GitHub Community</a></li>
</ul>
</footer>
<script src="../../../resources/javascript/dragula.min.js"></script>
<script src="../../../resources/javascript/easytimer.min.js"></script>
<script src="../../../resources/javascript/exercises/2nd-ed.min.js"></script>
<script src="../../../resources/javascript/genki.min.js"></script>
<script src="../../../resources/javascript/all.min.js"></script>
<script>Genki.generateQuiz({
type : 'drag',
info : 'Turn to page 328 of Genki I and study the readings and compounds for the kanji 雨, 書, and 友, then match the English expressions to the correct kanji.',
quizlet : {
'雨|あめ' : 'rain',
'雨期|うき' : 'rainy season',
'梅雨|つゆ' : 'rainy season (East Asia)',
'書く|かく' : 'to write',
'辞書|じしょ' : 'dictionary',
'教科書|きょうかしょ' : 'textbook',
'図書館|としょかん' : 'library',
'友だち|ともだち' : 'friend',
'親友|しんゆう' : 'best friend',
'友人|ゆうじん' : 'friend (formal)',
'友情|ゆうじょう' : 'friendship'
}
});</script>
</body>
</html>
|
{
"pile_set_name": "Github"
}
|
// Copyright (c) 2020 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import keyMirror from 'keymirror';
import {AGGREGATION_TYPES} from 'constants/default-settings';
import {DefaultColorRange} from 'constants/color-ranges';
export const PROPERTY_GROUPS = keyMirror({
color: null,
stroke: null,
radius: null,
height: null,
angle: null,
// for heatmap aggregation
cell: null,
precision: null
});
export const DEFAULT_LAYER_OPACITY = 0.8;
/** @type {import('./layer-factory').LayerTextLabel} */
export const DEFAULT_TEXT_LABEL = {
field: null,
color: [255, 255, 255],
size: 18,
offset: [0, 0],
anchor: 'start',
alignment: 'center'
};
export const DEFAULT_COLOR_RANGE = DefaultColorRange;
/** @type {import('./layer-factory').ColorRange} */
export const DEFAULT_CUSTOM_PALETTE = {
name: 'color.customPalette',
type: 'custom',
category: 'Custom',
colors: []
};
/** @type {import('./layer-factory').ColorUI} */
export const DEFAULT_COLOR_UI = {
// customPalette in edit
customPalette: DEFAULT_CUSTOM_PALETTE,
// show color sketcher modal
showSketcher: false,
// show color range selection panel
showDropdown: false,
// color range selector config
colorRangeConfig: {
type: 'all',
steps: 6,
reversed: false,
custom: false
}
};
/** @type {import('./layer-factory').LayerVisConfig} */
export const LAYER_VIS_CONFIGS = {
thickness: {
type: 'number',
defaultValue: 2,
label: 'layerVisConfigs.strokeWidth',
isRanged: false,
range: [0, 100],
step: 0.1,
group: PROPERTY_GROUPS.stroke,
property: 'thickness'
},
strokeWidthRange: {
type: 'number',
defaultValue: [0, 10],
label: 'layerVisConfigs.strokeWidthRange',
isRanged: true,
range: [0, 200],
step: 0.1,
group: PROPERTY_GROUPS.stroke,
property: 'sizeRange'
},
trailLength: {
type: 'number',
defaultValue: 180,
label: 'layerVisConfigs.strokeWidth',
isRanged: false,
range: [1, 1000],
step: 1,
group: PROPERTY_GROUPS.stroke,
property: 'trailLength'
},
// radius is actually radiusScale in deck.gl
radius: {
type: 'number',
defaultValue: 10,
label: 'layerVisConfigs.radius',
isRanged: false,
range: [0, 100],
step: 0.1,
group: PROPERTY_GROUPS.radius,
property: 'radius'
},
fixedRadius: {
defaultValue: false,
type: 'boolean',
label: 'layerVisConfigs.fixedRadius',
description: 'layerVisConfigs.fixedRadiusDescription',
group: PROPERTY_GROUPS.radius,
property: 'fixedRadius'
},
radiusRange: {
type: 'number',
defaultValue: [0, 50],
isRanged: true,
range: [0, 500],
step: 0.1,
label: 'layerVisConfigs.radiusRange',
group: PROPERTY_GROUPS.radius,
property: 'radiusRange'
},
clusterRadius: {
type: 'number',
label: 'layerVisConfigs.clusterRadius',
defaultValue: 40,
isRanged: false,
range: [1, 500],
step: 0.1,
group: PROPERTY_GROUPS.radius,
property: 'clusterRadius'
},
clusterRadiusRange: {
type: 'number',
label: 'layerVisConfigs.radiusRangePixels',
defaultValue: [1, 40],
isRanged: true,
range: [1, 150],
step: 0.1,
group: PROPERTY_GROUPS.radius,
property: 'radiusRange'
},
opacity: {
type: 'number',
defaultValue: DEFAULT_LAYER_OPACITY,
label: 'layerVisConfigs.opacity',
isRanged: false,
range: [0, 1],
step: 0.01,
group: PROPERTY_GROUPS.color,
property: 'opacity'
},
coverage: {
type: 'number',
defaultValue: 1,
label: 'layerVisConfigs.coverage',
isRanged: false,
range: [0, 1],
step: 0.01,
group: PROPERTY_GROUPS.cell,
property: 'coverage'
},
// used in point layer
outline: {
type: 'boolean',
defaultValue: false,
label: 'layer.outline',
group: PROPERTY_GROUPS.display,
property: 'outline'
},
colorRange: {
type: 'color-range-select',
defaultValue: DefaultColorRange,
label: 'layerVisConfigs.colorRange',
group: PROPERTY_GROUPS.color,
property: 'colorRange'
},
strokeColorRange: {
type: 'color-range-select',
defaultValue: DefaultColorRange,
label: 'layerVisConfigs.strokeColorRange',
group: PROPERTY_GROUPS.color,
property: 'strokeColorRange'
},
targetColor: {
type: 'color-select',
label: 'layerVisConfigs.targetColor',
defaultValue: null,
group: PROPERTY_GROUPS.color,
property: 'targetColor'
},
strokeColor: {
type: 'color-select',
label: 'layerVisConfigs.strokeColor',
defaultValue: null,
group: PROPERTY_GROUPS.color,
property: 'strokeColor'
},
aggregation: {
type: 'select',
defaultValue: AGGREGATION_TYPES.average,
label: 'layerVisConfigs.colorAggregation',
// aggregation options are based on color field types
options: Object.keys(AGGREGATION_TYPES),
group: PROPERTY_GROUPS.color,
property: 'colorAggregation',
condition: config => config.colorField
},
sizeAggregation: {
type: 'select',
defaultValue: AGGREGATION_TYPES.average,
label: 'layerVisConfigs.heightAggregation',
// aggregation options are based on color field types
options: Object.keys(AGGREGATION_TYPES),
group: PROPERTY_GROUPS.height,
property: 'sizeAggregation',
condition: config => config.sizeField
},
percentile: {
type: 'number',
defaultValue: [0, 100],
label: config =>
`Filter by ${
config.colorField
? `${config.visConfig.colorAggregation} ${config.colorField.name}`
: 'count'
} percentile`,
isRanged: true,
range: [0, 100],
step: 0.01,
group: PROPERTY_GROUPS.color,
property: 'percentile',
// percentile filter only makes sense with linear aggregation
condition: config => config.colorScale !== 'ordinal'
},
elevationPercentile: {
type: 'number',
defaultValue: [0, 100],
label: config =>
`Filter by ${
config.sizeField ? `${config.visConfig.sizeAggregation} ${config.sizeField.name}` : 'count'
} percentile`,
isRanged: true,
range: [0, 100],
step: 0.01,
group: PROPERTY_GROUPS.height,
property: 'elevationPercentile',
// percentile filter only makes sense with linear aggregation
condition: config => config.visConfig.enable3d && (config.colorField || config.sizeField)
},
resolution: {
type: 'number',
defaultValue: 8,
label: 'layerVisConfigs.resolution',
isRanged: false,
range: [0, 13],
step: 1,
group: PROPERTY_GROUPS.cell,
property: 'resolution'
},
sizeScale: {
type: 'number',
defaultValue: 10,
label: 'layerVisConfigs.sizeScale',
isRanged: false,
range: [1, 1000],
step: 1,
group: PROPERTY_GROUPS.stroke,
property: 'sizeScale'
},
angle: {
type: 'number',
label: 'layerVisConfigs.angle',
defaultValue: 0,
isRanged: false,
range: [0, 360],
group: PROPERTY_GROUPS.angle,
step: 1,
property: 'angle'
},
worldUnitSize: {
type: 'number',
defaultValue: 1,
label: 'layerVisConfigs.worldUnitSize',
isRanged: false,
range: [0, 500],
step: 0.0001,
group: PROPERTY_GROUPS.cell,
property: 'worldUnitSize'
},
elevationScale: {
type: 'number',
defaultValue: 5,
label: 'layerVisConfigs.elevationScale',
isRanged: false,
range: [0, 100],
step: 0.1,
group: PROPERTY_GROUPS.height,
property: 'elevationScale'
},
elevationRange: {
type: 'number',
defaultValue: [0, 500],
label: 'layerVisConfigs.heightScale',
isRanged: true,
range: [0, 1000],
step: 0.01,
group: PROPERTY_GROUPS.height,
property: 'sizeRange'
},
heightRange: {
type: 'number',
defaultValue: [0, 500],
label: 'Height Scale',
isRanged: true,
range: [0, 1000],
step: 0.01,
group: PROPERTY_GROUPS.height,
property: 'heightRange'
},
coverageRange: {
type: 'number',
defaultValue: [0, 1],
label: 'layerVisConfigs.coverageRange',
isRanged: true,
range: [0, 1],
step: 0.01,
group: PROPERTY_GROUPS.radius,
property: 'coverageRange'
},
// hi precision is deprecated by deck.gl
'hi-precision': {
type: 'boolean',
defaultValue: false,
label: 'layerVisConfigs.highPrecisionRendering',
group: PROPERTY_GROUPS.precision,
property: 'hi-precision',
description: 'layerVisConfigs.highPrecisionRenderingDescription'
},
enable3d: {
type: 'boolean',
defaultValue: false,
label: 'layerVisConfigs.height',
group: PROPERTY_GROUPS.height,
property: 'enable3d',
description: 'layerVisConfigs.heightDescription'
},
stroked: {
type: 'boolean',
label: 'layerVisConfigs.stroke',
defaultValue: true,
group: PROPERTY_GROUPS.display,
property: 'stroked'
},
filled: {
type: 'boolean',
label: 'layerVisConfigs.fill',
defaultValue: false,
group: PROPERTY_GROUPS.display,
property: 'filled'
},
extruded: {
type: 'boolean',
defaultValue: false,
label: 'layerVisConfigs.enablePolygonHeight',
group: PROPERTY_GROUPS.display,
property: 'extruded'
},
wireframe: {
type: 'boolean',
defaultValue: false,
label: 'layerVisConfigs.showWireframe',
group: PROPERTY_GROUPS.display,
property: 'wireframe'
},
// used for heatmap
weight: {
type: 'number',
defaultValue: 1,
label: 'layerVisConfigs.weightIntensity',
isRanged: false,
range: [0.01, 500],
step: 0.01,
group: PROPERTY_GROUPS.cell,
property: 'weight',
condition: config => config.weightField
},
heatmapRadius: {
type: 'number',
defaultValue: 20,
label: 'layerVisConfigs.radius',
isRanged: false,
range: [0, 100],
step: 0.1,
group: PROPERTY_GROUPS.cell,
property: 'radius'
}
};
/** @type {import('./layer-factory').LayerTextConfig} */
export const LAYER_TEXT_CONFIGS = {
fontSize: {
type: 'number',
range: [1, 100],
value0: 1,
step: 1,
isRanged: false,
label: 'Font size',
showInput: true
},
textAnchor: {
type: 'select',
options: ['start', 'middle', 'end'],
multiSelect: false,
searchable: false
},
textAlignment: {
type: 'select',
options: ['top', 'center', 'bottom'],
multiSelect: false,
searchable: false
}
};
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (C) 2005-2020 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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.
*/
// The following code is an implementation of a small OTB
// program. It tests including header files and linking with OTB
// libraries.
#include "otbImage.h"
#include <iostream>
int main()
{
using ImageType = otb::Image<unsigned short, 2>;
ImageType::Pointer image = ImageType::New();
std::cout << "OTB Hello World !" << std::endl;
return EXIT_SUCCESS;
}
// This code instantiates an image whose pixels are represented with
// type \code{unsigned short}. The image is then constructed and assigned to a
// \doxygen{itk}{SmartPointer}. Although later in the text we will discuss
// \code{SmartPointer}'s in detail, for now think of it as a handle on an
// instance of an object (see section \ref{sec:SmartPointers} for more
// information). The \doxygen{itk}{Image} class will be described in
// Section~\ref{sec:ImageSection}.
|
{
"pile_set_name": "Github"
}
|
/**
* Created by ezgoing on 14/9/2014.
*/
"use strict";
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function ($) {
var cropbox = function(options, el){
var el = el || $(options.imageBox),
obj =
{
state : {},
ratio : 1,
options : options,
imageBox : el,
thumbBox : el.find(options.thumbBox),
spinner : el.find(options.spinner),
image : new Image(),
getDataURL: function ()
{
var width = this.thumbBox.width(),
height = this.thumbBox.height(),
canvas = document.createElement("canvas"),
dim = el.css('background-position').split(' '),
size = el.css('background-size').split(' '),
dx = parseInt(dim[0]) - el.width()/2 + width/2,
dy = parseInt(dim[1]) - el.height()/2 + height/2,
dw = parseInt(size[0]),
dh = parseInt(size[1]),
sh = parseInt(this.image.height),
sw = parseInt(this.image.width);
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
context.drawImage(this.image, 0, 0, sw, sh, dx, dy, dw, dh);
var imageData = canvas.toDataURL('image/png');
return imageData;
},
getBlob: function()
{
var imageData = this.getDataURL();
var b64 = imageData.replace('data:image/png;base64,','');
var binary = atob(b64);
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/png'});
},
zoomIn: function ()
{
this.ratio*=1.1;
setBackground();
},
zoomOut: function ()
{
this.ratio*=0.9;
setBackground();
}
},
setBackground = function()
{
var w = parseInt(obj.image.width)*obj.ratio;
var h = parseInt(obj.image.height)*obj.ratio;
var pw = (el.width() - w) / 2;
var ph = (el.height() - h) / 2;
/*
'background-size': w/3.18 +'px ' + h/3.18 + 'px',
'background-position': pw/1.75 + 'px ' + ph/1.75 + 'px',
*/
el.css({
'background-image': 'url(' + obj.image.src + ')',
'background-size': w +'px ' + h + 'px',
'background-position': pw + 'px ' + ph + 'px',
'background-repeat': 'no-repeat'});
},
imgMouseDown = function(e)
{
e.stopImmediatePropagation();
obj.state.dragable = true;
obj.state.mouseX = e.clientX;
obj.state.mouseY = e.clientY;
},
imgMouseMove = function(e)
{
e.stopImmediatePropagation();
if (obj.state.dragable)
{
var x = e.clientX - obj.state.mouseX;
var y = e.clientY - obj.state.mouseY;
var bg = el.css('background-position').split(' ');
var bgX = x + parseInt(bg[0]);
var bgY = y + parseInt(bg[1]);
el.css('background-position', bgX +'px ' + bgY + 'px');
obj.state.mouseX = e.clientX;
obj.state.mouseY = e.clientY;
}
},
imgMouseUp = function(e)
{
e.stopImmediatePropagation();
obj.state.dragable = false;
},
zoomImage = function(e)
{
e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0 ? obj.ratio*=1.1 : obj.ratio*=0.9;
setBackground();
}
obj.spinner.show();
obj.image.onload = function() {
obj.spinner.hide();
setBackground();
el.bind('mousedown', imgMouseDown);
el.bind('mousemove', imgMouseMove);
$(window).bind('mouseup', imgMouseUp);
el.bind('mousewheel DOMMouseScroll', zoomImage);
};
obj.image.src = options.imgSrc;
el.on('remove', function(){$(window).unbind('mouseup', imgMouseUp)});
return obj;
};
jQuery.fn.cropbox = function(options){
return new cropbox(options, this);
};
}));
|
{
"pile_set_name": "Github"
}
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def crimtab(path):
"""Student's 3000 Criminals Data
Data of 3000 male criminals over 20 years old undergoing their sentences
in the chief prisons of England and Wales.
A `table` object of `integer` counts, of dimension *42 \* 22* with a
total count, `sum(crimtab)` of 3000.
The 42 `rownames` (`"9.4"`, `"9.5"`, ...) correspond to midpoints
of intervals of finger lengths whereas the 22 column names
(`colnames`) (`"142.24"`, `"144.78"`, ...) correspond to (body)
heights of 3000 criminals, see also below.
http://pbil.univ-lyon1.fr/R/donnees/criminals1902.txt thanks to Jean R.
Lobry and Anne-Béatrice Dufour.
Args:
path: str.
Path to directory which either stores file or otherwise file will
be downloaded and extracted there.
Filename is `crimtab.csv`.
Returns:
Tuple of np.ndarray `x_train` with 42 rows and 22 columns and
dictionary `metadata` of column headers (feature names).
"""
import pandas as pd
path = os.path.expanduser(path)
filename = 'crimtab.csv'
if not os.path.exists(os.path.join(path, filename)):
url = 'http://dustintran.com/data/r/datasets/crimtab.csv'
maybe_download_and_extract(path, url,
save_file_name='crimtab.csv',
resume=False)
data = pd.read_csv(os.path.join(path, filename), index_col=0,
parse_dates=True)
x_train = data.values
metadata = {'columns': data.columns}
return x_train, metadata
|
{
"pile_set_name": "Github"
}
|
<!DOCTYPE html><html class="theme-next muse use-motion" lang="zh-CN"><head><meta name="generator" content="Hexo 3.8.0"><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=2"><meta name="theme-color" content="#222"><script src="//cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script><link href="/lib/pace/pace-theme-corner-indicator.min.css?v=1.0.2" rel="stylesheet"><meta name="google-site-verification" content="sDeZZSmv4NPbU3sXi1IL5l8PiZt1wVqR5EKUsxOjruY"><link href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.2.5/dist/jquery.fancybox.min.css" rel="stylesheet" type="text/css"><link href="https://fonts.googleapis.cnpmjs.org/css?family=Noto Serif SC:300,300italic,400,400italic,700,700italic|Noto Serif SC:300,300italic,400,400italic,700,700italic|Roboto Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css"><link href="//cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"><link href="/css/main.css?v=6.6.0" rel="stylesheet" type="text/css"><link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.6.0"><link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.6.0"><link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.6.0"><link rel="mask-icon" href="/images/logo.svg?v=6.6.0" color="#222"><script id="hexo.configurations">var NexT=window.NexT||{},CONFIG={root:"/",scheme:"Muse",version:"6.6.0",sidebar:{position:"left",display:"hide",offset:12,b2t:!1,scrollpercent:!0,onmobile:!0},fancybox:!0,fastclick:!1,lazyload:!1,tabs:!0,motion:{enable:!0,async:!1,transition:{post_block:"fadeIn",post_header:"slideDownIn",post_body:"slideDownIn",coll_header:"slideLeftIn",sidebar:"slideUpIn"}},algolia:{applicationID:"",apiKey:"",indexName:"",hits:{per_page:10},labels:{input_placeholder:"Search for Posts",hits_empty:"We didn't find any results for the search: ${query}",hits_stats:"${hits} results found in ${time} ms"}}}</script><meta name="description" content="黑果小兵,daliansky,blog.daliansky.net,macOS,Hackintosh,黑苹果,linux"><meta name="keywords" content="daliansky,黑果小兵,macOS,Hackintosh,黑苹果,linux,blog.daliansky.net"><meta property="og:type" content="website"><meta property="og:title" content="黑果小兵的部落阁"><meta property="og:url" content="https://blog.daliansky.net/tags/亮度调整/index.html"><meta property="og:site_name" content="黑果小兵的部落阁"><meta property="og:description" content="黑果小兵,daliansky,blog.daliansky.net,macOS,Hackintosh,黑苹果,linux"><meta property="og:locale" content="zh-CN"><meta name="twitter:card" content="summary"><meta name="twitter:title" content="黑果小兵的部落阁"><meta name="twitter:description" content="黑果小兵,daliansky,blog.daliansky.net,macOS,Hackintosh,黑苹果,linux"><link rel="alternate" href="/atom.xml" title="黑果小兵的部落阁" type="application/atom+xml"><link rel="canonical" href="https://blog.daliansky.net/tags/亮度调整/"><script id="page.configurations">CONFIG.page={sidebar:""}</script><title>标签: 亮度调整 | 黑果小兵的部落阁</title><script async src="https://www.googletagmanager.com/gtag/js?id=UA-18130737-1"></script><script>function gtag(){dataLayer.push(arguments)}window.dataLayer=window.dataLayer||[],gtag("js",new Date),gtag("config","UA-18130737-1")</script><noscript><style>.sidebar-inner,.use-motion .brand,.use-motion .collection-title,.use-motion .comments,.use-motion .menu-item,.use-motion .motion-element,.use-motion .pagination,.use-motion .post-block,.use-motion .post-body,.use-motion .post-header{opacity:initial}.use-motion .logo,.use-motion .site-subtitle,.use-motion .site-title{opacity:initial;top:initial}.use-motion .logo-line-before i{left:initial}.use-motion .logo-line-after i{right:initial}</style></noscript></head><body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN"><div class="container sidebar-position-left"><div class="headband"></div><header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="header-inner"><div class="site-brand-wrapper"><div class="site-meta"><div class="custom-logo-site-title"><a href="/" class="brand" rel="start"><span class="logo-line-before"><i></i></span> <span class="site-title">黑果小兵的部落阁</span> <span class="logo-line-after"><i></i></span></a></div><p class="site-subtitle">Hackintosh安装镜像、教程及经验分享</p></div><div class="site-nav-toggle"><button aria-label="切换导航栏"><span class="btn-bar"></span> <span class="btn-bar"></span> <span class="btn-bar"></span></button></div></div><nav class="site-nav"><ul id="menu" class="menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i><br>首页</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i><br>归档</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i><br>分类</a></li><li class="menu-item menu-item-tags menu-item-active"><a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i><br>标签</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i><br>关于</a></li><li class="menu-item menu-item-search"><a href="javascript:;" class="popup-trigger"><i class="menu-item-icon fa fa-search fa-fw"></i><br>搜索</a></li></ul><div class="site-search"><div class="popup search-popup local-search-popup"><div class="local-search-header clearfix"><span class="search-icon"><i class="fa fa-search"></i> </span><span class="popup-btn-close"><i class="fa fa-times-circle"></i></span><div class="local-search-input-wrapper"><input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input"></div></div><div id="local-search-result"></div></div></div></nav></div></header><a href="https://github.com/daliansky" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#222;color:#fff;position:absolute;top:0;border:0;right:0" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin:130px 106px" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><main id="main" class="main"><div class="main-inner"><div class="content-wrap"><div id="content" class="content"><div class="post-block tag"><div id="posts" class="posts-collapse"><div class="collection-title"><h1>亮度调整<small>标签</small></h1></div><article class="post post-type-archive" itemscope itemtype="http://schema.org/Article"><header class="post-header"><h2 class="post-title"><a class="post-title-link" href="/CoffeeLake-UHD-630-black-screen-direct-bright-screen-and-correct-adjustment-of-brightness-adjustment.html" itemprop="url"><span itemprop="name">【黑果小兵】CoffeeLake UHD 630黑屏、直接亮屏及亮度调整的正确插入姿势</span></a></h2><div class="post-meta"><time class="post-time" itemprop="dateCreated" datetime="2018-10-18T07:32:17+08:00" content="2018-10-18">10-18</time></div></header></article></div></div></div></div><div class="sidebar-toggle"><div class="sidebar-toggle-line-wrap"><span class="sidebar-toggle-line sidebar-toggle-line-first"></span> <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span> <span class="sidebar-toggle-line sidebar-toggle-line-last"></span></div></div><aside id="sidebar" class="sidebar"><div id="sidebar-dimmer"></div><div class="sidebar-inner"><div class="site-overview-wrap sidebar-panel sidebar-panel-active"><div class="site-overview"><div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person"><a href="/"><img class="site-author-image" itemprop="image" src="/images/loading.gif" data-original="/images/avatar.png" alt="黑果小兵"></a><p class="site-author-name" itemprop="name">黑果小兵</p><p class="site-description motion-element" itemprop="description">黑果小兵</p></div><nav class="site-state motion-element"><div class="site-state-item site-state-posts"><a href="/archives/"><span class="site-state-item-count">102</span> <span class="site-state-item-name">日志</span></a></div><div class="site-state-item site-state-categories"><a href="/categories/index.html"><span class="site-state-item-count">24</span> <span class="site-state-item-name">分类</span></a></div><div class="site-state-item site-state-tags"><a href="/tags/index.html"><span class="site-state-item-count">236</span> <span class="site-state-item-name">标签</span></a></div></nav><div class="feed-link motion-element"><a href="/atom.xml" rel="alternate"><i class="fa fa-rss"></i> RSS</a></div><div class="links-of-author motion-element"><span class="links-of-author-item"><a href="https://github.com/daliansky" title="GitHub → https://github.com/daliansky" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i></a> </span><span class="links-of-author-item"><a href="http://www.jianshu.com/u/df9143008845" title="简书 → http://www.jianshu.com/u/df9143008845" rel="noopener" target="_blank"><i class="fa fa-fw fa-heartbeat"></i></a> </span><span class="links-of-author-item"><a href="http://shang.qq.com/wpa/qunwpa?idkey=db511a29e856f37cbb871108ffa77a6e79dde47e491b8f2c8d8fe4d3c310de91" title="QQ → http://shang.qq.com/wpa/qunwpa?idkey=db511a29e856f37cbb871108ffa77a6e79dde47e491b8f2c8d8fe4d3c310de91" rel="noopener" target="_blank"><i class="fa fa-fw fa-qq"></i></a></span></div><div class="links-of-blogroll motion-element links-of-blogroll-block"><div class="links-of-blogroll-title"><i class="fa fa-fw fa-link"></i> Links</div><ul class="links-of-blogroll-list"><li class="links-of-blogroll-item"><a href="https://blog.tlhub.cn" title="https://blog.tlhub.cn" rel="noopener" target="_blank">Athlonreg</a></li><li class="links-of-blogroll-item"><a href="http://www.sqlsec.com" title="http://www.sqlsec.com" rel="noopener" target="_blank">国光</a></li></ul></div></div></div></div></aside></div></main><footer id="footer" class="footer"><div class="footer-inner"><div class="copyright"><a href="http://www.beian.miit.gov.cn" rel="noopener" target="_blank">辽ICP备15000696号-3 </a>© 2016 – <span itemprop="copyrightYear">2020</span> <span class="with-love" id="animate"><i class="fa fa-apple"></i> </span><span class="author" itemprop="copyrightHolder">黑果小兵</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-area-chart"></i> </span><span title="站点总字数">661k</span> <span class="post-meta-divider">|</span> <span class="post-meta-item-icon"><i class="fa fa-coffee"></i> </span><span title="站点阅读时长">20:01</span></div><div class="busuanzi-count"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span class="site-uv" title="总访客量"><i class="fa fa-user"></i> <span class="busuanzi-value" id="busuanzi_value_site_uv"></span> </span><span class="site-pv" title="总访问量"><i class="fa fa-eye"></i> <span class="busuanzi-value" id="busuanzi_value_site_pv"></span></span></div></div></footer><div class="back-to-top"><i class="fa fa-arrow-up"></i> <span id="scrollpercent"><span>0</span>%</span></div></div><script>"[object Function]"!==Object.prototype.toString.call(window.Promise)&&(window.Promise=null)</script><script src="/lib/jquery/index.js?v=2.1.3"></script><script src="/lib/velocity/velocity.min.js?v=1.2.1"></script><script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.2.5/dist/jquery.fancybox.min.js"></script><script src="//cdn.jsdelivr.net/gh/theme-next/theme-next-reading-progress@1.1/reading_progress.min.js"></script><script src="/js/src/utils.js?v=6.6.0"></script><script src="/js/src/motion.js?v=6.6.0"></script><script src="/js/src/bootstrap.js?v=6.6.0"></script><script>// Popup Window;
var isfetched = false;
var isXml = true;
// Search DB path;
var search_path = "search.xml";
if (search_path.length === 0) {
search_path = "search.xml";
} else if (/json$/i.test(search_path)) {
isXml = false;
}
var path = "/" + search_path;
// monitor main search box;
var onPopupClose = function (e) {
$('.popup').hide();
$('#local-search-input').val('');
$('.search-result-list').remove();
$('#no-result').remove();
$(".local-search-pop-overlay").remove();
$('body').css('overflow', '');
}
function proceedsearch() {
$("body")
.append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
.css('overflow', 'hidden');
$('.search-popup-overlay').click(onPopupClose);
$('.popup').toggle();
var $localSearchInput = $('#local-search-input');
$localSearchInput.attr("autocapitalize", "none");
$localSearchInput.attr("autocorrect", "off");
$localSearchInput.focus();
}
// search function;
var searchFunc = function(path, search_id, content_id) {
'use strict';
// start loading animation
$("body")
.append('<div class="search-popup-overlay local-search-pop-overlay">' +
'<div id="search-loading-icon">' +
'<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
'</div>' +
'</div>')
.css('overflow', 'hidden');
$("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');
$.ajax({
url: path,
dataType: isXml ? "xml" : "json",
async: true,
success: function(res) {
// get the contents from search data
isfetched = true;
$('.popup').detach().appendTo('.header-inner');
var datas = isXml ? $("entry", res).map(function() {
return {
title: $("title", this).text(),
content: $("content",this).text(),
url: $("url" , this).text()
};
}).get() : res;
var input = document.getElementById(search_id);
var resultContent = document.getElementById(content_id);
var inputEventFunction = function() {
var searchText = input.value.trim().toLowerCase();
var keywords = searchText.split(/[\s\-]+/);
if (keywords.length > 1) {
keywords.push(searchText);
}
var resultItems = [];
if (searchText.length > 0) {
// perform local searching
datas.forEach(function(data) {
var isMatch = false;
var hitCount = 0;
var searchTextCount = 0;
var title = data.title.trim();
var titleInLowerCase = title.toLowerCase();
var content = data.content.trim().replace(/<[^>]+>/g,"");
var contentInLowerCase = content.toLowerCase();
var articleUrl = decodeURIComponent(data.url);
var indexOfTitle = [];
var indexOfContent = [];
// only match articles with not empty titles
if(title != '') {
keywords.forEach(function(keyword) {
function getIndexByWord(word, text, caseSensitive) {
var wordLen = word.length;
if (wordLen === 0) {
return [];
}
var startPosition = 0, position = [], index = [];
if (!caseSensitive) {
text = text.toLowerCase();
word = word.toLowerCase();
}
while ((position = text.indexOf(word, startPosition)) > -1) {
index.push({position: position, word: word});
startPosition = position + wordLen;
}
return index;
}
indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
});
if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
isMatch = true;
hitCount = indexOfTitle.length + indexOfContent.length;
}
}
// show search results
if (isMatch) {
// sort index by position of keyword
[indexOfTitle, indexOfContent].forEach(function (index) {
index.sort(function (itemLeft, itemRight) {
if (itemRight.position !== itemLeft.position) {
return itemRight.position - itemLeft.position;
} else {
return itemLeft.word.length - itemRight.word.length;
}
});
});
// merge hits into slices
function mergeIntoSlice(text, start, end, index) {
var item = index[index.length - 1];
var position = item.position;
var word = item.word;
var hits = [];
var searchTextCountInSlice = 0;
while (position + word.length <= end && index.length != 0) {
if (word === searchText) {
searchTextCountInSlice++;
}
hits.push({position: position, length: word.length});
var wordEnd = position + word.length;
// move to next position of hit
index.pop();
while (index.length != 0) {
item = index[index.length - 1];
position = item.position;
word = item.word;
if (wordEnd > position) {
index.pop();
} else {
break;
}
}
}
searchTextCount += searchTextCountInSlice;
return {
hits: hits,
start: start,
end: end,
searchTextCount: searchTextCountInSlice
};
}
var slicesOfTitle = [];
if (indexOfTitle.length != 0) {
slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
}
var slicesOfContent = [];
while (indexOfContent.length != 0) {
var item = indexOfContent[indexOfContent.length - 1];
var position = item.position;
var word = item.word;
// cut out 100 characters
var start = position - 20;
var end = position + 80;
if(start < 0){
start = 0;
}
if (end < position + word.length) {
end = position + word.length;
}
if(end > content.length){
end = content.length;
}
slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
}
// sort slices in content by search text's count and hits' count
slicesOfContent.sort(function (sliceLeft, sliceRight) {
if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
return sliceRight.searchTextCount - sliceLeft.searchTextCount;
} else if (sliceLeft.hits.length !== sliceRight.hits.length) {
return sliceRight.hits.length - sliceLeft.hits.length;
} else {
return sliceLeft.start - sliceRight.start;
}
});
// select top N slices in content
var upperBound = parseInt('1');
if (upperBound >= 0) {
slicesOfContent = slicesOfContent.slice(0, upperBound);
}
// highlight title and content
function highlightKeyword(text, slice) {
var result = '';
var prevEnd = slice.start;
slice.hits.forEach(function (hit) {
result += text.substring(prevEnd, hit.position);
var end = hit.position + hit.length;
result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
prevEnd = end;
});
result += text.substring(prevEnd, slice.end);
return result;
}
var resultItem = '';
if (slicesOfTitle.length != 0) {
resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
} else {
resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
}
slicesOfContent.forEach(function (slice) {
resultItem += "<a href='" + articleUrl + "'>" +
"<p class=\"search-result\">" + highlightKeyword(content, slice) +
"...</p>" + "</a>";
});
resultItem += "</li>";
resultItems.push({
item: resultItem,
searchTextCount: searchTextCount,
hitCount: hitCount,
id: resultItems.length
});
}
})
};
if (keywords.length === 1 && keywords[0] === "") {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
} else if (resultItems.length === 0) {
resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
} else {
resultItems.sort(function (resultLeft, resultRight) {
if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
return resultRight.searchTextCount - resultLeft.searchTextCount;
} else if (resultLeft.hitCount !== resultRight.hitCount) {
return resultRight.hitCount - resultLeft.hitCount;
} else {
return resultRight.id - resultLeft.id;
}
});
var searchResultList = '<ul class=\"search-result-list\">';
resultItems.forEach(function (result) {
searchResultList += result.item;
})
searchResultList += "</ul>";
resultContent.innerHTML = searchResultList;
}
}
if ('auto' === 'auto') {
input.addEventListener('input', inputEventFunction);
} else {
$('.search-icon').click(inputEventFunction);
input.addEventListener('keypress', function (event) {
if (event.keyCode === 13) {
inputEventFunction();
}
});
}
// remove loading animation
$(".local-search-pop-overlay").remove();
$('body').css('overflow', '');
proceedsearch();
}
});
}
// handle and trigger popup window;
$('.popup-trigger').click(function(e) {
e.stopPropagation();
if (isfetched === false) {
searchFunc(path, 'local-search-input', 'local-search-result');
} else {
proceedsearch();
};
});
$('.popup-btn-close').click(onPopupClose);
$('.popup').click(function(e){
e.stopPropagation();
});
$(document).on('keyup', function (event) {
var shouldDismissSearchPopup = event.which === 27 &&
$('.search-popup').is(':visible');
if (shouldDismissSearchPopup) {
onPopupClose();
}
});</script><script src="/js/src/js.cookie.js?v=6.6.0"></script><script src="/js/src/scroll-cookie.js?v=6.6.0"></script><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({pluginRootPath:"live2dw/",pluginJsPath:"lib/",pluginModelPath:"assets/",model:{scale:1.2,hHeadPos:.5,vHeadPos:.618,jsonPath:"/live2dw/assets/tororo.model.json"},display:{superSample:2,width:150,height:300,position:"right",hOffset:0,vOffset:-20},mobile:{show:!1,scale:.5},react:{opacityDefault:.7,opacityOnHover:.2},log:!1,tagMode:!1})</script><script>window.imageLazyLoadSetting={isSPA:!1,processImages:null}</script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})})</script><script>!function(n){n.imageLazyLoadSetting.processImages=i;var e=n.imageLazyLoadSetting.isSPA,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function i(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=r[a].getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight||document.documentElement.clientHeight)&&function(){var e=r[a],t=e,n=function(){r=r.filter(function(t){return e!==t})},i=new Image,o=t.getAttribute("data-original");i.onload=function(){t.src=o,n()},i.src=o}()}i(),n.addEventListener("scroll",function(){var t=i,e=n;clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this)</script></body></html>
|
{
"pile_set_name": "Github"
}
|
/*
** $Id: lobject.c,v 2.55 2011/11/30 19:30:16 roberto Exp $
** Some generic functions over Lua objects
** See Copyright Notice in lua.h
*/
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define lobject_c
#define LUA_CORE
#include "lua.h"
#include "lctype.h"
#include "ldebug.h"
#include "ldo.h"
#include "lmem.h"
#include "lobject.h"
#include "lstate.h"
#include "lstring.h"
#include "lvm.h"
LUAI_DDEF const TValue luaO_nilobject_ = {NILCONSTANT};
/*
** converts an integer to a "floating point byte", represented as
** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if
** eeeee != 0 and (xxx) otherwise.
*/
int luaO_int2fb (unsigned int x) {
int e = 0; /* exponent */
if (x < 8) return x;
while (x >= 0x10) {
x = (x+1) >> 1;
e++;
}
return ((e+1) << 3) | (cast_int(x) - 8);
}
/* converts back */
int luaO_fb2int (int x) {
int e = (x >> 3) & 0x1f;
if (e == 0) return x;
else return ((x & 7) + 8) << (e - 1);
}
int luaO_ceillog2 (unsigned int x) {
static const lu_byte log_2[256] = {
0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,
8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8
};
int l = 0;
x--;
while (x >= 256) { l += 8; x >>= 8; }
return l + log_2[x];
}
lua_Number luaO_arith (int op, lua_Number v1, lua_Number v2) {
switch (op) {
case LUA_OPADD: return luai_numadd(NULL, v1, v2);
case LUA_OPSUB: return luai_numsub(NULL, v1, v2);
case LUA_OPMUL: return luai_nummul(NULL, v1, v2);
case LUA_OPDIV: return luai_numdiv(NULL, v1, v2);
case LUA_OPMOD: return luai_nummod(NULL, v1, v2);
case LUA_OPPOW: return luai_numpow(NULL, v1, v2);
case LUA_OPUNM: return luai_numunm(NULL, v1);
default: lua_assert(0); return 0;
}
}
int luaO_hexavalue (int c) {
if (lisdigit(c)) return c - '0';
else return ltolower(c) - 'a' + 10;
}
#if !defined(lua_strx2number)
#include <math.h>
static int isneg (const char **s) {
if (**s == '-') { (*s)++; return 1; }
else if (**s == '+') (*s)++;
return 0;
}
static lua_Number readhexa (const char **s, lua_Number r, int *count) {
for (; lisxdigit(cast_uchar(**s)); (*s)++) { /* read integer part */
r = (r * 16.0) + cast_num(luaO_hexavalue(cast_uchar(**s)));
(*count)++;
}
return r;
}
/*
** convert an hexadecimal numeric string to a number, following
** C99 specification for 'strtod'
*/
static lua_Number lua_strx2number (const char *s, char **endptr) {
lua_Number r = 0.0;
int e = 0, i = 0;
int neg = 0; /* 1 if number is negative */
*endptr = cast(char *, s); /* nothing is valid yet */
while (lisspace(cast_uchar(*s))) s++; /* skip initial spaces */
neg = isneg(&s); /* check signal */
if (!(*s == '0' && (*(s + 1) == 'x' || *(s + 1) == 'X'))) /* check '0x' */
return 0.0; /* invalid format (no '0x') */
s += 2; /* skip '0x' */
r = readhexa(&s, r, &i); /* read integer part */
if (*s == '.') {
s++; /* skip dot */
r = readhexa(&s, r, &e); /* read fractional part */
}
if (i == 0 && e == 0)
return 0.0; /* invalid format (no digit) */
e *= -4; /* each fractional digit divides value by 2^-4 */
*endptr = cast(char *, s); /* valid up to here */
if (*s == 'p' || *s == 'P') { /* exponent part? */
int exp1 = 0;
int neg1;
s++; /* skip 'p' */
neg1 = isneg(&s); /* signal */
if (!lisdigit(cast_uchar(*s)))
goto ret; /* must have at least one digit */
while (lisdigit(cast_uchar(*s))) /* read exponent */
exp1 = exp1 * 10 + *(s++) - '0';
if (neg1) exp1 = -exp1;
e += exp1;
}
*endptr = cast(char *, s); /* valid up to here */
ret:
if (neg) r = -r;
return ldexp(r, e);
}
#endif
int luaO_str2d (const char *s, size_t len, lua_Number *result) {
char *endptr;
if (strpbrk(s, "nN")) /* reject 'inf' and 'nan' */
return 0;
else if (strpbrk(s, "xX")) /* hexa? */
*result = lua_strx2number(s, &endptr);
else
*result = lua_str2number(s, &endptr);
if (endptr == s) return 0; /* nothing recognized */
while (lisspace(cast_uchar(*endptr))) endptr++;
return (endptr == s + len); /* OK if no trailing characters */
}
static void pushstr (lua_State *L, const char *str, size_t l) {
setsvalue2s(L, L->top, luaS_newlstr(L, str, l));
incr_top(L);
}
/* this function handles only `%d', `%c', %f, %p, and `%s' formats */
const char *luaO_pushvfstring (lua_State *L, const char *fmt, va_list argp) {
int n = 0;
for (;;) {
const char *e = strchr(fmt, '%');
if (e == NULL) break;
setsvalue2s(L, L->top, luaS_newlstr(L, fmt, e-fmt));
incr_top(L);
switch (*(e+1)) {
case 's': {
const char *s = va_arg(argp, char *);
if (s == NULL) s = "(null)";
pushstr(L, s, strlen(s));
break;
}
case 'c': {
char buff;
buff = cast(char, va_arg(argp, int));
pushstr(L, &buff, 1);
break;
}
case 'd': {
setnvalue(L->top, cast_num(va_arg(argp, int)));
incr_top(L);
break;
}
case 'f': {
setnvalue(L->top, cast_num(va_arg(argp, l_uacNumber)));
incr_top(L);
break;
}
case 'p': {
char buff[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */
int l = sprintf(buff, "%p", va_arg(argp, void *));
pushstr(L, buff, l);
break;
}
case '%': {
pushstr(L, "%", 1);
break;
}
default: {
luaG_runerror(L,
"invalid option " LUA_QL("%%%c") " to " LUA_QL("lua_pushfstring"),
*(e + 1));
}
}
n += 2;
fmt = e+2;
}
pushstr(L, fmt, strlen(fmt));
if (n > 0) luaV_concat(L, n + 1);
return svalue(L->top - 1);
}
const char *luaO_pushfstring (lua_State *L, const char *fmt, ...) {
const char *msg;
va_list argp;
va_start(argp, fmt);
msg = luaO_pushvfstring(L, fmt, argp);
va_end(argp);
return msg;
}
/* number of chars of a literal string without the ending \0 */
#define LL(x) (sizeof(x)/sizeof(char) - 1)
#define RETS "..."
#define PRE "[string \""
#define POS "\"]"
#define addstr(a,b,l) ( memcpy(a,b,(l) * sizeof(char)), a += (l) )
void luaO_chunkid (char *out, const char *source, size_t bufflen) {
size_t l = strlen(source);
if (*source == '=') { /* 'literal' source */
if (l <= bufflen) /* small enough? */
memcpy(out, source + 1, l * sizeof(char));
else { /* truncate it */
addstr(out, source + 1, bufflen - 1);
*out = '\0';
}
}
else if (*source == '@') { /* file name */
if (l <= bufflen) /* small enough? */
memcpy(out, source + 1, l * sizeof(char));
else { /* add '...' before rest of name */
addstr(out, RETS, LL(RETS));
bufflen -= LL(RETS);
memcpy(out, source + 1 + l - bufflen, bufflen * sizeof(char));
}
}
else { /* string; format as [string "source"] */
const char *nl = strchr(source, '\n'); /* find first new line (if any) */
addstr(out, PRE, LL(PRE)); /* add prefix */
bufflen -= LL(PRE RETS POS) + 1; /* save space for prefix+suffix+'\0' */
if (l < bufflen && nl == NULL) { /* small one-line source? */
addstr(out, source, l); /* keep it */
}
else {
if (nl != NULL) l = nl - source; /* stop at first newline */
if (l > bufflen) l = bufflen;
addstr(out, source, l);
addstr(out, RETS, LL(RETS));
}
memcpy(out, POS, (LL(POS) + 1) * sizeof(char));
}
}
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright (c) 2008-2009 Nelson Carpentier
*
* 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.
*
*/
package com.google.code.ssm.aop.support;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
/**
*
* @author Nelson Carpentier
*
*/
public final class PertinentNegativeNull implements Externalizable {
public static final PertinentNegativeNull NULL = new PertinentNegativeNull();
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
}
@Override
public int hashCode() {
return 1;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
return obj instanceof PertinentNegativeNull;
}
}
|
{
"pile_set_name": "Github"
}
|
BEGIN:VCALENDAR
PRODID:-//tzurl.org//NONSGML Olson 2018g-rearguard//EN
VERSION:2.0
BEGIN:VTIMEZONE
TZID:America/Iqaluit
TZURL:http://tzurl.org/zoneinfo-global/America/Iqaluit
X-LIC-LOCATION:America/Iqaluit
BEGIN:DAYLIGHT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
TZNAME:EDT
DTSTART:20070311T020000
RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
TZNAME:EST
DTSTART:20071104T020000
RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU
END:STANDARD
BEGIN:DAYLIGHT
TZOFFSETFROM:+0000
TZOFFSETTO:-0400
TZNAME:EWT
DTSTART:19420801T000000
RDATE:19420801T000000
END:DAYLIGHT
BEGIN:DAYLIGHT
TZOFFSETFROM:-0400
TZOFFSETTO:-0400
TZNAME:EPT
DTSTART:19450814T190000
RDATE:19450814T190000
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:-0400
TZOFFSETTO:-0500
TZNAME:EST
DTSTART:19450930T020000
RDATE:19450930T020000
RDATE:19801026T020000
RDATE:19811025T020000
RDATE:19821031T020000
RDATE:19831030T020000
RDATE:19841028T020000
RDATE:19851027T020000
RDATE:19861026T020000
RDATE:19871025T020000
RDATE:19881030T020000
RDATE:19891029T020000
RDATE:19901028T020000
RDATE:19911027T020000
RDATE:19921025T020000
RDATE:19931031T020000
RDATE:19941030T020000
RDATE:19951029T020000
RDATE:19961027T020000
RDATE:19971026T020000
RDATE:19981025T020000
RDATE:20011028T020000
RDATE:20021027T020000
RDATE:20031026T020000
RDATE:20041031T020000
RDATE:20051030T020000
RDATE:20061029T020000
END:STANDARD
BEGIN:DAYLIGHT
TZOFFSETFROM:-0500
TZOFFSETTO:-0300
TZNAME:EDDT
DTSTART:19650425T000000
RDATE:19650425T000000
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:-0300
TZOFFSETTO:-0500
TZNAME:EST
DTSTART:19651031T020000
RDATE:19651031T020000
END:STANDARD
BEGIN:DAYLIGHT
TZOFFSETFROM:-0500
TZOFFSETTO:-0400
TZNAME:EDT
DTSTART:19800427T020000
RDATE:19800427T020000
RDATE:19810426T020000
RDATE:19820425T020000
RDATE:19830424T020000
RDATE:19840429T020000
RDATE:19850428T020000
RDATE:19860427T020000
RDATE:19870405T020000
RDATE:19880403T020000
RDATE:19890402T020000
RDATE:19900401T020000
RDATE:19910407T020000
RDATE:19920405T020000
RDATE:19930404T020000
RDATE:19940403T020000
RDATE:19950402T020000
RDATE:19960407T020000
RDATE:19970406T020000
RDATE:19980405T020000
RDATE:19990404T020000
RDATE:20010401T020000
RDATE:20020407T020000
RDATE:20030406T020000
RDATE:20040404T020000
RDATE:20050403T020000
RDATE:20060402T020000
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:-0400
TZOFFSETTO:-0600
TZNAME:CST
DTSTART:19991031T020000
RDATE:19991031T020000
END:STANDARD
BEGIN:DAYLIGHT
TZOFFSETFROM:-0600
TZOFFSETTO:-0500
TZNAME:CDT
DTSTART:20000402T020000
RDATE:20000402T020000
END:DAYLIGHT
BEGIN:STANDARD
TZOFFSETFROM:-0500
TZOFFSETTO:-0500
TZNAME:EST
DTSTART:20001029T020000
RDATE:20001029T020000
END:STANDARD
END:VTIMEZONE
END:VCALENDAR
|
{
"pile_set_name": "Github"
}
|
// Copyright Project Contour 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 v2
import (
"path"
"testing"
"time"
envoy_api_v2 "github.com/envoyproxy/go-control-plane/envoy/api/v2"
envoy_api_v2_auth "github.com/envoyproxy/go-control-plane/envoy/api/v2/auth"
envoy_api_v2_core "github.com/envoyproxy/go-control-plane/envoy/api/v2/core"
envoy_api_v2_listener "github.com/envoyproxy/go-control-plane/envoy/api/v2/listener"
"github.com/golang/protobuf/proto"
projcontour "github.com/projectcontour/contour/apis/projectcontour/v1"
"github.com/projectcontour/contour/internal/dag"
envoyv2 "github.com/projectcontour/contour/internal/envoy/v2"
"github.com/projectcontour/contour/internal/protobuf"
"github.com/projectcontour/contour/internal/timeout"
v1 "k8s.io/api/core/v1"
"k8s.io/api/networking/v1beta1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
func TestListenerCacheContents(t *testing.T) {
tests := map[string]struct {
contents map[string]*envoy_api_v2.Listener
want []proto.Message
}{
"empty": {
contents: nil,
want: nil,
},
"simple": {
contents: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
want: []proto.Message{
&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
},
},
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
var lc ListenerCache
lc.Update(tc.contents)
got := lc.Contents()
protobuf.ExpectEqual(t, tc.want, got)
})
}
}
func TestListenerCacheQuery(t *testing.T) {
tests := map[string]struct {
contents map[string]*envoy_api_v2.Listener
query []string
want []proto.Message
}{
"exact match": {
contents: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
query: []string{ENVOY_HTTP_LISTENER},
want: []proto.Message{
&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
},
},
},
"partial match": {
contents: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
query: []string{ENVOY_HTTP_LISTENER, "stats-listener"},
want: []proto.Message{
&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
},
},
},
"no match": {
contents: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
query: []string{"stats-listener"},
want: nil,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
var lc ListenerCache
lc.Update(tc.contents)
got := lc.Query(tc.query)
protobuf.ExpectEqual(t, tc.want, got)
})
}
}
func TestListenerVisit(t *testing.T) {
httpsFilterFor := func(vhost string) *envoy_api_v2_listener.Filter {
return envoyv2.HTTPConnectionManagerBuilder().
AddFilter(envoyv2.FilterMisdirectedRequests(vhost)).
DefaultFilters().
MetricsPrefix(ENVOY_HTTPS_LISTENER).
RouteConfigName(path.Join("https", vhost)).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
Get()
}
fallbackCertFilter := envoyv2.HTTPConnectionManagerBuilder().
DefaultFilters().
MetricsPrefix(ENVOY_HTTPS_LISTENER).
RouteConfigName(ENVOY_FALLBACK_ROUTECONFIG).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
Get()
tests := map[string]struct {
ListenerConfig
fallbackCertificate *types.NamespacedName
objs []interface{}
want map[string]*envoy_api_v2.Listener
}{
"nothing": {
objs: nil,
want: map[string]*envoy_api_v2.Listener{},
},
"one http only ingress": {
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1beta1.IngressSpec{
Backend: backend("kuard", 8080),
},
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 8080,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"one http only httpproxy": {
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
},
Routes: []projcontour.Route{{
Conditions: []projcontour.MatchCondition{{
Prefix: "/",
}},
Services: []projcontour.Service{{
Name: "backend",
Port: 80,
}},
}},
},
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"simple ingress with secret": {
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: v1beta1.IngressSpec{
TLS: []v1beta1.IngressTLS{{
Hosts: []string{"whatever.example.com"},
SecretName: "secret",
}},
Rules: []v1beta1.IngressRule{{
Host: "whatever.example.com",
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{{
Backend: *backend("kuard", 8080),
}},
},
},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 8080,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"whatever.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("whatever.example.com")),
}},
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"multiple tls ingress with secrets should be sorted": {
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "sortedsecond",
Namespace: "default",
},
Spec: v1beta1.IngressSpec{
TLS: []v1beta1.IngressTLS{{
Hosts: []string{"sortedsecond.example.com"},
SecretName: "secret",
}},
Rules: []v1beta1.IngressRule{{
Host: "sortedsecond.example.com",
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{{
Backend: *backend("kuard", 8080),
}},
},
},
}},
},
},
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "sortedfirst",
Namespace: "default",
},
Spec: v1beta1.IngressSpec{
TLS: []v1beta1.IngressTLS{{
Hosts: []string{"sortedfirst.example.com"},
SecretName: "secret",
}},
Rules: []v1beta1.IngressRule{{
Host: "sortedfirst.example.com",
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{{
Backend: *backend("kuard", 8080),
}},
},
},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 8080,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"sortedfirst.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("sortedfirst.example.com")),
}, {
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"sortedsecond.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("sortedsecond.example.com")),
}},
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"simple ingress with missing secret": {
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: v1beta1.IngressSpec{
TLS: []v1beta1.IngressTLS{{
Hosts: []string{"whatever.example.com"},
SecretName: "missing",
}},
Rules: []v1beta1.IngressRule{{
Host: "whatever.example.com",
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{{
Backend: *backend("kuard", 8080),
}},
},
},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 8080,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"simple httpproxy with secret": {
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
TLS: &projcontour.TLS{
SecretName: "secret",
},
},
Routes: []projcontour.Route{{
Services: []projcontour.Service{{
Name: "backend",
Port: 80,
}},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"www.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("www.example.com")),
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"ingress with allow-http: false": {
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
Annotations: map[string]string{
"kubernetes.io/ingress.allow-http": "false",
},
},
Spec: v1beta1.IngressSpec{
Backend: backend("kuard", 8080),
},
},
},
want: map[string]*envoy_api_v2.Listener{},
},
"simple tls ingress with allow-http:false": {
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
Annotations: map[string]string{
"kubernetes.io/ingress.allow-http": "false",
},
},
Spec: v1beta1.IngressSpec{
TLS: []v1beta1.IngressTLS{{
Hosts: []string{"www.example.com"},
SecretName: "secret",
}},
Rules: []v1beta1.IngressRule{{
Host: "www.example.com",
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{{
Backend: *backend("kuard", 8080),
}},
},
},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 8080,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"www.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("www.example.com")),
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"http listener on non default port": { // issue 72
ListenerConfig: ListenerConfig{
HTTPAddress: "127.0.0.100",
HTTPPort: 9100,
HTTPSAddress: "127.0.0.200",
HTTPSPort: 9200,
},
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: v1beta1.IngressSpec{
TLS: []v1beta1.IngressTLS{{
Hosts: []string{"whatever.example.com"},
SecretName: "secret",
}},
Rules: []v1beta1.IngressRule{{
Host: "whatever.example.com",
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{{
Backend: *backend("kuard", 8080),
}},
},
},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 8080,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("127.0.0.100", 9100),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("127.0.0.200", 9200),
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"whatever.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("whatever.example.com")),
}},
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"use proxy proto": {
ListenerConfig: ListenerConfig{
UseProxyProto: true,
},
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: v1beta1.IngressSpec{
TLS: []v1beta1.IngressTLS{{
Hosts: []string{"whatever.example.com"},
SecretName: "secret",
}},
Rules: []v1beta1.IngressRule{{
Host: "whatever.example.com",
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{{
Backend: *backend("kuard", 8080),
}},
},
},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 8080,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.ProxyProtocol(),
),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.ProxyProtocol(),
envoyv2.TLSInspector(),
),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"whatever.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("whatever.example.com")),
}},
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"--envoy-http-access-log": {
ListenerConfig: ListenerConfig{
HTTPAccessLog: "/tmp/http_access.log",
HTTPSAccessLog: "/tmp/https_access.log",
},
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: v1beta1.IngressSpec{
TLS: []v1beta1.IngressTLS{{
Hosts: []string{"whatever.example.com"},
SecretName: "secret",
}},
Rules: []v1beta1.IngressRule{{
Host: "whatever.example.com",
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{{
Backend: *backend("kuard", 8080),
}},
},
},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 8080,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress(DEFAULT_HTTP_LISTENER_ADDRESS, DEFAULT_HTTP_LISTENER_PORT),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy("/tmp/http_access.log"), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress(DEFAULT_HTTPS_LISTENER_ADDRESS, DEFAULT_HTTPS_LISTENER_PORT),
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"whatever.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(envoyv2.HTTPConnectionManagerBuilder().
AddFilter(envoyv2.FilterMisdirectedRequests("whatever.example.com")).
DefaultFilters().
MetricsPrefix(ENVOY_HTTPS_LISTENER).
RouteConfigName(path.Join("https", "whatever.example.com")).
AccessLoggers(envoyv2.FileAccessLogEnvoy("/tmp/https_access.log")).
Get()),
}},
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"tls-min-protocol-version from config": {
ListenerConfig: ListenerConfig{
MinimumTLSVersion: envoy_api_v2_auth.TlsParameters_TLSv1_3,
},
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: v1beta1.IngressSpec{
TLS: []v1beta1.IngressTLS{{
Hosts: []string{"whatever.example.com"},
SecretName: "secret",
}},
Rules: []v1beta1.IngressRule{{
Host: "whatever.example.com",
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{{
Backend: *backend("kuard", 8080),
}},
},
},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 8080,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"whatever.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_3, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("whatever.example.com")),
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"tls-min-protocol-version from config overridden by annotation": {
ListenerConfig: ListenerConfig{
MinimumTLSVersion: envoy_api_v2_auth.TlsParameters_TLSv1_3,
},
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
Annotations: map[string]string{
"projectcontour.io/tls-minimum-protocol-version": "1.2",
},
},
Spec: v1beta1.IngressSpec{
TLS: []v1beta1.IngressTLS{{
Hosts: []string{"whatever.example.com"},
SecretName: "secret",
}},
Rules: []v1beta1.IngressRule{{
Host: "whatever.example.com",
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{{
Backend: *backend("kuard", 8080),
}},
},
},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 8080,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"whatever.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_3, "h2", "http/1.1"), // note, cannot downgrade from the configured version
Filters: envoyv2.Filters(httpsFilterFor("whatever.example.com")),
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"tls-min-protocol-version from config overridden by legacy annotation": {
ListenerConfig: ListenerConfig{
MinimumTLSVersion: envoy_api_v2_auth.TlsParameters_TLSv1_3,
},
objs: []interface{}{
&v1beta1.Ingress{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
Annotations: map[string]string{
"contour.heptio.com/tls-minimum-protocol-version": "1.2",
},
},
Spec: v1beta1.IngressSpec{
TLS: []v1beta1.IngressTLS{{
Hosts: []string{"whatever.example.com"},
SecretName: "secret",
}},
Rules: []v1beta1.IngressRule{{
Host: "whatever.example.com",
IngressRuleValue: v1beta1.IngressRuleValue{
HTTP: &v1beta1.HTTPIngressRuleValue{
Paths: []v1beta1.HTTPIngressPath{{
Backend: *backend("kuard", 8080),
}},
},
},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "kuard",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 8080,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"whatever.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_3, "h2", "http/1.1"), // note, cannot downgrade from the configured version
Filters: envoyv2.Filters(httpsFilterFor("whatever.example.com")),
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"tls-min-protocol-version from config overridden by httpproxy": {
ListenerConfig: ListenerConfig{
MinimumTLSVersion: envoy_api_v2_auth.TlsParameters_TLSv1_3,
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
TLS: &projcontour.TLS{
SecretName: "secret",
MinimumProtocolVersion: "1.2",
},
},
Routes: []projcontour.Route{{
Services: []projcontour.Service{{
Name: "backend",
Port: 80,
}},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"www.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_3, "h2", "http/1.1"), // note, cannot downgrade from the configured version
Filters: envoyv2.Filters(httpsFilterFor("www.example.com")),
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"httpproxy with fallback certificate": {
fallbackCertificate: &types.NamespacedName{
Name: "fallbacksecret",
Namespace: "default",
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
TLS: &projcontour.TLS{
SecretName: "secret",
EnableFallbackCertificate: true,
},
},
Routes: []projcontour.Route{
{
Services: []projcontour.Service{
{
Name: "backend",
Port: 80,
},
},
},
},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "fallbacksecret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"www.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("www.example.com")),
}, {
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
TransportProtocol: "tls",
},
TransportSocket: transportSocket("fallbacksecret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(fallbackCertFilter),
Name: "fallback-certificate",
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"multiple httpproxies with fallback certificate": {
fallbackCertificate: &types.NamespacedName{
Name: "fallbacksecret",
Namespace: "default",
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple2",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.another.com",
TLS: &projcontour.TLS{
SecretName: "secret",
EnableFallbackCertificate: true,
},
},
Routes: []projcontour.Route{
{
Services: []projcontour.Service{
{
Name: "backend",
Port: 80,
},
},
},
},
},
},
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
TLS: &projcontour.TLS{
SecretName: "secret",
EnableFallbackCertificate: true,
},
},
Routes: []projcontour.Route{
{
Services: []projcontour.Service{
{
Name: "backend",
Port: 80,
},
},
},
},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "fallbacksecret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{
{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"www.another.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("www.another.com")),
},
{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"www.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("www.example.com")),
},
{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
TransportProtocol: "tls",
},
TransportSocket: transportSocket("fallbacksecret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(fallbackCertFilter),
Name: "fallback-certificate",
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"httpproxy with fallback certificate - no cert passed": {
fallbackCertificate: &types.NamespacedName{
Name: "",
Namespace: "",
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
TLS: &projcontour.TLS{
SecretName: "secret",
EnableFallbackCertificate: true,
},
},
Routes: []projcontour.Route{
{
Services: []projcontour.Service{
{
Name: "backend",
Port: 80,
},
},
},
},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(),
},
"httpproxy with fallback certificate - cert passed but vhost not enabled": {
fallbackCertificate: &types.NamespacedName{
Name: "fallbackcert",
Namespace: "default",
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
TLS: &projcontour.TLS{
SecretName: "secret",
EnableFallbackCertificate: false,
},
},
Routes: []projcontour.Route{
{
Services: []projcontour.Service{
{
Name: "backend",
Port: 80,
},
},
},
},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManager(ENVOY_HTTP_LISTENER, envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG), 0)),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"www.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(httpsFilterFor("www.example.com")),
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"httpproxy with connection idle timeout set in visitor config": {
ListenerConfig: ListenerConfig{
ConnectionIdleTimeout: timeout.DurationSetting(90 * time.Second),
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
},
Routes: []projcontour.Route{{
Conditions: []projcontour.MatchCondition{{
Prefix: "/",
}},
Services: []projcontour.Service{{
Name: "backend",
Port: 80,
}},
}},
},
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(
envoyv2.HTTPConnectionManagerBuilder().
RouteConfigName(ENVOY_HTTP_LISTENER).
MetricsPrefix(ENVOY_HTTP_LISTENER).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
DefaultFilters().
ConnectionIdleTimeout(timeout.DurationSetting(90 * time.Second)).
Get(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"httpproxy with stream idle timeout set in visitor config": {
ListenerConfig: ListenerConfig{
StreamIdleTimeout: timeout.DurationSetting(90 * time.Second),
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
},
Routes: []projcontour.Route{{
Conditions: []projcontour.MatchCondition{{
Prefix: "/",
}},
Services: []projcontour.Service{{
Name: "backend",
Port: 80,
}},
}},
},
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(
envoyv2.HTTPConnectionManagerBuilder().
RouteConfigName(ENVOY_HTTP_LISTENER).
MetricsPrefix(ENVOY_HTTP_LISTENER).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
DefaultFilters().
StreamIdleTimeout(timeout.DurationSetting(90 * time.Second)).
Get(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"httpproxy with max connection duration set in visitor config": {
ListenerConfig: ListenerConfig{
MaxConnectionDuration: timeout.DurationSetting(90 * time.Second),
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
},
Routes: []projcontour.Route{{
Conditions: []projcontour.MatchCondition{{
Prefix: "/",
}},
Services: []projcontour.Service{{
Name: "backend",
Port: 80,
}},
}},
},
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(
envoyv2.HTTPConnectionManagerBuilder().
RouteConfigName(ENVOY_HTTP_LISTENER).
MetricsPrefix(ENVOY_HTTP_LISTENER).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
DefaultFilters().
MaxConnectionDuration(timeout.DurationSetting(90 * time.Second)).
Get(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"httpproxy with connection shutdown grace period set in visitor config": {
ListenerConfig: ListenerConfig{
ConnectionShutdownGracePeriod: timeout.DurationSetting(90 * time.Second),
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
},
Routes: []projcontour.Route{{
Conditions: []projcontour.MatchCondition{{
Prefix: "/",
}},
Services: []projcontour.Service{{
Name: "backend",
Port: 80,
}},
}},
},
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(
envoyv2.HTTPConnectionManagerBuilder().
RouteConfigName(ENVOY_HTTP_LISTENER).
MetricsPrefix(ENVOY_HTTP_LISTENER).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
DefaultFilters().
ConnectionShutdownGracePeriod(timeout.DurationSetting(90 * time.Second)).
Get(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"httpsproxy with secret with connection idle timeout set in visitor config": {
ListenerConfig: ListenerConfig{
ConnectionIdleTimeout: timeout.DurationSetting(90 * time.Second),
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
TLS: &projcontour.TLS{
SecretName: "secret",
},
},
Routes: []projcontour.Route{{
Services: []projcontour.Service{{
Name: "backend",
Port: 80,
}},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManagerBuilder().
RouteConfigName(ENVOY_HTTP_LISTENER).
MetricsPrefix(ENVOY_HTTP_LISTENER).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
DefaultFilters().
ConnectionIdleTimeout(timeout.DurationSetting(90 * time.Second)).
Get(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"www.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(envoyv2.HTTPConnectionManagerBuilder().
AddFilter(envoyv2.FilterMisdirectedRequests("www.example.com")).
DefaultFilters().
MetricsPrefix(ENVOY_HTTPS_LISTENER).
RouteConfigName(path.Join("https", "www.example.com")).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
ConnectionIdleTimeout(timeout.DurationSetting(90 * time.Second)).
Get()),
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"httpsproxy with secret with stream idle timeout set in visitor config": {
ListenerConfig: ListenerConfig{
StreamIdleTimeout: timeout.DurationSetting(90 * time.Second),
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
TLS: &projcontour.TLS{
SecretName: "secret",
},
},
Routes: []projcontour.Route{{
Services: []projcontour.Service{{
Name: "backend",
Port: 80,
}},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManagerBuilder().
RouteConfigName(ENVOY_HTTP_LISTENER).
MetricsPrefix(ENVOY_HTTP_LISTENER).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
DefaultFilters().
StreamIdleTimeout(timeout.DurationSetting(90 * time.Second)).
Get(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"www.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(envoyv2.HTTPConnectionManagerBuilder().
AddFilter(envoyv2.FilterMisdirectedRequests("www.example.com")).
DefaultFilters().
MetricsPrefix(ENVOY_HTTPS_LISTENER).
RouteConfigName(path.Join("https", "www.example.com")).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
StreamIdleTimeout(timeout.DurationSetting(90 * time.Second)).
Get()),
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"httpsproxy with secret with max connection duration set in visitor config": {
ListenerConfig: ListenerConfig{
MaxConnectionDuration: timeout.DurationSetting(90 * time.Second),
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
TLS: &projcontour.TLS{
SecretName: "secret",
},
},
Routes: []projcontour.Route{{
Services: []projcontour.Service{{
Name: "backend",
Port: 80,
}},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManagerBuilder().
RouteConfigName(ENVOY_HTTP_LISTENER).
MetricsPrefix(ENVOY_HTTP_LISTENER).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
DefaultFilters().
MaxConnectionDuration(timeout.DurationSetting(90 * time.Second)).
Get(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"www.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(envoyv2.HTTPConnectionManagerBuilder().
AddFilter(envoyv2.FilterMisdirectedRequests("www.example.com")).
DefaultFilters().
MetricsPrefix(ENVOY_HTTPS_LISTENER).
RouteConfigName(path.Join("https", "www.example.com")).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
MaxConnectionDuration(timeout.DurationSetting(90 * time.Second)).
Get()),
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
"httpsproxy with secret with connection shutdown grace period set in visitor config": {
ListenerConfig: ListenerConfig{
ConnectionShutdownGracePeriod: timeout.DurationSetting(90 * time.Second),
},
objs: []interface{}{
&projcontour.HTTPProxy{
ObjectMeta: metav1.ObjectMeta{
Name: "simple",
Namespace: "default",
},
Spec: projcontour.HTTPProxySpec{
VirtualHost: &projcontour.VirtualHost{
Fqdn: "www.example.com",
TLS: &projcontour.TLS{
SecretName: "secret",
},
},
Routes: []projcontour.Route{{
Services: []projcontour.Service{{
Name: "backend",
Port: 80,
}},
}},
},
},
&v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "secret",
Namespace: "default",
},
Type: "kubernetes.io/tls",
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
&v1.Service{
ObjectMeta: metav1.ObjectMeta{
Name: "backend",
Namespace: "default",
},
Spec: v1.ServiceSpec{
Ports: []v1.ServicePort{{
Name: "http",
Protocol: "TCP",
Port: 80,
}},
},
},
},
want: listenermap(&envoy_api_v2.Listener{
Name: ENVOY_HTTP_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8080),
FilterChains: envoyv2.FilterChains(envoyv2.HTTPConnectionManagerBuilder().
RouteConfigName(ENVOY_HTTP_LISTENER).
MetricsPrefix(ENVOY_HTTP_LISTENER).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
DefaultFilters().
ConnectionShutdownGracePeriod(timeout.DurationSetting(90 * time.Second)).
Get(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}, &envoy_api_v2.Listener{
Name: ENVOY_HTTPS_LISTENER,
Address: envoyv2.SocketAddress("0.0.0.0", 8443),
FilterChains: []*envoy_api_v2_listener.FilterChain{{
FilterChainMatch: &envoy_api_v2_listener.FilterChainMatch{
ServerNames: []string{"www.example.com"},
},
TransportSocket: transportSocket("secret", envoy_api_v2_auth.TlsParameters_TLSv1_1, "h2", "http/1.1"),
Filters: envoyv2.Filters(envoyv2.HTTPConnectionManagerBuilder().
AddFilter(envoyv2.FilterMisdirectedRequests("www.example.com")).
DefaultFilters().
MetricsPrefix(ENVOY_HTTPS_LISTENER).
RouteConfigName(path.Join("https", "www.example.com")).
AccessLoggers(envoyv2.FileAccessLogEnvoy(DEFAULT_HTTP_ACCESS_LOG)).
ConnectionShutdownGracePeriod(timeout.DurationSetting(90 * time.Second)).
Get()),
}},
ListenerFilters: envoyv2.ListenerFilters(
envoyv2.TLSInspector(),
),
SocketOptions: envoyv2.TCPKeepaliveSocketOptions(),
}),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
root := buildDAGFallback(t, tc.fallbackCertificate, tc.objs...)
got := visitListeners(root, &tc.ListenerConfig)
protobuf.ExpectEqual(t, tc.want, got)
})
}
}
func transportSocket(secretname string, tlsMinProtoVersion envoy_api_v2_auth.TlsParameters_TlsProtocol, alpnprotos ...string) *envoy_api_v2_core.TransportSocket {
secret := &dag.Secret{
Object: &v1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: secretname,
Namespace: "default",
},
Type: v1.SecretTypeTLS,
Data: secretdata(CERTIFICATE, RSA_PRIVATE_KEY),
},
}
return envoyv2.DownstreamTLSTransportSocket(
envoyv2.DownstreamTLSContext(secret, tlsMinProtoVersion, nil, alpnprotos...),
)
}
func listenermap(listeners ...*envoy_api_v2.Listener) map[string]*envoy_api_v2.Listener {
m := make(map[string]*envoy_api_v2.Listener)
for _, l := range listeners {
m[l.Name] = l
}
return m
}
|
{
"pile_set_name": "Github"
}
|
//@flow
import React, { Component } from "react";
import {
StyleSheet,
View,
ScrollView,
Text,
TouchableOpacity
} from "react-native";
import { withNavigation } from "react-navigation";
const styles = StyleSheet.create({
root: {
flex: 1,
backgroundColor: "#fff"
},
container: {
flexDirection: "column",
justifyContent: "center"
},
rendering: {
alignSelf: "center"
},
toolbox: {
flexDirection: "column"
},
toolboxTitle: {
padding: 0,
marginVertical: 4
},
field: {
flexDirection: "column",
paddingVertical: 5,
paddingHorizontal: 10
},
fieldValue: {
flexDirection: "row"
},
btn: {
flex: 1,
padding: 10,
alignItems: "center",
justifyContent: "center"
},
btnText: {
color: "#fff",
fontSize: 12
}
});
class NextButton extends Component {
props: {
navigation: *,
next: string
};
goToNext = () => {
this.props.navigation.replace(this.props.next);
};
render() {
return (
<TouchableOpacity style={styles.btn} onPress={this.goToNext}>
<Text style={styles.btnText}>NEXT</Text>
</TouchableOpacity>
);
}
}
export default (
{ Main, title, toolbox, noScrollView, ToolboxFooter, overrideStyles = {} },
id,
nextId
) =>
class extends React.Component {
static displayName = id;
static navigationOptions = ({ navigation }) => ({
title: id,
headerRight: nextId ? (
<NextButton next={nextId} navigation={navigation} />
) : null
// TODO: also could use renderRight to have bg modes, like in Atom image-viewer // renderRight: (route, props) => ...
});
state = {
...Main.defaultProps,
width: 0,
height: 0
};
onLayout = e => {
const { width, height } = e.nativeEvent.layout;
if (this.state.width !== width || this.state.height !== height) {
this.setState({
width,
height
});
}
};
render() {
const { state } = this;
const props = {
setToolState: this.setState,
...state
};
const { width, height } = props;
const renderingEl = (
<View style={styles.rendering}>
{width && height ? <Main {...props} /> : null}
</View>
);
const toolboxEl = (
<View style={[styles.toolbox, overrideStyles.toolbox]}>
{ToolboxFooter ? <ToolboxFooter {...props} /> : null}
{(toolbox || []).map((field, i) => (
<View key={i} style={[styles.field, overrideStyles.field]}>
{field.title ? (
<Text style={styles.toolboxTitle}>
{typeof field.title === "function"
? field.title(props[field.prop])
: field.title}
</Text>
) : null}
<View
key={i}
style={[styles.fieldValue, overrideStyles.fieldValue]}
>
{field.Editor ? (
<field.Editor
{...field}
value={props[field.prop]}
onChange={value => {
this.setState({
[field.prop]: value
});
}}
/>
) : null}
</View>
</View>
))}
</View>
);
if (noScrollView) {
return (
<View
onLayout={this.onLayout}
style={[styles.root, styles.container]}
>
{renderingEl}
{toolboxEl}
</View>
);
}
return (
<ScrollView
bounces={false}
style={styles.root}
contentContainerStyle={styles.container}
onLayout={this.onLayout}
>
{renderingEl}
{toolboxEl}
</ScrollView>
);
}
};
|
{
"pile_set_name": "Github"
}
|
title = Frequency Domain
|
{
"pile_set_name": "Github"
}
|
/* global describe,test,expect */
/* eslint-env jest */
import offset from '../src/offset'
describe('Testing offset', () => {
test('offset element', () => {
// create mock elements
const elementMock: any = {
getClientRects: () => [
{
left: 10,
right: 20,
top: 5,
bottom: 15
}
],
parentElement: () => 'fakeParent'
}
Object.defineProperty(window, 'pageXOffset', { value: 7, writable: false })
Object.defineProperty(window, 'pageYOffset', { value: 14, writable: false })
// run function
const offsetResults: any = offset(elementMock)
// Assertions
expect(offsetResults.left).toBe(17)
expect(offsetResults.right).toBe(27)
expect(offsetResults.top).toBe(19)
expect(offsetResults.bottom).toBe(29)
})
test('offset of element that is not in the dom', () => {
const div = window.document.createElement('div')
expect(() => { offset(div) }).toThrow('target element must be part of the dom')
})
})
|
{
"pile_set_name": "Github"
}
|
#pragma once
#define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的内容
// Windows 头文件
#include <windows.h>
|
{
"pile_set_name": "Github"
}
|
<?php
/**
* Deprecated. No longer needed.
*
* @package WordPress
*/
_deprecated_file( basename(__FILE__), '3.1.0', null, __( 'This file no longer needs to be included.' ) );
|
{
"pile_set_name": "Github"
}
|
#!/usr/local/plan9/bin/rc
if (! ~ $DEBUG '') flag x +
REVFLAG=''
if (~ $LPCLASS *reverse*) {
switch ($REVERSE) {
case '';
REVFLAG=1
case 1;
REVFLAG=''
}
}
if (! ~ $REVFLAG '')
postreverse
if (~ $NOHEAD '') {
DATE=`{date}
face='FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF'
facedom=`{awk '{ if(match("'$LPMACHID'", $1)) {print $2; exit}}' $PLAN9/face/.machinelist}
if (~ $#facedom 0) facedom=$LPMACHID
facefile=`{awk '/^'$facedom'\/'$LPUSERID' /{print $2}' $PLAN9/face/48x48x4/.dict}
facedepth=4
if (~ $#facefile 0) {
facefile=`{awk '/^'$facedom'\/'$LPUSERID' /{print $2}' $PLAN9/face/48x48x2/.dict}
facedepth=2
}
if (~ $#facefile 0) {
facefile=`{awk '/^'$facedom'\/'$LPUSERID' /{print $2}' $PLAN9/face/48x48x1/.dict}
facedepth=1
}
if (~ $#facefile 0) {facefile=u/unknown.1; facedepth=1}
facefile=$PLAN9/face/48x48x$facedepth/$facefile
if (! ~ $#facefile 0 1)
facefile=$facefile(1)
if (~ $#facefile 0 || ! test -f $facefile ) {facefile=$PLAN9/face/48x48x2/u/unknown.1; facedepth=2}
if (test -r $facefile ) {
switch($facedepth){
case 1 2
face=`{cat $facefile |
sed -e 's/0x//g' -e 's/, *//g' |
tr 0123456789abcdef fedcba9876543210 };
case 4
face=`{iconv -u -c k4 $facefile |
dd -bs 60 -skip 1 >[2]/dev/null |
xd -b | sed 's/^[^ ]+ //;s/ //g' }
}
}
}
# We have to make sure the face information is set before rc sees the HERE file
# so the cat has to be in a separate if statement. This is an rc bug.
if (~ $NOHEAD '') cat <<EOF
%!PS-Adobe-2.0 div 112 page header - research!pg
/banner {
/saveobj save def
erasepage initgraphics
/#copies 1 def
/inch {72 mul} bind def
/pageborder {
25 747 moveto
590 747 lineto
590 25 lineto
25 25 lineto
closepath
2 setlinewidth
0 setgray
stroke
} def
/topborder {
25 773 moveto
590 773 lineto
590 747 lineto
25 747 lineto
closepath
2 setlinewidth
0 setgray
stroke
} def
/toptext {
120 756 moveto
/Courier-Bold findfont 14 scalefont setfont
($LPUSERID $DATE) show
} def
/prface {
gsave
translate rotate scale
setgray
48 48 $facedepth [48 0 0 -48 0 48] {<$face>} image
grestore
} def
EOF
if (~ $NOHEAD '') switch ($LPCLASS) {
case *hp4simx*;
echo '
%% set the default papertray to be the lower tray for HP4siMX printers
statusdict begin defaultpapertray end 1 ne {
statusdict begin
1 setdefaultpapertray
end
} if'
}
if (~ $NOHEAD '') cat <<EOF
statusdict /setduplexmode known {statusdict begin false setduplexmode end} if
statusdict begin /manualfeed false def end
pageborder
topborder
toptext
0 14 14 0 94 752 prface
.3 180 180 -90 3.0 inch 10.2 inch prface
showpage
saveobj
restore
} bind def
banner
EOF
if (~ $REVFLAG '') cat
exit ''
|
{
"pile_set_name": "Github"
}
|
# rules for finding the Jack library
find_package(PkgConfig REQUIRED)
pkg_check_modules(PC_JACK jack)
find_path(JACK_INCLUDE_DIR jack/jack.h HINTS ${PC_JACK_INCLUDEDIR} ${PC_JACK_INCLUDE_DIRS})
find_library(JACK_LIBRARY NAMES jack HINTS ${PC_JACK_LIBDIR} ${PC_JACK_LIBRARY_DIRS})
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Jack DEFAULT_MSG JACK_LIBRARY JACK_INCLUDE_DIR)
mark_as_advanced(JACK_INCLUDE_DIR JACK_LIBRARY)
set(JACK_INCLUDE_DIRS ${JACK_INCLUDE_DIR})
set(JACK_LIBRARIES ${JACK_LIBRARY})
|
{
"pile_set_name": "Github"
}
|
/*
* Copyright © 2000 SuSE, Inc.
* Copyright © 2007 Red Hat, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of SuSE not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. SuSE makes no representations about the
* suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*
* SuSE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL SuSE
* BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "pixman-private.h"
#if defined(USE_MIPS_DSPR2) || defined(USE_LOONGSON_MMI)
#include <string.h>
#include <stdlib.h>
static pixman_bool_t
have_feature (const char *search_string)
{
#if defined (__linux__) /* linux ELF */
/* Simple detection of MIPS features at runtime for Linux.
* It is based on /proc/cpuinfo, which reveals hardware configuration
* to user-space applications. According to MIPS (early 2010), no similar
* facility is universally available on the MIPS architectures, so it's up
* to individual OSes to provide such.
*/
const char *file_name = "/proc/cpuinfo";
char cpuinfo_line[256];
FILE *f = NULL;
if ((f = fopen (file_name, "r")) == NULL)
return FALSE;
while (fgets (cpuinfo_line, sizeof (cpuinfo_line), f) != NULL)
{
if (strstr (cpuinfo_line, search_string) != NULL)
{
fclose (f);
return TRUE;
}
}
fclose (f);
#endif
/* Did not find string in the proc file, or not Linux ELF. */
return FALSE;
}
#endif
pixman_implementation_t *
_pixman_mips_get_implementations (pixman_implementation_t *imp)
{
#ifdef USE_LOONGSON_MMI
/* I really don't know if some Loongson CPUs don't have MMI. */
if (!_pixman_disabled ("loongson-mmi") && have_feature ("Loongson"))
imp = _pixman_implementation_create_mmx (imp);
#endif
#ifdef USE_MIPS_DSPR2
if (!_pixman_disabled ("mips-dspr2"))
{
int already_compiling_everything_for_dspr2 = 0;
#if defined(__mips_dsp) && (__mips_dsp_rev >= 2)
already_compiling_everything_for_dspr2 = 1;
#endif
if (already_compiling_everything_for_dspr2 ||
/* Only currently available MIPS core that supports DSPr2 is 74K. */
have_feature ("MIPS 74K"))
{
imp = _pixman_implementation_create_mips_dspr2 (imp);
}
}
#endif
return imp;
}
|
{
"pile_set_name": "Github"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.