repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
kovertopz/Paulscode-SoundSystem
src/main/java/de/jarnbjo/vorbis/Floor.java
5644
/* * $ProjectName$ * $ProjectRevision$ * ----------------------------------------------------------- * $Id: Floor.java,v 1.3 2003/04/10 19:49:04 jarnbjo Exp $ * ----------------------------------------------------------- * * $Author: jarnbjo $ * * Description: * * Copyright 2002-2003 Tor-Einar Jarnbjo * ----------------------------------------------------------- * * Change History * ----------------------------------------------------------- * $Log: Floor.java,v $ * Revision 1.3 2003/04/10 19:49:04 jarnbjo * no message * * Revision 1.2 2003/03/16 01:11:12 jarnbjo * no message * * */ package de.jarnbjo.vorbis; import java.io.IOException; import de.jarnbjo.util.io.BitInputStream; public abstract class Floor { public final static float[] DB_STATIC_TABLE={ 1.0649863e-07f, 1.1341951e-07f, 1.2079015e-07f, 1.2863978e-07f, 1.3699951e-07f, 1.4590251e-07f, 1.5538408e-07f, 1.6548181e-07f, 1.7623575e-07f, 1.8768855e-07f, 1.9988561e-07f, 2.128753e-07f, 2.2670913e-07f, 2.4144197e-07f, 2.5713223e-07f, 2.7384213e-07f, 2.9163793e-07f, 3.1059021e-07f, 3.3077411e-07f, 3.5226968e-07f, 3.7516214e-07f, 3.9954229e-07f, 4.2550680e-07f, 4.5315863e-07f, 4.8260743e-07f, 5.1396998e-07f, 5.4737065e-07f, 5.8294187e-07f, 6.2082472e-07f, 6.6116941e-07f, 7.0413592e-07f, 7.4989464e-07f, 7.9862701e-07f, 8.5052630e-07f, 9.0579828e-07f, 9.6466216e-07f, 1.0273513e-06f, 1.0941144e-06f, 1.1652161e-06f, 1.2409384e-06f, 1.3215816e-06f, 1.4074654e-06f, 1.4989305e-06f, 1.5963394e-06f, 1.7000785e-06f, 1.8105592e-06f, 1.9282195e-06f, 2.0535261e-06f, 2.1869758e-06f, 2.3290978e-06f, 2.4804557e-06f, 2.6416497e-06f, 2.8133190e-06f, 2.9961443e-06f, 3.1908506e-06f, 3.3982101e-06f, 3.6190449e-06f, 3.8542308e-06f, 4.1047004e-06f, 4.3714470e-06f, 4.6555282e-06f, 4.9580707e-06f, 5.2802740e-06f, 5.6234160e-06f, 5.9888572e-06f, 6.3780469e-06f, 6.7925283e-06f, 7.2339451e-06f, 7.7040476e-06f, 8.2047000e-06f, 8.7378876e-06f, 9.3057248e-06f, 9.9104632e-06f, 1.0554501e-05f, 1.1240392e-05f, 1.1970856e-05f, 1.2748789e-05f, 1.3577278e-05f, 1.4459606e-05f, 1.5399272e-05f, 1.6400004e-05f, 1.7465768e-05f, 1.8600792e-05f, 1.9809576e-05f, 2.1096914e-05f, 2.2467911e-05f, 2.3928002e-05f, 2.5482978e-05f, 2.7139006e-05f, 2.8902651e-05f, 3.0780908e-05f, 3.2781225e-05f, 3.4911534e-05f, 3.7180282e-05f, 3.9596466e-05f, 4.2169667e-05f, 4.4910090e-05f, 4.7828601e-05f, 5.0936773e-05f, 5.4246931e-05f, 5.7772202e-05f, 6.1526565e-05f, 6.5524908e-05f, 6.9783085e-05f, 7.4317983e-05f, 7.9147585e-05f, 8.4291040e-05f, 8.9768747e-05f, 9.5602426e-05f, 0.00010181521f, 0.00010843174f, 0.00011547824f, 0.00012298267f, 0.00013097477f, 0.00013948625f, 0.00014855085f, 0.00015820453f, 0.00016848555f, 0.00017943469f, 0.00019109536f, 0.00020351382f, 0.00021673929f, 0.00023082423f, 0.00024582449f, 0.00026179955f, 0.00027881276f, 0.00029693158f, 0.00031622787f, 0.00033677814f, 0.00035866388f, 0.00038197188f, 0.00040679456f, 0.00043323036f, 0.00046138411f, 0.00049136745f, 0.00052329927f, 0.00055730621f, 0.00059352311f, 0.00063209358f, 0.00067317058f, 0.00071691700f, 0.00076350630f, 0.00081312324f, 0.00086596457f, 0.00092223983f, 0.00098217216f, 0.0010459992f, 0.0011139742f, 0.0011863665f, 0.0012634633f, 0.0013455702f, 0.0014330129f, 0.0015261382f, 0.0016253153f, 0.0017309374f, 0.0018434235f, 0.0019632195f, 0.0020908006f, 0.0022266726f, 0.0023713743f, 0.0025254795f, 0.0026895994f, 0.0028643847f, 0.0030505286f, 0.0032487691f, 0.0034598925f, 0.0036847358f, 0.0039241906f, 0.0041792066f, 0.0044507950f, 0.0047400328f, 0.0050480668f, 0.0053761186f, 0.0057254891f, 0.0060975636f, 0.0064938176f, 0.0069158225f, 0.0073652516f, 0.0078438871f, 0.0083536271f, 0.0088964928f, 0.009474637f, 0.010090352f, 0.010746080f, 0.011444421f, 0.012188144f, 0.012980198f, 0.013823725f, 0.014722068f, 0.015678791f, 0.016697687f, 0.017782797f, 0.018938423f, 0.020169149f, 0.021479854f, 0.022875735f, 0.024362330f, 0.025945531f, 0.027631618f, 0.029427276f, 0.031339626f, 0.033376252f, 0.035545228f, 0.037855157f, 0.040315199f, 0.042935108f, 0.045725273f, 0.048696758f, 0.051861348f, 0.055231591f, 0.058820850f, 0.062643361f, 0.066714279f, 0.071049749f, 0.075666962f, 0.080584227f, 0.085821044f, 0.091398179f, 0.097337747f, 0.10366330f, 0.11039993f, 0.11757434f, 0.12521498f, 0.13335215f, 0.14201813f, 0.15124727f, 0.16107617f, 0.17154380f, 0.18269168f, 0.19456402f, 0.20720788f, 0.22067342f, 0.23501402f, 0.25028656f, 0.26655159f, 0.28387361f, 0.30232132f, 0.32196786f, 0.34289114f, 0.36517414f, 0.38890521f, 0.41417847f, 0.44109412f, 0.46975890f, 0.50028648f, 0.53279791f, 0.56742212f, 0.60429640f, 0.64356699f, 0.68538959f, 0.72993007f, 0.77736504f, 0.82788260f, 0.88168307f, 0.9389798f, 1.0f}; static Floor createInstance(BitInputStream source, SetupHeader header) throws VorbisFormatException, IOException { int type=source.getInt(16); switch(type) { case 0: return new Floor0(source, header); case 1: return new Floor1(source, header); default: throw new VorbisFormatException("Floor type "+type+" is not supported."); } } abstract int getType(); abstract Floor decodeFloor(VorbisStream vorbis, BitInputStream source) throws VorbisFormatException, IOException; abstract void computeFloor(float[] vector); }
bsd-3-clause
endlessm/chromium-browser
chrome/browser/ui/android/sms/sms_infobar_delegate.cc
2312
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/android/sms/sms_infobar_delegate.h" #include "base/check_op.h" #include "base/strings/utf_string_conversions.h" #include "build/build_config.h" #include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/android/android_theme_resources.h" #include "chrome/grit/generated_resources.h" #include "components/infobars/core/infobar.h" #include "components/url_formatter/elide_url.h" #include "content/public/browser/web_contents.h" #include "ui/base/l10n/l10n_util.h" #include "url/origin.h" SmsInfoBarDelegate::SmsInfoBarDelegate(const url::Origin& origin, const std::string& one_time_code, base::OnceClosure on_confirm, base::OnceClosure on_cancel) : ConfirmInfoBarDelegate(), origin_(origin), one_time_code_(one_time_code), on_confirm_(std::move(on_confirm)), on_cancel_(std::move(on_cancel)) {} SmsInfoBarDelegate::~SmsInfoBarDelegate() = default; infobars::InfoBarDelegate::InfoBarIdentifier SmsInfoBarDelegate::GetIdentifier() const { return SMS_RECEIVER_INFOBAR_DELEGATE; } int SmsInfoBarDelegate::GetIconId() const { return IDR_ANDROID_INFOBAR_PHONE_ICON; } base::string16 SmsInfoBarDelegate::GetMessageText() const { base::string16 origin = url_formatter::FormatOriginForSecurityDisplay( origin_, url_formatter::SchemeDisplay::OMIT_HTTP_AND_HTTPS); return l10n_util::GetStringFUTF16(IDS_SMS_INFOBAR_STATUS_SMS_RECEIVED, base::UTF8ToUTF16(one_time_code_), origin); } int SmsInfoBarDelegate::GetButtons() const { return BUTTON_OK; } base::string16 SmsInfoBarDelegate::GetButtonLabel(InfoBarButton button) const { DCHECK_EQ(BUTTON_OK, button); return l10n_util::GetStringUTF16(IDS_SMS_INFOBAR_BUTTON_OK); } bool SmsInfoBarDelegate::Accept() { std::move(on_confirm_).Run(); return true; } void SmsInfoBarDelegate::InfoBarDismissed() { std::move(on_cancel_).Run(); } base::string16 SmsInfoBarDelegate::GetTitle() const { return l10n_util::GetStringUTF16(IDS_SMS_INFOBAR_TITLE); }
bsd-3-clause
hung101/kbs
frontend/views/profil-pusat-latihan-sukan/_form.php
4239
<?php use kartik\helpers\Html; //use yii\widgets\ActiveForm; use kartik\widgets\ActiveForm; use kartik\builder\Form; use kartik\builder\FormGrid; use yii\helpers\ArrayHelper; use kartik\datecontrol\DateControl; use yii\web\Session; // table reference use app\models\RefSukan; // contant values use app\models\general\Placeholder; use app\models\general\GeneralLabel; use app\models\general\GeneralVariable; use app\models\general\GeneralMessage; use common\models\general\GeneralFunction; /* @var $this yii\web\View */ /* @var $model app\models\PengurusanProgramBinaanAtlet */ /* @var $form yii\widgets\ActiveForm */ // Session $session = new Session; $session->open(); if(isset($session['pengurusan_program_binaan_bahagian_id']) && $session['pengurusan_program_binaan_bahagian_id']){ if($session['pengurusan_program_binaan_bahagian_id'] === '1')//assume normal { $sukan_list = RefSukan::find()->where(['cacat' => 0, 'aktif' => 1])->all(); } else { $sukan_list = RefSukan::find()->where(['cacat' => 1, 'aktif' => 1])->all(); } } else { $sukan_list = RefSukan::find()->where(['aktif' => 1])->all(); } $session->close(); ?> <div class="bantuan-profil-pusat-latihan-sukan-form"> <p class="text-muted"><span style="color: red">*</span> <?= GeneralLabel::mandatoryField?></p> <?php $form = ActiveForm::begin(['type'=>ActiveForm::TYPE_VERTICAL, 'staticOnly'=>$readonly, 'id'=>$model->formName(), 'options' => ['enctype' => 'multipart/form-data']]); ?> <?php echo FormGrid::widget([ 'model' => $model, 'form' => $form, 'autoGenerateColumns' => true, 'rows' => [ [ 'columns'=>12, 'autoGenerateColumns'=>false, // override columns setting 'attributes' => [ 'sukan' => [ 'type'=>Form::INPUT_WIDGET, 'widgetClass'=>'\kartik\widgets\Select2', 'options'=>[ 'addon' => (isset(Yii::$app->user->identity->peranan_akses['Admin']['is_admin'])) ? [ 'append' => [ 'content' => Html::a(Html::icon('edit'), ['/ref-sukan/index'], ['class'=>'btn btn-success', 'target' => '_blank']), 'asButton' => true ] ] : null, 'data'=>ArrayHelper::map(GeneralFunction::getSukan(),'id', 'desc'), 'options' => ['placeholder' => Placeholder::sukan], 'pluginOptions' => [ 'allowClear' => true ],], 'columnOptions'=>['colspan'=>6]], ], ], ] ]); ?> <div class="form-group"> <?php if(!$readonly): ?> <?= Html::submitButton($model->isNewRecord ? GeneralLabel::create : GeneralLabel::update, ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary', 'data' => [ 'confirm' => GeneralMessage::confirmSave, ],]) ?> <?php endif; ?> </div> <?php ActiveForm::end(); ?> </div> <?php $script = <<< JS $('form#{$model->formName()}').on('beforeSubmit', function (e) { var form = $(this); // submit form $.ajax({ url: form.attr('action'), type: "POST", data: new FormData(this), contentType: false, cache: false, processData:false, success: function (response) { // do something with response if(response != 1){ $('#modalContent').html(response); } else { $(document).find('#modal').modal('hide'); form.trigger("reset"); $.pjax.defaults.timeout = 100000; $.pjax.reload({container:'#profilPusatLatihanSukanGrid'}); } } }); return false; }); JS; $this->registerJs($script); ?>
bsd-3-clause
adem-team/advanced
lukisongroup/dashboard/controllers/HrmAbsensiController.php
3117
<?php /** * NOTE: Nama Class harus diawali Hurup Besar * Server Linux : hurup besar/kecil bermasalah -case sensitif- * Server Windows : hurup besar/kecil tidak bermasalah * Author: -ptr.nov- */ namespace lukisongroup\dashboard\controllers; /* VARIABLE BASE YII2 Author: -YII2- */ use Yii; use yii\web\Controller; use yii\web\NotFoundHttpException; use yii\filters\VerbFilter; use lukisongroup\widget\models\Chat; use lukisongroup\widget\models\ChatSearch; use lukisongroup\widget\models\ChatroomSearch; class HrmAbsensiController extends Controller { public function behaviors() { return [ 'verbs' => [ 'class' => VerbFilter::className(['dashboard']), 'actions' => [ //'delete' => ['post'], 'save' => ['post'], ], ], ]; } /** * ACTION INDEX | Session Login * @author ptrnov <piter@lukison.com> * @since 1.1 */ public function beforeAction($action){ if (Yii::$app->user->isGuest) { Yii::$app->user->logout(); $this->redirect(array('/site/login')); // } // Check only when the user is logged in if (!Yii::$app->user->isGuest) { if (Yii::$app->session['userSessionTimeout']< time() ) { // timeout Yii::$app->user->logout(); $this->redirect(array('/site/login')); // } else { //Yii::$app->user->setState('userSessionTimeout', time() + Yii::app()->params['sessionTimeoutSeconds']) ; Yii::$app->session->set('userSessionTimeout', time() + Yii::$app->params['sessionTimeoutSeconds']); return true; } } else { return true; } } /** * ACTION INDEX */ public function actionIndex() { /* variable content View Employe Author: -ptr.nov- */ // $searchModel_Dept = new DeptSearch(); //$dataProvider_Dept = $searchModel_Dept->search(Yii::$app->request->queryParams); return $this->render('index'); } public function actionChat() { $searchmodel1 = new ChatroomSearch(); $dataprovider1 = $searchmodel1->search(Yii::$app->request->queryParams); $dataprovider1->pagination->pageSize=2; $searchModel1 = new ChatSearch(); $dataProvider1 = $searchModel1->searchonline(Yii::$app->request->queryParams); $dataProvider1->pagination->pageSize=2; $searchModel = new ChatSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); $dataProvider->pagination->pageSize=5; return $this->render('@lukisongroup/widget/views/chat/index',[ //'model' => $model, 'searchModel' => $searchModel, 'dataProvider' => $dataProvider, 'searchmodel1' => $searchmodel1, 'dataprovider1' => $dataprovider1, 'searchModel1' => $searchModel1, 'dataProvider1' => $dataProvider1, 'ctrl_chat'=>'hrd_personalia', ]); } }
bsd-3-clause
Dench/resistor
backend/views/layouts/main.php
1420
<?php use yii\helpers\Html; /* @var $this \yii\web\View */ /* @var $content string */ if (Yii::$app->controller->action->id === 'login') { /** * Do not use this code in your template. Remove it. * Instead, use the code $this->layout = '//main-login'; in your controller. */ echo $this->render( 'main-login', ['content' => $content] ); } else { $directoryAsset = Yii::$app->assetManager->getPublishedUrl('@vendor/almasaeed2010/adminlte/dist'); dmstr\web\AdminLteAsset::register($this); backend\assets\AppAsset::register($this); ?> <?php $this->beginPage() ?> <!DOCTYPE html> <html lang="<?= Yii::$app->language ?>"> <head> <meta charset="<?= Yii::$app->charset ?>"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <?= Html::csrfMetaTags() ?> <title><?= Html::encode($this->title) ?></title> <?php $this->head() ?> </head> <body class="hold-transition skin-blue sidebar-mini"> <?php $this->beginBody() ?> <div class="wrapper"> <?= $this->render( 'header.php', ['directoryAsset' => $directoryAsset] ) ?> <?= $this->render( 'left.php', ['directoryAsset' => $directoryAsset] ) ?> <?= $this->render( 'content.php', ['content' => $content, 'directoryAsset' => $directoryAsset] ) ?> </div> <?php $this->endBody() ?> </body> </html> <?php $this->endPage() ?> <?php } ?>
bsd-3-clause
axkibe/node-vtk
wrappers/8.1.1/vtkCommonCoreNodeJsInit.cc
8323
/* this file has been autogenerated by vtkNodeJsWrapInit */ /* editing this might proof futile */ #include <nan.h> #include "vtkAbstractArrayWrap.h" #include "vtkAnimationCueWrap.h" #include "vtkArrayWrap.h" #include "vtkArrayIteratorWrap.h" #include "vtkBitArrayWrap.h" #include "vtkBitArrayIteratorWrap.h" #include "vtkBoxMuellerRandomSequenceWrap.h" #include "vtkByteSwapWrap.h" #include "vtkCharArrayWrap.h" #include "vtkCollectionWrap.h" #include "vtkCollectionIteratorWrap.h" #include "vtkCommandWrap.h" #include "vtkConditionVariableWrap.h" #include "vtkCriticalSectionWrap.h" #include "vtkDataArrayCollectionWrap.h" #include "vtkDataArrayCollectionIteratorWrap.h" #include "vtkDataArrayWrap.h" #include "vtkDataArraySelectionWrap.h" #include "vtkDebugLeaksWrap.h" #include "vtkDoubleArrayWrap.h" #include "vtkDynamicLoaderWrap.h" #include "vtkFileOutputWindowWrap.h" #include "vtkFloatArrayWrap.h" #include "vtkGarbageCollectorWrap.h" #include "vtkGaussianRandomSequenceWrap.h" #include "vtkIdListCollectionWrap.h" #include "vtkIdListWrap.h" #include "vtkIdTypeArrayWrap.h" #include "vtkInformationWrap.h" #include "vtkInformationDataObjectKeyWrap.h" #include "vtkInformationDoubleKeyWrap.h" #include "vtkInformationDoubleVectorKeyWrap.h" #include "vtkInformationIdTypeKeyWrap.h" #include "vtkInformationInformationKeyWrap.h" #include "vtkInformationInformationVectorKeyWrap.h" #include "vtkInformationIntegerKeyWrap.h" #include "vtkInformationIntegerPointerKeyWrap.h" #include "vtkInformationIntegerVectorKeyWrap.h" #include "vtkInformationIteratorWrap.h" #include "vtkInformationKeyWrap.h" #include "vtkInformationKeyLookupWrap.h" #include "vtkInformationKeyVectorKeyWrap.h" #include "vtkInformationObjectBaseKeyWrap.h" #include "vtkInformationObjectBaseVectorKeyWrap.h" #include "vtkInformationRequestKeyWrap.h" #include "vtkInformationStringKeyWrap.h" #include "vtkInformationStringVectorKeyWrap.h" #include "vtkInformationUnsignedLongKeyWrap.h" #include "vtkInformationVariantKeyWrap.h" #include "vtkInformationVariantVectorKeyWrap.h" #include "vtkInformationVectorWrap.h" #include "vtkIntArrayWrap.h" #include "vtkLongArrayWrap.h" #include "vtkLongLongArrayWrap.h" #include "vtkLookupTableWrap.h" #include "vtkMathWrap.h" #include "vtkMersenneTwisterWrap.h" #include "vtkMinimalStandardRandomSequenceWrap.h" #include "vtkMultiThreaderWrap.h" #include "vtkMutexLockWrap.h" #include "vtkObjectBaseWrap.h" #include "vtkObjectWrap.h" #include "vtkObjectFactoryCollectionWrap.h" #include "vtkObjectFactoryWrap.h" #include "vtkOutputWindowWrap.h" #include "vtkOverrideInformationCollectionWrap.h" #include "vtkOverrideInformationWrap.h" #include "vtkPoints2DWrap.h" #include "vtkPointsWrap.h" #include "vtkPriorityQueueWrap.h" #include "vtkRandomSequenceWrap.h" #include "vtkReferenceCountWrap.h" #include "vtkScalarsToColorsWrap.h" #include "vtkShortArrayWrap.h" #include "vtkSignedCharArrayWrap.h" #include "vtkSortDataArrayWrap.h" #include "vtkStringArrayWrap.h" #include "vtkStringOutputWindowWrap.h" #include "vtkTimePointUtilityWrap.h" #include "vtkUnicodeStringArrayWrap.h" #include "vtkUnsignedCharArrayWrap.h" #include "vtkUnsignedIntArrayWrap.h" #include "vtkUnsignedLongArrayWrap.h" #include "vtkUnsignedLongLongArrayWrap.h" #include "vtkUnsignedShortArrayWrap.h" #include "vtkVariantArrayWrap.h" #include "vtkVersionWrap.h" #include "vtkVoidArrayWrap.h" #include "vtkWeakReferenceWrap.h" #include "vtkWindowWrap.h" #include "vtkXMLFileOutputWindowWrap.h" #include "vtkInstantiatorWrap.h" #include "vtkTypeInt8ArrayWrap.h" #include "vtkTypeInt16ArrayWrap.h" #include "vtkTypeInt32ArrayWrap.h" #include "vtkTypeInt64ArrayWrap.h" #include "vtkTypeUInt8ArrayWrap.h" #include "vtkTypeUInt16ArrayWrap.h" #include "vtkTypeUInt32ArrayWrap.h" #include "vtkTypeUInt64ArrayWrap.h" #include "vtkTypeFloat32ArrayWrap.h" #include "vtkTypeFloat64ArrayWrap.h" using namespace v8; extern void vtkCommonCoreNodeJsInit( v8::Local<v8::Object> exports ) { VtkAbstractArrayWrap::Init( exports ); VtkAnimationCueWrap::Init( exports ); VtkArrayWrap::Init( exports ); VtkArrayIteratorWrap::Init( exports ); VtkBitArrayWrap::Init( exports ); VtkBitArrayIteratorWrap::Init( exports ); VtkBoxMuellerRandomSequenceWrap::Init( exports ); VtkByteSwapWrap::Init( exports ); VtkCharArrayWrap::Init( exports ); VtkCollectionWrap::Init( exports ); VtkCollectionIteratorWrap::Init( exports ); VtkCommandWrap::Init( exports ); VtkConditionVariableWrap::Init( exports ); VtkCriticalSectionWrap::Init( exports ); VtkDataArrayCollectionWrap::Init( exports ); VtkDataArrayCollectionIteratorWrap::Init( exports ); VtkDataArrayWrap::Init( exports ); VtkDataArraySelectionWrap::Init( exports ); VtkDebugLeaksWrap::Init( exports ); VtkDoubleArrayWrap::Init( exports ); VtkDynamicLoaderWrap::Init( exports ); VtkFileOutputWindowWrap::Init( exports ); VtkFloatArrayWrap::Init( exports ); VtkGarbageCollectorWrap::Init( exports ); VtkGaussianRandomSequenceWrap::Init( exports ); VtkIdListCollectionWrap::Init( exports ); VtkIdListWrap::Init( exports ); VtkIdTypeArrayWrap::Init( exports ); VtkInformationWrap::Init( exports ); VtkInformationDataObjectKeyWrap::Init( exports ); VtkInformationDoubleKeyWrap::Init( exports ); VtkInformationDoubleVectorKeyWrap::Init( exports ); VtkInformationIdTypeKeyWrap::Init( exports ); VtkInformationInformationKeyWrap::Init( exports ); VtkInformationInformationVectorKeyWrap::Init( exports ); VtkInformationIntegerKeyWrap::Init( exports ); VtkInformationIntegerPointerKeyWrap::Init( exports ); VtkInformationIntegerVectorKeyWrap::Init( exports ); VtkInformationIteratorWrap::Init( exports ); VtkInformationKeyWrap::Init( exports ); VtkInformationKeyLookupWrap::Init( exports ); VtkInformationKeyVectorKeyWrap::Init( exports ); VtkInformationObjectBaseKeyWrap::Init( exports ); VtkInformationObjectBaseVectorKeyWrap::Init( exports ); VtkInformationRequestKeyWrap::Init( exports ); VtkInformationStringKeyWrap::Init( exports ); VtkInformationStringVectorKeyWrap::Init( exports ); VtkInformationUnsignedLongKeyWrap::Init( exports ); VtkInformationVariantKeyWrap::Init( exports ); VtkInformationVariantVectorKeyWrap::Init( exports ); VtkInformationVectorWrap::Init( exports ); VtkIntArrayWrap::Init( exports ); VtkLongArrayWrap::Init( exports ); VtkLongLongArrayWrap::Init( exports ); VtkLookupTableWrap::Init( exports ); VtkMathWrap::Init( exports ); VtkMersenneTwisterWrap::Init( exports ); VtkMinimalStandardRandomSequenceWrap::Init( exports ); VtkMultiThreaderWrap::Init( exports ); VtkMutexLockWrap::Init( exports ); VtkObjectBaseWrap::Init( exports ); VtkObjectWrap::Init( exports ); VtkObjectFactoryCollectionWrap::Init( exports ); VtkObjectFactoryWrap::Init( exports ); VtkOutputWindowWrap::Init( exports ); VtkOverrideInformationCollectionWrap::Init( exports ); VtkOverrideInformationWrap::Init( exports ); VtkPoints2DWrap::Init( exports ); VtkPointsWrap::Init( exports ); VtkPriorityQueueWrap::Init( exports ); VtkRandomSequenceWrap::Init( exports ); VtkReferenceCountWrap::Init( exports ); VtkScalarsToColorsWrap::Init( exports ); VtkShortArrayWrap::Init( exports ); VtkSignedCharArrayWrap::Init( exports ); VtkSortDataArrayWrap::Init( exports ); VtkStringArrayWrap::Init( exports ); VtkStringOutputWindowWrap::Init( exports ); VtkTimePointUtilityWrap::Init( exports ); VtkUnicodeStringArrayWrap::Init( exports ); VtkUnsignedCharArrayWrap::Init( exports ); VtkUnsignedIntArrayWrap::Init( exports ); VtkUnsignedLongArrayWrap::Init( exports ); VtkUnsignedLongLongArrayWrap::Init( exports ); VtkUnsignedShortArrayWrap::Init( exports ); VtkVariantArrayWrap::Init( exports ); VtkVersionWrap::Init( exports ); VtkVoidArrayWrap::Init( exports ); VtkWeakReferenceWrap::Init( exports ); VtkWindowWrap::Init( exports ); VtkXMLFileOutputWindowWrap::Init( exports ); VtkInstantiatorWrap::Init( exports ); VtkTypeInt8ArrayWrap::Init( exports ); VtkTypeInt16ArrayWrap::Init( exports ); VtkTypeInt32ArrayWrap::Init( exports ); VtkTypeInt64ArrayWrap::Init( exports ); VtkTypeUInt8ArrayWrap::Init( exports ); VtkTypeUInt16ArrayWrap::Init( exports ); VtkTypeUInt32ArrayWrap::Init( exports ); VtkTypeUInt64ArrayWrap::Init( exports ); VtkTypeFloat32ArrayWrap::Init( exports ); VtkTypeFloat64ArrayWrap::Init( exports ); }
bsd-3-clause
EvgSp/yupi.loc
protected/modules/delivery/messages/ru/delivery.php
2982
<?php return [ '*unknown*' => '*неизвестно*', 'Active' => 'Активен', 'Add delivery and close' => 'Добавить доставку и закрыть', 'Add delivery and continue' => 'Добавить доставку и продолжить', 'are required' => 'обязательны.', 'Available from' => 'Доступна от', 'Create delivery' => 'Добавить способ доставки', 'Creating' => 'Добавление', 'creating' => 'добавление', 'Delete delivery' => 'Удалить способ доставки', 'Delivery lists' => 'Список способов доставки', 'Delivery method' => 'Способ доставки', 'Delivery methods - creating' => 'Способы доставки - добавление', 'Delivery methods - edition' => 'Способы доставки - редактирование', 'Delivery methods - manage' => 'Способы доставки - управление', 'Delivery methods - view' => 'Способы доставки - просмотр', 'Delivery methods' => 'Способы доставки', 'Delivery module' => 'Модуль для создания способов доставки в интернет-магазине', 'Delivery' => 'Доставка', 'Description' => 'Описание', 'Do you really want to remove this delivery?' => 'Вы уверены, что хотите удалить способ доставки?', 'Edition' => 'Изменение', 'Fields with' => 'Поля, отмеченные', 'Free from' => 'Бесплатна от', 'Manage delivery methods' => 'Управление способами доставки', 'Manage' => 'Управление', 'manage' => 'управление', 'Not active' => 'Неактивен', 'Page not found!' => 'Запрошенная страница не найдена!', 'Payment methods' => 'Способы оплаты', 'Position' => 'Позиция', 'Price' => 'Стоимость', 'Record created!' => 'Запись добавлена!', 'Record removed!' => 'Запись удалена!', 'Record updated!' => 'Запись изменена!', 'Save delivery and close' => 'Сохранить доставку и закрыть', 'Save delivery and continue' => 'Сохранить доставку и продолжить', 'Separate payment' => 'Оплачивается отдельно', 'Status' => 'Статус', 'Store' => 'Магазин', 'Title' => 'Название', 'Unknown request. Don\'t repeat it please!' => 'Неверный запрос. Пожалуйста, больше не повторяйте такие запросы!', 'Update delivery' => 'Редактировать способ доставки', 'View delivery' => 'Просмотр способа доставки', ];
bsd-3-clause
EddyBeaupre/Renci.SshNet
Common/ObjectIdentifier.cs
770
using System; namespace Renci.SshNet.Common { /// <summary> /// Describes object identifier for DER encoding /// </summary> public struct ObjectIdentifier { /// <summary> /// Gets the object identifier. /// </summary> public ulong[] Identifiers { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="ObjectIdentifier"/> class. /// </summary> /// <param name="identifiers">The identifiers.</param> public ObjectIdentifier(params ulong[] identifiers) : this() { if (identifiers.Length < 2) throw new ArgumentException("identifiers"); this.Identifiers = identifiers; } } }
bsd-3-clause
jamesslock/james.sl
src/components/organisms/Nav/Nav.js
918
import React, { Component } from "react" import { Link } from 'react-router' import styled from 'styled-components' // Import Atom Components import Hamburger from '../../atoms/Hamburger/Hamburger.js' import Container from '../../atoms/Container/Container.js' import AnimateFadeIn from '../../atoms/Animate/AnimateFadeIn.js' const Header = styled.header` padding: 20px 0; position: fixed; width: 100%; z-index: 120; `; const MenuTrigger = styled(Hamburger)` float: right; position: relative; z-index: 90; `; const HomeLink = styled(Link)` float: left; `; export default class Nav extends Component { render() { return ( <Header> <Container full> <AnimateFadeIn> <HomeLink to="/">JSL</HomeLink> <MenuTrigger /> </AnimateFadeIn> </Container> </Header> ) } }
bsd-3-clause
jMonkeyEngine/sdk
jme3-scenecomposer/src/com/jme3/gde/scenecomposer/tools/shortcuts/ShortcutManager.java
12227
/* * Copyright (c) 2009-2020 jMonkeyEngine * 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 'jMonkeyEngine' 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. */ package com.jme3.gde.scenecomposer.tools.shortcuts; import com.jme3.input.KeyInput; import com.jme3.input.event.KeyInputEvent; import com.jme3.math.Vector3f; import java.util.ArrayList; import org.openide.util.lookup.ServiceProvider; /** * The Class providing hotkeys to move, rotate and scale, much like in blender. * @author dokthar */ @ServiceProvider(service = ShortcutManager.class) public class ShortcutManager { private ShortcutTool currentShortcut; private final ArrayList<ShortcutTool> shortcutList; private boolean ctrlDown = false; private boolean shiftDown = false; private boolean altDown = false; public ShortcutManager() { shortcutList = new ArrayList<>(); shortcutList.add(new MoveShortcut()); shortcutList.add(new RotateShortcut()); shortcutList.add(new ScaleShortcut()); shortcutList.add(new DuplicateShortcut()); shortcutList.add(new DeleteShortcut()); } /* Methodes */ /** * This MUST be called by the shortcut tool once the modifications are done. */ public void terminate() { currentShortcut = null; } /** * * @return true if a shortCutTool is active, else return false. */ public boolean isActive() { return currentShortcut != null; } /** * @return the ctrlDown */ public boolean isCtrlDown() { return ctrlDown; } /** * @return the shiftDown */ public boolean isShiftDown() { return shiftDown; } /** * @return the altDown */ public boolean isAltDown() { return altDown; } /** * Set the current shortcut to <code>shortcut</code>. cancel the current * shortcut if it was still active * * @param shortcut the ShortCutTool to set */ public void setShortCut(ShortcutTool shortcut) { if (isActive()) { currentShortcut.cancel(); } currentShortcut = shortcut; } /** * Get the shortcut that can be enable with the given kei, the current * shortcut cannot be enable twice. This also check for command key used to * provide isCtrlDown(), isShiftDown() and isAltDown(). * * @param kie the KeyInputEvent * @return the activable shortcut else return null */ public ShortcutTool getActivableShortcut(KeyInputEvent kie) { if (checkCommandeKey(kie)) { return null; } for (ShortcutTool s : shortcutList) { if (s != currentShortcut) { if (s.isActivableBy(kie)) { return s; } } } return null; } /** * * @return the current active shortcut */ public ShortcutTool getActiveShortcut() { return currentShortcut; } /** * * @param kie the KeyInputEvent * @return true if the given Kei can enable a sortcut, else false */ public boolean canActivateShortcut(KeyInputEvent kie) { return getActivableShortcut(kie) != null; } /** * Set the current shortcut with the shortcut one that can be enable with * the given key * * @param kie the KeyInputEvent * @return true is the shortcut changed, else false */ public boolean activateShortcut(KeyInputEvent kie) { ShortcutTool newShortcut = getActivableShortcut(kie); if (newShortcut != null) { currentShortcut = newShortcut; } return newShortcut != null; } public void setActiveShortcut(ShortcutTool newShortcut) { if (newShortcut != null && newShortcut != currentShortcut) { currentShortcut = newShortcut; } } /** * This should be called to trigger the currentShortcut.keyPressed() method. * This also check for command key used to provide isCtrlDown(), * isShiftDown() and isAltDown(). * * @param kie */ public void doKeyPressed(KeyInputEvent kie) { if (checkCommandeKey(kie)) { //return; } else if (isActive()) { currentShortcut.keyPressed(kie); } } private boolean checkCommandeKey(KeyInputEvent kie) { if (isCtrlKey(kie)) { ctrlDown = kie.isPressed(); return true; } else if (isAltKey(kie)) { altDown = kie.isPressed(); return true; } else if (isShiftKey(kie)) { shiftDown = kie.isPressed(); return true; } return false; } /* STATIC */ /** * * @param kie * @return true if the given kie is KEY_RETURN */ public static boolean isEnterKey(KeyInputEvent kie) { return (kie.getKeyCode() == KeyInput.KEY_RETURN); } /** * * @param kie * @return true if the given kie is KEY_ESCAPE */ public static boolean isEscKey(KeyInputEvent kie) { return (kie.getKeyCode() == KeyInput.KEY_ESCAPE); } /** * * @param kie * @return true if the given kie is KEY_LCONTROL || KEY_RCONTROL */ public static boolean isCtrlKey(KeyInputEvent kie) { return (kie.getKeyCode() == KeyInput.KEY_LCONTROL || kie.getKeyCode() == KeyInput.KEY_RCONTROL); } /** * * @param kie * @return true if the given kie is KEY_LSHIFT || KEY_RSHIFT */ public static boolean isShiftKey(KeyInputEvent kie) { return (kie.getKeyCode() == KeyInput.KEY_LSHIFT || kie.getKeyCode() == KeyInput.KEY_RSHIFT); } /** * * @param kie * @return true if the given kie is KEY_LMENU || KEY_RMENU */ public static boolean isAltKey(KeyInputEvent kie) { return (kie.getKeyCode() == KeyInput.KEY_LMENU || kie.getKeyCode() == KeyInput.KEY_RMENU); } /** * * @param kie * @return */ public static boolean isNumberKey(KeyInputEvent kie) { switch (kie.getKeyCode()) { case KeyInput.KEY_MINUS: case KeyInput.KEY_0: case KeyInput.KEY_1: case KeyInput.KEY_2: case KeyInput.KEY_3: case KeyInput.KEY_4: case KeyInput.KEY_5: case KeyInput.KEY_6: case KeyInput.KEY_7: case KeyInput.KEY_8: case KeyInput.KEY_9: case KeyInput.KEY_NUMPAD0: case KeyInput.KEY_NUMPAD1: case KeyInput.KEY_NUMPAD2: case KeyInput.KEY_NUMPAD3: case KeyInput.KEY_NUMPAD4: case KeyInput.KEY_NUMPAD5: case KeyInput.KEY_NUMPAD6: case KeyInput.KEY_NUMPAD7: case KeyInput.KEY_NUMPAD8: case KeyInput.KEY_NUMPAD9: case KeyInput.KEY_PERIOD: return true; } return false; } /** * store the number kie into the numberBuilder * * @param kie the KeiInputEvent to be handled as a number. * @param numberBuilder the number builder that will be modified ! */ public static void setNumberKey(KeyInputEvent kie, StringBuilder numberBuilder) { switch (kie.getKeyCode()) { case KeyInput.KEY_MINUS: if (numberBuilder.length() > 0) { if (numberBuilder.charAt(0) == '-') { numberBuilder.replace(0, 1, ""); } else { numberBuilder.insert(0, '-'); } } else { numberBuilder.append('-'); } break; case KeyInput.KEY_0: case KeyInput.KEY_1: case KeyInput.KEY_2: case KeyInput.KEY_3: case KeyInput.KEY_4: case KeyInput.KEY_5: case KeyInput.KEY_6: case KeyInput.KEY_7: case KeyInput.KEY_8: case KeyInput.KEY_9: case KeyInput.KEY_NUMPAD0: case KeyInput.KEY_NUMPAD1: case KeyInput.KEY_NUMPAD2: case KeyInput.KEY_NUMPAD3: case KeyInput.KEY_NUMPAD4: case KeyInput.KEY_NUMPAD5: case KeyInput.KEY_NUMPAD6: case KeyInput.KEY_NUMPAD7: case KeyInput.KEY_NUMPAD8: case KeyInput.KEY_NUMPAD9: numberBuilder.append(kie.getKeyChar()); break; case KeyInput.KEY_PERIOD: if (numberBuilder.indexOf(".") == -1) { // if it doesn't exist yet if (numberBuilder.length() == 0 || (numberBuilder.length() == 1 && numberBuilder.charAt(0) == '-')) { numberBuilder.append("0."); } else { numberBuilder.append("."); } } break; } } /** * * @param numberBuilder the StringBuilder storing the float number * @return the float value created from the given StringBuilder */ public static float getNumberKey(StringBuilder numberBuilder) { if (numberBuilder.length() == 0) { return 0f; } else { try { return Float.parseFloat(numberBuilder.toString()); } catch (NumberFormatException nfe) { return 0f; // Don't crash on invalid input } } } /** * Test if the given kie can be handled as en axis input by the getAxisKey() * method. * * @param kie the KeyInputEvent to test * @return true is the kie can be handled as an axis input, else false */ public static boolean isAxisKey(KeyInputEvent kie) { switch (kie.getKeyCode()) { case KeyInput.KEY_X: case KeyInput.KEY_Y: case KeyInput.KEY_Z: return true; } return false; } /** * Handle the Kie as an axis input : return a Vector3f from the kie keyCode. * * @param kie the KeyInputEvent to handle as an Axis * @return UNIT_X for 'x', UNIT_Y for 'y' and UNIT_Z for 'z' kie. */ public static Vector3f getAxisKey(KeyInputEvent kie) { Vector3f result = Vector3f.ZERO; switch (kie.getKeyCode()) { case KeyInput.KEY_X: result = Vector3f.UNIT_X; break; case KeyInput.KEY_Y: result = Vector3f.UNIT_Y; break; case KeyInput.KEY_Z: result = Vector3f.UNIT_Z; break; } return result; } }
bsd-3-clause
111WARLOCK111/Caznowl-Cube-Zombie
fCraft/Utils/BitMap3D.cs
6789
using System; using System.Collections; using System.Collections.Generic; using JetBrains.Annotations; namespace fCraft { /// <summary> Specialized set data structure. Holds 1 bit of information per coordinate, /// with an easy way to enumerate all set coords. Used by /Fill3D and related commands. </summary> public class BitMap3D : IEnumerable<Vector3I> { const int BitCoordMask = 31; readonly uint[] store; readonly Vector3I offset, dimensions; int version; /// <summary> Number of set bits within this BitMap. </summary> public int Count { get; private set; } /// <summary> Bounding box within which coordinates are stored. </summary> public BoundingBox Bounds { get; set; } /// <summary> Creates a new 3D bit array, within the given bounds. </summary> /// <param name="bounds"> Bounding box inside which the coordinates are stored. </param> public BitMap3D( BoundingBox bounds ) { dimensions = bounds.Dimensions; offset = bounds.MinVertex; Bounds = bounds; // round capacity up to nearest multiple of 32 int bitCapacity = (int)((bounds.Volume + sizeof( uint ) - 1) & (uint.MaxValue ^ BitCoordMask)); int intCapacity = bitCapacity/sizeof( uint ); store = new uint[intCapacity]; } void Index( Vector3I coord, out int intIndex, out uint bitMask ) { Vector3I localCoord = coord - offset; int index = (localCoord.Z*dimensions.Y + localCoord.Y)*dimensions.X + localCoord.X; intIndex = (index >> 5); int bitIndex = index & BitCoordMask; bitMask = 1u << bitIndex; } /// <summary> Gets value of a bit at given coordinate. </summary> /// <exception cref="ArgumentOutOfRangeException"> Given coordinate is outside the bounds. </exception> public bool Get( Vector3I coord ) { if( !Bounds.Contains( coord ) ) throw new ArgumentOutOfRangeException( "coord" ); int intIndex; uint bitMask; Index( coord, out intIndex, out bitMask ); return (store[intIndex] & bitMask) != 0; } /// <summary> Sets bit at given coordinate to 1. </summary> /// <exception cref="ArgumentOutOfRangeException"> Given coordinate is outside the bounds. </exception> public bool Set( Vector3I coord ) { if( !Bounds.Contains( coord ) ) throw new ArgumentOutOfRangeException( "coord" ); int intIndex; uint bitMask; Index( coord, out intIndex, out bitMask ); bool oldVal = (store[intIndex] & bitMask) != 0; if( !oldVal ) { store[intIndex] |= bitMask; Count++; version++; } return oldVal; } /// <summary> Sets bit at given coordinate to 0. </summary> /// <exception cref="ArgumentOutOfRangeException"> Given coordinate is outside the bounds. </exception> public bool Unset( Vector3I coord ) { if( !Bounds.Contains( coord ) ) throw new ArgumentOutOfRangeException( "coord" ); int intIndex; uint bitMask; Index( coord, out intIndex, out bitMask ); bool oldVal = (store[intIndex] & bitMask) != 0; if( oldVal ) { store[intIndex] &= ~bitMask; Count--; version++; } return oldVal; } /// <summary> Resets all bits to 0. </summary> public void Clear() { Array.Clear( store, 0, store.Length ); Count = 0; version++; } #region Implementation of IEnumerable public IEnumerator<Vector3I> GetEnumerator() { return new BitMap3DEnumerator( this ); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } class BitMap3DEnumerator : IEnumerator<Vector3I> { readonly BitMap3D bitmap; readonly int dimX, dimY, dimZ; int startingVersion, x, y, z, intIndex, bitIndex; uint storeInt; public Vector3I Current { get; private set; } object IEnumerator.Current { get { return Current; } } public BitMap3DEnumerator( [NotNull] BitMap3D bitmap ) { if( bitmap == null ) { throw new ArgumentNullException( "bitmap" ); } this.bitmap = bitmap; startingVersion = bitmap.version; dimX = bitmap.dimensions.X; dimY = bitmap.dimensions.Y; dimZ = bitmap.dimensions.Z; Reset(); } public bool MoveNext() { // make sure bitmap has not been modified since Reset() if( bitmap.version != startingVersion ) { throw new InvalidOperationException( "BitMap3D modified while enumerating." ); } while( true ) { // advance real coordinates x++; if( x >= dimX ) { x = 0; y++; if( y >= dimY ) { y = 0; z++; if( z >= dimZ ) { return false; } } } // advance array coordinates bitIndex++; if( bitIndex > 31 ) { bitIndex = 0; intIndex++; if( intIndex >= bitmap.store.Length ) { return false; } storeInt = bitmap.store[intIndex]; } // check if current bit is set uint bitMask = 1u << bitIndex; if( (storeInt & bitMask) != 0 ) { Current = new Vector3I( x, y, z ) + bitmap.offset; return true; } } } public void Reset() { intIndex = 0; bitIndex = -1; startingVersion = bitmap.version; storeInt = bitmap.store[0]; x = -1; y = 0; z = 0; } public void Dispose() {} } #endregion } }
bsd-3-clause
Sharykhin/yii-box
modules/backend/modules/pages/views/default/index.php
455
<div class="pages-default-index"> <h1><?= $this->context->action->uniqueId ?></h1> <p> This is the view content for action "<?= $this->context->action->id ?>". The action belongs to the controller "<?= get_class($this->context) ?>" in the "<?= $this->context->module->id ?>" module. </p> <p> You may customize this page by editing the following file:<br> <code><?= __FILE__ ?></code> </p> </div>
bsd-3-clause
bosiam/textwizard
views/layouts/main.php
2643
<?php use yii\helpers\Html; use yii\bootstrap\Nav; use yii\bootstrap\NavBar; use yii\widgets\Breadcrumbs; use app\assets\AppAsset; /* @var $this \yii\web\View */ /* @var $content string */ AppAsset::register($this); ?> <?php $this->beginPage() ?> <!DOCTYPE html> <html lang="<?= Yii::$app->language ?>"> <head> <meta charset="<?= Yii::$app->charset ?>"/> <meta name="viewport" content="width=device-width, initial-scale=1"> <?= Html::csrfMetaTags() ?> <title><?= Html::encode($this->title) ?></title> <?php $this->head() ?> </head> <body> <?php $this->beginBody() ?> <div class="wrap"> <?php NavBar::begin([ 'brandLabel' => 'My Company', 'brandUrl' => Yii::$app->homeUrl, 'options' => [ 'class' => 'navbar-inverse navbar-fixed-top', ], ]); echo Nav::widget([ 'options' => ['class' => 'navbar-nav'], 'items' => [ ['label' => 'Home', 'url' => ['/site/index']], ['label' => 'About', 'url' => ['/site/about']], ['options' => ['class'=>'dropdown'],'label' => 'Contact', 'url' => ['/site/contact']], [ 'label' => 'Dropdown', 'items' => [ ['label' => 'Level 1 - Dropdown A', 'url' => '#'], '<li class="divider"></li>', '<li class="dropdown-header">Dropdown Header</li>', ['label' => 'Level 1 - Dropdown B', 'url' => '#'], ], ], Yii::$app->user->isGuest ? ['label' => 'Login', 'url' => ['/site/login']] : ['label' => 'Logout (' . Yii::$app->user->identity->username . ')', 'url' => ['/site/logout'], 'linkOptions' => ['data-method' => 'post']], ], ]); NavBar::end(); ?> <div class="container"> <?= Breadcrumbs::widget([ 'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [], ]) ?> <?= $content ?> </div> </div> <footer class="footer"> <div class="container"> <p class="pull-left">&copy; My Company <?= date('Y') ?></p> <p class="pull-right"><?= Yii::powered() ?></p> </div> </footer> <?php $this->endBody() ?> </body> </html> <?php $this->endPage() ?>
bsd-3-clause
OstapHEP/ostap
source/src/Ostap.cpp
454
// Include files // ============================================================================ // Ostap // ============================================================================ #include "Ostap/Ostap.h" // ============================================================================ // The END // ============================================================================
bsd-3-clause
cybergarage/round-cc
src/round/Client.cpp
877
/****************************************************************** * * Round for C++ * * Copyright (C) Satoshi Konno 2015 * * This is licensed under BSD-style license, see file COPYING. * ******************************************************************/ #include <round/Client.h> Round::Client::Client() { setFinderEnabled(true); this->finder.addObserver(this); } Round::Client::~Client() { Error error; stop(&error); } bool Round::Client::start(Error *error) { if (finderEnabled()) { if (!this->finder.start(error)) return false; } return true; } bool Round::Client::stop(Error *error) { if (finderEnabled()) { if (!this->finder.stop(error)) return false; } return true; } bool Round::Client::search(Error *error) { if (finderEnabled()) { if (!this->finder.search(error)) return false; } return true; }
bsd-3-clause
rerobins/rhobot_framework
test/components/scheduler/promises/test_2_2_6_1.py
5735
""" 2.2.6: `then` may be called multiple times on the same promise. https://github.com/promises-aplus/promises-tests/blob/2.1.1/lib/tests/2.2.6.js """ import mock from test.components.scheduler.promises.helpers import generate_fulfilled_test_case other = {'other': 'other'} sentinel = {'sentinel': 'sentinel'} sentinel2 = {'sentinel2': 'sentinel2'} sentinel3 = {'sentinel3': 'sentinel3'} dummy = {'dummy': 'dummy'} def multiple_boring_tests(test_case, promise, done): handler1 = mock.MagicMock(return_value=other) handler2 = mock.MagicMock(return_value=other) handler3 = mock.MagicMock(return_value=other) cancel = mock.MagicMock() def final_fulfilled(argument): test_case.assertEqual(argument, sentinel) handler1.assert_called_once_with(sentinel) handler2.assert_called_once_with(sentinel) handler3.assert_called_once_with(sentinel) cancel.assert_not_called() done() promise.then(handler1, cancel) promise.then(handler2, cancel) promise.then(handler3, cancel) promise.then(final_fulfilled, None) def multiple_one_throws(test_case, promise, done): handler1 = mock.MagicMock(return_value=other) handler2 = mock.MagicMock(side_effect=AttributeError()) handler3 = mock.MagicMock(return_value=other) cancel = mock.MagicMock() def final_fulfilled(argument): test_case.assertEqual(argument, sentinel) handler1.assert_called_once_with(sentinel) handler2.assert_called_once_with(sentinel) handler3.assert_called_once_with(sentinel) cancel.assert_not_called() done() promise.then(handler1, cancel) promise.then(handler2, cancel) promise.then(handler3, cancel) promise.then(final_fulfilled, None) def multiple_branching_chains_each_with_own_value(test_case, promise, done): test_case.session['semiDone'] = 0 def semidone(): test_case.session['semiDone'] += 1 if test_case.session['semiDone'] == 3: done() def branch01(value): return sentinel def branch01_final(value): test_case.assertIs(value, sentinel) semidone() branch02_error = TypeError() def branch02(value): raise branch02_error def branch02_final(value): test_case.assertIs(value, branch02_error) semidone() def branch03(value): return sentinel3 def branch03_final(value): test_case.assertIs(value, sentinel3) semidone() promise.then(branch01).then(branch01_final) promise.then(branch02).then(None, branch02_final) promise.then(branch03).then(branch03_final) def on_fulfilled_handlers_called_in_original_order(test_case, promise, done): handler_mock = mock.MagicMock(**{'handler01.return_value': sentinel, 'handler02.return_value': sentinel2, 'handler03.return_value': sentinel3}) promise.then(handler_mock.handler01) promise.then(handler_mock.handler02) promise.then(handler_mock.handler03) def test_handlers(value): test_case.assertIs(dummy, value) method_calls = [a[0] for a in handler_mock.method_calls] test_case.assertEquals(['handler01', 'handler02', 'handler03'], method_calls) done() promise.then(test_handlers) def order_manipulated_in_a_promise(test_case, promise, done): handler_mock = mock.MagicMock(**{'handler01.return_value': sentinel, 'handler02.return_value': sentinel2, 'handler03.return_value': sentinel3}) def inject_handler_during_execution(value): handler_mock.handler01() promise.then(handler_mock.handler03) promise.then(inject_handler_during_execution) promise.then(handler_mock.handler02) def test_handlers(): method_calls = [a[0] for a in handler_mock.method_calls] test_case.assertEquals(['handler01', 'handler02', 'handler03'], method_calls) done() def schedule_test(value): test_case.scheduler.schedule_task(test_handlers, 0.015) promise.then(schedule_test) MultipleBoringTestCases = generate_fulfilled_test_case(method=multiple_boring_tests, value=sentinel, module=__name__, name='MultipleBoringTestCases') MultipleOneThrowsTestCases = generate_fulfilled_test_case(method=multiple_one_throws, value=sentinel, module=__name__, name='MultipleOneThrowsTestCases') MultipleBranchingTestCases = generate_fulfilled_test_case(method=multiple_branching_chains_each_with_own_value, value=dummy, module=__name__, name='MultipleBranchingTestCases') FulfilledHandlersInOrder = generate_fulfilled_test_case(method=on_fulfilled_handlers_called_in_original_order, value=dummy, module=__name__, name='FulfilledHandlersInOrder') OrderManipulatedInPromise = generate_fulfilled_test_case(method=order_manipulated_in_a_promise, value=dummy, module=__name__, name='OrderManipulatedInPromise')
bsd-3-clause
apa-narola/yiibasic2.0
vendor/yiisoft/extensions.php
1133
<?php $vendorDir = dirname(__DIR__); return array ( 'yiisoft/yii2-swiftmailer' => array ( 'name' => 'yiisoft/yii2-swiftmailer', 'version' => '2.0.0.0-beta', 'alias' => array ( '@yii/swiftmailer' => $vendorDir . '/yiisoft/yii2-swiftmailer', ), ), 'yiisoft/yii2-codeception' => array ( 'name' => 'yiisoft/yii2-codeception', 'version' => '2.0.0.0-beta', 'alias' => array ( '@yii/codeception' => $vendorDir . '/yiisoft/yii2-codeception', ), ), 'yiisoft/yii2-bootstrap' => array ( 'name' => 'yiisoft/yii2-bootstrap', 'version' => '2.0.0.0-beta', 'alias' => array ( '@yii/bootstrap' => $vendorDir . '/yiisoft/yii2-bootstrap', ), ), 'yiisoft/yii2-debug' => array ( 'name' => 'yiisoft/yii2-debug', 'version' => '2.0.0.0-beta', 'alias' => array ( '@yii/debug' => $vendorDir . '/yiisoft/yii2-debug', ), ), 'yiisoft/yii2-gii' => array ( 'name' => 'yiisoft/yii2-gii', 'version' => '2.0.0.0-beta', 'alias' => array ( '@yii/gii' => $vendorDir . '/yiisoft/yii2-gii', ), ), );
bsd-3-clause
scalameta/scalameta
semanticdb/metacp/src/main/scala/scala/meta/internal/javacp/asm/MethodSignatureVisitor.scala
1289
package scala.meta.internal.javacp.asm import scala.meta.internal.javacp._ import scala.tools.asm.signature.SignatureVisitor class MethodSignatureVisitor extends TypedSignatureVisitor[MethodSignature] with TypeParametersVisitor { val params = List.newBuilder[JavaTypeSignatureVisitor] val returnType = new JavaTypeSignatureVisitor(false) val throws = List.newBuilder[ReferenceTypeSignatureVisitor] override def result(): MethodSignature = { val tparams = super.typeParametersResult() MethodSignature( tparams, params.result().map(_.result()), returnType.result(), throws.result().map(_.result().get).map { case cts: ClassTypeSignature => ThrowsSignature.ClassType(cts) case tvs: TypeVariableSignature => ThrowsSignature.TypeVariable(tvs) case els => throw new IllegalArgumentException(s"Expected ThrowsSignature, obtained $els") } ) } override def visitParameterType: SignatureVisitor = { val visitor = new JavaTypeSignatureVisitor(false) params += visitor visitor } override def visitReturnType: SignatureVisitor = { returnType } override def visitExceptionType: SignatureVisitor = { val visitor = new ReferenceTypeSignatureVisitor throws += visitor visitor } }
bsd-3-clause
NCIP/cagrid2
cagrid-gridgrouper/cagrid-gridgrouper-api/src/main/java/org/cagrid/gridgrouper/model/StemPrivilege.java
4799
package org.cagrid.gridgrouper.model; import java.io.Serializable; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for StemPrivilege complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="StemPrivilege"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="StemName" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="PrivilegeType" type="{http://cagrid.nci.nih.gov/1/GridGrouper}StemPrivilegeType"/> * &lt;element name="Subject" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="ImplementationClass" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="IsRevokable" type="{http://www.w3.org/2001/XMLSchema}boolean"/> * &lt;element name="Owner" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "StemPrivilege", propOrder = { "stemName", "privilegeType", "subject", "implementationClass", "isRevokable", "owner" }) public class StemPrivilege implements Serializable { @XmlElement(name = "StemName", required = true) protected String stemName; @XmlElement(name = "PrivilegeType", required = true) protected StemPrivilegeType privilegeType; @XmlElement(name = "Subject", required = true) protected String subject; @XmlElement(name = "ImplementationClass", required = true) protected String implementationClass; @XmlElement(name = "IsRevokable") protected boolean isRevokable; @XmlElement(name = "Owner", required = true) protected String owner; /** * Gets the value of the stemName property. * * @return * possible object is * {@link String } * */ public String getStemName() { return stemName; } /** * Sets the value of the stemName property. * * @param value * allowed object is * {@link String } * */ public void setStemName(String value) { this.stemName = value; } /** * Gets the value of the privilegeType property. * * @return * possible object is * {@link StemPrivilegeType } * */ public StemPrivilegeType getPrivilegeType() { return privilegeType; } /** * Sets the value of the privilegeType property. * * @param value * allowed object is * {@link StemPrivilegeType } * */ public void setPrivilegeType(StemPrivilegeType value) { this.privilegeType = value; } /** * Gets the value of the subject property. * * @return * possible object is * {@link String } * */ public String getSubject() { return subject; } /** * Sets the value of the subject property. * * @param value * allowed object is * {@link String } * */ public void setSubject(String value) { this.subject = value; } /** * Gets the value of the implementationClass property. * * @return * possible object is * {@link String } * */ public String getImplementationClass() { return implementationClass; } /** * Sets the value of the implementationClass property. * * @param value * allowed object is * {@link String } * */ public void setImplementationClass(String value) { this.implementationClass = value; } /** * Gets the value of the isRevokable property. * */ public boolean isIsRevokable() { return isRevokable; } /** * Sets the value of the isRevokable property. * */ public void setIsRevokable(boolean value) { this.isRevokable = value; } /** * Gets the value of the owner property. * * @return * possible object is * {@link String } * */ public String getOwner() { return owner; } /** * Sets the value of the owner property. * * @param value * allowed object is * {@link String } * */ public void setOwner(String value) { this.owner = value; } }
bsd-3-clause
NIAEFEUP/Kommando
viewer/Kinect/Kinect/Gestures/KinectGesture.cs
4293
using Microsoft.Kinect; using System; namespace Kinect.Gestures { /// <summary> /// This class describes and analyzes complex gestures. /// </summary> public class KinectGesture { protected IKinectGestureFrame[] gestureFrames; protected KinectGestureType gestureType; private int currentFrameCount; private int currentFrameIndex; private bool gesturePaused; private int pausedFrameCount; /// <summary> /// Creates a new KinectGesture instance. /// </summary> /// <param name="type">Type of the recognizable gesture</param> /// <param name="gestureFrames">Sequence of frames that represent the gesture</param> public KinectGesture(KinectGestureType type, IKinectGestureFrame[] gestureFrames) { this.gestureType = type; this.gestureFrames = gestureFrames; this.currentFrameIndex = 0; this.currentFrameCount = 0; this.pausedFrameCount = 0; this.gesturePaused = false; } /// <summary> /// Event that triggers when a gesture is recognized. Propagates the callback /// to the gesture controller. /// </summary> public event EventHandler<KinectGestureEventArgs> KinectGestureRecognized; /// <summary> /// Resets the gesture state. /// </summary> public void ResetGesture() { this.currentFrameIndex = 0; this.currentFrameCount = 0; this.pausedFrameCount = 5; this.gesturePaused = true; } /// <summary> /// Updates the gesture state. If a gesture is successfully recognized /// an event is triggered. /// </summary> /// <param name="skeleton">Skeleton to analyze</param> public void UpdateGesture(Skeleton skeleton) { // Checks if the enough time between active frame checks // has passed, unpausing them if if true. if (this.gesturePaused) { if (this.currentFrameCount == this.pausedFrameCount) { this.gesturePaused = false; } this.currentFrameCount++; } // Compares the skeleton data with the current frame. KinectGestureResult result = this.gestureFrames[this.currentFrameIndex].ProcessFrame(skeleton); // In case of a successful recognition, moves on to the next frame if there's any, // otherwise triggers the recognized gesture event. if (result == KinectGestureResult.Success) { if (this.currentFrameIndex + 1 < this.gestureFrames.Length) { this.currentFrameIndex++; this.currentFrameCount = 0; this.pausedFrameCount = 10; this.gesturePaused = true; } else { // Triggers any registered event if (this.KinectGestureRecognized != null) { KinectGestureEventArgs args = new KinectGestureEventArgs(this.gestureType, skeleton.TrackingId); this.KinectGestureRecognized(this, args); } // Resets the gesture state. this.ResetGesture(); } } // If the gesture recognition failed beyond recovery, or the gesture is being // processed for to long, the gesture state is reseted. else if (result == KinectGestureResult.Fail || this.currentFrameCount == 50) { this.currentFrameIndex = 0; this.currentFrameCount = 0; this.pausedFrameCount = 5; this.gesturePaused = true; } // If the gesture recognition was inconclusive and there's still // time to wait, the gesture waits for the next frame. else { this.currentFrameCount++; this.pausedFrameCount = 5; this.gesturePaused = true; } } } }
bsd-3-clause
sssilver/angler
rod/rod/model/company.py
709
import sqlalchemy.schema import sqlalchemy.types import rod.model class Company(rod.model.db.Model, rod.model.PersistentMixin): __tablename__ = 'company' id = sqlalchemy.schema.Column(sqlalchemy.types.Integer, primary_key=True) title = sqlalchemy.schema.Column(sqlalchemy.types.Text) # Contact person contact_name = sqlalchemy.schema.Column(sqlalchemy.types.Text) contact_email = sqlalchemy.schema.Column(sqlalchemy.types.Text) contact_phone = sqlalchemy.schema.Column(sqlalchemy.types.Text) contact_position = sqlalchemy.schema.Column(sqlalchemy.types.Text) # Corporate balance balance = sqlalchemy.schema.Column(sqlalchemy.types.Numeric(scale=2), default=0.00)
bsd-3-clause
youtube/cobalt
third_party/llvm-project/clang/lib/Sema/SemaLookup.cpp
198982
//===--------------------- SemaLookup.cpp - Name Lookup ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements name lookup for C, C++, Objective-C, and // Objective-C++. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclLookups.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/LangOptions.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/ModuleLoader.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Overload.h" #include "clang/Sema/Scope.h" #include "clang/Sema/ScopeInfo.h" #include "clang/Sema/Sema.h" #include "clang/Sema/SemaInternal.h" #include "clang/Sema/TemplateDeduction.h" #include "clang/Sema/TypoCorrection.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallPtrSet.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/ADT/edit_distance.h" #include "llvm/Support/ErrorHandling.h" #include <algorithm> #include <iterator> #include <list> #include <set> #include <utility> #include <vector> using namespace clang; using namespace sema; namespace { class UnqualUsingEntry { const DeclContext *Nominated; const DeclContext *CommonAncestor; public: UnqualUsingEntry(const DeclContext *Nominated, const DeclContext *CommonAncestor) : Nominated(Nominated), CommonAncestor(CommonAncestor) { } const DeclContext *getCommonAncestor() const { return CommonAncestor; } const DeclContext *getNominatedNamespace() const { return Nominated; } // Sort by the pointer value of the common ancestor. struct Comparator { bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) { return L.getCommonAncestor() < R.getCommonAncestor(); } bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) { return E.getCommonAncestor() < DC; } bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) { return DC < E.getCommonAncestor(); } }; }; /// A collection of using directives, as used by C++ unqualified /// lookup. class UnqualUsingDirectiveSet { Sema &SemaRef; typedef SmallVector<UnqualUsingEntry, 8> ListTy; ListTy list; llvm::SmallPtrSet<DeclContext*, 8> visited; public: UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {} void visitScopeChain(Scope *S, Scope *InnermostFileScope) { // C++ [namespace.udir]p1: // During unqualified name lookup, the names appear as if they // were declared in the nearest enclosing namespace which contains // both the using-directive and the nominated namespace. DeclContext *InnermostFileDC = InnermostFileScope->getEntity(); assert(InnermostFileDC && InnermostFileDC->isFileContext()); for (; S; S = S->getParent()) { // C++ [namespace.udir]p1: // A using-directive shall not appear in class scope, but may // appear in namespace scope or in block scope. DeclContext *Ctx = S->getEntity(); if (Ctx && Ctx->isFileContext()) { visit(Ctx, Ctx); } else if (!Ctx || Ctx->isFunctionOrMethod()) { for (auto *I : S->using_directives()) if (SemaRef.isVisible(I)) visit(I, InnermostFileDC); } } } // Visits a context and collect all of its using directives // recursively. Treats all using directives as if they were // declared in the context. // // A given context is only every visited once, so it is important // that contexts be visited from the inside out in order to get // the effective DCs right. void visit(DeclContext *DC, DeclContext *EffectiveDC) { if (!visited.insert(DC).second) return; addUsingDirectives(DC, EffectiveDC); } // Visits a using directive and collects all of its using // directives recursively. Treats all using directives as if they // were declared in the effective DC. void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { DeclContext *NS = UD->getNominatedNamespace(); if (!visited.insert(NS).second) return; addUsingDirective(UD, EffectiveDC); addUsingDirectives(NS, EffectiveDC); } // Adds all the using directives in a context (and those nominated // by its using directives, transitively) as if they appeared in // the given effective context. void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) { SmallVector<DeclContext*, 4> queue; while (true) { for (auto UD : DC->using_directives()) { DeclContext *NS = UD->getNominatedNamespace(); if (SemaRef.isVisible(UD) && visited.insert(NS).second) { addUsingDirective(UD, EffectiveDC); queue.push_back(NS); } } if (queue.empty()) return; DC = queue.pop_back_val(); } } // Add a using directive as if it had been declared in the given // context. This helps implement C++ [namespace.udir]p3: // The using-directive is transitive: if a scope contains a // using-directive that nominates a second namespace that itself // contains using-directives, the effect is as if the // using-directives from the second namespace also appeared in // the first. void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) { // Find the common ancestor between the effective context and // the nominated namespace. DeclContext *Common = UD->getNominatedNamespace(); while (!Common->Encloses(EffectiveDC)) Common = Common->getParent(); Common = Common->getPrimaryContext(); list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common)); } void done() { llvm::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator()); } typedef ListTy::const_iterator const_iterator; const_iterator begin() const { return list.begin(); } const_iterator end() const { return list.end(); } llvm::iterator_range<const_iterator> getNamespacesFor(DeclContext *DC) const { return llvm::make_range(std::equal_range(begin(), end(), DC->getPrimaryContext(), UnqualUsingEntry::Comparator())); } }; } // end anonymous namespace // Retrieve the set of identifier namespaces that correspond to a // specific kind of name lookup. static inline unsigned getIDNS(Sema::LookupNameKind NameKind, bool CPlusPlus, bool Redeclaration) { unsigned IDNS = 0; switch (NameKind) { case Sema::LookupObjCImplicitSelfParam: case Sema::LookupOrdinaryName: case Sema::LookupRedeclarationWithLinkage: case Sema::LookupLocalFriendName: IDNS = Decl::IDNS_Ordinary; if (CPlusPlus) { IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace; if (Redeclaration) IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend; } if (Redeclaration) IDNS |= Decl::IDNS_LocalExtern; break; case Sema::LookupOperatorName: // Operator lookup is its own crazy thing; it is not the same // as (e.g.) looking up an operator name for redeclaration. assert(!Redeclaration && "cannot do redeclaration operator lookup"); IDNS = Decl::IDNS_NonMemberOperator; break; case Sema::LookupTagName: if (CPlusPlus) { IDNS = Decl::IDNS_Type; // When looking for a redeclaration of a tag name, we add: // 1) TagFriend to find undeclared friend decls // 2) Namespace because they can't "overload" with tag decls. // 3) Tag because it includes class templates, which can't // "overload" with tag decls. if (Redeclaration) IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace; } else { IDNS = Decl::IDNS_Tag; } break; case Sema::LookupLabel: IDNS = Decl::IDNS_Label; break; case Sema::LookupMemberName: IDNS = Decl::IDNS_Member; if (CPlusPlus) IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary; break; case Sema::LookupNestedNameSpecifierName: IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace; break; case Sema::LookupNamespaceName: IDNS = Decl::IDNS_Namespace; break; case Sema::LookupUsingDeclName: assert(Redeclaration && "should only be used for redecl lookup"); IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend | Decl::IDNS_LocalExtern; break; case Sema::LookupObjCProtocolName: IDNS = Decl::IDNS_ObjCProtocol; break; case Sema::LookupOMPReductionName: IDNS = Decl::IDNS_OMPReduction; break; case Sema::LookupAnyName: IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol | Decl::IDNS_Type; break; } return IDNS; } void LookupResult::configure() { IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus, isForRedeclaration()); // If we're looking for one of the allocation or deallocation // operators, make sure that the implicitly-declared new and delete // operators can be found. switch (NameInfo.getName().getCXXOverloadedOperator()) { case OO_New: case OO_Delete: case OO_Array_New: case OO_Array_Delete: getSema().DeclareGlobalNewDelete(); break; default: break; } // Compiler builtins are always visible, regardless of where they end // up being declared. if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) { if (unsigned BuiltinID = Id->getBuiltinID()) { if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) AllowHidden = true; } } } bool LookupResult::sanity() const { // This function is never called by NDEBUG builds. assert(ResultKind != NotFound || Decls.size() == 0); assert(ResultKind != Found || Decls.size() == 1); assert(ResultKind != FoundOverloaded || Decls.size() > 1 || (Decls.size() == 1 && isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl()))); assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved()); assert(ResultKind != Ambiguous || Decls.size() > 1 || (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects || Ambiguity == AmbiguousBaseSubobjectTypes))); assert((Paths != nullptr) == (ResultKind == Ambiguous && (Ambiguity == AmbiguousBaseSubobjectTypes || Ambiguity == AmbiguousBaseSubobjects))); return true; } // Necessary because CXXBasePaths is not complete in Sema.h void LookupResult::deletePaths(CXXBasePaths *Paths) { delete Paths; } /// Get a representative context for a declaration such that two declarations /// will have the same context if they were found within the same scope. static DeclContext *getContextForScopeMatching(Decl *D) { // For function-local declarations, use that function as the context. This // doesn't account for scopes within the function; the caller must deal with // those. DeclContext *DC = D->getLexicalDeclContext(); if (DC->isFunctionOrMethod()) return DC; // Otherwise, look at the semantic context of the declaration. The // declaration must have been found there. return D->getDeclContext()->getRedeclContext(); } /// Determine whether \p D is a better lookup result than \p Existing, /// given that they declare the same entity. static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind, NamedDecl *D, NamedDecl *Existing) { // When looking up redeclarations of a using declaration, prefer a using // shadow declaration over any other declaration of the same entity. if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) && !isa<UsingShadowDecl>(Existing)) return true; auto *DUnderlying = D->getUnderlyingDecl(); auto *EUnderlying = Existing->getUnderlyingDecl(); // If they have different underlying declarations, prefer a typedef over the // original type (this happens when two type declarations denote the same // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef // might carry additional semantic information, such as an alignment override. // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag // declaration over a typedef. if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) { assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying)); bool HaveTag = isa<TagDecl>(EUnderlying); bool WantTag = Kind == Sema::LookupTagName; return HaveTag != WantTag; } // Pick the function with more default arguments. // FIXME: In the presence of ambiguous default arguments, we should keep both, // so we can diagnose the ambiguity if the default argument is needed. // See C++ [over.match.best]p3. if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) { auto *EFD = cast<FunctionDecl>(EUnderlying); unsigned DMin = DFD->getMinRequiredArguments(); unsigned EMin = EFD->getMinRequiredArguments(); // If D has more default arguments, it is preferred. if (DMin != EMin) return DMin < EMin; // FIXME: When we track visibility for default function arguments, check // that we pick the declaration with more visible default arguments. } // Pick the template with more default template arguments. if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) { auto *ETD = cast<TemplateDecl>(EUnderlying); unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments(); unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments(); // If D has more default arguments, it is preferred. Note that default // arguments (and their visibility) is monotonically increasing across the // redeclaration chain, so this is a quick proxy for "is more recent". if (DMin != EMin) return DMin < EMin; // If D has more *visible* default arguments, it is preferred. Note, an // earlier default argument being visible does not imply that a later // default argument is visible, so we can't just check the first one. for (unsigned I = DMin, N = DTD->getTemplateParameters()->size(); I != N; ++I) { if (!S.hasVisibleDefaultArgument( ETD->getTemplateParameters()->getParam(I)) && S.hasVisibleDefaultArgument( DTD->getTemplateParameters()->getParam(I))) return true; } } // VarDecl can have incomplete array types, prefer the one with more complete // array type. if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) { VarDecl *EVD = cast<VarDecl>(EUnderlying); if (EVD->getType()->isIncompleteType() && !DVD->getType()->isIncompleteType()) { // Prefer the decl with a more complete type if visible. return S.isVisible(DVD); } return false; // Avoid picking up a newer decl, just because it was newer. } // For most kinds of declaration, it doesn't really matter which one we pick. if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) { // If the existing declaration is hidden, prefer the new one. Otherwise, // keep what we've got. return !S.isVisible(Existing); } // Pick the newer declaration; it might have a more precise type. for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev; Prev = Prev->getPreviousDecl()) if (Prev == EUnderlying) return true; return false; } /// Determine whether \p D can hide a tag declaration. static bool canHideTag(NamedDecl *D) { // C++ [basic.scope.declarative]p4: // Given a set of declarations in a single declarative region [...] // exactly one declaration shall declare a class name or enumeration name // that is not a typedef name and the other declarations shall all refer to // the same variable, non-static data member, or enumerator, or all refer // to functions and function templates; in this case the class name or // enumeration name is hidden. // C++ [basic.scope.hiding]p2: // A class name or enumeration name can be hidden by the name of a // variable, data member, function, or enumerator declared in the same // scope. // An UnresolvedUsingValueDecl always instantiates to one of these. D = D->getUnderlyingDecl(); return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) || isa<UnresolvedUsingValueDecl>(D); } /// Resolves the result kind of this lookup. void LookupResult::resolveKind() { unsigned N = Decls.size(); // Fast case: no possible ambiguity. if (N == 0) { assert(ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation); return; } // If there's a single decl, we need to examine it to decide what // kind of lookup this is. if (N == 1) { NamedDecl *D = (*Decls.begin())->getUnderlyingDecl(); if (isa<FunctionTemplateDecl>(D)) ResultKind = FoundOverloaded; else if (isa<UnresolvedUsingValueDecl>(D)) ResultKind = FoundUnresolvedValue; return; } // Don't do any extra resolution if we've already resolved as ambiguous. if (ResultKind == Ambiguous) return; llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique; llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes; bool Ambiguous = false; bool HasTag = false, HasFunction = false; bool HasFunctionTemplate = false, HasUnresolved = false; NamedDecl *HasNonFunction = nullptr; llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions; unsigned UniqueTagIndex = 0; unsigned I = 0; while (I < N) { NamedDecl *D = Decls[I]->getUnderlyingDecl(); D = cast<NamedDecl>(D->getCanonicalDecl()); // Ignore an invalid declaration unless it's the only one left. if (D->isInvalidDecl() && !(I == 0 && N == 1)) { Decls[I] = Decls[--N]; continue; } llvm::Optional<unsigned> ExistingI; // Redeclarations of types via typedef can occur both within a scope // and, through using declarations and directives, across scopes. There is // no ambiguity if they all refer to the same type, so unique based on the // canonical type. if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) { QualType T = getSema().Context.getTypeDeclType(TD); auto UniqueResult = UniqueTypes.insert( std::make_pair(getSema().Context.getCanonicalType(T), I)); if (!UniqueResult.second) { // The type is not unique. ExistingI = UniqueResult.first->second; } } // For non-type declarations, check for a prior lookup result naming this // canonical declaration. if (!ExistingI) { auto UniqueResult = Unique.insert(std::make_pair(D, I)); if (!UniqueResult.second) { // We've seen this entity before. ExistingI = UniqueResult.first->second; } } if (ExistingI) { // This is not a unique lookup result. Pick one of the results and // discard the other. if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I], Decls[*ExistingI])) Decls[*ExistingI] = Decls[I]; Decls[I] = Decls[--N]; continue; } // Otherwise, do some decl type analysis and then continue. if (isa<UnresolvedUsingValueDecl>(D)) { HasUnresolved = true; } else if (isa<TagDecl>(D)) { if (HasTag) Ambiguous = true; UniqueTagIndex = I; HasTag = true; } else if (isa<FunctionTemplateDecl>(D)) { HasFunction = true; HasFunctionTemplate = true; } else if (isa<FunctionDecl>(D)) { HasFunction = true; } else { if (HasNonFunction) { // If we're about to create an ambiguity between two declarations that // are equivalent, but one is an internal linkage declaration from one // module and the other is an internal linkage declaration from another // module, just skip it. if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction, D)) { EquivalentNonFunctions.push_back(D); Decls[I] = Decls[--N]; continue; } Ambiguous = true; } HasNonFunction = D; } I++; } // C++ [basic.scope.hiding]p2: // A class name or enumeration name can be hidden by the name of // an object, function, or enumerator declared in the same // scope. If a class or enumeration name and an object, function, // or enumerator are declared in the same scope (in any order) // with the same name, the class or enumeration name is hidden // wherever the object, function, or enumerator name is visible. // But it's still an error if there are distinct tag types found, // even if they're not visible. (ref?) if (N > 1 && HideTags && HasTag && !Ambiguous && (HasFunction || HasNonFunction || HasUnresolved)) { NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1]; if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) && getContextForScopeMatching(Decls[UniqueTagIndex])->Equals( getContextForScopeMatching(OtherDecl)) && canHideTag(OtherDecl)) Decls[UniqueTagIndex] = Decls[--N]; else Ambiguous = true; } // FIXME: This diagnostic should really be delayed until we're done with // the lookup result, in case the ambiguity is resolved by the caller. if (!EquivalentNonFunctions.empty() && !Ambiguous) getSema().diagnoseEquivalentInternalLinkageDeclarations( getNameLoc(), HasNonFunction, EquivalentNonFunctions); Decls.set_size(N); if (HasNonFunction && (HasFunction || HasUnresolved)) Ambiguous = true; if (Ambiguous) setAmbiguous(LookupResult::AmbiguousReference); else if (HasUnresolved) ResultKind = LookupResult::FoundUnresolvedValue; else if (N > 1 || HasFunctionTemplate) ResultKind = LookupResult::FoundOverloaded; else ResultKind = LookupResult::Found; } void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) { CXXBasePaths::const_paths_iterator I, E; for (I = P.begin(), E = P.end(); I != E; ++I) for (DeclContext::lookup_iterator DI = I->Decls.begin(), DE = I->Decls.end(); DI != DE; ++DI) addDecl(*DI); } void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) { Paths = new CXXBasePaths; Paths->swap(P); addDeclsFromBasePaths(*Paths); resolveKind(); setAmbiguous(AmbiguousBaseSubobjects); } void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) { Paths = new CXXBasePaths; Paths->swap(P); addDeclsFromBasePaths(*Paths); resolveKind(); setAmbiguous(AmbiguousBaseSubobjectTypes); } void LookupResult::print(raw_ostream &Out) { Out << Decls.size() << " result(s)"; if (isAmbiguous()) Out << ", ambiguous"; if (Paths) Out << ", base paths present"; for (iterator I = begin(), E = end(); I != E; ++I) { Out << "\n"; (*I)->print(Out, 2); } } LLVM_DUMP_METHOD void LookupResult::dump() { llvm::errs() << "lookup results for " << getLookupName().getAsString() << ":\n"; for (NamedDecl *D : *this) D->dump(); } /// Lookup a builtin function, when name lookup would otherwise /// fail. static bool LookupBuiltin(Sema &S, LookupResult &R) { Sema::LookupNameKind NameKind = R.getLookupKind(); // If we didn't find a use of this identifier, and if the identifier // corresponds to a compiler builtin, create the decl object for the builtin // now, injecting it into translation unit scope, and return it. if (NameKind == Sema::LookupOrdinaryName || NameKind == Sema::LookupRedeclarationWithLinkage) { IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo(); if (II) { if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) { if (II == S.getASTContext().getMakeIntegerSeqName()) { R.addDecl(S.getASTContext().getMakeIntegerSeqDecl()); return true; } else if (II == S.getASTContext().getTypePackElementName()) { R.addDecl(S.getASTContext().getTypePackElementDecl()); return true; } } // If this is a builtin on this (or all) targets, create the decl. if (unsigned BuiltinID = II->getBuiltinID()) { // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined // library functions like 'malloc'. Instead, we'll just error. if ((S.getLangOpts().CPlusPlus || S.getLangOpts().OpenCL) && S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) return false; if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S.TUScope, R.isForRedeclaration(), R.getNameLoc())) { R.addDecl(D); return true; } } } } return false; } /// Determine whether we can declare a special member function within /// the class at this point. static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) { // We need to have a definition for the class. if (!Class->getDefinition() || Class->isDependentContext()) return false; // We can't be in the middle of defining the class. return !Class->isBeingDefined(); } void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) { if (!CanDeclareSpecialMemberFunction(Class)) return; // If the default constructor has not yet been declared, do so now. if (Class->needsImplicitDefaultConstructor()) DeclareImplicitDefaultConstructor(Class); // If the copy constructor has not yet been declared, do so now. if (Class->needsImplicitCopyConstructor()) DeclareImplicitCopyConstructor(Class); // If the copy assignment operator has not yet been declared, do so now. if (Class->needsImplicitCopyAssignment()) DeclareImplicitCopyAssignment(Class); if (getLangOpts().CPlusPlus11) { // If the move constructor has not yet been declared, do so now. if (Class->needsImplicitMoveConstructor()) DeclareImplicitMoveConstructor(Class); // If the move assignment operator has not yet been declared, do so now. if (Class->needsImplicitMoveAssignment()) DeclareImplicitMoveAssignment(Class); } // If the destructor has not yet been declared, do so now. if (Class->needsImplicitDestructor()) DeclareImplicitDestructor(Class); } /// Determine whether this is the name of an implicitly-declared /// special member function. static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) { switch (Name.getNameKind()) { case DeclarationName::CXXConstructorName: case DeclarationName::CXXDestructorName: return true; case DeclarationName::CXXOperatorName: return Name.getCXXOverloadedOperator() == OO_Equal; default: break; } return false; } /// If there are any implicit member functions with the given name /// that need to be declared in the given declaration context, do so. static void DeclareImplicitMemberFunctionsWithName(Sema &S, DeclarationName Name, SourceLocation Loc, const DeclContext *DC) { if (!DC) return; switch (Name.getNameKind()) { case DeclarationName::CXXConstructorName: if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) { CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); if (Record->needsImplicitDefaultConstructor()) S.DeclareImplicitDefaultConstructor(Class); if (Record->needsImplicitCopyConstructor()) S.DeclareImplicitCopyConstructor(Class); if (S.getLangOpts().CPlusPlus11 && Record->needsImplicitMoveConstructor()) S.DeclareImplicitMoveConstructor(Class); } break; case DeclarationName::CXXDestructorName: if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) if (Record->getDefinition() && Record->needsImplicitDestructor() && CanDeclareSpecialMemberFunction(Record)) S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record)); break; case DeclarationName::CXXOperatorName: if (Name.getCXXOverloadedOperator() != OO_Equal) break; if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) { if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) { CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record); if (Record->needsImplicitCopyAssignment()) S.DeclareImplicitCopyAssignment(Class); if (S.getLangOpts().CPlusPlus11 && Record->needsImplicitMoveAssignment()) S.DeclareImplicitMoveAssignment(Class); } } break; case DeclarationName::CXXDeductionGuideName: S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc); break; default: break; } } // Adds all qualifying matches for a name within a decl context to the // given lookup result. Returns true if any matches were found. static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) { bool Found = false; // Lazily declare C++ special member functions. if (S.getLangOpts().CPlusPlus) DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(), DC); // Perform lookup into this declaration context. DeclContext::lookup_result DR = DC->lookup(R.getLookupName()); for (NamedDecl *D : DR) { if ((D = R.getAcceptableDecl(D))) { R.addDecl(D); Found = true; } } if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R)) return true; if (R.getLookupName().getNameKind() != DeclarationName::CXXConversionFunctionName || R.getLookupName().getCXXNameType()->isDependentType() || !isa<CXXRecordDecl>(DC)) return Found; // C++ [temp.mem]p6: // A specialization of a conversion function template is not found by // name lookup. Instead, any conversion function templates visible in the // context of the use are considered. [...] const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC); if (!Record->isCompleteDefinition()) return Found; // For conversion operators, 'operator auto' should only match // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered // as a candidate for template substitution. auto *ContainedDeducedType = R.getLookupName().getCXXNameType()->getContainedDeducedType(); if (R.getLookupName().getNameKind() == DeclarationName::CXXConversionFunctionName && ContainedDeducedType && ContainedDeducedType->isUndeducedType()) return Found; for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(), UEnd = Record->conversion_end(); U != UEnd; ++U) { FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U); if (!ConvTemplate) continue; // When we're performing lookup for the purposes of redeclaration, just // add the conversion function template. When we deduce template // arguments for specializations, we'll end up unifying the return // type of the new declaration with the type of the function template. if (R.isForRedeclaration()) { R.addDecl(ConvTemplate); Found = true; continue; } // C++ [temp.mem]p6: // [...] For each such operator, if argument deduction succeeds // (14.9.2.3), the resulting specialization is used as if found by // name lookup. // // When referencing a conversion function for any purpose other than // a redeclaration (such that we'll be building an expression with the // result), perform template argument deduction and place the // specialization into the result set. We do this to avoid forcing all // callers to perform special deduction for conversion functions. TemplateDeductionInfo Info(R.getNameLoc()); FunctionDecl *Specialization = nullptr; const FunctionProtoType *ConvProto = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>(); assert(ConvProto && "Nonsensical conversion function template type"); // Compute the type of the function that we would expect the conversion // function to have, if it were to match the name given. // FIXME: Calling convention! FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo(); EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C); EPI.ExceptionSpec = EST_None; QualType ExpectedType = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(), None, EPI); // Perform template argument deduction against the type that we would // expect the function to have. if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType, Specialization, Info) == Sema::TDK_Success) { R.addDecl(Specialization); Found = true; } } return Found; } // Performs C++ unqualified lookup into the given file context. static bool CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context, DeclContext *NS, UnqualUsingDirectiveSet &UDirs) { assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!"); // Perform direct name lookup into the LookupCtx. bool Found = LookupDirect(S, R, NS); // Perform direct name lookup into the namespaces nominated by the // using directives whose common ancestor is this namespace. for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS)) if (LookupDirect(S, R, UUE.getNominatedNamespace())) Found = true; R.resolveKind(); return Found; } static bool isNamespaceOrTranslationUnitScope(Scope *S) { if (DeclContext *Ctx = S->getEntity()) return Ctx->isFileContext(); return false; } // Find the next outer declaration context from this scope. This // routine actually returns the semantic outer context, which may // differ from the lexical context (encoded directly in the Scope // stack) when we are parsing a member of a class template. In this // case, the second element of the pair will be true, to indicate that // name lookup should continue searching in this semantic context when // it leaves the current template parameter scope. static std::pair<DeclContext *, bool> findOuterContext(Scope *S) { DeclContext *DC = S->getEntity(); DeclContext *Lexical = nullptr; for (Scope *OuterS = S->getParent(); OuterS; OuterS = OuterS->getParent()) { if (OuterS->getEntity()) { Lexical = OuterS->getEntity(); break; } } // C++ [temp.local]p8: // In the definition of a member of a class template that appears // outside of the namespace containing the class template // definition, the name of a template-parameter hides the name of // a member of this namespace. // // Example: // // namespace N { // class C { }; // // template<class T> class B { // void f(T); // }; // } // // template<class C> void N::B<C>::f(C) { // C b; // C is the template parameter, not N::C // } // // In this example, the lexical context we return is the // TranslationUnit, while the semantic context is the namespace N. if (!Lexical || !DC || !S->getParent() || !S->getParent()->isTemplateParamScope()) return std::make_pair(Lexical, false); // Find the outermost template parameter scope. // For the example, this is the scope for the template parameters of // template<class C>. Scope *OutermostTemplateScope = S->getParent(); while (OutermostTemplateScope->getParent() && OutermostTemplateScope->getParent()->isTemplateParamScope()) OutermostTemplateScope = OutermostTemplateScope->getParent(); // Find the namespace context in which the original scope occurs. In // the example, this is namespace N. DeclContext *Semantic = DC; while (!Semantic->isFileContext()) Semantic = Semantic->getParent(); // Find the declaration context just outside of the template // parameter scope. This is the context in which the template is // being lexically declaration (a namespace context). In the // example, this is the global scope. if (Lexical->isFileContext() && !Lexical->Equals(Semantic) && Lexical->Encloses(Semantic)) return std::make_pair(Semantic, true); return std::make_pair(Lexical, false); } namespace { /// An RAII object to specify that we want to find block scope extern /// declarations. struct FindLocalExternScope { FindLocalExternScope(LookupResult &R) : R(R), OldFindLocalExtern(R.getIdentifierNamespace() & Decl::IDNS_LocalExtern) { R.setFindLocalExtern(R.getIdentifierNamespace() & (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator)); } void restore() { R.setFindLocalExtern(OldFindLocalExtern); } ~FindLocalExternScope() { restore(); } LookupResult &R; bool OldFindLocalExtern; }; } // end anonymous namespace bool Sema::CppLookupName(LookupResult &R, Scope *S) { assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup"); DeclarationName Name = R.getLookupName(); Sema::LookupNameKind NameKind = R.getLookupKind(); // If this is the name of an implicitly-declared special member function, // go through the scope stack to implicitly declare if (isImplicitlyDeclaredMemberFunctionName(Name)) { for (Scope *PreS = S; PreS; PreS = PreS->getParent()) if (DeclContext *DC = PreS->getEntity()) DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC); } // Implicitly declare member functions with the name we're looking for, if in // fact we are in a scope where it matters. Scope *Initial = S; IdentifierResolver::iterator I = IdResolver.begin(Name), IEnd = IdResolver.end(); // First we lookup local scope. // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir] // ...During unqualified name lookup (3.4.1), the names appear as if // they were declared in the nearest enclosing namespace which contains // both the using-directive and the nominated namespace. // [Note: in this context, "contains" means "contains directly or // indirectly". // // For example: // namespace A { int i; } // void foo() { // int i; // { // using namespace A; // ++i; // finds local 'i', A::i appears at global scope // } // } // UnqualUsingDirectiveSet UDirs(*this); bool VisitedUsingDirectives = false; bool LeftStartingScope = false; DeclContext *OutsideOfTemplateParamDC = nullptr; // When performing a scope lookup, we want to find local extern decls. FindLocalExternScope FindLocals(R); for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) { DeclContext *Ctx = S->getEntity(); bool SearchNamespaceScope = true; // Check whether the IdResolver has anything in this scope. for (; I != IEnd && S->isDeclScope(*I); ++I) { if (NamedDecl *ND = R.getAcceptableDecl(*I)) { if (NameKind == LookupRedeclarationWithLinkage && !(*I)->isTemplateParameter()) { // If it's a template parameter, we still find it, so we can diagnose // the invalid redeclaration. // Determine whether this (or a previous) declaration is // out-of-scope. if (!LeftStartingScope && !Initial->isDeclScope(*I)) LeftStartingScope = true; // If we found something outside of our starting scope that // does not have linkage, skip it. if (LeftStartingScope && !((*I)->hasLinkage())) { R.setShadowed(); continue; } } else { // We found something in this scope, we should not look at the // namespace scope SearchNamespaceScope = false; } R.addDecl(ND); } } if (!SearchNamespaceScope) { R.resolveKind(); if (S->isClassScope()) if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx)) R.setNamingClass(Record); return true; } if (NameKind == LookupLocalFriendName && !S->isClassScope()) { // C++11 [class.friend]p11: // If a friend declaration appears in a local class and the name // specified is an unqualified name, a prior declaration is // looked up without considering scopes that are outside the // innermost enclosing non-class scope. return false; } if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && S->getParent() && !S->getParent()->isTemplateParamScope()) { // We've just searched the last template parameter scope and // found nothing, so look into the contexts between the // lexical and semantic declaration contexts returned by // findOuterContext(). This implements the name lookup behavior // of C++ [temp.local]p8. Ctx = OutsideOfTemplateParamDC; OutsideOfTemplateParamDC = nullptr; } if (Ctx) { DeclContext *OuterCtx; bool SearchAfterTemplateScope; std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); if (SearchAfterTemplateScope) OutsideOfTemplateParamDC = OuterCtx; for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { // We do not directly look into transparent contexts, since // those entities will be found in the nearest enclosing // non-transparent context. if (Ctx->isTransparentContext()) continue; // We do not look directly into function or method contexts, // since all of the local variables and parameters of the // function/method are present within the Scope. if (Ctx->isFunctionOrMethod()) { // If we have an Objective-C instance method, look for ivars // in the corresponding interface. if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { if (Method->isInstanceMethod() && Name.getAsIdentifierInfo()) if (ObjCInterfaceDecl *Class = Method->getClassInterface()) { ObjCInterfaceDecl *ClassDeclared; if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable( Name.getAsIdentifierInfo(), ClassDeclared)) { if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) { R.addDecl(ND); R.resolveKind(); return true; } } } } continue; } // If this is a file context, we need to perform unqualified name // lookup considering using directives. if (Ctx->isFileContext()) { // If we haven't handled using directives yet, do so now. if (!VisitedUsingDirectives) { // Add using directives from this context up to the top level. for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) { if (UCtx->isTransparentContext()) continue; UDirs.visit(UCtx, UCtx); } // Find the innermost file scope, so we can add using directives // from local scopes. Scope *InnermostFileScope = S; while (InnermostFileScope && !isNamespaceOrTranslationUnitScope(InnermostFileScope)) InnermostFileScope = InnermostFileScope->getParent(); UDirs.visitScopeChain(Initial, InnermostFileScope); UDirs.done(); VisitedUsingDirectives = true; } if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) { R.resolveKind(); return true; } continue; } // Perform qualified name lookup into this context. // FIXME: In some cases, we know that every name that could be found by // this qualified name lookup will also be on the identifier chain. For // example, inside a class without any base classes, we never need to // perform qualified lookup because all of the members are on top of the // identifier chain. if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true)) return true; } } } // Stop if we ran out of scopes. // FIXME: This really, really shouldn't be happening. if (!S) return false; // If we are looking for members, no need to look into global/namespace scope. if (NameKind == LookupMemberName) return false; // Collect UsingDirectiveDecls in all scopes, and recursively all // nominated namespaces by those using-directives. // // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we // don't build it for each lookup! if (!VisitedUsingDirectives) { UDirs.visitScopeChain(Initial, S); UDirs.done(); } // If we're not performing redeclaration lookup, do not look for local // extern declarations outside of a function scope. if (!R.isForRedeclaration()) FindLocals.restore(); // Lookup namespace scope, and global scope. // Unqualified name lookup in C++ requires looking into scopes // that aren't strictly lexical, and therefore we walk through the // context as well as walking through the scopes. for (; S; S = S->getParent()) { // Check whether the IdResolver has anything in this scope. bool Found = false; for (; I != IEnd && S->isDeclScope(*I); ++I) { if (NamedDecl *ND = R.getAcceptableDecl(*I)) { // We found something. Look for anything else in our scope // with this same name and in an acceptable identifier // namespace, so that we can construct an overload set if we // need to. Found = true; R.addDecl(ND); } } if (Found && S->isTemplateParamScope()) { R.resolveKind(); return true; } DeclContext *Ctx = S->getEntity(); if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC && S->getParent() && !S->getParent()->isTemplateParamScope()) { // We've just searched the last template parameter scope and // found nothing, so look into the contexts between the // lexical and semantic declaration contexts returned by // findOuterContext(). This implements the name lookup behavior // of C++ [temp.local]p8. Ctx = OutsideOfTemplateParamDC; OutsideOfTemplateParamDC = nullptr; } if (Ctx) { DeclContext *OuterCtx; bool SearchAfterTemplateScope; std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S); if (SearchAfterTemplateScope) OutsideOfTemplateParamDC = OuterCtx; for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { // We do not directly look into transparent contexts, since // those entities will be found in the nearest enclosing // non-transparent context. if (Ctx->isTransparentContext()) continue; // If we have a context, and it's not a context stashed in the // template parameter scope for an out-of-line definition, also // look into that context. if (!(Found && S->isTemplateParamScope())) { assert(Ctx->isFileContext() && "We should have been looking only at file context here already."); // Look into context considering using-directives. if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) Found = true; } if (Found) { R.resolveKind(); return true; } if (R.isForRedeclaration() && !Ctx->isTransparentContext()) return false; } } if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext()) return false; } return !R.empty(); } void Sema::makeMergedDefinitionVisible(NamedDecl *ND) { if (auto *M = getCurrentModule()) Context.mergeDefinitionIntoModule(ND, M); else // We're not building a module; just make the definition visible. ND->setVisibleDespiteOwningModule(); // If ND is a template declaration, make the template parameters // visible too. They're not (necessarily) within a mergeable DeclContext. if (auto *TD = dyn_cast<TemplateDecl>(ND)) for (auto *Param : *TD->getTemplateParameters()) makeMergedDefinitionVisible(Param); } /// Find the module in which the given declaration was defined. static Module *getDefiningModule(Sema &S, Decl *Entity) { if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) { // If this function was instantiated from a template, the defining module is // the module containing the pattern. if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern()) Entity = Pattern; } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) { if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern()) Entity = Pattern; } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) { if (auto *Pattern = ED->getTemplateInstantiationPattern()) Entity = Pattern; } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) { if (VarDecl *Pattern = VD->getTemplateInstantiationPattern()) Entity = Pattern; } // Walk up to the containing context. That might also have been instantiated // from a template. DeclContext *Context = Entity->getLexicalDeclContext(); if (Context->isFileContext()) return S.getOwningModule(Entity); return getDefiningModule(S, cast<Decl>(Context)); } llvm::DenseSet<Module*> &Sema::getLookupModules() { unsigned N = CodeSynthesisContexts.size(); for (unsigned I = CodeSynthesisContextLookupModules.size(); I != N; ++I) { Module *M = getDefiningModule(*this, CodeSynthesisContexts[I].Entity); if (M && !LookupModulesCache.insert(M).second) M = nullptr; CodeSynthesisContextLookupModules.push_back(M); } return LookupModulesCache; } bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) { for (Module *Merged : Context.getModulesWithMergedDefinition(Def)) if (isModuleVisible(Merged)) return true; return false; } bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) { // FIXME: When not in local visibility mode, we can't tell the difference // between a declaration being visible because we merged a local copy of // the same declaration into it, and it being visible because its owning // module is visible. if (Def->getModuleOwnershipKind() == Decl::ModuleOwnershipKind::Visible && getLangOpts().ModulesLocalVisibility) return true; for (Module *Merged : Context.getModulesWithMergedDefinition(Def)) if (Merged->getTopLevelModuleName() == getLangOpts().CurrentModule) return true; return false; } template<typename ParmDecl> static bool hasVisibleDefaultArgument(Sema &S, const ParmDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { if (!D->hasDefaultArgument()) return false; while (D) { auto &DefaultArg = D->getDefaultArgStorage(); if (!DefaultArg.isInherited() && S.isVisible(D)) return true; if (!DefaultArg.isInherited() && Modules) { auto *NonConstD = const_cast<ParmDecl*>(D); Modules->push_back(S.getOwningModule(NonConstD)); const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD); Modules->insert(Modules->end(), Merged.begin(), Merged.end()); } // If there was a previous default argument, maybe its parameter is visible. D = DefaultArg.getInheritedFrom(); } return false; } bool Sema::hasVisibleDefaultArgument(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { if (auto *P = dyn_cast<TemplateTypeParmDecl>(D)) return ::hasVisibleDefaultArgument(*this, P, Modules); if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D)) return ::hasVisibleDefaultArgument(*this, P, Modules); return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D), Modules); } template<typename Filter> static bool hasVisibleDeclarationImpl(Sema &S, const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules, Filter F) { bool HasFilteredRedecls = false; for (auto *Redecl : D->redecls()) { auto *R = cast<NamedDecl>(Redecl); if (!F(R)) continue; if (S.isVisible(R)) return true; HasFilteredRedecls = true; if (Modules) { Modules->push_back(R->getOwningModule()); const auto &Merged = S.Context.getModulesWithMergedDefinition(R); Modules->insert(Modules->end(), Merged.begin(), Merged.end()); } } // Only return false if there is at least one redecl that is not filtered out. if (HasFilteredRedecls) return false; return true; } bool Sema::hasVisibleExplicitSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) { if (auto *RD = dyn_cast<CXXRecordDecl>(D)) return RD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization; if (auto *FD = dyn_cast<FunctionDecl>(D)) return FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization; if (auto *VD = dyn_cast<VarDecl>(D)) return VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization; llvm_unreachable("unknown explicit specialization kind"); }); } bool Sema::hasVisibleMemberSpecialization( const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { assert(isa<CXXRecordDecl>(D->getDeclContext()) && "not a member specialization"); return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) { // If the specialization is declared at namespace scope, then it's a member // specialization declaration. If it's lexically inside the class // definition then it was instantiated. // // FIXME: This is a hack. There should be a better way to determine this. // FIXME: What about MS-style explicit specializations declared within a // class definition? return D->getLexicalDeclContext()->isFileContext(); }); } /// Determine whether a declaration is visible to name lookup. /// /// This routine determines whether the declaration D is visible in the current /// lookup context, taking into account the current template instantiation /// stack. During template instantiation, a declaration is visible if it is /// visible from a module containing any entity on the template instantiation /// path (by instantiating a template, you allow it to see the declarations that /// your module can see, including those later on in your module). bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) { assert(D->isHidden() && "should not call this: not in slow case"); Module *DeclModule = SemaRef.getOwningModule(D); if (!DeclModule) { // A module-private declaration with no owning module means this is in the // global module in the C++ Modules TS. This is visible within the same // translation unit only. // FIXME: Don't assume that "same translation unit" means the same thing // as "not from an AST file". assert(D->isModulePrivate() && "hidden decl has no module"); if (!D->isFromASTFile() || SemaRef.hasMergedDefinitionInCurrentModule(D)) return true; } else { // If the owning module is visible, and the decl is not module private, // then the decl is visible too. (Module private is ignored within the same // top-level module.) if (D->isModulePrivate() ? DeclModule->getTopLevelModuleName() == SemaRef.getLangOpts().CurrentModule || SemaRef.hasMergedDefinitionInCurrentModule(D) : SemaRef.isModuleVisible(DeclModule) || SemaRef.hasVisibleMergedDefinition(D)) return true; } // Determine whether a decl context is a file context for the purpose of // visibility. This looks through some (export and linkage spec) transparent // contexts, but not others (enums). auto IsEffectivelyFileContext = [](const DeclContext *DC) { return DC->isFileContext() || isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC); }; // If this declaration is not at namespace scope // then it is visible if its lexical parent has a visible definition. DeclContext *DC = D->getLexicalDeclContext(); if (DC && !IsEffectivelyFileContext(DC)) { // For a parameter, check whether our current template declaration's // lexical context is visible, not whether there's some other visible // definition of it, because parameters aren't "within" the definition. // // In C++ we need to check for a visible definition due to ODR merging, // and in C we must not because each declaration of a function gets its own // set of declarations for tags in prototype scope. bool VisibleWithinParent; if (D->isTemplateParameter() || isa<ParmVarDecl>(D) || (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus)) VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC)); else if (D->isModulePrivate()) { // A module-private declaration is only visible if an enclosing lexical // parent was merged with another definition in the current module. VisibleWithinParent = false; do { if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) { VisibleWithinParent = true; break; } DC = DC->getLexicalParent(); } while (!IsEffectivelyFileContext(DC)); } else { VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC)); } if (VisibleWithinParent && SemaRef.CodeSynthesisContexts.empty() && // FIXME: Do something better in this case. !SemaRef.getLangOpts().ModulesLocalVisibility) { // Cache the fact that this declaration is implicitly visible because // its parent has a visible definition. D->setVisibleDespiteOwningModule(); } return VisibleWithinParent; } // FIXME: All uses of DeclModule below this point should also check merged // modules. if (!DeclModule) return false; // Find the extra places where we need to look. const auto &LookupModules = SemaRef.getLookupModules(); if (LookupModules.empty()) return false; // If our lookup set contains the decl's module, it's visible. if (LookupModules.count(DeclModule)) return true; // If the declaration isn't exported, it's not visible in any other module. if (D->isModulePrivate()) return false; // Check whether DeclModule is transitively exported to an import of // the lookup set. return std::any_of(LookupModules.begin(), LookupModules.end(), [&](const Module *M) { return M->isModuleVisible(DeclModule); }); } bool Sema::isVisibleSlow(const NamedDecl *D) { return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D)); } bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) { // FIXME: If there are both visible and hidden declarations, we need to take // into account whether redeclaration is possible. Example: // // Non-imported module: // int f(T); // #1 // Some TU: // static int f(U); // #2, not a redeclaration of #1 // int f(T); // #3, finds both, should link with #1 if T != U, but // // with #2 if T == U; neither should be ambiguous. for (auto *D : R) { if (isVisible(D)) return true; assert(D->isExternallyDeclarable() && "should not have hidden, non-externally-declarable result here"); } // This function is called once "New" is essentially complete, but before a // previous declaration is attached. We can't query the linkage of "New" in // general, because attaching the previous declaration can change the // linkage of New to match the previous declaration. // // However, because we've just determined that there is no *visible* prior // declaration, we can compute the linkage here. There are two possibilities: // // * This is not a redeclaration; it's safe to compute the linkage now. // // * This is a redeclaration of a prior declaration that is externally // redeclarable. In that case, the linkage of the declaration is not // changed by attaching the prior declaration, because both are externally // declarable (and thus ExternalLinkage or VisibleNoLinkage). // // FIXME: This is subtle and fragile. return New->isExternallyDeclarable(); } /// Retrieve the visible declaration corresponding to D, if any. /// /// This routine determines whether the declaration D is visible in the current /// module, with the current imports. If not, it checks whether any /// redeclaration of D is visible, and if so, returns that declaration. /// /// \returns D, or a visible previous declaration of D, whichever is more recent /// and visible. If no declaration of D is visible, returns null. static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D, unsigned IDNS) { assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); for (auto RD : D->redecls()) { // Don't bother with extra checks if we already know this one isn't visible. if (RD == D) continue; auto ND = cast<NamedDecl>(RD); // FIXME: This is wrong in the case where the previous declaration is not // visible in the same scope as D. This needs to be done much more // carefully. if (ND->isInIdentifierNamespace(IDNS) && LookupResult::isVisible(SemaRef, ND)) return ND; } return nullptr; } bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) { assert(!isVisible(D) && "not in slow case"); return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *) { return true; }); } NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const { if (auto *ND = dyn_cast<NamespaceDecl>(D)) { // Namespaces are a bit of a special case: we expect there to be a lot of // redeclarations of some namespaces, all declarations of a namespace are // essentially interchangeable, all declarations are found by name lookup // if any is, and namespaces are never looked up during template // instantiation. So we benefit from caching the check in this case, and // it is correct to do so. auto *Key = ND->getCanonicalDecl(); if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key)) return Acceptable; auto *Acceptable = isVisible(getSema(), Key) ? Key : findAcceptableDecl(getSema(), Key, IDNS); if (Acceptable) getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable)); return Acceptable; } return findAcceptableDecl(getSema(), D, IDNS); } /// Perform unqualified name lookup starting from a given /// scope. /// /// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is /// used to find names within the current scope. For example, 'x' in /// @code /// int x; /// int f() { /// return x; // unqualified name look finds 'x' in the global scope /// } /// @endcode /// /// Different lookup criteria can find different names. For example, a /// particular scope can have both a struct and a function of the same /// name, and each can be found by certain lookup criteria. For more /// information about lookup criteria, see the documentation for the /// class LookupCriteria. /// /// @param S The scope from which unqualified name lookup will /// begin. If the lookup criteria permits, name lookup may also search /// in the parent scopes. /// /// @param [in,out] R Specifies the lookup to perform (e.g., the name to /// look up and the lookup kind), and is updated with the results of lookup /// including zero or more declarations and possibly additional information /// used to diagnose ambiguities. /// /// @returns \c true if lookup succeeded and false otherwise. bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) { DeclarationName Name = R.getLookupName(); if (!Name) return false; LookupNameKind NameKind = R.getLookupKind(); if (!getLangOpts().CPlusPlus) { // Unqualified name lookup in C/Objective-C is purely lexical, so // search in the declarations attached to the name. if (NameKind == Sema::LookupRedeclarationWithLinkage) { // Find the nearest non-transparent declaration scope. while (!(S->getFlags() & Scope::DeclScope) || (S->getEntity() && S->getEntity()->isTransparentContext())) S = S->getParent(); } // When performing a scope lookup, we want to find local extern decls. FindLocalExternScope FindLocals(R); // Scan up the scope chain looking for a decl that matches this // identifier that is in the appropriate namespace. This search // should not take long, as shadowing of names is uncommon, and // deep shadowing is extremely uncommon. bool LeftStartingScope = false; for (IdentifierResolver::iterator I = IdResolver.begin(Name), IEnd = IdResolver.end(); I != IEnd; ++I) if (NamedDecl *D = R.getAcceptableDecl(*I)) { if (NameKind == LookupRedeclarationWithLinkage) { // Determine whether this (or a previous) declaration is // out-of-scope. if (!LeftStartingScope && !S->isDeclScope(*I)) LeftStartingScope = true; // If we found something outside of our starting scope that // does not have linkage, skip it. if (LeftStartingScope && !((*I)->hasLinkage())) { R.setShadowed(); continue; } } else if (NameKind == LookupObjCImplicitSelfParam && !isa<ImplicitParamDecl>(*I)) continue; R.addDecl(D); // Check whether there are any other declarations with the same name // and in the same scope. if (I != IEnd) { // Find the scope in which this declaration was declared (if it // actually exists in a Scope). while (S && !S->isDeclScope(D)) S = S->getParent(); // If the scope containing the declaration is the translation unit, // then we'll need to perform our checks based on the matching // DeclContexts rather than matching scopes. if (S && isNamespaceOrTranslationUnitScope(S)) S = nullptr; // Compute the DeclContext, if we need it. DeclContext *DC = nullptr; if (!S) DC = (*I)->getDeclContext()->getRedeclContext(); IdentifierResolver::iterator LastI = I; for (++LastI; LastI != IEnd; ++LastI) { if (S) { // Match based on scope. if (!S->isDeclScope(*LastI)) break; } else { // Match based on DeclContext. DeclContext *LastDC = (*LastI)->getDeclContext()->getRedeclContext(); if (!LastDC->Equals(DC)) break; } // If the declaration is in the right namespace and visible, add it. if (NamedDecl *LastD = R.getAcceptableDecl(*LastI)) R.addDecl(LastD); } R.resolveKind(); } return true; } } else { // Perform C++ unqualified name lookup. if (CppLookupName(R, S)) return true; } // If we didn't find a use of this identifier, and if the identifier // corresponds to a compiler builtin, create the decl object for the builtin // now, injecting it into translation unit scope, and return it. if (AllowBuiltinCreation && LookupBuiltin(*this, R)) return true; // If we didn't find a use of this identifier, the ExternalSource // may be able to handle the situation. // Note: some lookup failures are expected! // See e.g. R.isForRedeclaration(). return (ExternalSource && ExternalSource->LookupUnqualified(R, S)); } /// Perform qualified name lookup in the namespaces nominated by /// using directives by the given context. /// /// C++98 [namespace.qual]p2: /// Given X::m (where X is a user-declared namespace), or given \::m /// (where X is the global namespace), let S be the set of all /// declarations of m in X and in the transitive closure of all /// namespaces nominated by using-directives in X and its used /// namespaces, except that using-directives are ignored in any /// namespace, including X, directly containing one or more /// declarations of m. No namespace is searched more than once in /// the lookup of a name. If S is the empty set, the program is /// ill-formed. Otherwise, if S has exactly one member, or if the /// context of the reference is a using-declaration /// (namespace.udecl), S is the required set of declarations of /// m. Otherwise if the use of m is not one that allows a unique /// declaration to be chosen from S, the program is ill-formed. /// /// C++98 [namespace.qual]p5: /// During the lookup of a qualified namespace member name, if the /// lookup finds more than one declaration of the member, and if one /// declaration introduces a class name or enumeration name and the /// other declarations either introduce the same object, the same /// enumerator or a set of functions, the non-type name hides the /// class or enumeration name if and only if the declarations are /// from the same namespace; otherwise (the declarations are from /// different namespaces), the program is ill-formed. static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R, DeclContext *StartDC) { assert(StartDC->isFileContext() && "start context is not a file context"); // We have not yet looked into these namespaces, much less added // their "using-children" to the queue. SmallVector<NamespaceDecl*, 8> Queue; // We have at least added all these contexts to the queue. llvm::SmallPtrSet<DeclContext*, 8> Visited; Visited.insert(StartDC); // We have already looked into the initial namespace; seed the queue // with its using-children. for (auto *I : StartDC->using_directives()) { NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace(); if (S.isVisible(I) && Visited.insert(ND).second) Queue.push_back(ND); } // The easiest way to implement the restriction in [namespace.qual]p5 // is to check whether any of the individual results found a tag // and, if so, to declare an ambiguity if the final result is not // a tag. bool FoundTag = false; bool FoundNonTag = false; LookupResult LocalR(LookupResult::Temporary, R); bool Found = false; while (!Queue.empty()) { NamespaceDecl *ND = Queue.pop_back_val(); // We go through some convolutions here to avoid copying results // between LookupResults. bool UseLocal = !R.empty(); LookupResult &DirectR = UseLocal ? LocalR : R; bool FoundDirect = LookupDirect(S, DirectR, ND); if (FoundDirect) { // First do any local hiding. DirectR.resolveKind(); // If the local result is a tag, remember that. if (DirectR.isSingleTagDecl()) FoundTag = true; else FoundNonTag = true; // Append the local results to the total results if necessary. if (UseLocal) { R.addAllDecls(LocalR); LocalR.clear(); } } // If we find names in this namespace, ignore its using directives. if (FoundDirect) { Found = true; continue; } for (auto I : ND->using_directives()) { NamespaceDecl *Nom = I->getNominatedNamespace(); if (S.isVisible(I) && Visited.insert(Nom).second) Queue.push_back(Nom); } } if (Found) { if (FoundTag && FoundNonTag) R.setAmbiguousQualifiedTagHiding(); else R.resolveKind(); } return Found; } /// Callback that looks for any member of a class with the given name. static bool LookupAnyMember(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name) { RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl(); Path.Decls = BaseRecord->lookup(Name); return !Path.Decls.empty(); } /// Determine whether the given set of member declarations contains only /// static members, nested types, and enumerators. template<typename InputIterator> static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) { Decl *D = (*First)->getUnderlyingDecl(); if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D)) return true; if (isa<CXXMethodDecl>(D)) { // Determine whether all of the methods are static. bool AllMethodsAreStatic = true; for(; First != Last; ++First) { D = (*First)->getUnderlyingDecl(); if (!isa<CXXMethodDecl>(D)) { assert(isa<TagDecl>(D) && "Non-function must be a tag decl"); break; } if (!cast<CXXMethodDecl>(D)->isStatic()) { AllMethodsAreStatic = false; break; } } if (AllMethodsAreStatic) return true; } return false; } /// Perform qualified name lookup into a given context. /// /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find /// names when the context of those names is explicit specified, e.g., /// "std::vector" or "x->member", or as part of unqualified name lookup. /// /// Different lookup criteria can find different names. For example, a /// particular scope can have both a struct and a function of the same /// name, and each can be found by certain lookup criteria. For more /// information about lookup criteria, see the documentation for the /// class LookupCriteria. /// /// \param R captures both the lookup criteria and any lookup results found. /// /// \param LookupCtx The context in which qualified name lookup will /// search. If the lookup criteria permits, name lookup may also search /// in the parent contexts or (for C++ classes) base classes. /// /// \param InUnqualifiedLookup true if this is qualified name lookup that /// occurs as part of unqualified name lookup. /// /// \returns true if lookup succeeded, false if it failed. bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup) { assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context"); if (!R.getLookupName()) return false; // Make sure that the declaration context is complete. assert((!isa<TagDecl>(LookupCtx) || LookupCtx->isDependentContext() || cast<TagDecl>(LookupCtx)->isCompleteDefinition() || cast<TagDecl>(LookupCtx)->isBeingDefined()) && "Declaration context must already be complete!"); struct QualifiedLookupInScope { bool oldVal; DeclContext *Context; // Set flag in DeclContext informing debugger that we're looking for qualified name QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) { oldVal = ctx->setUseQualifiedLookup(); } ~QualifiedLookupInScope() { Context->setUseQualifiedLookup(oldVal); } } QL(LookupCtx); if (LookupDirect(*this, R, LookupCtx)) { R.resolveKind(); if (isa<CXXRecordDecl>(LookupCtx)) R.setNamingClass(cast<CXXRecordDecl>(LookupCtx)); return true; } // Don't descend into implied contexts for redeclarations. // C++98 [namespace.qual]p6: // In a declaration for a namespace member in which the // declarator-id is a qualified-id, given that the qualified-id // for the namespace member has the form // nested-name-specifier unqualified-id // the unqualified-id shall name a member of the namespace // designated by the nested-name-specifier. // See also [class.mfct]p5 and [class.static.data]p2. if (R.isForRedeclaration()) return false; // If this is a namespace, look it up in the implied namespaces. if (LookupCtx->isFileContext()) return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx); // If this isn't a C++ class, we aren't allowed to look into base // classes, we're done. CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx); if (!LookupRec || !LookupRec->getDefinition()) return false; // If we're performing qualified name lookup into a dependent class, // then we are actually looking into a current instantiation. If we have any // dependent base classes, then we either have to delay lookup until // template instantiation time (at which point all bases will be available) // or we have to fail. if (!InUnqualifiedLookup && LookupRec->isDependentContext() && LookupRec->hasAnyDependentBases()) { R.setNotFoundInCurrentInstantiation(); return false; } // Perform lookup into our base classes. CXXBasePaths Paths; Paths.setOrigin(LookupRec); // Look for this member in our base classes bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path, DeclarationName Name) = nullptr; switch (R.getLookupKind()) { case LookupObjCImplicitSelfParam: case LookupOrdinaryName: case LookupMemberName: case LookupRedeclarationWithLinkage: case LookupLocalFriendName: BaseCallback = &CXXRecordDecl::FindOrdinaryMember; break; case LookupTagName: BaseCallback = &CXXRecordDecl::FindTagMember; break; case LookupAnyName: BaseCallback = &LookupAnyMember; break; case LookupOMPReductionName: BaseCallback = &CXXRecordDecl::FindOMPReductionMember; break; case LookupUsingDeclName: // This lookup is for redeclarations only. case LookupOperatorName: case LookupNamespaceName: case LookupObjCProtocolName: case LookupLabel: // These lookups will never find a member in a C++ class (or base class). return false; case LookupNestedNameSpecifierName: BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember; break; } DeclarationName Name = R.getLookupName(); if (!LookupRec->lookupInBases( [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) { return BaseCallback(Specifier, Path, Name); }, Paths)) return false; R.setNamingClass(LookupRec); // C++ [class.member.lookup]p2: // [...] If the resulting set of declarations are not all from // sub-objects of the same type, or the set has a nonstatic member // and includes members from distinct sub-objects, there is an // ambiguity and the program is ill-formed. Otherwise that set is // the result of the lookup. QualType SubobjectType; int SubobjectNumber = 0; AccessSpecifier SubobjectAccess = AS_none; for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end(); Path != PathEnd; ++Path) { const CXXBasePathElement &PathElement = Path->back(); // Pick the best (i.e. most permissive i.e. numerically lowest) access // across all paths. SubobjectAccess = std::min(SubobjectAccess, Path->Access); // Determine whether we're looking at a distinct sub-object or not. if (SubobjectType.isNull()) { // This is the first subobject we've looked at. Record its type. SubobjectType = Context.getCanonicalType(PathElement.Base->getType()); SubobjectNumber = PathElement.SubobjectNumber; continue; } if (SubobjectType != Context.getCanonicalType(PathElement.Base->getType())) { // We found members of the given name in two subobjects of // different types. If the declaration sets aren't the same, this // lookup is ambiguous. if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) { CXXBasePaths::paths_iterator FirstPath = Paths.begin(); DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin(); DeclContext::lookup_iterator CurrentD = Path->Decls.begin(); while (FirstD != FirstPath->Decls.end() && CurrentD != Path->Decls.end()) { if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() != (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl()) break; ++FirstD; ++CurrentD; } if (FirstD == FirstPath->Decls.end() && CurrentD == Path->Decls.end()) continue; } R.setAmbiguousBaseSubobjectTypes(Paths); return true; } if (SubobjectNumber != PathElement.SubobjectNumber) { // We have a different subobject of the same type. // C++ [class.member.lookup]p5: // A static member, a nested type or an enumerator defined in // a base class T can unambiguously be found even if an object // has more than one base class subobject of type T. if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) continue; // We have found a nonstatic member name in multiple, distinct // subobjects. Name lookup is ambiguous. R.setAmbiguousBaseSubobjects(Paths); return true; } } // Lookup in a base class succeeded; return these results. for (auto *D : Paths.front().Decls) { AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess, D->getAccess()); R.addDecl(D, AS); } R.resolveKind(); return true; } /// Performs qualified name lookup or special type of lookup for /// "__super::" scope specifier. /// /// This routine is a convenience overload meant to be called from contexts /// that need to perform a qualified name lookup with an optional C++ scope /// specifier that might require special kind of lookup. /// /// \param R captures both the lookup criteria and any lookup results found. /// /// \param LookupCtx The context in which qualified name lookup will /// search. /// /// \param SS An optional C++ scope-specifier. /// /// \returns true if lookup succeeded, false if it failed. bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, CXXScopeSpec &SS) { auto *NNS = SS.getScopeRep(); if (NNS && NNS->getKind() == NestedNameSpecifier::Super) return LookupInSuper(R, NNS->getAsRecordDecl()); else return LookupQualifiedName(R, LookupCtx); } /// Performs name lookup for a name that was parsed in the /// source code, and may contain a C++ scope specifier. /// /// This routine is a convenience routine meant to be called from /// contexts that receive a name and an optional C++ scope specifier /// (e.g., "N::M::x"). It will then perform either qualified or /// unqualified name lookup (with LookupQualifiedName or LookupName, /// respectively) on the given name and return those results. It will /// perform a special type of lookup for "__super::" scope specifier. /// /// @param S The scope from which unqualified name lookup will /// begin. /// /// @param SS An optional C++ scope-specifier, e.g., "::N::M". /// /// @param EnteringContext Indicates whether we are going to enter the /// context of the scope-specifier SS (if present). /// /// @returns True if any decls were found (but possibly ambiguous) bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation, bool EnteringContext) { if (SS && SS->isInvalid()) { // When the scope specifier is invalid, don't even look for // anything. return false; } if (SS && SS->isSet()) { NestedNameSpecifier *NNS = SS->getScopeRep(); if (NNS->getKind() == NestedNameSpecifier::Super) return LookupInSuper(R, NNS->getAsRecordDecl()); if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) { // We have resolved the scope specifier to a particular declaration // contex, and will perform name lookup in that context. if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC)) return false; R.setContextRange(SS->getRange()); return LookupQualifiedName(R, DC); } // We could not resolve the scope specified to a specific declaration // context, which means that SS refers to an unknown specialization. // Name lookup can't find anything in this case. R.setNotFoundInCurrentInstantiation(); R.setContextRange(SS->getRange()); return false; } // Perform unqualified name lookup starting in the given scope. return LookupName(R, S, AllowBuiltinCreation); } /// Perform qualified name lookup into all base classes of the given /// class. /// /// \param R captures both the lookup criteria and any lookup results found. /// /// \param Class The context in which qualified name lookup will /// search. Name lookup will search in all base classes merging the results. /// /// @returns True if any decls were found (but possibly ambiguous) bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) { // The access-control rules we use here are essentially the rules for // doing a lookup in Class that just magically skipped the direct // members of Class itself. That is, the naming class is Class, and the // access includes the access of the base. for (const auto &BaseSpec : Class->bases()) { CXXRecordDecl *RD = cast<CXXRecordDecl>( BaseSpec.getType()->castAs<RecordType>()->getDecl()); LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind()); Result.setBaseObjectType(Context.getRecordType(Class)); LookupQualifiedName(Result, RD); // Copy the lookup results into the target, merging the base's access into // the path access. for (auto I = Result.begin(), E = Result.end(); I != E; ++I) { R.addDecl(I.getDecl(), CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(), I.getAccess())); } Result.suppressDiagnostics(); } R.resolveKind(); R.setNamingClass(Class); return !R.empty(); } /// Produce a diagnostic describing the ambiguity that resulted /// from name lookup. /// /// \param Result The result of the ambiguous lookup to be diagnosed. void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) { assert(Result.isAmbiguous() && "Lookup result must be ambiguous"); DeclarationName Name = Result.getLookupName(); SourceLocation NameLoc = Result.getNameLoc(); SourceRange LookupRange = Result.getContextRange(); switch (Result.getAmbiguityKind()) { case LookupResult::AmbiguousBaseSubobjects: { CXXBasePaths *Paths = Result.getBasePaths(); QualType SubobjectType = Paths->front().back().Base->getType(); Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects) << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths) << LookupRange; DeclContext::lookup_iterator Found = Paths->front().Decls.begin(); while (isa<CXXMethodDecl>(*Found) && cast<CXXMethodDecl>(*Found)->isStatic()) ++Found; Diag((*Found)->getLocation(), diag::note_ambiguous_member_found); break; } case LookupResult::AmbiguousBaseSubobjectTypes: { Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types) << Name << LookupRange; CXXBasePaths *Paths = Result.getBasePaths(); std::set<Decl *> DeclsPrinted; for (CXXBasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end(); Path != PathEnd; ++Path) { Decl *D = Path->Decls.front(); if (DeclsPrinted.insert(D).second) Diag(D->getLocation(), diag::note_ambiguous_member_found); } break; } case LookupResult::AmbiguousTagHiding: { Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange; llvm::SmallPtrSet<NamedDecl*, 8> TagDecls; for (auto *D : Result) if (TagDecl *TD = dyn_cast<TagDecl>(D)) { TagDecls.insert(TD); Diag(TD->getLocation(), diag::note_hidden_tag); } for (auto *D : Result) if (!isa<TagDecl>(D)) Diag(D->getLocation(), diag::note_hiding_object); // For recovery purposes, go ahead and implement the hiding. LookupResult::Filter F = Result.makeFilter(); while (F.hasNext()) { if (TagDecls.count(F.next())) F.erase(); } F.done(); break; } case LookupResult::AmbiguousReference: { Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange; for (auto *D : Result) Diag(D->getLocation(), diag::note_ambiguous_candidate) << D; break; } } } namespace { struct AssociatedLookup { AssociatedLookup(Sema &S, SourceLocation InstantiationLoc, Sema::AssociatedNamespaceSet &Namespaces, Sema::AssociatedClassSet &Classes) : S(S), Namespaces(Namespaces), Classes(Classes), InstantiationLoc(InstantiationLoc) { } Sema &S; Sema::AssociatedNamespaceSet &Namespaces; Sema::AssociatedClassSet &Classes; SourceLocation InstantiationLoc; }; } // end anonymous namespace static void addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T); static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces, DeclContext *Ctx) { // Add the associated namespace for this class. // We don't use DeclContext::getEnclosingNamespaceContext() as this may // be a locally scoped record. // We skip out of inline namespaces. The innermost non-inline namespace // contains all names of all its nested inline namespaces anyway, so we can // replace the entire inline namespace tree with its root. while (Ctx->isRecord() || Ctx->isTransparentContext() || Ctx->isInlineNamespace()) Ctx = Ctx->getParent(); if (Ctx->isFileContext()) Namespaces.insert(Ctx->getPrimaryContext()); } // Add the associated classes and namespaces for argument-dependent // lookup that involves a template argument (C++ [basic.lookup.koenig]p2). static void addAssociatedClassesAndNamespaces(AssociatedLookup &Result, const TemplateArgument &Arg) { // C++ [basic.lookup.koenig]p2, last bullet: // -- [...] ; switch (Arg.getKind()) { case TemplateArgument::Null: break; case TemplateArgument::Type: // [...] the namespaces and classes associated with the types of the // template arguments provided for template type parameters (excluding // template template parameters) addAssociatedClassesAndNamespaces(Result, Arg.getAsType()); break; case TemplateArgument::Template: case TemplateArgument::TemplateExpansion: { // [...] the namespaces in which any template template arguments are // defined; and the classes in which any member templates used as // template template arguments are defined. TemplateName Template = Arg.getAsTemplateOrTemplatePattern(); if (ClassTemplateDecl *ClassTemplate = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) { DeclContext *Ctx = ClassTemplate->getDeclContext(); if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) Result.Classes.insert(EnclosingClass); // Add the associated namespace for this class. CollectEnclosingNamespace(Result.Namespaces, Ctx); } break; } case TemplateArgument::Declaration: case TemplateArgument::Integral: case TemplateArgument::Expression: case TemplateArgument::NullPtr: // [Note: non-type template arguments do not contribute to the set of // associated namespaces. ] break; case TemplateArgument::Pack: for (const auto &P : Arg.pack_elements()) addAssociatedClassesAndNamespaces(Result, P); break; } } // Add the associated classes and namespaces for // argument-dependent lookup with an argument of class type // (C++ [basic.lookup.koenig]p2). static void addAssociatedClassesAndNamespaces(AssociatedLookup &Result, CXXRecordDecl *Class) { // Just silently ignore anything whose name is __va_list_tag. if (Class->getDeclName() == Result.S.VAListTagName) return; // C++ [basic.lookup.koenig]p2: // [...] // -- If T is a class type (including unions), its associated // classes are: the class itself; the class of which it is a // member, if any; and its direct and indirect base // classes. Its associated namespaces are the namespaces in // which its associated classes are defined. // Add the class of which it is a member, if any. DeclContext *Ctx = Class->getDeclContext(); if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) Result.Classes.insert(EnclosingClass); // Add the associated namespace for this class. CollectEnclosingNamespace(Result.Namespaces, Ctx); // Add the class itself. If we've already seen this class, we don't // need to visit base classes. // // FIXME: That's not correct, we may have added this class only because it // was the enclosing class of another class, and in that case we won't have // added its base classes yet. if (!Result.Classes.insert(Class)) return; // -- If T is a template-id, its associated namespaces and classes are // the namespace in which the template is defined; for member // templates, the member template's class; the namespaces and classes // associated with the types of the template arguments provided for // template type parameters (excluding template template parameters); the // namespaces in which any template template arguments are defined; and // the classes in which any member templates used as template template // arguments are defined. [Note: non-type template arguments do not // contribute to the set of associated namespaces. ] if (ClassTemplateSpecializationDecl *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Class)) { DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext(); if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) Result.Classes.insert(EnclosingClass); // Add the associated namespace for this class. CollectEnclosingNamespace(Result.Namespaces, Ctx); const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I) addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]); } // Only recurse into base classes for complete types. if (!Result.S.isCompleteType(Result.InstantiationLoc, Result.S.Context.getRecordType(Class))) return; // Add direct and indirect base classes along with their associated // namespaces. SmallVector<CXXRecordDecl *, 32> Bases; Bases.push_back(Class); while (!Bases.empty()) { // Pop this class off the stack. Class = Bases.pop_back_val(); // Visit the base classes. for (const auto &Base : Class->bases()) { const RecordType *BaseType = Base.getType()->getAs<RecordType>(); // In dependent contexts, we do ADL twice, and the first time around, // the base type might be a dependent TemplateSpecializationType, or a // TemplateTypeParmType. If that happens, simply ignore it. // FIXME: If we want to support export, we probably need to add the // namespace of the template in a TemplateSpecializationType, or even // the classes and namespaces of known non-dependent arguments. if (!BaseType) continue; CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl()); if (Result.Classes.insert(BaseDecl)) { // Find the associated namespace for this base class. DeclContext *BaseCtx = BaseDecl->getDeclContext(); CollectEnclosingNamespace(Result.Namespaces, BaseCtx); // Make sure we visit the bases of this base class. if (BaseDecl->bases_begin() != BaseDecl->bases_end()) Bases.push_back(BaseDecl); } } } } // Add the associated classes and namespaces for // argument-dependent lookup with an argument of type T // (C++ [basic.lookup.koenig]p2). static void addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) { // C++ [basic.lookup.koenig]p2: // // For each argument type T in the function call, there is a set // of zero or more associated namespaces and a set of zero or more // associated classes to be considered. The sets of namespaces and // classes is determined entirely by the types of the function // arguments (and the namespace of any template template // argument). Typedef names and using-declarations used to specify // the types do not contribute to this set. The sets of namespaces // and classes are determined in the following way: SmallVector<const Type *, 16> Queue; const Type *T = Ty->getCanonicalTypeInternal().getTypePtr(); while (true) { switch (T->getTypeClass()) { #define TYPE(Class, Base) #define DEPENDENT_TYPE(Class, Base) case Type::Class: #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: #define ABSTRACT_TYPE(Class, Base) #include "clang/AST/TypeNodes.def" // T is canonical. We can also ignore dependent types because // we don't need to do ADL at the definition point, but if we // wanted to implement template export (or if we find some other // use for associated classes and namespaces...) this would be // wrong. break; // -- If T is a pointer to U or an array of U, its associated // namespaces and classes are those associated with U. case Type::Pointer: T = cast<PointerType>(T)->getPointeeType().getTypePtr(); continue; case Type::ConstantArray: case Type::IncompleteArray: case Type::VariableArray: T = cast<ArrayType>(T)->getElementType().getTypePtr(); continue; // -- If T is a fundamental type, its associated sets of // namespaces and classes are both empty. case Type::Builtin: break; // -- If T is a class type (including unions), its associated // classes are: the class itself; the class of which it is a // member, if any; and its direct and indirect base // classes. Its associated namespaces are the namespaces in // which its associated classes are defined. case Type::Record: { CXXRecordDecl *Class = cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl()); addAssociatedClassesAndNamespaces(Result, Class); break; } // -- If T is an enumeration type, its associated namespace is // the namespace in which it is defined. If it is class // member, its associated class is the member's class; else // it has no associated class. case Type::Enum: { EnumDecl *Enum = cast<EnumType>(T)->getDecl(); DeclContext *Ctx = Enum->getDeclContext(); if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx)) Result.Classes.insert(EnclosingClass); // Add the associated namespace for this class. CollectEnclosingNamespace(Result.Namespaces, Ctx); break; } // -- If T is a function type, its associated namespaces and // classes are those associated with the function parameter // types and those associated with the return type. case Type::FunctionProto: { const FunctionProtoType *Proto = cast<FunctionProtoType>(T); for (const auto &Arg : Proto->param_types()) Queue.push_back(Arg.getTypePtr()); // fallthrough LLVM_FALLTHROUGH; } case Type::FunctionNoProto: { const FunctionType *FnType = cast<FunctionType>(T); T = FnType->getReturnType().getTypePtr(); continue; } // -- If T is a pointer to a member function of a class X, its // associated namespaces and classes are those associated // with the function parameter types and return type, // together with those associated with X. // // -- If T is a pointer to a data member of class X, its // associated namespaces and classes are those associated // with the member type together with those associated with // X. case Type::MemberPointer: { const MemberPointerType *MemberPtr = cast<MemberPointerType>(T); // Queue up the class type into which this points. Queue.push_back(MemberPtr->getClass()); // And directly continue with the pointee type. T = MemberPtr->getPointeeType().getTypePtr(); continue; } // As an extension, treat this like a normal pointer. case Type::BlockPointer: T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr(); continue; // References aren't covered by the standard, but that's such an // obvious defect that we cover them anyway. case Type::LValueReference: case Type::RValueReference: T = cast<ReferenceType>(T)->getPointeeType().getTypePtr(); continue; // These are fundamental types. case Type::Vector: case Type::ExtVector: case Type::Complex: break; // Non-deduced auto types only get here for error cases. case Type::Auto: case Type::DeducedTemplateSpecialization: break; // If T is an Objective-C object or interface type, or a pointer to an // object or interface type, the associated namespace is the global // namespace. case Type::ObjCObject: case Type::ObjCInterface: case Type::ObjCObjectPointer: Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl()); break; // Atomic types are just wrappers; use the associations of the // contained type. case Type::Atomic: T = cast<AtomicType>(T)->getValueType().getTypePtr(); continue; case Type::Pipe: T = cast<PipeType>(T)->getElementType().getTypePtr(); continue; } if (Queue.empty()) break; T = Queue.pop_back_val(); } } /// Find the associated classes and namespaces for /// argument-dependent lookup for a call with the given set of /// arguments. /// /// This routine computes the sets of associated classes and associated /// namespaces searched by argument-dependent lookup /// (C++ [basic.lookup.argdep]) for a given set of arguments. void Sema::FindAssociatedClassesAndNamespaces( SourceLocation InstantiationLoc, ArrayRef<Expr *> Args, AssociatedNamespaceSet &AssociatedNamespaces, AssociatedClassSet &AssociatedClasses) { AssociatedNamespaces.clear(); AssociatedClasses.clear(); AssociatedLookup Result(*this, InstantiationLoc, AssociatedNamespaces, AssociatedClasses); // C++ [basic.lookup.koenig]p2: // For each argument type T in the function call, there is a set // of zero or more associated namespaces and a set of zero or more // associated classes to be considered. The sets of namespaces and // classes is determined entirely by the types of the function // arguments (and the namespace of any template template // argument). for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) { Expr *Arg = Args[ArgIdx]; if (Arg->getType() != Context.OverloadTy) { addAssociatedClassesAndNamespaces(Result, Arg->getType()); continue; } // [...] In addition, if the argument is the name or address of a // set of overloaded functions and/or function templates, its // associated classes and namespaces are the union of those // associated with each of the members of the set: the namespace // in which the function or function template is defined and the // classes and namespaces associated with its (non-dependent) // parameter types and return type. Arg = Arg->IgnoreParens(); if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) if (unaryOp->getOpcode() == UO_AddrOf) Arg = unaryOp->getSubExpr(); UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg); if (!ULE) continue; for (const auto *D : ULE->decls()) { // Look through any using declarations to find the underlying function. const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction(); // Add the classes and namespaces associated with the parameter // types and return type of this function. addAssociatedClassesAndNamespaces(Result, FDecl->getType()); } } } NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl) { LookupResult R(*this, Name, Loc, NameKind, Redecl); LookupName(R, S); return R.getAsSingle<NamedDecl>(); } /// Find the protocol with the given name, if any. ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl) { Decl *D = LookupSingleName(TUScope, II, IdLoc, LookupObjCProtocolName, Redecl); return cast_or_null<ObjCProtocolDecl>(D); } void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S, QualType T1, QualType T2, UnresolvedSetImpl &Functions) { // C++ [over.match.oper]p3: // -- The set of non-member candidates is the result of the // unqualified lookup of operator@ in the context of the // expression according to the usual rules for name lookup in // unqualified function calls (3.4.2) except that all member // functions are ignored. DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op); LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName); LookupName(Operators, S); assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"); Functions.append(Operators.begin(), Operators.end()); } Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD, CXXSpecialMember SM, bool ConstArg, bool VolatileArg, bool RValueThis, bool ConstThis, bool VolatileThis) { assert(CanDeclareSpecialMemberFunction(RD) && "doing special member lookup into record that isn't fully complete"); RD = RD->getDefinition(); if (RValueThis || ConstThis || VolatileThis) assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) && "constructors and destructors always have unqualified lvalue this"); if (ConstArg || VolatileArg) assert((SM != CXXDefaultConstructor && SM != CXXDestructor) && "parameter-less special members can't have qualified arguments"); // FIXME: Get the caller to pass in a location for the lookup. SourceLocation LookupLoc = RD->getLocation(); llvm::FoldingSetNodeID ID; ID.AddPointer(RD); ID.AddInteger(SM); ID.AddInteger(ConstArg); ID.AddInteger(VolatileArg); ID.AddInteger(RValueThis); ID.AddInteger(ConstThis); ID.AddInteger(VolatileThis); void *InsertPoint; SpecialMemberOverloadResultEntry *Result = SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint); // This was already cached if (Result) return *Result; Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>(); Result = new (Result) SpecialMemberOverloadResultEntry(ID); SpecialMemberCache.InsertNode(Result, InsertPoint); if (SM == CXXDestructor) { if (RD->needsImplicitDestructor()) DeclareImplicitDestructor(RD); CXXDestructorDecl *DD = RD->getDestructor(); assert(DD && "record without a destructor"); Result->setMethod(DD); Result->setKind(DD->isDeleted() ? SpecialMemberOverloadResult::NoMemberOrDeleted : SpecialMemberOverloadResult::Success); return *Result; } // Prepare for overload resolution. Here we construct a synthetic argument // if necessary and make sure that implicit functions are declared. CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD)); DeclarationName Name; Expr *Arg = nullptr; unsigned NumArgs; QualType ArgType = CanTy; ExprValueKind VK = VK_LValue; if (SM == CXXDefaultConstructor) { Name = Context.DeclarationNames.getCXXConstructorName(CanTy); NumArgs = 0; if (RD->needsImplicitDefaultConstructor()) DeclareImplicitDefaultConstructor(RD); } else { if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) { Name = Context.DeclarationNames.getCXXConstructorName(CanTy); if (RD->needsImplicitCopyConstructor()) DeclareImplicitCopyConstructor(RD); if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) DeclareImplicitMoveConstructor(RD); } else { Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal); if (RD->needsImplicitCopyAssignment()) DeclareImplicitCopyAssignment(RD); if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) DeclareImplicitMoveAssignment(RD); } if (ConstArg) ArgType.addConst(); if (VolatileArg) ArgType.addVolatile(); // This isn't /really/ specified by the standard, but it's implied // we should be working from an RValue in the case of move to ensure // that we prefer to bind to rvalue references, and an LValue in the // case of copy to ensure we don't bind to rvalue references. // Possibly an XValue is actually correct in the case of move, but // there is no semantic difference for class types in this restricted // case. if (SM == CXXCopyConstructor || SM == CXXCopyAssignment) VK = VK_LValue; else VK = VK_RValue; } OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK); if (SM != CXXDefaultConstructor) { NumArgs = 1; Arg = &FakeArg; } // Create the object argument QualType ThisTy = CanTy; if (ConstThis) ThisTy.addConst(); if (VolatileThis) ThisTy.addVolatile(); Expr::Classification Classification = OpaqueValueExpr(LookupLoc, ThisTy, RValueThis ? VK_RValue : VK_LValue).Classify(Context); // Now we perform lookup on the name we computed earlier and do overload // resolution. Lookup is only performed directly into the class since there // will always be a (possibly implicit) declaration to shadow any others. OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal); DeclContext::lookup_result R = RD->lookup(Name); if (R.empty()) { // We might have no default constructor because we have a lambda's closure // type, rather than because there's some other declared constructor. // Every class has a copy/move constructor, copy/move assignment, and // destructor. assert(SM == CXXDefaultConstructor && "lookup for a constructor or assignment operator was empty"); Result->setMethod(nullptr); Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); return *Result; } // Copy the candidates as our processing of them may load new declarations // from an external source and invalidate lookup_result. SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end()); for (NamedDecl *CandDecl : Candidates) { if (CandDecl->isInvalidDecl()) continue; DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public); auto CtorInfo = getConstructorInfo(Cand); if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) { if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) AddMethodCandidate(M, Cand, RD, ThisTy, Classification, llvm::makeArrayRef(&Arg, NumArgs), OCS, true); else if (CtorInfo) AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl, llvm::makeArrayRef(&Arg, NumArgs), OCS, true); else AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS, true); } else if (FunctionTemplateDecl *Tmpl = dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) { if (SM == CXXCopyAssignment || SM == CXXMoveAssignment) AddMethodTemplateCandidate( Tmpl, Cand, RD, nullptr, ThisTy, Classification, llvm::makeArrayRef(&Arg, NumArgs), OCS, true); else if (CtorInfo) AddTemplateOverloadCandidate( CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true); else AddTemplateOverloadCandidate( Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true); } else { assert(isa<UsingDecl>(Cand.getDecl()) && "illegal Kind of operator = Decl"); } } OverloadCandidateSet::iterator Best; switch (OCS.BestViableFunction(*this, LookupLoc, Best)) { case OR_Success: Result->setMethod(cast<CXXMethodDecl>(Best->Function)); Result->setKind(SpecialMemberOverloadResult::Success); break; case OR_Deleted: Result->setMethod(cast<CXXMethodDecl>(Best->Function)); Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); break; case OR_Ambiguous: Result->setMethod(nullptr); Result->setKind(SpecialMemberOverloadResult::Ambiguous); break; case OR_No_Viable_Function: Result->setMethod(nullptr); Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted); break; } return *Result; } /// Look up the default constructor for the given class. CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) { SpecialMemberOverloadResult Result = LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false, false, false); return cast_or_null<CXXConstructorDecl>(Result.getMethod()); } /// Look up the copying constructor for the given class. CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class, unsigned Quals) { assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && "non-const, non-volatile qualifiers for copy ctor arg"); SpecialMemberOverloadResult Result = LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const, Quals & Qualifiers::Volatile, false, false, false); return cast_or_null<CXXConstructorDecl>(Result.getMethod()); } /// Look up the moving constructor for the given class. CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class, unsigned Quals) { SpecialMemberOverloadResult Result = LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const, Quals & Qualifiers::Volatile, false, false, false); return cast_or_null<CXXConstructorDecl>(Result.getMethod()); } /// Look up the constructors for the given class. DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) { // If the implicit constructors have not yet been declared, do so now. if (CanDeclareSpecialMemberFunction(Class)) { if (Class->needsImplicitDefaultConstructor()) DeclareImplicitDefaultConstructor(Class); if (Class->needsImplicitCopyConstructor()) DeclareImplicitCopyConstructor(Class); if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor()) DeclareImplicitMoveConstructor(Class); } CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class)); DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T); return Class->lookup(Name); } /// Look up the copying assignment operator for the given class. CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals) { assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && "non-const, non-volatile qualifiers for copy assignment arg"); assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && "non-const, non-volatile qualifiers for copy assignment this"); SpecialMemberOverloadResult Result = LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const, Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const, ThisQuals & Qualifiers::Volatile); return Result.getMethod(); } /// Look up the moving assignment operator for the given class. CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class, unsigned Quals, bool RValueThis, unsigned ThisQuals) { assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && "non-const, non-volatile qualifiers for copy assignment this"); SpecialMemberOverloadResult Result = LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const, Quals & Qualifiers::Volatile, RValueThis, ThisQuals & Qualifiers::Const, ThisQuals & Qualifiers::Volatile); return Result.getMethod(); } /// Look for the destructor of the given class. /// /// During semantic analysis, this routine should be used in lieu of /// CXXRecordDecl::getDestructor(). /// /// \returns The destructor for this class. CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) { return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor, false, false, false, false, false).getMethod()); } /// LookupLiteralOperator - Determine which literal operator should be used for /// a user-defined literal, per C++11 [lex.ext]. /// /// Normal overload resolution is not used to select which literal operator to /// call for a user-defined literal. Look up the provided literal operator name, /// and filter the results to the appropriate set for the given argument types. Sema::LiteralOperatorLookupResult Sema::LookupLiteralOperator(Scope *S, LookupResult &R, ArrayRef<QualType> ArgTys, bool AllowRaw, bool AllowTemplate, bool AllowStringTemplate, bool DiagnoseMissing) { LookupName(R, S); assert(R.getResultKind() != LookupResult::Ambiguous && "literal operator lookup can't be ambiguous"); // Filter the lookup results appropriately. LookupResult::Filter F = R.makeFilter(); bool FoundRaw = false; bool FoundTemplate = false; bool FoundStringTemplate = false; bool FoundExactMatch = false; while (F.hasNext()) { Decl *D = F.next(); if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D)) D = USD->getTargetDecl(); // If the declaration we found is invalid, skip it. if (D->isInvalidDecl()) { F.erase(); continue; } bool IsRaw = false; bool IsTemplate = false; bool IsStringTemplate = false; bool IsExactMatch = false; if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { if (FD->getNumParams() == 1 && FD->getParamDecl(0)->getType()->getAs<PointerType>()) IsRaw = true; else if (FD->getNumParams() == ArgTys.size()) { IsExactMatch = true; for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) { QualType ParamTy = FD->getParamDecl(ArgIdx)->getType(); if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) { IsExactMatch = false; break; } } } } if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) { TemplateParameterList *Params = FD->getTemplateParameters(); if (Params->size() == 1) IsTemplate = true; else IsStringTemplate = true; } if (IsExactMatch) { FoundExactMatch = true; AllowRaw = false; AllowTemplate = false; AllowStringTemplate = false; if (FoundRaw || FoundTemplate || FoundStringTemplate) { // Go through again and remove the raw and template decls we've // already found. F.restart(); FoundRaw = FoundTemplate = FoundStringTemplate = false; } } else if (AllowRaw && IsRaw) { FoundRaw = true; } else if (AllowTemplate && IsTemplate) { FoundTemplate = true; } else if (AllowStringTemplate && IsStringTemplate) { FoundStringTemplate = true; } else { F.erase(); } } F.done(); // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching // parameter type, that is used in preference to a raw literal operator // or literal operator template. if (FoundExactMatch) return LOLR_Cooked; // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal // operator template, but not both. if (FoundRaw && FoundTemplate) { Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName(); for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction()); return LOLR_Error; } if (FoundRaw) return LOLR_Raw; if (FoundTemplate) return LOLR_Template; if (FoundStringTemplate) return LOLR_StringTemplate; // Didn't find anything we could use. if (DiagnoseMissing) { Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator) << R.getLookupName() << (int)ArgTys.size() << ArgTys[0] << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw << (AllowTemplate || AllowStringTemplate); return LOLR_Error; } return LOLR_ErrorNoDiagnostic; } void ADLResult::insert(NamedDecl *New) { NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())]; // If we haven't yet seen a decl for this key, or the last decl // was exactly this one, we're done. if (Old == nullptr || Old == New) { Old = New; return; } // Otherwise, decide which is a more recent redeclaration. FunctionDecl *OldFD = Old->getAsFunction(); FunctionDecl *NewFD = New->getAsFunction(); FunctionDecl *Cursor = NewFD; while (true) { Cursor = Cursor->getPreviousDecl(); // If we got to the end without finding OldFD, OldFD is the newer // declaration; leave things as they are. if (!Cursor) return; // If we do find OldFD, then NewFD is newer. if (Cursor == OldFD) break; // Otherwise, keep looking. } Old = New; } void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc, ArrayRef<Expr *> Args, ADLResult &Result) { // Find all of the associated namespaces and classes based on the // arguments we have. AssociatedNamespaceSet AssociatedNamespaces; AssociatedClassSet AssociatedClasses; FindAssociatedClassesAndNamespaces(Loc, Args, AssociatedNamespaces, AssociatedClasses); // C++ [basic.lookup.argdep]p3: // Let X be the lookup set produced by unqualified lookup (3.4.1) // and let Y be the lookup set produced by argument dependent // lookup (defined as follows). If X contains [...] then Y is // empty. Otherwise Y is the set of declarations found in the // namespaces associated with the argument types as described // below. The set of declarations found by the lookup of the name // is the union of X and Y. // // Here, we compute Y and add its members to the overloaded // candidate set. for (auto *NS : AssociatedNamespaces) { // When considering an associated namespace, the lookup is the // same as the lookup performed when the associated namespace is // used as a qualifier (3.4.3.2) except that: // // -- Any using-directives in the associated namespace are // ignored. // // -- Any namespace-scope friend functions declared in // associated classes are visible within their respective // namespaces even if they are not visible during an ordinary // lookup (11.4). DeclContext::lookup_result R = NS->lookup(Name); for (auto *D : R) { auto *Underlying = D; if (auto *USD = dyn_cast<UsingShadowDecl>(D)) Underlying = USD->getTargetDecl(); if (!isa<FunctionDecl>(Underlying) && !isa<FunctionTemplateDecl>(Underlying)) continue; if (!isVisible(D)) { D = findAcceptableDecl( *this, D, (Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend)); if (!D) continue; if (auto *USD = dyn_cast<UsingShadowDecl>(D)) Underlying = USD->getTargetDecl(); } // If the only declaration here is an ordinary friend, consider // it only if it was declared in an associated classes. if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) { // If it's neither ordinarily visible nor a friend, we can't find it. if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0) continue; bool DeclaredInAssociatedClass = false; for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) { DeclContext *LexDC = DI->getLexicalDeclContext(); if (isa<CXXRecordDecl>(LexDC) && AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)) && isVisible(cast<NamedDecl>(DI))) { DeclaredInAssociatedClass = true; break; } } if (!DeclaredInAssociatedClass) continue; } // FIXME: Preserve D as the FoundDecl. Result.insert(Underlying); } } } //---------------------------------------------------------------------------- // Search for all visible declarations. //---------------------------------------------------------------------------- VisibleDeclConsumer::~VisibleDeclConsumer() { } bool VisibleDeclConsumer::includeHiddenDecls() const { return false; } namespace { class ShadowContextRAII; class VisibleDeclsRecord { public: /// An entry in the shadow map, which is optimized to store a /// single declaration (the common case) but can also store a list /// of declarations. typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry; private: /// A mapping from declaration names to the declarations that have /// this name within a particular scope. typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap; /// A list of shadow maps, which is used to model name hiding. std::list<ShadowMap> ShadowMaps; /// The declaration contexts we have already visited. llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts; friend class ShadowContextRAII; public: /// Determine whether we have already visited this context /// (and, if not, note that we are going to visit that context now). bool visitedContext(DeclContext *Ctx) { return !VisitedContexts.insert(Ctx).second; } bool alreadyVisitedContext(DeclContext *Ctx) { return VisitedContexts.count(Ctx); } /// Determine whether the given declaration is hidden in the /// current scope. /// /// \returns the declaration that hides the given declaration, or /// NULL if no such declaration exists. NamedDecl *checkHidden(NamedDecl *ND); /// Add a declaration to the current shadow map. void add(NamedDecl *ND) { ShadowMaps.back()[ND->getDeclName()].push_back(ND); } }; /// RAII object that records when we've entered a shadow context. class ShadowContextRAII { VisibleDeclsRecord &Visible; typedef VisibleDeclsRecord::ShadowMap ShadowMap; public: ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) { Visible.ShadowMaps.emplace_back(); } ~ShadowContextRAII() { Visible.ShadowMaps.pop_back(); } }; } // end anonymous namespace NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) { unsigned IDNS = ND->getIdentifierNamespace(); std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin(); for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend(); SM != SMEnd; ++SM) { ShadowMap::iterator Pos = SM->find(ND->getDeclName()); if (Pos == SM->end()) continue; for (auto *D : Pos->second) { // A tag declaration does not hide a non-tag declaration. if (D->hasTagIdentifierNamespace() && (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary | Decl::IDNS_ObjCProtocol))) continue; // Protocols are in distinct namespaces from everything else. if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol) || (IDNS & Decl::IDNS_ObjCProtocol)) && D->getIdentifierNamespace() != IDNS) continue; // Functions and function templates in the same scope overload // rather than hide. FIXME: Look for hiding based on function // signatures! if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() && SM == ShadowMaps.rbegin()) continue; // A shadow declaration that's created by a resolved using declaration // is not hidden by the same using declaration. if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) && cast<UsingShadowDecl>(ND)->getUsingDecl() == D) continue; // We've found a declaration that hides this one. return D; } } return nullptr; } static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result, bool QualifiedNameLookup, bool InBaseClass, VisibleDeclConsumer &Consumer, VisibleDeclsRecord &Visited, bool IncludeDependentBases, bool LoadExternal) { if (!Ctx) return; // Make sure we don't visit the same context twice. if (Visited.visitedContext(Ctx->getPrimaryContext())) return; Consumer.EnteredContext(Ctx); // Outside C++, lookup results for the TU live on identifiers. if (isa<TranslationUnitDecl>(Ctx) && !Result.getSema().getLangOpts().CPlusPlus) { auto &S = Result.getSema(); auto &Idents = S.Context.Idents; // Ensure all external identifiers are in the identifier table. if (LoadExternal) if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) { std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers()); for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next()) Idents.get(Name); } // Walk all lookup results in the TU for each identifier. for (const auto &Ident : Idents) { for (auto I = S.IdResolver.begin(Ident.getValue()), E = S.IdResolver.end(); I != E; ++I) { if (S.IdResolver.isDeclInScope(*I, Ctx)) { if (NamedDecl *ND = Result.getAcceptableDecl(*I)) { Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); Visited.add(ND); } } } } return; } if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) Result.getSema().ForceDeclarationOfImplicitMembers(Class); // We sometimes skip loading namespace-level results (they tend to be huge). bool Load = LoadExternal || !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx)); // Enumerate all of the results in this context. for (DeclContextLookupResult R : Load ? Ctx->lookups() : Ctx->noload_lookups(/*PreserveInternalState=*/false)) { for (auto *D : R) { if (auto *ND = Result.getAcceptableDecl(D)) { Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass); Visited.add(ND); } } } // Traverse using directives for qualified name lookup. if (QualifiedNameLookup) { ShadowContextRAII Shadow(Visited); for (auto I : Ctx->using_directives()) { if (!Result.getSema().isVisible(I)) continue; LookupVisibleDecls(I->getNominatedNamespace(), Result, QualifiedNameLookup, InBaseClass, Consumer, Visited, IncludeDependentBases, LoadExternal); } } // Traverse the contexts of inherited C++ classes. if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) { if (!Record->hasDefinition()) return; for (const auto &B : Record->bases()) { QualType BaseType = B.getType(); RecordDecl *RD; if (BaseType->isDependentType()) { if (!IncludeDependentBases) { // Don't look into dependent bases, because name lookup can't look // there anyway. continue; } const auto *TST = BaseType->getAs<TemplateSpecializationType>(); if (!TST) continue; TemplateName TN = TST->getTemplateName(); const auto *TD = dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl()); if (!TD) continue; RD = TD->getTemplatedDecl(); } else { const auto *Record = BaseType->getAs<RecordType>(); if (!Record) continue; RD = Record->getDecl(); } // FIXME: It would be nice to be able to determine whether referencing // a particular member would be ambiguous. For example, given // // struct A { int member; }; // struct B { int member; }; // struct C : A, B { }; // // void f(C *c) { c->### } // // accessing 'member' would result in an ambiguity. However, we // could be smart enough to qualify the member with the base // class, e.g., // // c->B::member // // or // // c->A::member // Find results in this base class (and its bases). ShadowContextRAII Shadow(Visited); LookupVisibleDecls(RD, Result, QualifiedNameLookup, true, Consumer, Visited, IncludeDependentBases, LoadExternal); } } // Traverse the contexts of Objective-C classes. if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) { // Traverse categories. for (auto *Cat : IFace->visible_categories()) { ShadowContextRAII Shadow(Visited); LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false, Consumer, Visited, IncludeDependentBases, LoadExternal); } // Traverse protocols. for (auto *I : IFace->all_referenced_protocols()) { ShadowContextRAII Shadow(Visited); LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, Visited, IncludeDependentBases, LoadExternal); } // Traverse the superclass. if (IFace->getSuperClass()) { ShadowContextRAII Shadow(Visited); LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup, true, Consumer, Visited, IncludeDependentBases, LoadExternal); } // If there is an implementation, traverse it. We do this to find // synthesized ivars. if (IFace->getImplementation()) { ShadowContextRAII Shadow(Visited); LookupVisibleDecls(IFace->getImplementation(), Result, QualifiedNameLookup, InBaseClass, Consumer, Visited, IncludeDependentBases, LoadExternal); } } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) { for (auto *I : Protocol->protocols()) { ShadowContextRAII Shadow(Visited); LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, Visited, IncludeDependentBases, LoadExternal); } } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) { for (auto *I : Category->protocols()) { ShadowContextRAII Shadow(Visited); LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer, Visited, IncludeDependentBases, LoadExternal); } // If there is an implementation, traverse it. if (Category->getImplementation()) { ShadowContextRAII Shadow(Visited); LookupVisibleDecls(Category->getImplementation(), Result, QualifiedNameLookup, true, Consumer, Visited, IncludeDependentBases, LoadExternal); } } } static void LookupVisibleDecls(Scope *S, LookupResult &Result, UnqualUsingDirectiveSet &UDirs, VisibleDeclConsumer &Consumer, VisibleDeclsRecord &Visited, bool LoadExternal) { if (!S) return; if (!S->getEntity() || (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) || (S->getEntity())->isFunctionOrMethod()) { FindLocalExternScope FindLocals(Result); // Walk through the declarations in this Scope. The consumer might add new // decls to the scope as part of deserialization, so make a copy first. SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end()); for (Decl *D : ScopeDecls) { if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) if ((ND = Result.getAcceptableDecl(ND))) { Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false); Visited.add(ND); } } } // FIXME: C++ [temp.local]p8 DeclContext *Entity = nullptr; if (S->getEntity()) { // Look into this scope's declaration context, along with any of its // parent lookup contexts (e.g., enclosing classes), up to the point // where we hit the context stored in the next outer scope. Entity = S->getEntity(); DeclContext *OuterCtx = findOuterContext(S).first; // FIXME for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) { if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) { if (Method->isInstanceMethod()) { // For instance methods, look for ivars in the method's interface. LookupResult IvarResult(Result.getSema(), Result.getLookupName(), Result.getNameLoc(), Sema::LookupMemberName); if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) { LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false, /*InBaseClass=*/false, Consumer, Visited, /*IncludeDependentBases=*/false, LoadExternal); } } // We've already performed all of the name lookup that we need // to for Objective-C methods; the next context will be the // outer scope. break; } if (Ctx->isFunctionOrMethod()) continue; LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false, /*InBaseClass=*/false, Consumer, Visited, /*IncludeDependentBases=*/false, LoadExternal); } } else if (!S->getParent()) { // Look into the translation unit scope. We walk through the translation // unit's declaration context, because the Scope itself won't have all of // the declarations if we loaded a precompiled header. // FIXME: We would like the translation unit's Scope object to point to the // translation unit, so we don't need this special "if" branch. However, // doing so would force the normal C++ name-lookup code to look into the // translation unit decl when the IdentifierInfo chains would suffice. // Once we fix that problem (which is part of a more general "don't look // in DeclContexts unless we have to" optimization), we can eliminate this. Entity = Result.getSema().Context.getTranslationUnitDecl(); LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false, /*InBaseClass=*/false, Consumer, Visited, /*IncludeDependentBases=*/false, LoadExternal); } if (Entity) { // Lookup visible declarations in any namespaces found by using // directives. for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity)) LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result, /*QualifiedNameLookup=*/false, /*InBaseClass=*/false, Consumer, Visited, /*IncludeDependentBases=*/false, LoadExternal); } // Lookup names in the parent scope. ShadowContextRAII Shadow(Visited); LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited, LoadExternal); } void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope, bool LoadExternal) { // Determine the set of using directives available during // unqualified name lookup. Scope *Initial = S; UnqualUsingDirectiveSet UDirs(*this); if (getLangOpts().CPlusPlus) { // Find the first namespace or translation-unit scope. while (S && !isNamespaceOrTranslationUnitScope(S)) S = S->getParent(); UDirs.visitScopeChain(Initial, S); } UDirs.done(); // Look for visible declarations. LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); Result.setAllowHidden(Consumer.includeHiddenDecls()); VisibleDeclsRecord Visited; if (!IncludeGlobalScope) Visited.visitedContext(Context.getTranslationUnitDecl()); ShadowContextRAII Shadow(Visited); ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited, LoadExternal); } void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind, VisibleDeclConsumer &Consumer, bool IncludeGlobalScope, bool IncludeDependentBases, bool LoadExternal) { LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind); Result.setAllowHidden(Consumer.includeHiddenDecls()); VisibleDeclsRecord Visited; if (!IncludeGlobalScope) Visited.visitedContext(Context.getTranslationUnitDecl()); ShadowContextRAII Shadow(Visited); ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true, /*InBaseClass=*/false, Consumer, Visited, IncludeDependentBases, LoadExternal); } /// LookupOrCreateLabel - Do a name lookup of a label with the specified name. /// If GnuLabelLoc is a valid source location, then this is a definition /// of an __label__ label name, otherwise it is a normal label definition /// or use. LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc, SourceLocation GnuLabelLoc) { // Do a lookup to see if we have a label with this name already. NamedDecl *Res = nullptr; if (GnuLabelLoc.isValid()) { // Local label definitions always shadow existing labels. Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc); Scope *S = CurScope; PushOnScopeChains(Res, S, true); return cast<LabelDecl>(Res); } // Not a GNU local label. Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration); // If we found a label, check to see if it is in the same context as us. // When in a Block, we don't want to reuse a label in an enclosing function. if (Res && Res->getDeclContext() != CurContext) Res = nullptr; if (!Res) { // If not forward referenced or defined already, create the backing decl. Res = LabelDecl::Create(Context, CurContext, Loc, II); Scope *S = CurScope->getFnParent(); assert(S && "Not in a function?"); PushOnScopeChains(Res, S, true); } return cast<LabelDecl>(Res); } //===----------------------------------------------------------------------===// // Typo correction //===----------------------------------------------------------------------===// static bool isCandidateViable(CorrectionCandidateCallback &CCC, TypoCorrection &Candidate) { Candidate.setCallbackDistance(CCC.RankCandidate(Candidate)); return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance; } static void LookupPotentialTypoResult(Sema &SemaRef, LookupResult &Res, IdentifierInfo *Name, Scope *S, CXXScopeSpec *SS, DeclContext *MemberContext, bool EnteringContext, bool isObjCIvarLookup, bool FindHidden); /// Check whether the declarations found for a typo correction are /// visible. Set the correction's RequiresImport flag to true if none of the /// declarations are visible, false otherwise. static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) { TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end(); for (/**/; DI != DE; ++DI) if (!LookupResult::isVisible(SemaRef, *DI)) break; // No filtering needed if all decls are visible. if (DI == DE) { TC.setRequiresImport(false); return; } llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI); bool AnyVisibleDecls = !NewDecls.empty(); for (/**/; DI != DE; ++DI) { if (LookupResult::isVisible(SemaRef, *DI)) { if (!AnyVisibleDecls) { // Found a visible decl, discard all hidden ones. AnyVisibleDecls = true; NewDecls.clear(); } NewDecls.push_back(*DI); } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate()) NewDecls.push_back(*DI); } if (NewDecls.empty()) TC = TypoCorrection(); else { TC.setCorrectionDecls(NewDecls); TC.setRequiresImport(!AnyVisibleDecls); } } // Fill the supplied vector with the IdentifierInfo pointers for each piece of // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::", // fill the vector with the IdentifierInfo pointers for "foo" and "bar"). static void getNestedNameSpecifierIdentifiers( NestedNameSpecifier *NNS, SmallVectorImpl<const IdentifierInfo*> &Identifiers) { if (NestedNameSpecifier *Prefix = NNS->getPrefix()) getNestedNameSpecifierIdentifiers(Prefix, Identifiers); else Identifiers.clear(); const IdentifierInfo *II = nullptr; switch (NNS->getKind()) { case NestedNameSpecifier::Identifier: II = NNS->getAsIdentifier(); break; case NestedNameSpecifier::Namespace: if (NNS->getAsNamespace()->isAnonymousNamespace()) return; II = NNS->getAsNamespace()->getIdentifier(); break; case NestedNameSpecifier::NamespaceAlias: II = NNS->getAsNamespaceAlias()->getIdentifier(); break; case NestedNameSpecifier::TypeSpecWithTemplate: case NestedNameSpecifier::TypeSpec: II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier(); break; case NestedNameSpecifier::Global: case NestedNameSpecifier::Super: return; } if (II) Identifiers.push_back(II); } void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding, DeclContext *Ctx, bool InBaseClass) { // Don't consider hidden names for typo correction. if (Hiding) return; // Only consider entities with identifiers for names, ignoring // special names (constructors, overloaded operators, selectors, // etc.). IdentifierInfo *Name = ND->getIdentifier(); if (!Name) return; // Only consider visible declarations and declarations from modules with // names that exactly match. if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo) return; FoundName(Name->getName()); } void TypoCorrectionConsumer::FoundName(StringRef Name) { // Compute the edit distance between the typo and the name of this // entity, and add the identifier to the list of results. addName(Name, nullptr); } void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) { // Compute the edit distance between the typo and this keyword, // and add the keyword to the list of results. addName(Keyword, nullptr, nullptr, true); } void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND, NestedNameSpecifier *NNS, bool isKeyword) { // Use a simple length-based heuristic to determine the minimum possible // edit distance. If the minimum isn't good enough, bail out early. StringRef TypoStr = Typo->getName(); unsigned MinED = abs((int)Name.size() - (int)TypoStr.size()); if (MinED && TypoStr.size() / MinED < 3) return; // Compute an upper bound on the allowable edit distance, so that the // edit-distance algorithm can short-circuit. unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1; unsigned ED = TypoStr.edit_distance(Name, true, UpperBound); if (ED >= UpperBound) return; TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED); if (isKeyword) TC.makeKeyword(); TC.setCorrectionRange(nullptr, Result.getLookupNameInfo()); addCorrection(TC); } static const unsigned MaxTypoDistanceResultSets = 5; void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) { StringRef TypoStr = Typo->getName(); StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName(); // For very short typos, ignore potential corrections that have a different // base identifier from the typo or which have a normalized edit distance // longer than the typo itself. if (TypoStr.size() < 3 && (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size())) return; // If the correction is resolved but is not viable, ignore it. if (Correction.isResolved()) { checkCorrectionVisibility(SemaRef, Correction); if (!Correction || !isCandidateViable(*CorrectionValidator, Correction)) return; } TypoResultList &CList = CorrectionResults[Correction.getEditDistance(false)][Name]; if (!CList.empty() && !CList.back().isResolved()) CList.pop_back(); if (NamedDecl *NewND = Correction.getCorrectionDecl()) { std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts()); for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end(); RI != RIEnd; ++RI) { // If the Correction refers to a decl already in the result list, // replace the existing result if the string representation of Correction // comes before the current result alphabetically, then stop as there is // nothing more to be done to add Correction to the candidate set. if (RI->getCorrectionDecl() == NewND) { if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts())) *RI = Correction; return; } } } if (CList.empty() || Correction.isResolved()) CList.push_back(Correction); while (CorrectionResults.size() > MaxTypoDistanceResultSets) CorrectionResults.erase(std::prev(CorrectionResults.end())); } void TypoCorrectionConsumer::addNamespaces( const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) { SearchNamespaces = true; for (auto KNPair : KnownNamespaces) Namespaces.addNameSpecifier(KNPair.first); bool SSIsTemplate = false; if (NestedNameSpecifier *NNS = (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) { if (const Type *T = NNS->getAsType()) SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization; } // Do not transform this into an iterator-based loop. The loop body can // trigger the creation of further types (through lazy deserialization) and // invalide iterators into this list. auto &Types = SemaRef.getASTContext().getTypes(); for (unsigned I = 0; I != Types.size(); ++I) { const auto *TI = Types[I]; if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) { CD = CD->getCanonicalDecl(); if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() && !CD->isUnion() && CD->getIdentifier() && (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) && (CD->isBeingDefined() || CD->isCompleteDefinition())) Namespaces.addNameSpecifier(CD); } } } const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() { if (++CurrentTCIndex < ValidatedCorrections.size()) return ValidatedCorrections[CurrentTCIndex]; CurrentTCIndex = ValidatedCorrections.size(); while (!CorrectionResults.empty()) { auto DI = CorrectionResults.begin(); if (DI->second.empty()) { CorrectionResults.erase(DI); continue; } auto RI = DI->second.begin(); if (RI->second.empty()) { DI->second.erase(RI); performQualifiedLookups(); continue; } TypoCorrection TC = RI->second.pop_back_val(); if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) { ValidatedCorrections.push_back(TC); return ValidatedCorrections[CurrentTCIndex]; } } return ValidatedCorrections[0]; // The empty correction. } bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) { IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo(); DeclContext *TempMemberContext = MemberContext; CXXScopeSpec *TempSS = SS.get(); retry_lookup: LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext, EnteringContext, CorrectionValidator->IsObjCIvarLookup, Name == Typo && !Candidate.WillReplaceSpecifier()); switch (Result.getResultKind()) { case LookupResult::NotFound: case LookupResult::NotFoundInCurrentInstantiation: case LookupResult::FoundUnresolvedValue: if (TempSS) { // Immediately retry the lookup without the given CXXScopeSpec TempSS = nullptr; Candidate.WillReplaceSpecifier(true); goto retry_lookup; } if (TempMemberContext) { if (SS && !TempSS) TempSS = SS.get(); TempMemberContext = nullptr; goto retry_lookup; } if (SearchNamespaces) QualifiedResults.push_back(Candidate); break; case LookupResult::Ambiguous: // We don't deal with ambiguities. break; case LookupResult::Found: case LookupResult::FoundOverloaded: // Store all of the Decls for overloaded symbols for (auto *TRD : Result) Candidate.addCorrectionDecl(TRD); checkCorrectionVisibility(SemaRef, Candidate); if (!isCandidateViable(*CorrectionValidator, Candidate)) { if (SearchNamespaces) QualifiedResults.push_back(Candidate); break; } Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo()); return true; } return false; } void TypoCorrectionConsumer::performQualifiedLookups() { unsigned TypoLen = Typo->getName().size(); for (const TypoCorrection &QR : QualifiedResults) { for (const auto &NSI : Namespaces) { DeclContext *Ctx = NSI.DeclCtx; const Type *NSType = NSI.NameSpecifier->getAsType(); // If the current NestedNameSpecifier refers to a class and the // current correction candidate is the name of that class, then skip // it as it is unlikely a qualified version of the class' constructor // is an appropriate correction. if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() : nullptr) { if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo()) continue; } TypoCorrection TC(QR); TC.ClearCorrectionDecls(); TC.setCorrectionSpecifier(NSI.NameSpecifier); TC.setQualifierDistance(NSI.EditDistance); TC.setCallbackDistance(0); // Reset the callback distance // If the current correction candidate and namespace combination are // too far away from the original typo based on the normalized edit // distance, then skip performing a qualified name lookup. unsigned TmpED = TC.getEditDistance(true); if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED && TypoLen / TmpED < 3) continue; Result.clear(); Result.setLookupName(QR.getCorrectionAsIdentifierInfo()); if (!SemaRef.LookupQualifiedName(Result, Ctx)) continue; // Any corrections added below will be validated in subsequent // iterations of the main while() loop over the Consumer's contents. switch (Result.getResultKind()) { case LookupResult::Found: case LookupResult::FoundOverloaded: { if (SS && SS->isValid()) { std::string NewQualified = TC.getAsString(SemaRef.getLangOpts()); std::string OldQualified; llvm::raw_string_ostream OldOStream(OldQualified); SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy()); OldOStream << Typo->getName(); // If correction candidate would be an identical written qualified // identifer, then the existing CXXScopeSpec probably included a // typedef that didn't get accounted for properly. if (OldOStream.str() == NewQualified) break; } for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end(); TRD != TRDEnd; ++TRD) { if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(), NSType ? NSType->getAsCXXRecordDecl() : nullptr, TRD.getPair()) == Sema::AR_accessible) TC.addCorrectionDecl(*TRD); } if (TC.isResolved()) { TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo()); addCorrection(TC); } break; } case LookupResult::NotFound: case LookupResult::NotFoundInCurrentInstantiation: case LookupResult::Ambiguous: case LookupResult::FoundUnresolvedValue: break; } } } QualifiedResults.clear(); } TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet( ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec) : Context(Context), CurContextChain(buildContextChain(CurContext)) { if (NestedNameSpecifier *NNS = CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) { llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier); NNS->print(SpecifierOStream, Context.getPrintingPolicy()); getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers); } // Build the list of identifiers that would be used for an absolute // (from the global context) NestedNameSpecifier referring to the current // context. for (DeclContext *C : llvm::reverse(CurContextChain)) { if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) CurContextIdentifiers.push_back(ND->getIdentifier()); } // Add the global context as a NestedNameSpecifier SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()), NestedNameSpecifier::GlobalSpecifier(Context), 1}; DistanceMap[1].push_back(SI); } auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain( DeclContext *Start) -> DeclContextList { assert(Start && "Building a context chain from a null context"); DeclContextList Chain; for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr; DC = DC->getLookupParent()) { NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC); if (!DC->isInlineNamespace() && !DC->isTransparentContext() && !(ND && ND->isAnonymousNamespace())) Chain.push_back(DC->getPrimaryContext()); } return Chain; } unsigned TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier( DeclContextList &DeclChain, NestedNameSpecifier *&NNS) { unsigned NumSpecifiers = 0; for (DeclContext *C : llvm::reverse(DeclChain)) { if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) { NNS = NestedNameSpecifier::Create(Context, NNS, ND); ++NumSpecifiers; } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) { NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(), RD->getTypeForDecl()); ++NumSpecifiers; } } return NumSpecifiers; } void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier( DeclContext *Ctx) { NestedNameSpecifier *NNS = nullptr; unsigned NumSpecifiers = 0; DeclContextList NamespaceDeclChain(buildContextChain(Ctx)); DeclContextList FullNamespaceDeclChain(NamespaceDeclChain); // Eliminate common elements from the two DeclContext chains. for (DeclContext *C : llvm::reverse(CurContextChain)) { if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C) break; NamespaceDeclChain.pop_back(); } // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS); // Add an explicit leading '::' specifier if needed. if (NamespaceDeclChain.empty()) { // Rebuild the NestedNameSpecifier as a globally-qualified specifier. NNS = NestedNameSpecifier::GlobalSpecifier(Context); NumSpecifiers = buildNestedNameSpecifier(FullNamespaceDeclChain, NNS); } else if (NamedDecl *ND = dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) { IdentifierInfo *Name = ND->getIdentifier(); bool SameNameSpecifier = false; if (std::find(CurNameSpecifierIdentifiers.begin(), CurNameSpecifierIdentifiers.end(), Name) != CurNameSpecifierIdentifiers.end()) { std::string NewNameSpecifier; llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier); SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers; getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); NNS->print(SpecifierOStream, Context.getPrintingPolicy()); SpecifierOStream.flush(); SameNameSpecifier = NewNameSpecifier == CurNameSpecifier; } if (SameNameSpecifier || std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(), Name) != CurContextIdentifiers.end()) { // Rebuild the NestedNameSpecifier as a globally-qualified specifier. NNS = NestedNameSpecifier::GlobalSpecifier(Context); NumSpecifiers = buildNestedNameSpecifier(FullNamespaceDeclChain, NNS); } } // If the built NestedNameSpecifier would be replacing an existing // NestedNameSpecifier, use the number of component identifiers that // would need to be changed as the edit distance instead of the number // of components in the built NestedNameSpecifier. if (NNS && !CurNameSpecifierIdentifiers.empty()) { SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers; getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers); NumSpecifiers = llvm::ComputeEditDistance( llvm::makeArrayRef(CurNameSpecifierIdentifiers), llvm::makeArrayRef(NewNameSpecifierIdentifiers)); } SpecifierInfo SI = {Ctx, NNS, NumSpecifiers}; DistanceMap[NumSpecifiers].push_back(SI); } /// Perform name lookup for a possible result for typo correction. static void LookupPotentialTypoResult(Sema &SemaRef, LookupResult &Res, IdentifierInfo *Name, Scope *S, CXXScopeSpec *SS, DeclContext *MemberContext, bool EnteringContext, bool isObjCIvarLookup, bool FindHidden) { Res.suppressDiagnostics(); Res.clear(); Res.setLookupName(Name); Res.setAllowHidden(FindHidden); if (MemberContext) { if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) { if (isObjCIvarLookup) { if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) { Res.addDecl(Ivar); Res.resolveKind(); return; } } if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration( Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) { Res.addDecl(Prop); Res.resolveKind(); return; } } SemaRef.LookupQualifiedName(Res, MemberContext); return; } SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false, EnteringContext); // Fake ivar lookup; this should really be part of // LookupParsedName. if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) { if (Method->isInstanceMethod() && Method->getClassInterface() && (Res.empty() || (Res.isSingleResult() && Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) { if (ObjCIvarDecl *IV = Method->getClassInterface()->lookupInstanceVariable(Name)) { Res.addDecl(IV); Res.resolveKind(); } } } } /// Add keywords to the consumer as possible typo corrections. static void AddKeywordsToConsumer(Sema &SemaRef, TypoCorrectionConsumer &Consumer, Scope *S, CorrectionCandidateCallback &CCC, bool AfterNestedNameSpecifier) { if (AfterNestedNameSpecifier) { // For 'X::', we know exactly which keywords can appear next. Consumer.addKeywordResult("template"); if (CCC.WantExpressionKeywords) Consumer.addKeywordResult("operator"); return; } if (CCC.WantObjCSuper) Consumer.addKeywordResult("super"); if (CCC.WantTypeSpecifiers) { // Add type-specifier keywords to the set of results. static const char *const CTypeSpecs[] = { "char", "const", "double", "enum", "float", "int", "long", "short", "signed", "struct", "union", "unsigned", "void", "volatile", "_Complex", "_Imaginary", // storage-specifiers as well "extern", "inline", "static", "typedef" }; const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs); for (unsigned I = 0; I != NumCTypeSpecs; ++I) Consumer.addKeywordResult(CTypeSpecs[I]); if (SemaRef.getLangOpts().C99) Consumer.addKeywordResult("restrict"); if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) Consumer.addKeywordResult("bool"); else if (SemaRef.getLangOpts().C99) Consumer.addKeywordResult("_Bool"); if (SemaRef.getLangOpts().CPlusPlus) { Consumer.addKeywordResult("class"); Consumer.addKeywordResult("typename"); Consumer.addKeywordResult("wchar_t"); if (SemaRef.getLangOpts().CPlusPlus11) { Consumer.addKeywordResult("char16_t"); Consumer.addKeywordResult("char32_t"); Consumer.addKeywordResult("constexpr"); Consumer.addKeywordResult("decltype"); Consumer.addKeywordResult("thread_local"); } } if (SemaRef.getLangOpts().GNUKeywords) Consumer.addKeywordResult("typeof"); } else if (CCC.WantFunctionLikeCasts) { static const char *const CastableTypeSpecs[] = { "char", "double", "float", "int", "long", "short", "signed", "unsigned", "void" }; for (auto *kw : CastableTypeSpecs) Consumer.addKeywordResult(kw); } if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) { Consumer.addKeywordResult("const_cast"); Consumer.addKeywordResult("dynamic_cast"); Consumer.addKeywordResult("reinterpret_cast"); Consumer.addKeywordResult("static_cast"); } if (CCC.WantExpressionKeywords) { Consumer.addKeywordResult("sizeof"); if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) { Consumer.addKeywordResult("false"); Consumer.addKeywordResult("true"); } if (SemaRef.getLangOpts().CPlusPlus) { static const char *const CXXExprs[] = { "delete", "new", "operator", "throw", "typeid" }; const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs); for (unsigned I = 0; I != NumCXXExprs; ++I) Consumer.addKeywordResult(CXXExprs[I]); if (isa<CXXMethodDecl>(SemaRef.CurContext) && cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance()) Consumer.addKeywordResult("this"); if (SemaRef.getLangOpts().CPlusPlus11) { Consumer.addKeywordResult("alignof"); Consumer.addKeywordResult("nullptr"); } } if (SemaRef.getLangOpts().C11) { // FIXME: We should not suggest _Alignof if the alignof macro // is present. Consumer.addKeywordResult("_Alignof"); } } if (CCC.WantRemainingKeywords) { if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) { // Statements. static const char *const CStmts[] = { "do", "else", "for", "goto", "if", "return", "switch", "while" }; const unsigned NumCStmts = llvm::array_lengthof(CStmts); for (unsigned I = 0; I != NumCStmts; ++I) Consumer.addKeywordResult(CStmts[I]); if (SemaRef.getLangOpts().CPlusPlus) { Consumer.addKeywordResult("catch"); Consumer.addKeywordResult("try"); } if (S && S->getBreakParent()) Consumer.addKeywordResult("break"); if (S && S->getContinueParent()) Consumer.addKeywordResult("continue"); if (SemaRef.getCurFunction() && !SemaRef.getCurFunction()->SwitchStack.empty()) { Consumer.addKeywordResult("case"); Consumer.addKeywordResult("default"); } } else { if (SemaRef.getLangOpts().CPlusPlus) { Consumer.addKeywordResult("namespace"); Consumer.addKeywordResult("template"); } if (S && S->isClassScope()) { Consumer.addKeywordResult("explicit"); Consumer.addKeywordResult("friend"); Consumer.addKeywordResult("mutable"); Consumer.addKeywordResult("private"); Consumer.addKeywordResult("protected"); Consumer.addKeywordResult("public"); Consumer.addKeywordResult("virtual"); } } if (SemaRef.getLangOpts().CPlusPlus) { Consumer.addKeywordResult("using"); if (SemaRef.getLangOpts().CPlusPlus11) Consumer.addKeywordResult("static_assert"); } } } std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer( const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr<CorrectionCandidateCallback> CCC, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool ErrorRecovery) { if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking || DisableTypoCorrection) return nullptr; // In Microsoft mode, don't perform typo correction in a template member // function dependent context because it interferes with the "lookup into // dependent bases of class templates" feature. if (getLangOpts().MSVCCompat && CurContext->isDependentContext() && isa<CXXMethodDecl>(CurContext)) return nullptr; // We only attempt to correct typos for identifiers. IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); if (!Typo) return nullptr; // If the scope specifier itself was invalid, don't try to correct // typos. if (SS && SS->isInvalid()) return nullptr; // Never try to correct typos during any kind of code synthesis. if (!CodeSynthesisContexts.empty()) return nullptr; // Don't try to correct 'super'. if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier()) return nullptr; // Abort if typo correction already failed for this specific typo. IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo); if (locs != TypoCorrectionFailures.end() && locs->second.count(TypoName.getLoc())) return nullptr; // Don't try to correct the identifier "vector" when in AltiVec mode. // TODO: Figure out why typo correction misbehaves in this case, fix it, and // remove this workaround. if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector")) return nullptr; // Provide a stop gap for files that are just seriously broken. Trying // to correct all typos can turn into a HUGE performance penalty, causing // some files to take minutes to get rejected by the parser. unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit; if (Limit && TyposCorrected >= Limit) return nullptr; ++TyposCorrected; // If we're handling a missing symbol error, using modules, and the // special search all modules option is used, look for a missing import. if (ErrorRecovery && getLangOpts().Modules && getLangOpts().ModulesSearchAll) { // The following has the side effect of loading the missing module. getModuleLoader().lookupMissingImports(Typo->getName(), TypoName.getLocStart()); } CorrectionCandidateCallback &CCCRef = *CCC; auto Consumer = llvm::make_unique<TypoCorrectionConsumer>( *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext, EnteringContext); // Perform name lookup to find visible, similarly-named entities. bool IsUnqualifiedLookup = false; DeclContext *QualifiedDC = MemberContext; if (MemberContext) { LookupVisibleDecls(MemberContext, LookupKind, *Consumer); // Look in qualified interfaces. if (OPT) { for (auto *I : OPT->quals()) LookupVisibleDecls(I, LookupKind, *Consumer); } } else if (SS && SS->isSet()) { QualifiedDC = computeDeclContext(*SS, EnteringContext); if (!QualifiedDC) return nullptr; LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer); } else { IsUnqualifiedLookup = true; } // Determine whether we are going to search in the various namespaces for // corrections. bool SearchNamespaces = getLangOpts().CPlusPlus && (IsUnqualifiedLookup || (SS && SS->isSet())); if (IsUnqualifiedLookup || SearchNamespaces) { // For unqualified lookup, look through all of the names that we have // seen in this translation unit. // FIXME: Re-add the ability to skip very unlikely potential corrections. for (const auto &I : Context.Idents) Consumer->FoundName(I.getKey()); // Walk through identifiers in external identifier sources. // FIXME: Re-add the ability to skip very unlikely potential corrections. if (IdentifierInfoLookup *External = Context.Idents.getExternalIdentifierLookup()) { std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers()); do { StringRef Name = Iter->Next(); if (Name.empty()) break; Consumer->FoundName(Name); } while (true); } } AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty()); // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going // to search those namespaces. if (SearchNamespaces) { // Load any externally-known namespaces. if (ExternalSource && !LoadedExternalKnownNamespaces) { SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces; LoadedExternalKnownNamespaces = true; ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces); for (auto *N : ExternalKnownNamespaces) KnownNamespaces[N] = true; } Consumer->addNamespaces(KnownNamespaces); } return Consumer; } /// Try to "correct" a typo in the source code by finding /// visible declarations whose names are similar to the name that was /// present in the source code. /// /// \param TypoName the \c DeclarationNameInfo structure that contains /// the name that was present in the source code along with its location. /// /// \param LookupKind the name-lookup criteria used to search for the name. /// /// \param S the scope in which name lookup occurs. /// /// \param SS the nested-name-specifier that precedes the name we're /// looking for, if present. /// /// \param CCC A CorrectionCandidateCallback object that provides further /// validation of typo correction candidates. It also provides flags for /// determining the set of keywords permitted. /// /// \param MemberContext if non-NULL, the context in which to look for /// a member access expression. /// /// \param EnteringContext whether we're entering the context described by /// the nested-name-specifier SS. /// /// \param OPT when non-NULL, the search for visible declarations will /// also walk the protocols in the qualified interfaces of \p OPT. /// /// \returns a \c TypoCorrection containing the corrected name if the typo /// along with information such as the \c NamedDecl where the corrected name /// was declared, and any additional \c NestedNameSpecifier needed to access /// it (C++ only). The \c TypoCorrection is empty if there is no correction. TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr<CorrectionCandidateCallback> CCC, CorrectTypoKind Mode, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT, bool RecordFailure) { assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback"); // Always let the ExternalSource have the first chance at correction, even // if we would otherwise have given up. if (ExternalSource) { if (TypoCorrection Correction = ExternalSource->CorrectTypo( TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT)) return Correction; } // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver; // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for // some instances of CTC_Unknown, while WantRemainingKeywords is true // for CTC_Unknown but not for CTC_ObjCMessageReceiver. bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords; IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); auto Consumer = makeTypoCorrectionConsumer( TypoName, LookupKind, S, SS, std::move(CCC), MemberContext, EnteringContext, OPT, Mode == CTK_ErrorRecovery); if (!Consumer) return TypoCorrection(); // If we haven't found anything, we're done. if (Consumer->empty()) return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); // Make sure the best edit distance (prior to adding any namespace qualifiers) // is not more that about a third of the length of the typo's identifier. unsigned ED = Consumer->getBestEditDistance(true); unsigned TypoLen = Typo->getName().size(); if (ED > 0 && TypoLen / ED < 3) return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); TypoCorrection BestTC = Consumer->getNextCorrection(); TypoCorrection SecondBestTC = Consumer->getNextCorrection(); if (!BestTC) return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); ED = BestTC.getEditDistance(); if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) { // If this was an unqualified lookup and we believe the callback // object wouldn't have filtered out possible corrections, note // that no correction was found. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); } // If only a single name remains, return that result. if (!SecondBestTC || SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) { const TypoCorrection &Result = BestTC; // Don't correct to a keyword that's the same as the typo; the keyword // wasn't actually in scope. if (ED == 0 && Result.isKeyword()) return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); TypoCorrection TC = Result; TC.setCorrectionRange(SS, TypoName); checkCorrectionVisibility(*this, TC); return TC; } else if (SecondBestTC && ObjCMessageReceiver) { // Prefer 'super' when we're completing in a message-receiver // context. if (BestTC.getCorrection().getAsString() != "super") { if (SecondBestTC.getCorrection().getAsString() == "super") BestTC = SecondBestTC; else if ((*Consumer)["super"].front().isKeyword()) BestTC = (*Consumer)["super"].front(); } // Don't correct to a keyword that's the same as the typo; the keyword // wasn't actually in scope. if (BestTC.getEditDistance() == 0 || BestTC.getCorrection().getAsString() != "super") return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure); BestTC.setCorrectionRange(SS, TypoName); return BestTC; } // Record the failure's location if needed and return an empty correction. If // this was an unqualified lookup and we believe the callback object did not // filter out possible corrections, also cache the failure for the typo. return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC); } /// Try to "correct" a typo in the source code by finding /// visible declarations whose names are similar to the name that was /// present in the source code. /// /// \param TypoName the \c DeclarationNameInfo structure that contains /// the name that was present in the source code along with its location. /// /// \param LookupKind the name-lookup criteria used to search for the name. /// /// \param S the scope in which name lookup occurs. /// /// \param SS the nested-name-specifier that precedes the name we're /// looking for, if present. /// /// \param CCC A CorrectionCandidateCallback object that provides further /// validation of typo correction candidates. It also provides flags for /// determining the set of keywords permitted. /// /// \param TDG A TypoDiagnosticGenerator functor that will be used to print /// diagnostics when the actual typo correction is attempted. /// /// \param TRC A TypoRecoveryCallback functor that will be used to build an /// Expr from a typo correction candidate. /// /// \param MemberContext if non-NULL, the context in which to look for /// a member access expression. /// /// \param EnteringContext whether we're entering the context described by /// the nested-name-specifier SS. /// /// \param OPT when non-NULL, the search for visible declarations will /// also walk the protocols in the qualified interfaces of \p OPT. /// /// \returns a new \c TypoExpr that will later be replaced in the AST with an /// Expr representing the result of performing typo correction, or nullptr if /// typo correction is not possible. If nullptr is returned, no diagnostics will /// be emitted and it is the responsibility of the caller to emit any that are /// needed. TypoExpr *Sema::CorrectTypoDelayed( const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, std::unique_ptr<CorrectionCandidateCallback> CCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode, DeclContext *MemberContext, bool EnteringContext, const ObjCObjectPointerType *OPT) { assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback"); auto Consumer = makeTypoCorrectionConsumer( TypoName, LookupKind, S, SS, std::move(CCC), MemberContext, EnteringContext, OPT, Mode == CTK_ErrorRecovery); // Give the external sema source a chance to correct the typo. TypoCorrection ExternalTypo; if (ExternalSource && Consumer) { ExternalTypo = ExternalSource->CorrectTypo( TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(), MemberContext, EnteringContext, OPT); if (ExternalTypo) Consumer->addCorrection(ExternalTypo); } if (!Consumer || Consumer->empty()) return nullptr; // Make sure the best edit distance (prior to adding any namespace qualifiers) // is not more that about a third of the length of the typo's identifier. unsigned ED = Consumer->getBestEditDistance(true); IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo(); if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3) return nullptr; ExprEvalContexts.back().NumTypos++; return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC)); } void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) { if (!CDecl) return; if (isKeyword()) CorrectionDecls.clear(); CorrectionDecls.push_back(CDecl); if (!CorrectionName) CorrectionName = CDecl->getDeclName(); } std::string TypoCorrection::getAsString(const LangOptions &LO) const { if (CorrectionNameSpec) { std::string tmpBuffer; llvm::raw_string_ostream PrefixOStream(tmpBuffer); CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO)); PrefixOStream << CorrectionName; return PrefixOStream.str(); } return CorrectionName.getAsString(); } bool CorrectionCandidateCallback::ValidateCandidate( const TypoCorrection &candidate) { if (!candidate.isResolved()) return true; if (candidate.isKeyword()) return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts || WantRemainingKeywords || WantObjCSuper; bool HasNonType = false; bool HasStaticMethod = false; bool HasNonStaticMethod = false; for (Decl *D : candidate) { if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D)) D = FTD->getTemplatedDecl(); if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) { if (Method->isStatic()) HasStaticMethod = true; else HasNonStaticMethod = true; } if (!isa<TypeDecl>(D)) HasNonType = true; } if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod && !candidate.getCorrectionSpecifier()) return false; return WantTypeSpecifiers || HasNonType; } FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs, MemberExpr *ME) : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs), CurContext(SemaRef.CurContext), MemberFn(ME) { WantTypeSpecifiers = false; WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1; WantRemainingKeywords = false; } bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) { if (!candidate.getCorrectionDecl()) return candidate.isKeyword(); for (auto *C : candidate) { FunctionDecl *FD = nullptr; NamedDecl *ND = C->getUnderlyingDecl(); if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND)) FD = FTD->getTemplatedDecl(); if (!HasExplicitTemplateArgs && !FD) { if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) { // If the Decl is neither a function nor a template function, // determine if it is a pointer or reference to a function. If so, // check against the number of arguments expected for the pointee. QualType ValType = cast<ValueDecl>(ND)->getType(); if (ValType.isNull()) continue; if (ValType->isAnyPointerType() || ValType->isReferenceType()) ValType = ValType->getPointeeType(); if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>()) if (FPT->getNumParams() == NumArgs) return true; } } // Skip the current candidate if it is not a FunctionDecl or does not accept // the current number of arguments. if (!FD || !(FD->getNumParams() >= NumArgs && FD->getMinRequiredArguments() <= NumArgs)) continue; // If the current candidate is a non-static C++ method, skip the candidate // unless the method being corrected--or the current DeclContext, if the // function being corrected is not a method--is a method in the same class // or a descendent class of the candidate's parent class. if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { if (MemberFn || !MD->isStatic()) { CXXMethodDecl *CurMD = MemberFn ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl()) : dyn_cast_or_null<CXXMethodDecl>(CurContext); CXXRecordDecl *CurRD = CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr; CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl(); if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD))) continue; } } return true; } return false; } void Sema::diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery) { diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl), ErrorRecovery); } /// Find which declaration we should import to provide the definition of /// the given declaration. static NamedDecl *getDefinitionToImport(NamedDecl *D) { if (VarDecl *VD = dyn_cast<VarDecl>(D)) return VD->getDefinition(); if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) return FD->getDefinition(); if (TagDecl *TD = dyn_cast<TagDecl>(D)) return TD->getDefinition(); if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) return ID->getDefinition(); if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) return PD->getDefinition(); if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) return getDefinitionToImport(TD->getTemplatedDecl()); return nullptr; } void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl, MissingImportKind MIK, bool Recover) { // Suggest importing a module providing the definition of this entity, if // possible. NamedDecl *Def = getDefinitionToImport(Decl); if (!Def) Def = Decl; Module *Owner = getOwningModule(Decl); assert(Owner && "definition of hidden declaration is not in a module"); llvm::SmallVector<Module*, 8> OwningModules; OwningModules.push_back(Owner); auto Merged = Context.getModulesWithMergedDefinition(Decl); OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end()); diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules, MIK, Recover); } /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic /// suggesting the addition of a #include of the specified file. static std::string getIncludeStringForHeader(Preprocessor &PP, const FileEntry *E) { bool IsSystem; auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(E, &IsSystem); return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"'); } void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl, SourceLocation DeclLoc, ArrayRef<Module *> Modules, MissingImportKind MIK, bool Recover) { assert(!Modules.empty()); // Weed out duplicates from module list. llvm::SmallVector<Module*, 8> UniqueModules; llvm::SmallDenseSet<Module*, 8> UniqueModuleSet; for (auto *M : Modules) if (UniqueModuleSet.insert(M).second) UniqueModules.push_back(M); Modules = UniqueModules; if (Modules.size() > 1) { std::string ModuleList; unsigned N = 0; for (Module *M : Modules) { ModuleList += "\n "; if (++N == 5 && N != Modules.size()) { ModuleList += "[...]"; break; } ModuleList += M->getFullModuleName(); } Diag(UseLoc, diag::err_module_unimported_use_multiple) << (int)MIK << Decl << ModuleList; } else if (const FileEntry *E = PP.getModuleHeaderToIncludeForDiagnostics( UseLoc, Modules[0], DeclLoc)) { // The right way to make the declaration visible is to include a header; // suggest doing so. // // FIXME: Find a smart place to suggest inserting a #include, and add // a FixItHint there. Diag(UseLoc, diag::err_module_unimported_use_header) << (int)MIK << Decl << Modules[0]->getFullModuleName() << getIncludeStringForHeader(PP, E); } else { // FIXME: Add a FixItHint that imports the corresponding module. Diag(UseLoc, diag::err_module_unimported_use) << (int)MIK << Decl << Modules[0]->getFullModuleName(); } unsigned DiagID; switch (MIK) { case MissingImportKind::Declaration: DiagID = diag::note_previous_declaration; break; case MissingImportKind::Definition: DiagID = diag::note_previous_definition; break; case MissingImportKind::DefaultArgument: DiagID = diag::note_default_argument_declared_here; break; case MissingImportKind::ExplicitSpecialization: DiagID = diag::note_explicit_specialization_declared_here; break; case MissingImportKind::PartialSpecialization: DiagID = diag::note_partial_specialization_declared_here; break; } Diag(DeclLoc, DiagID); // Try to recover by implicitly importing this module. if (Recover) createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]); } /// Diagnose a successfully-corrected typo. Separated from the correction /// itself to allow external validation of the result, etc. /// /// \param Correction The result of performing typo correction. /// \param TypoDiag The diagnostic to produce. This will have the corrected /// string added to it (and usually also a fixit). /// \param PrevNote A note to use when indicating the location of the entity to /// which we are correcting. Will have the correction string added to it. /// \param ErrorRecovery If \c true (the default), the caller is going to /// recover from the typo as if the corrected string had been typed. /// In this case, \c PDiag must be an error, and we will attach a fixit /// to it. void Sema::diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, const PartialDiagnostic &PrevNote, bool ErrorRecovery) { std::string CorrectedStr = Correction.getAsString(getLangOpts()); std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts()); FixItHint FixTypo = FixItHint::CreateReplacement( Correction.getCorrectionRange(), CorrectedStr); // Maybe we're just missing a module import. if (Correction.requiresImport()) { NamedDecl *Decl = Correction.getFoundDecl(); assert(Decl && "import required but no declaration to import"); diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl, MissingImportKind::Declaration, ErrorRecovery); return; } Diag(Correction.getCorrectionRange().getBegin(), TypoDiag) << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint()); NamedDecl *ChosenDecl = Correction.isKeyword() ? nullptr : Correction.getFoundDecl(); if (PrevNote.getDiagID() && ChosenDecl) Diag(ChosenDecl->getLocation(), PrevNote) << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo); // Add any extra diagnostics. for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics()) Diag(Correction.getCorrectionRange().getBegin(), PD); } TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC, TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC) { assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer"); auto TE = new (Context) TypoExpr(Context.DependentTy); auto &State = DelayedTypos[TE]; State.Consumer = std::move(TCC); State.DiagHandler = std::move(TDG); State.RecoveryHandler = std::move(TRC); return TE; } const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const { auto Entry = DelayedTypos.find(TE); assert(Entry != DelayedTypos.end() && "Failed to get the state for a TypoExpr!"); return Entry->second; } void Sema::clearDelayedTypo(TypoExpr *TE) { DelayedTypos.erase(TE); } void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) { DeclarationNameInfo Name(II, IILoc); LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration); R.suppressDiagnostics(); R.setHideTags(false); LookupName(R, S); R.dump(); }
bsd-3-clause
billyct/sushe
module/Application/src/Application/Entity/Health.php
1095
<?php namespace Application\Entity; use Doctrine\ORM\Mapping as ORM; /** * * * @ORM\Entity * @ORM\Table(name="health") * * @author billyct */ class Health extends AbstractBase { /** * @ORM\Column(type="date") **/ protected $checkdate; /** * @ORM\Column(type="integer") **/ protected $level; /** * @ORM\ManyToOne(targetEntity="Application\Entity\Room", inversedBy="healths") **/ protected $room; /** * @return the $checkdate */ public function getCheckdate() { return $this->checkdate; } /** * @return the $level */ public function getLevel() { return $this->level; } /** * @return the $room */ public function getRoom() { return $this->room; } /** * @param field_type $checkdate */ public function setCheckdate($checkdate) { $this->checkdate = $checkdate; return $this; } /** * @param field_type $level */ public function setLevel($level) { $this->level = $level; return $this; } /** * @param field_type $room */ public function setRoom($room) { $this->room = $room; return $this; } } ?>
bsd-3-clause
stan-dev/math
lib/boost_1.75.0/libs/config/checks/std/cpp_lib_hypot_17.cpp
742
// This file was automatically generated on Mon Dec 09 09:47:38 2019 // by libs/config/tools/generate.cpp // Copyright John Maddock 2002-4. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/config for the most recent version.// // Revision $Id$ // #ifdef __has_include #if __has_include(<version>) #include <version> #endif #endif #include <cmath> #ifndef __cpp_lib_hypot #error "Macro << __cpp_lib_hypot is not set" #endif #if __cpp_lib_hypot < 201603 #error "Macro __cpp_lib_hypot had too low a value" #endif int main( int, char *[] ) { return 0; }
bsd-3-clause
endlessm/chromium-browser
chrome/updater/external_constants_unittest.cc
757
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/updater/external_constants_unittest.h" #include <memory> #include "chrome/updater/constants.h" #include "chrome/updater/external_constants.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace updater { TEST_F(DevOverrideTest, TestDefaults) { std::unique_ptr<ExternalConstants> consts = CreateExternalConstants(); EXPECT_TRUE(consts->UseCUP()); std::vector<GURL> urls = consts->UpdateURL(); ASSERT_EQ(urls.size(), 1ul); EXPECT_EQ(urls[0], GURL(kUpdaterJSONDefaultUrl)); EXPECT_TRUE(urls[0].is_valid()); } } // namespace updater
bsd-3-clause
manifoldco/grafton
generated/connector/client/o_auth/o_auth_client.go
7689
package o_auth // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "github.com/go-openapi/runtime" strfmt "github.com/go-openapi/strfmt" ) // New creates a new o auth API client. func New(transport runtime.ClientTransport, formats strfmt.Registry) *Client { return &Client{transport: transport, formats: formats} } /* Client for o auth API */ type Client struct { transport runtime.ClientTransport formats strfmt.Registry } /* DeleteCredentialsID deletes an o auth credential pair Delete an OAuth 2.0 credential pair. Can only be called through [Grafton's credentials command](https://github.com/manifoldco/grafton) in the context of a Manifold user. */ func (a *Client) DeleteCredentialsID(params *DeleteCredentialsIDParams, authInfo runtime.ClientAuthInfoWriter) (*DeleteCredentialsIDNoContent, error) { // TODO: Validate the params before sending if params == nil { params = NewDeleteCredentialsIDParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "DeleteCredentialsID", Method: "DELETE", PathPattern: "/credentials/{id}", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json"}, Schemes: []string{"https"}, Params: params, Reader: &DeleteCredentialsIDReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } return result.(*DeleteCredentialsIDNoContent), nil } /* GetCredentials gets list of o auth credentials without secrets List all non-expired OAuth 2.0 credential pairs for a provider's product. One of the `product_id` or `provider_id` query parameters is required. **IMPORTANT**: This does **not** return the secret. Can only be called through [Grafton's credentials command](https://github.com/manifoldco/grafton) in the context of a Manifold user. */ func (a *Client) GetCredentials(params *GetCredentialsParams, authInfo runtime.ClientAuthInfoWriter) (*GetCredentialsOK, error) { // TODO: Validate the params before sending if params == nil { params = NewGetCredentialsParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "GetCredentials", Method: "GET", PathPattern: "/credentials/", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json"}, Schemes: []string{"https"}, Params: params, Reader: &GetCredentialsReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } return result.(*GetCredentialsOK), nil } /* GetSelf currents identity A provider can call this endpoint to return the identity represented by the access token. Depending on the grant type used to create an access token the underlying identity will be different. | Grant Type | Identity Type | | ---------- | ------------ | | `authorization_code` | `user` | | `client_credentials` | `product` or `provider` | */ func (a *Client) GetSelf(params *GetSelfParams, authInfo runtime.ClientAuthInfoWriter) (*GetSelfOK, error) { // TODO: Validate the params before sending if params == nil { params = NewGetSelfParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "GetSelf", Method: "GET", PathPattern: "/self", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json"}, Schemes: []string{"https"}, Params: params, Reader: &GetSelfReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } return result.(*GetSelfOK), nil } /* PostCredentials creates an o auth credential pair Create an OAuth 2.0 credential pair for a provider. That credential can either be scoped to all products of the provider or to a specific product. This is done by providing the `product_id`. `client_secret` is stored as an `scrypt` hash only. Therefore, If the value is lost after creation, it cannot be recovered. **IMPORTANT**: For security, Manifold expires all previously created credentials of the same scope (product or provider) within 24 hours of creating a new credential. This means that only the most recent credential of a specific scope should be used. Can only be called through [Grafton's credentials command](https://github.com/manifoldco/grafton) in the context of a Manifold user. */ func (a *Client) PostCredentials(params *PostCredentialsParams, authInfo runtime.ClientAuthInfoWriter) (*PostCredentialsOK, error) { // TODO: Validate the params before sending if params == nil { params = NewPostCredentialsParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "PostCredentials", Method: "POST", PathPattern: "/credentials/", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json"}, Schemes: []string{"https"}, Params: params, Reader: &PostCredentialsReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } return result.(*PostCredentialsOK), nil } /* PostOauthTokens creates access token A provider uses this endpoint to acquire a scoped access token which grants them authority to act on behalf of the grantor (either a provider or user). There are two grant types used for requesting an access token: * `authorization_code` which allows a provider to exchange a `code` grant from a user for an access token giving them permission to act on the user's behalf. * `client_credentials` which allows a provider to grant themselves an access token that is either scoped to all their products or to a specific one. This endpoint is a part of the Single Sign-On flow invoked by users attempting to navigate to a resource's dashboard. A `code` is only valid for five minutes and cannot be used more than once to grant an access token. Provider authentication is supported with `client_id` and `client_secret` in either the request body, or via basic authentication. Basic authentication is the preferred method, but is not required. The granted token will expire within 24 hours. */ func (a *Client) PostOauthTokens(params *PostOauthTokensParams) (*PostOauthTokensCreated, error) { // TODO: Validate the params before sending if params == nil { params = NewPostOauthTokensParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "PostOauthTokens", Method: "POST", PathPattern: "/oauth/tokens", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json", "application/x-www-form-urlencoded"}, Schemes: []string{"https"}, Params: params, Reader: &PostOauthTokensReader{formats: a.formats}, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } return result.(*PostOauthTokensCreated), nil } // SetTransport changes the transport on the client func (a *Client) SetTransport(transport runtime.ClientTransport) { a.transport = transport }
bsd-3-clause
ValentinMinder/pocketcampus
windows/Source/Common.WindowsRuntime/Controls/Placeholder.cs
1083
// Copyright (c) PocketCampus.Org 2014-15 // See LICENSE file for more details // File author: Solal Pirelli using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace PocketCampus.Common.Controls { public sealed class Placeholder : ContentControl { private static readonly DefaultToVisibilityConverter Converter = new DefaultToVisibilityConverter(); public object For { get { return GetValue( ForProperty ); } set { SetValue( ForProperty, value ); } } public static readonly DependencyProperty ForProperty = DependencyProperty.Register( "For", typeof( object ), typeof( Placeholder ), new PropertyMetadata( null, OnForChanged ) ); private static void OnForChanged( DependencyObject obj, DependencyPropertyChangedEventArgs args ) { ( (Placeholder) obj ).Visibility = Converter.Convert( args.NewValue ); } public Placeholder() { DefaultStyleKey = typeof( Placeholder ); } } }
bsd-3-clause
antoinecarme/pyaf
tests/artificial/transf_None/trend_MovingMedian/cycle_12/ar_12/test_artificial_32_None_MovingMedian_12_12_0.py
262
import pyaf.Bench.TS_datasets as tsds import tests.artificial.process_artificial_dataset as art art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 12, transform = "None", sigma = 0.0, exog_count = 0, ar_order = 12);
bsd-3-clause
takeplace/django-composite
composite/mixin.py
1222
from django.core.urlresolvers import reverse from django.http import HttpResponseForbidden from django.contrib.auth.views import redirect_to_login class LoginRequiredMixin(object): login_url_name = 'login' def dispatch(self, request, *args, **kwargs): if not request.user.is_authenticated(): return redirect_to_login(request.get_full_path(), reverse(self.login_url_name)) return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) class PermissionRequiredMixin(): login_url_name = 'login' is_staff = False is_superuser = False def get_permissions_required(self): return self.permissions_required def dispatch(self, request, *args, **kwargs): has_permission = request.user.has_perm(self.get_permissions_required()) if not has_permission: return redirect_to_login(request.get_full_path(), reverse(self.login_url_name)) if self.is_staff and not request.user.is_staff: return HttpResponseForbidden if self.is_superuser and not request.user.is_staff: return HttpResponseForbidden return super(PermissionRequiredMixin, self).dispatch(request, *args, **kwargs)
bsd-3-clause
timopulkkinen/BubbleFish
chrome/browser/automation/automation_util.cc
21171
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/automation/automation_util.h" #include <string> #include "ash/shell.h" #include "ash/shell_delegate.h" #include "base/bind.h" #include "base/memory/scoped_ptr.h" #include "base/stringprintf.h" #include "base/strings/string_number_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/time.h" #include "base/values.h" #include "chrome/browser/automation/automation_provider.h" #include "chrome/browser/automation/automation_provider_json.h" #include "chrome/browser/extensions/extension_process_manager.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/printing/print_preview_dialog_controller.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_id.h" #include "chrome/browser/sessions/session_tab_helper.h" #include "chrome/browser/ui/app_modal_dialogs/app_modal_dialog_queue.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_iterator.h" #include "chrome/browser/ui/browser_list.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/view_type_utils.h" #include "chrome/common/automation_id.h" #include "chrome/common/extensions/extension.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_monster.h" #include "net/cookies/cookie_store.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" #if defined(OS_CHROMEOS) #include "chrome/browser/chromeos/login/existing_user_controller.h" #include "chrome/browser/chromeos/login/login_display.h" #include "chrome/browser/chromeos/login/login_display_host.h" #include "chrome/browser/chromeos/login/webui_login_display.h" #include "chrome/browser/chromeos/login/webui_login_display_host.h" #include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h" #endif using content::BrowserThread; using content::RenderViewHost; using content::WebContents; #if defined(OS_CHROMEOS) using chromeos::ExistingUserController; using chromeos::User; using chromeos::UserManager; #endif namespace { void GetCookiesCallback(base::WaitableEvent* event, std::string* cookies, const std::string& cookie_line) { *cookies = cookie_line; event->Signal(); } void GetCookiesOnIOThread( const GURL& url, const scoped_refptr<net::URLRequestContextGetter>& context_getter, base::WaitableEvent* event, std::string* cookies) { context_getter->GetURLRequestContext()->cookie_store()-> GetCookiesWithOptionsAsync(url, net::CookieOptions(), base::Bind(&GetCookiesCallback, event, cookies)); } void GetCanonicalCookiesCallback( base::WaitableEvent* event, net::CookieList* cookie_list, const net::CookieList& cookies) { *cookie_list = cookies; event->Signal(); } void GetCanonicalCookiesOnIOThread( const GURL& url, const scoped_refptr<net::URLRequestContextGetter>& context_getter, base::WaitableEvent* event, net::CookieList* cookie_list) { context_getter->GetURLRequestContext()->cookie_store()-> GetCookieMonster()->GetAllCookiesForURLAsync( url, base::Bind(&GetCanonicalCookiesCallback, event, cookie_list)); } void SetCookieCallback(base::WaitableEvent* event, bool* success, bool result) { *success = result; event->Signal(); } void SetCookieOnIOThread( const GURL& url, const std::string& value, const scoped_refptr<net::URLRequestContextGetter>& context_getter, base::WaitableEvent* event, bool* success) { context_getter->GetURLRequestContext()->cookie_store()-> SetCookieWithOptionsAsync( url, value, net::CookieOptions(), base::Bind(&SetCookieCallback, event, success)); } void SetCookieWithDetailsOnIOThread( const GURL& url, const net::CanonicalCookie& cookie, const std::string& original_domain, const scoped_refptr<net::URLRequestContextGetter>& context_getter, base::WaitableEvent* event, bool* success) { net::CookieMonster* cookie_monster = context_getter->GetURLRequestContext()->cookie_store()-> GetCookieMonster(); cookie_monster->SetCookieWithDetailsAsync( url, cookie.Name(), cookie.Value(), original_domain, cookie.Path(), cookie.ExpiryDate(), cookie.IsSecure(), cookie.IsHttpOnly(), base::Bind(&SetCookieCallback, event, success)); } void DeleteCookieCallback(base::WaitableEvent* event) { event->Signal(); } void DeleteCookieOnIOThread( const GURL& url, const std::string& name, const scoped_refptr<net::URLRequestContextGetter>& context_getter, base::WaitableEvent* event) { context_getter->GetURLRequestContext()->cookie_store()-> DeleteCookieAsync(url, name, base::Bind(&DeleteCookieCallback, event)); } } // namespace namespace automation_util { Browser* GetBrowserAt(int index) { // The automation layer doesn't support non-native desktops. BrowserList* native_list = BrowserList::GetInstance(chrome::HOST_DESKTOP_TYPE_NATIVE); if (index < 0 || index >= static_cast<int>(native_list->size())) return NULL; return native_list->get(index); } WebContents* GetWebContentsAt(int browser_index, int tab_index) { if (tab_index < 0) return NULL; Browser* browser = GetBrowserAt(browser_index); if (!browser || tab_index >= browser->tab_strip_model()->count()) return NULL; return browser->tab_strip_model()->GetWebContentsAt(tab_index); } #if defined(OS_CHROMEOS) Profile* GetCurrentProfileOnChromeOS(std::string* error_message) { const UserManager* user_manager = UserManager::Get(); if (!user_manager) { *error_message = "No user manager."; return NULL; } if (!user_manager->IsUserLoggedIn()) { ExistingUserController* controller = ExistingUserController::current_controller(); if (!controller) { *error_message = "Cannot get controller though user is not logged in."; return NULL; } chromeos::WebUILoginDisplayHost* webui_login_display_host = static_cast<chromeos::WebUILoginDisplayHost*>( controller->login_display_host()); content::WebUI* web_ui = webui_login_display_host->GetOobeUI()->web_ui(); if (!web_ui) { *error_message = "Unable to get webui from login display host."; return NULL; } return Profile::FromWebUI(web_ui); } else { ash::Shell* shell = ash::Shell::GetInstance(); if (!shell || !shell->delegate()) { *error_message = "Unable to get shell delegate."; return NULL; } return Profile::FromBrowserContext( shell->delegate()->GetCurrentBrowserContext()); } return NULL; } #endif // defined(OS_CHROMEOS) Browser* GetBrowserForTab(WebContents* tab) { for (chrome::BrowserIterator it; !it.done(); it.Next()) { Browser* browser = *it; for (int tab_index = 0; tab_index < browser->tab_strip_model()->count(); ++tab_index) { if (browser->tab_strip_model()->GetWebContentsAt(tab_index) == tab) return browser; } } return NULL; } net::URLRequestContextGetter* GetRequestContext(WebContents* contents) { // Since we may be on the UI thread don't call GetURLRequestContext(). // Get the request context specific to the current WebContents and app. return contents->GetBrowserContext()->GetRequestContextForRenderProcess( contents->GetRenderProcessHost()->GetID()); } void GetCookies(const GURL& url, WebContents* contents, int* value_size, std::string* value) { *value_size = -1; if (url.is_valid() && contents) { scoped_refptr<net::URLRequestContextGetter> context_getter = GetRequestContext(contents); base::WaitableEvent event(true /* manual reset */, false /* not initially signaled */); CHECK(BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&GetCookiesOnIOThread, url, context_getter, &event, value))); event.Wait(); *value_size = static_cast<int>(value->size()); } } void SetCookie(const GURL& url, const std::string& value, WebContents* contents, int* response_value) { *response_value = -1; if (url.is_valid() && contents) { scoped_refptr<net::URLRequestContextGetter> context_getter = GetRequestContext(contents); base::WaitableEvent event(true /* manual reset */, false /* not initially signaled */); bool success = false; CHECK(BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&SetCookieOnIOThread, url, value, context_getter, &event, &success))); event.Wait(); if (success) *response_value = 1; } } void DeleteCookie(const GURL& url, const std::string& cookie_name, WebContents* contents, bool* success) { *success = false; if (url.is_valid() && contents) { scoped_refptr<net::URLRequestContextGetter> context_getter = GetRequestContext(contents); base::WaitableEvent event(true /* manual reset */, false /* not initially signaled */); CHECK(BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&DeleteCookieOnIOThread, url, cookie_name, context_getter, &event))); event.Wait(); *success = true; } } void GetCookiesJSON(AutomationProvider* provider, DictionaryValue* args, IPC::Message* reply_message) { AutomationJSONReply reply(provider, reply_message); std::string url; if (!args->GetString("url", &url)) { reply.SendError("'url' missing or invalid"); return; } // Since we may be on the UI thread don't call GetURLRequestContext(). scoped_refptr<net::URLRequestContextGetter> context_getter = provider->profile()->GetRequestContext(); net::CookieList cookie_list; base::WaitableEvent event(true /* manual reset */, false /* not initially signaled */); base::Closure task = base::Bind(&GetCanonicalCookiesOnIOThread, GURL(url), context_getter, &event, &cookie_list); if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, task)) { reply.SendError("Couldn't post task to get the cookies"); return; } event.Wait(); ListValue* list = new ListValue(); for (size_t i = 0; i < cookie_list.size(); ++i) { const net::CanonicalCookie& cookie = cookie_list[i]; DictionaryValue* cookie_dict = new DictionaryValue(); cookie_dict->SetString("name", cookie.Name()); cookie_dict->SetString("value", cookie.Value()); cookie_dict->SetString("path", cookie.Path()); cookie_dict->SetString("domain", cookie.Domain()); cookie_dict->SetBoolean("secure", cookie.IsSecure()); cookie_dict->SetBoolean("http_only", cookie.IsHttpOnly()); if (cookie.IsPersistent()) cookie_dict->SetDouble("expiry", cookie.ExpiryDate().ToDoubleT()); list->Append(cookie_dict); } DictionaryValue dict; dict.Set("cookies", list); reply.SendSuccess(&dict); } void DeleteCookieJSON(AutomationProvider* provider, DictionaryValue* args, IPC::Message* reply_message) { AutomationJSONReply reply(provider, reply_message); std::string url, name; if (!args->GetString("url", &url)) { reply.SendError("'url' missing or invalid"); return; } if (!args->GetString("name", &name)) { reply.SendError("'name' missing or invalid"); return; } // Since we may be on the UI thread don't call GetURLRequestContext(). scoped_refptr<net::URLRequestContextGetter> context_getter = provider->profile()->GetRequestContext(); base::WaitableEvent event(true /* manual reset */, false /* not initially signaled */); base::Closure task = base::Bind(&DeleteCookieOnIOThread, GURL(url), name, context_getter, &event); if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, task)) { reply.SendError("Couldn't post task to delete the cookie"); return; } event.Wait(); reply.SendSuccess(NULL); } void SetCookieJSON(AutomationProvider* provider, DictionaryValue* args, IPC::Message* reply_message) { AutomationJSONReply reply(provider, reply_message); std::string url; if (!args->GetString("url", &url)) { reply.SendError("'url' missing or invalid"); return; } DictionaryValue* cookie_dict; if (!args->GetDictionary("cookie", &cookie_dict)) { reply.SendError("'cookie' missing or invalid"); return; } std::string name, value; std::string domain; std::string path = "/"; bool secure = false; double expiry = 0; bool http_only = false; if (!cookie_dict->GetString("name", &name)) { reply.SendError("'name' missing or invalid"); return; } if (!cookie_dict->GetString("value", &value)) { reply.SendError("'value' missing or invalid"); return; } if (cookie_dict->HasKey("domain") && !cookie_dict->GetString("domain", &domain)) { reply.SendError("optional 'domain' invalid"); return; } if (cookie_dict->HasKey("path") && !cookie_dict->GetString("path", &path)) { reply.SendError("optional 'path' invalid"); return; } if (cookie_dict->HasKey("secure") && !cookie_dict->GetBoolean("secure", &secure)) { reply.SendError("optional 'secure' invalid"); return; } if (cookie_dict->HasKey("expiry")) { if (!cookie_dict->GetDouble("expiry", &expiry)) { reply.SendError("optional 'expiry' invalid"); return; } } if (cookie_dict->HasKey("http_only") && !cookie_dict->GetBoolean("http_only", &http_only)) { reply.SendError("optional 'http_only' invalid"); return; } scoped_ptr<net::CanonicalCookie> cookie( net::CanonicalCookie::Create( GURL(url), name, value, domain, path, base::Time(), base::Time::FromDoubleT(expiry), secure, http_only)); if (!cookie.get()) { reply.SendError("given 'cookie' parameters are invalid"); return; } // Since we may be on the UI thread don't call GetURLRequestContext(). scoped_refptr<net::URLRequestContextGetter> context_getter = provider->profile()->GetRequestContext(); base::WaitableEvent event(true /* manual reset */, false /* not initially signaled */); bool success = false; base::Closure task = base::Bind( &SetCookieWithDetailsOnIOThread, GURL(url), *cookie.get(), domain, context_getter, &event, &success); if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, task)) { reply.SendError("Couldn't post task to set the cookie"); return; } event.Wait(); if (!success) { reply.SendError("Could not set the cookie"); return; } reply.SendSuccess(NULL); } bool SendErrorIfModalDialogActive(AutomationProvider* provider, IPC::Message* message) { bool active = AppModalDialogQueue::GetInstance()->HasActiveDialog(); if (active) { AutomationJSONReply(provider, message).SendErrorCode( automation::kBlockedByModalDialog); } return active; } AutomationId GetIdForTab(const WebContents* tab) { const SessionTabHelper* session_tab_helper = SessionTabHelper::FromWebContents(tab); return AutomationId(AutomationId::kTypeTab, base::IntToString(session_tab_helper->session_id().id())); } AutomationId GetIdForExtensionView( const content::RenderViewHost* render_view_host) { AutomationId::Type type; WebContents* web_contents = WebContents::FromRenderViewHost(render_view_host); switch (chrome::GetViewType(web_contents)) { case chrome::VIEW_TYPE_EXTENSION_POPUP: type = AutomationId::kTypeExtensionPopup; break; case chrome::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE: type = AutomationId::kTypeExtensionBgPage; break; case chrome::VIEW_TYPE_EXTENSION_INFOBAR: type = AutomationId::kTypeExtensionInfobar; break; case chrome::VIEW_TYPE_APP_SHELL: type = AutomationId::kTypeAppShell; break; default: type = AutomationId::kTypeInvalid; break; } // Since these extension views do not permit navigation, using the // renderer process and view ID should suffice. std::string id = base::StringPrintf("%d|%d", render_view_host->GetRoutingID(), render_view_host->GetProcess()->GetID()); return AutomationId(type, id); } AutomationId GetIdForExtension(const extensions::Extension* extension) { return AutomationId(AutomationId::kTypeExtension, extension->id()); } bool GetTabForId(const AutomationId& id, WebContents** tab) { if (id.type() != AutomationId::kTypeTab) return false; printing::PrintPreviewDialogController* preview_controller = printing::PrintPreviewDialogController::GetInstance(); for (chrome::BrowserIterator it; !it.done(); it.Next()) { Browser* browser = *it; for (int tab_index = 0; tab_index < browser->tab_strip_model()->count(); ++tab_index) { WebContents* web_contents = browser->tab_strip_model()->GetWebContentsAt(tab_index); SessionTabHelper* session_tab_helper = SessionTabHelper::FromWebContents(web_contents); if (base::IntToString( session_tab_helper->session_id().id()) == id.id()) { *tab = web_contents; return true; } if (preview_controller) { WebContents* print_preview_contents = preview_controller->GetPrintPreviewForContents(web_contents); if (print_preview_contents) { SessionTabHelper* preview_session_tab_helper = SessionTabHelper::FromWebContents(print_preview_contents); std::string preview_id = base::IntToString( preview_session_tab_helper->session_id().id()); if (preview_id == id.id()) { *tab = print_preview_contents; return true; } } } } } return false; } namespace { bool GetExtensionRenderViewForId( const AutomationId& id, Profile* profile, RenderViewHost** rvh) { ExtensionProcessManager* extension_mgr = extensions::ExtensionSystem::Get(profile)->process_manager(); const ExtensionProcessManager::ViewSet view_set = extension_mgr->GetAllViews(); for (ExtensionProcessManager::ViewSet::const_iterator iter = view_set.begin(); iter != view_set.end(); ++iter) { content::RenderViewHost* host = *iter; AutomationId this_id = GetIdForExtensionView(host); if (id == this_id) { *rvh = host; return true; } } return false; } } // namespace bool GetRenderViewForId( const AutomationId& id, Profile* profile, RenderViewHost** rvh) { switch (id.type()) { case AutomationId::kTypeTab: { WebContents* tab; if (!GetTabForId(id, &tab)) return false; *rvh = tab->GetRenderViewHost(); break; } case AutomationId::kTypeExtensionPopup: case AutomationId::kTypeExtensionBgPage: case AutomationId::kTypeExtensionInfobar: case AutomationId::kTypeAppShell: if (!GetExtensionRenderViewForId(id, profile, rvh)) return false; break; default: return false; } return true; } bool GetExtensionForId( const AutomationId& id, Profile* profile, const extensions::Extension** extension) { if (id.type() != AutomationId::kTypeExtension) return false; ExtensionService* service = extensions::ExtensionSystem::Get(profile)-> extension_service(); const extensions::Extension* installed_extension = service->GetInstalledExtension(id.id()); if (installed_extension) *extension = installed_extension; return !!installed_extension; } bool DoesObjectWithIdExist(const AutomationId& id, Profile* profile) { switch (id.type()) { case AutomationId::kTypeTab: { WebContents* tab; return GetTabForId(id, &tab); } case AutomationId::kTypeExtensionPopup: case AutomationId::kTypeExtensionBgPage: case AutomationId::kTypeExtensionInfobar: case AutomationId::kTypeAppShell: { RenderViewHost* rvh; return GetExtensionRenderViewForId(id, profile, &rvh); } case AutomationId::kTypeExtension: { const extensions::Extension* extension; return GetExtensionForId(id, profile, &extension); } default: break; } return false; } } // namespace automation_util
bsd-3-clause
cjmabry/PoliChart
setup.py
900
# -*- coding: utf-8 -*- from setuptools import setup project = "polichart" setup( name=project, version='0.1', url='https://github.com/cjmabry/PoliChart', description='Election projections, data visualization, and political rants.', author='Chris Mabry', author_email='cjmab28@gmail.com', packages=["polichart"], include_package_data=True, zip_safe=False, install_requires=[ 'Flask>=0.10.1', 'Flask-SQLAlchemy', 'Flask-WTF', 'Flask-Script', 'Flask-Babel', 'Flask-Testing', 'Flask-Mail', 'Flask-Cache', 'Flask-Login', 'Flask-OpenID', 'nose', 'mysql-python', 'fabric', ], test_suite='tests', classifiers=[ 'Environment :: Web Environment', 'Operating System :: OS Independent', 'Programming Language :: Python' ] )
bsd-3-clause
brumschlag/rhino-tools
rhino-etl/Rhino.Etl.Core/Files/FluentFile.cs
3619
namespace Rhino.Etl.Core.Files { using System; using System.Collections; using System.IO; using System.Text; using FileHelpers; /// <summary> /// Gives a fluent interface syntax on top of the <see cref="FileHelperEngine"/> /// </summary> public class FluentFile { private readonly FileHelperAsyncEngine engine; /// <summary> /// Get a new fluent file instance for <typeparam name="T"></typeparam> /// </summary> public static FluentFile For<T>() { return new FluentFile(typeof(T)); } /// <summary> /// Initializes a new instance of the <see cref="FluentFile"/> class. /// </summary> /// <param name="type">The type.</param> public FluentFile(Type type) { engine = new FileHelperAsyncEngine(type); } /// <summary> /// Specify which file to start reading from /// </summary> /// <param name="filename">The filename.</param> public FileEngine From(string filename) { filename = NormalizeFilename(filename); engine.BeginReadFile(filename); return new FileEngine(engine); } /// <summary> /// Specify which file to start writing to /// </summary> /// <param name="filename">The filename.</param> /// <remarks> /// This will overwrite the file, use <see cref="AppendTo"/> if you want /// to append. /// </remarks> public FileEngine To(string filename) { filename = NormalizeFilename(filename); engine.BeginWriteFile(filename); return new FileEngine(engine); } /// <summary> /// Specify which file to start appending to /// </summary> /// <param name="filename">The filename.</param> /// <returns></returns> public FileEngine AppendTo(string filename) { engine.BeginAppendToFile(filename); return new FileEngine(engine); } private static string NormalizeFilename(string filename) { if (filename.StartsWith("~") == false) return filename; //note that this ignores rooted paths return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, filename); } /// <summary> /// Gets or sets the options. /// </summary> /// <value>The options.</value> public RecordOptions Options { get { return engine.Options; } set { engine.Options = value; } } /// <summary> /// Gets or sets the footer text. /// </summary> /// <value>The footer text.</value> public string FooterText { get { return engine.FooterText; } set { engine.FooterText = value; } } /// <summary> /// Gets or sets the header text. /// </summary> /// <value>The header text.</value> public string HeaderText { get { return engine.HeaderText; } set { engine.HeaderText = value; } } /// <summary> /// Gets or sets the encoding. /// </summary> /// <value>The encoding.</value> public Encoding Encoding { get { return engine.Encoding; } set { engine.Encoding = value; } } } }
bsd-3-clause
openjaf/spree_travel_core
spec/models/spree/context_option_value_spec.rb
229
require 'spec_helper' describe Spree::ContextOptionValue do it { expect(Spree::ContextOptionValue.new.respond_to?(:context)).to eq true } it { expect(Spree::ContextOptionValue.new.respond_to?(:option_value)).to eq true } end
bsd-3-clause
exponentjs/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/interfaces/font/FontManagerInterface.java
199
package abi44_0_0.expo.modules.interfaces.font; import android.graphics.Typeface; public interface FontManagerInterface { void setTypeface(String fontFamilyName, int style, Typeface typeface); }
bsd-3-clause
ridhobc/sitampan
backend/models/UserSearch.php
2535
<?php namespace backend\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use backend\models\User; /** * UserSearch represents the model behind the search form about `backend\models\User`. */ class UserSearch extends User { /** * @inheritdoc */ public function rules() { return [ [['id', 'gender', 'religion_id', 'status', 'created_at', 'updated_at'], 'integer'], [['username', 'auth_key', 'password_hash', 'password_reset_token', 'name', 'born', 'birthday', 'address', 'phone', 'email', 'role'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = User::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); $this->load($params); if (!$this->validate()) { // uncomment the following line if you do not want to any records when validation fails // $query->where('0=1'); return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'gender' => $this->gender, 'birthday' => $this->birthday, 'religion_id' => $this->religion_id, 'status' => $this->status, 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, 'religion_id' => $this->religion_id, ]); $query->andFilterWhere(['like', 'username', $this->username]) ->andFilterWhere(['like', 'auth_key', $this->auth_key]) ->andFilterWhere(['like', 'password_hash', $this->password_hash]) ->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token]) ->andFilterWhere(['like', 'name', $this->name]) ->andFilterWhere(['like', 'born', $this->born]) ->andFilterWhere(['like', 'address', $this->address]) ->andFilterWhere(['like', 'phone', $this->phone]) ->andFilterWhere(['like', 'email', $this->email]) ->andFilterWhere(['like', 'role', $this->role]) ->andFilterWhere(['like', 'religion_id', $this->religion_id]); return $dataProvider; } }
bsd-3-clause
UCSD-PL/RefScript
tests/pos/simple/08-func-expression.ts
325
/*@ readonly bar :: (x: number) => {number | v = x + 1} */ let bar = function(x: number) { return x + 1; } /*@ readonly foo :: (x: number) => {number | v = x + 2} */ let foo = function(x: number) { let a = bar(x); let b = bar(a); return b; } let baz = foo; assert(bar(1) === 2); assert(foo(1) === baz(1));
bsd-3-clause
endlessm/chromium-browser
components/permissions/android/java/src/org/chromium/components/permissions/nfc/NfcSystemLevelPrompt.java
5151
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.components.permissions.nfc; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.os.Build; import android.provider.Settings; import android.view.LayoutInflater; import android.view.View; import android.widget.TextView; import androidx.annotation.VisibleForTesting; import androidx.core.widget.TextViewCompat; import org.chromium.base.task.PostTask; import org.chromium.components.permissions.R; import org.chromium.content_public.browser.UiThreadTaskTraits; import org.chromium.ui.base.WindowAndroid; import org.chromium.ui.modaldialog.DialogDismissalCause; import org.chromium.ui.modaldialog.ModalDialogManager; import org.chromium.ui.modaldialog.ModalDialogProperties; import org.chromium.ui.modelutil.PropertyModel; /** * Implements a modal dialog that prompts the user about turning on the NFC adapter on the system * level. */ public class NfcSystemLevelPrompt implements ModalDialogProperties.Controller { private ModalDialogManager mModalDialogManager; private WindowAndroid mWindowAndroid; private Runnable mCallback; /** * Triggers a prompt to ask the user to turn on the system NFC setting on their device. * * <p>The prompt will be triggered within the specified window. * * @param window The current window to display the prompt into. * @param callback The callback to be called when dialog is closed. */ public void show(WindowAndroid window, Runnable callback) { ModalDialogManager modalDialogManager = window.getModalDialogManager(); if (modalDialogManager == null) { PostTask.postTask(UiThreadTaskTraits.DEFAULT, () -> callback.run()); return; } show(window, modalDialogManager, callback); } @VisibleForTesting protected void show( WindowAndroid window, ModalDialogManager modalDialogManager, Runnable callback) { Activity activity = window.getActivity().get(); LayoutInflater inflater = LayoutInflater.from(activity); View customView = inflater.inflate(R.layout.permission_dialog, null); TextView messageTextView = customView.findViewById(R.id.text); messageTextView.setText(R.string.nfc_disabled_on_device_message); TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds( messageTextView, R.drawable.settings_nfc, 0, 0, 0); Resources resources = activity.getResources(); PropertyModel model = new PropertyModel.Builder(ModalDialogProperties.ALL_KEYS) .with(ModalDialogProperties.CONTROLLER, this) .with(ModalDialogProperties.CUSTOM_VIEW, customView) .with(ModalDialogProperties.POSITIVE_BUTTON_TEXT, resources, R.string.nfc_prompt_turn_on) .with(ModalDialogProperties.NEGATIVE_BUTTON_TEXT, resources, R.string.cancel) .with(ModalDialogProperties.CONTENT_DESCRIPTION, resources, R.string.nfc_disabled_on_device_message) .with(ModalDialogProperties.FILTER_TOUCH_FOR_SECURITY, true) .build(); mWindowAndroid = window; mCallback = callback; mModalDialogManager = modalDialogManager; mModalDialogManager.showDialog(model, ModalDialogManager.ModalDialogType.TAB); } @Override public void onClick(PropertyModel model, int buttonType) { if (buttonType == ModalDialogProperties.ButtonType.NEGATIVE) { mModalDialogManager.dismissDialog(model, DialogDismissalCause.NEGATIVE_BUTTON_CLICKED); } else { String nfcAction = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) ? Settings.Panel.ACTION_NFC : Settings.ACTION_NFC_SETTINGS; Intent intent = new Intent(nfcAction); try { mWindowAndroid.showIntent(intent, new WindowAndroid.IntentCallback() { @Override public void onIntentCompleted( WindowAndroid window, int resultCode, Intent data) { mModalDialogManager.dismissDialog( model, DialogDismissalCause.POSITIVE_BUTTON_CLICKED); } }, null); } catch (android.content.ActivityNotFoundException ex) { mModalDialogManager.dismissDialog( model, DialogDismissalCause.POSITIVE_BUTTON_CLICKED); } } } @Override public void onDismiss(PropertyModel model, int dismissalCause) { if (mCallback != null) mCallback.run(); mCallback = null; } }
bsd-3-clause
pmos69/vast
test/unit/tests/hash.cc
1052
#include "vast/util/hash/crc.h" #include "vast/util/hash/murmur.h" #include "vast/util/hash/xxhash.h" #define SUITE util #include "test.h" using namespace vast; using namespace vast::util; TEST(murmur hash) { CHECK(murmur3<32>::digest(42) == 3160117731); } TEST(xxhash) { CHECK(xxhash64::digest("42", 42) == 7873697032674743835); // includes NUL xxhash64 xxh64; xxh64.add("foo", 3); CHECK(xxh64.get() == 3728699739546630719ul); xxh64.add("bar", 3); CHECK(xxh64.get() == 11721187498075204345ul); xxh64.add("baz", 3); CHECK(xxh64.get() == 6505385152087097371ul); CHECK(xxhash32::digest(42) == 1161967057); xxhash32 xxh32; xxh32.add(0); xxh32.add(1); xxh32.add(2); CHECK(xxh32.get() == 964478135); } TEST(crc32) { CHECK(crc32::digest('f') == 1993550816); CHECK(crc32::digest('o') == 252678980); CHECK(crc32::digest_bytes("foo", 3) == 2356372769); crc32 crc; crc.add('f'); CHECK(crc.get() == 1993550816); crc.add('o'); CHECK(crc.get() == 2943590935); crc.add('o'); CHECK(crc.get() == 2356372769); }
bsd-3-clause
h3/django-unsocial
unsocial/blocklist.py
100
PATTERNS = [ r'(<script\s+?.*facebook\.\w+\/.*</script>)', r'(<fb:like\s+?.*</fb:like>)', ]
bsd-3-clause
marineam/coreos-dev-util
downloader_unittest.py
8899
#!/usr/bin/python # # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Unit tests for downloader module.""" import os import shutil import tempfile import unittest import mox import build_artifact import common_util import devserver import downloader # Fake Dev Server Layout: TEST_LAYOUT = { 'test-board-1': ['R17-1413.0.0-a1-b1346', 'R17-18.0.0-a1-b1346'], 'test-board-2': ['R16-2241.0.0-a0-b2', 'R17-2.0.0-a1-b1346'], 'test-board-3': [] } class DownloaderTestBase(mox.MoxTestBase): def setUp(self): mox.MoxTestBase.setUp(self) self._work_dir = tempfile.mkdtemp('downloader-test') self.build = 'R17-1413.0.0-a1-b1346' self.archive_url_prefix = ( 'gs://chromeos-image-archive/x86-mario-release/' + self.build) def tearDown(self): shutil.rmtree(self._work_dir, ignore_errors=True) def _CommonDownloaderSetup(self, ignore_background=False): """Common code to downloader tests. Mocks out key util module methods, creates mock artifacts and sets appropriate expectations. @ignore_background Indicate that background artifacts should be ignored. @return iterable of artifact objects with appropriate expectations. """ board = 'x86-mario-release' self.mox.StubOutWithMock(common_util, 'AcquireLock') self.mox.StubOutWithMock(common_util, 'GatherArtifactDownloads') self.mox.StubOutWithMock(common_util, 'ReleaseLock') self.mox.StubOutWithMock(tempfile, 'mkdtemp') lock_tag = self._ClassUnderTest().GenerateLockTag(board, self.build) common_util.AcquireLock( static_dir=self._work_dir, tag=lock_tag).AndReturn(self._work_dir) common_util.ReleaseLock(static_dir=self._work_dir, tag=lock_tag) tempfile.mkdtemp(suffix=mox.IgnoreArg()).AndReturn(self._work_dir) return self._GenerateArtifacts(ignore_background) def _CreateArtifactDownloader(self, artifacts): """Create and return a Downloader of the appropriate type. The returned downloader will expect to download and stage the Artifacts listed in [artifacts]. @param artifacts: iterable of Artifacts. @return instance of downloader.Downloader or subclass. """ raise NotImplementedError() def _ClassUnderTest(self): """Return class object of the type being tested. @return downloader.Downloader class object, or subclass. """ raise NotImplementedError() def _GenerateArtifacts(self, ignore_background): """Instantiate artifact mocks and set expectations on them. @ignore_background Indicate that background artifacts should be ignored. This gets passed by CommonDownloaderSetup. @return iterable of artifact objects with appropriate expectations. """ raise NotImplementedError() class DownloaderTest(DownloaderTestBase): """Unit tests for downloader.Downloader. setUp() and tearDown() inherited from DownloaderTestBase. """ def _CreateArtifactDownloader(self, artifacts): d = downloader.Downloader(self._work_dir) self.mox.StubOutWithMock(d, 'GatherArtifactDownloads') d.GatherArtifactDownloads( self._work_dir, self.archive_url_prefix, self._work_dir, self.build).AndReturn(artifacts) return d def _ClassUnderTest(self): return downloader.Downloader def _GenerateArtifacts(self, ignore_background): """Instantiate artifact mocks and set expectations on them. Sets up artifacts and sets up expectations for synchronous artifacts to be downloaded first. @ignore_background If True, doesn't use mocks for download/stage methods. @return iterable of artifact objects with appropriate expectations. """ artifacts = [] for index in range(5): artifact = self.mox.CreateMock(build_artifact.BuildArtifact) # Make every other artifact synchronous. if index % 2 == 0: artifact.Synchronous = lambda: True artifact.Download() artifact.Stage() else: artifact.Synchronous = lambda: False if ignore_background: artifact.Download = lambda: None artifact.Stage = lambda: None artifacts.append(artifact) return artifacts def testDownloaderSerially(self): """Runs through the standard downloader workflow with no backgrounding.""" artifacts = self._CommonDownloaderSetup() # Downloads non-synchronous artifacts second. for index, artifact in enumerate(artifacts): if index % 2 != 0: artifact.Download() artifact.Stage() d = self._CreateArtifactDownloader(artifacts) self.mox.ReplayAll() self.assertEqual(d.Download(self.archive_url_prefix, background=False), 'Success') self.mox.VerifyAll() def testDownloaderInBackground(self): """Runs through the standard downloader workflow with backgrounding.""" artifacts = self._CommonDownloaderSetup(ignore_background=True) d = self._CreateArtifactDownloader(artifacts) self.mox.ReplayAll() d.Download(self.archive_url_prefix, background=True) self.assertEqual(d.GetStatusOfBackgroundDownloads(), 'Success') self.mox.VerifyAll() def testInteractionWithDevserver(self): """Tests interaction between the downloader and devserver methods.""" artifacts = self._CommonDownloaderSetup(ignore_background=True) common_util.GatherArtifactDownloads( self._work_dir, self.archive_url_prefix, self._work_dir, self.build).AndReturn(artifacts) class FakeUpdater(): static_dir = self._work_dir devserver.updater = FakeUpdater() self.mox.ReplayAll() dev = devserver.DevServerRoot() status = dev.download(archive_url=self.archive_url_prefix) self.assertTrue(status, 'Success') status = dev.wait_for_status(archive_url=self.archive_url_prefix) self.assertTrue(status, 'Success') self.mox.VerifyAll() def testBuildStaged(self): """Test whether we can correctly check if a build is previously staged.""" base_url = 'gs://chrome-awesome/' build_dir = 'x86-awesome-release/R99-1234.0-r1' archive_url = base_url + build_dir archive_url_non_staged = base_url + 'x86-awesome-release/R99-1234.0-r2' # Create the directory to reflect staging. os.makedirs(os.path.join(self._work_dir, build_dir)) self.assertTrue(downloader.Downloader.BuildStaged(archive_url, self._work_dir)) self.assertTrue(os.path.exists( os.path.join(os.path.join(self._work_dir, build_dir), downloader.Downloader._TIMESTAMP_FILENAME))) self.assertFalse(downloader.Downloader.BuildStaged(archive_url_non_staged, self._work_dir)) def testTrybotBuildStaged(self): """Test whether a previous staged trybot-build can be corrected detected""" base_url = 'gs://chrome-awesome/' build_dir = 'trybot/date/x86-awesome-release/R99-1234.0-r1' archive_url = base_url + build_dir archive_url_non_staged = base_url + 'x86-awesome-release/R99-1234.0-r2' # Create the directory to reflect staging. os.makedirs(os.path.join(self._work_dir, build_dir)) self.assertTrue(downloader.Downloader.BuildStaged(archive_url, self._work_dir)) self.assertFalse(downloader.Downloader.BuildStaged(archive_url_non_staged, self._work_dir)) class SymbolDownloaderTest(DownloaderTestBase): """Unit tests for downloader.SymbolDownloader. setUp() and tearDown() inherited from DownloaderTestBase. """ def _CreateArtifactDownloader(self, artifacts): d = downloader.SymbolDownloader(self._work_dir) self.mox.StubOutWithMock(d, 'GatherArtifactDownloads') d.GatherArtifactDownloads( self._work_dir, self.archive_url_prefix, self._work_dir).AndReturn(artifacts) return d def _ClassUnderTest(self): return downloader.SymbolDownloader def _GenerateArtifacts(self, unused_ignore_background): """Instantiate artifact mocks and set expectations on them. Sets up a DebugTarballBuildArtifact and sets up expectation that it will be downloaded and staged. @return iterable of one artifact object with appropriate expectations. """ artifact = self.mox.CreateMock(build_artifact.BuildArtifact) artifact.Synchronous = lambda: True artifact.Download() artifact.Stage() return [artifact] def testDownloaderSerially(self): """Runs through the symbol downloader workflow.""" d = self._CreateArtifactDownloader(self._CommonDownloaderSetup()) self.mox.ReplayAll() self.assertEqual(d.Download(self.archive_url_prefix), 'Success') self.mox.VerifyAll() if __name__ == '__main__': unittest.main()
bsd-3-clause
xishuophp/bibt
backend/views/article/category_create.php
584
<?php use yii\helpers\Html; /** * @var yii\web\View $this * @var common\models\User $model */ $this->title = Yii::t('app','Create Category'); $this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Category List'), 'url' => ['category-list']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="page-content"> <div class="page-header"> <h1> <?= Html::encode($this->title) ?> </h1> </div> <div class="row"> <div class="col-xs-12"> <?= $this->render('_form_category', [ 'model'=>$model,'categorys'=>$categorys ]) ?> </div> </div> </div>
bsd-3-clause
prolop/Prolop-cms
backend/views/site/_postDashboard.php
414
<?php use common\models\Post; use yii\helpers\Url; /** @var $model Post */ ?> <div class="panel panel-body"> <h4><a href="<?= Url::toRoute('post/update?id='). $model->id?>" class="dashboard-link" style="text-decoration: underline"><?= $model->title ?></a></h4> <img src="../web/<?= $model->images?>" alt="" width="100%"> <p><?= $model->anons ?></p> <h6><?= $model->publish_date ?></h6> </div>
bsd-3-clause
Workday/OpenFrame
mojo/runner/desktop/launcher_process.cc
2188
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <stdio.h> #include <string.h> #include <algorithm> #include <iostream> #include "base/base_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/files/file_util.h" #include "base/message_loop/message_loop.h" #include "base/path_service.h" #include "base/synchronization/waitable_event.h" #include "base/threading/platform_thread.h" #include "mojo/runner/context.h" #include "mojo/runner/switches.h" #include "mojo/shell/switches.h" namespace mojo { namespace runner { int LauncherProcessMain(const GURL& mojo_url, const base::Closure& callback) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (!command_line->HasSwitch(switches::kMojoSingleProcess) && !command_line->HasSwitch("gtest_list_tests")) command_line->AppendSwitch(switches::kEnableMultiprocess); command_line->AppendSwitch("use-new-edk"); // http://crbug.com/546644 command_line->AppendSwitch(switches::kMojoNoSandbox); base::PlatformThread::SetName("mojo_runner"); // We want the shell::Context to outlive the MessageLoop so that pipes are // all gracefully closed / error-out before we try to shut the Context down. Context shell_context; { base::MessageLoop message_loop; base::FilePath shell_dir; PathService::Get(base::DIR_MODULE, &shell_dir); if (!shell_context.Init(shell_dir)) return 0; if (mojo_url.is_empty()) { message_loop.PostTask( FROM_HERE, base::Bind(&Context::RunCommandLineApplication, base::Unretained(&shell_context), base::Closure())); } else { message_loop.PostTask(FROM_HERE, base::Bind(&mojo::runner::Context::Run, base::Unretained(&shell_context), mojo_url)); } message_loop.Run(); // Must be called before |message_loop| is destroyed. shell_context.Shutdown(); } return 0; } } // namespace runner } // namespace mojo
bsd-3-clause
ThePrimedTNT/SkriptEditor
src/skripteditor/addons/skript/evt/EvtOnVehicleExit.java
484
package skripteditor.addons.skript.evt; import skripteditor.events.Event; public class EvtOnVehicleExit extends Event { @Override public void registerUserFriendyPatterns() { registerUserFriendyPattern("vehicle exit"); registerUserFriendyPattern("exit[ing] [a] vehicle"); } @Override public void registerPatterns() { registerPattern("vehicle exit"); registerPattern("exit[ing][ a] vehicle"); } @Override public String getName() { return "On Vehicle Exit"; } }
bsd-3-clause
devilry/devilry-django
devilry/devilry_theme3/staticsources/devilry_theme3/webpack.config.js
1900
const path = require('path'); const webpack = require('webpack'); const appconfig = require("./ievv_buildstatic.appconfig.json"); const import_paths = [path.resolve(__dirname, 'node_modules')]; Array.prototype.push.apply(import_paths, appconfig.npmrun_jsbuild.import_paths); const include = appconfig.npmrun_jsbuild.import_paths.slice(); include.push(path.resolve(__dirname, "scripts/javascript")); const webpackConfig = { entry: path.resolve(__dirname, 'scripts/javascript/devilry_all.js'), output: { filename: 'devilry_all.js', path: path.resolve(appconfig.destinationfolder, 'scripts'), target: 'web' }, resolve: { root: import_paths, extensions: [".js", ""] }, resolveLoader: { // We only want loaders to be resolved from node_modules // in this directory (not in any of the other packages, and // not from other directories). root: path.resolve(__dirname, 'node_modules') }, module: { loaders: [ { test: /.js$/, loader: 'babel-loader', exclude: /node_modules/, include: include, query: { presets: [ 'babel-preset-es2015' ].map(require.resolve) } }, { test: /.json$/, loader: 'json-loader' } ] }, plugins: [] }; if(appconfig.is_in_production_mode) { webpackConfig.devtool = 'source-map'; webpackConfig.plugins.push( new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production') } }) ); } else { webpackConfig.devtool = 'cheap-module-eval-source-map'; webpackConfig.output.pathinfo = true; } module.exports = webpackConfig;
bsd-3-clause
wpjesus/codematch
ietf/utils/aliases.py
2288
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- # # $Id: aliasutil.py $ # # Author: Markus Stenberg <mstenber@cisco.com> # """ Mailing list alias dumping utilities """ from django.conf import settings def rewrite_email_address(email): """ Prettify the email address (and if it's empty, skip it by returning None). """ if not email: return email = email.strip() if not email: return if email[0]=='<' and email[-1] == '>': email = email[1:-1] # If it doesn't look like email, skip if '@' not in email and '?' not in email: return return email def rewrite_address_list(l): """ This utility function makes sure there is exactly one instance of an address within the result list, and preserves order (although it may not be relevant to start with) """ h = {} for address in l: #address = address.strip() if h.has_key(address): continue h[address] = True yield address def dump_sublist(afile, vfile, alias, domain, emails): if not emails: return emails # Nones in the list should be skipped emails = filter(None, emails) # Make sure emails are sane and eliminate the Nones again for # non-sane ones emails = [rewrite_email_address(e) for e in emails] emails = filter(None, emails) # And we'll eliminate the duplicates too but preserve order emails = list(rewrite_address_list(emails)) if not emails: return emails try: aliasaddr = '%s@ietf.org' % (alias, ) # in virtual, --> filtername filtername = 'xfilter-%s' % (alias, ) # in aliases, --> | expandname expandname = 'expand-%s' % (alias, ) # in virtual, --> email list vfile.write('%-64s %s\n' % (aliasaddr, filtername)) afile.write('%-64s "|%s filter %s %s"\n' % (filtername+':', settings.POSTCONFIRM_PATH, expandname, domain)) vfile.write('%-64s %s\n' % ("%s@%s"%(expandname, domain), ', '.join(emails))) except UnicodeEncodeError: # If there's unicode in email address, something is badly # wrong and we just silently punt # XXX - is there better approach? print '# Error encoding', alias, repr(emails) return [] return emails
bsd-3-clause
max-borisov/nerds.marketplace
tests/codeception/unit/models/nerds/SignInFormTest.php
2512
<?php namespace tests\codeception\unit\models\nerds; use Yii; use app\components\HelperUser; use app\models\SignInForm; use Codeception\Specify; use yii\codeception\TestCase; use app\tests\codeception\unit\fixtures\UserFixture; class SignInFormTest extends TestCase { use Specify; public function fixtures() { return [ 'user' => UserFixture::className(), ]; } public function testValidation() { $model = new SignInForm(); $this->specify('validate model with empty attributes', function () use ($model) { expect('email validation errors' , $model->validate(['email']))->false(); expect('password validation errors' , $model->validate(['password']))->false(); }); $this->specify('email has incorrect format', function() use ($model) { $model->email = 'abk.ru'; expect('email validation error', $model->validate(['email']))->false(); }); $this->specify('set correct email and incorrect password', function() use ($model) { $model->email = $this->user('max')->email; $model->password = 'asde'; expect('validate password error', $model->validate())->false(); }); $this->specify('set correct email and password. User account is activated.', function() use ($model) { $model->email = $this->user('max')->email; $model->password = '111111'; expect('validation success', $model->validate())->true(); }); $this->specify('set correct email and password. User account is not activated.', function() { $model = new SignInForm(); $model->email = $this->user('not_confirmed_account')->email; $model->password = '111111'; expect('signin error', $model->validate())->false(); }); } public function testLogin() { $this->specify('user is Guest', function() { expect('user is guest', HelperUser::isGuest())->true(); }); $this->specify('login user by email and password', function() { $model = new SignInForm(); $model->email = $this->user('max')->email; $model->password = '111111'; expect('login success', $model->login())->true(); }); $this->specify('user is not Guest', function() { expect('user is not guest', HelperUser::isGuest())->false(); }); } }
bsd-3-clause
jarlehansen/no5-events-publisher
no5-events-publisher-web/src/AppService.js
249
// @flow const options = { credentials: 'same-origin', headers: { Accept: 'application/json', 'Content-Type': 'application/json' } }; export function getText() { return fetch('/test', options).then(response => response.json()); }
bsd-3-clause
EMSTrack/WebServerAndClient
equipment/models.py
4379
from enum import Enum from django.contrib.gis.db import models from django.template.defaulttags import register from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from emstrack.models import UpdatedByModel from emstrack.util import make_choices @register.filter def get_equipment_type(type): return EquipmentType[type].value class EquipmentType(Enum): B = _('Boolean') I = _('Integer') S = _('String') EquipmentTypeDefaults = { EquipmentType.B.name: "True", EquipmentType.I.name: "0", EquipmentType.S.name: "" } class Equipment(models.Model): name = models.CharField(_('name'), max_length=254, unique=True) type = models.CharField(_('type'), max_length=1, choices=make_choices(EquipmentType)) default = models.CharField(_('default'), max_length=254) def save(self, *args, **kwargs): # set default value if not self.default: self.default = EquipmentTypeDefaults[self.type] # call super super().save(*args, **kwargs) def __str__(self): return "{} ({})".format(self.name, self.type) def get_absolute_url(self): return reverse('equipment:detail', kwargs={'pk': self.id}) class EquipmentSet(models.Model): name = models.CharField(_('name'), max_length=254, unique=True) def get_absolute_url(self): return reverse('equipment:detail-set', kwargs={'pk': self.id}) def __str__(self): return self.name class EquipmentSetItem(UpdatedByModel): equipment_set = models.ForeignKey(EquipmentSet, on_delete=models.CASCADE, verbose_name=_('equipment_set')) equipment = models.ForeignKey(Equipment, on_delete=models.CASCADE, verbose_name=_('equipment')) class EquipmentHolder(models.Model): equipmentsets = models.ManyToManyField(EquipmentSet, blank=True, verbose_name=_('equipmentsets')) def is_hospital(self): return hasattr(self, 'hospital') def is_ambulance(self): return hasattr(self, 'ambulance') def get_type(self): if self.is_hospital(): return "hospital" elif self.is_ambulance(): return "ambulance" return None def get_name(self): if self.is_hospital(): return self.hospital.name elif self.is_ambulance(): return self.ambulance.identifier return None def __str__(self): retval = "Equipment '{}'".format(self.id) if self.is_hospital(): retval += ", Hospital '{}'".format(self.hospital) elif self.is_ambulance(): retval += ", Ambulance '{}'".format(self.ambulance) else: retval += ", Unknown" return retval def get_absolute_url(self): if self.is_hospital(): return reverse('hospital:detail', kwargs={'pk': self.hospital.id}) elif self.is_ambulance(): return reverse('ambulance:detail', kwargs={'pk': self.ambulance.id}) else: return reverse('equipment:detail-holder', kwargs={'pk': self.id}) class EquipmentItem(UpdatedByModel): equipmentholder = models.ForeignKey(EquipmentHolder, on_delete=models.CASCADE, verbose_name=_('equipmentholder')) equipment = models.ForeignKey(Equipment, on_delete=models.CASCADE, verbose_name=_('equipment')) value = models.CharField(_('value'), max_length=254) def save(self, *args, **kwargs): # creation? created = self.pk is None # if no value, set default value if not self.value: self.value = self.equipment.default # save to EquipmentItem super().save(*args, **kwargs) from mqtt.publish import SingletonPublishClient # publish to mqtt client = SingletonPublishClient() client.publish_equipment_item(self) class Meta: unique_together = ('equipmentholder', 'equipment',) def __str__(self): return "EquipmentHolder: {}, Equipment: {}, Count: {}".format(self.equipmentholder, self.equipment, self.value)
bsd-3-clause
straight-street/straight-street-api
protected/config/apiconsts.php
933
<?php require ('common.conf.php'); define('VERSION', '0.1.0'); define('PAGESIZEDEF', 15); define('PAGESIZEMAX', 20); define('APPIDMINCHARS', 5); define('APPIDMAXCHARS', 25); define('VALID_APPID', '/^[a-z][a-z0-9]{'.APPIDMINCHARS.','.APPIDMAXCHARS.'}$/i'); define('MAX_CONCAT_LENGTH', 2048 * 3); # maximum length of group_concant - increasee if media list for tags gets truncated (no utf8 chars will be 1/3 of this) define('URLBASE', 'http://'.$_SERVER['SERVER_NAME'].'/'); define('SYMBOLSENURLBASE', URLBASE.'media/symbols/EN/'); define('APIURLBASE', $config['APP_URL']); define('APIMEDIAURLBASE', APIURLBASE.'symbol/EN/'); define('APITAGSURLBASE', APIURLBASE.'tag/EN/'); // hack to allow const reference in strings and heredoc // use as {$constHack(SYMBOLSENURLBASE)} // $const = function($constant) why does this not work? it's in docs function constHack($constant) { return $constant; } ?>
bsd-3-clause
grapto/Orchard.CloudBust
src/Orchard.Web/Modules/Orchard.Setup/Controllers/SetupController.cs
8091
using System; using System.Linq; using System.Web.Mvc; using Orchard.Environment; using Orchard.Environment.Configuration; using Orchard.Logging; using Orchard.Setup.Services; using Orchard.Setup.ViewModels; using Orchard.Localization; using Orchard.Recipes.Services; using Orchard.Themes; using Orchard.UI.Notify; using Orchard.Security; namespace Orchard.Setup.Controllers { [ValidateInput(false), Themed] public class SetupController : Controller { private readonly IViewsBackgroundCompilation _viewsBackgroundCompilation; private readonly ShellSettings _shellSettings; private readonly INotifier _notifier; private readonly ISetupService _setupService; private const string DefaultRecipe = "Default"; public SetupController( INotifier notifier, ISetupService setupService, IViewsBackgroundCompilation viewsBackgroundCompilation, ShellSettings shellSettings) { _viewsBackgroundCompilation = viewsBackgroundCompilation; _shellSettings = shellSettings; _notifier = notifier; _setupService = setupService; T = NullLocalizer.Instance; Logger = NullLogger.Instance; RecipeExecutionTimeout = 600; } public Localizer T { get; set; } public ILogger Logger { get; set; } public int RecipeExecutionTimeout { get; set; } public ActionResult HowTo() { _notifier.Add(NotifyType.Information, T("Guidelines and information for a succesfull CloudBust installation")); return View(); } public ActionResult Doticca() { _notifier.Add(NotifyType.Information, T("Your application factory on the cloud")); return View(); } private ActionResult IndexViewResult(SetupViewModel model) { return View(model); } public ActionResult Index() { var initialSettings = _setupService.Prime(); var recipes = _setupService.Recipes().ToList(); SetupViewModel setup = new SetupViewModel { AdminUsername = "admin", DatabaseIsPreconfigured = !String.IsNullOrEmpty(initialSettings.DataProvider), Recipes = recipes, startAzure = false }; if (recipes.Any()) { setup.RecipeDescription = recipes[0].Description; } string tenantRecipe = _setupService.Prime().Recipe; if (!string.IsNullOrWhiteSpace(tenantRecipe)) { setup.isTenant = true; if(recipes.Any(x=>x.Name == tenantRecipe && x.IsSetupRecipe)) { setup.Recipe = tenantRecipe; setup.RecipeDescription = recipes.Where(x => x.Name == tenantRecipe).First().Description; } } if (StringComparer.OrdinalIgnoreCase.Equals(initialSettings.Name, ShellSettings.DefaultName)) { _viewsBackgroundCompilation.Start(); } return IndexViewResult(setup); } [HttpPost, ActionName("Index")] public ActionResult IndexPOST(SetupViewModel model) { // Sets the setup request timeout to a configurable amount of seconds to give enough time to execute custom recipes. HttpContext.Server.ScriptTimeout = RecipeExecutionTimeout; var recipes = _setupService.Recipes().ToList(); // If no builtin provider, a connection string is mandatory. if (model.DatabaseProvider != SetupDatabaseType.Builtin && string.IsNullOrEmpty(model.DatabaseConnectionString)) ModelState.AddModelError("DatabaseConnectionString", T("A connection string is required.").Text); if (!String.IsNullOrWhiteSpace(model.ConfirmPassword) && model.AdminPassword != model.ConfirmPassword) { ModelState.AddModelError("ConfirmPassword", T("Password confirmation must match.").Text); } if (model.DatabaseProvider != SetupDatabaseType.Builtin && !string.IsNullOrWhiteSpace(model.DatabaseTablePrefix)) { model.DatabaseTablePrefix = model.DatabaseTablePrefix.Trim(); if (!Char.IsLetter(model.DatabaseTablePrefix[0])) { ModelState.AddModelError("DatabaseTablePrefix", T("The table prefix must begin with a letter.").Text); } if (model.DatabaseTablePrefix.Any(x => !Char.IsLetterOrDigit(x))) { ModelState.AddModelError("DatabaseTablePrefix", T("The table prefix must contain letters or digits.").Text); } } if (model.Recipe == null) { if (!(recipes.Select(r => r.Name).Contains(DefaultRecipe))) { ModelState.AddModelError("Recipe", T("No recipes were found.").Text); } else { model.Recipe = DefaultRecipe; } } if (!ModelState.IsValid) { model.Recipes = recipes; foreach (var recipe in recipes.Where(recipe => recipe.Name == model.Recipe)) { model.RecipeDescription = recipe.Description; } model.DatabaseIsPreconfigured = !String.IsNullOrEmpty(_setupService.Prime().DataProvider); return IndexViewResult(model); } try { string providerName = null; switch (model.DatabaseProvider) { case SetupDatabaseType.Builtin: providerName = "SqlCe"; break; case SetupDatabaseType.SqlServer: providerName = "SqlServer"; break; case SetupDatabaseType.MySql: providerName = "MySql"; break; case SetupDatabaseType.PostgreSql: providerName = "PostgreSql"; break; default: throw new ApplicationException("Unknown database type: " + model.DatabaseProvider); } var recipe = recipes.GetRecipeByName(model.Recipe); var setupContext = new SetupContext { SiteName = model.SiteName, AdminUsername = model.AdminUsername, AdminPassword = model.AdminPassword, DatabaseProvider = providerName, DatabaseConnectionString = model.DatabaseConnectionString, DatabaseTablePrefix = model.DatabaseTablePrefix, EnabledFeatures = null, // Default list Recipe = recipe, startAzure = model.startAzure }; var executionId = _setupService.Setup(setupContext); // First time installation if finally done. Tell the background views compilation // process to stop, so that it doesn't interfere with the user (asp.net compilation // uses a "single lock" mechanism for compiling views). _viewsBackgroundCompilation.Stop(); // Redirect to the welcome page. return Redirect("~/" + _shellSettings.RequestUrlPrefix); } catch (Exception ex) { Logger.Error(ex, "Setup failed"); _notifier.Error(T("Setup failed: {0}", ex.Message)); model.Recipes = recipes; foreach (var recipe in recipes.Where(recipe => recipe.Name == model.Recipe)) { model.RecipeDescription = recipe.Description; } model.DatabaseIsPreconfigured = !String.IsNullOrEmpty(_setupService.Prime().DataProvider); return IndexViewResult(model); } } } }
bsd-3-clause
matthieuklotz/appfabriccachingadmin
Clients/Source/AppFabric.Admin.Clients.Desktop/UserControls/ClusterHealthUserControl.xaml.cs
2250
// ----------------------------------------------------------------------- // <copyright file="ClusterHealthUserControl.xaml.cs" company="Matthieu Klotz"> // Copyright (c) 2013, Matthieu Klotz // 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 Matthieu Klotz 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 HOLDER 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. // </copyright> // ----------------------------------------------------------------------- namespace AppFabric.Admin.Clients.Desktop.UserControls { using System.Windows.Controls; /// <summary> /// Interaction logic for ClusterHealthUserControl.xaml /// </summary> public partial class ClusterHealthUserControl : UserControl { /// <summary> /// Initializes a new instance of the <see cref="ClusterHealthUserControl" /> class. /// </summary> public ClusterHealthUserControl() { this.InitializeComponent(); } } }
bsd-3-clause
assetgraph/assetgraph
test/relations/Html/HtmlAudio.js
1068
const pathModule = require('path'); const expect = require('../../unexpected-with-plugins'); const AssetGraph = require('../../../lib/AssetGraph'); describe('relations/HtmlAudio', function () { it('should handle a test case with existing <audio> tags', async function () { const assetGraph = new AssetGraph({ root: pathModule.resolve( __dirname, '../../../testdata/relations/Html/HtmlAudio/' ), }); await assetGraph.loadAssets('index.html'); await assetGraph.populate({ startAssets: { type: 'Html' }, followRelations: () => false, }); expect(assetGraph, 'to contain relations', 'HtmlAudio', 4); assetGraph.findAssets({ type: 'Html' })[0].url = 'http://example.com/foo/bar.html'; assetGraph.findRelations().forEach(function (relation) { relation.hrefType = 'relative'; }); expect(assetGraph.findRelations(), 'to satisfy', [ { href: '../sound.mp3' }, { href: '../sound.wav' }, { href: '../sound.wma' }, { href: '../sound.flac' }, ]); }); });
bsd-3-clause
SecureAuthCorp/saidp-sdk-csharp
SecureAuth.Sdk/Requests/GroupAssociateRequest.cs
592
using System.Collections.Generic; using System.Runtime.Serialization; namespace SecureAuth.Sdk { [DataContract] public class GroupAssociateRequest : BaseRequest { [DataMember(Name = "groupNames", EmitDefaultValue = false)] public List<string> GroupNames { get; set; } [DataMember(Name = "userIds", EmitDefaultValue = false)] public List<string> UserIds { get; set; } public GroupAssociateRequest() { GroupNames = new List<string>(); UserIds = new List<string>(); } } }
bsd-3-clause
uacaps/UniversityPrograms-Android
UniversityPrograms/app/src/main/java/ua/edu/universityprograms/app/models/Members.java
1168
package ua.edu.universityprograms.app.models; import android.os.Parcel; import android.os.Parcelable; /** * Created by vcaciuc on 6/4/2014. */ public class Members implements Parcelable { public String url, info, name, about; public Members(String url, String name, String info, String about) { this.url = url; this.info = info; this.name = name; this.about = about; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.url); dest.writeString(this.info); dest.writeString(this.name); dest.writeString(this.about); } private Members(Parcel in) { this.url = in.readString(); this.info = in.readString(); this.name = in.readString(); this.about = in.readString(); } public static Creator<Members> CREATOR = new Creator<Members>() { public Members createFromParcel(Parcel source) {return new Members(source); } public Members[] newArray(int size) { return new Members[size]; } }; }
bsd-3-clause
nipy/brainx
brainx/tests/test_nodal_roles.py
1397
#test nodal roles import unittest import networkx as nx from brainx import nodal_roles as nr from brainx import weighted_modularity as wm class TestNodalRoles(unittest.TestCase): def test_disconnected_communites(self): graph = nx.Graph([(0,1),(1,2),(2,0),(3,4),(3,5),(4,5)]) partition = wm.WeightedPartition(graph, communities=[set([0, 1, 2]), set([3, 4, 5])]) wcd = nr.within_community_degree(partition) self.assertAlmostEqual(wcd, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}) pc = nr.participation_coefficient(partition) self.assertEqual(pc, {0: 0.0, 1: 0.0, 2: 0.0, 3: 0.0, 4: 0.0, 5: 0.0}) def test_high_low_pc(self): graph = nx.Graph([(0,1),(1,2),(2,0),(0,3),(3,4),(3,5),(4,5)]) partition = wm.WeightedPartition(graph, communities=[set([0, 1, 2]), set([3, 4, 5])]) pc = nr.participation_coefficient(partition) self.assertAlmostEqual(pc,{0: 0.4444444444444444, 1: 0.0, 2: 0.0, 3: 0.4444444444444444, 4: 0.0, 5: 0.0}) def test_high_low_wcd(self): graph = nx.Graph([(0,1),(0,2),(0,3),(0,4),(0,5),(6,7),(7,8),(8,6)]) partition = wm.WeightedPartition(graph, communities=[set([0, 1, 2, 3, 4, 5]), set([8, 6, 7])]) wcd = nr.within_community_degree(partition) self.assertAlmostEqual(wcd, {0: 2.2360679774997898, 1: -0.44721359549995804, 2: -0.44721359549995804, 3: -0.44721359549995804, 4: -0.44721359549995804, 5: -0.44721359549995804, 6: 0.0, 7: 0.0, 8: 0.0})
bsd-3-clause
ng-web/leapro_crm
views/addresses/_search.php
978
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\AddressesSearch */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="addresses-search"> <?php $form = ActiveForm::begin([ 'action' => ['index'], 'method' => 'get', ]); ?> <?= $form->field($model, 'address_id') ?> <?= $form->field($model, 'address_line1') ?> <?= $form->field($model, 'address_line2') ?> <?= $form->field($model, 'address_province') ?> <?= $form->field($model, 'address_zip') ?> <?php // echo $form->field($model, 'address_type') ?> <?php // echo $form->field($model, 'address_status') ?> <?php // echo $form->field($model, 'address_details') ?> <div class="form-group"> <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?> <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?> </div> <?php ActiveForm::end(); ?> </div>
bsd-3-clause
mcleary/pipeline
dp/rix/gl/src/TextureGLBuffer.cpp
4843
// Copyright NVIDIA Corporation 2011 // 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 NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "BufferGL.h" #include "DataTypeConversionGL.h" #include "TextureGLBuffer.h" #include "SamplerStateGL.h" #include <dp/util/SharedPtr.h> #include <cmath> namespace dp { namespace rix { namespace gl { using namespace dp::rix::core; dp::rix::core::TextureHandle TextureGLBuffer::create( const TextureDescription &textureDescription ) { return new TextureGLBuffer( textureDescription ); } bool TextureGLBuffer::setData( const TextureData& textureData ) { DP_ASSERT( getTexture()->getTarget() == GL_TEXTURE_BUFFER ); switch ( textureData.getTextureDataType() ) { case dp::rix::core::TDT_NATIVE: { DP_ASSERT( dynamic_cast<const TextureDataGLTexture*>(&textureData) ); const TextureDataGLTexture& textureDataGLTexture = static_cast<const TextureDataGLTexture&>(textureData); setTexture( textureDataGLTexture.m_texture ); } break; case dp::rix::core::TDT_BUFFER: { DP_ASSERT( dynamic_cast<const TextureDataBuffer*>(&textureData) ); const TextureDataBuffer& dataBuffer = static_cast<const TextureDataBuffer&>(textureData); DP_ASSERT( handleIsTypeOf<BufferGL>( dataBuffer.m_buffer ) ); BufferGLHandle buffer = handleCast<BufferGL>( dataBuffer.m_buffer.get() ); dp::util::shared_cast<dp::gl::TextureBuffer>( getTexture() )->setBuffer( buffer->getBuffer() ); m_textureBuffer = buffer; } break; case dp::rix::core::TDT_POINTER: case dp::rix::core::TDT_NUM_TEXTUREDATATYPES: DP_ASSERT( !"unsupported" ); break; } return true; } TextureGLBuffer::TextureGLBuffer( const dp::rix::core::TextureDescription& description ) : TextureGL( dp::gl::TextureBuffer::create( getGLInternalFormat( description ) ), description.m_mipmaps ) , m_textureBuffer( nullptr ) { DP_ASSERT( description.m_width == 0 ); DP_ASSERT( description.m_height == 0 ); DP_ASSERT( description.m_depth == 0 ); DP_ASSERT( description.m_layers == 0 ); #if RIX_GL_SAMPLEROBJECT_SUPPORT #else // delete the defaulte sampler state for texture buffers, they should not have a sampler state m_defaultSamplerStateHandle.reset(); #endif } void TextureGLBuffer::upload( unsigned int /*mipMapLevel*/, unsigned int /*layer*/, const void* /*data*/ ) { DP_ASSERT(!"don't call this"); } void TextureGLBuffer::applySamplerState( SamplerStateGLHandle samplerState ) { DP_ASSERT( samplerState == 0 ); if ( samplerState != 0 ) { /* TODO throw exception */ } } void TextureGLBuffer::applyDefaultSamplerState() { } void TextureGLBuffer::setDefaultSamplerState( SamplerStateGLHandle samplerState ) { DP_ASSERT( samplerState == 0 ); if ( samplerState != 0 ) { /* TODO throw exception */ } } } // namespace gl } // namespace rix } // namespace dp
bsd-3-clause
DimensionSrl/ThunderBay
app/models/device.rb
111
class Device < ActiveRecord::Base belongs_to :app has_many :messages self.primary_key = 'identifier' end
bsd-3-clause
andys/ruby-iarm
lib/iarm/client.rb
148
require 'drb' module Iarm class Client def self.connect(server) #DRb.start_service DRbObject.new(nil, server) end end end
bsd-3-clause
eltondias/SistemaVendasGarantias
public/layouts/admin/admin/ajax/buttons.php
55404
<?php $base = 'public/layouts/admin/admin/'; ?> <div class="row"> <div class="col-xs-12 col-sm-7 col-md-7 col-lg-4"> <h1 class="page-title txt-color-blueDark"><i class="fa fa-desktop fa-fw "></i> UI Elements <span>> Buttons </span></h1> </div> <div class="col-xs-12 col-sm-5 col-md-5 col-lg-8"> <ul id="sparks" class=""> <li class="sparks-info"> <h5> My Income <span class="txt-color-blue">$47,171</span></h5> <div class="sparkline txt-color-blue hidden-mobile hidden-md hidden-sm"> 1300, 1877, 2500, 2577, 2000, 2100, 3000, 2700, 3631, 2471, 2700, 3631, 2471 </div> </li> <li class="sparks-info"> <h5> Site Traffic <span class="txt-color-purple"><i class="fa fa-arrow-circle-up" data-rel="bootstrap-tooltip" title="Increased"></i>&nbsp;45%</span></h5> <div class="sparkline txt-color-purple hidden-mobile hidden-md hidden-sm"> 110,150,300,130,400,240,220,310,220,300, 270, 210 </div> </li> <li class="sparks-info"> <h5> Site Orders <span class="txt-color-greenDark"><i class="fa fa-shopping-cart"></i>&nbsp;2447</span></h5> <div class="sparkline txt-color-greenDark hidden-mobile hidden-md hidden-sm"> 110,150,300,130,400,240,220,310,220,300, 270, 210 </div> </li> </ul> </div> </div> <!-- widget grid --> <section id="widget-grid" class=""> <!-- row --> <div class="row"> <!-- NEW WIDGET START --> <article class="col-sm-12"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget well" id="wid-id-0a" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-hand-o-up"></i> </span> <h2>Buttons at a glance </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <h1>Buttons at a glance...</h1> <p> See how aspects of the Bootstrap button system look and feel like at a glance. </p> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th>Button</th> <th>btn-lg Button</th> <th>Small Button</th> <th>Small Mini</th> <th>Disabled Button</th> <th>Button with Icon</th> <th>Split Button</th> </tr> </thead> <tbody> <tr> <td><a class="btn btn-default" href="javascript:void(0);">Default</a></td> <td><a class="btn btn-default btn-lg" href="javascript:void(0);">Default</a></td> <td><a class="btn btn-default btn-sm" href="javascript:void(0);">Default</a></td> <td><a class="btn btn-default btn-xs" href="javascript:void(0);">Default</a></td> <td><a class="btn btn-default disabled" href="javascript:void(0);">Default</a></td> <td><a class="btn btn-default" href="javascript:void(0);"><i class="fa fa-cog"></i> Default</a></td> <td> <div class="btn-group"> <a class="btn btn-default" href="javascript:void(0);">Default</a> <a class="btn btn-default dropdown-toggle" data-toggle="dropdown" href="javascript:void(0);"><span class="caret"></span></a> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div><!-- /btn-group --></td> </tr> <tr> <td><a class="btn btn-primary" href="javascript:void(0);">Primary</a></td> <td><a class="btn btn-primary btn-lg" href="javascript:void(0);">Primary</a></td> <td><a class="btn btn-primary btn-sm" href="javascript:void(0);">Primary</a></td> <td><a class="btn btn-primary btn-xs" href="javascript:void(0);">Primary</a></td> <td><a class="btn btn-primary disabled" href="javascript:void(0);">Primary</a></td> <td><a class="btn btn-primary" href="javascript:void(0);"><i class="fa fa-shopping-cart"></i> Primary</a></td> <td> <div class="btn-group"> <a class="btn btn-primary" href="javascript:void(0);">Primary</a> <a class="btn btn-primary dropdown-toggle" data-toggle="dropdown" href="javascript:void(0);"><span class="caret"></span></a> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div><!-- /btn-group --></td> </tr> <tr> <td><a class="btn btn-info" href="javascript:void(0);">Info</a></td> <td><a class="btn btn-info btn-lg" href="javascript:void(0);">Info</a></td> <td><a class="btn btn-info btn-sm" href="javascript:void(0);">Info</a></td> <td><a class="btn btn-info btn-xs" href="javascript:void(0);">Info</a></td> <td><a class="btn btn-info disabled" href="javascript:void(0);">Info</a></td> <td><a class="btn btn-info" href="javascript:void(0);"><i class="fa fa-exclamation-sign"></i> Info</a></td> <td> <div class="btn-group"> <a class="btn btn-info" href="javascript:void(0);">Info</a> <a class="btn btn-info dropdown-toggle" data-toggle="dropdown" href="javascript:void(0);"><span class="caret"></span></a> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div><!-- /btn-group --></td> </tr> <tr> <td><a class="btn btn-success" href="javascript:void(0);">Success</a></td> <td><a class="btn btn-success btn-lg" href="javascript:void(0);">Success</a></td> <td><a class="btn btn-success btn-sm" href="javascript:void(0);">Success</a></td> <td><a class="btn btn-success btn-xs" href="javascript:void(0);">Success</a></td> <td><a class="btn btn-success disabled" href="javascript:void(0);">Success</a></td> <td><a class="btn btn-success" href="javascript:void(0);"><i class="fa fa-check"></i> Success</a></td> <td> <div class="btn-group"> <a class="btn btn-success" href="javascript:void(0);">Success</a> <a class="btn btn-success dropdown-toggle" data-toggle="dropdown" href="javascript:void(0);"><span class="caret"></span></a> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div><!-- /btn-group --></td> </tr> <tr> <td><a class="btn btn-warning" href="javascript:void(0);">Warning</a></td> <td><a class="btn btn-warning btn-lg" href="javascript:void(0);">Warning</a></td> <td><a class="btn btn-warning btn-sm" href="javascript:void(0);">Warning</a></td> <td><a class="btn btn-warning btn-xs" href="javascript:void(0);">Warning</a></td> <td><a class="btn btn-warning disabled" href="javascript:void(0);">Warning</a></td> <td><a class="btn btn-warning" href="javascript:void(0);"><i class="fa fa-warning-sign"></i> Warning</a></td> <td> <div class="btn-group"> <a class="btn btn-warning" href="javascript:void(0);">Warning</a> <a class="btn btn-warning dropdown-toggle" data-toggle="dropdown" href="javascript:void(0);"><span class="caret"></span></a> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div><!-- /btn-group --></td> </tr> <tr> <td><a class="btn btn-danger" href="javascript:void(0);">Danger</a></td> <td><a class="btn btn-danger btn-lg" href="javascript:void(0);">Danger</a></td> <td><a class="btn btn-danger btn-sm" href="javascript:void(0);">Danger</a></td> <td><a class="btn btn-danger btn-xs" href="javascript:void(0);">Danger</a></td> <td><a class="btn btn-danger disabled" href="javascript:void(0);">Danger</a></td> <td><a class="btn btn-danger" href="javascript:void(0);"><i class="fa fa-remove"></i> Danger</a></td> <td> <div class="btn-group"> <a class="btn btn-danger" href="javascript:void(0);">Danger</a> <a class="btn btn-danger dropdown-toggle" data-toggle="dropdown" href="javascript:void(0);"><span class="caret"></span></a> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div><!-- /btn-group --></td> </tr> </tbody> </table> </div> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> </article> <!-- WIDGET END --> </div> <!-- end row --> <!-- row --> <div class="row"> <!-- NEW WIDGET START --> <article class="col-sm-12 col-md-12 col-lg-6"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-0" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-hand-o-up"></i> </span> <h2>Basic Buttons</h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <p class="alert alert-info"> The icons below are the most basic ones, without any icons or additional css applied to it </p> <p> Buttons come in 6 different default color sets <code> .btn .btn-* </code> <code> .btn-default, .btn-primary, .btn-success... etc </code> </p> <a href="javascript:void(0);" class="btn btn-default">Default</a> <a href="javascript:void(0);" class="btn btn-primary">Primary</a> <a href="javascript:void(0);" class="btn btn-success">Success</a> <a href="javascript:void(0);" class="btn btn-info">Info</a> <a href="javascript:void(0);" class="btn btn-warning">Warning</a> <a href="javascript:void(0);" class="btn btn-danger">Danger</a> <a href="javascript:void(0);" class="btn btn-default disabled">Disabled</a> <a href="javascript:void(0);" class="btn btn-link">Link</a> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-2" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-hand-o-up"></i> </span> <h2>Button Sizes </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <p> Large buttons to attract call to action <code> .btn .btn-lg </code> </p> <a href="javascript:void(0);" class="btn btn-primary btn-lg">Large button</a>&nbsp;<a href="javascript:void(0);" class="btn btn-default btn-lg">Large button</a> <hr class="simple"> <p> The Default button <code> .btn .btn-default </code> </p> <a href="javascript:void(0);" class="btn btn-primary">Default button</a>&nbsp;<a href="javascript:void(0);" class="btn btn-default">Default button</a> <hr class="simple"> <p> Small button for elegance <code> .btn .btn-sm </code> </p> <a href="javascript:void(0);" class="btn btn-primary btn-sm">Small button</a>&nbsp;<a href="javascript:void(0);" class="btn btn-default btn-sm">Small button</a> <hr class="simple"> <p> Extra small button for added info <code> .btn .btn-xs </code> </p> <a href="javascript:void(0);" class="btn btn-primary btn-xs">Mini button</a>&nbsp;<a href="javascript:void(0);" class="btn btn-default btn-xs">Mini button</a> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-4" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-hand-o-up"></i> </span> <h2>Circle Buttons </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <p> Extra Large round buttons <code> .btn-circle .btn-xl </code> </p> <ul class="demo-btns"> <li> <a href="javascript:void(0);" class="btn btn-primary btn-circle btn-xl"><i class="glyphicon glyphicon-list"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default btn-circle btn-xl"><i class="glyphicon glyphicon-ok"></i></a> </li> </ul> <p> Large round buttons <code> .btn-circle .btn-lg </code> </p> <ul class="demo-btns"> <li> <a href="javascript:void(0);" class="btn btn-primary btn-circle btn-lg"><i class="glyphicon glyphicon-list"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default btn-circle btn-lg"><i class="glyphicon glyphicon-ok"></i></a> </li> </ul> <p> Default round buttons <code> .btn-circle </code> </p> <ul class="demo-btns"> <li> <a href="javascript:void(0);" class="btn btn-primary btn-circle"><i class="glyphicon glyphicon-list"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default btn-circle"><i class="glyphicon glyphicon-ok"></i></a> </li> </ul> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-6" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-hand-o-up"></i> </span> <h2>Drop Down buttons </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <p> Button group with dropup/dropdown toggle <code> .btn-group </code> </p> <div class="btn-group"> <button class="btn btn-primary"> Drop Down </button> <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div> <div class="btn-group dropup"> <button class="btn btn-default"> Drop Up </button> <button class="btn btn-default dropdown-toggle" data-toggle="dropdown"> <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div> <hr class="simple"> <p> Default button dropdowns <code> .dropdown-toggle </code> </p> <div class="btn-group"> <button class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> Action <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div> <div class="btn-group"> <button class="btn btn-default dropdown-toggle" data-toggle="dropdown"> Action <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div> <hr class="simple"> <p> Smaller button dropdowns <code> .btn-sm .dropdown-toggle </code> </p> <div class="btn-group"> <button class="btn btn-primary btn-sm dropdown-toggle" data-toggle="dropdown"> Action <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div> <div class="btn-group"> <button class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown"> Action <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div> <hr class="simple"> <p> Extra small button dropdowns <code> .btn-xs .dropdown-toggle </code> </p> <div class="btn-group"> <button class="btn btn-primary btn-xs dropdown-toggle" data-toggle="dropdown"> Action <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div> <div class="btn-group"> <button class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown"> Action <span class="caret"></span> </button> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Action</a> </li> <li> <a href="javascript:void(0);">Another action</a> </li> <li> <a href="javascript:void(0);">Something else here</a> </li> <li class="divider"></li> <li> <a href="javascript:void(0);">Separated link</a> </li> </ul> </div> <hr class="simple"> <h3>Multiple Level Dropdown <small><span class="label label-warning">New!</span></small></h3> <p> Custom created Multiple Level dropdown that works with ease! Simply use the class <code> .dropdown-menu .multi-level </code> </p> <div class="dropdown"> <a id="dLabel" role="button" data-toggle="dropdown" class="btn btn-primary" data-target="#" href="javascript:void(0);"> Multi Level <span class="caret"></span> </a> <ul class="dropdown-menu multi-level" role="menu"> <li> <a href="javascript:void(0);">Some action</a> </li> <li> <a href="javascript:void(0);">Some other action</a> </li> <li class="divider"></li> <li class="dropdown-submenu"> <a tabindex="-1" href="javascript:void(0);">Hover me for more options</a> <ul class="dropdown-menu"> <li> <a tabindex="-1" href="javascript:void(0);">Second level</a> </li> <li class="dropdown-submenu"> <a href="javascript:void(0);">Even More..</a> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">3rd level</a> </li> <li> <a href="javascript:void(0);">3rd level</a> </li> </ul> </li> <li> <a href="javascript:void(0);">Second level</a> </li> <li> <a href="javascript:void(0);">Second level</a> </li> </ul> </li> </ul> </div> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-8" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-hand-o-up"></i> </span> <h2>Button Groups </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <p> Group a series of buttons together on a single line with the button group. Wrap a series of buttons with <code> .btn </code> in <code> .btn-group </code> . </p> <div class="row"> <div class="col-md-12"> <table class="table table-bordered"> <thead> <tr> <th style="width:25%">Horizontal Group</th> <th style="width:25%">With Icons</th> <th style="width:50%">Multiple Button Groups</th> </tr> </thead> <tbody> <tr> <td> <div class="btn-group"> <button type="button" class="btn btn-default"> Left </button> <button type="button" class="btn btn-default"> Middle </button> <button type="button" class="btn btn-default"> Right </button> </div></td> <td> <div class="btn-group"> <button type="button" class="btn btn-default"> <i class="fa fa-align-left"></i> </button> <button type="button" class="btn btn-default"> <i class="fa fa-align-center"></i> </button> <button type="button" class="btn btn-default"> <i class="fa fa-align-right"></i> </button> <button type="button" class="btn btn-default"> <i class="fa fa-align-justify"></i> </button> </div></td> <td> <div class="btn-toolbar"> <div class="btn-group"> <button type="button" class="btn btn-default"> 1 </button> <button type="button" class="btn btn-default"> 2 </button> <button type="button" class="btn btn-default"> 3 </button> <button type="button" class="btn btn-default"> 4 </button> </div> <div class="btn-group"> <button type="button" class="btn btn-default"> 5 </button> <button type="button" class="btn btn-default"> 6 </button> <button type="button" class="btn btn-default"> 7 </button> </div> <div class="btn-group"> <button type="button" class="btn btn-default"> 8 </button> </div> </div></td> </tr> </tbody> </table> </div> </div> <hr class="simple"> <p> Make a set of buttons appear vertically stacked rather than horizontally by putting it in <code> .btn-group-vertical </code> . </p> <div class="row"> <div class="col-md-12"> <table class="table table-bordered"> <thead> <tr> <th style="width:25%">Vertical Group</th> <th style="width:25%">With Dropdown</th> <th style="width:25%">With Icons</th> <th style="width:25%">Multiple Button Groups</th> </tr> </thead> <tbody> <tr> <td> <div class="btn-group-vertical"> <button type="button" class="btn btn-default"> Top </button> <button type="button" class="btn btn-default"> Middle </button> <button type="button" class="btn btn-default"> Bottom </button> </div></td> <td> <div class="btn-group-vertical"> <button type="button" class="btn btn-primary"> Button 1 </button> <button type="button" class="btn btn-primary"> Button 2 </button> <button type="button" class="btn btn-primary"> Button 3 </button> <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"> Dropdown <i class="fa fa-caret-down"></i> </button> <ul class="dropdown-menu"> <li> <a href="javascript:void(0);">Dropdown link</a> </li> <li> <a href="javascript:void(0);">Dropdown link</a> </li> </ul> </div></td> <td> <div class="btn btn-group-vertical"> <a class="btn btn-default" href="javascript:void(0);"><i class="fa fa-align-left"></i></a> <a class="btn btn-default" href="javascript:void(0);"><i class="fa fa-align-center"></i></a> <a class="btn btn-default" href="javascript:void(0);"><i class="fa fa-align-right"></i></a> <a class="btn btn-default" href="javascript:void(0);"><i class="fa fa-align-justify"></i></a> </div></td> <td> <div class="btn-toolbar"> <div class="btn-group-vertical"> <button type="button" class="btn btn-primary"> Page 1 </button> <button type="button" class="btn btn-primary"> Page 2 </button> <button type="button" class="btn btn-primary"> Page 3 </button> <button type="button" class="btn btn-primary"> Page 4 </button> </div> </div></td> </tr> </tbody> </table> </div> </div> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> </article> <!-- WIDGET END --> <!-- NEW WIDGET START --> <article class="col-sm-12 col-md-12 col-lg-6"> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-1" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-hand-o-up"></i> </span> <h2> Mix and match colors </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <p class="alert alert-info"> Custom buttons with core CSS elements. Mix and match existing classes to come up with unique style buttons. <strong>For example:</strong> <code> .btn .bg-color-blueLight .txt-color-white </code> </p> <ul class="demo-btns"> <li> <a href="javascript:void(0);" class="btn bg-color-blueLight txt-color-white">.bg-color-blueLight</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-blue txt-color-white">.bg-color-blue</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-teal txt-color-white">.bg-color-teal</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-blueDark txt-color-white">.bg-color-blueDark</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-green txt-color-white">.bg-color-green</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-greenDark txt-color-white">.bg-color-greenDark</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-greenLight txt-color-white">.bg-color-greenLight</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-purple txt-color-white">.bg-color-purple</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-magenta txt-color-white">.bg-color-magenta</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-pink txt-color-white">.bg-color-pink</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-pinkDark txt-color-white">.bg-color-pinkDark</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-yellow txt-color-white">.bg-color-yellow</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-orange txt-color-white">.bg-color-orange</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-red txt-color-white">.bg-color-red</a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-redLight txt-color-white">.bg-color-redLight</a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-dark">.btn-default</a> </li> </ul> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-3" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-hand-o-up"></i> </span> <h2> Mix and match colors </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <p class="alert alert-info"> Custom text colors can also be applied <strong>For example:</strong> <code> .txt-color-red </code> </p> <ul class="demo-btns"> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-blueLight"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-blue"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-teal"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-blueDark"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-green"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-greenDark"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-greenLight"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-purple"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-magenta"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-pink"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-pinkDark"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-yellow"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-orange"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default txt-color-red"><i class="fa fa-gear fa-lg"></i></a> </li> </ul> <hr class="simple"> <p> Mix and match color with backgrounds <code> .btn .bg-color-blueLight .txt-color-magenta </code> </p> <ul class="demo-btns"> <li> <a href="javascript:void(0);" class="btn bg-color-blueLight txt-color-magenta"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-blueDark txt-color-teal"><i class="fa fa-gear fa-3x"></i></a> </li> <li> <a href="javascript:void(0);" class="btn bg-color-red txt-color-white"><i class="fa fa-gear fa-4x fa-spin"></i></a> </li> </ul> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-5" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-hand-o-up"></i> </span> <h2>Button with icons </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <p> Default buttons have a single line of text with or without one or two icons aligned left or right. </p> <ul class="demo-btns"> <li> <a href="javascript:void(0);" class="btn btn-primary"><i class="fa fa-gear"></i> Icon Left</a> </li> <li> <a href="javascript:void(0);" class="btn btn-success"><i class="fa fa-gear"></i> Both Sides <i class="fa fa-gear"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-danger">Icon Right <i class="fa fa-gear"></i></a> </li> </ul> <ul class="demo-btns"> <li> <a href="javascript:void(0);" class="btn btn-default"><i class="fa fa-gear"></i> Icon Left</a> </li> <li> <a href="javascript:void(0);" class="btn btn-default"><i class="fa fa-gear"></i> Both Sides <i class="fa fa-gear"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default">Icon Right <i class="fa fa-gear"></i></a> </li> </ul> <hr class="simple"> <ul class="demo-btns"> <li> <div class="btn-group"> <button class="btn bg-color-blueDark txt-color-white"> <i class="fa fa-gear"></i> Drop Down </button> <button class="btn btn-primary dropdown-toggle"> <span class="caret"></span> </button> </div> </li> <li> <div class="btn-group"> <button class="btn bg-color-blueDark txt-color-white"> <i class="fa fa-gear"></i> Drop Down <i class="fa fa-gear"></i> </button> <button class="btn btn-success dropdown-toggle"> <span class="caret"></span> </button> </div> </li> <li> <div class="btn-group"> <button class="btn bg-color-blueDark txt-color-white"> Drop Down <i class="fa fa-gear"></i> </button> <button class="btn btn-danger dropdown-toggle"> <span class="caret"></span> </button> </div> </li> </ul> <ul class="demo-btns"> <li> <div class="btn-group"> <button class="btn btn-default"> <i class="fa fa-gear"></i> Drop Down </button> <button class="btn btn-default dropdown-toggle"> <span class="caret"></span> </button> </div> </li> <li> <div class="btn-group"> <button class="btn btn-default"> <i class="fa fa-gear"></i> Drop Down <i class="fa fa-gear"></i> </button> <button class="btn btn-default dropdown-toggle"> <span class="caret"></span> </button> </div> </li> <li> <div class="btn-group"> <button class="btn btn-default"> Drop Down <i class="fa fa-gear"></i> </button> <button class="btn btn-default dropdown-toggle"> <span class="caret"></span> </button> </div> </li> </ul> <hr class="simple"> <ul class="demo-btns"> <li> <a href="javascript:void(0);" class="btn btn-primary btn-xs"><i class="fa fa-gear"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default btn-sm"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-primary"><i class="fa fa-gear fa-lg"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-primary btn-lg"><i class="fa fa-gear fa-lg"></i></a> </li> </ul> <ul class="demo-btns"> <li> <a href="javascript:void(0);" class="btn btn-primary btn-xs"><i class="fa fa-gear"></i> <i class="fa fa-caret-down"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-default btn-sm"><i class="fa fa-gear fa-lg"></i> <i class="fa fa-caret-down"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-primary"><i class="fa fa-gear fa-lg"></i> <i class="fa fa-caret-down"></i></a> </li> <li> <a href="javascript:void(0);" class="btn btn-primary btn-lg"><i class="fa fa-gear fa-lg"></i> <i class="fa fa-caret-down"></i></a> </li> </ul> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-7" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-hand-o-up"></i> </span> <h2>Label Buttons </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <ul class="demo-btns"> <li> <a href="javascript:void(0);" class="btn btn-labeled btn-success"> <span class="btn-label"><i class="glyphicon glyphicon-ok"></i></span>Success </a> </li> <li> <a href="javascript:void(0);" class="btn btn-labeled btn-danger"> <span class="btn-label"><i class="glyphicon glyphicon-remove"></i></span>Cancel </a> </li> <li> <a href="javascript:void(0);" class="btn btn-labeled btn-warning"> <span class="btn-label"><i class="glyphicon glyphicon-bookmark"></i></span>Bookmark </a> </li> <li> <a href="javascript:void(0);" class="btn btn-labeled btn-primary"> <span class="btn-label"><i class="glyphicon glyphicon-camera"></i></span>Camera </a> </li> <li> <a href="javascript:void(0);" class="btn btn-labeled btn-default"> <span class="btn-label"><i class="glyphicon glyphicon-chevron-left"></i></span>Left </a> </li> <li> <a href="javascript:void(0);" class="btn btn-labeled btn-default"> <span class="btn-label"><i class="glyphicon glyphicon-chevron-right"></i></span> Right </a> </li> <li> <a href="javascript:void(0);" class="btn btn-labeled btn-success"> <span class="btn-label"><i class="glyphicon glyphicon-thumbs-up"></i></span>Thumbs Up </a> </li> <li> <a href="javascript:void(0);" class="btn btn-labeled btn-danger"> <span class="btn-label"><i class="glyphicon glyphicon-thumbs-down"></i></span>Thumbs Down </a> </li> <li> <a href="javascript:void(0);" class="btn btn-labeled btn-info"> <span class="btn-label"><i class="glyphicon glyphicon-refresh"></i></span>Refresh </a> </li> <li> <a href="javascript:void(0);" class="btn btn-labeled btn-danger"> <span class="btn-label"><i class="glyphicon glyphicon-trash"></i></span>Trash </a> </li> <li> <a class="btn btn-success btn-labeled" href="javascript:void(0);"> <span class="btn-label"><i class="glyphicon glyphicon-info-sign"></i></span>Info Web </a> </li> </ul> <pre> &lt;button type="button" class="btn btn-labeled btn-success"> &lt;span class="btn-label"> &lt;i class="glyphicon glyphicon-ok">&lt;/i> &lt;/>Success &lt;/button> </pre> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> <!-- Widget ID (each widget will need unique ID)--> <div class="jarviswidget" id="wid-id-9" data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-custombutton="false" data-widget-sortable="false"> <!-- widget options: usage: <div class="jarviswidget" id="wid-id-0" data-widget-editbutton="false"> data-widget-colorbutton="false" data-widget-editbutton="false" data-widget-togglebutton="false" data-widget-deletebutton="false" data-widget-fullscreenbutton="false" data-widget-custombutton="false" data-widget-collapsed="true" data-widget-sortable="false" --> <header> <span class="widget-icon"> <i class="fa fa-hand-o-up"></i> </span> <h2>Block Buttons </h2> </header> <!-- widget div--> <div> <!-- widget edit box --> <div class="jarviswidget-editbox"> <!-- This area used as dropdown edit box --> </div> <!-- end widget edit box --> <!-- widget content --> <div class="widget-body"> <p> Block buttons <code> .btn .btn-block </code> </p> <div class="well"> <button type="button" class="btn btn-primary btn-lg btn-block"> Block level button </button> <button type="button" class="btn btn-default btn-sm btn-block"> Block level small button </button> <button type="button" class="btn btn-default btn-xs btn-block"> Block level extra small button </button> </div> <hr class="simple"> <p> Block group buttons <code> .btn-group .btn-group-justified </code> </p> <div class="well"> <div class="btn-group btn-group-justified"> <a href="javascript:void(0);" class="btn btn-default">Left</a> <a href="javascript:void(0);" class="btn btn-default">Middle</a> <a href="javascript:void(0);" class="btn btn-default">Right</a> </div> </div> </div> <!-- end widget content --> </div> <!-- end widget div --> </div> <!-- end widget --> </article> <!-- WIDGET END --> </div> <!-- end row --> <!-- row --> <div class="row"> </div> <!-- end row --> </section> <!-- end widget grid --> <script type="text/javascript"> /* DO NOT REMOVE : GLOBAL FUNCTIONS! * * pageSetUp(); WILL CALL THE FOLLOWING FUNCTIONS * * // activate tooltips * $("[rel=tooltip]").tooltip(); * * // activate popovers * $("[rel=popover]").popover(); * * // activate popovers with hover states * $("[rel=popover-hover]").popover({ trigger: "hover" }); * * // activate inline charts * runAllCharts(); * * // setup widgets * setup_widgets_desktop(); * * // run form elements * runAllForms(); * ******************************** * * pageSetUp() is needed whenever you load a page. * It initializes and checks for all basic elements of the page * and makes rendering easier. * */ pageSetUp(); /* * ALL PAGE RELATED SCRIPTS CAN GO BELOW HERE * eg alert("my home function"); * * var pagefunction = function() { * ... * } * loadScript("<?php echo $base ?>js/plugin/_PLUGIN_NAME_.js", pagefunction); * * TO LOAD A SCRIPT: * var pagefunction = function (){ * loadScript(".../plugin.js", run_after_loaded); * } * * OR * * loadScript(".../plugin.js", run_after_loaded); */ // PAGE RELATED SCRIPTS // pagefunction var pagefunction = function() { // clears memory even if nothing is in the function }; // end pagefunction // run pagefunction on load pagefunction(); </script>
bsd-3-clause
char0n/ramda-adjunct
test/rejectP.js
1267
import { assert } from 'chai'; import * as RA from '../src'; describe('rejectP', function () { const rejectWithError = () => Promise.reject(new Error('Expected method to reject.')); it('should reject if provided with no arguments', function () { return RA.rejectP() .then(rejectWithError) .catch((actual) => assert.isUndefined(actual)); }); it('should be able to reject thenable values', function () { const expected = Promise.resolve(1); return RA.rejectP(expected) .then(rejectWithError) .catch((actual) => assert.deepEqual(actual, expected)); }); it('should reject the only argument', function () { const testNumber = RA.rejectP(1) .then(rejectWithError) .catch((actual) => assert.strictEqual(actual, 1)); const testString = RA.rejectP('a') .then(rejectWithError) .catch((actual) => assert.strictEqual(actual, 'a')); const testArray = RA.rejectP([1, 2, 3]) .then(rejectWithError) .catch((actual) => assert.sameOrderedMembers(actual, [1, 2, 3])); const testObj = RA.rejectP({ a: 1 }) .then(rejectWithError) .catch((actual) => assert.deepEqual(actual, { a: 1 })); return Promise.all([testNumber, testString, testArray, testObj]); }); });
bsd-3-clause
ltilve/chromium
third_party/mojo/src/mojo/public/go/application/connection.go
5166
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package application import ( "log" "mojo/public/go/bindings" "mojo/public/go/system" sp "mojo/public/interfaces/application/service_provider" ) type connectionInfo struct { requestorURL string connectionURL string } // RequestorURL returns the URL of application that established the connection. func (c *connectionInfo) RequestorURL() string { return c.requestorURL } // ConnectionURL returns the URL that was used by the source application to // establish a connection to the destination application. func (c *connectionInfo) ConnectionURL() string { return c.connectionURL } // ServiceRequest is an interface request for a specified mojo service. type ServiceRequest interface { // Name returns the name of requested mojo service. Name() string // PassMessagePipe passes ownership of the underlying message pipe // handle to the newly created handle object, invalidating the // underlying handle object in the process. PassMessagePipe() system.MessagePipeHandle } // ServiceFactory provides implementation of a mojo service. type ServiceFactory interface { // Name returns the name of provided mojo service. Name() string // Create binds an implementation of mojo service to the provided // message pipe and runs it. Create(pipe system.MessagePipeHandle) } // Connection represents a connection to another application. An instance of // this struct is passed to Delegate's AcceptConnection() function each time a // connection is made to this application. type Connection struct { connectionInfo // Request for local services. Is valid until ProvideServices is called. servicesRequest *sp.ServiceProviderRequest // Indicates that ProvideServices function was already called. servicesProvided bool localServices *bindings.Stub outgoingConnection *OutgoingConnection isClosed bool } func newConnection(requestorURL string, services *sp.ServiceProviderRequest, exposedServices *sp.ServiceProviderPointer, resolvedURL string) *Connection { info := connectionInfo{ requestorURL, resolvedURL, } var remoteServices *sp.ServiceProviderProxy if exposedServices != nil { remoteServices = sp.NewServiceProviderProxy(*exposedServices, bindings.GetAsyncWaiter()) } return &Connection{ connectionInfo: info, servicesRequest: services, outgoingConnection: &OutgoingConnection{ info, remoteServices, }, } } // ProvideServices starts a service provider on a separate goroutine that // provides given services to the remote application. Returns a pointer to // outgoing connection that can be used to connect to services provided by // remote application. // Panics if called more than once. func (c *Connection) ProvideServices(services ...ServiceFactory) *OutgoingConnection { if c.servicesProvided { panic("ProvideServices can be called only once") } c.servicesProvided = true if c.servicesRequest == nil { return c.outgoingConnection } if len(services) == 0 { c.servicesRequest.PassMessagePipe().Close() return c.outgoingConnection } provider := &serviceProviderImpl{ make(map[string]ServiceFactory), } for _, service := range services { provider.AddService(service) } c.localServices = sp.NewServiceProviderStub(*c.servicesRequest, provider, bindings.GetAsyncWaiter()) go func() { for { if err := c.localServices.ServeRequest(); err != nil { // TODO(rogulenko): don't log in case message pipe was closed log.Println(err) break } } }() return c.outgoingConnection } // Close closes both incoming and outgoing parts of the connection. func (c *Connection) Close() { if c.servicesRequest != nil { c.servicesRequest.Close() } if c.localServices != nil { c.localServices.Close() } if c.outgoingConnection.remoteServices != nil { c.outgoingConnection.remoteServices.Close_proxy() } c.isClosed = true } // OutgoingConnection represents outgoing part of connection to another // application. In order to close it close the |Connection| object that returned // this |OutgoingConnection|. type OutgoingConnection struct { connectionInfo remoteServices *sp.ServiceProviderProxy } // ConnectToService asks remote application to provide a service through the // message pipe endpoint supplied by the caller. func (c *OutgoingConnection) ConnectToService(request ServiceRequest) { pipe := request.PassMessagePipe() if c.remoteServices == nil { pipe.Close() return } c.remoteServices.ConnectToService(request.Name(), pipe) } // serviceProviderImpl is an implementation of mojo ServiceProvider interface. type serviceProviderImpl struct { factories map[string]ServiceFactory } // Mojo ServiceProvider implementation. func (sp *serviceProviderImpl) ConnectToService(name string, messagePipe system.MessagePipeHandle) error { factory, ok := sp.factories[name] if !ok { messagePipe.Close() return nil } factory.Create(messagePipe) return nil } func (sp *serviceProviderImpl) AddService(factory ServiceFactory) { sp.factories[factory.Name()] = factory }
bsd-3-clause
themasterchef/pcl-streamer
src/pclstreamer/TcpWriter.cpp
818
#include "TcpWriter.hpp" TcpWriter::TcpWriter(const Chanin<string>& _in, const int _port) : in(_in), port(_port) {} TcpWriter::~TcpWriter() { socketStream.close(); } void TcpWriter::run() { // Prepare try { boost::asio::io_service io_service; tcp::endpoint endpoint (tcp::v4(), port); tcp::acceptor acceptor (io_service, endpoint); std::cout << "Waiting for connection.." << std::endl; acceptor.accept (*socketStream.rdbuf()); std::cout << "Connected!" << std::endl; } catch (std::exception& e) { std::cerr << e.what() << std::endl; } // Now go while (true) { // cout << "Tcp writer fetching data from input" << endl; string data; in >> data; socketStream << data; } }
bsd-3-clause
MiddlewareICS/MiddlewareICS-2.0
app/controllers/Bootstrap.java
6431
/** * */ package controllers; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import play.Play; import play.jobs.Job; import play.jobs.OnApplicationStart; import edu.pc3.sensoract.vpds.api.SensorActAPI; import edu.pc3.sensoract.vpds.api.request.UserRegisterFormat; import edu.pc3.sensoract.vpds.constants.Const; import edu.pc3.sensoract.vpds.model.UserProfileModel; //mqtt import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; import org.eclipse.paho.client.mqttv3.MqttClient; import org.eclipse.paho.client.mqttv3.MqttConnectOptions; import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttTopic; import com.mongodb.*; import com.mongodb.util.JSON; import javacode.*; //为设备信息插入数据库而引入 import java.util.HashMap; import java.util.Map; import play.mvc.Before; import play.mvc.Controller; import edu.pc3.sensoract.vpds.api.SensorActAPI; import edu.pc3.sensoract.vpds.api.request.TaskletAddFormat; //Esper import com.espertech.esper.client.EPAdministrator; import com.espertech.esper.client.EPRuntime; import com.espertech.esper.client.EPServiceProvider; import com.espertech.esper.client.EPServiceProviderManager; import com.espertech.esper.client.EPStatement; import com.espertech.esper.client.EventBean; import com.espertech.esper.client.UpdateListener; //Rhino import java.io.FileReader; import java.io.LineNumberReader; import org.mozilla.javascript.Context; import org.mozilla.javascript.Function; import org.mozilla.javascript.Scriptable; //quartz import org.quartz.SchedulerException; import javacode.Schedule; //import com.mongodb.*; //import com.mongodb.util.JSON; /** * @author hewei * */ @OnApplicationStart public class Bootstrap extends Job { private String ownerName = null; private String ownerPassword = null; private String ownerEmail = null; private String ownerKey = null; private String uploadKey = null; private String actuationKey = null; public void getOwnerConfiguration() { ownerName = Play.configuration.getProperty(Const.OWNER_NAME); ownerPassword = Play.configuration.getProperty(Const.OWNER_PASSWORD); ownerEmail = Play.configuration.getProperty(Const.OWNER_EMAIL); ownerKey = Play.configuration.getProperty(Const.OWNER_OWNERKEY); uploadKey = Play.configuration.getProperty(Const.OWNER_UPLOADKEY); actuationKey = Play.configuration.getProperty(Const.OWNER_ACTUATIONKEY); } public void updateOwnerConfigurationFile() { // read the conf file and comment the existing lines and add all the new // configuration parameters // String confFileName = Play.applicationPath.getAbsolutePath() + "/conf/" + Const.OWNER_CONFIG_FILENAME; System.out.println("Updating " + confFileName); File confFile = new File(confFileName); // we need to store all the lines List<String> lines = new ArrayList<String>(); // first, read the file and store the changes BufferedReader in; try { in = new BufferedReader(new FileReader(confFile)); String line = in.readLine(); while (line != null) { lines.add(line); line = in.readLine(); } in.close(); // comment all the existing lines PrintWriter out = new PrintWriter(confFile); for (String l : lines) out.println("# " + l); // write the new parameters out.println("# "); out.println("# Updated on " + new Date().toString()); out.println(Const.OWNER_NAME + "=" + ownerName); out.println(Const.OWNER_PASSWORD + "=" + ownerPassword); out.println(Const.OWNER_EMAIL + "=" + ownerEmail); out.println(Const.OWNER_OWNERKEY + "=" + ownerKey); out.println(Const.OWNER_UPLOADKEY + "=" + uploadKey); out.println(Const.OWNER_ACTUATIONKEY + "=" + actuationKey); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public void verifyOwnerKeys() { boolean isChanged = false; if (ownerKey == null || ownerKey.isEmpty() || ownerKey.length() != 32) { System.out.println("Invalid " + Const.OWNER_OWNERKEY + ":" + ownerKey + " found. New key created!"); ownerKey = SensorActAPI.userProfile.generateNewKey(); Play.configuration.setProperty(Const.OWNER_OWNERKEY, ownerKey); isChanged = true; } if (uploadKey == null || uploadKey.isEmpty() || uploadKey.length() != 32) { System.out.println("Invalid " + Const.OWNER_UPLOADKEY + ":" + uploadKey + " found. New key created!"); uploadKey = SensorActAPI.userProfile.generateNewKey(); Play.configuration.setProperty(Const.OWNER_UPLOADKEY, uploadKey); isChanged = true; } if (actuationKey == null || actuationKey.isEmpty() || actuationKey.length() != 32) { System.out.println("Invalid " + Const.OWNER_ACTUATIONKEY + ":" + actuationKey + " found. New key created!"); actuationKey = SensorActAPI.userProfile.generateNewKey(); Play.configuration.setProperty(Const.OWNER_ACTUATIONKEY, actuationKey); isChanged = true; } if (isChanged) { updateOwnerConfigurationFile(); } } public void addOwnerProfile() { // TODO: validated ownerprofile attributes UserRegisterFormat owner = new UserRegisterFormat(); owner.username = ownerName; try { owner.password = SensorActAPI.userProfile .getHashCode(ownerPassword); } catch (Exception e) { e.printStackTrace(); } owner.email = ownerEmail; UserProfileModel.deleteAll(); SensorActAPI.userProfile.addUserProfile(owner, ownerKey); } // Esper public static String Epl = "select avg(temperature) from " + Temperature.class.getName() + ".win:length_batch(3)"; public static CEPEsper myEsper = new CEPEsper(Epl); public void doJob() { getOwnerConfiguration(); verifyOwnerKeys(); addOwnerProfile(); //esper 复杂事件处理 myEsper.state.addListener(myEsper.listener); //quartz 任务调度 包含脚本任务 Schedule mySchedule = new Schedule(); try { mySchedule.doSchedule(); } catch (SchedulerException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
bsd-3-clause
rstit/flask-airbrake
docs/source/conf.py
9440
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # Flask-Airbrake documentation build configuration file, created by # cookiecutter pipproject # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'Flask-Airbrake' copyright = '2016, Piotr Poteralski' author = 'Piotr Poteralski' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.0.1' # The full version, including alpha/beta/rc tags. release = '0.0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = [] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'sphinx_rtd_theme' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. #html_title = 'Flask-Airbrake v0.0.1' # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. #html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'Flask-Airbrakedoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'Flask-Airbrake.tex', 'Flask-Airbrake Documentation', 'Piotr Poteralski', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'Flask-Airbrake', 'Flask-Airbrake Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'Flask-Airbrake', 'Flask-Airbrake Documentation', author, 'Flask-Airbrake', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
bsd-3-clause
bgmerrell/tftpdmem
handlers/datahandlers_test.go
5012
package handlers import ( "bytes" "fmt" "net" "testing" fmgr "github.com/bgmerrell/tftpdmem/filemanager" errs "github.com/bgmerrell/tftpdmem/server/errors" ) func TestGetBlockNum(t *testing.T) { expectedBlockNum := uint16(0xa8ca) blockNum, err := getBlockNum([]byte{0xa8, 0xca, 0x61, 0x62, 0x3}) if err != nil { t.Fatal(err) } if blockNum != expectedBlockNum { t.Errorf("block num: %d, want %d", blockNum, expectedBlockNum) } } func TestGetBlockNumFail(t *testing.T) { // Not enough bytes should fail _, err := getBlockNum([]byte{0xa8}) if err == nil { t.Error("Expected unexpected EOF") } } func TestHandleWriteData(t *testing.T) { fm := fmgr.New() filename := "foo" nextBlockNum := uint16(1) ip := "127.0.0.1" data := []byte{0x00, 0x01, 0x61, 0x62, 0x63} // Expect an ack with block number set to 0 expectedResp := []byte{0x00, 0x04, 0x00, 0x01} lAddr := &net.UDPAddr{IP: net.ParseIP(ip)} conn, err := net.ListenUDP(lAddr.Network(), lAddr) if err != nil { t.Fatal("Error getting new UDP conn:", err) } defer conn.Close() lAddr = conn.LocalAddr().(*net.UDPAddr) rAddr := &net.UDPAddr{ IP: net.ParseIP(ip), Port: lAddr.Port - 1} err = fm.AddConnInfo(lAddr.Port, rAddr.Port, filename, nextBlockNum) if err != nil { t.Fatal(err) } resp, err := HandleWriteData(data, conn, rAddr, fm) if err != nil { t.Error(err) } if bytes.Compare(resp, expectedResp) != 0 { t.Errorf("resp: %#v, want %#v", resp, expectedResp) } } func TestHandleWriteDataBadBlock(t *testing.T) { fm := fmgr.New() filename := "foo" nextBlockNum := uint16(1) ip := "127.0.0.1" data := []byte{0xa1} lAddr := &net.UDPAddr{IP: net.ParseIP(ip)} conn, err := net.ListenUDP(lAddr.Network(), lAddr) if err != nil { t.Fatal("Error getting new UDP conn:", err) } defer conn.Close() lAddr = conn.LocalAddr().(*net.UDPAddr) rAddr := &net.UDPAddr{ IP: net.ParseIP(ip), Port: lAddr.Port - 1} err = fm.AddConnInfo(lAddr.Port, rAddr.Port, filename, nextBlockNum) if err != nil { t.Fatal(err) } _, err = HandleWriteData(data, conn, rAddr, fm) if err == nil { t.Errorf("Expected error getting block for data: %#v", data) } } func TestHandleWriteDataUnexpectedRemoteTid(t *testing.T) { fm := fmgr.New() filename := "foo" nextBlockNum := uint16(1) ip := "127.0.0.1" data := []byte{0x00, 0x01, 0x61, 0x62, 0x63} lAddr := &net.UDPAddr{IP: net.ParseIP(ip)} conn, err := net.ListenUDP(lAddr.Network(), lAddr) if err != nil { t.Fatal("Error getting new UDP conn:", err) } defer conn.Close() lAddr = conn.LocalAddr().(*net.UDPAddr) rAddr := &net.UDPAddr{ IP: net.ParseIP(ip), Port: lAddr.Port - 1} fmt.Println("ltid:", lAddr.Port) fmt.Println("rtid:", rAddr.Port) err = fm.AddConnInfo(lAddr.Port, rAddr.Port, filename, nextBlockNum) if err != nil { t.Fatal(err) } // Set wrong remote TID rAddr = &net.UDPAddr{ IP: net.ParseIP(ip), Port: lAddr.Port - 2} _, err = HandleWriteData(data, conn, rAddr, fm) if err == nil { t.Error("Expected error writing data with incorrect remote TID") } if _, ok := err.(errs.UnexpectedRemoteTidErr); !ok { t.Error("Expected UnexpectedRemoteTidErr writing data with incorrect TID") } } func TestHandleReadData(t *testing.T) { filename := "foo" fileBytes := []byte{0x61, 0x62, 0x63} fm := fmgr.NewWithExistingFiles(map[string][]byte{filename: fileBytes}) nextBlockNum := uint16(0) ip := "127.0.0.1" data := []byte{0x00, 0x00} // Expect a data packet with block number set to 1 and some data expectedResp := []byte{0x00, 0x03, 0x00, 0x01, 0x61, 0x62, 0x63} lAddr := &net.UDPAddr{IP: net.ParseIP(ip)} conn, err := net.ListenUDP(lAddr.Network(), lAddr) if err != nil { t.Fatal("Error getting new UDP conn:", err) } defer conn.Close() lAddr = conn.LocalAddr().(*net.UDPAddr) rAddr := &net.UDPAddr{ IP: net.ParseIP(ip), Port: lAddr.Port - 1} err = fm.AddConnInfo(lAddr.Port, rAddr.Port, filename, nextBlockNum) if err != nil { t.Fatal(err) } resp, err := HandleReadData(data, conn, rAddr, fm) if err != nil { t.Error(err) } if bytes.Compare(resp, expectedResp) != 0 { t.Errorf("resp: %#v, want %#v", resp, expectedResp) } // Send the final ACK data = []byte{0x00, 0x01} resp, err = HandleReadData(data, conn, rAddr, fm) if err != nil { t.Error(err) } if resp != nil { t.Error("Expected nil response for final ACK") } } func TestHandleReadDataNoConnInfo(t *testing.T) { filename := "foo" fileBytes := []byte{0x61, 0x62, 0x63} fm := fmgr.NewWithExistingFiles(map[string][]byte{filename: fileBytes}) ip := "127.0.0.1" data := []byte{0x00, 0x00} lAddr := &net.UDPAddr{IP: net.ParseIP(ip)} conn, err := net.ListenUDP(lAddr.Network(), lAddr) if err != nil { t.Fatal("Error getting new UDP conn:", err) } defer conn.Close() lAddr = conn.LocalAddr().(*net.UDPAddr) rAddr := &net.UDPAddr{ IP: net.ParseIP(ip), Port: lAddr.Port - 1} _, err = HandleReadData(data, conn, rAddr, fm) if err == nil { t.Error("Expected error due to no conn info") } }
bsd-3-clause
jhnsntmthy/tgs_store
app/models/order_observer.rb
608
class OrderObserver < ActiveRecord::Observer observe :order # Generic transition callback *after* the transition is performed def after_transition(record, attribute_name, event_name, from_state, to_state) current_user_session = UserSession.find rescue nil author = current_user_session ? current_user_session.user : record.user record.state_events.create({ :previous_state => from_state, :name => event_name, :user_id => author && author.id }) ActiveRecord::Base.logger.info("Order##{record.id}: #{from_state} => #{to_state}") end end
bsd-3-clause
OpenMediaPortal/omp-express-mongo-api
dao/sync.js
935
/** * @fileoverview Sync (status) schema * * @TODO: Find out why a sync object with no library key is always being inserted into the database * @author ojourmel */ const mongoose = require('mongoose'); const Schema = mongoose.Schema; const config = require('../config'); const syncSchema = new Schema({ status: { syncing: {type: Boolean }, syncTime: {type: Number }, totalFiles: {type: Number } }, library: {type: String }, lastSynced: {type: Date, default: Date.now } }, { id : false }); syncSchema.statics.init = function(libkey, s) { if (config.library.hasOwnProperty(libkey)) { if (!s) { s = new this(); } s.status = { syncing: false, syncTime: 0, totalFiles: 0 }; s.library = libkey; s.lastSynced = null; } return s; }; module.exports = mongoose.model('sync',syncSchema);
bsd-3-clause
leopoldkwok/zendframework2
public/index.php
569
<?php /** * This makes our life easier when dealing with paths. Everything is relative * to the application root now. */ error_reporting(E_ALL|E_STRICT); ini_set('display_errors', 'on'); chdir(dirname(__DIR__)); // Decline static file requests back to the PHP built-in webserver if (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) { return false; } // Setup autoloading require 'init_autoloader.php'; // Run the application! Zend\Mvc\Application::init(require 'config/application.config.php')->run();
bsd-3-clause
gotoAndBliss/True-Jersey
test/factories/order_factory.rb
216
Factory.define(:order) do |record| # associations: record.association(:user, :factory => :user) end Factory.define :order_with_totals, :parent => :order do |f| f.line_items { [Factory(:line_item)] } end
bsd-3-clause
petablox-project/petablox
android/models/src/java/nio/CharBuffer.java
2928
class CharBuffer { public CharBuffer() {} @STAMP(flows = {@Flow(from="array",to="@return")}) public static java.nio.CharBuffer wrap(char[] array) { return new StampCharBuffer(); } @STAMP(flows = {@Flow(from="array",to="@return"), @Flow(from="start",to="@return"), @Flow(from="charCount",to="@return")}) public static java.nio.CharBuffer wrap(char[] array, int start, int charCount) { return new StampCharBuffer(); } @STAMP(flows = {@Flow(from="chseq",to="@return")}) public static java.nio.CharBuffer wrap(java.lang.CharSequence chseq) { return new StampCharBuffer(); } @STAMP(flows = {@Flow(from="cs",to="@return"), @Flow(from="start",to="@return"), @Flow(from="end",to="@return")}) public static java.nio.CharBuffer wrap(java.lang.CharSequence cs, int start, int end) { return new StampCharBuffer(); } @STAMP(flows = {@Flow(from="this",to="@return")}) public final char[] array() { return new char[0]; } @STAMP(flows = {@Flow(from="this",to="@return")}) public final char charAt(int index) { return 'a'; } @STAMP(flows = {@Flow(from="this",to="dst")}) public java.nio.CharBuffer get(char[] dst) { return this; } @STAMP(flows = {@Flow(from="this",to="dst")}) public java.nio.CharBuffer get(char[] dst, int dstOffset, int charCount) { return this; } @STAMP(flows = {@Flow(from="src",to="this")}) public final java.nio.CharBuffer put(char[] src) { return this; } @STAMP(flows = {@Flow(from="src",to="this")}) public java.nio.CharBuffer put(char[] src, int srcOffset, int charCount) { return this; } @STAMP(flows = {@Flow(from="src",to="this")}) public java.nio.CharBuffer put(java.nio.CharBuffer src) { return this; } @STAMP(flows = {@Flow(from="str",to="this")}) public final java.nio.CharBuffer put(java.lang.String str) { return this; } @STAMP(flows = {@Flow(from="str",to="this")}) public java.nio.CharBuffer put(java.lang.String str, int start, int end) { return this; } @STAMP(flows = {@Flow(from="this",to="@return")}) public java.lang.String toString() { return new String(); } @STAMP(flows = {@Flow(from="c",to="this")}) public java.nio.CharBuffer append(char c) { return this; } @STAMP(flows = {@Flow(from="csq",to="this")}) public java.nio.CharBuffer append(java.lang.CharSequence csq) { return this; } @STAMP(flows = {@Flow(from="csq",to="this")}) public java.nio.CharBuffer append(java.lang.CharSequence csq, int start, int end) { return this; } @STAMP(flows = {@Flow(from="this",to="target"), @Flow(from="this",to="@return"), @Flow(from="target",to="@return")}) public int read(java.nio.CharBuffer target) throws java.io.IOException { return 0; } }
bsd-3-clause
jwang-net/sector-scraper
sectorscraper/linkscraper_nyse.py
2150
# coding=utf-8 import os import csv import requests import bs4 import pandas as pd home = os.path.expanduser('~') mainfolder = home + '/scrapecollect/' nysefile = mainfolder + 'healthcare-NYSE_filings_sorted_final.csv' nyselinks = mainfolder + 'healthcare-NYSE_links.csv' headers = ['Ticker', 'Link'] if os.path.isdir(mainfolder): if os.path.isdir(mainfolder): print('Folder exists') open(nyselinks, 'wb') with open(nyselinks, 'wt') as ns: writer = csv.writer(ns, delimiter = ',', quoting = csv.QUOTE_NONE, escapechar = ' ') writer.writerow(headers) ns.close() else: open(nyselinks, 'wb') with open(nyselinks, 'wt') as ns: writer = csv.writer(ns, delimiter = ',', quoting = csv.QUOTE_NONE, escapechar = ' ') writer.writerow(headers) ns.close() else: print('Creating folder') os.makedirs(mainfolder) open(nyselinks, 'wb') with open(nyselinks, 'wt') as ns: writer = csv.writer(ns, delimiter = ',', quoting = csv.QUOTE_NONE, escapechar = ' ') writer.writerow(headers) ns.close() tickers = [] ticklinkpair = [] df = pd.read_csv(nysefile) tickcol = df['Ticker'] for tick in tickcol: tickNW = tick.replace(" ", "") securl = 'https://www.sec.gov/cgi-bin/browse-edgar?CIK=' + tickNW + '&owner=exclude&action=getcompany' secsourcecode = requests.get(securl, stream = True) secsoup = bs4.BeautifulSoup(secsourcecode.text, "lxml") count = 0 if count == 0: for d in secsoup.find_all('a', id="documentsbutton"): if count == 0: first = secsoup.find_all('a', id="documentsbutton")[0] doclink = 'https://www.sec.gov' + first['href'] ticklinkpair.append(tickNW) ticklinkpair.append(doclink) tickers.append(ticklinkpair) count += 1 with open(nyselinks, 'a') as ns: writer = csv.writer(ns, delimiter = ',', quoting = csv.QUOTE_NONE, escapechar = ' ') writer.writerow(ticklinkpair) ticklinkpair = []
bsd-3-clause
endlessm/chromium-browser
tools/swarming_client/tests/test_env.py
2739
# Copyright 2014 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. import logging import os import sys import unittest import six # Directory client/tests/ TESTS_DIR = os.path.dirname(os.path.abspath(six.text_type(__file__))) # Directory client/ CLIENT_DIR = os.path.dirname(TESTS_DIR) sys.path.insert(0, CLIENT_DIR) # Fix import path. sys.path.insert(0, os.path.join( CLIENT_DIR, 'third_party', 'httplib2', 'python%d' % sys.version_info.major)) sys.path.insert(0, os.path.join(CLIENT_DIR, 'third_party', 'pyasn1')) sys.path.insert(0, os.path.join(CLIENT_DIR, 'third_party', 'rsa')) sys.path.insert(0, os.path.join(CLIENT_DIR, 'third_party')) # third_party/ from depot_tools import fix_encoding from utils import fs _UMASK = None class EnvVars(object): """Context manager for environment variables. Passed a dict to the constructor it sets variables named with the key to the value. Exiting the context causes all the variables named with the key to be restored to their value before entering the context. """ def __init__(self, var_map): self.var_map = var_map self._backup = None def __enter__(self): self._backup = os.environ os.environ = os.environ.copy() os.environ.update(self.var_map) def __exit__(self, exc_type, exc_value, traceback): os.environ = self._backup class SymLink(str): """Used as a marker to create a symlink instead of a file.""" def umask(): """Returns current process umask without modifying it.""" global _UMASK if _UMASK is None: _UMASK = os.umask(0o777) os.umask(_UMASK) return _UMASK def make_tree(out, contents): for relpath, content in sorted(contents.items()): filepath = os.path.join(out, relpath.replace('/', os.path.sep)) dirpath = os.path.dirname(filepath) if not fs.isdir(dirpath): fs.makedirs(dirpath, 0o700) if isinstance(content, SymLink): fs.symlink(content, filepath) else: mode = 0o700 if relpath.endswith('.py') else 0o600 flags = os.O_WRONLY | os.O_CREAT if sys.platform == 'win32': # pylint: disable=no-member flags |= os.O_BINARY with os.fdopen(os.open(filepath, flags, mode), 'wb') as f: f.write(content) def setup(): fix_encoding.fix_encoding() # Use an unusual umask. os.umask(0o070) fs.chdir(TESTS_DIR) def main(): """Improvement over unittest.main().""" logging.basicConfig( level=logging.DEBUG if '-v' in sys.argv else logging.ERROR, format='%(levelname)5s %(filename)15s(%(lineno)3d): %(message)s') if '-v' in sys.argv: unittest.TestCase.maxDiff = None setup() unittest.main()
bsd-3-clause
skeeks-cms/cms
src/validators/LoginValidator.php
764
<?php /** * @author Semenov Alexander <semenov@skeeks.com> * @link http://skeeks.com/ * @copyright 2010 SkeekS (СкикС) * @date 26.09.2015 */ namespace skeeks\cms\validators; use yii\validators\Validator; use Exception; /** * Class LoginValidator * @package skeeks\cms\validators */ class LoginValidator extends Validator { public function validateAttribute($model, $attribute) { $string = $model->{$attribute}; if (!preg_match('/^[a-z]{1}[a-z0-9_]+$/', $string)) { $this->addError($model, $attribute, \Yii::t('skeeks/cms', 'Use only letters (lowercase) and numbers. Must begin with a letter. Example {sample}', ['sample' => 'demo1'])); return false; } } }
bsd-3-clause
ujwalrao/quizdb2
models/Change.php
618
<?php /** * Created by PhpStorm. * User: vidhey * Date: 15/4/16 * Time: 9:01 PM */ namespace app\models; use Yii; use yii\base\Model; class Change extends Model { public $current; public $new; public $confirm; public function rules() { return [ [['current', 'new' ,'confirm'], 'required'], ['new', 'compare', 'compareAttribute'=>'confirm'], [['current','new','confirm'], 'string', 'min' => 6], /* [['current', 'new' ,'confirm'], 'password'], // define validation rules here */ ]; } }
bsd-3-clause
ropable/resource_tracking
tracking/migrations/0009_device_deleted.py
415
# Generated by Django 2.2.11 on 2021-04-19 03:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('tracking', '0008_auto_20210119_0826'), ] operations = [ migrations.AddField( model_name='device', name='deleted', field=models.BooleanField(default=False, verbose_name='Deleted?'), ), ]
bsd-3-clause
fimex/sistema
frontend/models/produccion/VProgramacionProduccion.php
3808
<?php namespace frontend\models\produccion; use Yii; /** * This is the model class for table "v_ProgramacionProduccion". * * @property integer $IdProgramacion * @property integer $IdProgramacionSemana * @property integer $IdProgramacionDia * @property integer $IdPedido * @property integer $IdArea * @property integer $IdProgramacionEstatus * @property integer $IdProducto * @property integer $Anio * @property integer $Semana * @property string $Dia * @property integer $IdProceso * @property integer $IdTurno * @property integer $IdCentroTrabajo * @property integer $IdMaquina * @property integer $Programadas * @property integer $Hechas * @property integer $prioridadSemana * @property integer $programadasSemana * @property integer $hechasSemana * @property integer $prioridadDia * @property integer $programadasDia * @property integer $hechasDia * @property integer $IdProduccion * @property integer $IdProduccionDetalle * @property integer $IdEmpleado * @property integer $IdProduccionEstatus * @property string $Inicio * @property string $Fin * @property integer $CiclosMolde * @property integer $PiezasMolde * @property integer $hechasProduccion * @property integer $rechazadasProduccion */ class VProgramacionProduccion extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'v_ProgramacionProduccion'; } /** * @inheritdoc */ public function rules() { return [ [['IdProgramacion', 'IdPedido', 'IdArea', 'IdProgramacionEstatus', 'IdProducto', 'Programadas', 'Hechas'], 'required'], [['IdProgramacion', 'IdProgramacionSemana', 'IdProgramacionDia', 'IdPedido', 'IdArea', 'IdProgramacionEstatus', 'IdProducto', 'Anio', 'Semana', 'IdProceso', 'IdTurno', 'IdCentroTrabajo', 'IdMaquina', 'Programadas', 'Hechas', 'prioridadSemana', 'programadasSemana', 'hechasSemana', 'prioridadDia', 'programadasDia', 'hechasDia', 'IdProduccion', 'IdProduccionDetalle', 'IdEmpleado', 'IdProduccionEstatus', 'CiclosMolde', 'PiezasMolde', 'hechasProduccion', 'rechazadasProduccion'], 'integer'], [['Dia', 'Inicio', 'Fin'], 'safe'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'IdProgramacion' => 'Id Programacion', 'IdProgramacionSemana' => 'Id Programacion Semana', 'IdProgramacionDia' => 'Id Programacion Dia', 'IdPedido' => 'Id Pedido', 'IdArea' => 'Id Area', 'IdProgramacionEstatus' => 'Id Programacion Estatus', 'IdProducto' => 'Id Producto', 'Anio' => 'Anio', 'Semana' => 'Semana', 'Dia' => 'Dia', 'IdProceso' => 'Id Proceso', 'IdTurno' => 'Id Turno', 'IdCentroTrabajo' => 'Id Centro Trabajo', 'IdMaquina' => 'Id Maquina', 'Programadas' => 'Programadas', 'Hechas' => 'Hechas', 'prioridadSemana' => 'Prioridad Semana', 'programadasSemana' => 'Programadas Semana', 'hechasSemana' => 'Hechas Semana', 'prioridadDia' => 'Prioridad Dia', 'programadasDia' => 'Programadas Dia', 'hechasDia' => 'Hechas Dia', 'IdProduccion' => 'Id Produccion', 'IdProduccionDetalle' => 'Id Produccion Detalle', 'IdEmpleado' => 'Id Empleado', 'IdProduccionEstatus' => 'Id Produccion Estatus', 'Inicio' => 'Inicio', 'Fin' => 'Fin', 'CiclosMolde' => 'Ciclos Molde', 'PiezasMolde' => 'Piezas Molde', 'hechasProduccion' => 'Hechas Produccion', 'rechazadasProduccion' => 'Rechazadas Produccion', ]; } }
bsd-3-clause
maurov/xraysloth
examples/rowland_tests.py
3861
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Tests/Examples for sloth.inst.rowland (generic tests) See also more specific tests (older first) ------------------------------------------ - rowland_sagittal_tests (data evaluation sagittal prototype) - rowland_detector_tests (figures showing detector movements) - rowland_pantograph_tests (pantograph control movements) """ __author__ = "Mauro Rovezzi" __email__ = "mauro.rovezzi@gmail.com" __license__ = "BSD license <http://opensource.org/licenses/BSD-3-Clause>" import os, sys import math import numpy as np import matplotlib.pyplot as plt ### SLOTH ### try: from sloth import __version__ as sloth_version from sloth.inst.rowland import cs_h, acenx, RcHoriz, RcVert from sloth.utils.genericutils import colorstr from sloth.utils.bragg import d_cubic, d_hexagonal except: raise ImportError('sloth is not installed (required version >= 0.2.0)') RS_MIN = 157.915 RS_MAX = 1012.252 SI_ALAT = 5.431065 # Ang at 25C GE_ALAT = 5.6579060 # Ang at 25C SIO2_A = 4.913 # beta-quartz, hexagonal SIO2_C = 5.405 dSi111 = d_cubic(SI_ALAT, (1,1,1)) dGe111 = d_cubic(GE_ALAT, (1,1,1)) dSi220 = d_cubic(SI_ALAT, (2,2,0)) dGe220 = d_cubic(GE_ALAT, (2,2,0)) dQz100 = d_hexagonal(SIO2_A, SIO2_C, (1,0,0)) ### TESTS ### def testSagOff(Rm, theta0, aXoff, aL=100.): rc = RcHoriz(Rm, theta0, aL=aL, showInfos=True) rc.get_sag_off(aXoff) def testChiOpt(): #from specfiledatawriter import SpecfileDataWrite #fname = 'testChiOpt.spec' #sfout = SpecfileDataWriter(fname) ths = np.linspace(34., 86., 27.) #theta scan rms = [250., 500.] als = [0., 25., 50., 100.] agxs = [0., 5.] dres = {'rm' : [], 'th' : [], 'al' : [], 'chi' : [], 'axoff' : [], 'sagoff' : [], 'chi0' : [], 'axoff0' : [], 'sagoff0' : []} for rm in rms: for al in als: rc = RcHoriz(rm, aL=al, showInfos=False) axoff = acenx(5, asx=25., agx=5.) for th in ths: rc.set_theta0(th) #[math.degrees(rchi), aXoff, SagOff, math.degrees(rchi0), aXoff0, SagOff0] lso = rc.get_sag_off(axoff, retAll=True) dres['rm'].append(rm) dres['th'].append(th) dres['al'].append(al) dres['chi'].append(lso[0]) dres['axoff'].append(lso[1]) dres['sagoff'].append(lso[2]) dres['chi0'].append(lso[3]) dres['axoff0'].append(lso[4]) dres['sagoff0'].append(lso[5]) return dres def testAzOff(eDelta, Rm=500., theta0=35, d=dSi111): t = RcHoriz(Rm=Rm, theta0=theta0, d=d) return t.get_az_off(eDelta) def testSagFocus(d=dSi111): """not finished yet!""" #first get the minimum position t0 = RcHoriz(Rm=250., theta0=35., d=d, aW=25., aWext=31.0266, aL=45.) c0 = t0.get_chi2(5.) d0 = t0.get_ana_dist(c0, 5.) s0 = t0.get_axoff(c0) sag0 = t0.get_sag_off(s0, retAll=True) t0.aXoffMin = sag0[1] t0.SagOffMin = sag0[2] #move theta and get new pivot point position t0.Rm = 510. t0.set_theta0(85.) s1 = t0.get_axoff_line(t0.aXoffMin, t0.SagOffMin, degRot=35.) return t0 def testMiscutOff1Ana(Rm, theta, alpha, d=dSi111): """test miscut offsets NOT WORKING YET!!!""" tv = RcVert(Rm=Rm, theta0=theta, alpha=alpha, d=d) tv_mo = tv.get_miscut_off() th = RcHoriz(Rm=Rm, theta0=theta, alpha=alpha, d=d) th_mo = th.get_miscut_off() print('RcVert: {0}'.format(tv_mo)) print('RcHor: {0}'.format(th_mo)) if __name__ == "__main__": #plt.close('all') #testSagOff(250., 35., 150., aL=12.) #dres = testChiOpt() #testAzOff(0.5) #testMiscutOff1Ana(500., 65., 36.) #t0 = testSagFocus() pass
bsd-3-clause
IG-Group/ig-webapi-dotnet-sample
IGWebApiClient/Model/dto/endpoint/funds/manage/edit/EditCardRequest.cs
360
using System.Collections.Generic; using dto.endpoint.auth.session; namespace dto.endpoint.funds.manage.edit { public class EditCardRequest{ ///<Summary> ///Start date ///todo should not be required to be notnull ///</Summary> public string startDate { get; set; } ///<Summary> ///Expiry date ///</Summary> public string expiryDate { get; set; } } }
bsd-3-clause
paperculture/alchemy_cms
config/routes.rb
4104
Alchemy::Engine.routes.draw do root :to => 'pages#show' get '/sitemap.xml' => 'pages#sitemap', format: 'xml' get '/admin' => redirect('admin/dashboard') get '/admin/dashboard' => 'admin/dashboard#index', :as => :admin_dashboard get '/admin/dashboard/info' => 'admin/dashboard#info', :as => :dashboard_info get '/admin/help' => 'admin/dashboard#help', :as => :help get '/admin/dashboard/update_check' => 'admin/dashboard#update_check', :as => :update_check get '/attachment/:id/download(/:name)' => 'attachments#download', :as => :download_attachment get '/attachment/:id/show' => 'attachments#show', :as => :show_attachment # Picture urls get "/pictures/:id/show(/:size)(/:crop)(/:crop_from/:crop_size)(/:quality)/:name.:format" => 'pictures#show', :as => :show_picture get '/pictures/:id/zoom/:name.:format' => 'pictures#zoom', :as => :zoom_picture get "/pictures/:id/thumbnails/:size(/:crop)(/:crop_from/:crop_size)/:name.:format" => 'pictures#thumbnail', :as => :thumbnail, :defaults => {:format => 'png', :name => "thumbnail"} get '/admin/leave' => 'admin/base#leave', :as => :leave_admin resources :messages, :only => [:index, :new, :create] resources :elements, :only => :show namespace :api, defaults: {format: 'json'} do resources :contents, only: [:index, :show] resources :elements, only: [:index, :show] do get '/contents' => 'contents#index', as: 'contents' get '/contents/:name' => 'contents#show', as: 'content' end resources :pages, only: [:index] do get 'elements' => 'elements#index', as: 'elements' get 'elements/:named' => 'elements#index', as: 'named_elements' end get '/pages/*urlname(.:format)' => 'pages#show', as: 'page' get '/admin/pages/:id(.:format)' => 'pages#show', as: 'preview_page' end namespace :admin do resources :contents do collection do post :order end end resources :pages do resources :elements collection do post :order post :flush post :copy_language_tree get :switch_language get :create_language get :link get :sort end member do post :unlock post :publish post :fold post :visit get :configure get :preview get :info end end resources :elements do resources :contents collection do get :list post :order end member do post :fold delete :trash end end resources :layoutpages, :only => [:index, :edit] resources :pictures do collection do post :flush, :update_multiple delete :delete_multiple get :edit_multiple end member do get :info delete :remove end end resources :attachments do member do get :download end end resources :essence_pictures, :except => [:show, :new, :create] do collection do put :assign end member do get :crop end end resources :essence_files, :only => [:edit, :update] do collection do put :assign end end resources :legacy_page_urls resources :languages resource :clipboard, :only => :index, :controller => 'clipboard' do collection do get :index delete :clear delete :remove post :insert end end resource :trash, :only => :index, :controller => 'trash' do collection do get :index delete :clear end end resources :tags do collection do get :autocomplete end end resources :sites end get '/:lang' => 'pages#show', :constraints => {:lang => /[a-z]{2}(-[a-z]{2})?/}, :as => :show_language_root # The page show action has to be last route get '(/:lang)/*urlname(.:format)' => 'pages#show', :constraints => {:lang => /[a-z]{2}(-[a-z]{2})?/}, :as => :show_page end
bsd-3-clause
exponent/exponent
packages/expo-notifications/android/src/main/java/expo/modules/notifications/serverregistration/ServerRegistrationModule.java
1145
package expo.modules.notifications.serverregistration; import android.content.Context; import org.unimodules.core.ExportedModule; import org.unimodules.core.Promise; import org.unimodules.core.interfaces.ExpoMethod; public class ServerRegistrationModule extends ExportedModule { private static final String EXPORTED_NAME = "NotificationsServerRegistrationModule"; protected InstallationId mInstallationId; private RegistrationInfo mRegistrationInfo; public ServerRegistrationModule(Context context) { super(context); mInstallationId = new InstallationId(context); mRegistrationInfo = new RegistrationInfo(context); } @Override public String getName() { return EXPORTED_NAME; } @ExpoMethod public void getInstallationIdAsync(Promise promise) { promise.resolve(mInstallationId.getOrCreateUUID()); } @ExpoMethod public void getRegistrationInfoAsync(Promise promise) { promise.resolve(mRegistrationInfo.get()); } @ExpoMethod public void setRegistrationInfoAsync(String registrationInfo, Promise promise) { mRegistrationInfo.set(registrationInfo); promise.resolve(null); } }
bsd-3-clause
mdaif/olympia
apps/editors/models.py
26061
import datetime from django.conf import settings from django.core.cache import cache from django.db import models from django.db.models import Sum from django.template import Context, loader from django.utils.datastructures import SortedDict import commonware.log from tower import ugettext_lazy as _lazy import amo import amo.models from access.models import Group from amo.helpers import absolutify from amo.urlresolvers import reverse from amo.utils import cache_ns_key, send_mail from addons.models import Addon, Persona from devhub.models import ActivityLog from editors.sql_model import RawSQLModel from translations.fields import save_signal, TranslatedField from users.models import UserForeignKey, UserProfile from versions.models import version_uploaded user_log = commonware.log.getLogger('z.users') class CannedResponse(amo.models.ModelBase): name = TranslatedField() response = TranslatedField(short=False) sort_group = models.CharField(max_length=255) type = models.PositiveIntegerField( choices=amo.CANNED_RESPONSE_CHOICES.items(), db_index=True, default=0) class Meta: db_table = 'cannedresponses' def __unicode__(self): return unicode(self.name) models.signals.pre_save.connect(save_signal, sender=CannedResponse, dispatch_uid='cannedresponses_translations') class AddonCannedResponseManager(amo.models.ManagerBase): def get_query_set(self): qs = super(AddonCannedResponseManager, self).get_query_set() return qs.filter(type=amo.CANNED_RESPONSE_ADDON) class AddonCannedResponse(CannedResponse): objects = AddonCannedResponseManager() class Meta: proxy = True class EventLog(models.Model): type = models.CharField(max_length=60) action = models.CharField(max_length=120) field = models.CharField(max_length=60, blank=True) user = models.ForeignKey(UserProfile) changed_id = models.IntegerField() added = models.CharField(max_length=765, blank=True) removed = models.CharField(max_length=765, blank=True) notes = models.TextField(blank=True) created = models.DateTimeField(auto_now_add=True) class Meta: db_table = u'eventlog' @staticmethod def new_editors(): action = amo.LOG.GROUP_USER_ADDED group = Group.objects.get(name='Add-on Reviewers') items = (ActivityLog.objects.for_group(group) .filter(action=action.id) .order_by('-created')[:5]) return [dict(user=i.arguments[1], created=i.created) for i in items] class ViewQueue(RawSQLModel): id = models.IntegerField() addon_name = models.CharField(max_length=255) addon_slug = models.CharField(max_length=30) addon_status = models.IntegerField() addon_type_id = models.IntegerField() admin_review = models.BooleanField() is_site_specific = models.BooleanField() external_software = models.BooleanField() binary = models.BooleanField() binary_components = models.BooleanField() premium_type = models.IntegerField() is_restartless = models.BooleanField() is_jetpack = models.BooleanField() source = models.CharField(max_length=100) is_webextension = models.BooleanField() latest_version = models.CharField(max_length=255) _file_platform_ids = models.CharField(max_length=255) has_info_request = models.BooleanField() has_editor_comment = models.BooleanField() _application_ids = models.CharField(max_length=255) waiting_time_days = models.IntegerField() waiting_time_hours = models.IntegerField() waiting_time_min = models.IntegerField() listed = True # ViewQueue for listed or unlisted addons. def base_query(self): return { 'select': SortedDict([ ('id', 'addons.id'), ('addon_name', 'tr.localized_string'), ('addon_status', 'addons.status'), ('addon_type_id', 'addons.addontype_id'), ('addon_slug', 'addons.slug'), ('admin_review', 'addons.adminreview'), ('is_site_specific', 'addons.sitespecific'), ('external_software', 'addons.externalsoftware'), ('binary', 'files.binary'), ('binary_components', 'files.binary_components'), ('latest_version', 'versions.version'), ('has_editor_comment', 'versions.has_editor_comment'), ('has_info_request', 'versions.has_info_request'), ('_file_platform_ids', """GROUP_CONCAT(DISTINCT files.platform_id)"""), ('is_jetpack', 'MAX(files.jetpack_version IS NOT NULL)'), ('is_restartless', 'MAX(files.no_restart)'), ('source', 'versions.source'), ('is_webextension', 'MAX(files.is_webextension)'), ('_application_ids', """GROUP_CONCAT(DISTINCT apps.application_id)"""), ('waiting_time_days', 'TIMESTAMPDIFF(DAY, MAX(versions.nomination), NOW())'), ('waiting_time_hours', 'TIMESTAMPDIFF(HOUR, MAX(versions.nomination), NOW())'), ('waiting_time_min', 'TIMESTAMPDIFF(MINUTE, MAX(versions.nomination), NOW())'), ]), 'from': [ 'addons', 'JOIN versions ON (versions.id = addons.latest_version)', 'JOIN files ON (files.version_id = versions.id)', """LEFT JOIN applications_versions as apps ON versions.id = apps.version_id""", # Translations """JOIN translations AS tr ON ( tr.id = addons.name AND tr.locale = addons.defaultlocale)""" ], 'where': [ 'NOT addons.inactive', # disabled_by_user # Are we showing listed or unlisted addons? '{0} addons.is_listed'.format('' if self.listed else 'NOT'), ], 'group_by': 'id'} @property def file_platform_ids(self): return self._explode_concat(self._file_platform_ids) @property def application_ids(self): return self._explode_concat(self._application_ids) @property def is_traditional_restartless(self): return self.is_restartless and not self.is_jetpack @property def sources_provided(self): return bool(self.source) @property def flags(self): props = ( ('admin_review', 'admin-review', _lazy('Admin Review')), ('is_jetpack', 'jetpack', _lazy('Jetpack Add-on')), ('is_traditional_restartless', 'restartless', _lazy('Restartless Add-on')), ('has_info_request', 'info', _lazy('More Information Requested')), ('has_editor_comment', 'editor', _lazy('Contains Editor Comment')), ('sources_provided', 'sources-provided', _lazy('Sources provided')), ('is_webextension', 'webextension', _lazy('WebExtension')), ) return [(cls, title) for (prop, cls, title) in props if getattr(self, prop)] class ViewFullReviewQueue(ViewQueue): def base_query(self): q = super(ViewFullReviewQueue, self).base_query() q['where'].extend(['files.status <> %s' % amo.STATUS_BETA, 'addons.status IN (%s, %s)' % ( amo.STATUS_NOMINATED, amo.STATUS_LITE_AND_NOMINATED)]) return q class ViewPendingQueue(ViewQueue): def base_query(self): q = super(ViewPendingQueue, self).base_query() q['where'].extend(['files.status = %s' % amo.STATUS_UNREVIEWED, 'addons.status = %s' % amo.STATUS_PUBLIC]) return q class ViewPreliminaryQueue(ViewQueue): def base_query(self): q = super(ViewPreliminaryQueue, self).base_query() q['where'].extend(['files.status = %s' % amo.STATUS_UNREVIEWED, 'addons.status IN (%s, %s)' % ( amo.STATUS_LITE, amo.STATUS_UNREVIEWED)]) return q class ViewFastTrackQueue(ViewQueue): def base_query(self): q = super(ViewFastTrackQueue, self).base_query() # Fast track includes jetpack-based addons that do not require chrome. q['where'].extend(['files.no_restart = 1', 'files.jetpack_version IS NOT NULL', 'files.requires_chrome = 0', 'files.status = %s' % amo.STATUS_UNREVIEWED, 'addons.status IN (%s, %s, %s, %s)' % ( amo.STATUS_LITE, amo.STATUS_UNREVIEWED, amo.STATUS_NOMINATED, amo.STATUS_LITE_AND_NOMINATED)]) return q class ViewUnlistedFullReviewQueue(ViewFullReviewQueue): listed = False class ViewUnlistedPendingQueue(ViewPendingQueue): listed = False class ViewUnlistedPreliminaryQueue(ViewPreliminaryQueue): listed = False class PerformanceGraph(ViewQueue): id = models.IntegerField() yearmonth = models.CharField(max_length=7) approval_created = models.DateTimeField() user_id = models.IntegerField() total = models.IntegerField() def base_query(self): request_ver = amo.LOG.REQUEST_VERSION.id review_ids = [str(r) for r in amo.LOG_REVIEW_QUEUE if r != request_ver] return { 'select': SortedDict([ ('yearmonth', "DATE_FORMAT(`log_activity`.`created`, '%%Y-%%m')"), ('approval_created', '`log_activity`.`created`'), ('user_id', '`log_activity`.`user_id`'), ('total', 'COUNT(*)') ]), 'from': [ 'log_activity', ], 'where': ['log_activity.action in (%s)' % ','.join(review_ids)], 'group_by': 'yearmonth, user_id' } class EditorSubscription(amo.models.ModelBase): user = models.ForeignKey(UserProfile) addon = models.ForeignKey(Addon) class Meta: db_table = 'editor_subscriptions' def send_notification(self, version): user_log.info('Sending addon update notice to %s for %s' % (self.user.email, self.addon.pk)) context = Context({ 'name': self.addon.name, 'url': absolutify(reverse('addons.detail', args=[self.addon.pk], add_prefix=False)), 'number': version.version, 'review': absolutify(reverse('editors.review', args=[self.addon.pk], add_prefix=False)), 'SITE_URL': settings.SITE_URL, }) # Not being localised because we don't know the editors locale. subject = 'Mozilla Add-ons: %s Updated' % self.addon.name template = loader.get_template('editors/emails/notify_update.ltxt') send_mail(subject, template.render(Context(context)), recipient_list=[self.user.email], from_email=settings.EDITORS_EMAIL, use_blacklist=False) def send_notifications(signal=None, sender=None, **kw): if sender.is_beta: return subscribers = sender.addon.editorsubscription_set.all() if not subscribers: return for subscriber in subscribers: subscriber.send_notification(sender) subscriber.delete() version_uploaded.connect(send_notifications, dispatch_uid='send_notifications') class ReviewerScore(amo.models.ModelBase): user = models.ForeignKey(UserProfile, related_name='_reviewer_scores') addon = models.ForeignKey(Addon, blank=True, null=True, related_name='+') score = models.SmallIntegerField() # For automated point rewards. note_key = models.SmallIntegerField(choices=amo.REVIEWED_CHOICES.items(), default=0) # For manual point rewards with a note. note = models.CharField(max_length=255) class Meta: db_table = 'reviewer_scores' ordering = ('-created',) @classmethod def get_key(cls, key=None, invalidate=False): namespace = 'riscore' if not key: # Assuming we're invalidating the namespace. cache_ns_key(namespace, invalidate) return else: # Using cache_ns_key so each cache val is invalidated together. ns_key = cache_ns_key(namespace, invalidate) return '%s:%s' % (ns_key, key) @classmethod def get_event(cls, addon, status, **kwargs): """Return the review event type constant. This is determined by the addon.type and the queue the addon is currently in (which is determined from the status). Note: We're not using addon.status because this is called after the status has been updated by the reviewer action. """ queue = '' if status in [amo.STATUS_UNREVIEWED, amo.STATUS_LITE]: queue = 'PRELIM' elif status in [amo.STATUS_NOMINATED, amo.STATUS_LITE_AND_NOMINATED]: queue = 'FULL' elif status == amo.STATUS_PUBLIC: queue = 'UPDATE' if (addon.type in [amo.ADDON_EXTENSION, amo.ADDON_PLUGIN, amo.ADDON_API] and queue): return getattr(amo, 'REVIEWED_ADDON_%s' % queue) elif addon.type == amo.ADDON_DICT and queue: return getattr(amo, 'REVIEWED_DICT_%s' % queue) elif addon.type in [amo.ADDON_LPAPP, amo.ADDON_LPADDON] and queue: return getattr(amo, 'REVIEWED_LP_%s' % queue) elif addon.type == amo.ADDON_PERSONA: return amo.REVIEWED_PERSONA elif addon.type == amo.ADDON_SEARCH and queue: return getattr(amo, 'REVIEWED_SEARCH_%s' % queue) elif addon.type == amo.ADDON_THEME and queue: return getattr(amo, 'REVIEWED_THEME_%s' % queue) else: return None @classmethod def award_points(cls, user, addon, status, **kwargs): """Awards points to user based on an event and the queue. `event` is one of the `REVIEWED_` keys in constants. `status` is one of the `STATUS_` keys in constants. """ event = cls.get_event(addon, status, **kwargs) score = amo.REVIEWED_SCORES.get(event) try: # Add bonus to reviews greater than our limit to encourage fixing # old reviews. vq = ViewQueue.objects.get( addon_slug=addon.slug, ) if vq.waiting_time_days > amo.REVIEWED_OVERDUE_LIMIT: days_over = vq.waiting_time_days - amo.REVIEWED_OVERDUE_LIMIT bonus = days_over * amo.REVIEWED_OVERDUE_BONUS score = score + bonus except ViewQueue.DoesNotExist: # If the object does not exist then we simply do not add a bonus pass if score: cls.objects.create(user=user, addon=addon, score=score, note_key=event) cls.get_key(invalidate=True) user_log.info( (u'Awarding %s points to user %s for "%s" for addon %s' % ( score, user, amo.REVIEWED_CHOICES[event], addon.id)) .encode('utf-8')) return score @classmethod def award_moderation_points(cls, user, addon, review_id, undo=False): """Awards points to user based on moderated review.""" event = (amo.REVIEWED_ADDON_REVIEW if not undo else amo.REVIEWED_ADDON_REVIEW_POORLY) score = amo.REVIEWED_SCORES.get(event) cls.objects.create(user=user, addon=addon, score=score, note_key=event) cls.get_key(invalidate=True) user_log.info( u'Awarding %s points to user %s for "%s" for review %s' % ( score, user, amo.REVIEWED_CHOICES[event], review_id)) @classmethod def get_total(cls, user): """Returns total points by user.""" key = cls.get_key('get_total:%s' % user.id) val = cache.get(key) if val is not None: return val val = (ReviewerScore.objects.no_cache().filter(user=user) .aggregate(total=Sum('score')) .values())[0] if val is None: val = 0 cache.set(key, val, None) return val @classmethod def get_recent(cls, user, limit=5, addon_type=None): """Returns most recent ReviewerScore records.""" key = cls.get_key('get_recent:%s' % user.id) val = cache.get(key) if val is not None: return val val = ReviewerScore.objects.no_cache().filter(user=user) if addon_type is not None: val.filter(addon__type=addon_type) val = list(val[:limit]) cache.set(key, val, None) return val @classmethod def get_breakdown(cls, user): """Returns points broken down by addon type.""" key = cls.get_key('get_breakdown:%s' % user.id) val = cache.get(key) if val is not None: return val sql = """ SELECT `reviewer_scores`.*, SUM(`reviewer_scores`.`score`) AS `total`, `addons`.`addontype_id` AS `atype` FROM `reviewer_scores` LEFT JOIN `addons` ON (`reviewer_scores`.`addon_id`=`addons`.`id`) WHERE `reviewer_scores`.`user_id` = %s GROUP BY `addons`.`addontype_id` ORDER BY `total` DESC """ with amo.models.skip_cache(): val = list(ReviewerScore.objects.raw(sql, [user.id])) cache.set(key, val, None) return val @classmethod def get_breakdown_since(cls, user, since): """ Returns points broken down by addon type since the given datetime. """ key = cls.get_key('get_breakdown:%s:%s' % (user.id, since.isoformat())) val = cache.get(key) if val is not None: return val sql = """ SELECT `reviewer_scores`.*, SUM(`reviewer_scores`.`score`) AS `total`, `addons`.`addontype_id` AS `atype` FROM `reviewer_scores` LEFT JOIN `addons` ON (`reviewer_scores`.`addon_id`=`addons`.`id`) WHERE `reviewer_scores`.`user_id` = %s AND `reviewer_scores`.`created` >= %s GROUP BY `addons`.`addontype_id` ORDER BY `total` DESC """ with amo.models.skip_cache(): val = list(ReviewerScore.objects.raw(sql, [user.id, since])) cache.set(key, val, 3600) return val @classmethod def _leaderboard_query(cls, since=None, types=None, addon_type=None): """ Returns common SQL to leaderboard calls. """ query = (cls.objects .values_list('user__id', 'user__display_name') .annotate(total=Sum('score')) .exclude(user__groups__name__in=('No Reviewer Incentives', 'Staff', 'Admins')) .order_by('-total')) if since is not None: query = query.filter(created__gte=since) if types is not None: query = query.filter(note_key__in=types) if addon_type is not None: query = query.filter(addon__type=addon_type) return query @classmethod def get_leaderboards(cls, user, days=7, types=None, addon_type=None): """Returns leaderboards with ranking for the past given days. This will return a dict of 3 items:: {'leader_top': [...], 'leader_near: [...], 'user_rank': (int)} If the user is not in the leaderboard, or if the user is in the top 5, 'leader_near' will be an empty list and 'leader_top' will contain 5 elements instead of the normal 3. """ key = cls.get_key('get_leaderboards:%s' % user.id) val = cache.get(key) if val is not None: return val week_ago = datetime.date.today() - datetime.timedelta(days=days) leader_top = [] leader_near = [] query = cls._leaderboard_query(since=week_ago, types=types, addon_type=addon_type) scores = [] user_rank = 0 in_leaderboard = False for rank, row in enumerate(query, 1): user_id, name, total = row scores.append({ 'user_id': user_id, 'name': name, 'rank': rank, 'total': int(total), }) if user_id == user.id: user_rank = rank in_leaderboard = True if not in_leaderboard: leader_top = scores[:5] else: if user_rank <= 5: # User is in top 5, show top 5. leader_top = scores[:5] else: leader_top = scores[:3] leader_near = [scores[user_rank - 2], scores[user_rank - 1]] try: leader_near.append(scores[user_rank]) except IndexError: pass # User is last on the leaderboard. val = { 'leader_top': leader_top, 'leader_near': leader_near, 'user_rank': user_rank, } cache.set(key, val, None) return val @classmethod def all_users_by_score(cls): """ Returns reviewers ordered by highest total points first. """ query = cls._leaderboard_query() scores = [] for row in query: user_id, name, total = row user_level = len(amo.REVIEWED_LEVELS) - 1 for i, level in enumerate(amo.REVIEWED_LEVELS): if total < level['points']: user_level = i - 1 break # Only show level if it changes. if user_level < 0: level = '' else: level = amo.REVIEWED_LEVELS[user_level]['name'] scores.append({ 'user_id': user_id, 'name': name, 'total': int(total), 'level': level, }) prev = None for score in reversed(scores): if score['level'] == prev: score['level'] = '' else: prev = score['level'] return scores class EscalationQueue(amo.models.ModelBase): addon = models.ForeignKey(Addon) class Meta: db_table = 'escalation_queue' class RereviewQueue(amo.models.ModelBase): addon = models.ForeignKey(Addon) class Meta: db_table = 'rereview_queue' @classmethod def flag(cls, addon, event, message=None): cls.objects.get_or_create(addon=addon) if message: amo.log(event, addon, addon.current_version, details={'comments': message}) else: amo.log(event, addon, addon.current_version) class RereviewQueueThemeManager(amo.models.ManagerBase): def __init__(self, include_deleted=False): # DO NOT change the default value of include_deleted unless you've read # through the comment just above the Addon managers # declaration/instanciation and understand the consequences. amo.models.ManagerBase.__init__(self) self.include_deleted = include_deleted def get_query_set(self): qs = super(RereviewQueueThemeManager, self).get_query_set() if self.include_deleted: return qs else: return qs.exclude(theme__addon__status=amo.STATUS_DELETED) class RereviewQueueTheme(amo.models.ModelBase): theme = models.ForeignKey(Persona) header = models.CharField(max_length=72, blank=True, default='') footer = models.CharField(max_length=72, blank=True, default='') # Holds whether this reuploaded theme is a duplicate. dupe_persona = models.ForeignKey(Persona, null=True, related_name='dupepersona') # The order of those managers is very important: please read the lengthy # comment above the Addon managers declaration/instanciation. unfiltered = RereviewQueueThemeManager(include_deleted=True) objects = RereviewQueueThemeManager() class Meta: db_table = 'rereview_queue_theme' def __str__(self): return str(self.id) @property def header_path(self): """Return the path to the header image.""" return self.theme._image_path(self.header or self.theme.header) @property def footer_path(self): """Return the path to the optional footer image.""" footer = self.footer or self.theme.footer return footer and self.theme._image_path(footer) or '' @property def header_url(self): """Return the url of the header imager.""" return self.theme._image_url(self.header or self.theme.header) @property def footer_url(self): """Return the url of the optional footer image.""" footer = self.footer or self.theme.footer return footer and self.theme._image_url(footer) or '' class ThemeLock(amo.models.ModelBase): theme = models.OneToOneField('addons.Persona') reviewer = UserForeignKey() expiry = models.DateTimeField() class Meta: db_table = 'theme_locks'
bsd-3-clause
matsumoto-r/synciga
src/third_party/webrtc/modules/audio_coding/main/test/iSACTest.cc
16812
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_coding/main/test/iSACTest.h" #include <cctype> #include <stdio.h> #include <string.h> #if _WIN32 #include <windows.h> #elif WEBRTC_LINUX #include <ctime> #else #include <sys/time.h> #include <time.h> #endif #include "webrtc/modules/audio_coding/main/source/acm_common_defs.h" #include "webrtc/modules/audio_coding/main/test/utility.h" #include "webrtc/system_wrappers/interface/event_wrapper.h" #include "webrtc/system_wrappers/interface/tick_util.h" #include "webrtc/system_wrappers/interface/trace.h" #include "webrtc/test/testsupport/fileutils.h" namespace webrtc { void SetISACConfigDefault( ACMTestISACConfig& isacConfig) { isacConfig.currentRateBitPerSec = 0; isacConfig.currentFrameSizeMsec = 0; isacConfig.maxRateBitPerSec = 0; isacConfig.maxPayloadSizeByte = 0; isacConfig.encodingMode = -1; isacConfig.initRateBitPerSec = 0; isacConfig.initFrameSizeInMsec = 0; isacConfig.enforceFrameSize = false; return; } int16_t SetISAConfig( ACMTestISACConfig& isacConfig, AudioCodingModule* acm, int testMode) { if((isacConfig.currentRateBitPerSec != 0) || (isacConfig.currentFrameSizeMsec != 0)) { CodecInst sendCodec; acm->SendCodec(&sendCodec); if(isacConfig.currentRateBitPerSec < 0) { sendCodec.rate = -1; CHECK_ERROR(acm->RegisterSendCodec(sendCodec)); if(testMode != 0) { printf("ISAC-%s Registered in adaptive (channel-dependent) mode.\n", (sendCodec.plfreq == 32000)? "swb":"wb"); } } else { if(isacConfig.currentRateBitPerSec != 0) { sendCodec.rate = isacConfig.currentRateBitPerSec; } if(isacConfig.currentFrameSizeMsec != 0) { sendCodec.pacsize = isacConfig.currentFrameSizeMsec * (sendCodec.plfreq / 1000); } CHECK_ERROR(acm->RegisterSendCodec(sendCodec)); if(testMode != 0) { printf("Target rate is set to %d bit/sec with frame-size %d ms \n", (int)isacConfig.currentRateBitPerSec, (int)sendCodec.pacsize / (sendCodec.plfreq / 1000)); } } } if(isacConfig.maxRateBitPerSec > 0) { CHECK_ERROR(acm->SetISACMaxRate(isacConfig.maxRateBitPerSec)); if(testMode != 0) { printf("Max rate is set to %u bit/sec\n", isacConfig.maxRateBitPerSec); } } if(isacConfig.maxPayloadSizeByte > 0) { CHECK_ERROR(acm->SetISACMaxPayloadSize(isacConfig.maxPayloadSizeByte)); if(testMode != 0) { printf("Max payload-size is set to %u bit/sec\n", isacConfig.maxPayloadSizeByte); } } if((isacConfig.initFrameSizeInMsec != 0) || (isacConfig.initRateBitPerSec != 0)) { CHECK_ERROR(acm->ConfigISACBandwidthEstimator( (uint8_t)isacConfig.initFrameSizeInMsec, (uint16_t)isacConfig.initRateBitPerSec, isacConfig.enforceFrameSize)); if((isacConfig.initFrameSizeInMsec != 0) && (testMode != 0)) { printf("Initialize BWE to %d msec frame-size\n", isacConfig.initFrameSizeInMsec); } if((isacConfig.initRateBitPerSec != 0) && (testMode != 0)) { printf("Initialize BWE to %u bit/sec send-bandwidth\n", isacConfig.initRateBitPerSec); } } return 0; } ISACTest::ISACTest(int testMode) { _testMode = testMode; } ISACTest::~ISACTest() { AudioCodingModule::Destroy(_acmA); AudioCodingModule::Destroy(_acmB); delete _channel_A2B; delete _channel_B2A; } int16_t ISACTest::Setup() { int codecCntr; CodecInst codecParam; _acmA = AudioCodingModule::Create(1); _acmB = AudioCodingModule::Create(2); for(codecCntr = 0; codecCntr < AudioCodingModule::NumberOfCodecs(); codecCntr++) { AudioCodingModule::Codec(codecCntr, &codecParam); if(!STR_CASE_CMP(codecParam.plname, "ISAC") && codecParam.plfreq == 16000) { memcpy(&_paramISAC16kHz, &codecParam, sizeof(CodecInst)); _idISAC16kHz = codecCntr; } if(!STR_CASE_CMP(codecParam.plname, "ISAC") && codecParam.plfreq == 32000) { memcpy(&_paramISAC32kHz, &codecParam, sizeof(CodecInst)); _idISAC32kHz = codecCntr; } } // register both iSAC-wb & iSAC-swb in both sides as receiver codecs CHECK_ERROR(_acmA->RegisterReceiveCodec(_paramISAC16kHz)); CHECK_ERROR(_acmA->RegisterReceiveCodec(_paramISAC32kHz)); CHECK_ERROR(_acmB->RegisterReceiveCodec(_paramISAC16kHz)); CHECK_ERROR(_acmB->RegisterReceiveCodec(_paramISAC32kHz)); //--- Set A-to-B channel _channel_A2B = new Channel; CHECK_ERROR(_acmA->RegisterTransportCallback(_channel_A2B)); _channel_A2B->RegisterReceiverACM(_acmB); //--- Set B-to-A channel _channel_B2A = new Channel; CHECK_ERROR(_acmB->RegisterTransportCallback(_channel_B2A)); _channel_B2A->RegisterReceiverACM(_acmA); file_name_swb_ = webrtc::test::ResourcePath("audio_coding/testfile32kHz", "pcm"); _acmB->RegisterSendCodec(_paramISAC16kHz); _acmA->RegisterSendCodec(_paramISAC32kHz); if(_testMode != 0) { printf("Side A Send Codec\n"); printf("%s %d\n", _paramISAC32kHz.plname, _paramISAC32kHz.plfreq); printf("Side B Send Codec\n"); printf("%s %d\n", _paramISAC16kHz.plname, _paramISAC16kHz.plfreq); } _inFileA.Open(file_name_swb_, 32000, "rb"); std::string fileNameA = webrtc::test::OutputPath() + "testisac_a.pcm"; std::string fileNameB = webrtc::test::OutputPath() + "testisac_b.pcm"; _outFileA.Open(fileNameA, 32000, "wb"); _outFileB.Open(fileNameB, 32000, "wb"); while(!_inFileA.EndOfFile()) { Run10ms(); } CodecInst receiveCodec; CHECK_ERROR(_acmA->ReceiveCodec(&receiveCodec)); if(_testMode != 0) { printf("Side A Receive Codec\n"); printf("%s %d\n", receiveCodec.plname, receiveCodec.plfreq); } CHECK_ERROR(_acmB->ReceiveCodec(&receiveCodec)); if(_testMode != 0) { printf("Side B Receive Codec\n"); printf("%s %d\n", receiveCodec.plname, receiveCodec.plfreq); } _inFileA.Close(); _outFileA.Close(); _outFileB.Close(); return 0; } void ISACTest::Perform() { if(_testMode == 0) { printf("Running iSAC Test"); WEBRTC_TRACE(webrtc::kTraceStateInfo, webrtc::kTraceAudioCoding, -1, "---------- iSACTest ----------"); } Setup(); int16_t testNr = 0; ACMTestISACConfig wbISACConfig; ACMTestISACConfig swbISACConfig; SetISACConfigDefault(wbISACConfig); SetISACConfigDefault(swbISACConfig); wbISACConfig.currentRateBitPerSec = -1; swbISACConfig.currentRateBitPerSec = -1; testNr++; EncodeDecode(testNr, wbISACConfig, swbISACConfig); if (_testMode != 0) { SetISACConfigDefault(wbISACConfig); SetISACConfigDefault(swbISACConfig); wbISACConfig.currentRateBitPerSec = -1; swbISACConfig.currentRateBitPerSec = -1; wbISACConfig.initRateBitPerSec = 13000; wbISACConfig.initFrameSizeInMsec = 60; swbISACConfig.initRateBitPerSec = 20000; swbISACConfig.initFrameSizeInMsec = 30; testNr++; EncodeDecode(testNr, wbISACConfig, swbISACConfig); SetISACConfigDefault(wbISACConfig); SetISACConfigDefault(swbISACConfig); wbISACConfig.currentRateBitPerSec = 20000; swbISACConfig.currentRateBitPerSec = 48000; testNr++; EncodeDecode(testNr, wbISACConfig, swbISACConfig); wbISACConfig.currentRateBitPerSec = 16000; swbISACConfig.currentRateBitPerSec = 30000; wbISACConfig.currentFrameSizeMsec = 60; testNr++; EncodeDecode(testNr, wbISACConfig, swbISACConfig); } SetISACConfigDefault(wbISACConfig); SetISACConfigDefault(swbISACConfig); testNr++; EncodeDecode(testNr, wbISACConfig, swbISACConfig); int user_input; if((_testMode == 0) || (_testMode == 1)) { swbISACConfig.maxPayloadSizeByte = (uint16_t)200; wbISACConfig.maxPayloadSizeByte = (uint16_t)200; } else { printf("Enter the max payload-size for side A: "); CHECK_ERROR(scanf("%d", &user_input)); swbISACConfig.maxPayloadSizeByte = (uint16_t)user_input; printf("Enter the max payload-size for side B: "); CHECK_ERROR(scanf("%d", &user_input)); wbISACConfig.maxPayloadSizeByte = (uint16_t)user_input; } testNr++; EncodeDecode(testNr, wbISACConfig, swbISACConfig); _acmA->ResetEncoder(); _acmB->ResetEncoder(); SetISACConfigDefault(wbISACConfig); SetISACConfigDefault(swbISACConfig); if((_testMode == 0) || (_testMode == 1)) { swbISACConfig.maxRateBitPerSec = (uint32_t)48000; wbISACConfig.maxRateBitPerSec = (uint32_t)48000; } else { printf("Enter the max rate for side A: "); CHECK_ERROR(scanf("%d", &user_input)); swbISACConfig.maxRateBitPerSec = (uint32_t)user_input; printf("Enter the max rate for side B: "); CHECK_ERROR(scanf("%d", &user_input)); wbISACConfig.maxRateBitPerSec = (uint32_t)user_input; } testNr++; EncodeDecode(testNr, wbISACConfig, swbISACConfig); testNr++; if(_testMode == 0) { SwitchingSamplingRate(testNr, 4); printf("Done!\n"); } else { SwitchingSamplingRate(testNr, 80); } } void ISACTest::Run10ms() { AudioFrame audioFrame; _inFileA.Read10MsData(audioFrame); CHECK_ERROR(_acmA->Add10MsData(audioFrame)); CHECK_ERROR(_acmB->Add10MsData(audioFrame)); CHECK_ERROR(_acmA->Process()); CHECK_ERROR(_acmB->Process()); CHECK_ERROR(_acmA->PlayoutData10Ms(32000, &audioFrame)); _outFileA.Write10MsData(audioFrame); CHECK_ERROR(_acmB->PlayoutData10Ms(32000, &audioFrame)); _outFileB.Write10MsData(audioFrame); } void ISACTest::EncodeDecode( int testNr, ACMTestISACConfig& wbISACConfig, ACMTestISACConfig& swbISACConfig) { if(_testMode == 0) { printf("."); } else { printf("\nTest %d:\n\n", testNr); } // Files in Side A and B _inFileA.Open(file_name_swb_, 32000, "rb", true); _inFileB.Open(file_name_swb_, 32000, "rb", true); std::string file_name_out; std::stringstream file_stream_a; std::stringstream file_stream_b; file_stream_a << webrtc::test::OutputPath(); file_stream_b << webrtc::test::OutputPath(); if(_testMode == 0) { file_stream_a << "out_iSACTest_A_" << testNr << ".pcm"; file_stream_b << "out_iSACTest_B_" << testNr << ".pcm"; } else { file_stream_a << "outA_" << testNr << ".pcm"; file_stream_b << "outB_" << testNr << ".pcm"; } file_name_out = file_stream_a.str(); _outFileA.Open(file_name_out, 32000, "wb"); file_name_out = file_stream_b.str(); _outFileB.Open(file_name_out, 32000, "wb"); CHECK_ERROR(_acmA->RegisterSendCodec(_paramISAC16kHz)); CHECK_ERROR(_acmA->RegisterSendCodec(_paramISAC32kHz)); CHECK_ERROR(_acmB->RegisterSendCodec(_paramISAC32kHz)); CHECK_ERROR(_acmB->RegisterSendCodec(_paramISAC16kHz)); if(_testMode != 0) { printf("Side A Sending Super-Wideband \n"); printf("Side B Sending Wideband\n\n"); } SetISAConfig(swbISACConfig, _acmA, _testMode); SetISAConfig(wbISACConfig, _acmB, _testMode); bool adaptiveMode = false; if((swbISACConfig.currentRateBitPerSec == -1) || (wbISACConfig.currentRateBitPerSec == -1)) { adaptiveMode = true; } _myTimer.Reset(); _channel_A2B->ResetStats(); _channel_B2A->ResetStats(); char currentTime[500]; if(_testMode == 2) printf("\n"); CodecInst sendCodec; EventWrapper* myEvent = EventWrapper::Create(); myEvent->StartTimer(true, 10); while(!(_inFileA.EndOfFile() || _inFileA.Rewinded())) { Run10ms(); _myTimer.Tick10ms(); _myTimer.CurrentTimeHMS(currentTime); if(_testMode == 2) printf("\r%s ", currentTime); if((adaptiveMode) && (_testMode != 0)) { myEvent->Wait(5000); _acmA->SendCodec(&sendCodec); if(_testMode == 2) printf("[%d] ", sendCodec.rate); _acmB->SendCodec(&sendCodec); if(_testMode == 2) printf("[%d] ", sendCodec.rate); } } if(_testMode != 0) { printf("\n\nSide A statistics\n\n"); _channel_A2B->PrintStats(_paramISAC32kHz); printf("\n\nSide B statistics\n\n"); _channel_B2A->PrintStats(_paramISAC16kHz); } _channel_A2B->ResetStats(); _channel_B2A->ResetStats(); if(_testMode != 0) printf("\n"); _outFileA.Close(); _outFileB.Close(); _inFileA.Close(); _inFileB.Close(); } void ISACTest::SwitchingSamplingRate( int testNr, int maxSampRateChange) { // Files in Side A _inFileA.Open(file_name_swb_, 32000, "rb"); _inFileB.Open(file_name_swb_, 32000, "rb"); std::string file_name_out; std::stringstream file_stream_a; std::stringstream file_stream_b; file_stream_a << webrtc::test::OutputPath(); file_stream_b << webrtc::test::OutputPath(); if(_testMode == 0) { file_stream_a << "out_iSACTest_A_" << testNr << ".pcm"; file_stream_b << "out_iSACTest_B_" << testNr << ".pcm"; } else { printf("\nTest %d", testNr); printf(" Alternate between WB and SWB at the sender Side\n\n"); file_stream_a << "outA_" << testNr << ".pcm"; file_stream_b << "outB_" << testNr << ".pcm"; } file_name_out = file_stream_a.str(); _outFileA.Open(file_name_out, 32000, "wb"); file_name_out = file_stream_b.str(); _outFileB.Open(file_name_out, 32000, "wb"); CHECK_ERROR(_acmA->RegisterSendCodec(_paramISAC32kHz)); CHECK_ERROR(_acmB->RegisterSendCodec(_paramISAC16kHz)); if(_testMode != 0) { printf("Side A Sending Super-Wideband \n"); printf("Side B Sending Wideband\n"); } int numSendCodecChanged = 0; _myTimer.Reset(); char currentTime[50]; while(numSendCodecChanged < (maxSampRateChange<<1)) { Run10ms(); _myTimer.Tick10ms(); _myTimer.CurrentTimeHMS(currentTime); if(_testMode == 2) printf("\r%s", currentTime); if(_inFileA.EndOfFile()) { if(_inFileA.SamplingFrequency() == 16000) { if(_testMode != 0) printf("\nSide A switched to Send Super-Wideband\n"); _inFileA.Close(); _inFileA.Open(file_name_swb_, 32000, "rb"); CHECK_ERROR(_acmA->RegisterSendCodec(_paramISAC32kHz)); } else { if(_testMode != 0) printf("\nSide A switched to Send Wideband\n"); _inFileA.Close(); _inFileA.Open(file_name_swb_, 32000, "rb"); CHECK_ERROR(_acmA->RegisterSendCodec(_paramISAC16kHz)); } numSendCodecChanged++; } if(_inFileB.EndOfFile()) { if(_inFileB.SamplingFrequency() == 16000) { if(_testMode != 0) printf("\nSide B switched to Send Super-Wideband\n"); _inFileB.Close(); _inFileB.Open(file_name_swb_, 32000, "rb"); CHECK_ERROR(_acmB->RegisterSendCodec(_paramISAC32kHz)); } else { if(_testMode != 0) printf("\nSide B switched to Send Wideband\n"); _inFileB.Close(); _inFileB.Open(file_name_swb_, 32000, "rb"); CHECK_ERROR(_acmB->RegisterSendCodec(_paramISAC16kHz)); } numSendCodecChanged++; } } _outFileA.Close(); _outFileB.Close(); _inFileA.Close(); _inFileB.Close(); } } // namespace webrtc
bsd-3-clause
ngokevin/cyder
setup.py
371
import os from setuptools import setup, find_packages setup(name='cyder', version='1.0', description='Django application.', long_description='', author='', author_email='', license='', url='', include_package_data=True, classifiers = [], packages=find_packages(exclude=['tests']), install_requires=[])
bsd-3-clause
gnanam336/ideal
ideal/development/constructs/modifier_construct.java
783
/* * Copyright 2014 The Ideal Authors. All rights reserved. * * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file or at * https://developers.google.com/open-source/licenses/bsd */ package ideal.development.constructs; import ideal.library.elements.*; import javax.annotation.Nullable; import ideal.runtime.elements.*; import ideal.development.elements.*; public class modifier_construct extends base_construct implements annotation_construct { public final modifier_kind the_kind; public modifier_construct(modifier_kind the_kind, position pos) { super(pos); assert the_kind != null; this.the_kind = the_kind; } public readonly_list<construct> children() { return new empty<construct>(); } }
bsd-3-clause
babagay/razzd
backend/models/Alias.php
941
<?php namespace backend\models; use Yii; /** * This is the model class for table "alias". * * @property string $id * @property integer $eid * @property string $model * @property string $url * @property string $alias */ class Alias extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%alias}}'; } /** * @inheritdoc */ public function rules() { return [ [['eid', 'model', 'url', 'alias'], 'required'], [['eid'], 'integer'], [['model'], 'string', 'max' => 40], [['url', 'alias'], 'string', 'max' => 255] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id' => 'ID', 'eid' => 'Eid', 'model' => 'Model', 'url' => 'Url', 'alias' => 'Alias', ]; } }
bsd-3-clause
kbc-developers/Mozc
src/session/random_keyevents_generator.cc
12005
// Copyright 2010-2016, 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. #include "session/random_keyevents_generator.h" #include <string> #include <vector> #include "base/logging.h" #include "base/mutex.h" #include "base/port.h" #include "base/util.h" #include "protocol/commands.pb.h" namespace mozc { namespace session { namespace { #include "session/session_stress_test_data.h" // Constants for ProbableKeyEvent. const double kMostPossibleKeyProbability = 0.98; const size_t kProbableKeyEventSize = 8; const commands::KeyEvent::SpecialKey kSpecialKeys[] = { commands::KeyEvent::SPACE, commands::KeyEvent::BACKSPACE, commands::KeyEvent::DEL, commands::KeyEvent::DOWN, commands::KeyEvent::END, commands::KeyEvent::ENTER, commands::KeyEvent::ESCAPE, commands::KeyEvent::HOME, commands::KeyEvent::INSERT, commands::KeyEvent::HENKAN, commands::KeyEvent::MUHENKAN, commands::KeyEvent::LEFT, commands::KeyEvent::RIGHT, commands::KeyEvent::UP, commands::KeyEvent::DOWN, commands::KeyEvent::PAGE_UP, commands::KeyEvent::PAGE_DOWN, commands::KeyEvent::TAB, commands::KeyEvent::F1, commands::KeyEvent::F2, commands::KeyEvent::F3, commands::KeyEvent::F4, commands::KeyEvent::F5, commands::KeyEvent::F6, commands::KeyEvent::F7, commands::KeyEvent::F8, commands::KeyEvent::F9, commands::KeyEvent::F10, commands::KeyEvent::F11, commands::KeyEvent::F12, commands::KeyEvent::NUMPAD0, commands::KeyEvent::NUMPAD1, commands::KeyEvent::NUMPAD2, commands::KeyEvent::NUMPAD3, commands::KeyEvent::NUMPAD4, commands::KeyEvent::NUMPAD5, commands::KeyEvent::NUMPAD6, commands::KeyEvent::NUMPAD7, commands::KeyEvent::NUMPAD8, commands::KeyEvent::NUMPAD9, commands::KeyEvent::MULTIPLY, commands::KeyEvent::ADD, commands::KeyEvent::SEPARATOR, commands::KeyEvent::SUBTRACT, commands::KeyEvent::DECIMAL, commands::KeyEvent::DIVIDE, commands::KeyEvent::EQUALS, commands::KeyEvent::COMMA, }; uint32 GetRandomAsciiKey() { return static_cast<uint32>(' ') + Util::Random(static_cast<uint32>('~' - ' ')); } void InitSeedWithRandomValue() { uint32 seed = 0; mozc::Util::GetRandomSequence(reinterpret_cast<char *>(&seed), sizeof(seed)); Util::SetRandomSeed(seed); } void DoNothing() { // Do nothing. // Used only for marking the seed initialized. } once_t seed_init_once = MOZC_ONCE_INIT; } // namespace void RandomKeyEventsGenerator::PrepareForMemoryLeakTest() { // Read all kTestSentences and load these to memory. const int size = arraysize(kTestSentences); for (int i = 0; i < size; ++i) { const char *sentence = kTestSentences[i]; CHECK_GT(strlen(sentence), 0); } } // Generates KeyEvent instances based on |romaji| and stores into |keys|. void TypeRawKeys(StringPiece romaji, bool create_probable_key_events, vector<commands::KeyEvent> *keys) { for (ConstChar32Iterator iter(romaji); !iter.Done(); iter.Next()) { const uint32 ucs4 = iter.Get(); if (ucs4 < 0x20 || ucs4 > 0x7F) { continue; } commands::KeyEvent key; key.set_key_code(ucs4); if (create_probable_key_events) { commands::KeyEvent::ProbableKeyEvent *probable_key_event = key.add_probable_key_event(); probable_key_event->set_key_code(ucs4); probable_key_event->set_probability(kMostPossibleKeyProbability); for (size_t i = 0; i < kProbableKeyEventSize; ++i) { commands::KeyEvent::ProbableKeyEvent *probable_key_event = key.add_probable_key_event(); probable_key_event->set_key_code(0x20 + Util::Random(0x7F - 0x20)); probable_key_event->set_probability( (1.0 - kMostPossibleKeyProbability) / kProbableKeyEventSize); } } keys->push_back(key); } } // Converts from Hiragana to Romaji. string ToRomaji(StringPiece hiragana) { string tmp, result; Util::HiraganaToRomanji(hiragana, &tmp); Util::FullWidthToHalfWidth(tmp, &result); return result; } void RandomKeyEventsGenerator::InitSeed(uint32 seed) { Util::SetRandomSeed(seed); CallOnce(&seed_init_once, &DoNothing); } // Generates KeyEvent instances based on |sentence| and stores into |keys|. // And Enter key event is appended at the tail. // The instances have ProbableKeyEvent if |create_probable_key_events| is set. void GenerateMobileSequenceInternal( StringPiece sentence, bool create_probable_key_events, vector<commands::KeyEvent> *keys) { const string input = ToRomaji(sentence); VLOG(1) << input; // Type the sentence TypeRawKeys(input, create_probable_key_events, keys); commands::KeyEvent key; key.set_special_key(commands::KeyEvent::ENTER); keys->push_back(key); } void RandomKeyEventsGenerator::GenerateMobileSequence( bool create_probable_key_events, vector<commands::KeyEvent> *keys) { CHECK(keys); keys->clear(); // If seed was not initialized, set seed randomly. CallOnce(&seed_init_once, &InitSeedWithRandomValue); const StringPiece sentence( kTestSentences[Util::Random(arraysize(kTestSentences))]); CHECK(!sentence.empty()); for (size_t i = 0; i < sentence.size(); ) { // To simulate mobile key events, split given sentence into smaller parts. // Average 5, Min 1, Max 15 const size_t len = Util::Random(5) + Util::Random(5) + Util::Random(5); GenerateMobileSequenceInternal(sentence.substr(i, len), create_probable_key_events, keys); i += len; } } void RandomKeyEventsGenerator::GenerateSequence( vector<commands::KeyEvent> *keys) { CHECK(keys); keys->clear(); // If seed was not initialized, set seed randomly. CallOnce(&seed_init_once, &InitSeedWithRandomValue); const string sentence = kTestSentences[Util::Random(arraysize(kTestSentences))]; CHECK(!sentence.empty()); const string input = ToRomaji(sentence); VLOG(1) << input; // Must send ON event first. { commands::KeyEvent key; key.set_special_key(commands::KeyEvent::ON); keys->push_back(key); } vector<commands::KeyEvent> basic_keys; // generate basic input TypeRawKeys(input, false, &basic_keys); // basic keys + conversion { for (size_t i = 0; i < basic_keys.size(); ++i) { keys->push_back(basic_keys[i]); } for (int i = 0; i < 5; ++i) { const size_t num = Util::Random(30) + 8; for (size_t j = 0; j < num; ++j) { commands::KeyEvent key; key.set_special_key(commands::KeyEvent::SPACE); if (Util::Random(4) == 0) { key.add_modifier_keys(commands::KeyEvent::SHIFT); keys->push_back(key); } } commands::KeyEvent key; key.set_special_key(commands::KeyEvent::RIGHT); keys->push_back(key); } commands::KeyEvent key; key.set_special_key(commands::KeyEvent::ENTER); keys->push_back(key); } // segment resize { for (size_t i = 0; i < basic_keys.size(); ++i) { keys->push_back(basic_keys[i]); } const size_t num = Util::Random(30) + 10; for (size_t i = 0; i < num; ++i) { commands::KeyEvent key; switch (Util::Random(4)) { case 0: key.set_special_key(commands::KeyEvent::LEFT); if (Util::Random(2) == 0) { key.add_modifier_keys(commands::KeyEvent::SHIFT); } break; case 1: key.set_special_key(commands::KeyEvent::RIGHT); if (Util::Random(2) == 0) { key.add_modifier_keys(commands::KeyEvent::SHIFT); } break; default: { const size_t space_num = Util::Random(20) + 3; for (size_t i = 0; i < space_num; ++i) { key.set_special_key(commands::KeyEvent::SPACE); keys->push_back(key); } } break; } if (Util::Random(4) == 0) { key.add_modifier_keys(commands::KeyEvent::CTRL); } if (Util::Random(10) == 0) { key.add_modifier_keys(commands::KeyEvent::ALT); } keys->push_back(key); } commands::KeyEvent key; key.set_special_key(commands::KeyEvent::ENTER); keys->push_back(key); } // insert + delete { for (size_t i = 0; i < basic_keys.size(); ++i) { keys->push_back(basic_keys[i]); } const size_t num = Util::Random(20) + 10; for (size_t i = 0; i < num; ++i) { commands::KeyEvent key; switch (Util::Random(5)) { case 0: key.set_special_key(commands::KeyEvent::LEFT); break; case 1: key.set_special_key(commands::KeyEvent::RIGHT); break; case 2: key.set_special_key(commands::KeyEvent::DEL); break; case 3: key.set_special_key(commands::KeyEvent::BACKSPACE); break; default: { // add any ascii const size_t insert_num = Util::Random(5) + 1; for (size_t i = 0; i < insert_num; ++i) { key.set_key_code(GetRandomAsciiKey()); } } } keys->push_back(key); } commands::KeyEvent key; key.set_special_key(commands::KeyEvent::ENTER); keys->push_back(key); } // basic keys + modifiers { for (size_t i = 0; i < basic_keys.size(); ++i) { commands::KeyEvent key; switch (Util::Random(8)) { case 0: key.set_key_code(kSpecialKeys[Util::Random(arraysize(kSpecialKeys))]); break; case 1: key.set_key_code(GetRandomAsciiKey()); break; default: key.CopyFrom(basic_keys[i]); break; } if (Util::Random(10) == 0) { // 10% key.add_modifier_keys(commands::KeyEvent::CTRL); } if (Util::Random(10) == 0) { // 10% key.add_modifier_keys(commands::KeyEvent::SHIFT); } if (Util::Random(50) == 0) { // 2% key.add_modifier_keys(commands::KeyEvent::KEY_DOWN); } if (Util::Random(50) == 0) { // 2% key.add_modifier_keys(commands::KeyEvent::KEY_UP); } keys->push_back(key); } // submit commands::KeyEvent key; key.set_special_key(commands::KeyEvent::ENTER); keys->push_back(key); } CHECK_GT(keys->size(), 0); VLOG(1) << "key sequence is generated: " << keys->size(); } // static const char **RandomKeyEventsGenerator::GetTestSentences(size_t *size) { *size = arraysize(kTestSentences); return kTestSentences; } } // namespace session } // namespace mozc
bsd-3-clause
vrkansagara/vrkansagara.in
config/app.php
9432
<?php declare(strict_types=1); return [ /* |-------------------------------------------------------------------------- | Application Name |-------------------------------------------------------------------------- | | This value is the name of your application. This value is used when the | framework needs to place the application's name in a notification or | any other location as required by the application or its packages. | */ 'name' => env('APP_NAME', 'VRKANSAGARA'), /* |-------------------------------------------------------------------------- | Application Environment |-------------------------------------------------------------------------- | | This value determines the "environment" your application is currently | running in. This may determine how you prefer to configure various | services the application utilizes. Set this in your ".env" file. | */ 'env' => env('APP_ENV', 'production'), /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => (bool) env('APP_DEBUG', false), /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => env('APP_URL', 'http://localhost'), 'asset_url' => env('ASSET_URL', null), /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Application Fallback Locale |-------------------------------------------------------------------------- | | The fallback locale determines the locale to use when the current one | is not available. You may change the value to correspond to any of | the language folders that are provided through your application. | */ 'fallback_locale' => 'en', /* |-------------------------------------------------------------------------- | Faker Locale |-------------------------------------------------------------------------- | | This locale will be used by the Faker PHP library when generating fake | data for your database seeds. For example, this will be used to get | localized telephone numbers, street address information and more. | */ 'faker_locale' => 'en_US', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => env('APP_KEY'), 'cipher' => 'AES-256-CBC', /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => [ /* * Laravel Framework Service Providers... */ Illuminate\Auth\AuthServiceProvider::class, Illuminate\Broadcasting\BroadcastServiceProvider::class, Illuminate\Bus\BusServiceProvider::class, Illuminate\Cache\CacheServiceProvider::class, Illuminate\Foundation\Providers\ConsoleSupportServiceProvider::class, Illuminate\Cookie\CookieServiceProvider::class, Illuminate\Database\DatabaseServiceProvider::class, Illuminate\Encryption\EncryptionServiceProvider::class, Illuminate\Filesystem\FilesystemServiceProvider::class, Illuminate\Foundation\Providers\FoundationServiceProvider::class, Illuminate\Hashing\HashServiceProvider::class, Illuminate\Mail\MailServiceProvider::class, Illuminate\Notifications\NotificationServiceProvider::class, Illuminate\Pagination\PaginationServiceProvider::class, Illuminate\Pipeline\PipelineServiceProvider::class, Illuminate\Queue\QueueServiceProvider::class, Illuminate\Redis\RedisServiceProvider::class, Illuminate\Auth\Passwords\PasswordResetServiceProvider::class, Illuminate\Session\SessionServiceProvider::class, Illuminate\Translation\TranslationServiceProvider::class, Illuminate\Validation\ValidationServiceProvider::class, Illuminate\View\ViewServiceProvider::class, /* * Package Service Providers... */ /* * Application Service Providers... */ App\Providers\AppServiceProvider::class, App\Providers\AuthServiceProvider::class, // App\Providers\BroadcastServiceProvider::class, App\Providers\EventServiceProvider::class, App\Providers\RouteServiceProvider::class, ], /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => [ 'App' => Illuminate\Support\Facades\App::class, 'Arr' => Illuminate\Support\Arr::class, 'Artisan' => Illuminate\Support\Facades\Artisan::class, 'Auth' => Illuminate\Support\Facades\Auth::class, 'Blade' => Illuminate\Support\Facades\Blade::class, 'Broadcast' => Illuminate\Support\Facades\Broadcast::class, 'Bus' => Illuminate\Support\Facades\Bus::class, 'Cache' => Illuminate\Support\Facades\Cache::class, 'Config' => Illuminate\Support\Facades\Config::class, 'Cookie' => Illuminate\Support\Facades\Cookie::class, 'Crypt' => Illuminate\Support\Facades\Crypt::class, 'DB' => Illuminate\Support\Facades\DB::class, 'Eloquent' => Illuminate\Database\Eloquent\Model::class, 'Event' => Illuminate\Support\Facades\Event::class, 'File' => Illuminate\Support\Facades\File::class, 'Gate' => Illuminate\Support\Facades\Gate::class, 'Hash' => Illuminate\Support\Facades\Hash::class, 'Lang' => Illuminate\Support\Facades\Lang::class, 'Log' => Illuminate\Support\Facades\Log::class, 'Mail' => Illuminate\Support\Facades\Mail::class, 'Notification' => Illuminate\Support\Facades\Notification::class, 'Password' => Illuminate\Support\Facades\Password::class, 'Queue' => Illuminate\Support\Facades\Queue::class, 'Redirect' => Illuminate\Support\Facades\Redirect::class, 'Redis' => Illuminate\Support\Facades\Redis::class, 'Request' => Illuminate\Support\Facades\Request::class, 'Response' => Illuminate\Support\Facades\Response::class, 'Route' => Illuminate\Support\Facades\Route::class, 'Schema' => Illuminate\Support\Facades\Schema::class, 'Session' => Illuminate\Support\Facades\Session::class, 'Storage' => Illuminate\Support\Facades\Storage::class, 'Str' => Illuminate\Support\Str::class, 'URL' => Illuminate\Support\Facades\URL::class, 'Validator' => Illuminate\Support\Facades\Validator::class, 'View' => Illuminate\Support\Facades\View::class, ], ];
bsd-3-clause
jklenzing/pysat
pysat/instruments/sw_f107.py
33411
# -*- coding: utf-8 -*- """Supports F10.7 index values. Downloads data from LASP and the SWPC. Parameters ---------- platform : string 'sw' name : string 'f107' tag : string '' LASP F10.7 data (downloads by month, loads by day) 'all' All LASP standard F10.7 'prelim' Preliminary SWPC daily solar indices 'daily' Daily SWPC solar indices (contains last 30 days) 'forecast' Grab forecast data from SWPC (next 3 days) '45day' 45-Day Forecast data from the Air Force Note ---- The forecast data is stored by generation date, where each file contains the forecast for the next three days. Forecast data downloads are only supported for the current day. When loading forecast data, the date specified with the load command is the date the forecast was generated. The data loaded will span three days. To always ensure you are loading the most recent data, load the data with tomorrow's date. f107 = pysat.Instrument('sw', 'f107', tag='forecast') f107.download() f107.load(date=f107.tomorrow()) The forecast data should not be used with the data padding option available from pysat.Instrument objects. The 'all' tag shouldn't be used either, no other data available to pad with. Warnings -------- The 'forecast' F10.7 data loads three days at a time. The data padding feature and multi_file_day feature available from the pyast.Instrument object is not appropriate for 'forecast' data. """ import os import warnings import numpy as np import pandas as pds import pysat platform = 'sw' name = 'f107' tags = {'': 'Daily LASP value of F10.7', 'all': 'All LASP F10.7 values', 'prelim': 'Preliminary SWPC daily solar indices', 'daily': 'Daily SWPC solar indices (contains last 30 days)', 'forecast': 'SWPC Forecast F107 data next (3 days)', '45day': 'Air Force 45-day Forecast'} # dict keyed by sat_id that lists supported tags for each sat_id sat_ids = {'': ['', 'all', 'prelim', 'daily', 'forecast', '45day']} # dict keyed by sat_id that lists supported tags and a good day of test data # generate todays date to support loading forecast data now = pysat.datetime.now() today = pysat.datetime(now.year, now.month, now.day) tomorrow = today + pds.DateOffset(days=1) # set test dates _test_dates = {'': {'': pysat.datetime(2009, 1, 1), 'all': pysat.datetime(2009, 1, 1), 'prelim': pysat.datetime(2009, 1, 1), 'daily': tomorrow, 'forecast': tomorrow, '45day': tomorrow}} def load(fnames, tag=None, sat_id=None): """Load F10.7 index files Parameters ------------ fnames : (pandas.Series) Series of filenames tag : (str or NoneType) tag or None (default=None) sat_id : (str or NoneType) satellite id or None (default=None) Returns --------- data : (pandas.DataFrame) Object containing satellite data meta : (pysat.Meta) Object containing metadata such as column names and units Notes ----- Called by pysat. Not intended for direct use by user. """ if tag == '': # f107 data stored monthly, need to return data daily # the daily date is attached to filename # parse off the last date, load month of data, downselect to desired # day date = pysat.datetime.strptime(fnames[0][-10:], '%Y-%m-%d') data = pds.read_csv(fnames[0][0:-11], index_col=0, parse_dates=True) idx, = np.where((data.index >= date) & (data.index < date + pds.DateOffset(days=1))) result = data.iloc[idx, :] elif tag == 'all': result = pds.read_csv(fnames[0], index_col=0, parse_dates=True) elif tag == 'daily' or tag == 'prelim': result = pds.read_csv(fnames[0], index_col=0, parse_dates=True) elif tag == 'forecast': # load forecast data result = pds.read_csv(fnames[0], index_col=0, parse_dates=True) elif tag == '45day': # load forecast data result = pds.read_csv(fnames[0], index_col=0, parse_dates=True) meta = pysat.Meta() meta['f107'] = {meta.units_label: 'SFU', meta.name_label: 'F10.7 cm solar index', meta.desc_label: 'F10.7 cm radio flux in Solar Flux Units (SFU)'} if tag == '45day': meta['ap'] = {meta.name_label: 'Daily Ap index', meta.desc_label: 'Daily average of 3-h ap indices'} elif tag == 'daily' or tag == 'prelim': meta['ssn'] = {meta.name_label: 'Sunspot Number', meta.desc_label: 'SESC Sunspot Number', meta.fill_label: -999} meta['ss_area'] = {meta.name_label: 'Sunspot Area', meta.desc_label: 'Sunspot Area 10$^6$ Hemisphere', meta.fill_label: -999} meta['new_reg'] = {meta.name_label: 'New Regions', meta.desc_label: 'New active solar regions', meta.fill_label: -999} meta['smf'] = {meta.name_label: 'Solar Mean Field', meta.desc_label: 'Standford Solar Mean Field', meta.fill_label: -999} meta['goes_bgd_flux'] = {meta.name_label: 'X-ray Background Flux', meta.desc_label: 'GOES15 X-ray Background Flux', meta.fill_label: '*'} meta['c_flare'] = {meta.name_label: 'C X-Ray Flares', meta.desc_label: 'C-class X-Ray Flares', meta.fill_label: -1} meta['m_flare'] = {meta.name_label: 'M X-Ray Flares', meta.desc_label: 'M-class X-Ray Flares', meta.fill_label: -1} meta['x_flare'] = {meta.name_label: 'X X-Ray Flares', meta.desc_label: 'X-class X-Ray Flares', meta.fill_label: -1} meta['o1_flare'] = {meta.name_label: '1 Optical Flares', meta.desc_label: '1-class Optical Flares', meta.fill_label: -1} meta['o2_flare'] = {meta.name_label: '2 Optical Flares', meta.desc_label: '2-class Optical Flares', meta.fill_label: -1} meta['o3_flare'] = {meta.name_label: '3 Optical Flares', meta.desc_label: '3-class Optical Flares', meta.fill_label: -1} return result, meta def list_files(tag=None, sat_id=None, data_path=None, format_str=None): """Return a Pandas Series of every file for F10.7 data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. (default=None) sat_id : (string or NoneType) Specifies the satellite ID for a constellation. Not used. (default=None) data_path : (string or NoneType) Path to data directory. If None is specified, the value previously set in Instrument.files.data_path is used. (default=None) format_str : (string or NoneType) User specified file format. If None is specified, the default formats associated with the supplied tags are used. (default=None) Returns -------- pysat.Files.from_os : (pysat._files.Files) A class containing the verified available files Notes ----- Called by pysat. Not intended for direct use by user. """ import time if data_path is not None: if tag == '': # files are by month, going to add date to monthly filename for # each day of the month. The load routine will load a month of # data and use the appended date to select out appropriate data. if format_str is None: format_str = 'f107_monthly_{year:04d}-{month:02d}.txt' out = pysat.Files.from_os(data_path=data_path, format_str=format_str) if not out.empty: out.loc[out.index[-1] + pds.DateOffset(months=1) - pds.DateOffset(days=1)] = out.iloc[-1] out = out.asfreq('D', 'pad') out = out + '_' + out.index.strftime('%Y-%m-%d') return out elif tag == 'all': # files are by year if format_str is None: format_str = ''.join(('f107_1947_to_{year:04d}-{month:02d}-', '{day:02d}.txt')) out = pysat.Files.from_os(data_path=data_path, format_str=format_str) # load the same data (all), regardless of which day a user selects # resample file list to provide the same filename for every day # of f107 data if not out.empty: # only want to use the most recent file out = out.iloc[-1:] # first day of data is 2-14, ensure same file for first and # most recent day out.loc[pysat.datetime(1947, 2, 13)] = out.iloc[0] # make sure things are in order and copy latest filename for # all days, thus no matter which day with data the user loads # they get the most recent F10.7 file out = out.sort_index() out = out.asfreq('D', 'pad') return out elif tag == 'prelim': # files are by year (and quarter). The load routine will load a # year of data and use the appended date to select out appropriate # data. if format_str is None: format_str = \ 'f107_prelim_{year:04d}_{month:02d}_v{version:01d}.txt' out = pysat.Files.from_os(data_path=data_path, format_str=format_str) if not out.empty: # Set each file's valid length at a 1-day resolution orig_files = out.sort_index().copy() new_files = list() for orig in orig_files.iteritems(): # Version determines each file's valid length version = int(orig[1].split("_v")[1][0]) doff = pds.DateOffset(years=1) if version == 2 \ else pds.DateOffset(months=3) istart = orig[0] iend = istart + doff - pds.DateOffset(days=1) # Ensure the end time does not extend past the number of # possible days included based on the file's download time fname = os.path.join(data_path, orig[1]) dend = pds.datetime.utcfromtimestamp(os.path.getctime(fname)) dend = dend - pds.DateOffset(days=1) if dend < iend: iend = dend # Pad the original file index out.loc[iend] = orig[1] out = out.sort_index() # Save the files at a daily cadence over the desired period new_files.append(out.loc[istart: iend].asfreq('D', 'pad')) # Add the newly indexed files to the file output out = pds.concat(new_files, sort=True) out = out.dropna() out = out.sort_index() return out elif tag == 'daily': format_str = 'f107_daily_{year:04d}-{month:02d}-{day:02d}.txt' files = pysat.Files.from_os(data_path=data_path, format_str=format_str) # pad list of files data to include most recent file under tomorrow if not files.empty: pds_off = pds.DateOffset(days=1) files.loc[files.index[-1] + pds_off] = files.values[-1] files.loc[files.index[-1] + pds_off] = files.values[-1] return files elif tag == 'forecast': format_str = 'f107_forecast_{year:04d}-{month:02d}-{day:02d}.txt' files = pysat.Files.from_os(data_path=data_path, format_str=format_str) # pad list of files data to include most recent file under tomorrow if not files.empty: pds_off = pds.DateOffset(days=1) files.loc[files.index[-1] + pds_off] = files.values[-1] files.loc[files.index[-1] + pds_off] = files.values[-1] return files elif tag == '45day': format_str = 'f107_45day_{year:04d}-{month:02d}-{day:02d}.txt' files = pysat.Files.from_os(data_path=data_path, format_str=format_str) # pad list of files data to include most recent file under tomorrow if not files.empty: pds_off = pds.DateOffset(days=1) files.loc[files.index[-1] + pds_off] = files.values[-1] files.loc[files.index[-1] + pds_off] = files.values[-1] return files else: raise ValueError('Unrecognized tag name for Space Weather Index ' + 'F107') else: raise ValueError('A data_path must be passed to the loading routine ' + 'for F107') def download(date_array, tag, sat_id, data_path, user=None, password=None): """Routine to download F107 index data Parameters ----------- tag : (string or NoneType) Denotes type of file to load. Accepted types are '' and 'forecast'. (default=None) sat_id : (string or NoneType) Specifies the satellite ID for a constellation. Not used. (default=None) data_path : (string or NoneType) Path to data directory. If None is specified, the value previously set in Instrument.files.data_path is used. (default=None) Returns -------- Void : (NoneType) data downloaded to disk, if available. Note ---- Called by pysat. Not intended for direct use by user. Warnings -------- Only able to download current forecast data, not archived forecasts. """ # download standard F107 data if tag == '': # download from LASP, by month import requests import json for date in date_array: # modify date to be the start of the month if date.day != 1: raise ValueError('The Download routine must be invoked with ' + 'a freq="MS" option.') # download webpage dstr = 'http://lasp.colorado.edu/lisird/latis/dap/' dstr += 'noaa_radio_flux.json?time%3E=' dstr += date.strftime('%Y-%m-%d') dstr += 'T00:00:00.000Z&time%3C=' dstr += (date + pds.DateOffset(months=1) - pds.DateOffset(days=1)).strftime('%Y-%m-%d') dstr += 'T00:00:00.000Z' # data returned as json r = requests.get(dstr) # process raw_dict = json.loads(r.text)['noaa_radio_flux'] data = pds.DataFrame.from_dict(raw_dict['samples']) if data.empty: warnings.warn("no data for {:}".format(date), UserWarning) else: times = [pysat.datetime.strptime(time, '%Y%m%d') for time in data.pop('time')] data.index = times # replace fill with NaNs idx, = np.where(data['f107'] == -99999.0) data.iloc[idx, :] = np.nan # create file data.to_csv(os.path.join(data_path, 'f107_monthly_' + date.strftime('%Y-%m') + '.txt'), header=True) elif tag == 'all': # download from LASP, by year import requests import json # download webpage dstr = 'http://lasp.colorado.edu/lisird/latis/dap/' dstr += 'noaa_radio_flux.json?time%3E=' dstr += pysat.datetime(1947, 2, 13).strftime('%Y-%m-%d') dstr += 'T00:00:00.000Z&time%3C=' now = pysat.datetime.utcnow() dstr += now.strftime('%Y-%m-%dT%H:%M:%S.000Z') # data returned as json r = requests.get(dstr) # process raw_dict = json.loads(r.text)['noaa_radio_flux'] data = pds.DataFrame.from_dict(raw_dict['samples']) try: # This is the new data format times = [pysat.datetime.strptime(time, '%Y%m%d') for time in data.pop('time')] except ValueError: # Accepts old file formats times = [pysat.datetime.strptime(time, '%Y %m %d') for time in data.pop('time')] data.index = times # replace fill with NaNs idx, = np.where(data['f107'] == -99999.0) data.iloc[idx, :] = np.nan # create file data.to_csv(os.path.join(data_path, 'f107_1947_to_' + now.strftime('%Y-%m-%d') + '.txt'), header=True) elif tag == 'prelim': import ftplib from ftplib import FTP import sys ftp = FTP('ftp.swpc.noaa.gov') # connect to host, default port ftp.login() # user anonymous, passwd anonymous@ ftp.cwd('/pub/indices/old_indices') bad_fname = list() # Get the local files, to ensure that the version 1 files are # downloaded again if more data has been added local_files = list_files(tag, sat_id, data_path) # To avoid downloading multiple files, cycle dates based on file length date = date_array[0] while date <= date_array[-1]: # The file name changes, depending on how recent the requested # data is qnum = (date.month-1) // 3 + 1 # Integer floor division qmonth = (qnum-1) * 3 + 1 quar = 'Q{:d}_'.format(qnum) fnames = ['{:04d}{:s}DSD.txt'.format(date.year, ss) for ss in ['_', quar]] versions = ["01_v2", "{:02d}_v1".format(qmonth)] vend = [pysat.datetime(date.year, 12, 31), pysat.datetime(date.year, qmonth, 1) + pds.DateOffset(months=3) - pds.DateOffset(days=1)] downloaded = False rewritten = False # Attempt the download(s) for iname, fname in enumerate(fnames): # Test to see if we already tried this filename if fname in bad_fname: continue local_fname = fname saved_fname = os.path.join(data_path, local_fname) ofile = '_'.join(['f107', 'prelim', '{:04d}'.format(date.year), '{:s}.txt'.format(versions[iname])]) outfile = os.path.join(data_path, ofile) if os.path.isfile(outfile): downloaded = True # Check the date to see if this should be rewritten checkfile = os.path.split(outfile)[-1] has_file = local_files == checkfile if np.any(has_file): if has_file[has_file].index[-1] < vend[iname]: # This file will be updated again, but only attempt # to do so if enough time has passed from the # last time it was downloaded yesterday = today - pds.DateOffset(days=1) if has_file[has_file].index[-1] < yesterday: rewritten = True else: # The file does not exist, if it can be downloaded, it # should be 'rewritten' rewritten = True # Attempt to download if the file does not exist or if the # file has been updated if rewritten or not downloaded: try: sys.stdout.flush() ftp.retrbinary('RETR ' + fname, open(saved_fname, 'wb').write) downloaded = True print('Downloaded file for ' + date.strftime('%x')) except ftplib.error_perm as exception: # Could not fetch, so cannot rewrite rewritten = False # Test for an error if str(exception.args[0]).split(" ", 1)[0] != '550': raise RuntimeError(exception) else: # file isn't actually there, try the next name os.remove(saved_fname) # Save this so we don't try again # Because there are two possible filenames for # each time, it's ok if one isn't there. We just # don't want to keep looking for it. bad_fname.append(fname) # If the first file worked, don't try again if downloaded: break if not downloaded: print('File not available for {:}'.format(date.strftime('%x'))) elif rewritten: with open(saved_fname, 'r') as fprelim: lines = fprelim.read() rewrite_daily_file(date.year, outfile, lines) os.remove(saved_fname) # Cycle to the next date date = vend[iname] + pds.DateOffset(days=1) # Close connection after downloading all dates ftp.close() elif tag == 'daily': import requests print('This routine can only download the latest 30 day file') # download webpage furl = 'https://services.swpc.noaa.gov/text/daily-solar-indices.txt' r = requests.get(furl) # Save the output outfile = os.path.join(data_path, 'f107_daily_' + today.strftime('%Y-%m-%d') + '.txt') rewrite_daily_file(today.year, outfile, r.text) elif tag == 'forecast': import requests print('This routine can only download the current forecast, not ' + 'archived forecasts') # download webpage furl = 'https://services.swpc.noaa.gov/text/' + \ '3-day-solar-geomag-predictions.txt' r = requests.get(furl) # parse text to get the date the prediction was generated date_str = r.text.split(':Issued: ')[-1].split(' UTC')[0] date = pysat.datetime.strptime(date_str, '%Y %b %d %H%M') # get starting date of the forecasts raw_data = r.text.split(':Prediction_dates:')[-1] forecast_date = pysat.datetime.strptime(raw_data[3:14], '%Y %b %d') # times for output data times = pds.date_range(forecast_date, periods=3, freq='1D') # string data is the forecast value for the next three days raw_data = r.text.split('10cm_flux:')[-1] raw_data = raw_data.split('\n')[1] val1 = int(raw_data[24:27]) val2 = int(raw_data[38:41]) val3 = int(raw_data[52:]) # put data into nicer DataFrame data = pds.DataFrame([val1, val2, val3], index=times, columns=['f107']) # write out as a file data.to_csv(os.path.join(data_path, 'f107_forecast_' + date.strftime('%Y-%m-%d') + '.txt'), header=True) elif tag == '45day': import requests print('This routine can only download the current forecast, not ' + 'archived forecasts') # download webpage furl = 'https://services.swpc.noaa.gov/text/45-day-ap-forecast.txt' r = requests.get(furl) # parse text to get the date the prediction was generated date_str = r.text.split(':Issued: ')[-1].split(' UTC')[0] date = pysat.datetime.strptime(date_str, '%Y %b %d %H%M') # get to the forecast data raw_data = r.text.split('45-DAY AP FORECAST')[-1] # grab AP part raw_ap = raw_data.split('45-DAY F10.7 CM FLUX FORECAST')[0] # clean up raw_ap = raw_ap.split('\n')[1:-1] # f107 raw_f107 = raw_data.split('45-DAY F10.7 CM FLUX FORECAST')[-1] # clean up raw_f107 = raw_f107.split('\n')[1:-4] # parse the AP data ap_times, ap = parse_45day_block(raw_ap) # parse the F10.7 data f107_times, f107 = parse_45day_block(raw_f107) # collect into DataFrame data = pds.DataFrame(f107, index=f107_times, columns=['f107']) data['ap'] = ap # write out as a file data.to_csv(os.path.join(data_path, 'f107_45day_' + date.strftime('%Y-%m-%d') + '.txt'), header=True) return def parse_45day_block(block_lines): """ Parse the data blocks used in the 45-day Ap and F10.7 Flux Forecast file Parameters ---------- block_lines : (list) List of lines containing data in this data block Returns ------- dates : (list) List of dates for each date/data pair in this block values : (list) List of values for each date/data pair in this block """ # Initialize the output dates = list() values = list() # Cycle through each line in this block for line in block_lines: # Split the line on whitespace split_line = line.split() # Format the dates dates.extend([pysat.datetime.strptime(tt, "%d%b%y") for tt in split_line[::2]]) # Format the data values values.extend([int(vv) for vv in split_line[1::2]]) return dates, values def rewrite_daily_file(year, outfile, lines): """ Rewrite the SWPC Daily Solar Data files Parameters ---------- year : (int) Year of data file (format changes based on date) outfile : (str) Output filename lines : (str) String containing all output data (result of 'read') Returns ------- Void """ # Parse text to get the date the prediction was generated date_str = lines.split(':Issued: ')[-1].split('\n')[0] date = pysat.datetime.strptime(date_str, '%H%M UT %d %b %Y') # get to the solar index data if year > 2000: raw_data = lines.split('#---------------------------------')[-1] raw_data = raw_data.split('\n')[1:-1] optical = True else: raw_data = lines.split('# ')[-1] raw_data = raw_data.split('\n') optical = False if raw_data[0].find('Not Available') or year == 1994 \ else True istart = 7 if year < 2000 else 1 raw_data = raw_data[istart:-1] # parse the data solar_times, data_dict = parse_daily_solar_data(raw_data, year, optical) # collect into DataFrame data = pds.DataFrame(data_dict, index=solar_times, columns=data_dict.keys()) # write out as a file data.to_csv(outfile, header=True) return def parse_daily_solar_data(data_lines, year, optical): """ Parse the data in the SWPC daily solar index file Parameters ---------- data_lines : (list) List of lines containing data year : (list) Year of file optical : (boolean) Flag denoting whether or not optical data is available Returns ------- dates : (list) List of dates for each date/data pair in this block values : (dict) Dict of lists of values, where each key is the value name """ # Initialize the output dates = list() val_keys = ['f107', 'ssn', 'ss_area', 'new_reg', 'smf', 'goes_bgd_flux', 'c_flare', 'm_flare', 'x_flare', 'o1_flare', 'o2_flare', 'o3_flare'] optical_keys = ['o1_flare', 'o2_flare', 'o3_flare'] xray_keys = ['c_flare', 'm_flare', 'x_flare'] values = {kk: list() for kk in val_keys} # Cycle through each line in this file for line in data_lines: # Split the line on whitespace split_line = line.split() # Format the date dfmt = "%Y %m %d" if year > 1996 else "%d %b %y" dates.append(pysat.datetime.strptime(" ".join(split_line[0:3]), dfmt)) # Format the data values j = 0 for i, kk in enumerate(val_keys): if year == 1994 and kk == 'new_reg': # New regions only in files after 1994 val = -999 elif((year == 1994 and kk in xray_keys) or (not optical and kk in optical_keys)): # X-ray flares in files after 1994, optical flares come later val = -1 else: val = split_line[j + 3] j += 1 if kk != 'goes_bgd_flux': if val == "*": val = -999 if i < 5 else -1 else: val = int(val) values[kk].append(val) return dates, values def calc_f107a(f107_inst, f107_name='f107', f107a_name='f107a', min_pnts=41): """ Calculate the 81 day mean F10.7 Parameters ---------- f107_inst : (pysat.Instrument) pysat Instrument holding the F10.7 data f107_name : (str) Data column name for the F10.7 data (default='f107') f107a_name : (str) Data column name for the F10.7a data (default='f107a') min_pnts : (int) Minimum number of points required to calculate an average (default=41) Returns ------- Void : Updates f107_inst with F10.7a data Notes ----- Will not pad data on its own """ # Test to see that the input data is present if f107_name not in f107_inst.data.columns: raise ValueError("unknown input data column: " + f107_name) # Test to see that the output data does not already exist if f107a_name in f107_inst.data.columns: raise ValueError("output data column already exists: " + f107a_name) if f107_name in f107_inst.meta: fill_val = f107_inst.meta[f107_name][f107_inst.fill_label] else: fill_val = np.nan # Calculate the rolling mean. Since these values are centered but rolling # function doesn't allow temporal windows to be calculated this way, create # a hack for this. # # Ensure the data are evenly sampled at a daily frequency, since this is # how often F10.7 is calculated. f107_fill = f107_inst.data.resample('1D').fillna(method=None) # Replace the time index with an ordinal time_ind = f107_fill.index f107_fill['ord'] = pds.Series([tt.toordinal() for tt in time_ind], index=time_ind) f107_fill.set_index('ord', inplace=True) # Calculate the mean f107_fill[f107a_name] = f107_fill[f107_name].rolling(window=81, min_periods=min_pnts, center=True).mean() # Replace the ordinal index with the time f107_fill['time'] = pds.Series(time_ind, index=f107_fill.index) f107_fill.set_index('time', inplace=True) # Resample to the original frequency, if it is not equal to 1 day freq = pysat.utils.time.calc_freq(f107_inst.index) if freq != "86400S": # Resample to the desired frequency f107_fill = f107_fill.resample(freq).pad() # Save the output in a list f107a = list(f107_fill[f107a_name]) # Fill any dates that fall time_ind = pds.date_range(f107_fill.index[0], f107_inst.index[-1], freq=freq) for itime in time_ind[f107_fill.index.shape[0]:]: if (itime - f107_fill.index[-1]).total_seconds() < 86400.0: f107a.append(f107a[-1]) else: f107a.append(fill_val) # Redefine the Series f107_fill = pds.DataFrame({f107a_name: f107a}, index=time_ind) # There may be missing days in the output data, remove these if f107_inst.index.shape < f107_fill.index.shape: f107_fill = f107_fill.loc[f107_inst.index] # Save the data f107_inst[f107a_name] = f107_fill[f107a_name] # Update the metadata meta_dict = {f107_inst.units_label: 'SFU', f107_inst.name_label: 'F10.7a', f107_inst.desc_label: "81-day centered average of F10.7", f107_inst.plot_label: "F$_{10.7a}$", f107_inst.axis_label: "F$_{10.7a}$", f107_inst.scale_label: 'linear', f107_inst.min_label: 0.0, f107_inst.max_label: np.nan, f107_inst.fill_label: fill_val, f107_inst.notes_label: 'Calculated using data between ' + '{:} and {:}'.format(f107_inst.index[0], f107_inst.index[-1])} f107_inst.meta[f107a_name] = meta_dict return
bsd-3-clause
nwolek/LowkeyNW
source/projects/nw.phasorshift_tilde/nw.phasorshift_tilde.cpp
11696
/* ** nw.phasorshift~.c ** ** MSP object ** generates evenly shifted phase signals ** 2001/08/09 started by Nathan Wolek ** ** Copyright © 2001,2014 by Nathan Wolek ** License: http://opensource.org/licenses/BSD-3-Clause ** */ #include "c74_msp.h" using namespace c74::max; //#define DEBUG //enable debugging messages #define OBJECT_NAME "nw.phasorshift~" // name of the object /* for the assist method */ #define ASSIST_INLET 1 #define ASSIST_OUTLET 2 /* for interpolation flag */ #define INTERP_OFF 0 #define INTERP_ON 1 #define OUTLET_MAX 64 // maximum number of outlets specifiable #define OUTLET_MIN 2 // minimum number of outlets specifiable #define VEC_SIZE OUTLET_MAX + 4 // size of vector array passed to perform method static t_class *phasorshift_class; // required global pointer to this class /* structure definition for this object */ typedef struct _phasorShift { t_pxobject ps_obj; long ps_outletcount; float ps_currIndex[OUTLET_MAX]; float ps_freq; float ps_stepsize; short ps_inlet_connected; double ps_samp_rate; } t_phasorShift; /* method definitions for this object */ void phasorShift_setIndexArray(t_phasorShift *x); void *phasorShift_new(long outlets); void phasorShift_dsp64(t_phasorShift *x, t_object *dsp64, short *count, double samplerate, long maxvectorsize, long flags); void phasorShift_perform64(t_phasorShift *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long vectorsize, long flags, void *userparam); void phasorShift_float(t_phasorShift *x, double f); void phasorShift_int(t_phasorShift *x, long l); void phasorShift_assist(t_phasorShift *x, t_object *b, long msg, long arg, char *s); void phasorShift_getinfo(t_phasorShift *x); float allpassInterp(float *in_array, float index, float last_out, long buf_length); /******************************************************************************** void main(void) inputs: nothing description: called the first time the object is used in MAX environment; defines inlets, outlets and accepted messages returns: int ********************************************************************************/ int C74_EXPORT main(void) { t_class *c; c = class_new(OBJECT_NAME, (method)phasorShift_new, (method)dsp_free, (short)sizeof(t_phasorShift), 0L, A_DEFLONG, 0); class_dspinit(c); // add standard functions to class /* bind method "phasorShift_float" to the float message */ class_addmethod(c, (method)phasorShift_float, "float", A_FLOAT, 0); /* bind method "phasorShift_int" to the int message */ class_addmethod(c, (method)phasorShift_int, "int", A_LONG, 0); /* bind method "phasorShift_assist" to the assistance message */ class_addmethod(c, (method)phasorShift_assist, "assist", A_CANT, 0); /* bind method "phasorShift_getinfo" to the getinfo message */ class_addmethod(c, (method)phasorShift_getinfo, "getinfo", A_NOTHING, 0); /* bind method "phasorShift_dsp64" to the dsp64 message */ class_addmethod(c, (method)phasorShift_dsp64, "dsp64", A_CANT, 0); class_register(CLASS_BOX, c); // register the class w max phasorshift_class = c; #ifdef DEBUG #endif /* DEBUG */ return 0; } /******************************************************************************** void phasorShift_setIndexArray(t_phasorShift *x) inputs: x -- pointer to this object description: fills array with indexs for phasor output to outlets returns: nothing ********************************************************************************/ void phasorShift_setIndexArray(t_phasorShift *x) { float *tab = (float *)(x->ps_currIndex); // get pointer to ps_table float num_out = (float)(x->ps_outletcount); // local var for number of outlets long n = OUTLET_MAX; // set counter equal to ps_outletcount n += 1; while (--n) { // fill indexs with zero first, to be safe tab[n] = 0.0; } n = x->ps_outletcount; // set counter equal to ps_outletcount while (--n >= 0) { /* fill ps_table with pointer values */ tab[n] = (float)n / num_out; } #ifdef DEBUG object_post((t_object*)x, "pointers set"); #endif /* DEBUG */ } /******************************************************************************** void *phasorShift_new(double initial_pos) inputs: initial_pos -- object argument 1; initial position of pan description: called for each new instance of object in the MAX environment; defines inlets and outlets; fills ps_table; sets pointers returns: nothing ********************************************************************************/ void *phasorShift_new(long outlets) { long i; t_phasorShift *x = (t_phasorShift *) object_alloc((t_class*) phasorshift_class); // set outlets within limits x->ps_outletcount = outlets>OUTLET_MAX?OUTLET_MAX:outlets<OUTLET_MIN?OUTLET_MIN:outlets; dsp_setup((t_pxobject *)x, 1); // one inlet for (i = 0; i < x->ps_outletcount; i++) { outlet_new((t_pxobject *)x, "signal"); // create outlets } phasorShift_setIndexArray(x); // set the indexs x->ps_freq = 20.0; // default freq to 20.0 x->ps_obj.z_misc = Z_NO_INPLACE; #ifdef DEBUG object_post((t_object*)x, "new function was called"); #endif /* DEBUG */ /* return a pointer to the new object */ return (x); } /******************************************************************************** void phasorShift_dsp64() inputs: x -- pointer to this object dsp64 -- signal chain to which object belongs count -- array detailing number of signals attached to each inlet samplerate -- number of samples per second maxvectorsize -- sample frames per vector of audio flags -- description: called when 64 bit DSP call chain is built; adds object to signal flow returns: nothing ********************************************************************************/ void phasorShift_dsp64(t_phasorShift *x, t_object *dsp64, short *count, double samplerate, long maxvectorsize, long flags) { #ifdef DEBUG object_post((t_object*)x, "adding 64 bit perform method"); #endif /* DEBUG */ // check if inlets are connected at audio rate x->ps_inlet_connected = count[0]; // save other info to object vars x->ps_samp_rate = samplerate; // add the perform routine to the signal chain dsp_add64(dsp64, (t_object*)x, (t_perfroutine64)phasorShift_perform64, 0, NULL); } /******************************************************************************** void *phasorShift_perform64(t_phasorShift *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long vectorsize, long flags, void *userparam) inputs: x -- dsp64 -- ins -- numins -- outs -- numouts -- vectorsize -- flags -- userparam -- description: called at interrupt level to compute object's output at 64-bit returns: nothing ********************************************************************************/ void phasorShift_perform64(t_phasorShift *x, t_object *dsp64, double **ins, long numins, double **outs, long numouts, long vectorsize, long flags, void *userparam) { // local vars for outlets, interval, width, step size and index double *curr_out[OUTLET_MAX]; double curr_freq = x->ps_inlet_connected ? *ins[0] : x->ps_freq; double curr_step_size; float *currIndex = x->ps_currIndex; // TODO: upgrade to double later // local vars used for while loop double temp; long n, m; // fill local pointer array for outlets m = numouts; while(m--) { curr_out[m] = outs[m]; } // check constraints // NOT NECESSARY // then compute step size curr_step_size = curr_freq / x->ps_samp_rate; // update object variables x->ps_freq = curr_freq; x->ps_stepsize = curr_step_size; n = vectorsize; while (n--) { m = numouts; while (m--) { temp = (double)(currIndex[m]); // check bounds // while (temp < 0.0) temp += 1.0; while (temp >= 1.0) temp -= 1.0; *(curr_out[m]) = temp; // save to output temp += curr_step_size; // advance index currIndex[m] = (float)temp; // save next index (curr_out[m])++; // advance the outlet pointer } } } /******************************************************************************** void phasorShift_float(t_phasorShift *x, double f) inputs: x -- pointer to our object f -- value of float input description: handles floats sent to inlets; left inlet sets "ps_freq" variable; other inlets generate error message in max window returns: nothing ********************************************************************************/ void phasorShift_float(t_phasorShift *x, double f) { if (x->ps_obj.z_in == 0) // if right inlet { x->ps_freq = f; // save frequency input } else { object_post((t_object*)x, "that inlet does not accept floats"); } } /******************************************************************************** void phasorShift_int(t_phasorShift *x, long l) inputs: x -- pointer to our object l -- value of int input description: handles ints sent to inlets; left inlet sets "ps_freq" variable; other inlets generate error message in max window returns: nothing ********************************************************************************/ void phasorShift_int(t_phasorShift *x, long l) { if (x->ps_obj.z_in == 0) // if right inlet { x->ps_freq = (double) l; // save frequency input } else { object_post((t_object*)x, "that inlet does not accept floats"); } } /******************************************************************************** void phasorShift_assist(t_phasorShift *x, t_object *b, long msg, long arg, char *s) inputs: x -- pointer to our object b -- msg -- arg -- s -- description: method called when "assist" message is received; allows inlets and outlets to display assist messages as the mouse passes over them returns: nothing ********************************************************************************/ void phasorShift_assist(t_phasorShift *x, t_object *b, long msg, long arg, char *s) { char out_mess[30]; short which_outlet; short num_out = x->ps_outletcount; if (msg==ASSIST_INLET) { switch (arg) { case 0: strcpy(s, "(signal/float) phasor frequency"); break; } } else if (msg==ASSIST_OUTLET) { which_outlet = arg + 1; sprintf(out_mess, "(signal) phasor output %hd of %hd", which_outlet, num_out); strcpy(s, out_mess); } #ifdef DEBUG object_post((t_object*)x, "assist message displayed"); #endif /* DEBUG */ } /******************************************************************************** void phasorShift_getinfo(t_phasorShift *x) inputs: x -- pointer to our object description: method called when "getinfo" message is received; displays info about object and last update returns: nothing ********************************************************************************/ void phasorShift_getinfo(t_phasorShift *x) { object_post((t_object*)x, "%s object by Nathan Wolek", OBJECT_NAME); object_post((t_object*)x, "Last updated on %s - www.nathanwolek.com", __DATE__); }
bsd-3-clause
sheldon/epgp
LibItemUtils-1.0.lua
15193
-- This library provides an interface to query if an item can be -- use by a certain class. The API is as follows: -- -- CanClassUse(class, itemType): class is one of **** and itemType a localized itemType (http://www.wowwiki.com/ItemType). -- local MAJOR_VERSION = "LibItemUtils-1.0" local MINOR_VERSION = tonumber(("$Revision: $"):match("%d+")) or 0 local lib, oldMinor = LibStub:NewLibrary(MAJOR_VERSION, MINOR_VERSION) if not lib then return end local Debug = LibStub("LibDebug-1.0") -- Inventory types are localized on each client. For this we need -- LibBabble-Inventory to unlocalize the strings. local LBIR = LibStub("LibBabble-Inventory-3.0"):GetReverseLookupTable() local deformat = LibStub("LibDeformat-3.0") -- Make a frame for our repeating calls to GetItemInfo. lib.frame = lib.frame or CreateFrame("Frame", MAJOR_VERSION .. "_Frame") local frame = lib.frame frame:Hide() frame:SetScript('OnUpdate', nil) frame:UnregisterAllEvents() -- Use the GameTooltip or create a new one and initialize it -- Used to extract Class limitations for an item, upgraded ilvl, -- and binding type. lib.tooltip = lib.tooltip or CreateFrame("GameTooltip", MAJOR_VERSION .. "_Tooltip", frame, "GameTooltipTemplate") local tooltip = lib.tooltip local bindingFrame = getglobal(tooltip:GetName().."TextLeft2") local restrictedClassFrameNameFormat = tooltip:GetName().."TextLeft%d" tooltip:Hide(); ------------- -- OTHER ------------- --- Convert an itemlink to itemID -- @param itemlink of which you want the itemID from -- @returns number or nils function lib:ItemlinkToID(itemlink) if not itemlink then return nil end local itemID = strmatch(itemlink, 'item:(%d+)') if not itemID then return end return tonumber(itemID) end ------------- -- ITEM USAGE ------------- --[[ All item types we care about: Cloth = true, Leather = true, Mail = true, Plate = true, Shields = true, Bows = true, Crossbows = true, Daggers = true, ["Fist Weapons"] = true, Guns = true, ["One-Handed Axes"] = true, ["One-Handed Maces"] = true, ["One-Handed Swords"] = true, Polearms = true, Staves = true, ["Two-Handed Axes"] = true, ["Two-Handed Maces"] = true, ["Two-Handed Swords"] = true, Idols = true, Librams = true, Sigils = true, Thrown = true, Totems = true, Wands = true, --]] local disallowed = { DEATHKNIGHT = { Shields = true, Bows = true, Crossbows = true, Daggers = true, ["Fist Weapons"] = true, Guns = true, Polearms = true, Staves = true, Idols = true, Librams = true, Thrown = true, Totems = true, Wands = true, }, DRUID = { Mail = true, Plate = true, Shields = true, Bows = true, Crossbows = true, Guns = true, ["One-Handed Axes"] = true, ["One-Handed Swords"] = true, ["Two-Handed Axes"] = true, ["Two-Handed Swords"] = true, Librams = true, Sigils = true, Thrown = true, Totems = true, Wands = true, }, HUNTER = { Plate = true, Shields = true, ["One-Handed Maces"] = true, ["Two-Handed Maces"] = true, Idols = true, Librams = true, Sigils = true, Totems = true, Wands = true, }, MAGE = { Leather = true, Mail = true, Plate = true, Shields = true, Bows = true, Crossbows = true, ["Fist Weapons"] = true, Guns = true, ["One-Handed Axes"] = true, ["One-Handed Maces"] = true, Polearms = true, ["Two-Handed Axes"] = true, ["Two-Handed Maces"] = true, ["Two-Handed Swords"] = true, Idols = true, Librams = true, Sigils = true, Thrown = true, Totems = true, }, PALADIN = { Bows = true, Crossbows = true, ["Fist Weapons"] = true, Guns = true, Staves = true, Idols = true, Sigils = true, Thrown = true, Totems = true, Wands = true, }, PRIEST = { Leather = true, Mail = true, Plate = true, Shields = true, Bows = true, Crossbows = true, ["Fist Weapons"] = true, Guns = true, ["One-Handed Axes"] = true, ["One-Handed Swords"] = true, Polearms = true, ["Two-Handed Axes"] = true, ["Two-Handed Maces"] = true, ["Two-Handed Swords"] = true, Idols = true, Librams = true, Sigils = true, Thrown = true, Totems = true, }, ROGUE = { Mail = true, Plate = true, Shields = true, Polearms = true, Staves = true, ["Two-Handed Axes"] = true, ["Two-Handed Maces"] = true, ["Two-Handed Swords"] = true, Idols = true, Librams = true, Sigils = true, Totems = true, Wands = true, }, SHAMAN = { Plate = true, Bows = true, Crossbows = true, Guns = true, ["One-Handed Swords"] = true, Polearms = true, ["Two-Handed Swords"] = true, Idols = true, Librams = true, Sigils = true, Thrown = true, Wands = true, }, WARLOCK = { Leather = true, Mail = true, Plate = true, Shields = true, Bows = true, Crossbows = true, ["Fist Weapons"] = true, Guns = true, ["One-Handed Axes"] = true, ["One-Handed Maces"] = true, Polearms = true, ["Two-Handed Axes"] = true, ["Two-Handed Maces"] = true, ["Two-Handed Swords"] = true, Idols = true, Librams = true, Sigils = true, Thrown = true, Totems = true, }, WARRIOR = { Idols = true, Librams = true, Sigils = true, Totems = true, Wands = true, }, } function lib:ClassCanUse(class, item) local subType = select(7, GetItemInfo(item)) if not subType then return true end -- Check if this is a restricted class token. -- TODO(alkis): Possibly cache this check if performance is an issue. local link = select(2, GetItemInfo(item)) tooltip:SetOwner(UIParent, "ANCHOR_NONE") tooltip:SetHyperlink(link) -- lets see if we can find a 'Classes: Mage, Druid' string on the itemtooltip -- Only scanning line 2 is not enough, we need to scan all the lines for lineID = 1, tooltip:NumLines(), 1 do local line = _G[restrictedClassFrameNameFormat:format(lineID)] if line then local text = line:GetText() if text then local classList = deformat(text, ITEM_CLASSES_ALLOWED) if classList then tooltip:Hide() for _, restrictedClass in pairs({strsplit(',', classList)}) do restrictedClass = strtrim(strupper(restrictedClass)) restrictedClass = strupper(LOCALIZED_CLASS_NAMES_FEMALE[restrictedClass] or LOCALIZED_CLASS_NAMES_MALE[restrictedClass]) if class == restrictedClass then return true end end return false end end end end tooltip:Hide() -- Check if players can equip this item. subType = LBIR[subType] if disallowed[class][subType] then return false end return true end function lib:GetItemIlevel(item, fallback) tooltip:SetOwner(UIParent, "ANCHOR_NONE") tooltip:SetHyperlink(item) -- lets see if we can find a 'Classes: Mage, Druid' string on the itemtooltip -- Only scanning line 2 is not enough, we need to scan all the lines for lineID = 1, tooltip:NumLines(), 1 do local line = _G[restrictedClassFrameNameFormat:format(lineID)] if line then local text = line:GetText() if text then local item_level_pattern = ITEM_LEVEL:gsub("%%d", "(%%d+)") local ilvl = tonumber(text:match(item_level_pattern)) if ilvl then return ilvl end end end end return fallback end function lib:ClassCannotUse(class, item) return not self:ClassCanUse(class, item) end local function NewTableOrClear(t) if not t then return {} end wipe(t) return t end function lib:ClassesThatCanUse(item, t) t = NewTableOrClear(t) for class, _ in pairs(RAID_CLASS_COLORS) do if self:ClassCanUse(class, item) then table.insert(t, class) end end return t end function lib:ClassesThatCannotUse(item, t) t = NewTableOrClear(t) for class, _ in pairs(RAID_CLASS_COLORS) do if self:ClassCannotUse(class, item) then table.insert(t, class) end end return t end ----------------- -- ITEMS FOR SLOT ----------------- local slot_table = { INVTYPE_HEAD = {"HeadSlot", nil}, INVTYPE_NECK = {"NeckSlot", nil}, INVTYPE_SHOULDER = {"ShoulderSlot", nil}, INVTYPE_CLOAK = {"BackSlot", nil}, INVTYPE_CHEST = {"ChestSlot", nil}, INVTYPE_WRIST = {"WristSlot", nil}, INVTYPE_HAND = {"HandsSlot", nil}, INVTYPE_WAIST = {"WaistSlot", nil}, INVTYPE_LEGS = {"LegsSlot", nil}, INVTYPE_FEET = {"FeetSlot", nil}, INVTYPE_SHIELD = {"SecondaryHandSlot", nil}, INVTYPE_ROBE = {"ChestSlot", nil}, INVTYPE_2HWEAPON = {"MainHandSlot", "SecondaryHandSlot"}, INVTYPE_WEAPONMAINHAND = {"MainHandSlot", nil}, INVTYPE_WEAPONOFFHAND = {"SecondaryHandSlot", "MainHandSlot"}, INVTYPE_WEAPON = {"MainHandSlot","SecondaryHandSlot"}, INVTYPE_THROWN = {"RangedSlot", nil}, INVTYPE_RANGED = {"RangedSlot", nil}, INVTYPE_RANGEDRIGHT = {"RangedSlot", nil}, INVTYPE_FINGER = {"Finger0Slot", "Finger1Slot"}, INVTYPE_HOLDABLE = {"SecondaryHandSlot", "MainHandSlot"}, INVTYPE_TRINKET = {"Trinket0Slot", "Trinket1Slot"}, -- Hack for Tier 9 25M heroic tokens. -- TODO(alkis): Fix this to return more than 2 slots because these tokens -- can go in any of 5 slots. INVTYPE_CUSTOM_MULTISLOT_TIER = {"HeadSlot", "ChestSlot"} } function lib:ItemsForSlot(invtype, unit) local t = slot_table[invtype] if not t then return end local first, second = unpack(t) -- Translate to slot ids first = first and GetInventorySlotInfo(first) second = second and GetInventorySlotInfo(second) -- Translate to item links first = first and GetInventoryItemLink(unit or "player", first) second = second and GetInventoryItemLink(unit or "player", second) return first, second end ---------------- -- ITEM BINDINGS ---------------- -- binding is one of: ITEM_BIND_ON_PICKUP, ITEM_BIND_ON_EQUIP, -- ITEM_BIND_ON_USE, ITEM_BIND_TO_ACCOUNT function lib:IsBinding(binding, item) local link = select(2, GetItemInfo(item)) tooltip:SetOwner(UIParent, "ANCHOR_NONE") tooltip:SetHyperlink(link) if tooltip:NumLines() > 1 then local text = bindingFrame:GetText() if text then return text == binding end end tooltip:Hide() end function lib:IsBoP(item) return lib:IsBinding(ITEM_BIND_ON_PICKUP, item) end function lib:IsBoE(item) return lib:IsBinding(ITEM_BIND_ON_EQUIP, item) end -------------- -- ITEMCACHING -------------- -- Reuse or create a table to store the lookup queue in lib.itemQueue = lib.itemQueue or {} local itemQueue = lib.itemQueue --- Try to lookup the items on the itemQueue -- -- This will lookup all the items on the itemQueue, and if found it -- will call the callbacks and remove them. If they are not found it -- will retry once per second for a max of 30 seconds after the last -- callback was called, and after that it will give up. local timeout = 0 local ticker = 0 local function LookupItems(frame, elapsed) timeout = timeout + elapsed ticker = ticker + elapsed if timeout > 30 then Debug("Giving up, clearing itemQueue") for item, _ in pairs(itemQueue) do Debug("\t%s", item) end wipe(itemQueue) ticker = 0 frame:Hide() return end if ticker > 1 then ticker = 0 -- Go through all the items and check if they have data in the -- client cache. If the do call the saved functions and args. Debug("Checking for new items in the cache") for itemLink, itemData in pairs(itemQueue) do if GetItemInfo(itemLink) then -- If we found an item, reset the timeout. timeout = 0 itemQueue[itemLink] = nil for callback, args in pairs(itemData) do pcall(callback, unpack(args)) end else -- Otherwise set the hyperlink on a tooltip to make the cache -- fetch it. tooltip:SetHyperlink(itemLink) tooltip:Show() tooltip:Hide() end end end -- If we have no more items in the itemQueue to lookup, reset the -- timeout and hide the frame. if not next(itemQueue) then timeout = 0 ticker = 0 frame:Hide() end end frame:SetScript("OnUpdate", LookupItems) --- Try to cache an item and call the callback function when the item --- is available -- -- @param itemLink any itemLink in Hitem:1234 form -- @param callback function pointer to the callback function that -- should be called when the item is available -- @param ... a list of variables you would like to pass to the -- callback function. -- @return boolean true if the item has been registered successfully function lib:CacheItem(itemLink, callback, ...) -- Reset the timeout for the itemQueue timeout = 0 if type(itemLink) == 'number' then itemLink = format('item:%d', itemLink) end if type(callback) ~= "function" then error("Usage: CacheItem(itemLink, callback, [...]): 'callback' - function.", 2) end if not itemLink or not strmatch(itemLink, 'item:(%d+)') then error("Usage: CacheItem(itemLink, callback, [...]): 'itemLink' - not a valid itemLink (item:12345).", 2) end itemQueue[itemLink] = itemQueue[itemLink] or {} itemQueue[itemLink][callback] = {...} -- show the frame to start looking up items frame:Show() return true end ------------- -- UNIT TESTS ------------- local items = { 40558, -- Cloth 40539, -- Leather 40543, -- Mail 40592, -- Plate 40405, -- Cloak 40192, -- Off-Hand 40401, -- Shield 40387, -- Neck 40399, -- Ring 40532, -- Trinket 40342, -- Idol 40268, -- Libram 40322, -- Totem 40207, -- Sigil 40386, -- Dagger 40383, -- Fist Weapon 40402, -- One-Handed Axe 40395, -- One-Handed Mace 40396, -- One-Handed Sword 40497, -- Polearm 40388, -- Stave 40384, -- Two-Handed Axe 40406, -- Two-Handed Mace 40343, -- Two-Handed Sword 40265, -- Bow 40346, -- Crossbow 40385, -- Gun 40190, -- Thrown 40245, -- Wand 40626, -- Protector token 1234567890, -- Non existent item } function lib:DebugTest() for _, itemID in ipairs(items) do self:CacheItem(itemID, self.DebugTestItem, self, itemID) end for slot, _ in pairs(slot_table) do local first, second = self:ItemsForSlot(slot) if first then if second then Debug("%s: %s or %s", slot, tostring(first), tostring(second)) else Debug("%s: %s", slot, tostring(first)) end end end end local t = {} function lib:DebugTestItem(itemID) local link = select(2, GetItemInfo(itemID)) t = self:ClassesThatCanUse(itemID, t) Debug("Classes that can use %s: %s", link, table.concat(t, ' ')) t = self:ClassesThatCannotUse(itemID, t) Debug("Classes that cannot use %s: %s", link, table.concat(t, ' ')) Debug("IsBoP: %s, IsBoE: %s", tostring(self:IsBoP(itemID)), tostring(self:IsBoE(itemID))) end -- /script LibStub("LibItemUtils-1.0"):DebugTest() -- /script LibStub("LibItemUtils-1.0"):CacheItem(32386, function() end)
bsd-3-clause
cvmfs/cvmfs_services
internal/gateway/receiver/mock_receiver.go
861
package receiver import ( "context" "io" gw "github.com/cvmfs/gateway/internal/gateway" ) // MockReceiver is a mocked implementation of the Receiver interface, for testing // Can implement fault injection type MockReceiver struct { } // NewMockReceiver constructs a new MockReceiver object which implements the // Receiver interface func NewMockReceiver(ctx context.Context) (Receiver, error) { return &MockReceiver{}, nil } // Quit command func (r *MockReceiver) Quit() error { return nil } // Echo command func (r *MockReceiver) Echo() error { return nil } // SubmitPayload command func (r *MockReceiver) SubmitPayload(leasePath string, payload io.Reader, digest string, headerSize int) error { return nil } // Commit command func (r *MockReceiver) Commit(leasePath, oldRootHash, newRootHash string, tag gw.RepositoryTag) error { return nil }
bsd-3-clause
dbastin/donkey
src/java/prod/edge/org/apache/commons/io/FileUtilsStatic.java
862
package edge.org.apache.commons.io; import au.net.netstorm.boost.bullet.scalpel.core.Edge; import org.apache.commons.io.filefilter.IOFileFilter; import java.io.File; import java.util.Collection; import java.util.List; public interface FileUtilsStatic extends Edge { void cleanDirectory(File file); void copyFile(File copiedFile, File localFile); void copyFileToDirectory(File source, File target); void moveFileToDirectory(File source, File target, boolean createDir); void moveFile(File source, File target); String readFileToString(File file); long sizeOfDirectory(File dir); void writeStringToFile(File file, String s); Collection listFiles(File directory, IOFileFilter fileFilter, IOFileFilter dirFilter); List readLines(File file); byte[] readFileToByteArray(File file); void touch(File file); }
bsd-3-clause
Youxiang11/lvmeida
member/views/travel-fund/view.php
777
<?php use yii\helpers\Html; use yii\widgets\DetailView; /* @var $this yii\web\View */ /* @var $model member\models\IntegrationRecord */ $this->title = $model->travel_record_id; $this->params['breadcrumbs'][] = ['label' => Yii::t('app', '旅游积分'), 'url' => ['index']]; $this->params['breadcrumbs'][] = $this->title; ?> <div class="integration-record-view"> <h1><?= Html::encode('ID:' . $this->title) ?></h1> <?= DetailView::widget([ 'model' => $model, 'attributes' => [ 'travel_record_id', 'uid', 'product_id', 'action_typy', 'after', 'status', 'fund_amount', 'created_at:datetime', 'updated_at:datetime', ], ]) ?> </div>
bsd-3-clause
kurli/blink-crosswalk
Source/platform/heap/HeapTest.cpp
206271
/* * Copyright (C) 2013 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. */ #include "config.h" #include "platform/Task.h" #include "platform/heap/Handle.h" #include "platform/heap/Heap.h" #include "platform/heap/HeapLinkedStack.h" #include "platform/heap/HeapTerminatedArrayBuilder.h" #include "platform/heap/SafePoint.h" #include "platform/heap/ThreadState.h" #include "platform/heap/Visitor.h" #include "public/platform/Platform.h" #include "public/platform/WebTraceLocation.h" #include "wtf/HashTraits.h" #include "wtf/LinkedHashSet.h" #include <gtest/gtest.h> namespace blink { class IntWrapper : public GarbageCollectedFinalized<IntWrapper> { public: static IntWrapper* create(int x) { return new IntWrapper(x); } virtual ~IntWrapper() { ++s_destructorCalls; } static int s_destructorCalls; DEFINE_INLINE_TRACE() { } int value() const { return m_x; } bool operator==(const IntWrapper& other) const { return other.value() == value(); } unsigned hash() { return IntHash<int>::hash(m_x); } IntWrapper(int x) : m_x(x) { } private: IntWrapper(); int m_x; }; static_assert(WTF::NeedsTracing<IntWrapper>::value, "NeedsTracing macro failed to recognize trace method."); class ThreadMarker { public: ThreadMarker() : m_creatingThread(reinterpret_cast<ThreadState*>(0)), m_num(0) { } ThreadMarker(unsigned i) : m_creatingThread(ThreadState::current()), m_num(i) { } ThreadMarker(WTF::HashTableDeletedValueType deleted) : m_creatingThread(reinterpret_cast<ThreadState*>(-1)), m_num(0) { } ~ThreadMarker() { EXPECT_TRUE((m_creatingThread == ThreadState::current()) || (m_creatingThread == reinterpret_cast<ThreadState*>(0)) || (m_creatingThread == reinterpret_cast<ThreadState*>(-1))); } bool isHashTableDeletedValue() const { return m_creatingThread == reinterpret_cast<ThreadState*>(-1); } bool operator==(const ThreadMarker& other) const { return other.m_creatingThread == m_creatingThread && other.m_num == m_num; } ThreadState* m_creatingThread; unsigned m_num; }; struct ThreadMarkerHash { static unsigned hash(const ThreadMarker& key) { return static_cast<unsigned>(reinterpret_cast<uintptr_t>(key.m_creatingThread) + key.m_num); } static bool equal(const ThreadMarker& a, const ThreadMarker& b) { return a == b; } static const bool safeToCompareToEmptyOrDeleted = false; }; typedef std::pair<Member<IntWrapper>, WeakMember<IntWrapper>> StrongWeakPair; struct PairWithWeakHandling : public StrongWeakPair { ALLOW_ONLY_INLINE_ALLOCATION(); public: // Regular constructor. PairWithWeakHandling(IntWrapper* one, IntWrapper* two) : StrongWeakPair(one, two) { ASSERT(one); // We use null first field to indicate empty slots in the hash table. } // The HashTable (via the HashTrait) calls this constructor with a // placement new to mark slots in the hash table as being deleted. We will // never call trace or the destructor on these slots. We mark ourselves deleted // with a pointer to -1 in the first field. PairWithWeakHandling(WTF::HashTableDeletedValueType) : StrongWeakPair(reinterpret_cast<IntWrapper*>(-1), nullptr) { } // Used by the HashTable (via the HashTrait) to skip deleted slots in the // table. Recognizes objects that were 'constructed' using the above // constructor. bool isHashTableDeletedValue() const { return first == reinterpret_cast<IntWrapper*>(-1); } // Since we don't allocate independent objects of this type, we don't need // a regular trace method. Instead, we use a traceInCollection method. If // the entry should be deleted from the collection we return true and don't // trace the strong pointer. template<typename VisitorDispatcher> bool traceInCollection(VisitorDispatcher visitor, WTF::ShouldWeakPointersBeMarkedStrongly strongify) { visitor->traceInCollection(second, strongify); if (!visitor->isAlive(second)) return true; // FIXME: traceInCollection is also called from WeakProcessing to check if the entry is dead. // The below if avoids calling trace in that case by only calling trace when |first| is not yet marked. if (!visitor->isAlive(first)) visitor->trace(first); return false; } }; } namespace WTF { template<typename T> struct DefaultHash; template<> struct DefaultHash<blink::ThreadMarker> { typedef blink::ThreadMarkerHash Hash; }; // ThreadMarkerHash is the default hash for ThreadMarker template<> struct HashTraits<blink::ThreadMarker> : GenericHashTraits<blink::ThreadMarker> { static const bool emptyValueIsZero = true; static void constructDeletedValue(blink::ThreadMarker& slot, bool) { new (NotNull, &slot) blink::ThreadMarker(HashTableDeletedValue); } static bool isDeletedValue(const blink::ThreadMarker& slot) { return slot.isHashTableDeletedValue(); } }; // The hash algorithm for our custom pair class is just the standard double // hash for pairs. Note that this means you can't mutate either of the parts of // the pair while they are in the hash table, as that would change their hash // code and thus their preferred placement in the table. template<> struct DefaultHash<blink::PairWithWeakHandling> { typedef PairHash<blink::Member<blink::IntWrapper>, blink::WeakMember<blink::IntWrapper>> Hash; }; // Custom traits for the pair. These are weakness handling traits, which means // PairWithWeakHandling must implement the traceInCollection method. // In addition, these traits are concerned with the two magic values for the // object, that represent empty and deleted slots in the hash table. The // SimpleClassHashTraits allow empty slots in the table to be initialzed with // memset to zero, and we use -1 in the first part of the pair to represent // deleted slots. template<> struct HashTraits<blink::PairWithWeakHandling> : blink::WeakHandlingHashTraits<blink::PairWithWeakHandling> { static const bool hasIsEmptyValueFunction = true; static bool isEmptyValue(const blink::PairWithWeakHandling& value) { return !value.first; } static void constructDeletedValue(blink::PairWithWeakHandling& slot, bool) { new (NotNull, &slot) blink::PairWithWeakHandling(HashTableDeletedValue); } static bool isDeletedValue(const blink::PairWithWeakHandling& value) { return value.isHashTableDeletedValue(); } }; } namespace blink { class TestGCScope { public: explicit TestGCScope(ThreadState::StackState state) : m_state(ThreadState::current()) , m_safePointScope(state) , m_parkedAllThreads(false) { m_state->checkThread(); if (LIKELY(ThreadState::stopThreads())) { Heap::preGC(); m_parkedAllThreads = true; } } bool allThreadsParked() { return m_parkedAllThreads; } ~TestGCScope() { // Only cleanup if we parked all threads in which case the GC happened // and we need to resume the other threads. if (LIKELY(m_parkedAllThreads)) { Heap::postGC(ThreadState::GCWithSweep); ThreadState::resumeThreads(); } } private: ThreadState* m_state; SafePointScope m_safePointScope; bool m_parkedAllThreads; // False if we fail to park all threads }; #define DEFINE_VISITOR_METHODS(Type) \ virtual void mark(const Type* object, TraceCallback callback) override \ { \ if (object) \ m_count++; \ } \ virtual bool isMarked(const Type*) override { return false; } \ virtual bool ensureMarked(const Type* objectPointer) override \ { \ return ensureMarked(objectPointer); \ } class CountingVisitor : public Visitor { public: CountingVisitor() : Visitor(Visitor::GenericVisitorType) , m_count(0) { configureEagerTraceLimit(); } virtual void mark(const void* object, TraceCallback) override { if (object) m_count++; } virtual void markHeader(HeapObjectHeader* header, TraceCallback callback) override { ASSERT(header->payload()); m_count++; } virtual void registerDelayedMarkNoTracing(const void*) override { } virtual void registerWeakMembers(const void*, const void*, WeakPointerCallback) override { } virtual void registerWeakTable(const void*, EphemeronCallback, EphemeronCallback) override { } #if ENABLE(ASSERT) virtual bool weakTableRegistered(const void*) override { return false; } #endif virtual void registerWeakCellWithCallback(void**, WeakPointerCallback) override { } virtual bool isMarked(const void*) override { return false; } virtual bool ensureMarked(const void* objectPointer) override { if (!objectPointer || isMarked(objectPointer)) return false; markNoTracing(objectPointer); return true; } size_t count() { return m_count; } void reset() { m_count = 0; } private: size_t m_count; }; #undef DEFINE_VISITOR_METHODS class SimpleObject : public GarbageCollected<SimpleObject> { public: static SimpleObject* create() { return new SimpleObject(); } DEFINE_INLINE_TRACE() { } char getPayload(int i) { return payload[i]; } // This virtual method is unused but it is here to make sure // that this object has a vtable. This object is used // as the super class for objects that also have garbage // collected mixins and having a virtual here makes sure // that adjustment is needed both for marking and for isAlive // checks. virtual void virtualMethod() { } protected: SimpleObject() { } char payload[64]; }; class HeapTestSuperClass : public GarbageCollectedFinalized<HeapTestSuperClass> { public: static HeapTestSuperClass* create() { return new HeapTestSuperClass(); } virtual ~HeapTestSuperClass() { ++s_destructorCalls; } static int s_destructorCalls; DEFINE_INLINE_TRACE() { } protected: HeapTestSuperClass() { } }; int HeapTestSuperClass::s_destructorCalls = 0; class HeapTestOtherSuperClass { public: int payload; }; static const size_t classMagic = 0xABCDDBCA; class HeapTestSubClass : public HeapTestOtherSuperClass, public HeapTestSuperClass { public: static HeapTestSubClass* create() { return new HeapTestSubClass(); } virtual ~HeapTestSubClass() { EXPECT_EQ(classMagic, m_magic); ++s_destructorCalls; } static int s_destructorCalls; private: HeapTestSubClass() : m_magic(classMagic) { } const size_t m_magic; }; int HeapTestSubClass::s_destructorCalls = 0; class HeapAllocatedArray : public GarbageCollected<HeapAllocatedArray> { public: HeapAllocatedArray() { for (int i = 0; i < s_arraySize; ++i) { m_array[i] = i % 128; } } int8_t at(size_t i) { return m_array[i]; } DEFINE_INLINE_TRACE() { } private: static const int s_arraySize = 1000; int8_t m_array[s_arraySize]; }; // Do several GCs to make sure that later GCs don't free up old memory from // previously run tests in this process. static void clearOutOldGarbage() { while (true) { size_t used = Heap::objectPayloadSizeForTesting(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); if (Heap::objectPayloadSizeForTesting() >= used) break; } } class OffHeapInt : public RefCounted<OffHeapInt> { public: static RefPtr<OffHeapInt> create(int x) { return adoptRef(new OffHeapInt(x)); } virtual ~OffHeapInt() { ++s_destructorCalls; } static int s_destructorCalls; int value() const { return m_x; } bool operator==(const OffHeapInt& other) const { return other.value() == value(); } unsigned hash() { return IntHash<int>::hash(m_x); } void voidFunction() { } protected: OffHeapInt(int x) : m_x(x) { } private: OffHeapInt(); int m_x; }; int IntWrapper::s_destructorCalls = 0; int OffHeapInt::s_destructorCalls = 0; class ThreadedTesterBase { protected: static void test(ThreadedTesterBase* tester) { Vector<OwnPtr<WebThread>, numberOfThreads> m_threads; for (int i = 0; i < numberOfThreads; i++) { m_threads.append(adoptPtr(Platform::current()->createThread("blink gc testing thread"))); m_threads.last()->postTask(FROM_HERE, new Task(WTF::bind(threadFunc, tester))); } while (tester->m_threadsToFinish) { SafePointScope scope(ThreadState::NoHeapPointersOnStack); Platform::current()->yieldCurrentThread(); } delete tester; } virtual void runThread() = 0; protected: static const int numberOfThreads = 10; static const int gcPerThread = 5; static const int numberOfAllocations = 50; ThreadedTesterBase() : m_gcCount(0), m_threadsToFinish(numberOfThreads) { } virtual ~ThreadedTesterBase() { } inline bool done() const { return m_gcCount >= numberOfThreads * gcPerThread; } volatile int m_gcCount; volatile int m_threadsToFinish; private: static void threadFunc(void* data) { reinterpret_cast<ThreadedTesterBase*>(data)->runThread(); } }; class ThreadedHeapTester : public ThreadedTesterBase { public: static void test() { ThreadedTesterBase::test(new ThreadedHeapTester); } protected: virtual void runThread() override { ThreadState::attach(); int gcCount = 0; while (!done()) { ThreadState::current()->safePoint(ThreadState::NoHeapPointersOnStack); { Persistent<IntWrapper> wrapper; typedef Persistent<IntWrapper, GlobalPersistents> GlobalIntWrapperPersistent; OwnPtr<GlobalIntWrapperPersistent> globalPersistent = adoptPtr(new GlobalIntWrapperPersistent(IntWrapper::create(0x0ed0cabb))); for (int i = 0; i < numberOfAllocations; i++) { wrapper = IntWrapper::create(0x0bbac0de); if (!(i % 10)) { globalPersistent = adoptPtr(new GlobalIntWrapperPersistent(IntWrapper::create(0x0ed0cabb))); } SafePointScope scope(ThreadState::NoHeapPointersOnStack); Platform::current()->yieldCurrentThread(); } if (gcCount < gcPerThread) { Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); gcCount++; atomicIncrement(&m_gcCount); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(wrapper->value(), 0x0bbac0de); EXPECT_EQ((*globalPersistent)->value(), 0x0ed0cabb); } SafePointScope scope(ThreadState::NoHeapPointersOnStack); Platform::current()->yieldCurrentThread(); } ThreadState::detach(); atomicDecrement(&m_threadsToFinish); } }; class ThreadedWeaknessTester : public ThreadedTesterBase { public: static void test() { ThreadedTesterBase::test(new ThreadedWeaknessTester); } private: virtual void runThread() override { ThreadState::attach(); int gcCount = 0; while (!done()) { ThreadState::current()->safePoint(ThreadState::NoHeapPointersOnStack); { Persistent<HeapHashMap<ThreadMarker, WeakMember<IntWrapper>>> weakMap = new HeapHashMap<ThreadMarker, WeakMember<IntWrapper>>; PersistentHeapHashMap<ThreadMarker, WeakMember<IntWrapper>> weakMap2; for (int i = 0; i < numberOfAllocations; i++) { weakMap->add(static_cast<unsigned>(i), IntWrapper::create(0)); weakMap2.add(static_cast<unsigned>(i), IntWrapper::create(0)); SafePointScope scope(ThreadState::NoHeapPointersOnStack); Platform::current()->yieldCurrentThread(); } if (gcCount < gcPerThread) { Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); gcCount++; atomicIncrement(&m_gcCount); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(weakMap->isEmpty()); EXPECT_TRUE(weakMap2.isEmpty()); } SafePointScope scope(ThreadState::NoHeapPointersOnStack); Platform::current()->yieldCurrentThread(); } ThreadState::detach(); atomicDecrement(&m_threadsToFinish); } }; class ThreadPersistentHeapTester : public ThreadedTesterBase { public: static void test() { ThreadedTesterBase::test(new ThreadPersistentHeapTester); } protected: class Local final : public GarbageCollected<Local> { public: Local() { } DEFINE_INLINE_TRACE() { } }; class BookEnd; class PersistentStore { public: static PersistentStore* create(int count, int* gcCount, BookEnd* bookend) { return new PersistentStore(count, gcCount, bookend); } void advance() { (*m_gcCount)++; m_store.removeLast(); // Remove reference to BookEnd when there are no Persistent<Local>s left. // The BookEnd object will then be swept out at the next GC, and pre-finalized, // causing this PersistentStore instance to be destructed, along with // the Persistent<BookEnd>. It being the very last Persistent<>, causing the // GC loop in ThreadState::detach() to terminate. if (!m_store.size()) m_bookend = nullptr; } private: PersistentStore(int count, int* gcCount, BookEnd* bookend) { m_gcCount = gcCount; m_bookend = bookend; for (int i = 0; i < count; ++i) m_store.append(Persistent<ThreadPersistentHeapTester::Local>(new ThreadPersistentHeapTester::Local())); } Vector<Persistent<Local>> m_store; Persistent<BookEnd> m_bookend; int* m_gcCount; }; class BookEnd final : public GarbageCollected<BookEnd> { USING_PRE_FINALIZER(BookEnd, dispose); public: BookEnd() : m_store(nullptr) { ThreadState::current()->registerPreFinalizer(*this); } void initialize(PersistentStore* store) { m_store = store; } void dispose() { delete m_store; } DEFINE_INLINE_TRACE() { ASSERT(m_store); m_store->advance(); } private: PersistentStore* m_store; }; virtual void runThread() override { ThreadState::attach(); const int iterations = 5; int gcCount = 0; BookEnd* bookend = new BookEnd(); PersistentStore* store = PersistentStore::create(iterations, &gcCount, bookend); bookend->initialize(store); bookend = nullptr; store = nullptr; // Upon thread detach, GCs will run until all persistents have been // released. We verify that the draining of persistents proceeds // as expected by dropping one Persistent<> per GC until there // are none left. ThreadState::detach(); EXPECT_EQ(iterations, gcCount); atomicDecrement(&m_threadsToFinish); } }; // The accounting for memory includes the memory used by rounding up object // sizes. This is done in a different way on 32 bit and 64 bit, so we have to // have some slack in the tests. template<typename T> void CheckWithSlack(T expected, T actual, int slack) { EXPECT_LE(expected, actual); EXPECT_GE((intptr_t)expected + slack, (intptr_t)actual); } class TraceCounter : public GarbageCollectedFinalized<TraceCounter> { public: static TraceCounter* create() { return new TraceCounter(); } void trace(Visitor*) { m_traceCount++; } int traceCount() { return m_traceCount; } private: TraceCounter() : m_traceCount(0) { } int m_traceCount; }; class ClassWithMember : public GarbageCollected<ClassWithMember> { public: static ClassWithMember* create() { return new ClassWithMember(); } DEFINE_INLINE_TRACE() { EXPECT_TRUE(visitor->isMarked(this)); if (!traceCount()) EXPECT_FALSE(visitor->isMarked(m_traceCounter)); else EXPECT_TRUE(visitor->isMarked(m_traceCounter)); visitor->trace(m_traceCounter); } int traceCount() { return m_traceCounter->traceCount(); } private: ClassWithMember() : m_traceCounter(TraceCounter::create()) { } Member<TraceCounter> m_traceCounter; }; class SimpleFinalizedObject : public GarbageCollectedFinalized<SimpleFinalizedObject> { public: static SimpleFinalizedObject* create() { return new SimpleFinalizedObject(); } ~SimpleFinalizedObject() { ++s_destructorCalls; } static int s_destructorCalls; DEFINE_INLINE_TRACE() { } private: SimpleFinalizedObject() { } }; int SimpleFinalizedObject::s_destructorCalls = 0; class IntNode : public GarbageCollected<IntNode> { public: static IntNode* create(int i) { return new IntNode(i); } DEFINE_INLINE_TRACE() { } int value() { return m_value; } private: IntNode(int i) : m_value(i) { } int m_value; }; // IntNode is used to test typed heap allocation. Instead of // redefining blink::Node to our test version, we keep it separate // so as to avoid possible warnings about linker duplicates. // Provide a HeapIndexTrait<> specialization to assign the test // object to Node's typed heap instead. // // FIXME: untangling the heap unit tests from Blink would simplify // and avoid running into this problem - http://crbug.com/425381 template<> struct HeapIndexTrait<IntNode> { static int index(size_t) { return NodeHeapIndex; } }; class Bar : public GarbageCollectedFinalized<Bar> { public: static Bar* create() { return new Bar(); } void finalizeGarbageCollectedObject() { EXPECT_TRUE(m_magic == magic); m_magic = 0; s_live--; } bool hasBeenFinalized() const { return !m_magic; } DEFINE_INLINE_VIRTUAL_TRACE() { } static unsigned s_live; protected: static const int magic = 1337; int m_magic; Bar() : m_magic(magic) { s_live++; } }; WILL_NOT_BE_EAGERLY_TRACED(Bar); unsigned Bar::s_live = 0; class Baz : public GarbageCollected<Baz> { public: static Baz* create(Bar* bar) { return new Baz(bar); } DEFINE_INLINE_TRACE() { visitor->trace(m_bar); } void clear() { m_bar.release(); } // willFinalize is called by FinalizationObserver. void willFinalize() { EXPECT_TRUE(!m_bar->hasBeenFinalized()); } private: explicit Baz(Bar* bar) : m_bar(bar) { } Member<Bar> m_bar; }; class Foo : public Bar { public: static Foo* create(Bar* bar) { return new Foo(bar); } static Foo* create(Foo* foo) { return new Foo(foo); } DEFINE_INLINE_VIRTUAL_TRACE() { if (m_pointsToFoo) visitor->mark(static_cast<Foo*>(m_bar)); else visitor->mark(m_bar); } private: Foo(Bar* bar) : Bar() , m_bar(bar) , m_pointsToFoo(false) { } Foo(Foo* foo) : Bar() , m_bar(foo) , m_pointsToFoo(true) { } Bar* m_bar; bool m_pointsToFoo; }; class Bars : public Bar { public: static Bars* create() { return new Bars(); } DEFINE_INLINE_VIRTUAL_TRACE() { for (unsigned i = 0; i < m_width; i++) visitor->trace(m_bars[i]); } unsigned getWidth() const { return m_width; } static const unsigned width = 7500; private: Bars() : m_width(0) { for (unsigned i = 0; i < width; i++) { m_bars[i] = Bar::create(); m_width++; } } unsigned m_width; Member<Bar> m_bars[width]; }; class ConstructorAllocation : public GarbageCollected<ConstructorAllocation> { public: static ConstructorAllocation* create() { return new ConstructorAllocation(); } DEFINE_INLINE_TRACE() { visitor->trace(m_intWrapper); } private: ConstructorAllocation() { m_intWrapper = IntWrapper::create(42); } Member<IntWrapper> m_intWrapper; }; class LargeHeapObject : public GarbageCollectedFinalized<LargeHeapObject> { public: ~LargeHeapObject() { s_destructorCalls++; } static LargeHeapObject* create() { return new LargeHeapObject(); } char get(size_t i) { return m_data[i]; } void set(size_t i, char c) { m_data[i] = c; } size_t length() { return s_length; } DEFINE_INLINE_TRACE() { visitor->trace(m_intWrapper); } static int s_destructorCalls; private: static const size_t s_length = 1024 * 1024; LargeHeapObject() { m_intWrapper = IntWrapper::create(23); } Member<IntWrapper> m_intWrapper; char m_data[s_length]; }; int LargeHeapObject::s_destructorCalls = 0; class RefCountedAndGarbageCollected : public RefCountedGarbageCollected<RefCountedAndGarbageCollected> { public: static RefCountedAndGarbageCollected* create() { return new RefCountedAndGarbageCollected(); } ~RefCountedAndGarbageCollected() { ++s_destructorCalls; } // These are here with their default implementations so you can break in // them in the debugger. void ref() { RefCountedGarbageCollected<RefCountedAndGarbageCollected>::ref(); } void deref() { RefCountedGarbageCollected<RefCountedAndGarbageCollected>::deref(); } DEFINE_INLINE_TRACE() { } static int s_destructorCalls; private: RefCountedAndGarbageCollected() { } }; int RefCountedAndGarbageCollected::s_destructorCalls = 0; class RefCountedAndGarbageCollected2 : public HeapTestOtherSuperClass, public RefCountedGarbageCollected<RefCountedAndGarbageCollected2> { public: static RefCountedAndGarbageCollected2* create() { return new RefCountedAndGarbageCollected2(); } ~RefCountedAndGarbageCollected2() { ++s_destructorCalls; } DEFINE_INLINE_TRACE() { } static int s_destructorCalls; private: RefCountedAndGarbageCollected2() { } }; int RefCountedAndGarbageCollected2::s_destructorCalls = 0; #define DEFINE_VISITOR_METHODS(Type) \ virtual void mark(const Type* object, TraceCallback callback) override \ { \ mark(object); \ } \ class RefCountedGarbageCollectedVisitor : public CountingVisitor { public: RefCountedGarbageCollectedVisitor(int expected, void** objects) : m_count(0) , m_expectedCount(expected) , m_expectedObjects(objects) { } void mark(const void* ptr) { markNoTrace(ptr); } virtual void markNoTrace(const void* ptr) { if (!ptr) return; if (m_count < m_expectedCount) EXPECT_TRUE(expectedObject(ptr)); else EXPECT_FALSE(expectedObject(ptr)); m_count++; } virtual void mark(const void* ptr, TraceCallback) override { mark(ptr); } virtual void markHeader(HeapObjectHeader* header, TraceCallback callback) override { mark(header->payload()); } bool validate() { return m_count >= m_expectedCount; } void reset() { m_count = 0; } private: bool expectedObject(const void* ptr) { for (int i = 0; i < m_expectedCount; i++) { if (m_expectedObjects[i] == ptr) return true; } return false; } int m_count; int m_expectedCount; void** m_expectedObjects; }; #undef DEFINE_VISITOR_METHODS class Weak : public Bar { public: static Weak* create(Bar* strong, Bar* weak) { return new Weak(strong, weak); } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_strongBar); visitor->registerWeakMembers(this, zapWeakMembers); } static void zapWeakMembers(Visitor* visitor, void* self) { reinterpret_cast<Weak*>(self)->zapWeakMembers(visitor); } bool strongIsThere() { return !!m_strongBar; } bool weakIsThere() { return !!m_weakBar; } private: Weak(Bar* strongBar, Bar* weakBar) : Bar() , m_strongBar(strongBar) , m_weakBar(weakBar) { } void zapWeakMembers(Visitor* visitor) { if (!visitor->isAlive(m_weakBar)) m_weakBar = 0; } Member<Bar> m_strongBar; Bar* m_weakBar; }; class WithWeakMember : public Bar { public: static WithWeakMember* create(Bar* strong, Bar* weak) { return new WithWeakMember(strong, weak); } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_strongBar); visitor->trace(m_weakBar); } bool strongIsThere() { return !!m_strongBar; } bool weakIsThere() { return !!m_weakBar; } private: WithWeakMember(Bar* strongBar, Bar* weakBar) : Bar() , m_strongBar(strongBar) , m_weakBar(weakBar) { } Member<Bar> m_strongBar; WeakMember<Bar> m_weakBar; }; class Observable : public GarbageCollectedFinalized<Observable> { USING_PRE_FINALIZER(Observable, willFinalize); public: static Observable* create(Bar* bar) { return new Observable(bar); } ~Observable() { m_wasDestructed = true; } DEFINE_INLINE_TRACE() { visitor->trace(m_bar); } // willFinalize is called by FinalizationObserver. willFinalize can touch // other on-heap objects. void willFinalize() { EXPECT_FALSE(m_wasDestructed); EXPECT_FALSE(m_bar->hasBeenFinalized()); s_willFinalizeWasCalled = true; } static bool s_willFinalizeWasCalled; private: explicit Observable(Bar* bar) : m_bar(bar) , m_wasDestructed(false) { } Member<Bar> m_bar; bool m_wasDestructed; }; bool Observable::s_willFinalizeWasCalled = false; class ObservableWithPreFinalizer : public GarbageCollected<ObservableWithPreFinalizer> { USING_PRE_FINALIZER(ObservableWithPreFinalizer, dispose); public: static ObservableWithPreFinalizer* create() { return new ObservableWithPreFinalizer(); } ~ObservableWithPreFinalizer() { m_wasDestructed = true; } DEFINE_INLINE_TRACE() { } void dispose() { ThreadState::current()->unregisterPreFinalizer(*this); EXPECT_FALSE(m_wasDestructed); s_disposeWasCalled = true; } static bool s_disposeWasCalled; private: explicit ObservableWithPreFinalizer() : m_wasDestructed(false) { ThreadState::current()->registerPreFinalizer(*this); } bool m_wasDestructed; }; bool ObservableWithPreFinalizer::s_disposeWasCalled = false; template <typename T> class FinalizationObserver : public GarbageCollected<FinalizationObserver<T>> { public: static FinalizationObserver* create(T* data) { return new FinalizationObserver(data); } bool didCallWillFinalize() const { return m_didCallWillFinalize; } DEFINE_INLINE_TRACE() { visitor->registerWeakMembers(this, zapWeakMembers); } private: FinalizationObserver(T* data) : m_data(data) , m_didCallWillFinalize(false) { } static void zapWeakMembers(Visitor* visitor, void* self) { FinalizationObserver* o = reinterpret_cast<FinalizationObserver*>(self); if (o->m_data && !visitor->isAlive(o->m_data)) { o->m_data->willFinalize(); o->m_data = nullptr; o->m_didCallWillFinalize = true; } } WeakMember<T> m_data; bool m_didCallWillFinalize; }; class FinalizationObserverWithHashMap { public: typedef HeapHashMap<WeakMember<Observable>, OwnPtr<FinalizationObserverWithHashMap>> ObserverMap; explicit FinalizationObserverWithHashMap(Observable& target) : m_target(target) { } ~FinalizationObserverWithHashMap() { m_target.willFinalize(); s_didCallWillFinalize = true; } static ObserverMap& observe(Observable& target) { ObserverMap& map = observers(); ObserverMap::AddResult result = map.add(&target, nullptr); if (result.isNewEntry) result.storedValue->value = adoptPtr(new FinalizationObserverWithHashMap(target)); else ASSERT(result.storedValue->value); return map; } static void clearObservers() { delete s_observerMap; s_observerMap = nullptr; } static bool s_didCallWillFinalize; private: static ObserverMap& observers() { if (!s_observerMap) s_observerMap = new Persistent<ObserverMap>(new ObserverMap()); return **s_observerMap; } Observable& m_target; static Persistent<ObserverMap>* s_observerMap; }; bool FinalizationObserverWithHashMap::s_didCallWillFinalize = false; Persistent<FinalizationObserverWithHashMap::ObserverMap>* FinalizationObserverWithHashMap::s_observerMap; class SuperClass; class PointsBack : public RefCountedWillBeGarbageCollectedFinalized<PointsBack> { public: static PassRefPtrWillBeRawPtr<PointsBack> create() { return adoptRefWillBeNoop(new PointsBack()); } ~PointsBack() { --s_aliveCount; } void setBackPointer(SuperClass* backPointer) { m_backPointer = backPointer; } SuperClass* backPointer() const { return m_backPointer; } DEFINE_INLINE_TRACE() { visitor->trace(m_backPointer); } static int s_aliveCount; private: PointsBack() : m_backPointer(nullptr) { ++s_aliveCount; } RawPtrWillBeWeakMember<SuperClass> m_backPointer; }; int PointsBack::s_aliveCount = 0; class SuperClass : public RefCountedWillBeGarbageCollectedFinalized<SuperClass> { public: static PassRefPtrWillBeRawPtr<SuperClass> create(PassRefPtrWillBeRawPtr<PointsBack> pointsBack) { return adoptRefWillBeNoop(new SuperClass(pointsBack)); } virtual ~SuperClass() { #if !ENABLE(OILPAN) m_pointsBack->setBackPointer(0); #endif --s_aliveCount; } void doStuff(PassRefPtrWillBeRawPtr<SuperClass> targetPass, PointsBack* pointsBack, int superClassCount) { RefPtrWillBeRawPtr<SuperClass> target = targetPass; Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(pointsBack, target->pointsBack()); EXPECT_EQ(superClassCount, SuperClass::s_aliveCount); } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_pointsBack); } PointsBack* pointsBack() const { return m_pointsBack.get(); } static int s_aliveCount; protected: explicit SuperClass(PassRefPtrWillBeRawPtr<PointsBack> pointsBack) : m_pointsBack(pointsBack) { m_pointsBack->setBackPointer(this); ++s_aliveCount; } private: RefPtrWillBeMember<PointsBack> m_pointsBack; }; int SuperClass::s_aliveCount = 0; class SubData : public NoBaseWillBeGarbageCollectedFinalized<SubData> { public: SubData() { ++s_aliveCount; } ~SubData() { --s_aliveCount; } DEFINE_INLINE_TRACE() { } static int s_aliveCount; }; int SubData::s_aliveCount = 0; class SubClass : public SuperClass { public: static PassRefPtrWillBeRawPtr<SubClass> create(PassRefPtrWillBeRawPtr<PointsBack> pointsBack) { return adoptRefWillBeNoop(new SubClass(pointsBack)); } virtual ~SubClass() { --s_aliveCount; } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_data); SuperClass::trace(visitor); } static int s_aliveCount; private: explicit SubClass(PassRefPtrWillBeRawPtr<PointsBack> pointsBack) : SuperClass(pointsBack) , m_data(adoptPtrWillBeNoop(new SubData())) { ++s_aliveCount; } private: OwnPtrWillBeMember<SubData> m_data; }; int SubClass::s_aliveCount = 0; class TransitionRefCounted : public RefCountedWillBeRefCountedGarbageCollected<TransitionRefCounted> { public: static PassRefPtrWillBeRawPtr<TransitionRefCounted> create() { return adoptRefWillBeNoop(new TransitionRefCounted()); } ~TransitionRefCounted() { --s_aliveCount; } DEFINE_INLINE_TRACE() { } static int s_aliveCount; private: TransitionRefCounted() { ++s_aliveCount; } }; int TransitionRefCounted::s_aliveCount = 0; class Mixin : public GarbageCollectedMixin { public: DEFINE_INLINE_VIRTUAL_TRACE() { } virtual char getPayload(int i) { return m_padding[i]; } protected: int m_padding[8]; }; class UseMixin : public SimpleObject, public Mixin { USING_GARBAGE_COLLECTED_MIXIN(UseMixin) public: static UseMixin* create() { return new UseMixin(); } static int s_traceCount; DEFINE_INLINE_VIRTUAL_TRACE() { SimpleObject::trace(visitor); Mixin::trace(visitor); ++s_traceCount; } private: UseMixin() { s_traceCount = 0; } }; int UseMixin::s_traceCount = 0; class VectorObject { ALLOW_ONLY_INLINE_ALLOCATION(); public: VectorObject() { m_value = SimpleFinalizedObject::create(); } DEFINE_INLINE_TRACE() { visitor->trace(m_value); } private: Member<SimpleFinalizedObject> m_value; }; class VectorObjectInheritedTrace : public VectorObject { }; class VectorObjectNoTrace { ALLOW_ONLY_INLINE_ALLOCATION(); public: VectorObjectNoTrace() { m_value = SimpleFinalizedObject::create(); } private: Member<SimpleFinalizedObject> m_value; }; class TerminatedArrayItem { ALLOW_ONLY_INLINE_ALLOCATION(); public: TerminatedArrayItem(IntWrapper* payload) : m_payload(payload), m_isLast(false) { } DEFINE_INLINE_TRACE() { visitor->trace(m_payload); } bool isLastInArray() const { return m_isLast; } void setLastInArray(bool value) { m_isLast = value; } IntWrapper* payload() const { return m_payload; } private: Member<IntWrapper> m_payload; bool m_isLast; }; } // namespace blink WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(blink::VectorObject); WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(blink::VectorObjectInheritedTrace); WTF_ALLOW_MOVE_INIT_AND_COMPARE_WITH_MEM_FUNCTIONS(blink::VectorObjectNoTrace); namespace blink { class OneKiloByteObject : public GarbageCollectedFinalized<OneKiloByteObject> { public: ~OneKiloByteObject() { s_destructorCalls++; } char* data() { return m_data; } DEFINE_INLINE_TRACE() { } static int s_destructorCalls; private: static const size_t s_length = 1024; char m_data[s_length]; }; int OneKiloByteObject::s_destructorCalls = 0; class DynamicallySizedObject : public GarbageCollected<DynamicallySizedObject> { public: static DynamicallySizedObject* create(size_t size) { void* slot = Heap::allocate<DynamicallySizedObject>(size); return new (slot) DynamicallySizedObject(); } void* operator new(std::size_t, void* location) { return location; } uint8_t get(int i) { return *(reinterpret_cast<uint8_t*>(this) + i); } DEFINE_INLINE_TRACE() { } private: DynamicallySizedObject() { } }; class FinalizationAllocator : public GarbageCollectedFinalized<FinalizationAllocator> { public: FinalizationAllocator(Persistent<IntWrapper>* wrapper) : m_wrapper(wrapper) { } ~FinalizationAllocator() { for (int i = 0; i < 10; ++i) *m_wrapper = IntWrapper::create(42); for (int i = 0; i < 512; ++i) new OneKiloByteObject(); for (int i = 0; i < 32; ++i) LargeHeapObject::create(); } DEFINE_INLINE_TRACE() { } private: Persistent<IntWrapper>* m_wrapper; }; TEST(HeapTest, Transition) { { RefPtrWillBePersistent<TransitionRefCounted> refCounted = TransitionRefCounted::create(); EXPECT_EQ(1, TransitionRefCounted::s_aliveCount); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, TransitionRefCounted::s_aliveCount); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, TransitionRefCounted::s_aliveCount); RefPtrWillBePersistent<PointsBack> pointsBack1 = PointsBack::create(); RefPtrWillBePersistent<PointsBack> pointsBack2 = PointsBack::create(); RefPtrWillBePersistent<SuperClass> superClass = SuperClass::create(pointsBack1); RefPtrWillBePersistent<SubClass> subClass = SubClass::create(pointsBack2); EXPECT_EQ(2, PointsBack::s_aliveCount); EXPECT_EQ(2, SuperClass::s_aliveCount); EXPECT_EQ(1, SubClass::s_aliveCount); EXPECT_EQ(1, SubData::s_aliveCount); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, TransitionRefCounted::s_aliveCount); EXPECT_EQ(2, PointsBack::s_aliveCount); EXPECT_EQ(2, SuperClass::s_aliveCount); EXPECT_EQ(1, SubClass::s_aliveCount); EXPECT_EQ(1, SubData::s_aliveCount); superClass->doStuff(superClass.release(), pointsBack1.get(), 2); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2, PointsBack::s_aliveCount); EXPECT_EQ(1, SuperClass::s_aliveCount); EXPECT_EQ(1, SubClass::s_aliveCount); EXPECT_EQ(1, SubData::s_aliveCount); EXPECT_EQ(0, pointsBack1->backPointer()); pointsBack1.release(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, PointsBack::s_aliveCount); EXPECT_EQ(1, SuperClass::s_aliveCount); EXPECT_EQ(1, SubClass::s_aliveCount); EXPECT_EQ(1, SubData::s_aliveCount); subClass->doStuff(subClass.release(), pointsBack2.get(), 1); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, PointsBack::s_aliveCount); EXPECT_EQ(0, SuperClass::s_aliveCount); EXPECT_EQ(0, SubClass::s_aliveCount); EXPECT_EQ(0, SubData::s_aliveCount); EXPECT_EQ(0, pointsBack2->backPointer()); pointsBack2.release(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, PointsBack::s_aliveCount); EXPECT_EQ(0, SuperClass::s_aliveCount); EXPECT_EQ(0, SubClass::s_aliveCount); EXPECT_EQ(0, SubData::s_aliveCount); EXPECT_TRUE(superClass == subClass); } TEST(HeapTest, Threading) { ThreadedHeapTester::test(); } TEST(HeapTest, ThreadedWeakness) { ThreadedWeaknessTester::test(); } TEST(HeapTest, ThreadPersistent) { ThreadPersistentHeapTester::test(); } TEST(HeapTest, BasicFunctionality) { clearOutOldGarbage(); size_t initialObjectPayloadSize = Heap::objectPayloadSizeForTesting(); { size_t slack = 0; // When the test starts there may already have been leaked some memory // on the heap, so we establish a base line. size_t baseLevel = initialObjectPayloadSize; bool testPagesAllocated = !baseLevel; if (testPagesAllocated) EXPECT_EQ(Heap::allocatedSpace(), 0ul); // This allocates objects on the general heap which should add a page of memory. DynamicallySizedObject* alloc32 = DynamicallySizedObject::create(32); slack += 4; memset(alloc32, 40, 32); DynamicallySizedObject* alloc64 = DynamicallySizedObject::create(64); slack += 4; memset(alloc64, 27, 64); size_t total = 96; CheckWithSlack(baseLevel + total, Heap::objectPayloadSizeForTesting(), slack); if (testPagesAllocated) EXPECT_EQ(Heap::allocatedSpace(), blinkPageSize * 2); EXPECT_EQ(alloc32->get(0), 40); EXPECT_EQ(alloc32->get(31), 40); EXPECT_EQ(alloc64->get(0), 27); EXPECT_EQ(alloc64->get(63), 27); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(alloc32->get(0), 40); EXPECT_EQ(alloc32->get(31), 40); EXPECT_EQ(alloc64->get(0), 27); EXPECT_EQ(alloc64->get(63), 27); } clearOutOldGarbage(); size_t total = 0; size_t slack = 0; size_t baseLevel = Heap::objectPayloadSizeForTesting(); bool testPagesAllocated = !baseLevel; if (testPagesAllocated) EXPECT_EQ(Heap::allocatedSpace(), 0ul); size_t big = 1008; Persistent<DynamicallySizedObject> bigArea = DynamicallySizedObject::create(big); total += big; slack += 4; size_t persistentCount = 0; const size_t numPersistents = 100000; Persistent<DynamicallySizedObject>* persistents[numPersistents]; for (int i = 0; i < 1000; i++) { size_t size = 128 + i * 8; total += size; persistents[persistentCount++] = new Persistent<DynamicallySizedObject>(DynamicallySizedObject::create(size)); slack += 4; CheckWithSlack(baseLevel + total, Heap::objectPayloadSizeForTesting(), slack); if (testPagesAllocated) EXPECT_EQ(0ul, Heap::allocatedSpace() & (blinkPageSize - 1)); } { DynamicallySizedObject* alloc32b(DynamicallySizedObject::create(32)); slack += 4; memset(alloc32b, 40, 32); DynamicallySizedObject* alloc64b(DynamicallySizedObject::create(64)); slack += 4; memset(alloc64b, 27, 64); EXPECT_TRUE(alloc32b != alloc64b); total += 96; CheckWithSlack(baseLevel + total, Heap::objectPayloadSizeForTesting(), slack); if (testPagesAllocated) EXPECT_EQ(0ul, Heap::allocatedSpace() & (blinkPageSize - 1)); } clearOutOldGarbage(); total -= 96; slack -= 8; if (testPagesAllocated) EXPECT_EQ(0ul, Heap::allocatedSpace() & (blinkPageSize - 1)); // Clear the persistent, so that the big area will be garbage collected. bigArea.release(); clearOutOldGarbage(); total -= big; slack -= 4; CheckWithSlack(baseLevel + total, Heap::objectPayloadSizeForTesting(), slack); if (testPagesAllocated) EXPECT_EQ(0ul, Heap::allocatedSpace() & (blinkPageSize - 1)); CheckWithSlack(baseLevel + total, Heap::objectPayloadSizeForTesting(), slack); if (testPagesAllocated) EXPECT_EQ(0ul, Heap::allocatedSpace() & (blinkPageSize - 1)); for (size_t i = 0; i < persistentCount; i++) { delete persistents[i]; persistents[i] = 0; } uint8_t* address = reinterpret_cast<uint8_t*>(Heap::reallocate<DynamicallySizedObject>(0, 100)); for (int i = 0; i < 100; i++) address[i] = i; address = reinterpret_cast<uint8_t*>(Heap::reallocate<DynamicallySizedObject>(address, 100000)); for (int i = 0; i < 100; i++) EXPECT_EQ(address[i], i); address = reinterpret_cast<uint8_t*>(Heap::reallocate<DynamicallySizedObject>(address, 50)); for (int i = 0; i < 50; i++) EXPECT_EQ(address[i], i); // This should be equivalent to free(address). EXPECT_EQ(reinterpret_cast<uintptr_t>(Heap::reallocate<DynamicallySizedObject>(address, 0)), 0ul); // This should be equivalent to malloc(0). EXPECT_EQ(reinterpret_cast<uintptr_t>(Heap::reallocate<DynamicallySizedObject>(0, 0)), 0ul); } TEST(HeapTest, SimpleAllocation) { clearOutOldGarbage(); EXPECT_EQ(0ul, Heap::objectPayloadSizeForTesting()); // Allocate an object in the heap. HeapAllocatedArray* array = new HeapAllocatedArray(); EXPECT_TRUE(Heap::objectPayloadSizeForTesting() >= sizeof(HeapAllocatedArray)); // Sanity check of the contents in the heap. EXPECT_EQ(0, array->at(0)); EXPECT_EQ(42, array->at(42)); EXPECT_EQ(0, array->at(128)); EXPECT_EQ(999 % 128, array->at(999)); } TEST(HeapTest, SimplePersistent) { Persistent<TraceCounter> traceCounter = TraceCounter::create(); EXPECT_EQ(0, traceCounter->traceCount()); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, traceCounter->traceCount()); Persistent<ClassWithMember> classWithMember = ClassWithMember::create(); EXPECT_EQ(0, classWithMember->traceCount()); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, classWithMember->traceCount()); EXPECT_EQ(2, traceCounter->traceCount()); } TEST(HeapTest, SimpleFinalization) { { Persistent<SimpleFinalizedObject> finalized = SimpleFinalizedObject::create(); EXPECT_EQ(0, SimpleFinalizedObject::s_destructorCalls); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, SimpleFinalizedObject::s_destructorCalls); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, SimpleFinalizedObject::s_destructorCalls); } // FIXME: Lazy sweeping is disabled in non-oilpan builds. #if ENABLE(OILPAN) TEST(HeapTest, LazySweepingPages) { clearOutOldGarbage(); SimpleFinalizedObject::s_destructorCalls = 0; EXPECT_EQ(0, SimpleFinalizedObject::s_destructorCalls); for (int i = 0; i < 1000; i++) SimpleFinalizedObject::create(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithoutSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, SimpleFinalizedObject::s_destructorCalls); for (int i = 0; i < 10000; i++) SimpleFinalizedObject::create(); EXPECT_EQ(1000, SimpleFinalizedObject::s_destructorCalls); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(11000, SimpleFinalizedObject::s_destructorCalls); } TEST(HeapTest, LazySweepingLargeObjectPages) { clearOutOldGarbage(); LargeHeapObject::s_destructorCalls = 0; EXPECT_EQ(0, LargeHeapObject::s_destructorCalls); for (int i = 0; i < 10; i++) LargeHeapObject::create(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithoutSweep, Heap::ForcedGCForTesting); for (int i = 0; i < 10; i++) { LargeHeapObject::create(); EXPECT_EQ(i + 1, LargeHeapObject::s_destructorCalls); } LargeHeapObject::create(); LargeHeapObject::create(); EXPECT_EQ(10, LargeHeapObject::s_destructorCalls); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithoutSweep, Heap::ForcedGCForTesting); EXPECT_EQ(10, LargeHeapObject::s_destructorCalls); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(22, LargeHeapObject::s_destructorCalls); } #endif TEST(HeapTest, Finalization) { { HeapTestSubClass* t1 = HeapTestSubClass::create(); HeapTestSubClass* t2 = HeapTestSubClass::create(); HeapTestSuperClass* t3 = HeapTestSuperClass::create(); // FIXME(oilpan): Ignore unused variables. (void)t1; (void)t2; (void)t3; } // Nothing is marked so the GC should free everything and call // the finalizer on all three objects. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2, HeapTestSubClass::s_destructorCalls); EXPECT_EQ(3, HeapTestSuperClass::s_destructorCalls); // Destructors not called again when GCing again. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2, HeapTestSubClass::s_destructorCalls); EXPECT_EQ(3, HeapTestSuperClass::s_destructorCalls); } TEST(HeapTest, TypedHeapSanity) { // We use TraceCounter for allocating an object on the general heap. Persistent<TraceCounter> generalHeapObject = TraceCounter::create(); Persistent<IntNode> typedHeapObject = IntNode::create(0); EXPECT_NE(pageFromObject(generalHeapObject.get()), pageFromObject(typedHeapObject.get())); } TEST(HeapTest, NoAllocation) { ThreadState* state = ThreadState::current(); EXPECT_TRUE(state->isAllocationAllowed()); { // Disallow allocation ThreadState::NoAllocationScope noAllocationScope(state); EXPECT_FALSE(state->isAllocationAllowed()); } EXPECT_TRUE(state->isAllocationAllowed()); } TEST(HeapTest, Members) { Bar::s_live = 0; { Persistent<Baz> h1; Persistent<Baz> h2; { h1 = Baz::create(Bar::create()); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1u, Bar::s_live); h2 = Baz::create(Bar::create()); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2u, Bar::s_live); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2u, Bar::s_live); h1->clear(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1u, Bar::s_live); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, Bar::s_live); } TEST(HeapTest, MarkTest) { { Bar::s_live = 0; Persistent<Bar> bar = Bar::create(); ASSERT(ThreadState::current()->findPageFromAddress(bar)); EXPECT_EQ(1u, Bar::s_live); { Foo* foo = Foo::create(bar); ASSERT(ThreadState::current()->findPageFromAddress(foo)); EXPECT_EQ(2u, Bar::s_live); EXPECT_TRUE(reinterpret_cast<Address>(foo) != reinterpret_cast<Address>(bar.get())); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(foo != bar); // To make sure foo is kept alive. EXPECT_EQ(2u, Bar::s_live); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1u, Bar::s_live); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, Bar::s_live); } TEST(HeapTest, DeepTest) { const unsigned depth = 100000; Bar::s_live = 0; { Bar* bar = Bar::create(); ASSERT(ThreadState::current()->findPageFromAddress(bar)); Foo* foo = Foo::create(bar); ASSERT(ThreadState::current()->findPageFromAddress(foo)); EXPECT_EQ(2u, Bar::s_live); for (unsigned i = 0; i < depth; i++) { Foo* foo2 = Foo::create(foo); foo = foo2; ASSERT(ThreadState::current()->findPageFromAddress(foo)); } EXPECT_EQ(depth + 2, Bar::s_live); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(foo != bar); // To make sure foo and bar are kept alive. EXPECT_EQ(depth + 2, Bar::s_live); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, Bar::s_live); } TEST(HeapTest, WideTest) { Bar::s_live = 0; { Bars* bars = Bars::create(); unsigned width = Bars::width; EXPECT_EQ(width + 1, Bar::s_live); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(width + 1, Bar::s_live); // Use bars here to make sure that it will be on the stack // for the conservative stack scan to find. EXPECT_EQ(width, bars->getWidth()); } EXPECT_EQ(Bars::width + 1, Bar::s_live); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, Bar::s_live); } TEST(HeapTest, HashMapOfMembers) { IntWrapper::s_destructorCalls = 0; clearOutOldGarbage(); size_t initialObjectPayloadSize = Heap::objectPayloadSizeForTesting(); { typedef HeapHashMap< Member<IntWrapper>, Member<IntWrapper>, DefaultHash<Member<IntWrapper>>::Hash, HashTraits<Member<IntWrapper>>, HashTraits<Member<IntWrapper>>> HeapObjectIdentityMap; Persistent<HeapObjectIdentityMap> map = new HeapObjectIdentityMap(); map->clear(); size_t afterSetWasCreated = Heap::objectPayloadSizeForTesting(); EXPECT_TRUE(afterSetWasCreated > initialObjectPayloadSize); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); size_t afterGC = Heap::objectPayloadSizeForTesting(); EXPECT_EQ(afterGC, afterSetWasCreated); // If the additions below cause garbage collections, these // pointers should be found by conservative stack scanning. IntWrapper* one(IntWrapper::create(1)); IntWrapper* anotherOne(IntWrapper::create(1)); map->add(one, one); size_t afterOneAdd = Heap::objectPayloadSizeForTesting(); EXPECT_TRUE(afterOneAdd > afterGC); HeapObjectIdentityMap::iterator it(map->begin()); HeapObjectIdentityMap::iterator it2(map->begin()); ++it; ++it2; map->add(anotherOne, one); // The addition above can cause an allocation of a new // backing store. We therefore garbage collect before // taking the heap stats in order to get rid of the old // backing store. We make sure to not use conservative // stack scanning as that could find a pointer to the // old backing. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); size_t afterAddAndGC = Heap::objectPayloadSizeForTesting(); EXPECT_TRUE(afterAddAndGC >= afterOneAdd); EXPECT_EQ(map->size(), 2u); // Two different wrappings of '1' are distinct. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(map->contains(one)); EXPECT_TRUE(map->contains(anotherOne)); IntWrapper* gotten(map->get(one)); EXPECT_EQ(gotten->value(), one->value()); EXPECT_EQ(gotten, one); size_t afterGC2 = Heap::objectPayloadSizeForTesting(); EXPECT_EQ(afterGC2, afterAddAndGC); IntWrapper* dozen = 0; for (int i = 1; i < 1000; i++) { // 999 iterations. IntWrapper* iWrapper(IntWrapper::create(i)); IntWrapper* iSquared(IntWrapper::create(i * i)); map->add(iWrapper, iSquared); if (i == 12) dozen = iWrapper; } size_t afterAdding1000 = Heap::objectPayloadSizeForTesting(); EXPECT_TRUE(afterAdding1000 > afterGC2); IntWrapper* gross(map->get(dozen)); EXPECT_EQ(gross->value(), 144); // This should clear out any junk backings created by all the adds. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); size_t afterGC3 = Heap::objectPayloadSizeForTesting(); EXPECT_TRUE(afterGC3 <= afterAdding1000); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // The objects 'one', anotherOne, and the 999 other pairs. EXPECT_EQ(IntWrapper::s_destructorCalls, 2000); size_t afterGC4 = Heap::objectPayloadSizeForTesting(); EXPECT_EQ(afterGC4, initialObjectPayloadSize); } TEST(HeapTest, NestedAllocation) { clearOutOldGarbage(); size_t initialObjectPayloadSize = Heap::objectPayloadSizeForTesting(); { Persistent<ConstructorAllocation> constructorAllocation = ConstructorAllocation::create(); } clearOutOldGarbage(); size_t afterFree = Heap::objectPayloadSizeForTesting(); EXPECT_TRUE(initialObjectPayloadSize == afterFree); } TEST(HeapTest, LargeHeapObjects) { clearOutOldGarbage(); size_t initialObjectPayloadSize = Heap::objectPayloadSizeForTesting(); size_t initialAllocatedSpace = Heap::allocatedSpace(); IntWrapper::s_destructorCalls = 0; LargeHeapObject::s_destructorCalls = 0; { int slack = 8; // LargeHeapObject points to an IntWrapper that is also allocated. Persistent<LargeHeapObject> object = LargeHeapObject::create(); ASSERT(ThreadState::current()->findPageFromAddress(object)); ASSERT(ThreadState::current()->findPageFromAddress(reinterpret_cast<char*>(object.get()) + sizeof(LargeHeapObject) - 1)); #if ENABLE(GC_PROFILING) const GCInfo* info = ThreadState::current()->findGCInfo(reinterpret_cast<Address>(object.get())); EXPECT_NE(reinterpret_cast<const GCInfo*>(0), info); EXPECT_EQ(info, ThreadState::current()->findGCInfo(reinterpret_cast<Address>(object.get()) + sizeof(LargeHeapObject) - 1)); EXPECT_NE(info, ThreadState::current()->findGCInfo(reinterpret_cast<Address>(object.get()) + sizeof(LargeHeapObject))); EXPECT_NE(info, ThreadState::current()->findGCInfo(reinterpret_cast<Address>(object.get()) - 1)); #endif clearOutOldGarbage(); size_t afterAllocation = Heap::allocatedSpace(); { object->set(0, 'a'); EXPECT_EQ('a', object->get(0)); object->set(object->length() - 1, 'b'); EXPECT_EQ('b', object->get(object->length() - 1)); size_t expectedLargeHeapObjectPayloadSize = Heap::allocationSizeFromSize(sizeof(LargeHeapObject)); size_t expectedObjectPayloadSize = expectedLargeHeapObjectPayloadSize + sizeof(IntWrapper); size_t actualObjectPayloadSize = Heap::objectPayloadSizeForTesting() - initialObjectPayloadSize; CheckWithSlack(expectedObjectPayloadSize, actualObjectPayloadSize, slack); // There is probably space for the IntWrapper in a heap page without // allocating extra pages. However, the IntWrapper allocation might cause // the addition of a heap page. size_t largeObjectAllocationSize = sizeof(LargeObjectPage) + expectedLargeHeapObjectPayloadSize; size_t allocatedSpaceLowerBound = initialAllocatedSpace + largeObjectAllocationSize; size_t allocatedSpaceUpperBound = allocatedSpaceLowerBound + slack + blinkPageSize; EXPECT_LE(allocatedSpaceLowerBound, afterAllocation); EXPECT_LE(afterAllocation, allocatedSpaceUpperBound); EXPECT_EQ(0, IntWrapper::s_destructorCalls); EXPECT_EQ(0, LargeHeapObject::s_destructorCalls); for (int i = 0; i < 10; i++) object = LargeHeapObject::create(); } clearOutOldGarbage(); EXPECT_TRUE(Heap::allocatedSpace() == afterAllocation); EXPECT_EQ(10, IntWrapper::s_destructorCalls); EXPECT_EQ(10, LargeHeapObject::s_destructorCalls); } clearOutOldGarbage(); EXPECT_TRUE(initialObjectPayloadSize == Heap::objectPayloadSizeForTesting()); EXPECT_TRUE(initialAllocatedSpace == Heap::allocatedSpace()); EXPECT_EQ(11, IntWrapper::s_destructorCalls); EXPECT_EQ(11, LargeHeapObject::s_destructorCalls); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); } typedef std::pair<Member<IntWrapper>, int> PairWrappedUnwrapped; typedef std::pair<int, Member<IntWrapper>> PairUnwrappedWrapped; typedef std::pair<WeakMember<IntWrapper>, Member<IntWrapper>> PairWeakStrong; typedef std::pair<Member<IntWrapper>, WeakMember<IntWrapper>> PairStrongWeak; typedef std::pair<WeakMember<IntWrapper>, int> PairWeakUnwrapped; typedef std::pair<int, WeakMember<IntWrapper>> PairUnwrappedWeak; class Container : public GarbageCollected<Container> { public: static Container* create() { return new Container(); } HeapHashMap<Member<IntWrapper>, Member<IntWrapper>> map; HeapHashSet<Member<IntWrapper>> set; HeapHashSet<Member<IntWrapper>> set2; HeapHashCountedSet<Member<IntWrapper>> set3; HeapVector<Member<IntWrapper>, 2> vector; HeapVector<PairWrappedUnwrapped, 2> vectorWU; HeapVector<PairUnwrappedWrapped, 2> vectorUW; HeapDeque<Member<IntWrapper>, 0> deque; HeapDeque<PairWrappedUnwrapped, 0> dequeWU; HeapDeque<PairUnwrappedWrapped, 0> dequeUW; DEFINE_INLINE_TRACE() { visitor->trace(map); visitor->trace(set); visitor->trace(set2); visitor->trace(set3); visitor->trace(vector); visitor->trace(vectorWU); visitor->trace(vectorUW); visitor->trace(deque); visitor->trace(dequeWU); visitor->trace(dequeUW); } }; struct ShouldBeTraced { explicit ShouldBeTraced(IntWrapper* wrapper) : m_wrapper(wrapper) { } DEFINE_INLINE_TRACE() { visitor->trace(m_wrapper); } Member<IntWrapper> m_wrapper; }; class OffHeapContainer : public GarbageCollectedFinalized<OffHeapContainer> { public: static OffHeapContainer* create() { return new OffHeapContainer(); } static const int iterations = 300; static const int deadWrappers = 600; OffHeapContainer() { for (int i = 0; i < iterations; i++) { m_deque1.append(ShouldBeTraced(IntWrapper::create(i))); m_vector1.append(ShouldBeTraced(IntWrapper::create(i))); } Deque<ShouldBeTraced>::iterator d1Iterator(m_deque1.begin()); Vector<ShouldBeTraced>::iterator v1Iterator(m_vector1.begin()); for (int i = 0; i < iterations; i++) { EXPECT_EQ(i, m_vector1[i].m_wrapper->value()); EXPECT_EQ(i, d1Iterator->m_wrapper->value()); EXPECT_EQ(i, v1Iterator->m_wrapper->value()); ++d1Iterator; ++v1Iterator; } EXPECT_EQ(d1Iterator, m_deque1.end()); EXPECT_EQ(v1Iterator, m_vector1.end()); } DEFINE_INLINE_TRACE() { visitor->trace(m_deque1); visitor->trace(m_vector1); } Deque<ShouldBeTraced> m_deque1; Vector<ShouldBeTraced> m_vector1; }; const int OffHeapContainer::iterations; const int OffHeapContainer::deadWrappers; // These class definitions test compile-time asserts with transition // types. They are therefore unused in test code and just need to // compile. This is intentional; do not delete the A and B classes below. class A : public WillBeGarbageCollectedMixin { }; class B : public NoBaseWillBeGarbageCollected<B>, public A { WILL_BE_USING_GARBAGE_COLLECTED_MIXIN(B); public: DEFINE_INLINE_TRACE() { } }; TEST(HeapTest, HeapVectorFilledWithValue) { IntWrapper* val = IntWrapper::create(1); HeapVector<Member<IntWrapper>> vector(10, val); EXPECT_EQ(10u, vector.size()); for (size_t i = 0; i < vector.size(); i++) EXPECT_EQ(val, vector[i]); } TEST(HeapTest, HeapVectorWithInlineCapacity) { IntWrapper* one = IntWrapper::create(1); IntWrapper* two = IntWrapper::create(2); IntWrapper* three = IntWrapper::create(3); IntWrapper* four = IntWrapper::create(4); IntWrapper* five = IntWrapper::create(5); IntWrapper* six = IntWrapper::create(6); { HeapVector<Member<IntWrapper>, 2> vector; vector.append(one); vector.append(two); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(vector.contains(one)); EXPECT_TRUE(vector.contains(two)); vector.append(three); vector.append(four); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(vector.contains(one)); EXPECT_TRUE(vector.contains(two)); EXPECT_TRUE(vector.contains(three)); EXPECT_TRUE(vector.contains(four)); vector.shrink(1); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(vector.contains(one)); EXPECT_FALSE(vector.contains(two)); EXPECT_FALSE(vector.contains(three)); EXPECT_FALSE(vector.contains(four)); } { HeapVector<Member<IntWrapper>, 2> vector1; HeapVector<Member<IntWrapper>, 2> vector2; vector1.append(one); vector2.append(two); vector1.swap(vector2); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(vector1.contains(two)); EXPECT_TRUE(vector2.contains(one)); } { HeapVector<Member<IntWrapper>, 2> vector1; HeapVector<Member<IntWrapper>, 2> vector2; vector1.append(one); vector1.append(two); vector2.append(three); vector2.append(four); vector2.append(five); vector2.append(six); vector1.swap(vector2); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(vector1.contains(three)); EXPECT_TRUE(vector1.contains(four)); EXPECT_TRUE(vector1.contains(five)); EXPECT_TRUE(vector1.contains(six)); EXPECT_TRUE(vector2.contains(one)); EXPECT_TRUE(vector2.contains(two)); } } TEST(HeapTest, HeapVectorShrinkCapacity) { clearOutOldGarbage(); HeapVector<Member<IntWrapper>> vector1; HeapVector<Member<IntWrapper>> vector2; vector1.reserveCapacity(96); EXPECT_LE(96u, vector1.capacity()); vector1.grow(vector1.capacity()); // Assumes none was allocated just after a vector backing of vector1. vector1.shrink(56); vector1.shrinkToFit(); EXPECT_GT(96u, vector1.capacity()); vector2.reserveCapacity(20); // Assumes another vector backing was allocated just after the vector // backing of vector1. vector1.shrink(10); vector1.shrinkToFit(); EXPECT_GT(56u, vector1.capacity()); vector1.grow(192); EXPECT_LE(192u, vector1.capacity()); } TEST(HeapTest, HeapVectorShrinkInlineCapacity) { clearOutOldGarbage(); const size_t inlineCapacity = 64; HeapVector<Member<IntWrapper>, inlineCapacity> vector1; vector1.reserveCapacity(128); EXPECT_LE(128u, vector1.capacity()); vector1.grow(vector1.capacity()); // Shrink the external buffer. vector1.shrink(90); vector1.shrinkToFit(); EXPECT_GT(128u, vector1.capacity()); // Shrinking switches the buffer from the external one to the inline one. vector1.shrink(inlineCapacity - 1); vector1.shrinkToFit(); EXPECT_EQ(inlineCapacity, vector1.capacity()); // Try to shrink the inline buffer. vector1.shrink(1); vector1.shrinkToFit(); EXPECT_EQ(inlineCapacity, vector1.capacity()); } template<typename T, size_t inlineCapacity, typename U> bool dequeContains(HeapDeque<T, inlineCapacity>& deque, U u) { typedef typename HeapDeque<T, inlineCapacity>::iterator iterator; for (iterator it = deque.begin(); it != deque.end(); ++it) { if (*it == u) return true; } return false; } TEST(HeapTest, HeapCollectionTypes) { IntWrapper::s_destructorCalls = 0; typedef HeapHashMap<Member<IntWrapper>, Member<IntWrapper>> MemberMember; typedef HeapHashMap<Member<IntWrapper>, int> MemberPrimitive; typedef HeapHashMap<int, Member<IntWrapper>> PrimitiveMember; typedef HeapHashSet<Member<IntWrapper>> MemberSet; typedef HeapHashCountedSet<Member<IntWrapper>> MemberCountedSet; typedef HeapVector<Member<IntWrapper>, 2> MemberVector; typedef HeapDeque<Member<IntWrapper>, 0> MemberDeque; typedef HeapVector<PairWrappedUnwrapped, 2> VectorWU; typedef HeapVector<PairUnwrappedWrapped, 2> VectorUW; typedef HeapDeque<PairWrappedUnwrapped, 0> DequeWU; typedef HeapDeque<PairUnwrappedWrapped, 0> DequeUW; Persistent<MemberMember> memberMember = new MemberMember(); Persistent<MemberMember> memberMember2 = new MemberMember(); Persistent<MemberMember> memberMember3 = new MemberMember(); Persistent<MemberPrimitive> memberPrimitive = new MemberPrimitive(); Persistent<PrimitiveMember> primitiveMember = new PrimitiveMember(); Persistent<MemberSet> set = new MemberSet(); Persistent<MemberSet> set2 = new MemberSet(); Persistent<MemberCountedSet> set3 = new MemberCountedSet(); Persistent<MemberVector> vector = new MemberVector(); Persistent<MemberVector> vector2 = new MemberVector(); Persistent<VectorWU> vectorWU = new VectorWU(); Persistent<VectorWU> vectorWU2 = new VectorWU(); Persistent<VectorUW> vectorUW = new VectorUW(); Persistent<VectorUW> vectorUW2 = new VectorUW(); Persistent<MemberDeque> deque = new MemberDeque(); Persistent<MemberDeque> deque2 = new MemberDeque(); Persistent<DequeWU> dequeWU = new DequeWU(); Persistent<DequeWU> dequeWU2 = new DequeWU(); Persistent<DequeUW> dequeUW = new DequeUW(); Persistent<DequeUW> dequeUW2 = new DequeUW(); Persistent<Container> container = Container::create(); clearOutOldGarbage(); { Persistent<IntWrapper> one(IntWrapper::create(1)); Persistent<IntWrapper> two(IntWrapper::create(2)); Persistent<IntWrapper> oneB(IntWrapper::create(1)); Persistent<IntWrapper> twoB(IntWrapper::create(2)); Persistent<IntWrapper> oneC(IntWrapper::create(1)); Persistent<IntWrapper> oneD(IntWrapper::create(1)); Persistent<IntWrapper> oneE(IntWrapper::create(1)); Persistent<IntWrapper> oneF(IntWrapper::create(1)); { IntWrapper* threeB(IntWrapper::create(3)); IntWrapper* threeC(IntWrapper::create(3)); IntWrapper* threeD(IntWrapper::create(3)); IntWrapper* threeE(IntWrapper::create(3)); IntWrapper* threeF(IntWrapper::create(3)); IntWrapper* three(IntWrapper::create(3)); IntWrapper* fourB(IntWrapper::create(4)); IntWrapper* fourC(IntWrapper::create(4)); IntWrapper* fourD(IntWrapper::create(4)); IntWrapper* fourE(IntWrapper::create(4)); IntWrapper* fourF(IntWrapper::create(4)); IntWrapper* four(IntWrapper::create(4)); IntWrapper* fiveC(IntWrapper::create(5)); IntWrapper* fiveD(IntWrapper::create(5)); IntWrapper* fiveE(IntWrapper::create(5)); IntWrapper* fiveF(IntWrapper::create(5)); // Member Collections. memberMember2->add(one, two); memberMember2->add(two, three); memberMember2->add(three, four); memberMember2->add(four, one); primitiveMember->add(1, two); primitiveMember->add(2, three); primitiveMember->add(3, four); primitiveMember->add(4, one); memberPrimitive->add(one, 2); memberPrimitive->add(two, 3); memberPrimitive->add(three, 4); memberPrimitive->add(four, 1); set2->add(one); set2->add(two); set2->add(three); set2->add(four); set->add(oneB); set3->add(oneB); set3->add(oneB); vector->append(oneB); deque->append(oneB); vector2->append(threeB); vector2->append(fourB); deque2->append(threeE); deque2->append(fourE); vectorWU->append(PairWrappedUnwrapped(&*oneC, 42)); dequeWU->append(PairWrappedUnwrapped(&*oneE, 42)); vectorWU2->append(PairWrappedUnwrapped(&*threeC, 43)); vectorWU2->append(PairWrappedUnwrapped(&*fourC, 44)); vectorWU2->append(PairWrappedUnwrapped(&*fiveC, 45)); dequeWU2->append(PairWrappedUnwrapped(&*threeE, 43)); dequeWU2->append(PairWrappedUnwrapped(&*fourE, 44)); dequeWU2->append(PairWrappedUnwrapped(&*fiveE, 45)); vectorUW->append(PairUnwrappedWrapped(1, &*oneD)); vectorUW2->append(PairUnwrappedWrapped(103, &*threeD)); vectorUW2->append(PairUnwrappedWrapped(104, &*fourD)); vectorUW2->append(PairUnwrappedWrapped(105, &*fiveD)); dequeUW->append(PairUnwrappedWrapped(1, &*oneF)); dequeUW2->append(PairUnwrappedWrapped(103, &*threeF)); dequeUW2->append(PairUnwrappedWrapped(104, &*fourF)); dequeUW2->append(PairUnwrappedWrapped(105, &*fiveF)); EXPECT_TRUE(dequeContains(*deque, oneB)); // Collect garbage. This should change nothing since we are keeping // alive the IntWrapper objects with on-stack pointers. Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(dequeContains(*deque, oneB)); EXPECT_EQ(0u, memberMember->size()); EXPECT_EQ(4u, memberMember2->size()); EXPECT_EQ(4u, primitiveMember->size()); EXPECT_EQ(4u, memberPrimitive->size()); EXPECT_EQ(1u, set->size()); EXPECT_EQ(4u, set2->size()); EXPECT_EQ(1u, set3->size()); EXPECT_EQ(1u, vector->size()); EXPECT_EQ(2u, vector2->size()); EXPECT_EQ(1u, vectorWU->size()); EXPECT_EQ(3u, vectorWU2->size()); EXPECT_EQ(1u, vectorUW->size()); EXPECT_EQ(3u, vectorUW2->size()); EXPECT_EQ(1u, deque->size()); EXPECT_EQ(2u, deque2->size()); EXPECT_EQ(1u, dequeWU->size()); EXPECT_EQ(3u, dequeWU2->size()); EXPECT_EQ(1u, dequeUW->size()); EXPECT_EQ(3u, dequeUW2->size()); MemberVector& cvec = container->vector; cvec.swap(*vector.get()); vector2->swap(cvec); vector->swap(cvec); VectorWU& cvecWU = container->vectorWU; cvecWU.swap(*vectorWU.get()); vectorWU2->swap(cvecWU); vectorWU->swap(cvecWU); VectorUW& cvecUW = container->vectorUW; cvecUW.swap(*vectorUW.get()); vectorUW2->swap(cvecUW); vectorUW->swap(cvecUW); MemberDeque& cDeque = container->deque; cDeque.swap(*deque.get()); deque2->swap(cDeque); deque->swap(cDeque); DequeWU& cDequeWU = container->dequeWU; cDequeWU.swap(*dequeWU.get()); dequeWU2->swap(cDequeWU); dequeWU->swap(cDequeWU); DequeUW& cDequeUW = container->dequeUW; cDequeUW.swap(*dequeUW.get()); dequeUW2->swap(cDequeUW); dequeUW->swap(cDequeUW); // Swap set and set2 in a roundabout way. MemberSet& cset1 = container->set; MemberSet& cset2 = container->set2; set->swap(cset1); set2->swap(cset2); set->swap(cset2); cset1.swap(cset2); cset2.swap(set2); MemberCountedSet& cCountedSet = container->set3; set3->swap(cCountedSet); EXPECT_EQ(0u, set3->size()); set3->swap(cCountedSet); // Triple swap. container->map.swap(memberMember2); MemberMember& containedMap = container->map; memberMember3->swap(containedMap); memberMember3->swap(memberMember); EXPECT_TRUE(memberMember->get(one) == two); EXPECT_TRUE(memberMember->get(two) == three); EXPECT_TRUE(memberMember->get(three) == four); EXPECT_TRUE(memberMember->get(four) == one); EXPECT_TRUE(primitiveMember->get(1) == two); EXPECT_TRUE(primitiveMember->get(2) == three); EXPECT_TRUE(primitiveMember->get(3) == four); EXPECT_TRUE(primitiveMember->get(4) == one); EXPECT_EQ(1, memberPrimitive->get(four)); EXPECT_EQ(2, memberPrimitive->get(one)); EXPECT_EQ(3, memberPrimitive->get(two)); EXPECT_EQ(4, memberPrimitive->get(three)); EXPECT_TRUE(set->contains(one)); EXPECT_TRUE(set->contains(two)); EXPECT_TRUE(set->contains(three)); EXPECT_TRUE(set->contains(four)); EXPECT_TRUE(set2->contains(oneB)); EXPECT_TRUE(set3->contains(oneB)); EXPECT_TRUE(vector->contains(threeB)); EXPECT_TRUE(vector->contains(fourB)); EXPECT_TRUE(dequeContains(*deque, threeE)); EXPECT_TRUE(dequeContains(*deque, fourE)); EXPECT_TRUE(vector2->contains(oneB)); EXPECT_FALSE(vector2->contains(threeB)); EXPECT_TRUE(dequeContains(*deque2, oneB)); EXPECT_FALSE(dequeContains(*deque2, threeE)); EXPECT_TRUE(vectorWU->contains(PairWrappedUnwrapped(&*threeC, 43))); EXPECT_TRUE(vectorWU->contains(PairWrappedUnwrapped(&*fourC, 44))); EXPECT_TRUE(vectorWU->contains(PairWrappedUnwrapped(&*fiveC, 45))); EXPECT_TRUE(vectorWU2->contains(PairWrappedUnwrapped(&*oneC, 42))); EXPECT_FALSE(vectorWU2->contains(PairWrappedUnwrapped(&*threeC, 43))); EXPECT_TRUE(vectorUW->contains(PairUnwrappedWrapped(103, &*threeD))); EXPECT_TRUE(vectorUW->contains(PairUnwrappedWrapped(104, &*fourD))); EXPECT_TRUE(vectorUW->contains(PairUnwrappedWrapped(105, &*fiveD))); EXPECT_TRUE(vectorUW2->contains(PairUnwrappedWrapped(1, &*oneD))); EXPECT_FALSE(vectorUW2->contains(PairUnwrappedWrapped(103, &*threeD))); EXPECT_TRUE(dequeContains(*dequeWU, PairWrappedUnwrapped(&*threeE, 43))); EXPECT_TRUE(dequeContains(*dequeWU, PairWrappedUnwrapped(&*fourE, 44))); EXPECT_TRUE(dequeContains(*dequeWU, PairWrappedUnwrapped(&*fiveE, 45))); EXPECT_TRUE(dequeContains(*dequeWU2, PairWrappedUnwrapped(&*oneE, 42))); EXPECT_FALSE(dequeContains(*dequeWU2, PairWrappedUnwrapped(&*threeE, 43))); EXPECT_TRUE(dequeContains(*dequeUW, PairUnwrappedWrapped(103, &*threeF))); EXPECT_TRUE(dequeContains(*dequeUW, PairUnwrappedWrapped(104, &*fourF))); EXPECT_TRUE(dequeContains(*dequeUW, PairUnwrappedWrapped(105, &*fiveF))); EXPECT_TRUE(dequeContains(*dequeUW2, PairUnwrappedWrapped(1, &*oneF))); EXPECT_FALSE(dequeContains(*dequeUW2, PairUnwrappedWrapped(103, &*threeF))); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(4u, memberMember->size()); EXPECT_EQ(0u, memberMember2->size()); EXPECT_EQ(4u, primitiveMember->size()); EXPECT_EQ(4u, memberPrimitive->size()); EXPECT_EQ(4u, set->size()); EXPECT_EQ(1u, set2->size()); EXPECT_EQ(1u, set3->size()); EXPECT_EQ(2u, vector->size()); EXPECT_EQ(1u, vector2->size()); EXPECT_EQ(3u, vectorUW->size()); EXPECT_EQ(1u, vector2->size()); EXPECT_EQ(2u, deque->size()); EXPECT_EQ(1u, deque2->size()); EXPECT_EQ(3u, dequeUW->size()); EXPECT_EQ(1u, deque2->size()); EXPECT_TRUE(memberMember->get(one) == two); EXPECT_TRUE(primitiveMember->get(1) == two); EXPECT_TRUE(primitiveMember->get(4) == one); EXPECT_EQ(2, memberPrimitive->get(one)); EXPECT_EQ(3, memberPrimitive->get(two)); EXPECT_TRUE(set->contains(one)); EXPECT_TRUE(set->contains(two)); EXPECT_FALSE(set->contains(oneB)); EXPECT_TRUE(set2->contains(oneB)); EXPECT_TRUE(set3->contains(oneB)); EXPECT_EQ(2u, set3->find(oneB)->value); EXPECT_EQ(3, vector->at(0)->value()); EXPECT_EQ(4, vector->at(1)->value()); EXPECT_EQ(3, deque->begin()->get()->value()); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(4u, memberMember->size()); EXPECT_EQ(4u, primitiveMember->size()); EXPECT_EQ(4u, memberPrimitive->size()); EXPECT_EQ(4u, set->size()); EXPECT_EQ(1u, set2->size()); EXPECT_EQ(2u, vector->size()); EXPECT_EQ(1u, vector2->size()); EXPECT_EQ(3u, vectorWU->size()); EXPECT_EQ(1u, vectorWU2->size()); EXPECT_EQ(3u, vectorUW->size()); EXPECT_EQ(1u, vectorUW2->size()); EXPECT_EQ(2u, deque->size()); EXPECT_EQ(1u, deque2->size()); EXPECT_EQ(3u, dequeWU->size()); EXPECT_EQ(1u, dequeWU2->size()); EXPECT_EQ(3u, dequeUW->size()); EXPECT_EQ(1u, dequeUW2->size()); } template<typename T> void MapIteratorCheck(T& it, const T& end, int expected) { int found = 0; while (it != end) { found++; int key = it->key->value(); int value = it->value->value(); EXPECT_TRUE(key >= 0 && key < 1100); EXPECT_TRUE(value >= 0 && value < 1100); ++it; } EXPECT_EQ(expected, found); } template<typename T> void SetIteratorCheck(T& it, const T& end, int expected) { int found = 0; while (it != end) { found++; int value = (*it)->value(); EXPECT_TRUE(value >= 0 && value < 1100); ++it; } EXPECT_EQ(expected, found); } TEST(HeapTest, HeapWeakCollectionSimple) { clearOutOldGarbage(); IntWrapper::s_destructorCalls = 0; PersistentHeapVector<Member<IntWrapper>> keepNumbersAlive; typedef HeapHashMap<WeakMember<IntWrapper>, Member<IntWrapper>> WeakStrong; typedef HeapHashMap<Member<IntWrapper>, WeakMember<IntWrapper>> StrongWeak; typedef HeapHashMap<WeakMember<IntWrapper>, WeakMember<IntWrapper>> WeakWeak; typedef HeapHashSet<WeakMember<IntWrapper>> WeakSet; typedef HeapHashCountedSet<WeakMember<IntWrapper>> WeakCountedSet; Persistent<WeakStrong> weakStrong = new WeakStrong(); Persistent<StrongWeak> strongWeak = new StrongWeak(); Persistent<WeakWeak> weakWeak = new WeakWeak(); Persistent<WeakSet> weakSet = new WeakSet(); Persistent<WeakCountedSet> weakCountedSet = new WeakCountedSet(); Persistent<IntWrapper> two = IntWrapper::create(2); keepNumbersAlive.append(IntWrapper::create(103)); keepNumbersAlive.append(IntWrapper::create(10)); { weakStrong->add(IntWrapper::create(1), two); strongWeak->add(two, IntWrapper::create(1)); weakWeak->add(two, IntWrapper::create(42)); weakWeak->add(IntWrapper::create(42), two); weakSet->add(IntWrapper::create(0)); weakSet->add(two); weakSet->add(keepNumbersAlive[0]); weakSet->add(keepNumbersAlive[1]); weakCountedSet->add(IntWrapper::create(0)); weakCountedSet->add(two); weakCountedSet->add(two); weakCountedSet->add(two); weakCountedSet->add(keepNumbersAlive[0]); weakCountedSet->add(keepNumbersAlive[1]); EXPECT_EQ(1u, weakStrong->size()); EXPECT_EQ(1u, strongWeak->size()); EXPECT_EQ(2u, weakWeak->size()); EXPECT_EQ(4u, weakSet->size()); EXPECT_EQ(4u, weakCountedSet->size()); EXPECT_EQ(3u, weakCountedSet->find(two)->value); weakCountedSet->remove(two); EXPECT_EQ(2u, weakCountedSet->find(two)->value); } keepNumbersAlive[0] = nullptr; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, weakStrong->size()); EXPECT_EQ(0u, strongWeak->size()); EXPECT_EQ(0u, weakWeak->size()); EXPECT_EQ(2u, weakSet->size()); EXPECT_EQ(2u, weakCountedSet->size()); } template<typename Set> void orderedSetHelper(bool strong) { clearOutOldGarbage(); IntWrapper::s_destructorCalls = 0; PersistentHeapVector<Member<IntWrapper>> keepNumbersAlive; Persistent<Set> set1 = new Set(); Persistent<Set> set2 = new Set(); const Set& constSet = *set1.get(); keepNumbersAlive.append(IntWrapper::create(2)); keepNumbersAlive.append(IntWrapper::create(103)); keepNumbersAlive.append(IntWrapper::create(10)); set1->add(IntWrapper::create(0)); set1->add(keepNumbersAlive[0]); set1->add(keepNumbersAlive[1]); set1->add(keepNumbersAlive[2]); set2->clear(); set2->add(IntWrapper::create(42)); set2->clear(); EXPECT_EQ(4u, set1->size()); typename Set::iterator it(set1->begin()); typename Set::reverse_iterator reverse(set1->rbegin()); typename Set::const_iterator cit(constSet.begin()); typename Set::const_reverse_iterator creverse(constSet.rbegin()); EXPECT_EQ(0, (*it)->value()); EXPECT_EQ(0, (*cit)->value()); ++it; ++cit; EXPECT_EQ(2, (*it)->value()); EXPECT_EQ(2, (*cit)->value()); --it; --cit; EXPECT_EQ(0, (*it)->value()); EXPECT_EQ(0, (*cit)->value()); ++it; ++cit; ++it; ++cit; EXPECT_EQ(103, (*it)->value()); EXPECT_EQ(103, (*cit)->value()); ++it; ++cit; EXPECT_EQ(10, (*it)->value()); EXPECT_EQ(10, (*cit)->value()); ++it; ++cit; EXPECT_EQ(10, (*reverse)->value()); EXPECT_EQ(10, (*creverse)->value()); ++reverse; ++creverse; EXPECT_EQ(103, (*reverse)->value()); EXPECT_EQ(103, (*creverse)->value()); --reverse; --creverse; EXPECT_EQ(10, (*reverse)->value()); EXPECT_EQ(10, (*creverse)->value()); ++reverse; ++creverse; ++reverse; ++creverse; EXPECT_EQ(2, (*reverse)->value()); EXPECT_EQ(2, (*creverse)->value()); ++reverse; ++creverse; EXPECT_EQ(0, (*reverse)->value()); EXPECT_EQ(0, (*creverse)->value()); ++reverse; ++creverse; EXPECT_EQ(set1->end(), it); EXPECT_EQ(constSet.end(), cit); EXPECT_EQ(set1->rend(), reverse); EXPECT_EQ(constSet.rend(), creverse); typename Set::iterator iX(set2->begin()); EXPECT_EQ(set2->end(), iX); if (strong) set1->remove(keepNumbersAlive[0]); keepNumbersAlive[0] = nullptr; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2u + (strong ? 1u : 0u), set1->size()); EXPECT_EQ(2 + (strong ? 0 : 1), IntWrapper::s_destructorCalls); typename Set::iterator i2(set1->begin()); if (strong) { EXPECT_EQ(0, (*i2)->value()); ++i2; EXPECT_NE(set1->end(), i2); } EXPECT_EQ(103, (*i2)->value()); ++i2; EXPECT_NE(set1->end(), i2); EXPECT_EQ(10, (*i2)->value()); ++i2; EXPECT_EQ(set1->end(), i2); } TEST(HeapTest, HeapWeakLinkedHashSet) { orderedSetHelper<HeapLinkedHashSet<Member<IntWrapper>>>(true); orderedSetHelper<HeapLinkedHashSet<WeakMember<IntWrapper>>>(false); orderedSetHelper<HeapListHashSet<Member<IntWrapper>>>(true); } class ThingWithDestructor { public: ThingWithDestructor() : m_x(emptyValue) { s_liveThingsWithDestructor++; } ThingWithDestructor(int x) : m_x(x) { s_liveThingsWithDestructor++; } ThingWithDestructor(const ThingWithDestructor&other) { *this = other; s_liveThingsWithDestructor++; } ~ThingWithDestructor() { s_liveThingsWithDestructor--; } int value() { return m_x; } static int s_liveThingsWithDestructor; unsigned hash() { return IntHash<int>::hash(m_x); } private: static const int emptyValue = 0; int m_x; }; int ThingWithDestructor::s_liveThingsWithDestructor; static void heapMapDestructorHelper(bool clearMaps) { clearOutOldGarbage(); ThingWithDestructor::s_liveThingsWithDestructor = 0; typedef HeapHashMap<WeakMember<IntWrapper>, Member<RefCountedAndGarbageCollected>> RefMap; typedef HeapHashMap< WeakMember<IntWrapper>, ThingWithDestructor, DefaultHash<WeakMember<IntWrapper>>::Hash, HashTraits<WeakMember<IntWrapper>>> Map; Persistent<Map> map(new Map()); Persistent<RefMap> refMap(new RefMap()); Persistent<IntWrapper> luck(IntWrapper::create(103)); int baseLine, refBaseLine; { Map stackMap; RefMap stackRefMap; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); stackMap.add(IntWrapper::create(42), ThingWithDestructor(1729)); stackMap.add(luck, ThingWithDestructor(8128)); stackRefMap.add(IntWrapper::create(42), RefCountedAndGarbageCollected::create()); stackRefMap.add(luck, RefCountedAndGarbageCollected::create()); baseLine = ThingWithDestructor::s_liveThingsWithDestructor; refBaseLine = RefCountedAndGarbageCollected::s_destructorCalls; // Although the heap maps are on-stack, we can't expect prompt // finalization of the elements, so when they go out of scope here we // will not necessarily have called the relevant destructors. } // The RefCountedAndGarbageCollected things need an extra GC to discover // that they are no longer ref counted. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(baseLine - 2, ThingWithDestructor::s_liveThingsWithDestructor); EXPECT_EQ(refBaseLine + 2, RefCountedAndGarbageCollected::s_destructorCalls); // Now use maps kept alive with persistents. Here we don't expect any // destructors to be called before there have been GCs. map->add(IntWrapper::create(42), ThingWithDestructor(1729)); map->add(luck, ThingWithDestructor(8128)); refMap->add(IntWrapper::create(42), RefCountedAndGarbageCollected::create()); refMap->add(luck, RefCountedAndGarbageCollected::create()); baseLine = ThingWithDestructor::s_liveThingsWithDestructor; refBaseLine = RefCountedAndGarbageCollected::s_destructorCalls; luck.clear(); if (clearMaps) { map->clear(); // Clear map. refMap->clear(); // Clear map. } else { map.clear(); // Clear Persistent handle, not map. refMap.clear(); // Clear Persistent handle, not map. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); } EXPECT_EQ(baseLine - 2, ThingWithDestructor::s_liveThingsWithDestructor); // Need a GC to make sure that the RefCountedAndGarbageCollected thing // noticies it's been decremented to zero. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(refBaseLine + 2, RefCountedAndGarbageCollected::s_destructorCalls); } TEST(HeapTest, HeapMapDestructor) { heapMapDestructorHelper(true); heapMapDestructorHelper(false); } typedef HeapHashSet<PairWeakStrong> WeakStrongSet; typedef HeapHashSet<PairWeakUnwrapped> WeakUnwrappedSet; typedef HeapHashSet<PairStrongWeak> StrongWeakSet; typedef HeapHashSet<PairUnwrappedWeak> UnwrappedWeakSet; typedef HeapLinkedHashSet<PairWeakStrong> WeakStrongLinkedSet; typedef HeapLinkedHashSet<PairWeakUnwrapped> WeakUnwrappedLinkedSet; typedef HeapLinkedHashSet<PairStrongWeak> StrongWeakLinkedSet; typedef HeapLinkedHashSet<PairUnwrappedWeak> UnwrappedWeakLinkedSet; typedef HeapHashCountedSet<PairWeakStrong> WeakStrongCountedSet; typedef HeapHashCountedSet<PairWeakUnwrapped> WeakUnwrappedCountedSet; typedef HeapHashCountedSet<PairStrongWeak> StrongWeakCountedSet; typedef HeapHashCountedSet<PairUnwrappedWeak> UnwrappedWeakCountedSet; template<typename T> T& iteratorExtractor(WTF::KeyValuePair<T, unsigned>& pair) { return pair.key; } template<typename T> T& iteratorExtractor(T& notAPair) { return notAPair; } template<typename WSSet, typename SWSet, typename WUSet, typename UWSet> void checkPairSets( Persistent<WSSet>& weakStrong, Persistent<SWSet>& strongWeak, Persistent<WUSet>& weakUnwrapped, Persistent<UWSet>& unwrappedWeak, bool ones, Persistent<IntWrapper>& two) { typename WSSet::iterator itWS = weakStrong->begin(); typename SWSet::iterator itSW = strongWeak->begin(); typename WUSet::iterator itWU = weakUnwrapped->begin(); typename UWSet::iterator itUW = unwrappedWeak->begin(); EXPECT_EQ(2u, weakStrong->size()); EXPECT_EQ(2u, strongWeak->size()); EXPECT_EQ(2u, weakUnwrapped->size()); EXPECT_EQ(2u, unwrappedWeak->size()); PairWeakStrong p = iteratorExtractor(*itWS); PairStrongWeak p2 = iteratorExtractor(*itSW); PairWeakUnwrapped p3 = iteratorExtractor(*itWU); PairUnwrappedWeak p4 = iteratorExtractor(*itUW); if (p.first == two && p.second == two) ++itWS; if (p2.first == two && p2.second == two) ++itSW; if (p3.first == two && p3.second == 2) ++itWU; if (p4.first == 2 && p4.second == two) ++itUW; p = iteratorExtractor(*itWS); p2 = iteratorExtractor(*itSW); p3 = iteratorExtractor(*itWU); p4 = iteratorExtractor(*itUW); IntWrapper* nullWrapper = 0; if (ones) { EXPECT_EQ(p.first->value(), 1); EXPECT_EQ(p2.second->value(), 1); EXPECT_EQ(p3.first->value(), 1); EXPECT_EQ(p4.second->value(), 1); } else { EXPECT_EQ(p.first, nullWrapper); EXPECT_EQ(p2.second, nullWrapper); EXPECT_EQ(p3.first, nullWrapper); EXPECT_EQ(p4.second, nullWrapper); } EXPECT_EQ(p.second->value(), 2); EXPECT_EQ(p2.first->value(), 2); EXPECT_EQ(p3.second, 2); EXPECT_EQ(p4.first, 2); EXPECT_TRUE(weakStrong->contains(PairWeakStrong(&*two, &*two))); EXPECT_TRUE(strongWeak->contains(PairStrongWeak(&*two, &*two))); EXPECT_TRUE(weakUnwrapped->contains(PairWeakUnwrapped(&*two, 2))); EXPECT_TRUE(unwrappedWeak->contains(PairUnwrappedWeak(2, &*two))); } template<typename WSSet, typename SWSet, typename WUSet, typename UWSet> void weakPairsHelper() { IntWrapper::s_destructorCalls = 0; PersistentHeapVector<Member<IntWrapper>> keepNumbersAlive; Persistent<WSSet> weakStrong = new WSSet(); Persistent<SWSet> strongWeak = new SWSet(); Persistent<WUSet> weakUnwrapped = new WUSet(); Persistent<UWSet> unwrappedWeak = new UWSet(); Persistent<IntWrapper> two = IntWrapper::create(2); weakStrong->add(PairWeakStrong(IntWrapper::create(1), &*two)); weakStrong->add(PairWeakStrong(&*two, &*two)); strongWeak->add(PairStrongWeak(&*two, IntWrapper::create(1))); strongWeak->add(PairStrongWeak(&*two, &*two)); weakUnwrapped->add(PairWeakUnwrapped(IntWrapper::create(1), 2)); weakUnwrapped->add(PairWeakUnwrapped(&*two, 2)); unwrappedWeak->add(PairUnwrappedWeak(2, IntWrapper::create(1))); unwrappedWeak->add(PairUnwrappedWeak(2, &*two)); checkPairSets<WSSet, SWSet, WUSet, UWSet>(weakStrong, strongWeak, weakUnwrapped, unwrappedWeak, true, two); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); checkPairSets<WSSet, SWSet, WUSet, UWSet>(weakStrong, strongWeak, weakUnwrapped, unwrappedWeak, false, two); } TEST(HeapTest, HeapWeakPairs) { { typedef HeapHashSet<PairWeakStrong> WeakStrongSet; typedef HeapHashSet<PairWeakUnwrapped> WeakUnwrappedSet; typedef HeapHashSet<PairStrongWeak> StrongWeakSet; typedef HeapHashSet<PairUnwrappedWeak> UnwrappedWeakSet; weakPairsHelper<WeakStrongSet, StrongWeakSet, WeakUnwrappedSet, UnwrappedWeakSet>(); } { typedef HeapListHashSet<PairWeakStrong> WeakStrongSet; typedef HeapListHashSet<PairWeakUnwrapped> WeakUnwrappedSet; typedef HeapListHashSet<PairStrongWeak> StrongWeakSet; typedef HeapListHashSet<PairUnwrappedWeak> UnwrappedWeakSet; weakPairsHelper<WeakStrongSet, StrongWeakSet, WeakUnwrappedSet, UnwrappedWeakSet>(); } { typedef HeapLinkedHashSet<PairWeakStrong> WeakStrongSet; typedef HeapLinkedHashSet<PairWeakUnwrapped> WeakUnwrappedSet; typedef HeapLinkedHashSet<PairStrongWeak> StrongWeakSet; typedef HeapLinkedHashSet<PairUnwrappedWeak> UnwrappedWeakSet; weakPairsHelper<WeakStrongSet, StrongWeakSet, WeakUnwrappedSet, UnwrappedWeakSet>(); } } TEST(HeapTest, HeapWeakCollectionTypes) { IntWrapper::s_destructorCalls = 0; typedef HeapHashMap<WeakMember<IntWrapper>, Member<IntWrapper>> WeakStrong; typedef HeapHashMap<Member<IntWrapper>, WeakMember<IntWrapper>> StrongWeak; typedef HeapHashMap<WeakMember<IntWrapper>, WeakMember<IntWrapper>> WeakWeak; typedef HeapHashSet<WeakMember<IntWrapper>> WeakSet; typedef HeapLinkedHashSet<WeakMember<IntWrapper>> WeakOrderedSet; clearOutOldGarbage(); const int weakStrongIndex = 0; const int strongWeakIndex = 1; const int weakWeakIndex = 2; const int numberOfMapIndices = 3; const int weakSetIndex = 3; const int weakOrderedSetIndex = 4; const int numberOfCollections = 5; for (int testRun = 0; testRun < 4; testRun++) { for (int collectionNumber = 0; collectionNumber < numberOfCollections; collectionNumber++) { bool deleteAfterwards = (testRun == 1); bool addAfterwards = (testRun == 2); bool testThatIteratorsMakeStrong = (testRun == 3); // The test doesn't work for strongWeak with deleting because we lost // the key from the keepNumbersAlive array, so we can't do the lookup. if (deleteAfterwards && collectionNumber == strongWeakIndex) continue; unsigned added = addAfterwards ? 100 : 0; Persistent<WeakStrong> weakStrong = new WeakStrong(); Persistent<StrongWeak> strongWeak = new StrongWeak(); Persistent<WeakWeak> weakWeak = new WeakWeak(); Persistent<WeakSet> weakSet = new WeakSet(); Persistent<WeakOrderedSet> weakOrderedSet = new WeakOrderedSet(); PersistentHeapVector<Member<IntWrapper>> keepNumbersAlive; for (int i = 0; i < 128; i += 2) { IntWrapper* wrapped = IntWrapper::create(i); IntWrapper* wrapped2 = IntWrapper::create(i + 1); keepNumbersAlive.append(wrapped); keepNumbersAlive.append(wrapped2); weakStrong->add(wrapped, wrapped2); strongWeak->add(wrapped2, wrapped); weakWeak->add(wrapped, wrapped2); weakSet->add(wrapped); weakOrderedSet->add(wrapped); } EXPECT_EQ(64u, weakStrong->size()); EXPECT_EQ(64u, strongWeak->size()); EXPECT_EQ(64u, weakWeak->size()); EXPECT_EQ(64u, weakSet->size()); EXPECT_EQ(64u, weakOrderedSet->size()); // Collect garbage. This should change nothing since we are keeping // alive the IntWrapper objects. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(64u, weakStrong->size()); EXPECT_EQ(64u, strongWeak->size()); EXPECT_EQ(64u, weakWeak->size()); EXPECT_EQ(64u, weakSet->size()); EXPECT_EQ(64u, weakOrderedSet->size()); for (int i = 0; i < 128; i += 2) { IntWrapper* wrapped = keepNumbersAlive[i]; IntWrapper* wrapped2 = keepNumbersAlive[i + 1]; EXPECT_EQ(wrapped2, weakStrong->get(wrapped)); EXPECT_EQ(wrapped, strongWeak->get(wrapped2)); EXPECT_EQ(wrapped2, weakWeak->get(wrapped)); EXPECT_TRUE(weakSet->contains(wrapped)); EXPECT_TRUE(weakOrderedSet->contains(wrapped)); } for (int i = 0; i < 128; i += 3) keepNumbersAlive[i] = nullptr; if (collectionNumber != weakStrongIndex) weakStrong->clear(); if (collectionNumber != strongWeakIndex) strongWeak->clear(); if (collectionNumber != weakWeakIndex) weakWeak->clear(); if (collectionNumber != weakSetIndex) weakSet->clear(); if (collectionNumber != weakOrderedSetIndex) weakOrderedSet->clear(); if (testThatIteratorsMakeStrong) { WeakStrong::iterator it1 = weakStrong->begin(); StrongWeak::iterator it2 = strongWeak->begin(); WeakWeak::iterator it3 = weakWeak->begin(); WeakSet::iterator it4 = weakSet->begin(); WeakOrderedSet::iterator it5 = weakOrderedSet->begin(); // Collect garbage. This should change nothing since the // iterators make the collections strong. Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); if (collectionNumber == weakStrongIndex) { EXPECT_EQ(64u, weakStrong->size()); MapIteratorCheck(it1, weakStrong->end(), 64); } else if (collectionNumber == strongWeakIndex) { EXPECT_EQ(64u, strongWeak->size()); MapIteratorCheck(it2, strongWeak->end(), 64); } else if (collectionNumber == weakWeakIndex) { EXPECT_EQ(64u, weakWeak->size()); MapIteratorCheck(it3, weakWeak->end(), 64); } else if (collectionNumber == weakSetIndex) { EXPECT_EQ(64u, weakSet->size()); SetIteratorCheck(it4, weakSet->end(), 64); } else if (collectionNumber == weakOrderedSetIndex) { EXPECT_EQ(64u, weakOrderedSet->size()); SetIteratorCheck(it5, weakOrderedSet->end(), 64); } } else { // Collect garbage. This causes weak processing to remove // things from the collections. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); unsigned count = 0; for (int i = 0; i < 128; i += 2) { bool firstAlive = keepNumbersAlive[i]; bool secondAlive = keepNumbersAlive[i + 1]; if (firstAlive && (collectionNumber == weakStrongIndex || collectionNumber == strongWeakIndex)) secondAlive = true; if (firstAlive && secondAlive && collectionNumber < numberOfMapIndices) { if (collectionNumber == weakStrongIndex) { if (deleteAfterwards) EXPECT_EQ(i + 1, weakStrong->take(keepNumbersAlive[i])->value()); } else if (collectionNumber == strongWeakIndex) { if (deleteAfterwards) EXPECT_EQ(i, strongWeak->take(keepNumbersAlive[i + 1])->value()); } else if (collectionNumber == weakWeakIndex) { if (deleteAfterwards) EXPECT_EQ(i + 1, weakWeak->take(keepNumbersAlive[i])->value()); } if (!deleteAfterwards) count++; } else if (collectionNumber == weakSetIndex && firstAlive) { ASSERT_TRUE(weakSet->contains(keepNumbersAlive[i])); if (deleteAfterwards) weakSet->remove(keepNumbersAlive[i]); else count++; } else if (collectionNumber == weakOrderedSetIndex && firstAlive) { ASSERT_TRUE(weakOrderedSet->contains(keepNumbersAlive[i])); if (deleteAfterwards) weakOrderedSet->remove(keepNumbersAlive[i]); else count++; } } if (addAfterwards) { for (int i = 1000; i < 1100; i++) { IntWrapper* wrapped = IntWrapper::create(i); keepNumbersAlive.append(wrapped); weakStrong->add(wrapped, wrapped); strongWeak->add(wrapped, wrapped); weakWeak->add(wrapped, wrapped); weakSet->add(wrapped); weakOrderedSet->add(wrapped); } } if (collectionNumber == weakStrongIndex) EXPECT_EQ(count + added, weakStrong->size()); else if (collectionNumber == strongWeakIndex) EXPECT_EQ(count + added, strongWeak->size()); else if (collectionNumber == weakWeakIndex) EXPECT_EQ(count + added, weakWeak->size()); else if (collectionNumber == weakSetIndex) EXPECT_EQ(count + added, weakSet->size()); else if (collectionNumber == weakOrderedSetIndex) EXPECT_EQ(count + added, weakOrderedSet->size()); WeakStrong::iterator it1 = weakStrong->begin(); StrongWeak::iterator it2 = strongWeak->begin(); WeakWeak::iterator it3 = weakWeak->begin(); WeakSet::iterator it4 = weakSet->begin(); WeakOrderedSet::iterator it5 = weakOrderedSet->begin(); MapIteratorCheck(it1, weakStrong->end(), (collectionNumber == weakStrongIndex ? count : 0) + added); MapIteratorCheck(it2, strongWeak->end(), (collectionNumber == strongWeakIndex ? count : 0) + added); MapIteratorCheck(it3, weakWeak->end(), (collectionNumber == weakWeakIndex ? count : 0) + added); SetIteratorCheck(it4, weakSet->end(), (collectionNumber == weakSetIndex ? count : 0) + added); SetIteratorCheck(it5, weakOrderedSet->end(), (collectionNumber == weakOrderedSetIndex ? count : 0) + added); } for (unsigned i = 0; i < 128 + added; i++) keepNumbersAlive[i] = nullptr; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, weakStrong->size()); EXPECT_EQ(0u, strongWeak->size()); EXPECT_EQ(0u, weakWeak->size()); EXPECT_EQ(0u, weakSet->size()); EXPECT_EQ(0u, weakOrderedSet->size()); } } } TEST(HeapTest, RefCountedGarbageCollected) { RefCountedAndGarbageCollected::s_destructorCalls = 0; { RefPtr<RefCountedAndGarbageCollected> refPtr3; { Persistent<RefCountedAndGarbageCollected> persistent; { Persistent<RefCountedAndGarbageCollected> refPtr1 = RefCountedAndGarbageCollected::create(); Persistent<RefCountedAndGarbageCollected> refPtr2 = RefCountedAndGarbageCollected::create(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, RefCountedAndGarbageCollected::s_destructorCalls); persistent = refPtr1.get(); } // Reference count is zero for both objects but one of // them is kept alive by a persistent handle. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, RefCountedAndGarbageCollected::s_destructorCalls); refPtr3 = persistent.get(); } // The persistent handle is gone but the ref count has been // increased to 1. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, RefCountedAndGarbageCollected::s_destructorCalls); } // Both persistent handle is gone and ref count is zero so the // object can be collected. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2, RefCountedAndGarbageCollected::s_destructorCalls); } TEST(HeapTest, RefCountedGarbageCollectedWithStackPointers) { RefCountedAndGarbageCollected::s_destructorCalls = 0; RefCountedAndGarbageCollected2::s_destructorCalls = 0; { RefCountedAndGarbageCollected* pointer1 = 0; RefCountedAndGarbageCollected2* pointer2 = 0; { Persistent<RefCountedAndGarbageCollected> object1 = RefCountedAndGarbageCollected::create(); Persistent<RefCountedAndGarbageCollected2> object2 = RefCountedAndGarbageCollected2::create(); pointer1 = object1.get(); pointer2 = object2.get(); void* objects[2] = { object1.get(), object2.get() }; RefCountedGarbageCollectedVisitor visitor(2, objects); ThreadState::current()->visitPersistents(&visitor); EXPECT_TRUE(visitor.validate()); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, RefCountedAndGarbageCollected::s_destructorCalls); EXPECT_EQ(0, RefCountedAndGarbageCollected2::s_destructorCalls); } Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, RefCountedAndGarbageCollected::s_destructorCalls); EXPECT_EQ(0, RefCountedAndGarbageCollected2::s_destructorCalls); // At this point, the reference counts of object1 and object2 are 0. // Only pointer1 and pointer2 keep references to object1 and object2. void* objects[] = { 0 }; RefCountedGarbageCollectedVisitor visitor(0, objects); ThreadState::current()->visitPersistents(&visitor); EXPECT_TRUE(visitor.validate()); { Persistent<RefCountedAndGarbageCollected> object1(pointer1); Persistent<RefCountedAndGarbageCollected2> object2(pointer2); void* objects[2] = { object1.get(), object2.get() }; RefCountedGarbageCollectedVisitor visitor(2, objects); ThreadState::current()->visitPersistents(&visitor); EXPECT_TRUE(visitor.validate()); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, RefCountedAndGarbageCollected::s_destructorCalls); EXPECT_EQ(0, RefCountedAndGarbageCollected2::s_destructorCalls); } Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, RefCountedAndGarbageCollected::s_destructorCalls); EXPECT_EQ(0, RefCountedAndGarbageCollected2::s_destructorCalls); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, RefCountedAndGarbageCollected::s_destructorCalls); EXPECT_EQ(1, RefCountedAndGarbageCollected2::s_destructorCalls); } TEST(HeapTest, WeakMembers) { Bar::s_live = 0; { Persistent<Bar> h1 = Bar::create(); Persistent<Weak> h4; Persistent<WithWeakMember> h5; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); ASSERT_EQ(1u, Bar::s_live); // h1 is live. { Bar* h2 = Bar::create(); Bar* h3 = Bar::create(); h4 = Weak::create(h2, h3); h5 = WithWeakMember::create(h2, h3); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(5u, Bar::s_live); // The on-stack pointer keeps h3 alive. EXPECT_TRUE(h4->strongIsThere()); EXPECT_TRUE(h4->weakIsThere()); EXPECT_TRUE(h5->strongIsThere()); EXPECT_TRUE(h5->weakIsThere()); } // h3 is collected, weak pointers from h4 and h5 don't keep it alive. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(4u, Bar::s_live); EXPECT_TRUE(h4->strongIsThere()); EXPECT_FALSE(h4->weakIsThere()); // h3 is gone from weak pointer. EXPECT_TRUE(h5->strongIsThere()); EXPECT_FALSE(h5->weakIsThere()); // h3 is gone from weak pointer. h1.release(); // Zero out h1. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(3u, Bar::s_live); // Only h4, h5 and h2 are left. EXPECT_TRUE(h4->strongIsThere()); // h2 is still pointed to from h4. EXPECT_TRUE(h5->strongIsThere()); // h2 is still pointed to from h5. } // h4 and h5 have gone out of scope now and they were keeping h2 alive. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, Bar::s_live); // All gone. } TEST(HeapTest, FinalizationObserver) { Persistent<FinalizationObserver<Observable>> o; { Observable* foo = Observable::create(Bar::create()); // |o| observes |foo|. o = FinalizationObserver<Observable>::create(foo); } // FinalizationObserver doesn't have a strong reference to |foo|. So |foo| // and its member will be collected. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, Bar::s_live); EXPECT_TRUE(o->didCallWillFinalize()); FinalizationObserverWithHashMap::s_didCallWillFinalize = false; Observable* foo = Observable::create(Bar::create()); FinalizationObserverWithHashMap::ObserverMap& map = FinalizationObserverWithHashMap::observe(*foo); EXPECT_EQ(1u, map.size()); foo = 0; // FinalizationObserverWithHashMap doesn't have a strong reference to // |foo|. So |foo| and its member will be collected. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, Bar::s_live); EXPECT_EQ(0u, map.size()); EXPECT_TRUE(FinalizationObserverWithHashMap::s_didCallWillFinalize); FinalizationObserverWithHashMap::clearObservers(); } TEST(HeapTest, PreFinalizer) { Observable::s_willFinalizeWasCalled = false; { Observable* foo = Observable::create(Bar::create()); ThreadState::current()->registerPreFinalizer(*foo); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(Observable::s_willFinalizeWasCalled); } TEST(HeapTest, PreFinalizerIsNotCalledIfUnregistered) { Observable::s_willFinalizeWasCalled = false; { Observable* foo = Observable::create(Bar::create()); ThreadState::current()->registerPreFinalizer(*foo); ThreadState::current()->unregisterPreFinalizer(*foo); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_FALSE(Observable::s_willFinalizeWasCalled); } TEST(HeapTest, PreFinalizerUnregistersItself) { ObservableWithPreFinalizer::s_disposeWasCalled = false; ObservableWithPreFinalizer::create(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(ObservableWithPreFinalizer::s_disposeWasCalled); // Don't crash, and assertions don't fail. } TEST(HeapTest, Comparisons) { Persistent<Bar> barPersistent = Bar::create(); Persistent<Foo> fooPersistent = Foo::create(barPersistent); EXPECT_TRUE(barPersistent != fooPersistent); barPersistent = fooPersistent; EXPECT_TRUE(barPersistent == fooPersistent); } TEST(HeapTest, CheckAndMarkPointer) { clearOutOldGarbage(); Vector<Address> objectAddresses; Vector<Address> endAddresses; Address largeObjectAddress; Address largeObjectEndAddress; CountingVisitor visitor; for (int i = 0; i < 10; i++) { SimpleObject* object = SimpleObject::create(); Address objectAddress = reinterpret_cast<Address>(object); objectAddresses.append(objectAddress); endAddresses.append(objectAddress + sizeof(SimpleObject) - 1); } LargeHeapObject* largeObject = LargeHeapObject::create(); largeObjectAddress = reinterpret_cast<Address>(largeObject); largeObjectEndAddress = largeObjectAddress + sizeof(LargeHeapObject) - 1; // This is a low-level test where we call checkAndMarkPointer. This method // causes the object start bitmap to be computed which requires the heap // to be in a consistent state (e.g. the free allocation area must be put // into a free list header). However when we call makeConsistentForSweeping it // also clears out the freelists so we have to rebuild those before trying // to allocate anything again. We do this by forcing a GC after doing the // checkAndMarkPointer tests. { TestGCScope scope(ThreadState::HeapPointersOnStack); EXPECT_TRUE(scope.allThreadsParked()); // Fail the test if we could not park all threads. Heap::flushHeapDoesNotContainCache(); for (size_t i = 0; i < objectAddresses.size(); i++) { EXPECT_TRUE(Heap::checkAndMarkPointer(&visitor, objectAddresses[i])); EXPECT_TRUE(Heap::checkAndMarkPointer(&visitor, endAddresses[i])); } EXPECT_EQ(objectAddresses.size() * 2, visitor.count()); visitor.reset(); EXPECT_TRUE(Heap::checkAndMarkPointer(&visitor, largeObjectAddress)); EXPECT_TRUE(Heap::checkAndMarkPointer(&visitor, largeObjectEndAddress)); EXPECT_EQ(2ul, visitor.count()); visitor.reset(); } // This forces a GC without stack scanning which results in the objects // being collected. This will also rebuild the above mentioned freelists, // however we don't rely on that below since we don't have any allocations. clearOutOldGarbage(); { TestGCScope scope(ThreadState::HeapPointersOnStack); EXPECT_TRUE(scope.allThreadsParked()); Heap::flushHeapDoesNotContainCache(); for (size_t i = 0; i < objectAddresses.size(); i++) { // We would like to assert that checkAndMarkPointer returned false // here because the pointers no longer point into a valid object // (it's been freed by the GCs. But checkAndMarkPointer will return // true for any pointer that points into a heap page, regardless of // whether it points at a valid object (this ensures the // correctness of the page-based on-heap address caches), so we // can't make that assert. Heap::checkAndMarkPointer(&visitor, objectAddresses[i]); Heap::checkAndMarkPointer(&visitor, endAddresses[i]); } EXPECT_EQ(0ul, visitor.count()); Heap::checkAndMarkPointer(&visitor, largeObjectAddress); Heap::checkAndMarkPointer(&visitor, largeObjectEndAddress); EXPECT_EQ(0ul, visitor.count()); } // This round of GC is important to make sure that the object start // bitmap are cleared out and that the free lists are rebuild. clearOutOldGarbage(); } TEST(HeapTest, VisitOffHeapCollections) { clearOutOldGarbage(); IntWrapper::s_destructorCalls = 0; Persistent<OffHeapContainer> container = OffHeapContainer::create(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, IntWrapper::s_destructorCalls); container = nullptr; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(OffHeapContainer::deadWrappers, IntWrapper::s_destructorCalls); } TEST(HeapTest, PersistentHeapCollectionTypes) { IntWrapper::s_destructorCalls = 0; typedef HeapVector<Member<IntWrapper>> Vec; typedef PersistentHeapVector<Member<IntWrapper>> PVec; typedef PersistentHeapHashSet<Member<IntWrapper>> PSet; typedef PersistentHeapListHashSet<Member<IntWrapper>> PListSet; typedef PersistentHeapLinkedHashSet<Member<IntWrapper>> PLinkedSet; typedef PersistentHeapHashMap<Member<IntWrapper>, Member<IntWrapper>> PMap; typedef PersistentHeapHashMap<WeakMember<IntWrapper>, Member<IntWrapper>> WeakPMap; typedef PersistentHeapDeque<Member<IntWrapper>> PDeque; clearOutOldGarbage(); { PVec pVec; PDeque pDeque; PSet pSet; PListSet pListSet; PLinkedSet pLinkedSet; PMap pMap; WeakPMap wpMap; IntWrapper* one(IntWrapper::create(1)); IntWrapper* two(IntWrapper::create(2)); IntWrapper* three(IntWrapper::create(3)); IntWrapper* four(IntWrapper::create(4)); IntWrapper* five(IntWrapper::create(5)); IntWrapper* six(IntWrapper::create(6)); IntWrapper* seven(IntWrapper::create(7)); IntWrapper* eight(IntWrapper::create(8)); IntWrapper* nine(IntWrapper::create(9)); Persistent<IntWrapper> ten(IntWrapper::create(10)); IntWrapper* eleven(IntWrapper::create(11)); pVec.append(one); pVec.append(two); pDeque.append(seven); pDeque.append(two); Vec* vec = new Vec(); vec->swap(pVec); pVec.append(two); pVec.append(three); pSet.add(four); pListSet.add(eight); pLinkedSet.add(nine); pMap.add(five, six); wpMap.add(ten, eleven); // Collect |vec| and |one|. vec = 0; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, IntWrapper::s_destructorCalls); EXPECT_EQ(2u, pVec.size()); EXPECT_EQ(two, pVec.at(0)); EXPECT_EQ(three, pVec.at(1)); EXPECT_EQ(2u, pDeque.size()); EXPECT_EQ(seven, pDeque.first()); EXPECT_EQ(seven, pDeque.takeFirst()); EXPECT_EQ(two, pDeque.first()); EXPECT_EQ(1u, pDeque.size()); EXPECT_EQ(1u, pSet.size()); EXPECT_TRUE(pSet.contains(four)); EXPECT_EQ(1u, pListSet.size()); EXPECT_TRUE(pListSet.contains(eight)); EXPECT_EQ(1u, pLinkedSet.size()); EXPECT_TRUE(pLinkedSet.contains(nine)); EXPECT_EQ(1u, pMap.size()); EXPECT_EQ(six, pMap.get(five)); EXPECT_EQ(1u, wpMap.size()); EXPECT_EQ(eleven, wpMap.get(ten)); ten.clear(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, wpMap.size()); } // Collect previous roots. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(11, IntWrapper::s_destructorCalls); } TEST(HeapTest, CollectionNesting) { clearOutOldGarbage(); int* key = &IntWrapper::s_destructorCalls; IntWrapper::s_destructorCalls = 0; typedef HeapVector<Member<IntWrapper>> IntVector; typedef HeapDeque<Member<IntWrapper>> IntDeque; HeapHashMap<void*, IntVector>* map = new HeapHashMap<void*, IntVector>(); HeapHashMap<void*, IntDeque>* map2 = new HeapHashMap<void*, IntDeque>(); static_assert(WTF::NeedsTracing<IntVector>::value, "Failed to recognize HeapVector as NeedsTracing"); static_assert(WTF::NeedsTracing<IntDeque>::value, "Failed to recognize HeapDeque as NeedsTracing"); map->add(key, IntVector()); map2->add(key, IntDeque()); HeapHashMap<void*, IntVector>::iterator it = map->find(key); EXPECT_EQ(0u, map->get(key).size()); HeapHashMap<void*, IntDeque>::iterator it2 = map2->find(key); EXPECT_EQ(0u, map2->get(key).size()); it->value.append(IntWrapper::create(42)); EXPECT_EQ(1u, map->get(key).size()); it2->value.append(IntWrapper::create(42)); EXPECT_EQ(1u, map2->get(key).size()); Persistent<HeapHashMap<void*, IntVector>> keepAlive(map); Persistent<HeapHashMap<void*, IntDeque>> keepAlive2(map2); for (int i = 0; i < 100; i++) { map->add(key + 1 + i, IntVector()); map2->add(key + 1 + i, IntDeque()); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1u, map->get(key).size()); EXPECT_EQ(1u, map2->get(key).size()); EXPECT_EQ(0, IntWrapper::s_destructorCalls); keepAlive = nullptr; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, IntWrapper::s_destructorCalls); } TEST(HeapTest, GarbageCollectedMixin) { clearOutOldGarbage(); Persistent<UseMixin> usemixin = UseMixin::create(); EXPECT_EQ(0, UseMixin::s_traceCount); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1, UseMixin::s_traceCount); Persistent<Mixin> mixin = usemixin; usemixin = nullptr; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2, UseMixin::s_traceCount); PersistentHeapHashSet<WeakMember<Mixin>> weakMap; weakMap.add(UseMixin::create()); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, weakMap.size()); } TEST(HeapTest, CollectionNesting2) { clearOutOldGarbage(); void* key = &IntWrapper::s_destructorCalls; IntWrapper::s_destructorCalls = 0; typedef HeapHashSet<Member<IntWrapper>> IntSet; HeapHashMap<void*, IntSet>* map = new HeapHashMap<void*, IntSet>(); map->add(key, IntSet()); HeapHashMap<void*, IntSet>::iterator it = map->find(key); EXPECT_EQ(0u, map->get(key).size()); it->value.add(IntWrapper::create(42)); EXPECT_EQ(1u, map->get(key).size()); Persistent<HeapHashMap<void*, IntSet>> keepAlive(map); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1u, map->get(key).size()); EXPECT_EQ(0, IntWrapper::s_destructorCalls); } TEST(HeapTest, CollectionNesting3) { clearOutOldGarbage(); IntWrapper::s_destructorCalls = 0; typedef HeapVector<Member<IntWrapper>> IntVector; typedef HeapDeque<Member<IntWrapper>> IntDeque; HeapVector<IntVector>* vector = new HeapVector<IntVector>(); HeapDeque<IntDeque>* deque = new HeapDeque<IntDeque>(); vector->append(IntVector()); deque->append(IntDeque()); HeapVector<IntVector>::iterator it = vector->begin(); HeapDeque<IntDeque>::iterator it2 = deque->begin(); EXPECT_EQ(0u, it->size()); EXPECT_EQ(0u, it2->size()); it->append(IntWrapper::create(42)); it2->append(IntWrapper::create(42)); EXPECT_EQ(1u, it->size()); EXPECT_EQ(1u, it2->size()); Persistent<HeapVector<IntVector>> keepAlive(vector); Persistent<HeapDeque<IntDeque>> keepAlive2(deque); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1u, it->size()); EXPECT_EQ(1u, it2->size()); EXPECT_EQ(0, IntWrapper::s_destructorCalls); } TEST(HeapTest, EmbeddedInVector) { clearOutOldGarbage(); SimpleFinalizedObject::s_destructorCalls = 0; { PersistentHeapVector<VectorObject, 2> inlineVector; PersistentHeapVector<VectorObject> outlineVector; VectorObject i1, i2; inlineVector.append(i1); inlineVector.append(i2); VectorObject o1, o2; outlineVector.append(o1); outlineVector.append(o2); PersistentHeapVector<VectorObjectInheritedTrace> vectorInheritedTrace; VectorObjectInheritedTrace it1, it2; vectorInheritedTrace.append(it1); vectorInheritedTrace.append(it2); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, SimpleFinalizedObject::s_destructorCalls); // Since VectorObjectNoTrace has no trace method it will // not be traced and hence be collected when doing GC. // We trace items in a collection braced on the item's // having a trace method. This is determined via the // NeedsTracing trait in wtf/TypeTraits.h. PersistentHeapVector<VectorObjectNoTrace> vectorNoTrace; VectorObjectNoTrace n1, n2; vectorNoTrace.append(n1); vectorNoTrace.append(n2); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2, SimpleFinalizedObject::s_destructorCalls); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(8, SimpleFinalizedObject::s_destructorCalls); } TEST(HeapTest, EmbeddedInDeque) { clearOutOldGarbage(); SimpleFinalizedObject::s_destructorCalls = 0; { PersistentHeapDeque<VectorObject, 2> inlineDeque; PersistentHeapDeque<VectorObject> outlineDeque; VectorObject i1, i2; inlineDeque.append(i1); inlineDeque.append(i2); VectorObject o1, o2; outlineDeque.append(o1); outlineDeque.append(o2); PersistentHeapDeque<VectorObjectInheritedTrace> dequeInheritedTrace; VectorObjectInheritedTrace it1, it2; dequeInheritedTrace.append(it1); dequeInheritedTrace.append(it2); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, SimpleFinalizedObject::s_destructorCalls); // Since VectorObjectNoTrace has no trace method it will // not be traced and hence be collected when doing GC. // We trace items in a collection braced on the item's // having a trace method. This is determined via the // NeedsTracing trait in wtf/TypeTraits.h. PersistentHeapDeque<VectorObjectNoTrace> dequeNoTrace; VectorObjectNoTrace n1, n2; dequeNoTrace.append(n1); dequeNoTrace.append(n2); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2, SimpleFinalizedObject::s_destructorCalls); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(8, SimpleFinalizedObject::s_destructorCalls); } template<typename Set> void rawPtrInHashHelper() { Set set; set.add(new int(42)); set.add(new int(42)); EXPECT_EQ(2u, set.size()); for (typename Set::iterator it = set.begin(); it != set.end(); ++it) { EXPECT_EQ(42, **it); delete *it; } } TEST(HeapTest, RawPtrInHash) { rawPtrInHashHelper<HashSet<RawPtr<int>>>(); rawPtrInHashHelper<ListHashSet<RawPtr<int>>>(); rawPtrInHashHelper<LinkedHashSet<RawPtr<int>>>(); } TEST(HeapTest, HeapTerminatedArray) { clearOutOldGarbage(); IntWrapper::s_destructorCalls = 0; HeapTerminatedArray<TerminatedArrayItem>* arr = 0; const size_t prefixSize = 4; const size_t suffixSize = 4; { HeapTerminatedArrayBuilder<TerminatedArrayItem> builder(arr); builder.grow(prefixSize); for (size_t i = 0; i < prefixSize; i++) builder.append(TerminatedArrayItem(IntWrapper::create(i))); arr = builder.release(); } Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, IntWrapper::s_destructorCalls); EXPECT_EQ(prefixSize, arr->size()); for (size_t i = 0; i < prefixSize; i++) EXPECT_EQ(i, static_cast<size_t>(arr->at(i).payload()->value())); { HeapTerminatedArrayBuilder<TerminatedArrayItem> builder(arr); builder.grow(suffixSize); for (size_t i = 0; i < suffixSize; i++) builder.append(TerminatedArrayItem(IntWrapper::create(prefixSize + i))); arr = builder.release(); } Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, IntWrapper::s_destructorCalls); EXPECT_EQ(prefixSize + suffixSize, arr->size()); for (size_t i = 0; i < prefixSize + suffixSize; i++) EXPECT_EQ(i, static_cast<size_t>(arr->at(i).payload()->value())); { Persistent<HeapTerminatedArray<TerminatedArrayItem>> persistentArr = arr; arr = 0; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); arr = persistentArr.get(); EXPECT_EQ(0, IntWrapper::s_destructorCalls); EXPECT_EQ(prefixSize + suffixSize, arr->size()); for (size_t i = 0; i < prefixSize + suffixSize; i++) EXPECT_EQ(i, static_cast<size_t>(arr->at(i).payload()->value())); } arr = 0; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(8, IntWrapper::s_destructorCalls); } TEST(HeapTest, HeapLinkedStack) { clearOutOldGarbage(); IntWrapper::s_destructorCalls = 0; HeapLinkedStack<TerminatedArrayItem>* stack = new HeapLinkedStack<TerminatedArrayItem>(); const size_t stackSize = 10; for (size_t i = 0; i < stackSize; i++) stack->push(TerminatedArrayItem(IntWrapper::create(i))); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, IntWrapper::s_destructorCalls); EXPECT_EQ(stackSize, stack->size()); while (!stack->isEmpty()) { EXPECT_EQ(stack->size() - 1, static_cast<size_t>(stack->peek().payload()->value())); stack->pop(); } Persistent<HeapLinkedStack<TerminatedArrayItem>> pStack = stack; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(stackSize, static_cast<size_t>(IntWrapper::s_destructorCalls)); EXPECT_EQ(0u, pStack->size()); } TEST(HeapTest, AllocationDuringFinalization) { clearOutOldGarbage(); IntWrapper::s_destructorCalls = 0; OneKiloByteObject::s_destructorCalls = 0; LargeHeapObject::s_destructorCalls = 0; Persistent<IntWrapper> wrapper; new FinalizationAllocator(&wrapper); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, IntWrapper::s_destructorCalls); EXPECT_EQ(0, OneKiloByteObject::s_destructorCalls); EXPECT_EQ(0, LargeHeapObject::s_destructorCalls); // Check that the wrapper allocated during finalization is not // swept away and zapped later in the same sweeping phase. EXPECT_EQ(42, wrapper->value()); wrapper.clear(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(42, IntWrapper::s_destructorCalls); EXPECT_EQ(512, OneKiloByteObject::s_destructorCalls); EXPECT_EQ(32, LargeHeapObject::s_destructorCalls); } class SimpleClassWithDestructor { public: SimpleClassWithDestructor() { } ~SimpleClassWithDestructor() { s_wasDestructed = true; } static bool s_wasDestructed; }; bool SimpleClassWithDestructor::s_wasDestructed; class RefCountedWithDestructor : public RefCounted<RefCountedWithDestructor> { public: RefCountedWithDestructor() { } ~RefCountedWithDestructor() { s_wasDestructed = true; } static bool s_wasDestructed; }; bool RefCountedWithDestructor::s_wasDestructed; template<typename Set> void destructorsCalledOnGC(bool addLots) { RefCountedWithDestructor::s_wasDestructed = false; { Set set; RefCountedWithDestructor* hasDestructor = new RefCountedWithDestructor(); set.add(adoptRef(hasDestructor)); EXPECT_FALSE(RefCountedWithDestructor::s_wasDestructed); if (addLots) { for (int i = 0; i < 1000; i++) { set.add(adoptRef(new RefCountedWithDestructor())); } } EXPECT_FALSE(RefCountedWithDestructor::s_wasDestructed); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_FALSE(RefCountedWithDestructor::s_wasDestructed); } // The destructors of the sets don't call the destructors of the elements // in the heap sets. You have to actually remove the elments, call clear() // or have a GC to get the destructors called. EXPECT_FALSE(RefCountedWithDestructor::s_wasDestructed); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_TRUE(RefCountedWithDestructor::s_wasDestructed); } template<typename Set> void destructorsCalledOnClear(bool addLots) { RefCountedWithDestructor::s_wasDestructed = false; Set set; RefCountedWithDestructor* hasDestructor = new RefCountedWithDestructor(); set.add(adoptRef(hasDestructor)); EXPECT_FALSE(RefCountedWithDestructor::s_wasDestructed); if (addLots) { for (int i = 0; i < 1000; i++) { set.add(adoptRef(new RefCountedWithDestructor())); } } EXPECT_FALSE(RefCountedWithDestructor::s_wasDestructed); set.clear(); EXPECT_TRUE(RefCountedWithDestructor::s_wasDestructed); } TEST(HeapTest, DestructorsCalled) { HeapHashMap<SimpleClassWithDestructor*, OwnPtr<SimpleClassWithDestructor>> map; SimpleClassWithDestructor* hasDestructor = new SimpleClassWithDestructor(); map.add(hasDestructor, adoptPtr(hasDestructor)); SimpleClassWithDestructor::s_wasDestructed = false; map.clear(); EXPECT_TRUE(SimpleClassWithDestructor::s_wasDestructed); destructorsCalledOnClear<HeapHashSet<RefPtr<RefCountedWithDestructor>>>(false); destructorsCalledOnClear<HeapListHashSet<RefPtr<RefCountedWithDestructor>>>(false); destructorsCalledOnClear<HeapLinkedHashSet<RefPtr<RefCountedWithDestructor>>>(false); destructorsCalledOnClear<HeapHashSet<RefPtr<RefCountedWithDestructor>>>(true); destructorsCalledOnClear<HeapListHashSet<RefPtr<RefCountedWithDestructor>>>(true); destructorsCalledOnClear<HeapLinkedHashSet<RefPtr<RefCountedWithDestructor>>>(true); destructorsCalledOnGC<HeapHashSet<RefPtr<RefCountedWithDestructor>>>(false); destructorsCalledOnGC<HeapListHashSet<RefPtr<RefCountedWithDestructor>>>(false); destructorsCalledOnGC<HeapLinkedHashSet<RefPtr<RefCountedWithDestructor>>>(false); destructorsCalledOnGC<HeapHashSet<RefPtr<RefCountedWithDestructor>>>(true); destructorsCalledOnGC<HeapListHashSet<RefPtr<RefCountedWithDestructor>>>(true); destructorsCalledOnGC<HeapLinkedHashSet<RefPtr<RefCountedWithDestructor>>>(true); } class MixinA : public GarbageCollectedMixin { public: MixinA() : m_obj(IntWrapper::create(100)) { } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_obj); } Member<IntWrapper> m_obj; }; class MixinB : public GarbageCollectedMixin { public: MixinB() : m_obj(IntWrapper::create(101)) { } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_obj); } Member<IntWrapper> m_obj; }; class MultipleMixins : public GarbageCollected<MultipleMixins>, public MixinA, public MixinB { USING_GARBAGE_COLLECTED_MIXIN(MultipleMixins); public: MultipleMixins() : m_obj(IntWrapper::create(102)) { } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_obj); MixinA::trace(visitor); MixinB::trace(visitor); } Member<IntWrapper> m_obj; }; static const bool s_isMixinTrue = IsGarbageCollectedMixin<MultipleMixins>::value; static const bool s_isMixinFalse = IsGarbageCollectedMixin<IntWrapper>::value; TEST(HeapTest, MultipleMixins) { EXPECT_TRUE(s_isMixinTrue); EXPECT_FALSE(s_isMixinFalse); clearOutOldGarbage(); IntWrapper::s_destructorCalls = 0; MultipleMixins* obj = new MultipleMixins(); { Persistent<MixinA> a = obj; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, IntWrapper::s_destructorCalls); } { Persistent<MixinB> b = obj; Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0, IntWrapper::s_destructorCalls); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(3, IntWrapper::s_destructorCalls); } class GCParkingThreadTester { public: static void test() { OwnPtr<WebThread> sleepingThread = adoptPtr(Platform::current()->createThread("SleepingThread")); sleepingThread->postTask(FROM_HERE, new Task(WTF::bind(sleeperMainFunc))); // Wait for the sleeper to run. while (!s_sleeperRunning) { Platform::current()->yieldCurrentThread(); } { // Expect the first attempt to park the sleeping thread to fail TestGCScope scope(ThreadState::NoHeapPointersOnStack); EXPECT_FALSE(scope.allThreadsParked()); } s_sleeperDone = true; // Wait for the sleeper to finish. while (s_sleeperRunning) { // We enter the safepoint here since the sleeper thread will detach // causing it to GC. ThreadState::current()->safePoint(ThreadState::NoHeapPointersOnStack); Platform::current()->yieldCurrentThread(); } { // Since the sleeper thread has detached this is the only thread. TestGCScope scope(ThreadState::NoHeapPointersOnStack); EXPECT_TRUE(scope.allThreadsParked()); } } private: static void sleeperMainFunc() { ThreadState::attach(); s_sleeperRunning = true; // Simulate a long running op that is not entering a safepoint. while (!s_sleeperDone) { Platform::current()->yieldCurrentThread(); } ThreadState::detach(); s_sleeperRunning = false; } static volatile bool s_sleeperRunning; static volatile bool s_sleeperDone; }; volatile bool GCParkingThreadTester::s_sleeperRunning = false; volatile bool GCParkingThreadTester::s_sleeperDone = false; TEST(HeapTest, GCParkingTimeout) { GCParkingThreadTester::test(); } TEST(HeapTest, NeedsAdjustAndMark) { // class Mixin : public GarbageCollectedMixin {}; EXPECT_TRUE(NeedsAdjustAndMark<Mixin>::value); EXPECT_TRUE(NeedsAdjustAndMark<const Mixin>::value); // class SimpleObject : public GarbageCollected<SimpleObject> {}; EXPECT_FALSE(NeedsAdjustAndMark<SimpleObject>::value); EXPECT_FALSE(NeedsAdjustAndMark<const SimpleObject>::value); // class UseMixin : public SimpleObject, public Mixin {}; EXPECT_FALSE(NeedsAdjustAndMark<UseMixin>::value); EXPECT_FALSE(NeedsAdjustAndMark<const UseMixin>::value); } template<typename Set> void setWithCustomWeaknessHandling() { typedef typename Set::iterator Iterator; Persistent<IntWrapper> livingInt(IntWrapper::create(42)); Persistent<Set> set1(new Set()); { Set set2; Set* set3 = new Set(); set2.add(PairWithWeakHandling(IntWrapper::create(0), IntWrapper::create(1))); set3->add(PairWithWeakHandling(IntWrapper::create(2), IntWrapper::create(3))); set1->add(PairWithWeakHandling(IntWrapper::create(4), IntWrapper::create(5))); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // The first set is pointed to from a persistent, so it's referenced, but // the weak processing may have taken place. if (set1->size()) { Iterator i1 = set1->begin(); EXPECT_EQ(4, i1->first->value()); EXPECT_EQ(5, i1->second->value()); } // The second set is on-stack, so its backing store must be referenced from // the stack. That makes the weak references strong. Iterator i2 = set2.begin(); EXPECT_EQ(0, i2->first->value()); EXPECT_EQ(1, i2->second->value()); // The third set is pointed to from the stack, so it's referenced, but the // weak processing may have taken place. if (set3->size()) { Iterator i3 = set3->begin(); EXPECT_EQ(2, i3->first->value()); EXPECT_EQ(3, i3->second->value()); } } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, set1->size()); set1->add(PairWithWeakHandling(IntWrapper::create(103), livingInt)); set1->add(PairWithWeakHandling(livingInt, IntWrapper::create(103))); // This one gets zapped at GC time because nothing holds the 103 alive. set1->add(PairWithWeakHandling(IntWrapper::create(103), IntWrapper::create(103))); // This one gets zapped too. set1->add(PairWithWeakHandling(livingInt, livingInt)); set1->add(PairWithWeakHandling(livingInt, livingInt)); // This one is identical to the previous and doesn't add anything. EXPECT_EQ(4u, set1->size()); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2u, set1->size()); Iterator i1 = set1->begin(); EXPECT_TRUE(i1->first->value() == 103 || i1->first == livingInt); EXPECT_EQ(livingInt, i1->second); ++i1; EXPECT_TRUE(i1->first->value() == 103 || i1->first == livingInt); EXPECT_EQ(livingInt, i1->second); } TEST(HeapTest, SetWithCustomWeaknessHandling) { setWithCustomWeaknessHandling<HeapHashSet<PairWithWeakHandling>>(); setWithCustomWeaknessHandling<HeapLinkedHashSet<PairWithWeakHandling>>(); } TEST(HeapTest, MapWithCustomWeaknessHandling) { typedef HeapHashMap<PairWithWeakHandling, RefPtr<OffHeapInt>> Map; typedef Map::iterator Iterator; clearOutOldGarbage(); OffHeapInt::s_destructorCalls = 0; Persistent<Map> map1(new Map()); Persistent<IntWrapper> livingInt(IntWrapper::create(42)); { Map map2; Map* map3 = new Map(); map2.add(PairWithWeakHandling(IntWrapper::create(0), IntWrapper::create(1)), OffHeapInt::create(1001)); map3->add(PairWithWeakHandling(IntWrapper::create(2), IntWrapper::create(3)), OffHeapInt::create(1002)); map1->add(PairWithWeakHandling(IntWrapper::create(4), IntWrapper::create(5)), OffHeapInt::create(1003)); EXPECT_EQ(0, OffHeapInt::s_destructorCalls); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // The first map2 is pointed to from a persistent, so it's referenced, but // the weak processing may have taken place. if (map1->size()) { Iterator i1 = map1->begin(); EXPECT_EQ(4, i1->key.first->value()); EXPECT_EQ(5, i1->key.second->value()); EXPECT_EQ(1003, i1->value->value()); } // The second map2 is on-stack, so its backing store must be referenced from // the stack. That makes the weak references strong. Iterator i2 = map2.begin(); EXPECT_EQ(0, i2->key.first->value()); EXPECT_EQ(1, i2->key.second->value()); EXPECT_EQ(1001, i2->value->value()); // The third map2 is pointed to from the stack, so it's referenced, but the // weak processing may have taken place. if (map3->size()) { Iterator i3 = map3->begin(); EXPECT_EQ(2, i3->key.first->value()); EXPECT_EQ(3, i3->key.second->value()); EXPECT_EQ(1002, i3->value->value()); } } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, map1->size()); EXPECT_EQ(3, OffHeapInt::s_destructorCalls); OffHeapInt::s_destructorCalls = 0; map1->add(PairWithWeakHandling(IntWrapper::create(103), livingInt), OffHeapInt::create(2000)); map1->add(PairWithWeakHandling(livingInt, IntWrapper::create(103)), OffHeapInt::create(2001)); // This one gets zapped at GC time because nothing holds the 103 alive. map1->add(PairWithWeakHandling(IntWrapper::create(103), IntWrapper::create(103)), OffHeapInt::create(2002)); // This one gets zapped too. RefPtr<OffHeapInt> dupeInt(OffHeapInt::create(2003)); map1->add(PairWithWeakHandling(livingInt, livingInt), dupeInt); map1->add(PairWithWeakHandling(livingInt, livingInt), dupeInt); // This one is identical to the previous and doesn't add anything. dupeInt.clear(); EXPECT_EQ(0, OffHeapInt::s_destructorCalls); EXPECT_EQ(4u, map1->size()); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2, OffHeapInt::s_destructorCalls); EXPECT_EQ(2u, map1->size()); Iterator i1 = map1->begin(); EXPECT_TRUE(i1->key.first->value() == 103 || i1->key.first == livingInt); EXPECT_EQ(livingInt, i1->key.second); ++i1; EXPECT_TRUE(i1->key.first->value() == 103 || i1->key.first == livingInt); EXPECT_EQ(livingInt, i1->key.second); } TEST(HeapTest, MapWithCustomWeaknessHandling2) { typedef HeapHashMap<RefPtr<OffHeapInt>, PairWithWeakHandling> Map; typedef Map::iterator Iterator; clearOutOldGarbage(); OffHeapInt::s_destructorCalls = 0; Persistent<Map> map1(new Map()); Persistent<IntWrapper> livingInt(IntWrapper::create(42)); { Map map2; Map* map3 = new Map(); map2.add(OffHeapInt::create(1001), PairWithWeakHandling(IntWrapper::create(0), IntWrapper::create(1))); map3->add(OffHeapInt::create(1002), PairWithWeakHandling(IntWrapper::create(2), IntWrapper::create(3))); map1->add(OffHeapInt::create(1003), PairWithWeakHandling(IntWrapper::create(4), IntWrapper::create(5))); EXPECT_EQ(0, OffHeapInt::s_destructorCalls); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // The first map2 is pointed to from a persistent, so it's referenced, but // the weak processing may have taken place. if (map1->size()) { Iterator i1 = map1->begin(); EXPECT_EQ(4, i1->value.first->value()); EXPECT_EQ(5, i1->value.second->value()); EXPECT_EQ(1003, i1->key->value()); } // The second map2 is on-stack, so its backing store must be referenced from // the stack. That makes the weak references strong. Iterator i2 = map2.begin(); EXPECT_EQ(0, i2->value.first->value()); EXPECT_EQ(1, i2->value.second->value()); EXPECT_EQ(1001, i2->key->value()); // The third map2 is pointed to from the stack, so it's referenced, but the // weak processing may have taken place. if (map3->size()) { Iterator i3 = map3->begin(); EXPECT_EQ(2, i3->value.first->value()); EXPECT_EQ(3, i3->value.second->value()); EXPECT_EQ(1002, i3->key->value()); } } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, map1->size()); EXPECT_EQ(3, OffHeapInt::s_destructorCalls); OffHeapInt::s_destructorCalls = 0; map1->add(OffHeapInt::create(2000), PairWithWeakHandling(IntWrapper::create(103), livingInt)); map1->add(OffHeapInt::create(2001), PairWithWeakHandling(livingInt, IntWrapper::create(103))); // This one gets zapped at GC time because nothing holds the 103 alive. map1->add(OffHeapInt::create(2002), PairWithWeakHandling(IntWrapper::create(103), IntWrapper::create(103))); // This one gets zapped too. RefPtr<OffHeapInt> dupeInt(OffHeapInt::create(2003)); map1->add(dupeInt, PairWithWeakHandling(livingInt, livingInt)); map1->add(dupeInt, PairWithWeakHandling(livingInt, livingInt)); // This one is identical to the previous and doesn't add anything. dupeInt.clear(); EXPECT_EQ(0, OffHeapInt::s_destructorCalls); EXPECT_EQ(4u, map1->size()); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2, OffHeapInt::s_destructorCalls); EXPECT_EQ(2u, map1->size()); Iterator i1 = map1->begin(); EXPECT_TRUE(i1->value.first->value() == 103 || i1->value.first == livingInt); EXPECT_EQ(livingInt, i1->value.second); ++i1; EXPECT_TRUE(i1->value.first->value() == 103 || i1->value.first == livingInt); EXPECT_EQ(livingInt, i1->value.second); } static void addElementsToWeakMap(HeapHashMap<int, WeakMember<IntWrapper>>* map) { // Key cannot be zero in hashmap. for (int i = 1; i < 11; i++) map->add(i, IntWrapper::create(i)); } // crbug.com/402426 // If it doesn't assert a concurrent modification to the map, then it's passing. TEST(HeapTest, RegressNullIsStrongified) { Persistent<HeapHashMap<int, WeakMember<IntWrapper>>> map = new HeapHashMap<int, WeakMember<IntWrapper>>(); addElementsToWeakMap(map); HeapHashMap<int, WeakMember<IntWrapper>>::AddResult result = map->add(800, nullptr); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); result.storedValue->value = IntWrapper::create(42); } TEST(HeapTest, Bind) { OwnPtr<Closure> closure = bind(static_cast<void (Bar::*)(Visitor*)>(&Bar::trace), Bar::create(), static_cast<Visitor*>(0)); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // The closure should have a persistent handle to the Bar. EXPECT_EQ(1u, Bar::s_live); OwnPtr<Closure> closure2 = bind(static_cast<void (Bar::*)(Visitor*)>(&Bar::trace), RawPtr<Bar>(Bar::create()), static_cast<Visitor*>(0)); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // The closure should have a persistent handle to the Bar. EXPECT_EQ(2u, Bar::s_live); // RawPtr<OffHeapInt> should not make Persistent. OwnPtr<Closure> closure3 = bind(&OffHeapInt::voidFunction, RawPtr<OffHeapInt>(OffHeapInt::create(1).get())); UseMixin::s_traceCount = 0; Mixin* mixin = UseMixin::create(); OwnPtr<Closure> mixinClosure = bind(static_cast<void (Mixin::*)(Visitor*)>(&Mixin::trace), mixin, static_cast<Visitor*>(0)); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // The closure should have a persistent handle to the mixin. EXPECT_EQ(1, UseMixin::s_traceCount); } typedef HeapHashSet<WeakMember<IntWrapper>> WeakSet; // These special traits will remove a set from a map when the set is empty. struct EmptyClearingHashSetTraits : HashTraits<WeakSet> { static const WTF::WeakHandlingFlag weakHandlingFlag = WTF::WeakHandlingInCollections; template<typename VisitorDispatcher> static bool traceInCollection(VisitorDispatcher visitor, WeakSet& set, WTF::ShouldWeakPointersBeMarkedStrongly strongify) { bool liveEntriesFound = false; WeakSet::iterator end = set.end(); for (WeakSet::iterator it = set.begin(); it != end; ++it) { if (visitor->isAlive(*it)) { liveEntriesFound = true; break; } } // If there are live entries in the set then the set cannot be removed // from the map it is contained in, and we need to mark it (and its // backing) live. We just trace normally, which will invoke the normal // weak handling for any entries that are not live. if (liveEntriesFound) set.trace(visitor); return !liveEntriesFound; } }; // This is an example to show how you can remove entries from a T->WeakSet map // when the weak sets become empty. For this example we are using a type that // is given to use (HeapHashSet) rather than a type of our own. This means: // 1) We can't just override the HashTrait for the type since this would affect // all collections that use this kind of weak set. Instead we have our own // traits and use a map with custom traits for the value type. These traits // are the 5th template parameter, so we have to supply default values for // the 3rd and 4th template parameters // 2) We can't just inherit from WeakHandlingHashTraits, since that trait // assumes we can add methods to the type, but we can't add methods to // HeapHashSet. TEST(HeapTest, RemoveEmptySets) { clearOutOldGarbage(); OffHeapInt::s_destructorCalls = 0; Persistent<IntWrapper> livingInt(IntWrapper::create(42)); typedef RefPtr<OffHeapInt> Key; typedef HeapHashMap<Key, WeakSet, WTF::DefaultHash<Key>::Hash, HashTraits<Key>, EmptyClearingHashSetTraits> Map; Persistent<Map> map(new Map()); map->add(OffHeapInt::create(1), WeakSet()); { WeakSet& set = map->begin()->value; set.add(IntWrapper::create(103)); // Weak set can't hold this long. set.add(livingInt); // This prevents the set from being emptied. EXPECT_EQ(2u, set.size()); } // The set we add here is empty, so the entry will be removed from the map // at the next GC. map->add(OffHeapInt::create(2), WeakSet()); EXPECT_EQ(2u, map->size()); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1u, map->size()); // The one with key 2 was removed. EXPECT_EQ(1, OffHeapInt::s_destructorCalls); { WeakSet& set = map->begin()->value; EXPECT_EQ(1u, set.size()); } livingInt.clear(); // The weak set can no longer keep the '42' alive now. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, map->size()); } TEST(HeapTest, EphemeronsInEphemerons) { typedef HeapHashMap<WeakMember<IntWrapper>, Member<IntWrapper>> InnerMap; typedef HeapHashMap<WeakMember<IntWrapper>, InnerMap> OuterMap; for (int keepOuterAlive = 0; keepOuterAlive <= 1; keepOuterAlive++) { for (int keepInnerAlive = 0; keepInnerAlive <=1; keepInnerAlive++) { Persistent<OuterMap> outer = new OuterMap(); Persistent<IntWrapper> one = IntWrapper::create(1); Persistent<IntWrapper> two = IntWrapper::create(2); outer->add(one, InnerMap()); outer->begin()->value.add(two, IntWrapper::create(3)); EXPECT_EQ(1u, outer->get(one).size()); if (!keepOuterAlive) one.clear(); if (!keepInnerAlive) two.clear(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); if (keepOuterAlive) { const InnerMap& inner = outer->get(one); if (keepInnerAlive) { EXPECT_EQ(1u, inner.size()); IntWrapper* three = inner.get(two); EXPECT_EQ(3, three->value()); } else { EXPECT_EQ(0u, inner.size()); } } else { EXPECT_EQ(0u, outer->size()); } outer->clear(); Persistent<IntWrapper> deep = IntWrapper::create(42); Persistent<IntWrapper> home = IntWrapper::create(103); Persistent<IntWrapper> composite = IntWrapper::create(91); Persistent<HeapVector<Member<IntWrapper>>> keepAlive = new HeapVector<Member<IntWrapper>>(); for (int i = 0; i < 10000; i++) { IntWrapper* value = IntWrapper::create(i); keepAlive->append(value); OuterMap::AddResult newEntry = outer->add(value, InnerMap()); newEntry.storedValue->value.add(deep, home); newEntry.storedValue->value.add(composite, home); } composite.clear(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(10000u, outer->size()); for (int i = 0; i < 10000; i++) { IntWrapper* value = keepAlive->at(i); EXPECT_EQ(1u, outer->get(value).size()); // Other one was deleted by weak handling. if (i & 1) keepAlive->at(i) = nullptr; } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(5000u, outer->size()); } } } class EphemeronWrapper : public GarbageCollected<EphemeronWrapper> { public: DEFINE_INLINE_TRACE() { visitor->trace(m_map); } typedef HeapHashMap<WeakMember<IntWrapper>, Member<EphemeronWrapper>> Map; Map& map() { return m_map; } private: Map m_map; }; TEST(HeapTest, EphemeronsPointToEphemerons) { Persistent<IntWrapper> key = IntWrapper::create(42); Persistent<IntWrapper> key2 = IntWrapper::create(103); Persistent<EphemeronWrapper> chain; for (int i = 0; i < 100; i++) { EphemeronWrapper* oldHead = chain; chain = new EphemeronWrapper(); if (i == 50) chain->map().add(key2, oldHead); else chain->map().add(key, oldHead); chain->map().add(IntWrapper::create(103), new EphemeronWrapper()); } Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EphemeronWrapper* wrapper = chain; for (int i = 0; i< 100; i++) { EXPECT_EQ(1u, wrapper->map().size()); if (i == 49) wrapper = wrapper->map().get(key2); else wrapper = wrapper->map().get(key); } EXPECT_EQ(nullptr, wrapper); key2.clear(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); wrapper = chain; for (int i = 0; i < 50; i++) { EXPECT_EQ(i == 49 ? 0u : 1u, wrapper->map().size()); wrapper = wrapper->map().get(key); } EXPECT_EQ(nullptr, wrapper); key.clear(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, chain->map().size()); } TEST(HeapTest, Ephemeron) { typedef HeapHashMap<WeakMember<IntWrapper>, PairWithWeakHandling> WeakPairMap; typedef HeapHashMap<PairWithWeakHandling, WeakMember<IntWrapper>> PairWeakMap; typedef HeapHashSet<WeakMember<IntWrapper>> Set; Persistent<WeakPairMap> weakPairMap = new WeakPairMap(); Persistent<WeakPairMap> weakPairMap2 = new WeakPairMap(); Persistent<WeakPairMap> weakPairMap3 = new WeakPairMap(); Persistent<WeakPairMap> weakPairMap4 = new WeakPairMap(); Persistent<PairWeakMap> pairWeakMap = new PairWeakMap(); Persistent<PairWeakMap> pairWeakMap2 = new PairWeakMap(); Persistent<Set> set = new Set(); Persistent<IntWrapper> wp1 = IntWrapper::create(1); Persistent<IntWrapper> wp2 = IntWrapper::create(2); Persistent<IntWrapper> pw1 = IntWrapper::create(3); Persistent<IntWrapper> pw2 = IntWrapper::create(4); weakPairMap->add(wp1, PairWithWeakHandling(wp1, wp1)); weakPairMap->add(wp2, PairWithWeakHandling(wp1, wp1)); weakPairMap2->add(wp1, PairWithWeakHandling(wp1, wp2)); weakPairMap2->add(wp2, PairWithWeakHandling(wp1, wp2)); // The map from wp1 to (wp2, wp1) would mark wp2 live, so we skip that. weakPairMap3->add(wp2, PairWithWeakHandling(wp2, wp1)); weakPairMap4->add(wp1, PairWithWeakHandling(wp2, wp2)); weakPairMap4->add(wp2, PairWithWeakHandling(wp2, wp2)); pairWeakMap->add(PairWithWeakHandling(pw1, pw1), pw1); pairWeakMap->add(PairWithWeakHandling(pw1, pw2), pw1); // The map from (pw2, pw1) to pw1 would make pw2 live, so we skip that. pairWeakMap->add(PairWithWeakHandling(pw2, pw2), pw1); pairWeakMap2->add(PairWithWeakHandling(pw1, pw1), pw2); pairWeakMap2->add(PairWithWeakHandling(pw1, pw2), pw2); pairWeakMap2->add(PairWithWeakHandling(pw2, pw1), pw2); pairWeakMap2->add(PairWithWeakHandling(pw2, pw2), pw2); set->add(wp1); set->add(wp2); set->add(pw1); set->add(pw2); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2u, weakPairMap->size()); EXPECT_EQ(2u, weakPairMap2->size()); EXPECT_EQ(1u, weakPairMap3->size()); EXPECT_EQ(2u, weakPairMap4->size()); EXPECT_EQ(3u, pairWeakMap->size()); EXPECT_EQ(4u, pairWeakMap2->size()); EXPECT_EQ(4u, set->size()); wp2.clear(); // Kills all entries in the weakPairMaps except the first. pw2.clear(); // Kills all entries in the pairWeakMaps except the first. for (int i = 0; i < 2; i++) { Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1u, weakPairMap->size()); EXPECT_EQ(0u, weakPairMap2->size()); EXPECT_EQ(0u, weakPairMap3->size()); EXPECT_EQ(0u, weakPairMap4->size()); EXPECT_EQ(1u, pairWeakMap->size()); EXPECT_EQ(0u, pairWeakMap2->size()); EXPECT_EQ(2u, set->size()); // wp1 and pw1. } wp1.clear(); pw1.clear(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, weakPairMap->size()); EXPECT_EQ(0u, pairWeakMap->size()); EXPECT_EQ(0u, set->size()); } class Link1 : public GarbageCollected<Link1> { public: Link1(IntWrapper* link) : m_link(link) { } DEFINE_INLINE_TRACE() { visitor->trace(m_link); } IntWrapper* link() { return m_link; } private: Member<IntWrapper> m_link; }; TEST(HeapTest, IndirectStrongToWeak) { typedef HeapHashMap<WeakMember<IntWrapper>, Member<Link1>> Map; Persistent<Map> map = new Map(); Persistent<IntWrapper> deadObject = IntWrapper::create(100); // Named for "Drowning by Numbers" (1988). Persistent<IntWrapper> lifeObject = IntWrapper::create(42); map->add(deadObject, new Link1(deadObject)); map->add(lifeObject, new Link1(lifeObject)); EXPECT_EQ(2u, map->size()); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(2u, map->size()); EXPECT_EQ(deadObject, map->get(deadObject)->link()); EXPECT_EQ(lifeObject, map->get(lifeObject)->link()); deadObject.clear(); // Now it can live up to its name. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(1u, map->size()); EXPECT_EQ(lifeObject, map->get(lifeObject)->link()); lifeObject.clear(); // Despite its name. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, map->size()); } static Mutex& mainThreadMutex() { AtomicallyInitializedStaticReference(Mutex, mainMutex, new Mutex); return mainMutex; } static ThreadCondition& mainThreadCondition() { AtomicallyInitializedStaticReference(ThreadCondition, mainCondition, new ThreadCondition); return mainCondition; } static void parkMainThread() { mainThreadCondition().wait(mainThreadMutex()); } static void wakeMainThread() { MutexLocker locker(mainThreadMutex()); mainThreadCondition().signal(); } static Mutex& workerThreadMutex() { AtomicallyInitializedStaticReference(Mutex, workerMutex, new Mutex); return workerMutex; } static ThreadCondition& workerThreadCondition() { AtomicallyInitializedStaticReference(ThreadCondition, workerCondition, new ThreadCondition); return workerCondition; } static void parkWorkerThread() { workerThreadCondition().wait(workerThreadMutex()); } static void wakeWorkerThread() { MutexLocker locker(workerThreadMutex()); workerThreadCondition().signal(); } class DeadBitTester { public: static void test() { IntWrapper::s_destructorCalls = 0; MutexLocker locker(mainThreadMutex()); OwnPtr<WebThread> workerThread = adoptPtr(Platform::current()->createThread("Test Worker Thread")); workerThread->postTask(FROM_HERE, new Task(WTF::bind(workerThreadMain))); // Wait for the worker thread to have done its initialization, // IE. the worker allocates an object and then throw aways any // pointers to it. parkMainThread(); // Now do a GC. This will not find the worker threads object since it // is not referred from any of the threads. Even a conservative // GC will not find it. // Also at this point the worker is waiting for the main thread // to be parked and will not do any sweep of its heap. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // Since the worker thread is not sweeping the worker object should // not have been finalized. EXPECT_EQ(0, IntWrapper::s_destructorCalls); // Put the worker thread's object address on the stack and do a // conservative GC. This should find the worker object, but since // it was dead in the previous GC it should not be traced in this // GC. uintptr_t stackPtrValue = s_workerObjectPointer; s_workerObjectPointer = 0; ASSERT_UNUSED(stackPtrValue, stackPtrValue); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // Since the worker thread is not sweeping the worker object should // not have been finalized. EXPECT_EQ(0, IntWrapper::s_destructorCalls); // Wake up the worker thread so it can continue with its sweeping. // This should finalized the worker object which we test below. // The worker thread will go back to sleep once sweeping to ensure // we don't have thread local GCs until after validating the destructor // was called. wakeWorkerThread(); // Wait for the worker thread to sweep its heaps before checking. parkMainThread(); EXPECT_EQ(1, IntWrapper::s_destructorCalls); // Wake up the worker to allow it thread to continue with thread // shutdown. wakeWorkerThread(); } private: static void workerThreadMain() { MutexLocker locker(workerThreadMutex()); ThreadState::attach(); { // Create a worker object that is not kept alive except the // main thread will keep it as an integer value on its stack. IntWrapper* workerObject = IntWrapper::create(42); s_workerObjectPointer = reinterpret_cast<uintptr_t>(workerObject); } // Signal the main thread that the worker is done with its allocation. wakeMainThread(); { // Wait for the main thread to do two GCs without sweeping this thread // heap. The worker waits within a safepoint, but there is no sweeping // until leaving the safepoint scope. SafePointScope scope(ThreadState::NoHeapPointersOnStack); parkWorkerThread(); } // Wake up the main thread when done sweeping. wakeMainThread(); // Wait with detach until the main thread says so. This is not strictly // necessary, but it means the worker thread will not do its thread local // GCs just yet, making it easier to reason about that no new GC has occurred // and the above sweep was the one finalizing the worker object. parkWorkerThread(); ThreadState::detach(); } static volatile uintptr_t s_workerObjectPointer; }; volatile uintptr_t DeadBitTester::s_workerObjectPointer = 0; TEST(HeapTest, ObjectDeadBit) { DeadBitTester::test(); } class ThreadedStrongificationTester { public: static void test() { IntWrapper::s_destructorCalls = 0; MutexLocker locker(mainThreadMutex()); OwnPtr<WebThread> workerThread = adoptPtr(Platform::current()->createThread("Test Worker Thread")); workerThread->postTask(FROM_HERE, new Task(WTF::bind(workerThreadMain))); // Wait for the worker thread initialization. The worker // allocates a weak collection where both collection and // contents are kept alive via persistent pointers. parkMainThread(); // Perform two garbage collections where the worker thread does // not wake up in between. This will cause us to remove marks // and mark unmarked objects dead. The collection on the worker // heap is found through the persistent and the backing should // be marked. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // Wake up the worker thread so it can continue. It will sweep // and perform another GC where the backing store of its // collection should be strongified. wakeWorkerThread(); // Wait for the worker thread to sweep its heaps before checking. { SafePointScope scope(ThreadState::NoHeapPointersOnStack); parkMainThread(); } } private: static HeapHashSet<WeakMember<IntWrapper>>* allocateCollection() { // Create a weak collection that is kept alive by a persistent // and keep the contents alive with a persistents as // well. Persistent<IntWrapper> wrapper1 = IntWrapper::create(32); Persistent<IntWrapper> wrapper2 = IntWrapper::create(32); Persistent<IntWrapper> wrapper3 = IntWrapper::create(32); Persistent<IntWrapper> wrapper4 = IntWrapper::create(32); Persistent<IntWrapper> wrapper5 = IntWrapper::create(32); Persistent<IntWrapper> wrapper6 = IntWrapper::create(32); Persistent<HeapHashSet<WeakMember<IntWrapper>>> weakCollection = new HeapHashSet<WeakMember<IntWrapper>>; weakCollection->add(wrapper1); weakCollection->add(wrapper2); weakCollection->add(wrapper3); weakCollection->add(wrapper4); weakCollection->add(wrapper5); weakCollection->add(wrapper6); // Signal the main thread that the worker is done with its allocation. wakeMainThread(); { // Wait for the main thread to do two GCs without sweeping // this thread heap. The worker waits within a safepoint, // but there is no sweeping until leaving the safepoint // scope. If the weak collection backing is marked dead // because of this we will not get strongification in the // GC we force when we continue. SafePointScope scope(ThreadState::NoHeapPointersOnStack); parkWorkerThread(); } return weakCollection; } static void workerThreadMain() { MutexLocker locker(workerThreadMutex()); ThreadState::attach(); { Persistent<HeapHashSet<WeakMember<IntWrapper>>> collection = allocateCollection(); { // Prevent weak processing with an iterator and GC. HeapHashSet<WeakMember<IntWrapper>>::iterator it = collection->begin(); Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // The backing should be strongified because of the iterator. EXPECT_EQ(6u, collection->size()); EXPECT_EQ(32, (*it)->value()); } // Disregarding the iterator but keeping the collection alive // with a persistent should lead to weak processing. Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(0u, collection->size()); } wakeMainThread(); ThreadState::detach(); } static volatile uintptr_t s_workerObjectPointer; }; TEST(HeapTest, ThreadedStrongification) { ThreadedStrongificationTester::test(); } static bool allocateAndReturnBool() { Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); return true; } class MixinWithGarbageCollectionInConstructor : public GarbageCollectedMixin { public: MixinWithGarbageCollectionInConstructor() : m_dummy(allocateAndReturnBool()) { } private: bool m_dummy; }; class ClassWithGarbageCollectingMixinConstructor : public GarbageCollected<ClassWithGarbageCollectingMixinConstructor> , public MixinWithGarbageCollectionInConstructor { USING_GARBAGE_COLLECTED_MIXIN(ClassWithGarbageCollectingMixinConstructor); public: static int s_traceCalled; ClassWithGarbageCollectingMixinConstructor() : m_traceCounter(TraceCounter::create()) , m_wrapper(IntWrapper::create(32)) { } DEFINE_INLINE_VIRTUAL_TRACE() { s_traceCalled++; visitor->trace(m_traceCounter); visitor->trace(m_wrapper); } void verify() { EXPECT_EQ(32, m_wrapper->value()); EXPECT_EQ(0, m_traceCounter->traceCount()); EXPECT_EQ(0, s_traceCalled); } private: Member<TraceCounter> m_traceCounter; Member<IntWrapper> m_wrapper; }; int ClassWithGarbageCollectingMixinConstructor::s_traceCalled = 0; // Regression test for out of bounds call through vtable. // Passes if it doesn't crash. TEST(HeapTest, GarbageCollectionDuringMixinConstruction) { ClassWithGarbageCollectingMixinConstructor* a = new ClassWithGarbageCollectingMixinConstructor(); a->verify(); } static RecursiveMutex& recursiveMutex() { AtomicallyInitializedStaticReference(RecursiveMutex, recursiveMutex, new RecursiveMutex); return recursiveMutex; } class DestructorLockingObject : public GarbageCollectedFinalized<DestructorLockingObject> { public: static DestructorLockingObject* create() { return new DestructorLockingObject(); } virtual ~DestructorLockingObject() { SafePointAwareMutexLocker lock(recursiveMutex()); ++s_destructorCalls; } static int s_destructorCalls; DEFINE_INLINE_TRACE() { } private: DestructorLockingObject() { } }; int DestructorLockingObject::s_destructorCalls = 0; class RecursiveLockingTester { public: static void test() { DestructorLockingObject::s_destructorCalls = 0; MutexLocker locker(mainThreadMutex()); OwnPtr<WebThread> workerThread = adoptPtr(Platform::current()->createThread("Test Worker Thread")); workerThread->postTask(FROM_HERE, new Task(WTF::bind(workerThreadMain))); // Park the main thread until the worker thread has initialized. parkMainThread(); { SafePointAwareMutexLocker recursiveLocker(recursiveMutex()); // Let the worker try to acquire the above mutex. It won't get it // until the main thread has done its GC. wakeWorkerThread(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // The worker thread should not have swept yet since it is waiting // to get the global mutex. EXPECT_EQ(0, DestructorLockingObject::s_destructorCalls); } // At this point the main thread releases the global lock and the worker // can acquire it and do its sweep of its heaps. Just wait for the worker // to complete its sweep and check the result. parkMainThread(); EXPECT_EQ(1, DestructorLockingObject::s_destructorCalls); } private: static void workerThreadMain() { MutexLocker locker(workerThreadMutex()); ThreadState::attach(); DestructorLockingObject* dlo = DestructorLockingObject::create(); ASSERT_UNUSED(dlo, dlo); // Wake up the main thread which is waiting for the worker to do its // allocation. wakeMainThread(); // Wait for the main thread to get the global lock to ensure it has // it before the worker tries to acquire it. We want the worker to // block in the SafePointAwareMutexLocker until the main thread // has done a GC. The GC will not mark the "dlo" object since the worker // is entering the safepoint with NoHeapPointersOnStack. When the worker // subsequently gets the global lock and leaves the safepoint it will // sweep its heap and finalize "dlo". The destructor of "dlo" will try // to acquire the same global lock that the thread just got and deadlock // unless the global lock is recursive. parkWorkerThread(); SafePointAwareMutexLocker recursiveLocker(recursiveMutex(), ThreadState::NoHeapPointersOnStack); // We won't get here unless the lock is recursive since the sweep done // in the constructor of SafePointAwareMutexLocker after // getting the lock will not complete given the "dlo" destructor is // waiting to get the same lock. // Tell the main thread the worker has done its sweep. wakeMainThread(); ThreadState::detach(); } static volatile IntWrapper* s_workerObjectPointer; }; TEST(HeapTest, RecursiveMutex) { RecursiveLockingTester::test(); } template<typename T> class TraceIfNeededTester : public GarbageCollectedFinalized<TraceIfNeededTester<T>> { public: static TraceIfNeededTester<T>* create() { return new TraceIfNeededTester<T>(); } static TraceIfNeededTester<T>* create(const T& obj) { return new TraceIfNeededTester<T>(obj); } DEFINE_INLINE_TRACE() { TraceIfNeeded<T>::trace(visitor, &m_obj); } T& obj() { return m_obj; } ~TraceIfNeededTester() { } private: TraceIfNeededTester() { } explicit TraceIfNeededTester(const T& obj) : m_obj(obj) { } T m_obj; }; class PartObject { DISALLOW_ALLOCATION(); public: PartObject() : m_obj(SimpleObject::create()) { } DEFINE_INLINE_TRACE() { visitor->trace(m_obj); } private: Member<SimpleObject> m_obj; }; TEST(HeapTest, TraceIfNeeded) { CountingVisitor visitor; { TraceIfNeededTester<RefPtr<OffHeapInt>>* m_offHeap = TraceIfNeededTester<RefPtr<OffHeapInt>>::create(OffHeapInt::create(42)); visitor.reset(); m_offHeap->trace(&visitor); EXPECT_EQ(0u, visitor.count()); } { TraceIfNeededTester<PartObject>* m_part = TraceIfNeededTester<PartObject>::create(); visitor.reset(); m_part->trace(&visitor); EXPECT_EQ(1u, visitor.count()); } { TraceIfNeededTester<Member<SimpleObject>>* m_obj = TraceIfNeededTester<Member<SimpleObject>>::create(Member<SimpleObject>(SimpleObject::create())); visitor.reset(); m_obj->trace(&visitor); EXPECT_EQ(1u, visitor.count()); } { TraceIfNeededTester<HeapVector<Member<SimpleObject>>>* m_vec = TraceIfNeededTester<HeapVector<Member<SimpleObject>>>::create(); m_vec->obj().append(SimpleObject::create()); visitor.reset(); m_vec->trace(&visitor); EXPECT_EQ(2u, visitor.count()); } } class AllocatesOnAssignment { public: AllocatesOnAssignment(std::nullptr_t) : m_value(nullptr) { } AllocatesOnAssignment(int x) : m_value(new IntWrapper(x)) { } AllocatesOnAssignment(IntWrapper* x) : m_value(x) { } AllocatesOnAssignment& operator=(const AllocatesOnAssignment x) { m_value = x.m_value; return *this; } enum DeletedMarker { DeletedValue }; AllocatesOnAssignment(const AllocatesOnAssignment& other) { Heap::collectGarbage(ThreadState::HeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); m_value = new IntWrapper(other.m_value->value()); } AllocatesOnAssignment(DeletedMarker) : m_value(reinterpret_cast<IntWrapper*>(-1)) { } inline bool isDeleted() const { return m_value == reinterpret_cast<IntWrapper*>(-1); } DEFINE_INLINE_VIRTUAL_TRACE() { visitor->trace(m_value); } int value() { return m_value->value(); } private: Member<IntWrapper> m_value; friend bool operator==(const AllocatesOnAssignment&, const AllocatesOnAssignment&); friend void swap(AllocatesOnAssignment&, AllocatesOnAssignment&); }; bool operator==(const AllocatesOnAssignment& a, const AllocatesOnAssignment& b) { if (a.m_value) return b.m_value && a.m_value->value() == b.m_value->value(); return !b.m_value; } void swap(AllocatesOnAssignment& a, AllocatesOnAssignment& b) { std::swap(a.m_value, b.m_value); } struct DegenerateHash { static unsigned hash(const AllocatesOnAssignment&) { return 0; } static bool equal(const AllocatesOnAssignment& a, const AllocatesOnAssignment& b) { return !a.isDeleted() && a == b; } static const bool safeToCompareToEmptyOrDeleted = true; }; struct AllocatesOnAssignmentHashTraits : WTF::GenericHashTraits<AllocatesOnAssignment> { typedef AllocatesOnAssignment T; typedef std::nullptr_t EmptyValueType; static EmptyValueType emptyValue() { return nullptr; } static const bool emptyValueIsZero = false; // Can't be zero if it has a vtable. static void constructDeletedValue(T& slot, bool) { slot = T(AllocatesOnAssignment::DeletedValue); } static bool isDeletedValue(const T& value) { return value.isDeleted(); } }; } // namespace blink namespace WTF { template<> struct DefaultHash<blink::AllocatesOnAssignment> { typedef blink::DegenerateHash Hash; }; template <> struct HashTraits<blink::AllocatesOnAssignment> : blink::AllocatesOnAssignmentHashTraits { }; } // namespace WTF namespace blink { TEST(HeapTest, GCInHashMapOperations) { typedef HeapHashMap<AllocatesOnAssignment, AllocatesOnAssignment> Map; Map* map = new Map(); IntWrapper* key = new IntWrapper(42); map->add(key, AllocatesOnAssignment(103)); map->remove(key); for (int i = 0; i < 10; i++) map->add(AllocatesOnAssignment(i), AllocatesOnAssignment(i)); for (Map::iterator it = map->begin(); it != map->end(); ++it) EXPECT_EQ(it->key.value(), it->value.value()); } class PartObjectWithVirtualMethod { public: DEFINE_INLINE_VIRTUAL_TRACE() { } }; class ObjectWithVirtualPartObject : public GarbageCollected<ObjectWithVirtualPartObject> { public: ObjectWithVirtualPartObject() : m_dummy(allocateAndReturnBool()) { } DEFINE_INLINE_TRACE() { visitor->trace(m_part); } private: bool m_dummy; PartObjectWithVirtualMethod m_part; }; TEST(HeapTest, PartObjectWithVirtualMethod) { ObjectWithVirtualPartObject* object = new ObjectWithVirtualPartObject(); EXPECT_TRUE(object); } class AllocInSuperConstructorArgumentSuper : public GarbageCollectedFinalized<AllocInSuperConstructorArgumentSuper> { public: AllocInSuperConstructorArgumentSuper(bool value) : m_value(value) { } DEFINE_INLINE_VIRTUAL_TRACE() { } bool value() { return m_value; } private: bool m_value; }; class AllocInSuperConstructorArgument : public AllocInSuperConstructorArgumentSuper { public: AllocInSuperConstructorArgument() : AllocInSuperConstructorArgumentSuper(allocateAndReturnBool()) { } }; // Regression test for crbug.com/404511. Tests conservative marking of // an object with an uninitialized vtable. TEST(HeapTest, AllocationInSuperConstructorArgument) { AllocInSuperConstructorArgument* object = new AllocInSuperConstructorArgument(); EXPECT_TRUE(object); Heap::collectAllGarbage(); } class NonNodeAllocatingNodeInDestructor : public GarbageCollectedFinalized<NonNodeAllocatingNodeInDestructor> { public: ~NonNodeAllocatingNodeInDestructor() { s_node = new Persistent<IntNode>(IntNode::create(10)); } DEFINE_INLINE_TRACE() { } static Persistent<IntNode>* s_node; }; Persistent<IntNode>* NonNodeAllocatingNodeInDestructor::s_node = 0; TEST(HeapTest, NonNodeAllocatingNodeInDestructor) { new NonNodeAllocatingNodeInDestructor(); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); EXPECT_EQ(10, (*NonNodeAllocatingNodeInDestructor::s_node)->value()); delete NonNodeAllocatingNodeInDestructor::s_node; NonNodeAllocatingNodeInDestructor::s_node = 0; } class TraceTypeEagerly1 : public GarbageCollected<TraceTypeEagerly1> { }; class TraceTypeEagerly2 : public TraceTypeEagerly1 { }; class TraceTypeNonEagerly1 { }; WILL_NOT_BE_EAGERLY_TRACED(TraceTypeNonEagerly1); class TraceTypeNonEagerly2 : public TraceTypeNonEagerly1 { }; class TraceTypeNonEagerly3 { }; WILL_NOT_BE_EAGERLY_TRACED_CLASS(TraceTypeNonEagerly3); class TraceTypeNonEagerly4 : public TraceTypeNonEagerly3 { }; TEST(HeapTest, TraceTypesEagerly) { static_assert(TraceEagerlyTrait<TraceTypeEagerly1>::value, "should be true"); static_assert(TraceEagerlyTrait<Member<TraceTypeEagerly1>>::value, "should be true"); static_assert(TraceEagerlyTrait<WeakMember<TraceTypeEagerly1>>::value, "should be true"); static_assert(TraceEagerlyTrait<RawPtr<TraceTypeEagerly1>>::value == MARKER_EAGER_TRACING, "should be true"); static_assert(TraceEagerlyTrait<HeapVector<Member<TraceTypeEagerly1>>>::value, "should be true"); static_assert(TraceEagerlyTrait<HeapVector<WeakMember<TraceTypeEagerly1>>>::value, "should be true"); static_assert(TraceEagerlyTrait<HeapHashSet<Member<TraceTypeEagerly1>>>::value, "should be true"); static_assert(TraceEagerlyTrait<HeapHashSet<Member<TraceTypeEagerly1>>>::value, "should be true"); using HashMapIntToObj = HeapHashMap<int, Member<TraceTypeEagerly1>>; static_assert(TraceEagerlyTrait<HashMapIntToObj>::value, "should be true"); using HashMapObjToInt = HeapHashMap<Member<TraceTypeEagerly1>, int>; static_assert(TraceEagerlyTrait<HashMapObjToInt>::value, "should be true"); static_assert(TraceEagerlyTrait<TraceTypeEagerly2>::value, "should be true"); static_assert(TraceEagerlyTrait<Member<TraceTypeEagerly2>>::value, "should be true"); static_assert(!TraceEagerlyTrait<TraceTypeNonEagerly1>::value, "should be true"); static_assert(!TraceEagerlyTrait<TraceTypeNonEagerly2>::value, "should be true"); static_assert(!TraceEagerlyTrait<TraceTypeNonEagerly3>::value, "should be true"); static_assert(TraceEagerlyTrait<TraceTypeNonEagerly4>::value == MARKER_EAGER_TRACING, "should be true"); } class DeepEagerly final : public GarbageCollected<DeepEagerly> { public: DeepEagerly(DeepEagerly* next) : m_next(next) { } DEFINE_INLINE_TRACE() { int calls = ++sTraceCalls; if (sTraceLazy <= 2) visitor->trace(m_next); if (sTraceCalls == calls) sTraceLazy++; } Member<DeepEagerly> m_next; static int sTraceCalls; static int sTraceLazy; }; int DeepEagerly::sTraceCalls = 0; int DeepEagerly::sTraceLazy = 0; TEST(HeapTest, TraceDeepEagerly) { #if !ENABLE(ASSERT) DeepEagerly* obj = nullptr; for (int i = 0; i < 10000000; i++) obj = new DeepEagerly(obj); Persistent<DeepEagerly> persistent(obj); Heap::collectGarbage(ThreadState::NoHeapPointersOnStack, ThreadState::GCWithSweep, Heap::ForcedGCForTesting); // Verify that the DeepEagerly chain isn't completely unravelled // by performing eager trace() calls, but the explicit mark // stack is switched once some nesting limit is exceeded. EXPECT_GT(DeepEagerly::sTraceLazy, 2); #endif } TEST(HeapTest, DequeExpand) { // Test expansion of a HeapDeque<>'s buffer. typedef HeapDeque<Member<IntWrapper>> IntDeque; Persistent<IntDeque> deque = new IntDeque(); // Append a sequence, bringing about repeated expansions of the // deque's buffer. int i = 0; for (; i < 60; ++i) deque->append(IntWrapper::create(i)); EXPECT_EQ(60u, deque->size()); i = 0; for (const auto& intWrapper : *deque) { EXPECT_EQ(i, intWrapper->value()); i++; } // Remove most of the queued objects and have the buffer's start index // 'point' somewhere into the buffer, just behind the end index. for (i = 0; i < 50; ++i) deque->takeFirst(); EXPECT_EQ(10u, deque->size()); i = 0; for (const auto& intWrapper : *deque) { EXPECT_EQ(50 + i, intWrapper->value()); i++; } // Append even more, eventually causing an expansion of the underlying // buffer once the end index wraps around and reaches the start index. for (i = 0; i < 70; ++i) deque->append(IntWrapper::create(60 + i)); // Verify that the final buffer expansion copied the start and end segments // of the old buffer to both ends of the expanded buffer, along with // re-adjusting both start&end indices in terms of that expanded buffer. EXPECT_EQ(80u, deque->size()); i = 0; for (const auto& intWrapper : *deque) { EXPECT_EQ(i + 50, intWrapper->value()); i++; } } namespace { enum GrowthDirection { GrowsTowardsHigher, GrowsTowardsLower, }; NEVER_INLINE NO_SANITIZE_ADDRESS GrowthDirection stackGrowthDirection() { // Disable ASan, otherwise its stack checking (use-after-return) will // confuse the direction check. static char* previous = nullptr; char dummy; if (!previous) { previous = &dummy; GrowthDirection result = stackGrowthDirection(); previous = nullptr; return result; } ASSERT(&dummy != previous); return &dummy < previous ? GrowsTowardsLower : GrowsTowardsHigher; } } // namespace TEST(HeapTest, StackGrowthDirection) { // The implementation of marking probes stack usage as it runs, // and has a builtin assumption that the stack grows towards // lower addresses. EXPECT_EQ(GrowsTowardsLower, stackGrowthDirection()); } class TestMixinAllocationA : public GarbageCollected<TestMixinAllocationA>, public GarbageCollectedMixin { USING_GARBAGE_COLLECTED_MIXIN(TestMixinAllocationA); public: TestMixinAllocationA() { // Completely wrong in general, but test only // runs this constructor while constructing another mixin. ASSERT(ThreadState::current()->isGCForbidden()); } DEFINE_INLINE_VIRTUAL_TRACE() { } }; class TestMixinAllocationB : public TestMixinAllocationA { USING_GARBAGE_COLLECTED_MIXIN_NESTED(TestMixinAllocationB, TestMixinAllocationA); public: TestMixinAllocationB() { // Completely wrong in general, but test only // runs this constructor while constructing another mixin. ASSERT(ThreadState::current()->isGCForbidden()); } DEFINE_INLINE_TRACE() { TestMixinAllocationA::trace(visitor); } }; class TestMixinAllocationC final : public TestMixinAllocationB { USING_GARBAGE_COLLECTED_MIXIN_NESTED(TestMixinAllocationC, TestMixinAllocationB); public: TestMixinAllocationC() { ASSERT(!ThreadState::current()->isGCForbidden()); } DEFINE_INLINE_TRACE() { TestMixinAllocationB::trace(visitor); } }; TEST(HeapTest, NestedMixinConstruction) { TestMixinAllocationC* object = new TestMixinAllocationC(); EXPECT_TRUE(object); } class ObjectWithLargeAmountsOfAllocationInConstructor { public: ObjectWithLargeAmountsOfAllocationInConstructor(size_t numberOfLargeObjectsToAllocate, ClassWithMember* member) { // Should a constructor allocate plenty in its constructor, // and it is a base of GC mixin, GCs will remain locked out // regardless, as we cannot safely trace the leftmost GC // mixin base. ASSERT(ThreadState::current()->isGCForbidden()); for (size_t i = 0; i < numberOfLargeObjectsToAllocate; i++) { LargeHeapObject* largeObject = LargeHeapObject::create(); EXPECT_TRUE(largeObject); EXPECT_EQ(0, member->traceCount()); } } }; class TestMixinAllocatingObject final : public TestMixinAllocationB, public ObjectWithLargeAmountsOfAllocationInConstructor { USING_GARBAGE_COLLECTED_MIXIN_NESTED(TestMixinAllocatingObject, TestMixinAllocationB); public: static TestMixinAllocatingObject* create(ClassWithMember* member) { return new TestMixinAllocatingObject(member); } DEFINE_INLINE_TRACE() { visitor->trace(m_traceCounter); TestMixinAllocationB::trace(visitor); } int traceCount() const { return m_traceCounter->traceCount(); } private: TestMixinAllocatingObject(ClassWithMember* member) : ObjectWithLargeAmountsOfAllocationInConstructor(600, member) , m_traceCounter(TraceCounter::create()) { ASSERT(!ThreadState::current()->isGCForbidden()); // The large object allocation should trigger a GC.. LargeHeapObject* largeObject = LargeHeapObject::create(); EXPECT_TRUE(largeObject); EXPECT_GT(member->traceCount(), 0); EXPECT_GT(traceCount(), 0); } Member<TraceCounter> m_traceCounter; }; TEST(HeapTest, MixinConstructionNoGC) { Persistent<ClassWithMember> object = ClassWithMember::create(); EXPECT_EQ(0, object->traceCount()); TestMixinAllocatingObject* mixin = TestMixinAllocatingObject::create(object.get()); EXPECT_TRUE(mixin); EXPECT_GT(object->traceCount(), 0); EXPECT_GT(mixin->traceCount(), 0); } } // namespace blink
bsd-3-clause
forcedotcom/phoenix
phoenix-core/src/test/java/com/salesforce/phoenix/end2end/IsNullTest.java
3666
/******************************************************************************* * Copyright (c) 2013, Salesforce.com, 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 Salesforce.com 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 HOLDER 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. ******************************************************************************/ package com.salesforce.phoenix.end2end; import static com.salesforce.phoenix.util.TestUtil.PHOENIX_JDBC_URL; import static org.junit.Assert.*; import java.sql.*; import java.util.Properties; import org.junit.Test; import com.salesforce.phoenix.util.PhoenixRuntime; public class IsNullTest extends BaseClientManagedTimeTest { @Test public void testIsNullInPk() throws Exception { long ts = nextTimestamp(); ensureTableCreated(getUrl(),"IntIntKeyTest",null, ts-2); Properties props = new Properties(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 1)); // Execute at timestamp 1 Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String upsert = "UPSERT INTO IntIntKeyTest VALUES(4,2)"; PreparedStatement upsertStmt = conn.prepareStatement(upsert); int rowsInserted = upsertStmt.executeUpdate(); assertEquals(1, rowsInserted); upsert = "UPSERT INTO IntIntKeyTest VALUES(6)"; upsertStmt = conn.prepareStatement(upsert); rowsInserted = upsertStmt.executeUpdate(); assertEquals(1, rowsInserted); conn.commit(); conn.close(); props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 1 conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props); String select = "SELECT i/j FROM IntIntKeyTest WHERE j IS NULL"; ResultSet rs; rs = conn.createStatement().executeQuery(select); assertTrue(rs.next()); assertEquals(0,rs.getInt(1)); assertTrue(rs.wasNull()); assertFalse(rs.next()); select = "SELECT i/j FROM IntIntKeyTest WHERE j IS NOT NULL"; rs = conn.createStatement().executeQuery(select); assertTrue(rs.next()); assertEquals(2,rs.getInt(1)); assertFalse(rs.next()); } }
bsd-3-clause
graysky/tourbus
public/javascripts/lightWindow.js
52416
// lightWindow.js v1.1 // // Copyright (c) 2007 Einstein Industries // Author: Kevin P Miller | http://www.stickmanlabs.com // // LightWindow is freely distributable under the terms of an MIT-style license. // // I don't care what you think about the file size... // Be a pro: // http://www.thinkvitamin.com/features/webapps/serving-javascript-fast // http://rakaz.nl/item/make_your_pages_load_faster_by_combining_and_compressing_javascript_and_css_files // /*-----------------------------------------------------------------------------------------------*/ if(typeof Effect == 'undefined') throw("lightWindow.js requires including script.aculo.us' effects.js library!"); var lightWindow = Class.create(); lightWindow.prototype = { // // Setup Variables // element : null, contentToFetch : null, boxOverFlow : 'hidden', retroIE : null, windowType : null, animating : false, scrollX : null, scrollY : null, imageArray : [], preloadImage : null, activeGallery : null, activeImage : 0, galleryDirection : null, showDataToggle : false, galleryToggle : false, showTitleToggle : false, // // Initialize the lightWindow. // initialize : function(options) { this.options = Object.extend({ resizeSpeed : 9, cushion : 10, dimensions : { image : {height : 250, width : 250}, page : {height : 250, width : 500}, inline : {height : 250, width : 500}, media : {height : 250, width : 250}, external : {height : 250, width : 250}, dataHeight : 40, titleHeight : 25 }, classNames : { standard : 'lWOn', action : 'lWAction' }, fileTypes : { page : ['htm', 'html', 'rhtml', 'phtml', 'txt', 'php', 'shtml', 'php4', 'php3', 'php', 'php5', 'asp', 'aspx', 'vbs', 'pl', 'cgi', 'rb'], media : ['mpg', 'mp4', 'avi', 'mov', 'mp3', 'aif', 'wmv', 'wav', 'mpeg', 'flv', 'aiff', 'aac', 'ac3', 'asf', 'divx', 'qt', 'rm', 'ram', 'swf', 'wma', 'moov'], image : ['png', 'jpg', 'gif', 'bmp', 'tiff'] }, loadingDialog : { message : 'Loading', image : 'images/ajax-loading.gif', options : '<a onclick="javascript: mylightWindow.deactivate();">Cancel</a>', delay : 3.0 }, authorLead : 'by ', galleryTab : { name : 'Galleries', height : 20, visible : true }, overlay : { color : '#000000', opacity : 70, image : 'images/black-70.png' }, formMethod : 'get', hideFlash : true, showTitleBar : true }, options || {}) this.duration = ((11-this.options.resizeSpeed)*0.15); this.setupLinks(); this.addLightWindowMarkup(false); this.setupDimensions(true); }, // // Set Links Up // setupLinks : function () { var links = $$('.'+this.options.classNames.standard); links.each(function(link) { if (this.fileType(link.href) == 'image') { if (gallery = this.getGalleryInfo(link.rel)) { if (!this.imageArray[gallery[0]]) this.imageArray[gallery[0]] = new Array(); if (!this.imageArray[gallery[0]][gallery[1]]) this.imageArray[gallery[0]][gallery[1]] = new Array(); this.imageArray[gallery[0]][gallery[1]].push(new Array(link.href, link.getAttribute('title'), link.getAttribute('caption'), link.getAttribute('author'), link.getAttribute('rel'), link.getAttribute('params'))); } } var url = link.getAttribute('href'); if (link.href.indexOf('?') > -1) url = url.substring(0, url.indexOf('?')); container = url.substring(url.indexOf('#')+1); if($(container)) $(container).style.display = 'none'; Event.observe(link, 'click', this.activate.bindAsEventListener(this, link)); link.onclick = function() {return false;}; }.bind(this)); }, // // Initialize specific window // initializeWindow : function (id) { var link = $(id); if (this.fileType(link.href) == 'image') { if (gallery = this.getGalleryInfo(link.rel)) { if (!this.imageArray[gallery[0]]) this.imageArray[gallery[0]] = new Array(); if (!this.imageArray[gallery[0]][gallery[1]]) this.imageArray[gallery[0]][gallery[1]] = new Array(); this.imageArray[gallery[0]][gallery[1]].push(new Array(link.href, link.getAttribute('title'), link.getAttribute('caption'), link.getAttribute('author'), link.getAttribute('rel'), link.getAttribute('params'))); } } var url = link.getAttribute('href'); if (link.href.indexOf('?') > -1) url = url.substring(0, url.indexOf('?')); container = url.substring(url.indexOf('#')+1); if($(container)) $(container).style.display = 'none'; Event.observe(link, 'click', this.activate.bindAsEventListener(this, link)); link.onclick = function() {return false;}; }, // // Add the markup to the page. // addLightWindowMarkup : function(rebuild) { if (!rebuild) { var overlay = document.createElement('div'); overlay.setAttribute('id', 'overlay'); if (this.checkBrowser('mac') && this.checkBrowser('firefox')) { overlay.style.backgroundImage = 'url('+this.options.overlay.image+')'; overlay.style.backgroundRepeat = 'repeat'; } else { overlay.style.backgroundColor = this.options.overlay.color; overlay.style.MozOpacity = '.'+this.options.overlay.opacity; overlay.style.opacity = '.'+this.options.overlay.opacity; overlay.style.filter = 'alpha(opacity='+this.options.overlay.opacity+')'; } var lw = document.createElement('div'); lw.setAttribute('id', 'lightWindow'); } else { var lw = $('lightWindow'); } if (this.options.showTitleBar) lw = this.addTitleBarMarkup(lw); var lwc = document.createElement('div'); lwc.setAttribute('id', 'lightWindow-contents'); var lwcc = document.createElement('div'); lwcc.setAttribute('id', 'lightWindow-contents-container'); lwc.appendChild(lwcc); var lwl = document.createElement('div'); lwl.setAttribute('id', 'lightWindow-loading'); var lwi = document.createElement('img'); lwi.setAttribute('src', this.options.loadingDialog.image); lwl.appendChild(lwi); var lwld = document.createElement('span'); lwld.setAttribute('id', 'lightWindow-loading-message'); lwld.innerHTML += this.options.loadingDialog.message; lwl.appendChild(lwld); var lwlo = document.createElement('span'); lwlo.setAttribute('id', 'lightWindow-loading-options'); lwlo.setAttribute('style', 'display:none;'); lwlo.innerHTML += this.options.loadingDialog.options; lwl.appendChild(lwlo); lwc.appendChild(lwl); lw.appendChild(lwc); if (!rebuild) { var body = document.getElementsByTagName('body')[0]; body.appendChild(overlay); body.appendChild(lw); Event.observe(overlay, 'click', this.deactivate.bindAsEventListener(this), false); overlay.onclick = function() {return false;}; } this.addDataWindowMarkup(); this.actions('#lightWindow-loading-options'); }, // // Add the Title Bar Markup // addTitleBarMarkup : function(lw) { var lwdt = document.createElement('div'); lwdt.setAttribute('id', 'lightWindow-title-bar'); lwdt.style.display = 'none'; var lwdtt = document.createElement('div'); lwdtt.setAttribute('id', 'lightWindow-title-bar-title'); lwdt.appendChild(lwdtt); var lwdtc = document.createElement('div'); lwdtc.setAttribute('id', 'lightWindow-title-bar-close'); var lwdtca = document.createElement('a'); lwdtca.setAttribute('id', 'lightWindow-title-bar-close-link'); lwdtca.innerHTML = 'close'; Event.observe(lwdtca, 'click', this.deactivate.bindAsEventListener(this)); lwdtca.onclick = function() {return false;}; lwdtc.appendChild(lwdtca); lwdt.appendChild(lwdtc); lw.appendChild(lwdt); return lw; }, // // Add the Data Window Markup // addDataWindowMarkup : function() { var lw = $('lightWindow'); var lwd = document.createElement('div'); lwd.setAttribute('id', 'lightWindow-data'); lwd.style.display = 'none'; // This container needs to be here to get the data slide to slide as a group var lwds = document.createElement('div'); lwds.setAttribute('id', 'lightWindow-data-slide'); if (!this.options.showTitleBar) { var lwdt = document.createElement('div'); lwdt.setAttribute('id', 'lightWindow-data-title'); lwds.appendChild(lwdt); } var lwdc = document.createElement('div'); lwdc.setAttribute('id', 'lightWindow-data-caption'); lwds.appendChild(lwdc); var lwda = document.createElement('div'); lwda.setAttribute('id', 'lightWindow-data-author'); lwds.appendChild(lwda); var lwdi = document.createElement('div'); lwdi.setAttribute('id', 'lightWindow-data-image'); lwds.appendChild(lwdi); lwd.appendChild(lwds); lw.appendChild(lwd); }, // // Add Photo Window Markup // addPhotoWindowMarkup : function() { var lwc = $('lightWindow-contents'); var lwpc = document.createElement('div'); lwpc.setAttribute('id', 'lightWindow-photo-container'); lwpc.style.display = 'none'; if (images = parseInt(this.getParam('lWShowImages'))) { for (var x = 0; x < images; x++) { lwp = document.createElement('img'); lwp.setAttribute('id', 'lightWindow-photo-'+x); lwpc.appendChild(lwp); } } else { lwp = document.createElement('img'); lwp.setAttribute('id', 'lightWindow-photo-0'); lwpc.appendChild(lwp); } // You ask why I do this? I ask why you insist on using a browser worse than IE? ...Safari! lwps = document.createElement('img'); lwps.setAttribute('id', 'lightWindow-photo-sizer'); lwps.style.display = 'none'; lwps.style.height = '1px'; lwpc.appendChild(lwps); lwc.appendChild(lwpc); }, // // Add Gallery Window Markup // addGalleryWindowMarkup : function() { var lwpc = $('lightWindow-photo-container'); var lwpg = document.createElement('div'); lwpg.setAttribute('id', 'lightWindow-photo-galleries'); lwpg.style.display = 'none'; if (!this.options.galleryTab.visible) lwpg.style.visibility = 'hidden'; var lwptc = document.createElement('div'); lwptc.setAttribute('id', 'lightWindow-photo-tab-container'); var lwpgt = document.createElement('a'); lwpgt.setAttribute('id', 'lightWindow-photo-galleries-tab'); lwpgt.className = 'up'; lwpgt.innerHTML = this.options.galleryTab.name; Event.observe(lwpgt, 'click', this.getGallery.bindAsEventListener(this)); lwpgt.onclick = function() {return false;}; lwptc.appendChild(lwpgt); lwpg.appendChild(lwptc); var lwpgl = document.createElement('div'); lwpgl.setAttribute('id', 'lightWindow-photo-galleries-list'); lwpg.appendChild(lwpgl); lwpc.appendChild(lwpg); }, // // Activate the lightWindow. // activate : function(e, link){ link.blur(); this.element = link; this.element.title = link.getAttribute('title'); this.element.author = link.getAttribute('author'); this.element.caption = link.getAttribute('caption'); this.element.rel = link.getAttribute('rel'); this.element.params = this.element.getAttribute('params'); this.windowType = this.fileType(this.contentToFetch = link.href); if (this.element.caption || this.element.author) this.showDataToggle = true; if (this.options.showTitleBar && this.element.title) this.showTitleToggle = true; else if (!this.options.showTitleBar && this.element.title) this.showDataToggle = true; if (this.getGalleryInfo(this.element.rel)) this.galleryToggle = true; this.prepareIE(true); this.toggleTroubleElements('hidden', false); this.displayLightWindow(true); this.setupDimensions(true); this.monitorKeyboard(true); this.loadInfo(); }, // // Turn off the window // deactivate : function(){ var queue = Effect.Queues.get('lightWindowAnimation').each(function(e) {e.cancel();}); queue = Effect.Queues.get('lightWindowAnimation-loading').each(function(e) {e.cancel();}); if ($('lightWindow-iframe')) Element.remove($('lightWindow-iframe')); Element.remove($('lightWindow-contents')); if ($('lightWindow-data')) Element.remove($('lightWindow-data')); if ($('lightWindow-title-bar')) Element.remove($('lightWindow-title-bar')); this.displayLightWindow(false); this.boxOverFlow = 'hidden'; this.prepareIE(false); this.setStatus(false); this.showDataToggle = this.galleryToggle = this.showTitleToggle = false; this.addLightWindowMarkup(true); this.setupDimensions(true); this.monitorKeyboard(false); this.toggleTroubleElements('visible', false); }, // // Setup our actions // actions : function(prefix) { if (prefix) links = $$(prefix+' .'+this.options.classNames.action); else links = $$('.'+this.options.classNames.action); links.each(function(link) { Event.observe(link, 'click', this[link.rel].bindAsEventListener(this, link), false); link.onclick = function() {return false;}; }.bind(this)); }, // // Set the staus of our animation to keep things from getting clunky // setStatus : function(status) { this.animating = status; // We have to put this here to avoid a flicker in FF Mac if (this.showTitleToggle && !status && $('lightWindow-title-bar')) { $('lightWindow-title-bar').setStyle({ display : 'block' }); } }, // // Setup Dimensions of lightWindow. // setupDataDimensions : function() { if ($('lightWindow-contents') && $('lightWindow-data') && this.showDataToggle) { $('lightWindow-data').setStyle({ height : this.options.dimensions.dataHeight+'px', width : (parseFloat($('lightWindow-contents').style.width)+this.options.cushion*2)+'px' }); $('lightWindow-data-slide').setStyle({ height : this.options.dimensions.dataHeight+'px', overflow : 'hidden' // Because of IE }); } if (this.showTitleToggle && $('lightWindow-title-bar')) { $('lightWindow-title-bar').setStyle({ height : this.options.dimensions.titleHeight+'px', width : (parseFloat($('lightWindow-contents').style.width)+this.options.cushion*2)+'px' }); } }, // // Setup Dimensions of lightWindow. // setupDimensions : function(reset) { if (this.showDataToggle || (this.galleryToggle && this.options.galleryTab.visible)) var adjust = this.options.dimensions.dataHeight; else var adjust = 0; var originalHeight, originalWidth, titleHeight; switch (this.windowType) { case 'page' : originalHeight = this.options.dimensions.page.height; originalWidth = this.options.dimensions.page.width; break; case 'image' : originalHeight = this.options.dimensions.image.height; originalWidth = this.options.dimensions.image.width; break; case 'media' : originalHeight = this.options.dimensions.media.height; originalWidth = this.options.dimensions.media.width; break; case 'external' : originalHeight = this.options.dimensions.external.height; originalWidth = this.options.dimensions.external.width; break; case 'inline' : originalHeight = this.options.dimensions.inline.height; originalWidth = this.options.dimensions.inline.width; break; default : originalHeight = this.options.dimensions.page.height; originalWidth = this.options.dimensions.page.width; break; } if (this.showTitleToggle) titleHeight = this.options.dimensions.titleHeight-1; // We subtract one to smooth out the hiccup when the title bar is added else titleHeight = 0; if (reset) { if (parseFloat($('lightWindow-contents').style.height) != originalHeight) { $('lightWindow-contents').setStyle({ top : titleHeight+'px', width : (originalWidth+this.options.cushion)+'px', height : (originalHeight+this.options.cushion)+'px' }); } else { $('lightWindow-contents').setStyle({ width : (originalWidth+this.options.cushion)+'px', height : (originalHeight+this.options.cushion)+'px' }); } $('lightWindow').setStyle({ padding : '0 0 0 0', width : '0px', height : '0px', margin : (-(((originalHeight+this.options.cushion*3)/2)+(adjust/2)+(titleHeight/2)))+'px 0 0 '+(-((originalWidth+this.options.cushion*3)/2))+'px' }); } else { $('lightWindow').setStyle({ padding : parseFloat($('lightWindow-contents').style.height)+2*this.options.cushion+titleHeight+'px 0 0 0', width : '0px', height : '0px', margin : (-(((parseFloat($('lightWindow-contents').style.height)+this.options.cushion*2)/2)+(adjust/2)+(titleHeight/2)))+'px 0 0 '+(-((parseFloat($('lightWindow-contents').style.width)+this.options.cushion*2)/2))+'px' }); if (parseFloat($('lightWindow-contents').style.height) != originalHeight) { $('lightWindow-contents').setStyle({ top : titleHeight+'px', left : '0px' }); } } }, // // Setup the Overlay (Special Thanks to quirksmode.com and huddletogether.com) // setupOverlay : function() { var xScroll, yScroll; if (window.innerHeight && window.scrollMaxY) { xScroll = document.body.scrollWidth; yScroll = window.innerHeight + window.scrollMaxY; } else if (document.body.scrollHeight > document.body.offsetHeight){ xScroll = document.body.scrollWidth; yScroll = document.body.scrollHeight; } else { xScroll = document.body.offsetWidth; yScroll = document.body.offsetHeight; } var windowWidth, windowHeight; if (self.innerHeight) { windowWidth = self.innerWidth; windowHeight = self.innerHeight; } else if (document.documentElement && document.documentElement.clientHeight) { windowWidth = document.documentElement.clientWidth; windowHeight = document.documentElement.clientHeight; } else if (document.body) { windowWidth = document.body.clientWidth; windowHeight = document.body.clientHeight; } if(yScroll < windowHeight){ pageHeight = windowHeight; } else { pageHeight = yScroll; } if(xScroll < windowWidth){ pageWidth = windowWidth; } else { pageWidth = xScroll; } $('overlay').style.height = pageHeight; $('overlay').style.width = pageWidth; }, // // Display the lightWindow. // displayLightWindow : function(display) { if (display) { $('overlay').style.display = $('lightWindow').style.display = $('lightWindow-contents').style.display = 'block'; } else { $('overlay').style.display = $('lightWindow').style.display = 'none'; } }, // // Is this IE? // checkBrowser : function(type) { var detect = navigator.userAgent.toLowerCase(); var version = parseInt(navigator.appVersion); var place = detect.indexOf(type)+1; return place; }, // // Prepare the window for IE. // prepareIE : function(setup) { if (this.checkBrowser('msie')) { var height, overflowX, overflowY; if (setup) { this.getScroll(); this.setScroll(0, 0); var height = '100%'; } else { var height = 'auto'; } var body = document.getElementsByTagName('body')[0]; var html = document.getElementsByTagName('html')[0]; html.style.height = body.style.height = height; html.style.margin = body.style.margin = '0'; this.setupOverlay(); if (!setup) this.setScroll(this.scrollX, this.scrollY); } }, // // Hide Selects from the page because of IE. // We could use iframe shims instead here but why add all the extra markup for one browser when this is much easier and cleaner // toggleTroubleElements : function(visibility, content){ if (content) var selects = $('lightWindow-contents').getElementsByTagName('select'); else var selects = document.getElementsByTagName('select'); for(var i = 0; i < selects.length; i++) { selects[i].style.visibility = visibility; } if (!content) { if (this.options.hideFlash){ var objects = document.getElementsByTagName('object'); for (i = 0; i != objects.length; i++) { objects[i].style.visibility = visibility; } var embeds = document.getElementsByTagName('embed'); for (i = 0; i != embeds.length; i++) { embeds[i].style.visibility = visibility; } } var iframes = document.getElementsByTagName('iframe'); for (i = 0; i != iframes.length; i++) { iframes[i].style.visibility = visibility; } } }, // // Get the scroll for the page. // getScroll : function(){ if(typeof(window.pageYOffset) == 'number') { this.scrollY = window.pageYOffset; this.scrollX = window.pageXOffset; } else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) { this.scrollY = document.body.scrollTop; this.scrollX = document.body.scrollLeft; } else if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) { this.scrollY = document.documentElement.scrollTop; this.scrollX = document.documentElement.scrollLeft; } }, // // Reset the scroll. // setScroll : function(x, y) { document.documentElement.scrollLeft = x; document.documentElement.scrollTop = y; }, // // Get the value from the params attribute string. // getParam : function(strParamName, strParams) { if (!strParams) { if (this.element.params) strParams = this.element.params; else return; } var strReturn; var aQueryString = strParams.split(','); var cmpstring = strParamName+'='; var cmplen = cmpstring.length; for (var iParam = 0; iParam < aQueryString.length; iParam++) { if (aQueryString[iParam].substr(0, cmplen) == cmpstring) { var aParam = aQueryString[iParam].split('='); strReturn = aParam[1]; break; } } if (!strReturn) return false; else return unescape(strReturn); }, // // Get the domain from a string. // getDomain : function(url) { var leadSlashes = url.indexOf('//'); var domainStart = leadSlashes+2; var withoutResource = url.substring(domainStart, url.length); var nextSlash = withoutResource.indexOf('/'); var domain = withoutResource.substring(0, nextSlash); if (domain.indexOf(':') > -1){ var portColon = domain.indexOf(':'); domain = domain.substring(0, portColon); } return domain; }, // // Get the type of file. // fileType : function(url) { var image = new RegExp("[^\.]\.("+this.options.fileTypes.image.join('|')+")\s*$", "i"); if (image.test(url)) return 'image'; if (url.indexOf('#') > -1 && (document.domain == this.getDomain(url))) return 'inline'; if (url.indexOf('?') > -1) url = url.substring(0, url.indexOf('?')); var type = 'unknown'; var page = new RegExp("[^\.]\.("+this.options.fileTypes.page.join('|')+")\s*$", "i"); var media = new RegExp("[^\.]\.("+this.options.fileTypes.media.join('|')+")\s*$", "i"); if (document.domain != this.getDomain(url)) type = 'external'; if (media.test(url)) type = 'media'; if (type == 'external' || type == 'media') return type; if (page.test(url) || url.substr((url.length-1), url.length) == '/') type = 'page'; return type; }, // // Monitor the keyboard while this lightWindow is up // monitorKeyboard : function(status) { if (status) document.onkeydown = this.eventKeypress.bind(this); else document.onkeydown = ''; }, // // Perform keyboard actions // eventKeypress : function(e) { if (e == null) var keycode = event.keyCode; else var keycode = e.which; switch (keycode) { case 27: this.deactivate(); break; case 13: return; default: break; } // Gotta stop those quick fingers if (this.animating || !this.galleryToggle) return; switch (String.fromCharCode(keycode).toLowerCase()) { case 'p': this.galleryDirection = -1; this.changeImage(); break; case 'n': this.galleryDirection = 1; this.changeImage(); break; default: break; } }, // // Make the Data Box for the Window // showData : function() { if (this.galleryToggle) $('lightWindow-photo-galleries').style.display = 'block'; this.setupDataDimensions(); this.setupDimensions(false); if (this.showDataToggle) { var showDatabox = new Effect.Parallel( [new Effect.SlideDown( 'lightWindow-data', {sync: true, duration: this.duration+1.0, from: 0.0, to: 1.0}), new Effect.Appear('lightWindow-data', {sync: true, duration: 1.0}) ], {duration: 0.65, afterFinish: this.setStatus.bind(this, false), queue: {position: 'end', scope: 'lightWindowAnimation'} } ); } else { this.setStatus(false); } }, // // Insert Data into Window // insertData : function() { if (this.element.title) { if (this.showTitleToggle) $('lightWindow-title-bar-title').innerHTML = this.element.title; else $('lightWindow-data-title').innerHTML = this.element.title; } if (this.element.caption) $('lightWindow-data-caption').innerHTML = this.element.caption; if (this.element.author) $('lightWindow-data-author').innerHTML = this.options.authorLead+this.element.author; }, // // Reset the scroll. // getGalleryInfo : function(rel) { if (rel.indexOf('[') > -1) { return new Array(escape(rel.substring(0, rel.indexOf('['))), escape(rel.substring(rel.indexOf('[')+1, rel.indexOf(']')))); } else { return false; } }, // // Choose a gallery/category // getGallery : function() { var isBadBrowser = this.checkBrowser('msie 6'); if (!$('lightWindow-photo-galleries').style.height || parseInt($('lightWindow-photo-galleries').style.height) == this.options.galleryTab.height) { if (isBadBrowser) { var gallerySize = 100; } else { var gallerySize = ((parseInt($('lightWindow-contents').style.height)*0.95)/this.options.galleryTab.height)*100; } $('lightWindow-photo-galleries-list').setStyle({ height : (parseInt($('lightWindow-contents').style.height)*0.95)-this.options.galleryTab.height+'px' }); // Get out Galleries from the imageArray $('lightWindow-photo-galleries-list').innerHTML = ''; var output = ''; for (i in this.imageArray) { if (typeof this.imageArray[i] == 'object') { output += '<div class="lightWindow-photo-gallery-listing"><h1>'+unescape(i)+'</h1><ul>'; for (j in this.imageArray[i]) { if (typeof this.imageArray[i][j] == 'object') { if (this.imageArray[i][j][0][5]) showImages = ',lWShowImages='+this.getParam('lWShowImages', this.imageArray[i][j][0][5]); else showImages = ''; output += '<li><a href="#" params="lWGallery='+escape(i)+',lWCategory='+escape(j)+''+showImages+'" class="'+this.options.classNames.action+'" rel="reloadGallery" >'+unescape(j)+'</a></li>'; } } output += '</ul></div>'; } } new Insertion.Top('lightWindow-photo-galleries-list', output); this.actions('.lightWindow-photo-gallery-listing'); // IE CSS support sucks and I cannot scale from the bottom.... if (isBadBrowser) { $('lightWindow-photo-galleries').setStyle({ height : (parseInt($('lightWindow-contents').style.height)*0.95)+'px', bottom : '0px' }); $('lightWindow-photo-galleries-tab').className = 'down'; } else { var showGalleries = new Effect.CushionScale('lightWindow-photo-galleries', gallerySize, {duration: this.duration, afterFinish: function(){$('lightWindow-photo-galleries-list').style.overflow = 'auto'; $('lightWindow-photo-galleries-tab').className = 'down';}, scaleX: false, scaleY: true, scaleContent: false, scaleFromCenter: false, queue: {position: 'end', scope: 'lightWindowAnimation'}}); } } else { if (isBadBrowser) { var bottom = -(parseInt($('lightWindow-contents').style.height)*0.95)+this.options.galleryTab.height; } else { var bottom = 0; } $('lightWindow-photo-galleries').setStyle({ height : this.options.galleryTab.height+'px', bottom : bottom+'px', top : '' }); $('lightWindow-photo-galleries-list').setStyle({ overflow : 'hidden' }); $('lightWindow-photo-galleries-tab').className = 'up'; } }, // // Set the gallery up. // setupGallery : function(gallery, start) { var lwc = $('lightWindow-photo-container'); if (!(images = parseInt(this.getParam('lWShowImages')))) images = 1; for (var x = 0; x < this.imageArray[gallery[0]][gallery[1]].length; x++) { if (this.imageArray[gallery[0]][gallery[1]][x][0] == this.contentToFetch) break; } this.activeImage = x; this.activeGallery = gallery; var lwn = document.createElement("div"); lwn.setAttribute('id','lightWindow-navigation'); lwc.appendChild(lwn); if (x != 0 && this.imageArray[gallery[0]][gallery[1]][x-images]) { var lwnp = document.createElement("a"); lwnp.setAttribute('id','lightWindow-previous'); lwnp.setAttribute('href','#'); lwn.appendChild(lwnp); Event.observe(lwnp, 'click', this.changeImage.bindAsEventListener(this, this.imageArray[gallery[0]][gallery[1]][x-images][0], this.imageArray[gallery[0]][gallery[1]][x-images][1], this.imageArray[gallery[0]][gallery[1]][x-images][2], this.imageArray[gallery[0]][gallery[1]][x-images][3], this.imageArray[gallery[0]][gallery[1]][x-images][4])); lwnp.onclick = function(){return false;}; } if ((x+1) < this.imageArray[gallery[0]][gallery[1]].length && this.imageArray[gallery[0]][gallery[1]][x+images]) { var lwnn = document.createElement("a"); lwnn.setAttribute('id','lightWindow-next'); lwnn.setAttribute('href','#'); lwn.appendChild(lwnn); Event.observe(lwnn, 'click', this.changeImage.bindAsEventListener(this, this.imageArray[gallery[0]][gallery[1]][x+images][0], this.imageArray[gallery[0]][gallery[1]][x+images][1], this.imageArray[gallery[0]][gallery[1]][x+images][2], this.imageArray[gallery[0]][gallery[1]][x+images][3], this.imageArray[gallery[0]][gallery[1]][x+images][4])); lwnn.onclick = function(){return false;}; } if (images == 1) $('lightWindow-data-image').innerHTML = 'Image '+(x+1)+' of '+this.imageArray[gallery[0]][gallery[1]].length; this.addGalleryWindowMarkup(); }, // // Get the contents for the window // loadInfo : function() { var showLoadingOptions = new Effect.Appear('lightWindow-loading-options', {delay: this.options.loadingDialog.delay, duration: this.duration, queue: {position: 'front', scope: 'lightWindowAnimation-loading'}}); switch (this.windowType) { case 'image' : this.preloadImage = new Array(); if (!$('lightWindow-photo-container')) { this.addPhotoWindowMarkup(); this.addDataWindowMarkup(); this.addGalleryWindowMarkup(); } var totalWidth = 0; var totalHeight = 0; var gallery = this.getGalleryInfo(this.element.rel); if (images = parseInt(this.getParam('lWShowImages'))) { for (var z = 0; z < this.imageArray[gallery[0]][gallery[1]].length; z++) { if (this.imageArray[gallery[0]][gallery[1]][z][0] == this.contentToFetch) break; } $('lightWindow-photo-container').style.display = 'none'; this.loading = images-1; for (var x = 0; x < images; x++) { if (this.imageArray[gallery[0]][gallery[1]][x+z]) { this.preloadImage[x] = new Image(); this.preloadImage[x].onload=function(){ if ($('lightWindow-photo-container').style.display != 'block') { for (var t = 0; t <= x; t++) { if (this.preloadImage[t] && (this.preloadImage[t].width != 0 && this.preloadImage[t].height != 0)) { totalWidth = totalWidth+this.preloadImage[t].width; totalHeight = this.preloadImage[t].height; this.preloadImage.splice(t, 1); this.loading--; } } if (this.loading < 0) { $('lightWindow-photo-container').setStyle({ display : 'block' }); $('lightWindow-photo-sizer').setStyle({ width : totalWidth+'px', height : totalHeight+'px' }); this.processInfo(); } } }.bind(this, x); this.preloadImage[x].src = $('lightWindow-photo-'+x).src = this.imageArray[gallery[0]][gallery[1]][x+z][0]; } } this.activeImage = this.activeImage+x-1; if (this.galleryToggle) this.setupGallery(this.getGalleryInfo(this.element.rel)); } else { this.preloadImage[0] = new Image(); this.preloadImage[0].onload=function(){ totalWidth = this.preloadImage[0].width; totalHeight = this.preloadImage[0].height; $('lightWindow-photo-container').setStyle({ display : 'block' }); $('lightWindow-photo-sizer').setStyle({ width : totalWidth+'px', height : totalHeight+'px' }); this.processInfo(); }.bind(this); this.preloadImage[0].src = $('lightWindow-photo-0').src = this.contentToFetch; if (this.galleryToggle) this.setupGallery(this.getGalleryInfo(this.element.rel)); } break; case 'media' : // Don't question it.... damn safari var lwi = '<iframe id="lightWindow-iframe" name="lightWindow-iframe" height="100%" width="100%" frameborder="0" scrolling="no"></iframe>'; new Insertion.Top($('lightWindow-contents'), lwi); parent.$('lightWindow-iframe').style.visibility = 'hidden'; this.processInfo(); break; case 'external' : // Don't question it.... damn safari var lwi = '<iframe id="lightWindow-iframe" name="lightWindow-iframe" height="100%" width="100%" frameborder="0" scrolling="auto"></iframe>'; new Insertion.Top($('lightWindow-contents'), lwi); parent.$('lightWindow-iframe').style.visibility = 'hidden'; this.processInfo(); break; case 'page' : var newAJAX = new Ajax.Request( this.contentToFetch, {method: 'get', parameters: '', onComplete: this.processInfo.bind(this)} ); break; case 'inline' : var content = this.contentToFetch; if (content.indexOf('?') > -1) { content = content.substring(0, content.indexOf('?')); } content = content.substring(content.indexOf('#')+1); new Insertion.Top($('lightWindow-contents-container'), $(content).innerHTML); this.toggleTroubleElements('hidden', true); this.processInfo(); break; default : throw('Page Type could not be determined, please amend this lightWindow URL '+this.contentToFetch); break; } }, // // Finish the loading process and clean up. // loadFinish : function() { this.actions(); this.insertData(false); switch (this.windowType) { case 'page' : var hideLoading = new Effect.Fade('lightWindow-loading', {duration: this.duration, afterFinish: this.windowAdjust.bind(this), queue: {position: 'end', scope: 'lightWindowAnimation'}}); break; case 'image' : var hideLoading = new Effect.Fade('lightWindow-loading', {duration: this.duration, afterFinish: this.windowAdjust.bind(this), queue: {position: 'end', scope: 'lightWindowAnimation'}}); break; case 'media' : parent.$('lightWindow-iframe').src = this.contentToFetch; var hideLoading = new Effect.Fade('lightWindow-loading', {duration: this.duration, afterFinish: this.windowAdjust.bind(this), queue: {position: 'end', scope: 'lightWindowAnimation'}}); break; case 'external' : parent.$('lightWindow-iframe').src = this.contentToFetch; var hideLoading = new Effect.Fade('lightWindow-loading', {duration: this.duration, afterFinish: this.windowAdjust.bind(this), queue: {position: 'end', scope: 'lightWindowAnimation'}}); break; case 'inline' : var hideLoading = new Effect.Fade('lightWindow-loading', {duration: this.duration, afterFinish: this.windowAdjust.bind(this), queue: {position: 'end', scope: 'lightWindowAnimation'}}); break; default : break; } }, // // Adjust the Window and add the data box if it needs it // windowAdjust : function() { if (this.windowType == 'external' || this.windowType == 'media') { // No I don't like this but it works with a small flicker, FF for the Mac is a little more buggy than I would have thought // Of Note this is really for the quicktime samples as far as I can tell.... if (this.checkBrowser('mac') && this.checkBrowser('firefox')) { if ($('overlay').style.height == '100%' || !$('overlay').style.height) $('overlay').style.height = '101%'; else $('overlay').style.height = '100%'; } parent.$('lightWindow-iframe').style.visibility = 'visible'; } $('lightWindow-contents').style.overflow = this.boxOverFlow; this.toggleTroubleElements('visible', true); if (this.showDataToggle || this.showTitleToggle) { this.showData(); } }, // // Get the content into the window and show it off. // processInfo : function(response) { if(this.checkBrowser('msie')) { var windowHeight = document.documentElement.clientHeight; var windowWidth = document.documentElement.clientWidth; } else { var windowHeight = window.innerHeight; var windowWidth = window.innerWidth; } // What if the window size is ridiculously small? If so we need some overrides to make it fit and make it usable (even on set dimensions) if (this.showDataToggle) var dataWindow = this.options.dimensions.dataHeight; else var dataWindow = 0; if (this.options.showTitleBar) titleHeight = this.options.dimensions.titleHeight; else titleHeight = 0; var lWcWidth = parseInt($('lightWindow-contents').style.width); var lWcHeight = parseInt($('lightWindow-contents').style.height); var availableHeight = windowHeight-dataWindow-2*this.options.cushion-titleHeight; var availableWidth = windowWidth-2*this.options.cushion; var boxWidth, boxScrollWidth, boxHeight, boxScrollHeight, scaleX, scaleY; var totalHeight = 0; var totalWidth = 0; switch (this.windowType) { case 'image' : if (!(images = parseInt(this.getParam('lWShowImages')))) images = 1; boxWidth = $('lightWindow-contents').offsetWidth; boxHeight = $('lightWindow-contents').offsetHeight; if ($('lightWindow-photo-0').height > availableHeight) { var totalWidth = 0; for (var x = 0; x < images; x++) { $('lightWindow-photo-'+x).height = availableHeight; totalWidth = totalWidth+$('lightWindow-photo-'+x).width; } if (images > 1) totalWidth++; // This is needed for putting images side by side when we resize the iamge only boxScrollHeight = availableHeight; boxScrollWidth = totalWidth; $('lightWindow-photo-sizer').style.height = availableHeight+'px'; $('lightWindow-photo-sizer').style.width = totalWidth+'px'; } else { boxScrollHeight = parseInt($('lightWindow-photo-sizer').style.height); boxScrollWidth = parseInt($('lightWindow-photo-sizer').style.width); } break; case 'external' : boxWidth = $('lightWindow-contents').offsetWidth; boxHeight = $('lightWindow-contents').offsetHeight; break; case 'media' : boxWidth = $('lightWindow-contents').offsetWidth; boxHeight = $('lightWindow-contents').offsetHeight; break; case 'page' : new Insertion.Top($('lightWindow-contents-container'), response.responseText); this.toggleTroubleElements('hidden', true); boxWidth = $('lightWindow-contents').offsetWidth; boxScrollWidth = $('lightWindow-contents').scrollWidth; boxHeight = $('lightWindow-contents').offsetHeight; boxScrollHeight = $('lightWindow-contents').scrollHeight; break; case 'inline' : boxWidth = $('lightWindow-contents').offsetWidth; boxScrollWidth = $('lightWindow-contents').scrollWidth; boxHeight = $('lightWindow-contents').offsetHeight; boxScrollHeight = $('lightWindow-contents').scrollHeight+3; break; default : break; } // Were dimensions set? // This also resizes to fit the window, for things like flash! var ignorelWHeight = false; if (lWWidth = this.getParam('lWWidth')) { boxScrollWidth = parseFloat(lWWidth); if (boxScrollWidth > (windowWidth*.95)) { tmp = boxScrollWidth; boxScrollWidth = 0.90*windowWidth; lWHeight = this.getParam('lWHeight'); // For this case I require a height to be set, why would you set width and not set height? boxScrollHeight = parseFloat(lWHeight); boxScrollHeight = boxScrollHeight * (boxScrollWidth/tmp) ignorelWHeight = true; } } if (lWHeight = this.getParam('lWHeight')) { if (!ignorelWHeight) { boxScrollHeight = parseFloat(lWHeight); if (boxScrollHeight > (windowHeight*.8)) { boxScrollHeight = 0.8*windowHeight; } } } if (lWOverflow = this.getParam('lWOverflow')) this.boxOverFlow = lWOverflow; if ((boxScrollHeight < (windowHeight*.8)) && this.windowType != 'external' && this.windowType != 'image') { scaleY = parseFloat((boxScrollHeight/boxHeight)*100); } else if (this.windowType == 'external' && !lWHeight) { scaleY = parseFloat((windowHeight/(1.2*boxHeight))*100); } else if (this.windowType == 'external' && lWHeight) { scaleY = parseFloat((boxScrollHeight/(boxHeight))*100); } else if (this.windowType == 'image' || this.windowType == 'media') { scaleY = parseFloat(((boxScrollHeight)/boxHeight)*100); } else { if (this.windowType != 'media') this.boxOverFlow = 'auto'; $('lightWindow-contents-container').marginRight = '16px'; scaleY = parseFloat((windowHeight/(1.2*boxHeight))*100); } if ((boxScrollWidth < (windowWidth*.8)) && this.windowType != 'external' && this.windowType != 'image' && this.windowType != 'media') { scaleX = parseFloat(((boxScrollWidth)/boxWidth)*100); } else if (this.windowType == 'external' && !lWWidth) { scaleX = parseFloat((windowWidth/(1.1*boxWidth))*100); } else if (this.windowType == 'external' && lWWidth) { scaleX = parseFloat((boxScrollWidth/(boxWidth))*100); } else if (this.windowType == 'image' || this.windowType == 'media') { scaleX = parseFloat(((boxScrollWidth)/boxWidth)*100); } else { if (this.windowType != 'media') this.boxOverFlow = 'auto'; $('lightWindow-contents-container').marginRight = '16px'; scaleX = parseFloat((windowWidth/(1.1*boxWidth))*100); } this.setStatus(true); var doDelay = 0; if (scaleX != 100 && lWcWidth != boxScrollWidth) { if (scaleY == 100) var doX = new Effect.CushionScale('lightWindow-contents', scaleX, {duration: this.duration, scaleX: true, scaleY: false, scaleCushion: {top: this.options.cushion, left: this.options.cushion}, afterFinish: this.loadFinish.bind(this), scaleFromCenter: true, scaleContent: false, queue: {position: 'front', scope: 'lightWindowAnimation'}}); else var doX = new Effect.CushionScale('lightWindow-contents', scaleX, {duration: this.duration, scaleX: true, scaleY: false, scaleCushion: {top: this.options.cushion, left: this.options.cushion}, scaleContent: false, scaleFromCenter: true, queue: {position: 'front', scope: 'lightWindowAnimation'}}); doDelay = this.duration/2; } if (scaleY != 100 && lWcHeight != boxScrollHeight) { var doY = new Effect.CushionScale('lightWindow-contents', scaleY, {duration: this.duration, delay: doDelay, scaleX: false, scaleY: true, scaleCushion: {top: this.options.cushion, left: this.options.cushion}, afterFinish: this.loadFinish.bind(this), scaleContent: false, scaleFromCenter: true, queue: {position: 'end', scope: 'lightWindowAnimation'}}); } if ((!doX && !doY) || (doX && scaleY != 100 && !doY)) this.loadFinish(); }, // // Reload the window with another location // reloadWindow : function(element) { Element.remove($('lightWindow-contents')); if ($('lightWindow-data')) Element.remove($('lightWindow-data')); this.element = element; this.contentToFetch = this.element.href; this.addLightWindowMarkup(true); this.setupDimensions(true); this.displayLightWindow(true); this.loadInfo(); }, // // Reload the Gallery // reloadGallery : function(e, link) { this.element.params = link.getAttribute('params'); var gallery = this.getParam('lWGallery', this.element.params); var category = this.getParam('lWCategory', this.element.paramse); this.element.rel = this.imageArray[gallery][category][0][4]; this.element.title = this.imageArray[gallery][category][0][1]; this.element.caption = this.imageArray[gallery][category][0][2]; this.element.author = this.imageArray[gallery][category][0][3]; this.contentToFetch = this.imageArray[gallery][category][0][0]; Element.remove($('lightWindow-photo-container')); if ($('lightWindow-data')) Element.remove($('lightWindow-data')); if ($('lightWindow-title-bar')) $('lightWindow-title-bar').style.display = 'none'; this.galleryToggle = true; this.activeGallery[0] = gallery this.activeGallery[1] = category; this.activeImage = 0; // Becuase of IE we have to use either Appear or setOpacity/show var showLoading = Effect.Appear('lightWindow-loading', {duration: 0, afterFinish: this.loadInfo.bind(this)}); }, // // Change the Image // changeImage : function(e) { var data = $A(arguments); data.shift(); if (data != '') { this.contentToFetch = data[0]; this.element.title = data[1]; this.element.caption = data[2]; this.element.author = data[3]; this.element.rel = data[4]; } else { if (!(images = parseInt(this.getParam('lWShowImages')))) images = 1; if ((this.galleryDirection < 0 && (this.activeImage-1*images) < 0) || (this.galleryDirection > 0 && (this.activeImage+1*images) >= this.imageArray[this.activeGallery[0]][this.activeGallery[1]].length)) return false; this.element.title = this.imageArray[this.activeGallery[0]][this.activeGallery[1]][this.activeImage+this.galleryDirection*images][1]; this.element.caption = this.imageArray[this.activeGallery[0]][this.activeGallery[1]][this.activeImage+this.galleryDirection*images][2]; this.element.author = this.imageArray[this.activeGallery[0]][this.activeGallery[1]][this.activeImage+this.galleryDirection*images][3]; this.element.params = this.imageArray[this.activeGallery[0]][this.activeGallery[1]][0][5]; this.element.rel = unescape(this.activeGallery[0]+'['+this.activeGallery[1]+']'); this.contentToFetch = this.imageArray[this.activeGallery[0]][this.activeGallery[1]][this.activeImage+this.galleryDirection*images][0]; this.activeImage = this.activeImage+this.galleryDirection*images; } // Preload the previous and next images if ((this.activeImage-1) >= 0) { var preloadNextImage = new Image(); preloadNextImage.src = this.imageArray[this.activeGallery[0]][this.activeGallery[1]][this.activeImage-1][0]; } if ((this.activeImage+1) < this.imageArray[this.activeGallery[0]][this.activeGallery[1]].length) { var preloadPrevImage = new Image(); preloadPrevImage.src = this.imageArray[this.activeGallery[0]][this.activeGallery[1]][this.activeImage+1][0]; } Element.remove($('lightWindow-photo-container')); if ($('lightWindow-data')) Element.remove($('lightWindow-data')); if ($('lightWindow-title-bar')) $('lightWindow-title-bar').style.display = 'none'; this.galleryToggle = true; $('lightWindow-loading-options').style.display = 'none'; // Becuase of IE we have to use either Appear or setOpacity/show var showLoading = Effect.Appear('lightWindow-loading', {duration: 0, afterFinish: this.loadInfo.bind(this)}); }, // // Submit a form to another lightWindow // insertForm : function(e) { var element = Event.element(e).parentNode; var parameterString = Form.serialize(this.getParam('lWForm', element.getAttribute('params'))); if (this.options.formMethod == 'post') { var newAJAX = new Ajax.Request( element.href, {method: 'post', postBody: parameterString, onComplete: this.reloadWindow.bind(this, element)} ); } else if (this.options.formMethod == 'get') { var newAJAX = new Ajax.Request( element.href, {method: 'get', parameters: parameterString, onComplete: this.reloadWindow.bind(this, element)} ); } } } /*-----------------------------------------------------------------------------------------------*/ Event.observe(window, 'load', lightWindowInit, false); // // Set up all of our links // var mylightWindow = null; function lightWindowInit() { mylightWindow = new lightWindow(); } /*----------------------------------------------------------------------------------------------- Problem: This effect does not take into account padding or a border on an element, especially an absolutely position element. Added: Options: scaleCushion: 0 // or {top, left} with provided values Example: scaleCushion: {top: 10, left: 10} Code: To setDimensions: function(height, width) Original: if(this.options.scaleY) d.top = this.originalTop-topd + 'px'; if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; New: if(this.options.scaleCushion == 'none') { if(this.options.scaleY) d.top = this.originalTop-topd + 'px'; if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; } else { if(this.options.scaleY) d.top = (this.originalTop-topd-this.options.scaleCushion.top-this.options.scaleCushion.bottom) + 'px'; if(this.options.scaleX) d.left = (this.originalLeft-leftd-this.options.scaleCushion.right-this.options.scaleCushion.left) + 'px'; } Credit: Kevin P Miller http://www.stickmanlabs.com -----------------------------------------------------------------------------------------------*/ Effect.CushionScale = Class.create(); Object.extend(Object.extend(Effect.CushionScale.prototype, Effect.Base.prototype), { initialize: function(element, percent) { this.element = $(element); if(!this.element) throw(Effect._elementDoesNotExistError); var options = Object.extend({ scaleX: true, scaleY: true, scaleContent: true, scaleFromCenter: false, scaleMode: 'box', // 'box' or 'contents' or {} with provided values scaleFrom: 100.0, scaleTo: percent, scaleCushion: 'none' // 'none' or {} with provided values }, arguments[2] || {}); this.start(options); }, setup: function() { this.restoreAfterFinish = this.options.restoreAfterFinish || false; this.elementPositioning = this.element.getStyle('position'); this.originalStyle = {}; ['top','left','width','height','fontSize'].each( function(k) { this.originalStyle[k] = this.element.style[k]; }.bind(this)); this.originalTop = this.element.offsetTop; this.originalLeft = this.element.offsetLeft; var fontSize = this.element.getStyle('font-size') || '100%'; ['em','px','%','pt'].each( function(fontSizeType) { if(fontSize.indexOf(fontSizeType)>0) { this.fontSize = parseFloat(fontSize); this.fontSizeType = fontSizeType; } }.bind(this)); this.factor = (this.options.scaleTo - this.options.scaleFrom)/100; this.dims = null; if(this.options.scaleMode=='box') this.dims = [this.element.offsetHeight, this.element.offsetWidth]; if(/^content/.test(this.options.scaleMode)) this.dims = [this.element.scrollHeight, this.element.scrollWidth]; if(!this.dims) this.dims = [this.options.scaleMode.originalHeight, this.options.scaleMode.originalWidth]; }, update: function(position) { var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position); if(this.options.scaleContent && this.fontSize) this.element.setStyle({fontSize: this.fontSize * currentScale + this.fontSizeType }); this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale); }, finish: function(position) { if(this.restoreAfterFinish) this.element.setStyle(this.originalStyle); }, setDimensions: function(height, width) { var d = {}; if(this.options.scaleX) d.width = width + 'px'; if(this.options.scaleY) d.height = height + 'px'; if(this.options.scaleFromCenter) { var topd = (height - this.dims[0])/2; var leftd = (width - this.dims[1])/2; if(this.elementPositioning == 'absolute') { if(this.options.scaleCushion == 'none') { if(this.options.scaleY) d.top = this.originalTop-topd + 'px'; if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px'; } else { if(this.options.scaleY) d.top = (this.originalTop-topd-this.options.scaleCushion.top) + 'px'; if(this.options.scaleX) d.left = (this.originalLeft-leftd-this.options.scaleCushion.left) + 'px'; } } else { if(this.options.scaleY) d.top = -topd + 'px'; if(this.options.scaleX) d.left = -leftd + 'px'; } } this.element.setStyle(d); } });
bsd-3-clause
aekkapun/Other-Charge-Management
models/OcrEntrySearch.php
2686
<?php namespace app\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use app\models\OcrEntry; /** * OcrEntrySearch represents the model behind the search form about `app\models\OcrEntry`. */ class OcrEntrySearch extends OcrEntry { /** * @inheritdoc */ public function rules() { return [ [['id', 'dep_id', 'user_id'], 'integer'], [['finance_year', 'opening_ammount', 'total_expend', 'avail_bal', 'timestamp', 'source_ip'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = OcrEntry::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if ($this->load($params) && !$this->validate()) { return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'dep_id' => $this->dep_id, 'timestamp' => $this->timestamp, 'user_id' => $this->user_id, ]); $query->andFilterWhere(['like', 'finance_year', $this->finance_year]) ->andFilterWhere(['like', 'opening_ammount', $this->opening_ammount]) ->andFilterWhere(['like', 'total_expend', $this->total_expend]) ->andFilterWhere(['like', 'avail_bal', $this->avail_bal]) ->andFilterWhere(['like', 'source_ip', $this->source_ip]); return $dataProvider; } public function usersearch($params, $data) { $query = OcrEntry::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if (isset($_GET['OcrEntrySearch']) && !($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'dep_id' => $data, 'timestamp' => $this->timestamp, 'user_id' => $this->user_id, ]); $query->andFilterWhere(['like', 'finance_year', $this->finance_year]) ->andFilterWhere(['like', 'opening_ammount', $this->opening_ammount]) ->andFilterWhere(['like', 'total_expend', $this->total_expend]) ->andFilterWhere(['like', 'avail_bal', $this->avail_bal]) ->andFilterWhere(['like', 'source_ip', $this->source_ip]); return $dataProvider; } }
bsd-3-clause
aghiles/microexr
src/channel.cpp
1628
/******************************************************************************/ /* */ /* Copyright (c) 2011, DNA Research, the 3Delight Developers. */ /* All Rights Reserved. */ /* */ /******************************************************************************/ /* class Channel Single channel block in exr file */ #include "channel.h" /* Channel::WriteToFile Writes channel block to i_outputFile according [1]: Channel layout: - name: zero-terminated string, from 1 to 31 bytes long - pixel type: int, possible values are UINT = 0, HALF = 1, FLOAT = 2 - pLinear: unsigned char, possible values are 0 and 1 - reserved: three chars, should be zero - xSampling: int - ySampling: int */ int Channel::WriteToFile(FILE *i_outputFile)const { fputs(m_name, i_outputFile); fputc('\0', i_outputFile); fwrite(&m_type, sizeof(m_type), 1, i_outputFile); fwrite(&m_pLinear, sizeof(m_pLinear), 1, i_outputFile); fputc('\0', i_outputFile); fputc('\0', i_outputFile); fputc('\0', i_outputFile); fwrite(&m_xSampling, sizeof(m_xSampling), 1, i_outputFile); fwrite(&m_ySampling, sizeof(m_ySampling), 1, i_outputFile); return IMF_ERROR_NOERROR; } /* Channel::Size Returns size of channel's data in bytes */ size_t Channel::Size()const { int size = strlen(m_name) + 1 + sizeof(m_type) + sizeof(m_pLinear) + 3 + sizeof(m_xSampling) + sizeof(m_ySampling); return size; }
bsd-3-clause