answer stringlengths 15 1.25M |
|---|
// <API key>.h
// Skim
#import <Cocoa/Cocoa.h>
#import "SKPreferencePane.h"
@interface <API key> : SKPreferencePane {
NSPopUpButton *<API key>;
NSArray *<API key>;
NSTextField *openFilesLabelField;
NSMatrix *openFilesMatrix;
NSTextField *<API key>;
NSMatrix *savePasswordsMatrix;
NSInteger updateInterval;
}
@property (nonatomic, retain) IBOutlet NSPopUpButton *<API key>;
@property (nonatomic, retain) IBOutlet NSArray *<API key>;
@property (nonatomic, retain) IBOutlet NSTextField *openFilesLabelField;
@property (nonatomic, retain) IBOutlet NSMatrix *openFilesMatrix;
@property (nonatomic, retain) IBOutlet NSTextField *<API key>;
@property (nonatomic, retain) IBOutlet NSMatrix *savePasswordsMatrix;
@property (nonatomic) NSInteger updateInterval;
- (IBAction)<API key>:(id)sender;
@end |
#ifndef <API key>
#define <API key>
class WebDatabase;
namespace autofill {
class <API key>;
// Interface for doing Autofill work directly on the DB thread (used by
// Sync, mostly), without fully exposing the <API key> to clients.
class <API key> {
public:
virtual ~<API key>() {}
// Get a raw pointer to the WebDatabase.
virtual WebDatabase* GetDatabase() = 0;
// Add an observer to be notified of changes on the DB thread.
virtual void AddObserver(
<API key>* observer) = 0;
// Remove an observer.
virtual void RemoveObserver(
<API key>* observer) = 0;
// Remove expired elements from the database and commit if needed.
virtual void <API key>() = 0;
// Notifies listeners on the UI thread that multiple changes have been made to
// to Autofill records of the database.
// NOTE: This method is intended to be called from the DB thread. It
// asynchronously notifies listeners on the UI thread.
virtual void <API key>() = 0;
};
} // namespace autofill
#endif // <API key> |
<?php
require("login/login.php");
include 'monitor.inc';
include 'db_utils.inc';
$user_id = getCurrentUserId();
try
{
// Folder
if (isset($_REQUEST['folderId']) && ($folderId = $_REQUEST['folderId'])) {
$_SESSION['alertFolderId'] = $folderId;
}
if (!isset($_SESSION['alertFolderId'])) {
$_SESSION['alertFolderId'] = <API key>($user_id, 'Alert');
}
$folderId = $_SESSION['alertFolderId'];
$smarty->assign('folderId', $_SESSION['alertFolderId']);
$folderTree = getFolderTree($user_id,'Alert');
$smarty->assign('folderTree', $folderTree);
// Handle filter settings
if (isset($_REQUEST['clearFilter'])) {
unset($_SESSION['alertsFilterField']);
unset($_SESSION['alertsFilterValue']);
} else {
if (isset($_REQUEST['filterField']) && $alertsFilterField = $_REQUEST['filterField']) {
$_SESSION['alertsFilterField'] = $alertsFilterField;
}
if (isset($_REQUEST['filterValue']) && $alertsFilterValue = $_REQUEST['filterValue']) {
$_SESSION['alertsFilterValue'] = $alertsFilterValue;
}
}
if ( isset($_SESSION['alertsFilterField'] ) ){
$alertsFilterField = $_SESSION['alertsFilterField'];
$alertsFilterValue = $_SESSION['alertsFilterValue'];
}
// Handle pager settings
if (isset($_REQUEST['currentPage'])) {
$_SESSION['alertsCurrentPage'] = $_REQUEST['currentPage'];
}
if (!$_SESSION['alertsCurrentPage']) {
$_SESSION['alertsCurrentPage'] = 1;
}
$alertsCurrentPage = $_SESSION['alertsCurrentPage'];
// Show inactive alerts
if (isset($_REQUEST['showInactiveAlerts'])) {
if ($_REQUEST['showInactiveAlerts'] == 1 || $_REQUEST['showInactiveAlerts'] == "true") {
$_SESSION['showInactiveAlerts'] = true;
} else {
$_SESSION['showInactiveAlerts'] = false;
}
} else if ( !isset($_SESSION['showInactiveAlerts'])){
$_SESSION['showInactiveAlerts'] = true;
}
$showInactiveAlerts = $_SESSION['showInactiveAlerts'];
// Order by direction
if (isset($_REQUEST['orderByDir']) && ($orderByDir = $_REQUEST['orderByDir'])) {
$_SESSION['<API key>'] = $orderByDir;
}
if (!isset($_SESSION['<API key>'])) {
$_SESSION['<API key>'] = "ASC";
}
if ($_SESSION['<API key>'] == "ASC") {
$orderByDirInv = "DESC";
} else {
$orderByDirInv = "ASC";
}
// Order by
if (isset($_REQUEST['orderBy']) && ($orderBy = $_REQUEST['orderBy'])) {
$_SESSION['orderAlertsBy'] = $orderBy;
}
if (!isset($_SESSION['orderAlertsBy'])) {
$_SESSION['orderAlertsBy'] = "Id";
}
// fixRootFolder('Alert',$user_id);
$smarty->assign('<API key>', $_SESSION['<API key>']);
$smarty->assign('<API key>', $orderByDirInv);
$smarty->assign('orderAlertsBy', $_SESSION['orderAlertsBy']);
$orderAlertsBy = "a." . $_SESSION['orderAlertsBy'] . ' ' . $_SESSION['<API key>'];
$selectFields = 'a.Active, a.Id, a.Label, a.Description, a.AlertOnType COUNT(a.Id) AS ResultCount';
$q = Doctrine_Query::create()->select($selectFields)
->from('Alert a, a.AlertFolder f')
->orderBy($orderAlertsBy)
->groupBy('a.Id');
if (!$showInactiveAlerts) {
$q->andWhere('a.Active = ?', true);
}
if (isset($alertsFilterField) && isset($alertsFilterValue)) {
$q->andWhere('a.' . $alertsFilterField . ' LIKE ?', '%' . $alertsFilterValue . '%');
} else {
// set for smarty
$alertsFilterField='';
$alertsFilterValue='';
}
if ($folderId > -1 && hasPermission('Alert',$folderId,PERMISSION_READ)) {
$q->andWhere('a.AlertFolderId = ?', $folderId);
} else {
$q->andWhere('a.UserId = ?', $user_id);
}
$pager = new Doctrine_Pager($q, $alertsCurrentPage, $resultsPerPage);
$result = $pager->execute();
global $<API key>;
$smarty->assign('<API key>', $<API key>);
global $<API key>;
$smarty->assign('<API key>', $<API key>);
$smarty->assign('alertsFilterField', $alertsFilterField);
$smarty->assign('alertsFilterValue', $alertsFilterValue);
$smarty->assign('currentPage', $alertsCurrentPage);
$smarty->assign('maxpages', $pager->getLastPage());
$smarty->assign('showInactiveAlerts', $_SESSION['showInactiveAlerts']);
$smarty->assign('result', $result);
// $smarty->assign('resultCount', $resultCount);
// $smarty->assign('current_seconds', $current_Seconds);
$shares = getFolderShares($user_id,'Alert');
$smarty->assign('shares',$shares);
} catch (Exception $e) {
error_log("[WPTMonitor] Failed while Listing alerts: " . $wptResultId . " message: " . $e->getMessage());
print 'Exception : ' . $e->getMessage();
}
unset($share);
// unset($pager);
// unset($results);
$smarty->display('alert/listAlerts.tpl');
?> |
from django import forms
from django.core.urlresolvers import reverse, NoReverseMatch
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from django.core.validators import URLValidator
from treenav.models import MenuItem
from mptt.forms import TreeNodeChoiceField, MPTTAdminForm
class MenuItemFormMixin(object):
def clean_link(self):
link = self.cleaned_data['link'] or ''
# It could be a fully-qualified URL -- try that first b/c reverse()
if any([link.startswith(s) for s in ('http:
URLValidator()(link)
elif link and not any([link.startswith(s) for s in ('^', '/')]):
# Not a regex or site-root-relative absolute path -- see if it's a
# named URL or view
try:
reverse(link)
except NoReverseMatch:
raise forms.ValidationError('Please supply a valid URL, URL '
'name, or regular expression.')
return self.cleaned_data['link']
def clean(self):
super(MenuItemFormMixin, self).clean()
content_type = self.cleaned_data['content_type']
object_id = self.cleaned_data['object_id']
if (content_type and not object_id) or (not content_type and object_id):
raise forms.ValidationError(
"Both 'Content type' and 'Object id' must be specified to use generic relationship"
)
if content_type and object_id:
try:
obj = content_type.<API key>(pk=object_id)
except ObjectDoesNotExist, e:
raise forms.ValidationError(str(e))
try:
obj.get_absolute_url()
except AttributeError, e:
raise forms.ValidationError(str(e))
if 'is_enabled' in self.cleaned_data and \
self.cleaned_data['is_enabled'] and \
'link' in self.cleaned_data and \
self.cleaned_data['link'].startswith('^'):
raise forms.ValidationError('Menu items with regular expression '
'URLs must be disabled.')
return self.cleaned_data
class MenuItemForm(MenuItemFormMixin, MPTTAdminForm):
class Meta:
model = MenuItem
exclude = ()
class MenuItemInlineForm(MenuItemFormMixin, forms.ModelForm):
class Meta:
model = MenuItem
exclude = ()
class <API key>(forms.ModelForm):
parent = TreeNodeChoiceField(
queryset=MenuItem.tree.all(),
required=False
)
class Meta:
model = MenuItem
fields = ('parent', 'label', 'slug', 'order', 'is_enabled') |
<?php
use yii\helpers\Html;
use yii\helpers\ArrayHelper;
use kartik\grid\GridView;
use yii\helpers\Url;
use yii\web\View;
$this->title = 'Bentuk Obats';
$this->params['breadcrumbs'][] = $this->title;
/*
* Tombol Create
* create
*/
function tombolCreate(){
$title1 = Yii::t('app', 'New Bentuk Obat');
$url = Url::toRoute(['/master/jenis-obat/create']);
$options1 = ['value'=>$url,
'id'=>'jenisobat-id-create',
'class'=>"btn btn-info btn-xs"
];
$icon1 = '<span class="fa fa-plus fa-lg"></span>';
$label1 = $icon1 . ' ' . $title1;
$content = Html::button($label1,$options1);
return $content;
}
function tombolRefresh(){
$title = Yii::t('app', 'Refresh');
$url = Url::toRoute(['/master/jenis-obat/']);
$options = ['id'=>'<API key>',
'data-pjax' => 0,
'class'=>"btn btn-info btn-xs",
];
$icon = '<span class="fa fa-history fa-lg"></span>';
$label = $icon . ' ' . $title;
return $content = Html::a($label,$url,$options);
}
/*
* Tombol View
*/
function tombolView($url, $model){
$title = Yii::t('app', 'View');
$icon = '<span class="fa fa-eye"></span>';
$label = $icon . ' ' . $title;
$url = Url::toRoute(['/master/jenis-obat/view','id'=>$model->id_jenis_obat]);
$options1 = ['value'=>$url,
'id'=>'view-jenis-obat-id',
'class'=>"btn btn-default btn-xs",
'style'=>['width'=>'170px', 'height'=>'25px','border'=> 'none','background-color'=>'white'],
];
$content = Html::button($label,$options1);
return $content;
}
/*
* Tombol Update
*/
function tombolUpdate($url, $model){
$title = Yii::t('app', 'Edit');
$icon = '<span class="fa fa-edit"></span>';
$label = $icon . ' ' . $title;
$url = Url::toRoute(['/master/jenis-obat/edit','id'=>$model->id_jenis_obat]);
$options1 = ['value'=>$url,
'id'=>'edit-jenis-obat-id',
'class'=>"btn btn-default btn-xs",
'style'=>['width'=>'170px', 'height'=>'25px','border'=>'none','background-color'=>'white'],
];
$content = Html::button($label,$options1);
return $content;
}
/*
* Tombol Delete
*/
function tombolDelete(){
$title = Yii::t('app', 'Delete');
$options = ['id'=>'<API key>',
'data-pjax' => 0,
'<API key>'=>'<API key>',
'class'=>"btn btn-danger btn-xs",
];
$icon = '<span class="fa fa-trash fa-lg"></span>';
$label = $icon . ' ' . $title;
return $content = Html::a($label,'#',$options);
}
/*
* GRID Jenis obat
* @author wawan [aditiya@lukison.com]
* @since 1.2
*/
$attDinamik =[];
$headColomnBT=[
['ID' =>0, 'ATTR' =>['FIELD'=>'jenis_obat','SIZE' => '30px','label'=>'Bentuk Obat','align'=>'left','warna'=>'73, 162, 182, 1','grp'=>false]],
['ID' =>1, 'ATTR' =>['FIELD'=>'description','SIZE' => '30px','label'=>'Description','align'=>'left','warna'=>'73, 162, 182, 1','grp'=>false]],
['ID' =>2, 'ATTR' =>['FIELD'=>'status','SIZE' => '30px','label'=>'Status','align'=>'left','warna'=>'73, 162, 182, 1','grp'=>false]],
];
$gvHeadColomnBT = ArrayHelper::map($headColomnBT, 'ID', 'ATTR');
$attDinamik[] =[
'class'=>'kartik\grid\SerialColumn',
//'contentOptions'=>['class'=>'kartik-sheet-style'],
'width'=>'10px',
'header'=>'No.',
'headerOptions'=>[
'style'=>[
'text-align'=>'center',
'width'=>'10px',
'font-family'=>'verdana, arial, sans-serif',
'font-size'=>'9pt',
'background-color'=>'rgba(73, 162, 182, 1)',
]
],
'contentOptions'=>[
'style'=>[
'text-align'=>'center',
'width'=>'10px',
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'9pt',
]
],
];
$attDinamik[] =[
'class'=>'kartik\grid\ExpandRowColumn',
'width'=>'50px',
'header'=>'Detail',
'value'=>function ($model, $key, $index, $column) {
return GridView::ROW_COLLAPSED;
},
'detail'=>function ($model, $key, $index, $column){
return Yii::$app->controller->renderPartial('<API key>',[
'model1'=>$model,
]);
},
'collapseTitle'=>'Close Exploler',
'expandTitle'=>'Click to views detail',
//'headerOptions'=>['class'=>'kartik-sheet-style'] ,
// 'allowBatchToggle'=>true,
'expandOneOnly'=>true,
// 'enableRowClick'=>true,
//'disabled'=>true,
'headerOptions'=>[
'style'=>[
'text-align'=>'center',
'width'=>'10px',
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'7pt',
'background-color'=>'rgba(73, 162, 182, 1)',
]
],
'contentOptions'=>[
'style'=>[
'text-align'=>'center',
'width'=>'10px',
'height'=>'10px',
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'7pt',
]
],
];
foreach($gvHeadColomnBT as $key =>$value[]){
if($value[$key]['FIELD'] == 'status')
{
$attDinamik[]=[
'attribute'=>$value[$key]['FIELD'],
'label'=>$value[$key]['label'],
'filterType'=>GridView::FILTER_SELECT2,
'filter' => $valStt,
'filterWidgetOptions'=>[
'pluginOptions'=>['allowClear'=>true],
],
'filterInputOptions'=>['placeholder'=>'Pilih'],
'format' => 'raw',
'value'=>function($model){
if ($model->status == 1) {
return Html::a('<i class="fa fa-check"></i> InActive', '',['class'=>'btn btn-success btn-xs', 'title'=>'InActive']);
} else if ($model->status == 0) {
return Html::a('<i class="fa fa-close"></i> Active', '',['class'=>'btn btn-danger btn-xs', 'title'=>'Active']);
}
},
'hAlign'=>'right',
'vAlign'=>'middle',
'noWrap'=>true,
'headerOptions'=>[
'style'=>[
'text-align'=>'center',
'width'=>$value[$key]['SIZE'],
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'8pt',
'background-color'=>'rgba('.$value[$key]['warna'].')',
]
],
'contentOptions'=>[
'style'=>[
'width'=>$value[$key]['SIZE'],
'text-align'=>$value[$key]['align'],
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'8pt',
]
],
];
}elseif($value[$key]['FIELD'] == 'description'){
$attDinamik[]=[
'class'=>'kartik\grid\EditableColumn',
'attribute'=>$value[$key]['FIELD'],
'label'=>$value[$key]['label'],
'filter'=>true,
'hAlign'=>'right',
'vAlign'=>'middle',
'noWrap'=>true,
//'group'=>$value[$key]['grp'],
'headerOptions'=>[
'style'=>[
'text-align'=>'center',
'width'=>$value[$key]['SIZE'],
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'8pt',
'background-color'=>'rgba('.$value[$key]['warna'].')',
]
],
'contentOptions'=>[
'style'=>[
'width'=>$value[$key]['SIZE'],
'text-align'=>$value[$key]['align'],
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'8pt',
]
],
'editableOptions' => [
'inputType' => \kartik\editable\Editable::INPUT_TEXTAREA ,
'size' => 'md',
],
];
}else{
# code...
$attDinamik[]=[
'class'=>'kartik\grid\EditableColumn',
'attribute'=>$value[$key]['FIELD'],
'label'=>$value[$key]['label'],
'filter'=>true,
'hAlign'=>'right',
'vAlign'=>'middle',
'noWrap'=>true,
//'group'=>$value[$key]['grp'],
'headerOptions'=>[
'style'=>[
'text-align'=>'center',
'width'=>$value[$key]['SIZE'],
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'8pt',
'background-color'=>'rgba('.$value[$key]['warna'].')',
]
],
'contentOptions'=>[
'style'=>[
'width'=>$value[$key]['SIZE'],
'text-align'=>$value[$key]['align'],
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'8pt',
]
],
];
}
};
/*GRIDVIEW ARRAY ACTION*/
$actionClass='btn btn-info btn-xs';
$actionLabel='Action';
$attDinamik[]=[
'class'=>'kartik\grid\ActionColumn',
'dropdown' => true,
'template' => '{view}{update}',
'dropdownOptions'=>['class'=>'pull-right dropup','style'=>['disable'=>true]],
'dropdownButton'=>['class'=>'btn btn-default btn-xs'],
'dropdownButton'=>[
'class' => $actionClass,
'label'=>$actionLabel,
'caret'=>'<span class="caret"></span>',
],
'buttons' => [
/* View PO | Permissian All */
'view' => function ($url, $model) {
return tombolView($url, $model);
},
'update' => function ($url, $model) {
return tombolUpdate($url, $model);
}
],
'headerOptions'=>[
'style'=>[
'text-align'=>'center',
'width'=>'10px',
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'9pt',
'background-color'=>'rgba(73, 162, 182, 1)',
]
],
'contentOptions'=>[
'style'=>[
'text-align'=>'center',
'width'=>'10px',
'height'=>'10px',
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'9pt',
]
],
];
$attDinamik[]=[
'class' => '\kartik\grid\CheckboxColumn',
'contentOptions'=>['class'=>'kartik-sheet-style'],
'width'=>'10px',
// 'header'=>'No.',
'headerOptions'=>[
'style'=>[
'text-align'=>'center',
'width'=>'10px',
'font-family'=>'verdana, arial, sans-serif',
'font-size'=>'9pt',
'background-color'=>'rgba(126, 189, 188, 0.9)',
]
],
'contentOptions'=>[
'style'=>[
'text-align'=>'center',
'width'=>'10px',
'font-family'=>'tahoma, arial, sans-serif',
'font-size'=>'8pt',
]
],
];
$gvjenis_obat=GridView::widget([
'id'=>'gv-jenis-obat-id',
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'filterRowOptions'=>['style'=>'background-color:rgba(97, 211, 96, 0.3); align:center'],
'columns' => $attDinamik,
'pjax'=>true,
'pjaxSettings'=>[
'options'=>[
'enablePushState'=>false,
'id'=>'gv-jenis-obat-id',
],
],
'panel' => [
'heading'=>false,
'type'=>'info',
'before'=> tombolCreate().' '.tombolRefresh(),
'showFooter'=>false,
],
/* 'export' =>['target' => GridView::TARGET_BLANK],
'exportConfig' => [
GridView::PDF => [ 'filename' => 'kategori'.'-'.date('ymdHis') ],
GridView::EXCEL => [ 'filename' => 'kategori'.'-'.date('ymdHis') ],
], */
'toolbar'=> ['content'=>tombolDelete()
],
'hover'=>true, //cursor select
'responsive'=>true,
'responsiveWrap'=>true,
'bordered'=>true,
'striped'=>true,
]);
?>
<div class="jenis-obat-index">
<?= $gvjenis_obat ?>
</div>
<?php
echo \Yii::$app->view->renderFile('@backend/master/views/jenis-obat/modal_jenis.php'); // view modal
$urls = [
'deleteurl' => Url::toRoute(['/master/jenis-obat/pilih-delete']),
];
$this->registerJs(
"var yiiOptions = ".\yii\helpers\Json::htmlEncode($urls).";",
View::POS_HEAD,
'yiiOptions'
);
$this->registerJs($this->render('all_jenis_obat.js'),View::POS_READY); |
<?php
use yii\widgets\Breadcrumbs;
use dmstr\widgets\Alert;
?>
<div class="content-wrapper">
<section class="content-header">
<?php if (isset($this->blocks['content-header'])) { ?>
<h1><?= $this->blocks['content-header'] ?></h1>
<?php } else { ?>
<h1>
<?php
if ($this->title !== null) {
echo \yii\helpers\Html::encode($this->title);
} else {
echo \yii\helpers\Inflector::camel2words(
\yii\helpers\Inflector::id2camel($this->context->module->id)
);
echo ($this->context->module->id !== \Yii::$app->id) ? '<small>Module</small>' : '';
} ?>
</h1>
<?php } ?>
<?=
Breadcrumbs::widget(
[
'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
]
) ?>
</section>
<section class="content">
<?= Alert::widget() ?>
<?= $content ?>
</section>
</div>
<footer class="main-footer">
<div class="pull-right hidden-xs">
<b>Version</b> 1.0
</div>
<strong>Copyright © 2016-<?= date('Y') ?> <?= Yii::$app->ServiceSupport->powered() ?>.</strong> All rights
reserved.
</footer>
<!-- Control Sidebar -->
<aside class="control-sidebar <API key>">
<!-- Create the tabs -->
<ul class="nav nav-tabs nav-justified <API key>">
<li><a href="#<API key>" data-toggle="tab"><i class="fa fa-home"></i></a></li>
<li><a href="#<API key>" data-toggle="tab"><i class="fa fa-gears"></i></a></li>
</ul>
<!-- Tab panes -->
<div class="tab-content">
<!-- Home tab content -->
<div class="tab-pane" id="<API key>">
<h3 class="<API key>">Recent Activity</h3>
<ul class='<API key>'>
<li>
<a href='javascript::;'>
<i class="menu-icon fa fa-birthday-cake bg-red"></i>
<div class="menu-info">
<h4 class="<API key>">Langdon's Birthday</h4>
<p>Will be 23 on April 24th</p>
</div>
</a>
</li>
<li>
<a href='javascript::;'>
<i class="menu-icon fa fa-user bg-yellow"></i>
<div class="menu-info">
<h4 class="<API key>">Frodo Updated His Profile</h4>
<p>New phone +1(800)555-1234</p>
</div>
</a>
</li>
<li>
<a href='javascript::;'>
<i class="menu-icon fa fa-envelope-o bg-light-blue"></i>
<div class="menu-info">
<h4 class="<API key>">Nora Joined Mailing List</h4>
<p>nora@example.com</p>
</div>
</a>
</li>
<li>
<a href='javascript::;'>
<i class="menu-icon fa fa-file-code-o bg-green"></i>
<div class="menu-info">
<h4 class="<API key>">Cron Job 254 Executed</h4>
<p>Execution time 5 seconds</p>
</div>
</a>
</li>
</ul>
<!-- /.<API key> -->
<h3 class="<API key>">Tasks Progress</h3>
<ul class='<API key>'>
<li>
<a href='javascript::;'>
<h4 class="<API key>">
Custom Template Design
<span class="label label-danger pull-right">70%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar progress-bar-danger" style="width: 70%"></div>
</div>
</a>
</li>
<li>
<a href='javascript::;'>
<h4 class="<API key>">
Update Resume
<span class="label label-success pull-right">95%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar <API key>" style="width: 95%"></div>
</div>
</a>
</li>
<li>
<a href='javascript::;'>
<h4 class="<API key>">
Laravel Integration
<span class="label label-waring pull-right">50%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar <API key>" style="width: 50%"></div>
</div>
</a>
</li>
<li>
<a href='javascript::;'>
<h4 class="<API key>">
Back End Framework
<span class="label label-primary pull-right">68%</span>
</h4>
<div class="progress progress-xxs">
<div class="progress-bar <API key>" style="width: 68%"></div>
</div>
</a>
</li>
</ul>
<!-- /.<API key> -->
</div>
<!-- /.tab-pane -->
<!-- Settings tab content -->
<div class="tab-pane" id="<API key>">
<form method="post">
<h3 class="<API key>">General Settings</h3>
<div class="form-group">
<label class="<API key>">
Report panel usage
<input type="checkbox" class="pull-right" checked/>
</label>
<p>
Some information about this general settings option
</p>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="<API key>">
Allow mail redirect
<input type="checkbox" class="pull-right" checked/>
</label>
<p>
Other sets of options are available
</p>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="<API key>">
Expose author name in posts
<input type="checkbox" class="pull-right" checked/>
</label>
<p>
Allow the user to show his name in blog posts
</p>
</div>
<!-- /.form-group -->
<h3 class="<API key>">Chat Settings</h3>
<div class="form-group">
<label class="<API key>">
Show me as online
<input type="checkbox" class="pull-right" checked/>
</label>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="<API key>">
Turn off notifications
<input type="checkbox" class="pull-right"/>
</label>
</div>
<!-- /.form-group -->
<div class="form-group">
<label class="<API key>">
Delete chat history
<a href="javascript::;" class="text-red pull-right"><i class="fa fa-trash-o"></i></a>
</label>
</div>
<!-- /.form-group -->
</form>
</div>
<!-- /.tab-pane -->
</div>
</aside><!-- /.control-sidebar -->
<!-- Add the sidebar's background. This div must be placed
immediately after the control sidebar
<div class='control-sidebar-bg'></div> |
<!doctype html>
<html>
<head>
<title>Error</title>
</head>
<body>
<h1>An Error Occurred</h1>
<pre>
{{.URL}}
</pre>
{{with .Error -}}
<p>
Error: {{.}}.
</p>
{{end}}
<p>
<a href="{{.Home}}">Home</a>
</p>
</body>
</html> |
<?php
use yii\easyii\helpers\Image;
use yii\easyii\models\Photo;
use yii\easyii\widgets\Fancybox;
use yii\helpers\Html;
use yii\helpers\Url;
use yii\easyii\assets\PhotosAsset;
PhotosAsset::register($this);
Fancybox::widget(['selector' => '.plugin-box']);
$class = get_class($this->context->model);
$item_id = $this->context->model->primaryKey;
$linkParams = [
'class' => $class,
'item_id' => $item_id,
];
$photoTemplate = '<tr data-id="{{photo_id}}">'.(IS_ROOT ? '<td>{{photo_id}}</td>' : '').'\
<td><a href="{{photo_image}}" class="plugin-box" title="{{photo_description}}" rel="easyii-photos"><img class="photo-thumb" id="photo-{{photo_id}}" src="{{photo_thumb}}"></a></td>\
<td>\
<textarea class="form-control photo-description">{{photo_description}}</textarea>\
<a href="' . Url::to(['/admin/photos/description/{{photo_id}}']) . '" class="btn btn-sm btn-primary disabled <API key>">'. Yii::t('easyii', 'Save') .'</a>\
</td>\
<td class="control vtop">\
<div class="btn-group btn-group-sm" role="group">\
<a href="' . Url::to(['/admin/photos/up/{{photo_id}}'] + $linkParams) . '" class="btn btn-default move-up" title="'. Yii::t('easyii', 'Move up') .'"><span class="glyphicon glyphicon-arrow-up"></span></a>\
<a href="' . Url::to(['/admin/photos/down/{{photo_id}}'] + $linkParams) . '" class="btn btn-default move-down" title="'. Yii::t('easyii', 'Move down') .'"><span class="glyphicon <API key>"></span></a>\
<a href="' . Url::to(['/admin/photos/image/{{photo_id}}'] + $linkParams) . '" class="btn btn-default change-image-button" title="'. Yii::t('easyii', 'Change image') .'"><span class="glyphicon <API key>"></span></a>\
<a href="' . Url::to(['/admin/photos/delete/{{photo_id}}']) . '" class="btn btn-default color-red delete-photo" title="'. Yii::t('easyii', 'Delete item') .'"><span class="glyphicon glyphicon-remove"></span></a>\
<input type="file" name="Photo[image]" class="change-image-input hidden">\
</div>\
</td>\
</tr>';
$this->registerJs("
var photoTemplate = '{$photoTemplate}';
", \yii\web\View::POS_HEAD);
$photoTemplate = str_replace('>\\', '>', $photoTemplate);
?>
<button id="photo-upload" class="btn btn-success text-uppercase"><span class="glyphicon glyphicon-arrow-up"></span> <?= Yii::t('easyii', 'Upload')?></button>
<small id="uploading-text" class="smooth"><?= Yii::t('easyii', 'Uploading. Please wait')?><span></span></small>
<table id="photo-table" class="table table-hover" style="display: <?= count($photos) ? 'table' : 'none' ?>;">
<thead>
<tr>
<?php if(IS_ROOT) : ?>
<th width="50">
<?php endif; ?>
<th width="150"><?= Yii::t('easyii', 'Image') ?></th>
<th><?= Yii::t('easyii', 'Description') ?></th>
<th width="150"></th>
</tr>
</thead>
<tbody>
<?php foreach($photos as $photo) : ?>
<?= str_replace(
['{{photo_id}}', '{{photo_thumb}}', '{{photo_image}}', '{{photo_description}}'],
[$photo->primaryKey, Image::thumb($photo->image, Photo::PHOTO_THUMB_WIDTH, Photo::PHOTO_THUMB_HEIGHT), $photo->image, $photo->description],
$photoTemplate)
?>
<?php endforeach; ?>
</tbody>
</table>
<p class="empty" style="display: <?= count($photos) ? 'none' : 'block' ?>;"><?= Yii::t('easyii', 'No photos uploaded yet') ?>.</p>
<?= Html::beginForm(Url::to(['/admin/photos/upload'] + $linkParams), 'post', ['enctype' => 'multipart/form-data']) ?>
<?= Html::fileInput('', null, [
'id' => 'photo-file',
'class' => 'hidden',
'multiple' => 'multiple',
])
?>
<?php Html::endForm() ?> |
#include "ui/aura/root_window.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/aura/event.h"
#include "ui/aura/test/aura_test_base.h"
#include "ui/aura/test/<API key>.h"
#include "ui/aura/test/test_windows.h"
#include "ui/base/hit_test.h"
#include "ui/gfx/point.h"
#include "ui/gfx/rect.h"
namespace aura {
namespace test {
namespace {
// A delegate that always returns a non-client component for hit tests.
class NonClientDelegate : public TestWindowDelegate {
public:
NonClientDelegate()
: non_client_count_(0),
mouse_event_count_(0),
mouse_event_flags_(0x0) {
}
virtual ~NonClientDelegate() {}
int non_client_count() const { return non_client_count_; }
gfx::Point non_client_location() const { return <API key>; }
int mouse_event_count() const { return mouse_event_count_; }
gfx::Point <API key>() const { return <API key>; }
int mouse_event_flags() const { return mouse_event_flags_; }
virtual int <API key>(const gfx::Point& location) const OVERRIDE {
NonClientDelegate* self = const_cast<NonClientDelegate*>(this);
self->non_client_count_++;
self-><API key> = location;
return HTTOPLEFT;
}
virtual bool OnMouseEvent(MouseEvent* event) OVERRIDE {
mouse_event_count_++;
<API key> = event->location();
mouse_event_flags_ = event->flags();
return true;
}
private:
int non_client_count_;
gfx::Point <API key>;
int mouse_event_count_;
gfx::Point <API key>;
int mouse_event_flags_;
};
} // namespace
typedef AuraTestBase RootWindowTest;
TEST_F(RootWindowTest, DispatchMouseEvent) {
// Create two non-overlapping windows so we don't have to worry about which
// is on top.
scoped_ptr<NonClientDelegate> delegate1(new NonClientDelegate());
scoped_ptr<NonClientDelegate> delegate2(new NonClientDelegate());
const int kWindowWidth = 123;
const int kWindowHeight = 45;
gfx::Rect bounds1(100, 200, kWindowWidth, kWindowHeight);
gfx::Rect bounds2(300, 400, kWindowWidth, kWindowHeight);
scoped_ptr<aura::Window> window1(<API key>(
delegate1.get(), -1234, bounds1, NULL));
scoped_ptr<aura::Window> window2(<API key>(
delegate2.get(), -5678, bounds2, NULL));
// Send a mouse event to window1.
gfx::Point point(101, 201);
MouseEvent event1(
ui::ET_MOUSE_PRESSED, point, point, ui::<API key>);
RootWindow::GetInstance()->DispatchMouseEvent(&event1);
// Event was tested for non-client area for the target window.
EXPECT_EQ(1, delegate1->non_client_count());
EXPECT_EQ(0, delegate2->non_client_count());
// The non-client component test was in local coordinates.
EXPECT_EQ(gfx::Point(1, 1), delegate1->non_client_location());
// Mouse event was received by target window.
EXPECT_EQ(1, delegate1->mouse_event_count());
EXPECT_EQ(0, delegate2->mouse_event_count());
// Event was in local coordinates.
EXPECT_EQ(gfx::Point(1, 1), delegate1-><API key>());
// Non-client flag was set.
EXPECT_TRUE(delegate1->mouse_event_flags() & ui::EF_IS_NON_CLIENT);
}
// Check that we correctly track the state of the mouse buttons in response to
// button press and release events.
TEST_F(RootWindowTest, MouseButtonState) {
RootWindow* root_window = RootWindow::GetInstance();
EXPECT_FALSE(root_window->IsMouseButtonDown());
gfx::Point location;
scoped_ptr<MouseEvent> event;
// Press the left button.
event.reset(new MouseEvent(
ui::ET_MOUSE_PRESSED,
location,
location,
ui::<API key>));
root_window->DispatchMouseEvent(event.get());
EXPECT_TRUE(root_window->IsMouseButtonDown());
// Additionally press the right.
event.reset(new MouseEvent(
ui::ET_MOUSE_PRESSED,
location,
location,
ui::<API key> | ui::<API key>));
root_window->DispatchMouseEvent(event.get());
EXPECT_TRUE(root_window->IsMouseButtonDown());
// Release the left button.
event.reset(new MouseEvent(
ui::ET_MOUSE_RELEASED,
location,
location,
ui::<API key>));
root_window->DispatchMouseEvent(event.get());
EXPECT_TRUE(root_window->IsMouseButtonDown());
// Release the right button. We should ignore the Shift-is-down flag.
event.reset(new MouseEvent(
ui::ET_MOUSE_RELEASED,
location,
location,
ui::EF_SHIFT_DOWN));
root_window->DispatchMouseEvent(event.get());
EXPECT_FALSE(root_window->IsMouseButtonDown());
// Press the middle button.
event.reset(new MouseEvent(
ui::ET_MOUSE_PRESSED,
location,
location,
ui::<API key>));
root_window->DispatchMouseEvent(event.get());
EXPECT_TRUE(root_window->IsMouseButtonDown());
}
TEST_F(RootWindowTest, TranslatedEvent) {
RootWindow* root_window = RootWindow::GetInstance();
scoped_ptr<Window> w1(<API key>(NULL, 1,
gfx::Rect(50, 50, 100, 100), NULL));
gfx::Point origin(100, 100);
MouseEvent root(ui::ET_MOUSE_PRESSED, origin, origin, 0);
EXPECT_EQ("100,100", root.location().ToString());
EXPECT_EQ("100,100", root.root_location().ToString());
MouseEvent translated_event(
root, root_window, w1.get(),
ui::ET_MOUSE_ENTERED, root.flags());
EXPECT_EQ("50,50", translated_event.location().ToString());
EXPECT_EQ("100,100", translated_event.root_location().ToString());
}
} // namespace test
} // namespace aura |
// modification, are permitted provided that the following conditions
// are met:
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the project nor the names of its contributors
// may be used to endorse or promote products derived from this software
// THIS SOFTWARE IS PROVIDED BY THE PROJECT 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 PROJECT 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 <Game/GameServer/Common/Constants.hpp>
#include <Language/Interface/RequestBuilder.hpp>
#include <Test/include/Client.hpp>
#include <Test/include/IntegrationTest.hpp>
class <API key>
: public IntegrationTest
{
protected:
<API key>()
{
mClient.send(mRequestBuilder.<API key>("Login", "Password"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World"));
mCommandReply = mClient.send(mRequestBuilder.buildGetLandRequest("Login", "Password", "Land"));
}
Client mClient;
Language::RequestBuilder mRequestBuilder;
Language::Command::Handle mCommandReply;
};
TEST_F(<API key>, ReturnsProperID)
{
ASSERT_EQ(Language::<API key>, mCommandReply->getID());
}
TEST_F(<API key>, ReturnsProperCode)
{
ASSERT_EQ(Game::<API key>, mCommandReply->getCode());
}
class ScenarioGetLand
: public IntegrationTest
{
protected:
ScenarioGetLand()
{
mClient.send(mRequestBuilder.<API key>("Login", "Password"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World"));
mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land"));
mCommandReply = mClient.send(mRequestBuilder.buildGetLandRequest("Login", "Password", "Land"));
}
Client mClient;
Language::RequestBuilder mRequestBuilder;
Language::Command::Handle mCommandReply;
};
TEST_F(ScenarioGetLand, ReturnsProperID)
{
ASSERT_EQ(Language::<API key>, mCommandReply->getID());
}
TEST_F(ScenarioGetLand, ReturnsProperCode)
{
ASSERT_EQ(Game::REPLY_STATUS_OK, mCommandReply->getCode());
}
TEST_F(ScenarioGetLand, <API key>)
{
ASSERT_STREQ(Game::<API key>.c_str(), mCommandReply->getMessage().c_str());
}
TEST_F(ScenarioGetLand, ReturnsOneObject)
{
ASSERT_EQ(1, mCommandReply->getObjects().size());
}
TEST_F(ScenarioGetLand, <API key>)
{
ASSERT_STREQ("Login", mCommandReply->getObjects().front().at("login").c_str());
}
TEST_F(ScenarioGetLand, <API key>)
{
ASSERT_STREQ("Land", mCommandReply->getObjects().front().at("land_name").c_str());
}
TEST_F(ScenarioGetLand, <API key>)
{
ASSERT_STREQ("World", mCommandReply->getObjects().front().at("world_name").c_str());
}
TEST_F(ScenarioGetLand, <API key>)
{
ASSERT_STREQ("false", mCommandReply->getObjects().front().at("granted").c_str());
}
class <API key>
: public IntegrationTest
{
protected:
<API key>()
{
mClient.send(mRequestBuilder.<API key>("Login", "Password"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World"));
mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land"));
mCommandReply = mClient.send(mRequestBuilder.buildGetLandRequest("Login", "BadPassword", "Land"));
}
Client mClient;
Language::RequestBuilder mRequestBuilder;
Language::Command::Handle mCommandReply;
};
TEST_F(<API key>, ReturnsProperID)
{
ASSERT_EQ(Language::<API key>, mCommandReply->getID());
}
TEST_F(<API key>, ReturnsProperCode)
{
ASSERT_EQ(Game::<API key>, mCommandReply->getCode());
}
class <API key>
: public IntegrationTest
{
protected:
<API key>()
{
mClient.send(mRequestBuilder.<API key>("Login1", "Password"));
mClient.send(mRequestBuilder.<API key>("Login2", "Password"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World"));
mClient.send(mRequestBuilder.<API key>("Login1", "Password", "World", "Land"));
mCommandReply = mClient.send(mRequestBuilder.buildGetLandRequest("Login2", "Password", "Land"));
}
Client mClient;
Language::RequestBuilder mRequestBuilder;
Language::Command::Handle mCommandReply;
};
TEST_F(<API key>, ReturnsProperID)
{
ASSERT_EQ(Language::<API key>, mCommandReply->getID());
}
TEST_F(<API key>, ReturnsProperCode)
{
ASSERT_EQ(Game::<API key>, mCommandReply->getCode());
}
class <API key>
: public IntegrationTest
{
protected:
<API key>()
{
mClient.send(mRequestBuilder.<API key>("Login", "Password"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World", "Epoch"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World"));
mClient.send(mRequestBuilder.<API key>("Login", "Password", "World", "Land"));
mClient.send(mRequestBuilder.<API key>("modbot", "modbotpass", "World"));
mCommandReply = mClient.send(mRequestBuilder.buildGetLandRequest("Login", "Password", "Land"));
}
Client mClient;
Language::RequestBuilder mRequestBuilder;
Language::Command::Handle mCommandReply;
};
TEST_F(<API key>, ReturnsProperID)
{
ASSERT_EQ(Language::<API key>, mCommandReply->getID());
}
TEST_F(<API key>, ReturnsProperCode)
{
ASSERT_EQ(Game::<API key>, mCommandReply->getCode());
} |
#define <API key>
#include "boost/test/unit_test.hpp"
#include "boost/random.hpp"
#include "boost/log/trivial.hpp"
#include "boost/log/utility/setup/file.hpp"
#include "boost/log/utility/setup/common_attributes.hpp"
#include "boost/log/sources/severity_logger.hpp"
#include "boost/noncopyable.hpp"
#include "libq/fixed_point.hpp"
#include <ctime>
#include <iomanip>
#include <fstream>
#include <sstream>
#include <stdexcept>
namespace libq {
namespace unit_tests {
namespace logging = boost::log;
namespace src = boost::log::sources;
namespace sinks = boost::log::sinks;
namespace keywords = boost::log::keywords;
class logger
: public src::severity_logger<logging::trivial::severity_level>
{
public:
logger(std::string const& _log_filename)
{
logging::add_file_log(
keywords::file_name = _log_filename,
keywords::format = "[%TimeStamp%]: %Message%"
);
logging::core::get()->set_filter(
logging::trivial::severity >= logging::trivial::info
);
logging::<API key>();
}
};
/*!
\brief gets the random uniform number that is within
the dynamic range of specified fixed-point format
*/
template<typename Q>
double <API key>(void)
{
static boost::mt19937 gen(std::size_t(std::time(0)));
static boost::uniform_01<boost::mt19937> uniform(gen);
double const low = static_cast<double>(std::numeric_limits<Q>::min());
double const high = static_cast<double>(std::numeric_limits<Q>::max());
return low + uniform() * (high - low);
}
\brief stringify the type
template<typename Q_type>
class Q_stringifier
{
public:
static std::string name()
{
static std::string type_label;
if (type_label.empty()) {
std::stringstream stream;
if (Q_type::is_signed) {
stream << "Q";
}
else {
stream << "UQ";
}
stream
<< Q_type::<API key> << "." << Q_type::bits_for_fractional;
if (Q_type::<API key> > 0) {
stream << "." << Q_type::<API key>;
}
type_label = stream.str();
}
return type_label;
}
};
/*!
\brief
*/
template<typename Q_type1, typename Q_type2, typename Operation, typename Error, std::size_t iterations = 1000u>
void <API key>(Operation _op, Error _limit, logger& _log)
{
for (std::size_t it = 0; it != iterations; ++it) {
double const u1 = <API key><Q_type1>();
double const u2 = <API key><Q_type2>();
if (Q_type2(u2).value() == 0) {
it
continue;
}
Q_type1 const a(u1);
Q_type2 const b(u2);
std::stringstream stream;
stream
<< Q_stringifier<Q_type1>::name() << "\t"
<< Q_stringifier<Q_type2>::name() << "\t"
<< std::setprecision(20)
<< u1 << "\t" << u2 << "\t";
try {
double const abs_diff = std::fabs(_op(a, b) - _op(u1, u2));
stream << abs_diff;
std::string const message = stream.str();
if (abs_diff > _limit(u1, u2, static_cast<double>(a), static_cast<double>(b))) {
BOOST_LOG_SEV(_log, logging::trivial::error) << "[Error]\t" << message;
BOOST_CHECK_MESSAGE(false, message);
}
else {
BOOST_LOG_SEV(_log, logging::trivial::info) << "[Info]\t" << message;
}
}
catch (std::exception const& _e) {
stream << _e.what();
std::string const message = stream.str();
BOOST_LOG_SEV(_log, logging::trivial::error) << "[Error]\t" << message;
BOOST_CHECK_MESSAGE(false, message);
}
}
}
template<typename Q_type1, typename Operation, typename Error, std::size_t iterations = 100u>
void <API key>(Operation _op, Error _limit, logger& _log)
{
return <API key><Q_type1, Q_type1>(_op, _limit, _log);
}
<API key>(Precision)
class plus_op
{
public:
template<typename T1, typename T2>
double operator()(T1 _x, T2 _y) const{ return static_cast<double>(_x + _y); }
};
<API key>(precision_of_plus)
{
/*
note, the summation max error can be determined as shown below:
(x + e_x) + (y + e_y) = (x + y) + (e_x + e_y)
note, error = error(x, y, a, b), where
* x, y are the referenced real numbers
* a = x + e_x, b = y + e_y are their approximations by fixed-point numbers (as real numbers)
*/
#define error(_precision, _prescale) [](double, double, double, double){ \
double const factor = 1u << std::abs(_prescale); \
return 2 * _precision * ((_prescale > 0) ? 1.0/factor : factor); \
}
using libq::Q;
using libq::UQ;
plus_op const op;
logger custom_log("plus.log");
<API key><UQ<23, 13, 3> >(op, error(1E-3, 3), custom_log); // floor(log(10,2^13-1))=3
<API key><Q<56, 34, -5> >(op, error(1E-10, -5), custom_log);
<API key><Q<61, 52, 3> >(op, error(1E-15, 3), custom_log);
<API key><UQ<53, 23, 7> >(op, error(1E-6, 7), custom_log);
}
/*
note, the subtraction max error is the same as the summation has
*/
class minus_op
{
public:
template<typename T1, typename T2>
double operator()(T1 _x, T2 _y) const{ return static_cast<double>(_x - _y); }
};
<API key>(precision_of_minus)
{
minus_op const op;
logger custom_log("minus.log");
using libq::Q;
using libq::UQ;
<API key><Q<28, 13, 5> >(op, error(1E-3, 5), custom_log);
<API key><Q<56, 34, -6> >(op, error(1E-10, -6), custom_log);
<API key><Q<61, 52, 23> >(op, error(1E-15, 23), custom_log);
<API key><Q<53, 23, 1> >(op, error(1E-6, 1), custom_log);
#undef error
}
class multiply_op
{
public:
template<typename T1, typename T2>
double operator()(T1 _x, T2 _y) const{ return static_cast<double>(_x * _y); }
};
<API key>(<API key>)
{
/*
note, the multiplication max error can be determined as shown below:
(x + e_x) * (y + e_y) = (x * y) + (|x| * e_y + |y| * e_x) + o(e_x, e_y)
*/
#define error(_precision1, _precision2) [](double _x, double _y, double _a, double _b) \
{ \
return (std::fabs(_x) * _precision1) + (std::fabs(_y) * _precision2); \
}
multiply_op const op;
logger custom_log("multiplication.log");
using libq::Q;
using libq::UQ;
<API key><UQ<18, 13>, UQ<20, 15> >(op, error(1E-3, 1E-4), custom_log);
<API key><Q<24, 23>, Q<30, 22> >(op, error(1E-6, 1E-6), custom_log);
<API key><Q<30, 29>, Q<33, 33> >(op, error(1E-8, 1E-9), custom_log);
<API key><UQ<18, 13>, UQ<18, 13> >(op, error(1E-3, 1E-3), custom_log);
<API key><UQ<20, 15>, UQ<20, 15> >(op, error(1E-4, 1E-4), custom_log);
<API key><Q<24, 23>, Q<24, 23> >(op, error(1E-6, 1E-6), custom_log);
<API key><Q<30, 22>, Q<30, 22> >(op, error(1E-6, 1E-6), custom_log);
<API key><Q<30, 29>, Q<30, 29> >(op, error(1E-8, 1E-8), custom_log);
#undef error
}
class division_op
{
public:
template<typename T1, typename T2>
double operator()(T1 _x, T2 _y) const{ return static_cast<double>(_x / _y); }
};
<API key>(<API key>)
{
/*
note, the division max error can be determined as shown below:
(x + e_x) / (y + e_y) = c = (x/y + e_x/y) / (1 + e_y/y)
c = x/y + (e_x + |c|*e_y)/|y|
*/
#define error(_precision1, _precision2) [](double _x, double _y, double _a, double _b) \
{ \
return (_precision1 + std::fabs(_a / _b) * _precision2) / std::fabs(_y); \
}
division_op const op;
logger custom_log("division.log");
using libq::Q;
using libq::UQ;
<API key><UQ<18, 13, 1>, UQ<20, 15, -3> >(op, error(1E-3, 1E-4), custom_log);
<API key><Q<24, 23, -20>, Q<30, 22, 4> >(op, error(1E-6, 1E-6), custom_log);
<API key><Q<29, 29>, Q<33, 33> >(op, error(1E-8, 1E-9), custom_log);
<API key><Q<52, 52, -2>, Q<5, 4, 4> >(op, error(1E-15, 1E-1), custom_log);
<API key><UQ<18, 13>, UQ<18, 13> >(op, error(1E-3, 1E-3), custom_log);
<API key><UQ<20, 15, 1>, UQ<20, 15> >(op, error(1E-4, 1E-4), custom_log);
<API key><Q<24, 23>, Q<24, 23, 2> >(op, error(1E-6, 1E-6), custom_log);
<API key><Q<30, 22>, Q<30, 22> >(op, error(1E-6, 1E-6), custom_log);
<API key><Q<30, 29, 5>, Q<30, 29> >(op, error(1E-8, 1E-8), custom_log);
#undef error
}
class log_op
{
public:
template<typename T1, typename T2>
double operator()(T1 _x, T2 _y) const{ return static_cast<double>(std::log(_x)); }
};
<API key>(precision_of_log)
{
#define error(_precision) [](double, double, double, double){ return _precision; }
log_op const op;
logger custom_log("log.log");
using libq::Q;
using libq::UQ;
<API key><UQ<23, 17> >(op, error(1E-4), custom_log); // floor(log(10, 2^f))-1
<API key><UQ<32, 16> >(op, error(1E-3), custom_log);
<API key><UQ<43, 20> >(op, error(1E-4), custom_log);
<API key><UQ<50, 13> >(op, error(1E-2), custom_log);
}
//<API key>(std_functions)
//#define ERROR(limit) [](double, double, double, double){ return limit; }
//#define LOG(a, b) std::log(a)
// <API key>(UQ(23, 17), LOG, ERROR(1E-2));
// <API key>(UQ(32, 16), LOG, ERROR(1E-3));
// <API key>(UQ(43, 20), LOG, ERROR(1E-2));
// <API key>(UQ(50, 13), LOG, ERROR(1E-2));
//#undef LOG
//#define SQRT(a, b) std::sqrt(a)
// <API key>(UQ(23, 17), SQRT, ERROR(1E-2));
// <API key>(UQ(32, 30), SQRT, ERROR(1E-2));
// <API key>(UQ(40, 20), SQRT, ERROR(1));
// <API key>(UQ(40, 40), SQRT, ERROR(1E-5));
//#undef SQRT
//#define SIN(a, b) std::sin(a)
// <API key>(Q(25, 21), SIN, ERROR(1E-4));
// <API key>(Q(44, 40), SIN, ERROR(1E-7));
// <API key>(Q(20, 16), SIN, ERROR(1E-3));
// <API key>(Q(63, 60), SIN, ERROR(1E-13));
//#undef SIN
//#define COS(a, b) std::cos(a)
// <API key>(Q(25, 21), COS, ERROR(1E-4));
// <API key>(Q(44, 40), COS, ERROR(1E-7));
// <API key>(Q(20, 16), COS, ERROR(1E-3));
// <API key>(Q(63, 60), COS, ERROR(1E-13));
//#undef COS
//#define TAN(a, b) std::tan(a)
// <API key>(Q(25, 21), TAN, ERROR(1E-4));
// <API key>(Q(44, 40), TAN, ERROR(1E-7));
// <API key>(Q(20, 16), TAN, ERROR(1E-3));
// <API key>(Q(63, 60), TAN, ERROR(1E-13));
//#undef TAN
//#define ASIN(a, b) std::asin(a)
// <API key>(Q(23, 21), ASIN, ERROR(1E-4));
// <API key>(Q(17, 16), ASIN, ERROR(1E-2));
// <API key>(Q(31, 30), ASIN, ERROR(1E-6));
// <API key>(Q(63, 60), ASIN, ERROR(1E-13));
//#undef ASIN
//#undef ERROR
/
/ PRECISION_TEST(t1, -0.999, 0.999, acos, 1E-4, "./acos_Q4_21.dat");
/ PRECISION_TEST(t2, -0.999, 0.999, acos, 1E-2, "./acos_Q4_16.dat");
/ PRECISION_TEST(t3, -0.999, 0.999, acos, 1E-6, "./acos_Q1_30.dat");
/
/ PRECISION_TEST(t1, -0.999, 0.999, atan, 1E-5, "./atan_Q4_21.dat");
/ PRECISION_TEST(t2, -0.999, 0.999, atan, 1E-3, "./atan_Q4_16.dat");
/ PRECISION_TEST(t3, -0.999, 0.999, atan, 1E-7, "./atan_Q1_30.dat");
/ }
/
/ <API key>(exp)
/ {
/ S(22,21,t1); PRECISION_TEST(t1, FMIN(t1), FMAX(t1), exp, 1E-4, "./exp_Q4_21.dat");
/ S(17,16,t2); PRECISION_TEST(t2, FMIN(t2), FMAX(t2), exp, 1E-3, "./exp_Q4_16.dat");
/ S(31,30,t3); PRECISION_TEST(t3, FMIN(t3), FMAX(t3), exp, 1E-7, "./exp_Q1_30.dat");
/ }
/
/ <API key>(sinh)
/ {
/ S(23,21,t1); PRECISION_TEST(t1, FMIN(t1), FMAX(t1), sinh, 1E-4, "./sinh_Q4_21.dat");
/ S(31,16,t2); PRECISION_TEST(t2, -3, 3u, sinh, 1E-3, "./sinh_Q15_16.dat");
/ S(31,30,t3); PRECISION_TEST(t3, FMIN(t3), FMAX(t3), sinh, 1E-7, "./sinh_Q3_60.dat");
/ }
/
/ <API key>(cosh)
/ {
/ S(23,21,t1); PRECISION_TEST(t1, FMIN(t1), FMAX(t1), cosh, 1E-4, "./cosh_Q4_21.dat");
/ S(31,16,t2); PRECISION_TEST(t2, -3, 3u, cosh, 1E-3, "./cosh_Q15_16.dat");
/ S(31,30,t3); PRECISION_TEST(t3, FMIN(t3), FMAX(t3), cosh, 1E-7, "./cosh_Q3_60.dat");
/ }
/
/ //<API key>(asinh)
/
/ // S(23,21,t1); PRECISION_TEST(t1, -2.0, 2.0, asinh, 1E-1, "./asinh_Q4_21.dat");
/ // S(31,16,t2); PRECISION_TEST(t2, -5.0, 5.0, asinh, 1E-1, "./asinh_Q15_16.dat");
/ // S(31,25,t3); PRECISION_TEST(t3, -7.0, 7.0, asinh, 1E-1, "./asinh_Q1_30.dat"); //!
/
/
/ //<API key>(acosh)
/
/ // S(23,21,t1); PRECISION_TEST(t1, 1.0, FMAX(t1), acosh, 1E-1, "./acosh_Q4_21.dat");
/ // S(31,16,t2);/* PRECISION_TEST(t2, 1.0, FMAX(t2), acosh, 1E-1, "./acosh_Q15_16.dat");*/
/ // std::acosh(t2(13333.7)); //!
/
/
/ //<API key>(atanh)
/
/ // S(23,21,t1); PRECISION_TEST(t1, -0.9999, 0.9999, atanh, 1E-1, "./atanh_Q4_21.dat");
/ // S(31,16,t2); PRECISION_TEST(t2, -0.9999, 0.9999, atanh, 1E-1, "./atanh_Q15_16.dat");
/
/
/ //<API key>(tanh)
/
/ // S(23,21,t1);/* PRECISION_TEST(t1, FMIN(t1), FMAX(t1), tanh, 1e-1, "./tanh_q4_21.dat");*/
/ // std::tanh(t1(-3.90405)); // !
/ // //S(31,16,t2); PRECISION_TEST(t2, FMIN(t2), FMAX(t2), tanh, 1e-1, "./tanh_q15_16.dat");
/
/
/#undef PRECISION_TEST
/
<API key>()
} // unit_tests
} // libq |
import { <API key>, ChangeDetectorRef, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Select, Store } from '@ngxs/store';
import { CDNLine, CDNStreamFilter, PipelineStatus } from 'app/model/pipeline.model';
import { Project } from 'app/model/project.model';
import { Stage } from 'app/model/stage.model';
import { WorkflowNodeJobRun, WorkflowNodeRun } from 'app/model/workflow.run.model';
import { WorkflowService } from 'app/service/workflow/workflow.service';
import { AutoUnsubscribe } from 'app/shared/decorator/autoUnsubscribe';
import { DurationService } from 'app/shared/duration/duration.service';
import { ProjectState } from 'app/store/project.state';
import { <API key> } from 'app/store/workflow.action';
import { WorkflowState, WorkflowStateModel } from 'app/store/workflow.state';
import cloneDeep from 'lodash-es/cloneDeep';
import { Observable, Subscription } from 'rxjs';
import { delay, retryWhen } from 'rxjs/operators';
import { webSocket, WebSocketSubject } from 'rxjs/webSocket';
import { ScrollTarget, <API key> } from './workflow-run-job/workflow-run-job.component';
@Component({
selector: '<API key>',
templateUrl: './pipeline.html',
styleUrls: ['./pipeline.scss'],
changeDetection: <API key>.OnPush
})
@AutoUnsubscribe()
export class <API key> implements OnInit, OnDestroy {
readonly initLoadLinesCount = 10;
@ViewChild('scrollContent') scrollContent: ElementRef;
@ViewChild('runjobComponent') runjobComponent: <API key>;
@Select(WorkflowState.getSelectedNodeRun()) nodeRun$: Observable<WorkflowNodeRun>;
nodeRunSubs: Subscription;
@Select(WorkflowState.<API key>()) nodeJobRun$: Observable<WorkflowNodeJobRun>;
nodeJobRunSubs: Subscription;
project: Project;
workflowName: string;
workflowRunNum: number;
// Pipeline data
stages: Array<Stage>;
jobTime: Map<number, string>;
mapJobStatus: Map<number, { status: string, warnings: number, start: string, done: string }>
= new Map<number, { status: string, warnings: number, start: string, done: string }>();
queryParamsSub: Subscription;
pipelineStatusEnum = PipelineStatus;
currentNodeRunID: number;
currentNodeRunNum: number;
currentNodeJobRun: WorkflowNodeJobRun;
<API key>: string;
durationIntervalID: number;
websocket: WebSocketSubject<any>;
<API key>: Subscription;
cdnFilter: CDNStreamFilter;
constructor(
private _route: ActivatedRoute,
private _router: Router,
private _cd: ChangeDetectorRef,
private _store: Store,
private _workflowService: WorkflowService
) {
this.project = this._store.selectSnapshot(ProjectState.projectSnapshot);
this.workflowName = (<WorkflowStateModel>this._store.selectSnapshot(WorkflowState)).workflowRun.workflow.name;
this.workflowRunNum = (<WorkflowStateModel>this._store.selectSnapshot(WorkflowState)).workflowRun.num;
}
ngOnInit() {
this.nodeJobRunSubs = this.nodeJobRun$.subscribe(rj => {
if (!rj && !this.currentNodeJobRun) {
this.<API key>();
return;
}
if (!rj) {
delete this.currentNodeJobRun;
this._cd.markForCheck();
return;
}
if (this.currentNodeJobRun && rj.id === this.currentNodeJobRun.id && this.currentNodeJobRun?.status === rj?.status) {
if (this.currentNodeJobRun?.job?.pipeline_action_id === rj.job.pipeline_action_id) {
const stepStatusChanged = rj.job.step_status?.length !== this.currentNodeJobRun.job.step_status?.length;
const addParameters = !this.currentNodeJobRun.parameters && rj.parameters;
if (!stepStatusChanged && !addParameters) {
return;
}
}
}
// Update step status data
this.currentNodeJobRun = cloneDeep(rj);
// Start websocket if job is not finished
if (!PipelineStatus.isDone(this.currentNodeJobRun.status)) {
this.<API key>().then(() => {});
}
this._cd.markForCheck();
});
this.nodeRunSubs = this.nodeRun$.subscribe(nr => {
if (!nr) {
return;
}
if (this.currentNodeRunID !== nr.id) {
this.currentNodeRunID = nr.id;
this.currentNodeRunNum = nr.num;
this.stages = nr.stages;
this.refreshNodeRun(nr);
this.deleteInterval();
this.updateTime();
this.durationIntervalID = window.setInterval(() => {
this.updateTime();
}, 5000);
this._cd.markForCheck();
} else {
if (this.refreshNodeRun(nr)) {
this._cd.markForCheck();
}
}
});
}
async <API key>() {
if (!this.currentNodeJobRun || !this.currentNodeJobRun.job.step_status) {
return;
}
if (!this.cdnFilter) {
this.cdnFilter = new CDNStreamFilter();
}
if (!this.websocket) {
const protocol = window.location.protocol.replace('http', 'ws');
const host = window.location.host;
const href = this._router['location']._baseHref;
this.websocket = webSocket({
url: `${protocol}//${host}${href}/cdscdn/item/stream`,
openObserver: {
next: value => {
if (value.type === 'open') {
this.cdnFilter.job_run_id = this.currentNodeJobRun.id;
this.websocket.next(this.cdnFilter);
}
}
}
});
this.<API key> = this.websocket
.pipe(retryWhen(errors => errors.pipe(delay(2000))))
.subscribe((l: CDNLine) => {
if (this.runjobComponent) {
this.runjobComponent.receiveLogs(l);
} else {
console.log('job component not loaded');
}
}, (err) => {
console.error('Error: ', err);
}, () => {
console.warn('Websocket Completed');
});
} else {
// Refresh cdn filter if job changed
if (this.cdnFilter.job_run_id !== this.currentNodeJobRun.id) {
this.cdnFilter.job_run_id = this.currentNodeJobRun.id;
this.websocket.next(this.cdnFilter);
}
}
}
selectedJobManual(jobID: number) {
if (!this.mapJobStatus.has(jobID)) {
return;
}
let queryParams = cloneDeep(this._route.snapshot.queryParams);
queryParams['stageId'] = null;
queryParams['actionId'] = null;
queryParams['stepOrder'] = null;
queryParams['line'] = null;
this._router.navigate(['.'], { relativeTo: this._route, queryParams, fragment: null });
this.selectJob(jobID);
}
selectJob(jobID: number): void {
if (jobID === this.currentNodeJobRun?.job?.pipeline_action_id) {
return;
}
this._store.dispatch(new <API key>({ jobID }));
}
refreshNodeRun(data: WorkflowNodeRun): boolean {
let refresh = false;
let currentNodeJobRun = (<WorkflowStateModel>this._store.selectSnapshot(WorkflowState)).workflowNodeJobRun;
if (this.<API key> !== data.status) {
this.<API key> = data.status;
refresh = true;
}
if (data.stages) {
data.stages.forEach((s, sIndex) => {
// Test Job status
if (s.run_jobs) {
s.run_jobs.forEach((rj, rjIndex) => {
let warnings = 0;
// compute warning
if (rj.job.step_status) {
rj.job.step_status.forEach(ss => {
if (ss.status === PipelineStatus.FAIL && rj.job.action.actions[ss.step_order] &&
rj.job.action.actions[ss.step_order].optional) {
warnings++;
}
});
}
// Update job status
let jobStatusItem = this.mapJobStatus.get(rj.job.pipeline_action_id);
if (!jobStatusItem || jobStatusItem.status !== rj.status) {
refresh = true;
this.mapJobStatus.set(rj.job.pipeline_action_id,
{ status: rj.status, warnings, start: rj.start, done: rj.done });
}
if (!currentNodeJobRun && sIndex === 0 && rjIndex === 0 && !this._route.snapshot.queryParams['actionId']) {
refresh = true;
this.selectJob(s.jobs[0].pipeline_action_id);
} else if (currentNodeJobRun &&
currentNodeJobRun.job.pipeline_action_id === this.currentNodeJobRun.job.pipeline_action_id) {
this.selectJob(this.currentNodeJobRun.job.pipeline_action_id);
} else if (this._route.snapshot.queryParams['actionId'] &&
this._route.snapshot.queryParams['actionId'] === rj.job.pipeline_action_id.toString()) {
this.selectJob(rj.job.pipeline_action_id);
}
});
}
});
}
return refresh;
}
/**
* Update job time
*/
updateTime(): void {
if (!this.mapJobStatus || this.mapJobStatus.size === 0) {
return;
}
if (!this.jobTime) {
this.jobTime = new Map<number, string>();
}
let stillRunning = false;
let refresh = false;
this.mapJobStatus.forEach((v, k) => {
switch (v.status) {
case this.pipelineStatusEnum.WAITING:
case this.pipelineStatusEnum.BUILDING:
refresh = true;
stillRunning = true;
this.jobTime.set(k,
DurationService.duration(new Date(v.start), new Date()));
break;
case this.pipelineStatusEnum.SUCCESS:
case this.pipelineStatusEnum.FAIL:
case this.pipelineStatusEnum.STOPPED:
let dd = DurationService.duration(new Date(v.start), new Date(v.done));
let item = this.jobTime.get(k);
if (!item || item !== dd) {
this.jobTime.set(k, dd);
}
refresh = true;
break;
}
});
if (!stillRunning) {
this.deleteInterval();
this._cd.markForCheck();
}
if (refresh) {
this._cd.markForCheck();
}
}
ngOnDestroy(): void {
this.deleteInterval();
this._store.dispatch(new <API key>({ jobID: 0 }));
this.<API key>();
}
deleteInterval(): void {
if (this.durationIntervalID) {
clearInterval(this.durationIntervalID);
this.durationIntervalID = 0;
}
}
onJobScroll(target: ScrollTarget): void {
this.scrollContent.nativeElement.scrollTop = target === ScrollTarget.TOP ? 0 : this.scrollContent.nativeElement.scrollHeight;
}
<API key>(): void {
if (this.<API key>) {
this.<API key>.unsubscribe();
}
}
} |
module Graphics.Vty.Widgets.Builder.SrcHelpers
( defAttr
, toAST
, call
, bind
, tBind
, noLoc
, act
, expr
, mkTyp
, parseType
, mkList
, parens
, mkName
, mkString
, mkInt
, mkChar
, mkTup
, opApp
, mkLet
, mkImportDecl
, nameStr
, attrsToExpr
)
where
import qualified Language.Haskell.Exts as Hs
defAttr :: Hs.Exp
defAttr = expr $ mkName "def_attr"
toAST :: (Show a) => a -> Hs.Exp
toAST thing = parsed
where
Hs.ParseOk parsed = Hs.parse $ show thing
call :: String -> [Hs.Exp] -> Hs.Exp
call func [] = Hs.Var $ Hs.UnQual $ mkName func
call func args =
mkApp (Hs.Var $ Hs.UnQual $ mkName func) args
where
mkApp app [] = app
mkApp app (arg:rest) = mkApp (Hs.App app arg) rest
bind :: Hs.Name -> String -> [Hs.Exp] -> Hs.Stmt
bind lval func args =
Hs.Generator noLoc (Hs.PVar lval) $ call func args
tBind :: [Hs.Name] -> String -> [Hs.Exp] -> Hs.Stmt
tBind lvals func args =
Hs.Generator noLoc (Hs.PTuple (map Hs.PVar lvals)) $ call func args
act :: Hs.Exp -> Hs.Stmt
act = Hs.Qualifier
expr :: Hs.Name -> Hs.Exp
expr = Hs.Var . Hs.UnQual
parens :: Hs.Exp -> Hs.Exp
parens = Hs.Paren
mkString :: String -> Hs.Exp
mkString = Hs.Lit . Hs.String
mkInt :: Int -> Hs.Exp
mkInt = Hs.Lit . Hs.Int . toEnum
mkChar :: Char -> Hs.Exp
mkChar = Hs.Lit . Hs.Char
mkTup :: [Hs.Exp] -> Hs.Exp
mkTup = Hs.Tuple
mkList :: [Hs.Exp] -> Hs.Exp
mkList = Hs.List
opApp :: Hs.Exp -> Hs.Name -> Hs.Exp -> Hs.Exp
opApp a op b = Hs.InfixApp a (Hs.QVarOp $ Hs.UnQual op) b
mkLet :: [(Hs.Name, Hs.Exp)] -> Hs.Stmt
mkLet pairs = Hs.LetStmt $ Hs.BDecls $ map mkDecl pairs
where
mkDecl (nam, e) = Hs.PatBind
noLoc
(Hs.PVar nam)
Nothing
(Hs.UnGuardedRhs e)
(Hs.BDecls [])
mkName :: String -> Hs.Name
mkName = Hs.Ident
mkImportDecl :: String -> [String] -> Hs.ImportDecl
mkImportDecl name hidden =
Hs.ImportDecl { Hs.importLoc = noLoc
, Hs.importModule = Hs.ModuleName name
, Hs.importQualified = False
, Hs.importSrc = False
, Hs.importPkg = Nothing
, Hs.importAs = Nothing
, Hs.importSpecs = case hidden of
[] -> Nothing
is -> Just (True, map (Hs.IVar . mkName) is)
}
parseType :: String -> Hs.Type
parseType s =
case Hs.parse s of
Hs.ParseOk val -> val
Hs.ParseFailed _ msg -> error $ "Error parsing type string '" ++ s ++ "': " ++ msg
attrsToExpr :: (Maybe String, Maybe String) -> Maybe Hs.Exp
attrsToExpr (Nothing, Nothing) = Nothing
attrsToExpr (Just fg, Nothing) = Just $ call "fgColor" [expr $ mkName fg]
attrsToExpr (Nothing, Just bg) = Just $ call "bgColor" [expr $ mkName bg]
attrsToExpr (Just fg, Just bg) = Just $ opApp
(expr $ mkName fg)
(mkName "on")
(expr $ mkName bg)
nameStr :: Hs.Name -> String
nameStr (Hs.Ident s) = s
nameStr n = error $ "Unsupported name: " ++ (show n)
noLoc :: Hs.SrcLoc
noLoc = Hs.SrcLoc { Hs.srcFilename = "-"
, Hs.srcLine = 0
, Hs.srcColumn = 0
}
mkTyp :: String -> [Hs.Type] -> Hs.Type
mkTyp tyCon [] = Hs.TyCon $ Hs.UnQual $ mkName tyCon
mkTyp tyCon args = mkApp (Hs.TyCon (Hs.UnQual (mkName tyCon))) args
where
mkApp ty [] = ty
mkApp ty (ty':tys) = mkApp (Hs.TyApp ty ty') tys |
window.addEventListener('WebComponentsReady', () => {
'use strict';
const app = Polymer.dom(document).querySelector('x-app');
const swCache = Polymer.dom(document).querySelector('platinum-sw-cache');
document.addEventListener('<API key>', () => {
// environment.
if (!swCache.disabled) {
app.showToast('Caching complete! This app will work offline.');
}
});
window.app = app;
}); |
// modification, are permitted provided that the following conditions are
// met:
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// 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 "v8.h"
#include "code-stubs.h"
#include "compilation-cache.h"
#include "deoptimizer.h"
#include "execution.h"
#include "gdb-jit.h"
#include "global-handles.h"
#include "heap-profiler.h"
#include "ic-inl.h"
#include "incremental-marking.h"
#include "liveobjectlist-inl.h"
#include "mark-compact.h"
#include "objects-visiting.h"
#include "<API key>.h"
#include "stub-cache.h"
namespace v8 {
namespace internal {
const char* Marking::kWhiteBitPattern = "00";
const char* Marking::kBlackBitPattern = "10";
const char* Marking::kGreyBitPattern = "11";
const char* Marking::<API key> = "01";
// <API key>
<API key>::<API key>() : // NOLINT
#ifdef DEBUG
state_(IDLE),
#endif
sweep_precisely_(false),
compacting_(false),
<API key>(false),
collect_maps_(FLAG_collect_maps),
<API key>(false),
tracer_(NULL),
<API key>(NULL),
heap_(NULL),
code_flusher_(NULL),
<API key>(NULL) { }
#ifdef DEBUG
class <API key>: public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
for (Object** current = start; current < end; current++) {
if ((*current)->IsHeapObject()) {
HeapObject* object = HeapObject::cast(*current);
ASSERT(HEAP-><API key>()->IsMarked(object));
}
}
}
};
static void VerifyMarking(Address bottom, Address top) {
<API key> visitor;
HeapObject* object;
Address <API key> = bottom;
for (Address current = bottom;
current < top;
current += kPointerSize) {
object = HeapObject::FromAddress(current);
if (<API key>::IsMarked(object)) {
ASSERT(current >= <API key>);
object->Iterate(&visitor);
<API key> = current + object->Size();
}
}
}
static void VerifyMarking(NewSpace* space) {
Address end = space->top();
<API key> it(space->bottom(), end);
// The bottom position is at the start of its page. Allows us to use
// page->area_start() as start of range on all pages.
ASSERT_EQ(space->bottom(),
NewSpacePage::FromAddress(space->bottom())->area_start());
while (it.has_next()) {
NewSpacePage* page = it.next();
Address limit = it.has_next() ? page->area_end() : end;
ASSERT(limit == end || !page->Contains(end));
VerifyMarking(page->area_start(), limit);
}
}
static void VerifyMarking(PagedSpace* space) {
PageIterator it(space);
while (it.has_next()) {
Page* p = it.next();
VerifyMarking(p->area_start(), p->area_end());
}
}
static void VerifyMarking(Heap* heap) {
VerifyMarking(heap->old_pointer_space());
VerifyMarking(heap->old_data_space());
VerifyMarking(heap->code_space());
VerifyMarking(heap->cell_space());
VerifyMarking(heap->map_space());
VerifyMarking(heap->new_space());
<API key> visitor;
LargeObjectIterator it(heap->lo_space());
for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
if (<API key>::IsMarked(obj)) {
obj->Iterate(&visitor);
}
}
heap->IterateStrongRoots(&visitor, VISIT_ONLY_STRONG);
}
class <API key>: public ObjectVisitor {
public:
void VisitPointers(Object** start, Object** end) {
for (Object** current = start; current < end; current++) {
if ((*current)->IsHeapObject()) {
HeapObject* object = HeapObject::cast(*current);
CHECK(!<API key>::<API key>(object));
}
}
}
};
static void VerifyEvacuation(Address bottom, Address top) {
<API key> visitor;
HeapObject* object;
Address <API key> = bottom;
for (Address current = bottom;
current < top;
current += kPointerSize) {
object = HeapObject::FromAddress(current);
if (<API key>::IsMarked(object)) {
ASSERT(current >= <API key>);
object->Iterate(&visitor);
<API key> = current + object->Size();
}
}
}
static void VerifyEvacuation(NewSpace* space) {
<API key> it(space->bottom(), space->top());
<API key> visitor;
while (it.has_next()) {
NewSpacePage* page = it.next();
Address current = page->area_start();
Address limit = it.has_next() ? page->area_end() : space->top();
ASSERT(limit == space->top() || !page->Contains(space->top()));
while (current < limit) {
HeapObject* object = HeapObject::FromAddress(current);
object->Iterate(&visitor);
current += object->Size();
}
}
}
static void VerifyEvacuation(PagedSpace* space) {
PageIterator it(space);
while (it.has_next()) {
Page* p = it.next();
if (p-><API key>()) continue;
VerifyEvacuation(p->area_start(), p->area_end());
}
}
static void VerifyEvacuation(Heap* heap) {
VerifyEvacuation(heap->old_pointer_space());
VerifyEvacuation(heap->old_data_space());
VerifyEvacuation(heap->code_space());
VerifyEvacuation(heap->cell_space());
VerifyEvacuation(heap->map_space());
VerifyEvacuation(heap->new_space());
<API key> visitor;
heap->IterateStrongRoots(&visitor, VISIT_ALL);
}
#endif
void <API key>::<API key>(Page* p) {
p-><API key>();
<API key>.Add(p);
}
static void TraceFragmentation(PagedSpace* space) {
int number_of_pages = space->CountTotalPages();
intptr_t reserved = (number_of_pages * space->AreaSize());
intptr_t free = reserved - space->SizeOfObjects();
PrintF("[%s]: %d pages, %d (%.1f%%) free\n",
AllocationSpaceName(space->identity()),
number_of_pages,
static_cast<int>(free),
static_cast<double>(free) * 100 / reserved);
}
bool <API key>::StartCompaction(CompactionMode mode) {
if (!compacting_) {
ASSERT(<API key>.length() == 0);
<API key>(heap()->old_pointer_space());
<API key>(heap()->old_data_space());
if (mode == <API key>) {
<API key>(heap()->code_space());
} else if (<API key>) {
TraceFragmentation(heap()->code_space());
}
if (<API key>) {
TraceFragmentation(heap()->map_space());
TraceFragmentation(heap()->cell_space());
}
heap()->old_pointer_space()-><API key>();
heap()->old_data_space()-><API key>();
heap()->code_space()-><API key>();
compacting_ = <API key>.length() > 0;
}
return compacting_;
}
void <API key>::CollectGarbage() {
// Make sure that Prepare() has been called. The individual steps below will
// update the state as they proceed.
ASSERT(state_ == PREPARE_GC);
ASSERT(<API key> == Smi::FromInt(0));
MarkLiveObjects();
ASSERT(heap_->incremental_marking()->IsStopped());
if (collect_maps_) <API key>();
ClearWeakMaps();
#ifdef DEBUG
if (FLAG_verify_heap) {
VerifyMarking(heap_);
}
#endif
SweepSpaces();
if (!collect_maps_) ReattachInitialMaps();
heap_->isolate()-><API key>()->Flush();
Finish();
tracer_ = NULL;
}
#ifdef DEBUG
void <API key>::<API key>(PagedSpace* space) {
PageIterator it(space);
while (it.has_next()) {
Page* p = it.next();
CHECK(p->markbits()->IsClean());
CHECK_EQ(0, p->LiveBytes());
}
}
void <API key>::<API key>(NewSpace* space) {
<API key> it(space->bottom(), space->top());
while (it.has_next()) {
NewSpacePage* p = it.next();
CHECK(p->markbits()->IsClean());
CHECK_EQ(0, p->LiveBytes());
}
}
void <API key>::<API key>() {
<API key>(heap_->old_pointer_space());
<API key>(heap_->old_data_space());
<API key>(heap_->code_space());
<API key>(heap_->cell_space());
<API key>(heap_->map_space());
<API key>(heap_->new_space());
LargeObjectIterator it(heap_->lo_space());
for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
MarkBit mark_bit = Marking::MarkBitFrom(obj);
ASSERT(Marking::IsWhite(mark_bit));
}
}
#endif
static void <API key>(PagedSpace* space) {
PageIterator it(space);
while (it.has_next()) {
Bitmap::Clear(it.next());
}
}
static void <API key>(NewSpace* space) {
<API key> it(space->ToSpaceStart(), space->ToSpaceEnd());
while (it.has_next()) {
Bitmap::Clear(it.next());
}
}
void <API key>::ClearMarkbits() {
<API key>(heap_->code_space());
<API key>(heap_->map_space());
<API key>(heap_->old_pointer_space());
<API key>(heap_->old_data_space());
<API key>(heap_->cell_space());
<API key>(heap_->new_space());
LargeObjectIterator it(heap_->lo_space());
for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
MarkBit mark_bit = Marking::MarkBitFrom(obj);
mark_bit.Clear();
mark_bit.Next().Clear();
}
}
bool Marking::TransferMark(Address old_start, Address new_start) {
// This is only used when resizing an object.
ASSERT(MemoryChunk::FromAddress(old_start) ==
MemoryChunk::FromAddress(new_start));
// If the mark doesn't move, we don't check the color of the object.
// It doesn't matter whether the object is black, since it hasn't changed
// size, so the adjustment to the live data count will be zero anyway.
if (old_start == new_start) return false;
MarkBit new_mark_bit = MarkBitFrom(new_start);
MarkBit old_mark_bit = MarkBitFrom(old_start);
#ifdef DEBUG
ObjectColor old_color = Color(old_mark_bit);
#endif
if (Marking::IsBlack(old_mark_bit)) {
old_mark_bit.Clear();
ASSERT(IsWhite(old_mark_bit));
Marking::MarkBlack(new_mark_bit);
return true;
} else if (Marking::IsGrey(old_mark_bit)) {
ASSERT(heap_->incremental_marking()->IsMarking());
old_mark_bit.Clear();
old_mark_bit.Next().Clear();
ASSERT(IsWhite(old_mark_bit));
heap_->incremental_marking()->WhiteToGreyAndPush(
HeapObject::FromAddress(new_start), new_mark_bit);
heap_->incremental_marking()->RestartIfNotMarking();
}
#ifdef DEBUG
ObjectColor new_color = Color(new_mark_bit);
ASSERT(new_color == old_color);
#endif
return false;
}
const char* AllocationSpaceName(AllocationSpace space) {
switch (space) {
case NEW_SPACE: return "NEW_SPACE";
case OLD_POINTER_SPACE: return "OLD_POINTER_SPACE";
case OLD_DATA_SPACE: return "OLD_DATA_SPACE";
case CODE_SPACE: return "CODE_SPACE";
case MAP_SPACE: return "MAP_SPACE";
case CELL_SPACE: return "CELL_SPACE";
case LO_SPACE: return "LO_SPACE";
default:
UNREACHABLE();
}
return NULL;
}
// Returns zero for pages that have so little fragmentation that it is not
// worth defragmenting them. Otherwise a positive integer that gives an
// estimate of fragmentation on an arbitrary scale.
static int <API key>(PagedSpace* space, Page* p) {
// If page was not swept then there are no free list items on it.
if (!p->WasSwept()) {
if (<API key>) {
PrintF("%p [%s]: %d bytes live (unswept)\n",
reinterpret_cast<void*>(p),
AllocationSpaceName(space->identity()),
p->LiveBytes());
}
return 0;
}
FreeList::SizeStats sizes;
space->CountFreeListItems(p, &sizes);
intptr_t ratio;
intptr_t ratio_threshold;
int area_size = space->AreaSize();
if (space->identity() == CODE_SPACE) {
ratio = (sizes.medium_size_ * 10 + sizes.large_size_ * 2) * 100 /
area_size;
ratio_threshold = 10;
} else {
ratio = (sizes.small_size_ * 5 + sizes.medium_size_) * 100 /
area_size;
ratio_threshold = 15;
}
if (<API key>) {
PrintF("%p [%s]: %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %d (%.2f%%) %s\n",
reinterpret_cast<void*>(p),
AllocationSpaceName(space->identity()),
static_cast<int>(sizes.small_size_),
static_cast<double>(sizes.small_size_ * 100) /
area_size,
static_cast<int>(sizes.medium_size_),
static_cast<double>(sizes.medium_size_ * 100) /
area_size,
static_cast<int>(sizes.large_size_),
static_cast<double>(sizes.large_size_ * 100) /
area_size,
static_cast<int>(sizes.huge_size_),
static_cast<double>(sizes.huge_size_ * 100) /
area_size,
(ratio > ratio_threshold) ? "[fragmented]" : "");
}
if (FLAG_always_compact && sizes.Total() != area_size) {
return 1;
}
if (ratio <= ratio_threshold) return 0; // Not fragmented.
return static_cast<int>(ratio - ratio_threshold);
}
void <API key>::<API key>(PagedSpace* space) {
ASSERT(space->identity() == OLD_POINTER_SPACE ||
space->identity() == OLD_DATA_SPACE ||
space->identity() == CODE_SPACE);
int number_of_pages = space->CountTotalPages();
const int <API key> = 1000;
int <API key> = Min(
<API key>,
static_cast<int>(sqrt(static_cast<double>(number_of_pages / 2)) + 1));
if (<API key> || FLAG_always_compact) {
<API key> = <API key>;
}
class Candidate {
public:
Candidate() : fragmentation_(0), page_(NULL) { }
Candidate(int f, Page* p) : fragmentation_(f), page_(p) { }
int fragmentation() { return fragmentation_; }
Page* page() { return page_; }
private:
int fragmentation_;
Page* page_;
};
enum CompactionMode {
COMPACT_FREE_LISTS,
<API key>
};
CompactionMode mode = COMPACT_FREE_LISTS;
intptr_t reserved = number_of_pages * space->AreaSize();
intptr_t over_reserved = reserved - space->SizeOfObjects();
static const intptr_t kFreenessThreshold = 50;
if (over_reserved >= 2 * space->AreaSize() &&
<API key>) {
mode = <API key>;
// We expect that empty pages are easier to compact so slightly bump the
// limit.
<API key> += 2;
if (<API key>) {
PrintF("Estimated over reserved memory: %.1f MB (setting threshold %d)\n",
static_cast<double>(over_reserved) / MB,
static_cast<int>(kFreenessThreshold));
}
}
intptr_t estimated_release = 0;
Candidate candidates[<API key>];
int count = 0;
int fragmentation = 0;
Candidate* least = NULL;
PageIterator it(space);
if (it.has_next()) it.next(); // Never compact the first page.
while (it.has_next()) {
Page* p = it.next();
p-><API key>();
if (<API key>) {
int counter = space->heap()->ms_count();
uintptr_t page_number = reinterpret_cast<uintptr_t>(p) >> kPageSizeBits;
if ((counter & 1) == (page_number & 1)) fragmentation = 1;
} else if (mode == <API key>) {
// Don't try to release too many pages.
if (estimated_release >= ((over_reserved * 3) / 4)) {
continue;
}
intptr_t free_bytes = 0;
if (!p->WasSwept()) {
free_bytes = (p->size() - p->LiveBytes());
} else {
FreeList::SizeStats sizes;
space->CountFreeListItems(p, &sizes);
free_bytes = sizes.Total();
}
int free_pct = static_cast<int>(free_bytes * 100 / p->area_size());
if (free_pct >= kFreenessThreshold) {
estimated_release += p->area_size() +
(p->area_size() - free_bytes);
fragmentation = free_pct;
} else {
fragmentation = 0;
}
if (<API key>) {
PrintF("%p [%s]: %d (%.2f%%) free %s\n",
reinterpret_cast<void*>(p),
AllocationSpaceName(space->identity()),
static_cast<int>(free_bytes),
static_cast<double>(free_bytes * 100) / p->area_size(),
(fragmentation > 0) ? "[fragmented]" : "");
}
} else {
fragmentation = <API key>(space, p);
}
if (fragmentation != 0) {
if (count < <API key>) {
candidates[count++] = Candidate(fragmentation, p);
} else {
if (least == NULL) {
for (int i = 0; i < <API key>; i++) {
if (least == NULL ||
candidates[i].fragmentation() < least->fragmentation()) {
least = candidates + i;
}
}
}
if (least->fragmentation() < fragmentation) {
*least = Candidate(fragmentation, p);
least = NULL;
}
}
}
}
for (int i = 0; i < count; i++) {
<API key>(candidates[i].page());
}
if (count > 0 && <API key>) {
PrintF("Collected %d evacuation candidates for space %s\n",
count,
AllocationSpaceName(space->identity()));
}
}
void <API key>::AbortCompaction() {
if (compacting_) {
int npages = <API key>.length();
for (int i = 0; i < npages; i++) {
Page* p = <API key>[i];
<API key>.DeallocateChain(p-><API key>());
p-><API key>();
p->ClearFlag(MemoryChunk::<API key>);
}
compacting_ = false;
<API key>.Rewind(0);
invalidated_code_.Rewind(0);
}
ASSERT_EQ(0, <API key>.length());
}
void <API key>::Prepare(GCTracer* tracer) {
<API key> = heap()->incremental_marking()->IsMarking();
// Disable collection of maps if incremental marking is enabled.
// Map collection algorithm relies on a special map transition tree traversal
// order which is not implemented for incremental marking.
collect_maps_ = FLAG_collect_maps && !<API key>;
// Monomorphic ICs are preserved when possible, but need to be flushed
// when they might be keeping a Context alive, or when the heap is about
// to be serialized.
<API key> =
heap()->isolate()-><API key>() || Serializer::enabled();
// Rather than passing the tracer around we stash it in a static member
// variable.
tracer_ = tracer;
#ifdef DEBUG
ASSERT(state_ == IDLE);
state_ = PREPARE_GC;
#endif
ASSERT(!FLAG_never_compact || !FLAG_always_compact);
if (collect_maps_) CreateBackPointers();
#ifdef <API key>
if (FLAG_gdbjit) {
// If GDBJIT interface is active disable compaction.
<API key> = false;
}
#endif
// Clear marking bits for precise sweeping to collect all garbage.
if (<API key> && <API key>()) {
heap()->incremental_marking()->Abort();
ClearMarkbits();
AbortCompaction();
<API key> = false;
}
// Don't start compaction if we are in the middle of incremental
// marking cycle. We did not collect any slots.
if (!FLAG_never_compact && !<API key>) {
StartCompaction(<API key>);
}
PagedSpaces spaces;
for (PagedSpace* space = spaces.next();
space != NULL;
space = spaces.next()) {
space-><API key>();
}
#ifdef DEBUG
if (!<API key> && FLAG_verify_heap) {
<API key>();
}
#endif
}
void <API key>::Finish() {
#ifdef DEBUG
ASSERT(state_ == SWEEP_SPACES || state_ == RELOCATE_OBJECTS);
state_ = IDLE;
#endif
// The stub cache is not traversed during GC; clear the cache to
// force lazy re-initialization of it. This must be done after the
// GC, because it relies on the new address of certain old space
heap()->isolate()->stub_cache()->Clear();
heap()-><API key>.CleanUp();
}
// Phase 1: tracing and marking live objects.
// before: all objects are in normal state.
// after: a live object's map pointer is marked as '00'.
// Marking all live objects in the heap as part of mark-sweep or mark-compact
// collection. Before marking, all objects are in their normal state. After
// marking, live objects' map pointers are marked indicating that the object
// has been found reachable.
// The marking algorithm is a (mostly) depth-first (because of possible stack
// overflow) traversal of the graph of objects reachable from the roots. It
// uses an explicit stack of pointers rather than recursion. The young
// generation's inactive ('from') space is used as a marking stack. The
// objects in the marking stack are the ones that have been reached and marked
// but their children have not yet been visited.
// The marking stack can overflow during traversal. In that case, we set an
// overflow flag. When the overflow flag is set, we continue marking objects
// reachable from the objects on the marking stack, but no longer push them on
// the marking stack. Instead, we mark them as both marked and overflowed.
// When the stack is in the overflowed state, objects marked as overflowed
// have been reached and marked but their children have not been visited yet.
// After emptying the marking stack, we clear the overflow flag and traverse
// the heap looking for objects marked as overflowed, push them on the stack,
// and continue with marking. This process repeats until all reachable
// objects have been marked.
class CodeFlusher {
public:
explicit CodeFlusher(Isolate* isolate)
: isolate_(isolate),
<API key>(NULL),
<API key>(NULL) {}
void AddCandidate(SharedFunctionInfo* shared_info) {
SetNextCandidate(shared_info, <API key>);
<API key> = shared_info;
}
void AddCandidate(JSFunction* function) {
ASSERT(function->code() == function->shared()->code());
SetNextCandidate(function, <API key>);
<API key> = function;
}
void ProcessCandidates() {
<API key>();
<API key>();
}
private:
void <API key>() {
Code* lazy_compile = isolate_->builtins()->builtin(Builtins::kLazyCompile);
JSFunction* candidate = <API key>;
JSFunction* next_candidate;
while (candidate != NULL) {
next_candidate = GetNextCandidate(candidate);
SharedFunctionInfo* shared = candidate->shared();
Code* code = shared->code();
MarkBit code_mark = Marking::MarkBitFrom(code);
if (!code_mark.Get()) {
shared->set_code(lazy_compile);
candidate->set_code(lazy_compile);
} else {
candidate->set_code(shared->code());
}
// We are in the middle of a GC cycle so the write barrier in the code
// setter did not record the slot update and we have to do that manually.
Address slot = candidate->address() + JSFunction::kCodeEntryOffset;
Code* target = Code::cast(Code::<API key>(slot));
isolate_->heap()-><API key>()->
RecordCodeEntrySlot(slot, target);
<API key>(shared);
candidate = next_candidate;
}
<API key> = NULL;
}
void <API key>() {
Code* lazy_compile = isolate_->builtins()->builtin(Builtins::kLazyCompile);
SharedFunctionInfo* candidate = <API key>;
SharedFunctionInfo* next_candidate;
while (candidate != NULL) {
next_candidate = GetNextCandidate(candidate);
SetNextCandidate(candidate, NULL);
Code* code = candidate->code();
MarkBit code_mark = Marking::MarkBitFrom(code);
if (!code_mark.Get()) {
candidate->set_code(lazy_compile);
}
<API key>(candidate);
candidate = next_candidate;
}
<API key> = NULL;
}
void <API key>(SharedFunctionInfo* shared) {
Object** slot = HeapObject::RawField(shared,
SharedFunctionInfo::kCodeOffset);
isolate_->heap()-><API key>()->
RecordSlot(slot, slot, HeapObject::cast(*slot));
}
static JSFunction** <API key>(JSFunction* candidate) {
return reinterpret_cast<JSFunction**>(
candidate->address() + JSFunction::kCodeEntryOffset);
}
static JSFunction* GetNextCandidate(JSFunction* candidate) {
return *<API key>(candidate);
}
static void SetNextCandidate(JSFunction* candidate,
JSFunction* next_candidate) {
*<API key>(candidate) = next_candidate;
}
static SharedFunctionInfo** <API key>(
SharedFunctionInfo* candidate) {
Code* code = candidate->code();
return reinterpret_cast<SharedFunctionInfo**>(
code->address() + Code::kGCMetadataOffset);
}
static SharedFunctionInfo* GetNextCandidate(SharedFunctionInfo* candidate) {
return reinterpret_cast<SharedFunctionInfo*>(
candidate->code()->gc_metadata());
}
static void SetNextCandidate(SharedFunctionInfo* candidate,
SharedFunctionInfo* next_candidate) {
candidate->code()->set_gc_metadata(next_candidate);
}
Isolate* isolate_;
JSFunction* <API key>;
SharedFunctionInfo* <API key>;
<API key>(CodeFlusher);
};
<API key>::~<API key>() {
if (code_flusher_ != NULL) {
delete code_flusher_;
code_flusher_ = NULL;
}
}
static inline HeapObject* <API key>(Object** p) {
// Optimization: If the heap object pointed to by p is a non-symbol
// cons string whose right substring is HEAP->empty_string, update
// it in place to its left substring. Return the updated value.
// Here we assume that if we change *p, we replace it with a heap object
// (i.e., the left substring of a cons string is always a heap object).
// The check performed is:
// object->IsConsString() && !object->IsSymbol() &&
// (ConsString::cast(object)->second() == HEAP->empty_string())
// except the maps for the object and its possible substrings might be
// marked.
HeapObject* object = HeapObject::cast(*p);
if (!<API key>) return object;
Map* map = object->map();
InstanceType type = map->instance_type();
if ((type & kShortcutTypeMask) != kShortcutTypeTag) return object;
Object* second = reinterpret_cast<ConsString*>(object)->unchecked_second();
Heap* heap = map->GetHeap();
if (second != heap->empty_string()) {
return object;
}
// Since we don't have the object's start, it is impossible to update the
// page dirty marks. Therefore, we only replace the string with its left
// substring when page dirty marks do not change.
Object* first = reinterpret_cast<ConsString*>(object)->unchecked_first();
if (!heap->InNewSpace(object) && heap->InNewSpace(first)) return object;
*p = first;
return HeapObject::cast(first);
}
class <API key> : public StaticVisitorBase {
public:
static inline void IterateBody(Map* map, HeapObject* obj) {
table_.GetVisitor(map)(map, obj);
}
static void Initialize() {
table_.Register(<API key>,
&FixedBodyVisitor<<API key>,
ConsString::BodyDescriptor,
void>::Visit);
table_.Register(kVisitConsString,
&FixedBodyVisitor<<API key>,
ConsString::BodyDescriptor,
void>::Visit);
table_.Register(kVisitSlicedString,
&FixedBodyVisitor<<API key>,
SlicedString::BodyDescriptor,
void>::Visit);
table_.Register(kVisitFixedArray,
&FlexibleBodyVisitor<<API key>,
FixedArray::BodyDescriptor,
void>::Visit);
table_.Register(kVisitGlobalContext, &VisitGlobalContext);
table_.Register(<API key>, DataObjectVisitor::Visit);
table_.Register(kVisitByteArray, &DataObjectVisitor::Visit);
table_.Register(kVisitFreeSpace, &DataObjectVisitor::Visit);
table_.Register(<API key>, &DataObjectVisitor::Visit);
table_.Register(<API key>, &DataObjectVisitor::Visit);
table_.Register(kVisitJSWeakMap, &VisitJSWeakMap);
table_.Register(kVisitOddball,
&FixedBodyVisitor<<API key>,
Oddball::BodyDescriptor,
void>::Visit);
table_.Register(kVisitMap,
&FixedBodyVisitor<<API key>,
Map::BodyDescriptor,
void>::Visit);
table_.Register(kVisitCode, &VisitCode);
table_.Register(<API key>,
&<API key>);
table_.Register(kVisitJSFunction,
&<API key>);
table_.Register(kVisitJSRegExp,
&<API key>);
table_.Register(kVisitPropertyCell,
&FixedBodyVisitor<<API key>,
<API key>::BodyDescriptor,
void>::Visit);
table_.<API key><DataObjectVisitor,
kVisitDataObject,
<API key>>();
table_.<API key><JSObjectVisitor,
kVisitJSObject,
<API key>>();
table_.<API key><StructObjectVisitor,
kVisitStruct,
kVisitStructGeneric>();
}
INLINE(static void VisitPointer(Heap* heap, Object** p)) {
MarkObjectByPointer(heap-><API key>(), p, p);
}
INLINE(static void VisitPointers(Heap* heap, Object** start, Object** end)) {
// Mark all objects pointed to in [start, end).
const int <API key> = 64;
if (end - start >= <API key>) {
if (<API key>(heap, start, end)) return;
// We are close to a stack overflow, so just mark the objects.
}
<API key>* collector = heap-><API key>();
for (Object** p = start; p < end; p++) {
MarkObjectByPointer(collector, start, p);
}
}
static void <API key>(Heap* heap, RelocInfo* rinfo) {
ASSERT(rinfo->rmode() == RelocInfo::<API key>);
<API key>* cell =
<API key>::cast(rinfo->target_cell());
MarkBit mark = Marking::MarkBitFrom(cell);
heap-><API key>()->MarkObject(cell, mark);
}
static inline void <API key>(Heap* heap, RelocInfo* rinfo) {
ASSERT(rinfo->rmode() == RelocInfo::EMBEDDED_OBJECT);
// TODO(mstarzinger): We do not short-circuit cons strings here, verify
// that there can be no such embedded pointers and add assertion here.
HeapObject* object = HeapObject::cast(rinfo->target_object());
heap-><API key>()->RecordRelocSlot(rinfo, object);
MarkBit mark = Marking::MarkBitFrom(object);
heap-><API key>()->MarkObject(object, mark);
}
static inline void VisitCodeTarget(Heap* heap, RelocInfo* rinfo) {
ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
Code* target = Code::<API key>(rinfo->target_address());
if (<API key> && target-><API key>()
&& (target->ic_state() == MEGAMORPHIC ||
heap-><API key>()-><API key>)) {
IC::Clear(rinfo->pc());
target = Code::<API key>(rinfo->target_address());
} else {
if (<API key> &&
target->kind() == Code::STUB &&
target->major_key() == CodeStub::CallFunction &&
target->has_function_cache()) {
CallFunctionStub::Clear(heap, rinfo->pc());
}
}
MarkBit code_mark = Marking::MarkBitFrom(target);
heap-><API key>()->MarkObject(target, code_mark);
heap-><API key>()->RecordRelocSlot(rinfo, target);
}
static inline void VisitDebugTarget(Heap* heap, RelocInfo* rinfo) {
ASSERT((RelocInfo::IsJSReturn(rinfo->rmode()) &&
rinfo-><API key>()) ||
(RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
rinfo-><API key>()));
Code* target = Code::<API key>(rinfo->call_address());
MarkBit code_mark = Marking::MarkBitFrom(target);
heap-><API key>()->MarkObject(target, code_mark);
heap-><API key>()->RecordRelocSlot(rinfo, target);
}
// Mark object pointed to by p.
INLINE(static void MarkObjectByPointer(<API key>* collector,
Object** anchor_slot,
Object** p)) {
if (!(*p)->IsHeapObject()) return;
HeapObject* object = <API key>(p);
collector->RecordSlot(anchor_slot, p, object);
MarkBit mark = Marking::MarkBitFrom(object);
collector->MarkObject(object, mark);
}
// Visit an unmarked object.
INLINE(static void VisitUnmarkedObject(<API key>* collector,
HeapObject* obj)) {
#ifdef DEBUG
ASSERT(Isolate::Current()->heap()->Contains(obj));
ASSERT(!HEAP-><API key>()->IsMarked(obj));
#endif
Map* map = obj->map();
Heap* heap = obj->GetHeap();
MarkBit mark = Marking::MarkBitFrom(obj);
heap-><API key>()->SetMark(obj, mark);
// Mark the map pointer and the body.
MarkBit map_mark = Marking::MarkBitFrom(map);
heap-><API key>()->MarkObject(map, map_mark);
IterateBody(map, obj);
}
// Visit all unmarked objects pointed to by [start, end).
// Returns false if the operation fails (lack of stack space).
static inline bool <API key>(Heap* heap,
Object** start,
Object** end) {
// Return false is we are close to the stack limit.
StackLimitCheck check(heap->isolate());
if (check.HasOverflowed()) return false;
<API key>* collector = heap-><API key>();
// Visit the unmarked objects.
for (Object** p = start; p < end; p++) {
Object* o = *p;
if (!o->IsHeapObject()) continue;
collector->RecordSlot(start, p, o);
HeapObject* obj = HeapObject::cast(o);
MarkBit mark = Marking::MarkBitFrom(obj);
if (mark.Get()) continue;
VisitUnmarkedObject(collector, obj);
}
return true;
}
static inline void <API key>(Address* p) { }
static inline void <API key>(RelocInfo* rinfo) { }
static inline void VisitRuntimeEntry(RelocInfo* rinfo) { }
private:
class DataObjectVisitor {
public:
template<int size>
static void VisitSpecialized(Map* map, HeapObject* object) {
}
static void Visit(Map* map, HeapObject* object) {
}
};
typedef FlexibleBodyVisitor<<API key>,
JSObject::BodyDescriptor,
void> JSObjectVisitor;
typedef FlexibleBodyVisitor<<API key>,
<API key>,
void> StructObjectVisitor;
static void VisitJSWeakMap(Map* map, HeapObject* object) {
<API key>* collector = map->GetHeap()-><API key>();
JSWeakMap* weak_map = reinterpret_cast<JSWeakMap*>(object);
// Enqueue weak map in linked list of encountered weak maps.
ASSERT(weak_map->next() == Smi::FromInt(0));
weak_map->set_next(collector-><API key>());
collector-><API key>(weak_map);
// Skip visiting the backing hash table containing the mappings.
int object_size = JSWeakMap::BodyDescriptor::SizeOf(map, object);
BodyVisitorBase<<API key>>::IteratePointers(
map->GetHeap(),
object,
JSWeakMap::BodyDescriptor::kStartOffset,
JSWeakMap::kTableOffset);
BodyVisitorBase<<API key>>::IteratePointers(
map->GetHeap(),
object,
JSWeakMap::kTableOffset + kPointerSize,
object_size);
// Mark the backing hash table without pushing it on the marking stack.
ObjectHashTable* table = ObjectHashTable::cast(weak_map->table());
ASSERT(!<API key>::IsMarked(table));
collector->SetMark(table, Marking::MarkBitFrom(table));
collector->MarkObject(table->map(), Marking::MarkBitFrom(table->map()));
ASSERT(<API key>::IsMarked(table->map()));
}
static void VisitCode(Map* map, HeapObject* object) {
reinterpret_cast<Code*>(object)->CodeIterateBody<<API key>>(
map->GetHeap());
}
// Code flushing support.
// How many collections newly compiled code object will survive before being
// flushed.
static const int kCodeAgeThreshold = 5;
static const int <API key> = 5;
inline static bool HasSourceCode(Heap* heap, SharedFunctionInfo* info) {
Object* undefined = heap->undefined_value();
return (info->script() != undefined) &&
(reinterpret_cast<Script*>(info->script())->source() != undefined);
}
inline static bool IsCompiled(JSFunction* function) {
return function->code() !=
function->GetIsolate()->builtins()->builtin(Builtins::kLazyCompile);
}
inline static bool IsCompiled(SharedFunctionInfo* function) {
return function->code() !=
function->GetIsolate()->builtins()->builtin(Builtins::kLazyCompile);
}
inline static bool IsFlushable(Heap* heap, JSFunction* function) {
SharedFunctionInfo* shared_info = function->unchecked_shared();
// Code is either on stack, in compilation cache or referenced
// by optimized version of function.
MarkBit code_mark = Marking::MarkBitFrom(function->code());
if (code_mark.Get()) {
if (!Marking::MarkBitFrom(shared_info).Get()) {
shared_info->set_code_age(0);
}
return false;
}
// We do not flush code for optimized functions.
if (function->code() != shared_info->code()) {
return false;
}
return IsFlushable(heap, shared_info);
}
inline static bool IsFlushable(Heap* heap, SharedFunctionInfo* shared_info) {
// Code is either on stack, in compilation cache or referenced
// by optimized version of function.
MarkBit code_mark =
Marking::MarkBitFrom(shared_info->code());
if (code_mark.Get()) {
return false;
}
// The function must be compiled and have the source code available,
// to be able to recompile it in case we need the function again.
if (!(shared_info->is_compiled() && HasSourceCode(heap, shared_info))) {
return false;
}
// We never flush code for Api functions.
Object* function_data = shared_info->function_data();
if (function_data-><API key>()) {
return false;
}
// Only flush code for functions.
if (shared_info->code()->kind() != Code::FUNCTION) {
return false;
}
// Function must be lazy compilable.
if (!shared_info-><API key>()) {
return false;
}
// If this is a full script wrapped in a function we do no flush the code.
if (shared_info->is_toplevel()) {
return false;
}
// Age this shared function info.
if (shared_info->code_age() < kCodeAgeThreshold) {
shared_info->set_code_age(shared_info->code_age() + 1);
return false;
}
return true;
}
static bool <API key>(Heap* heap, JSFunction* function) {
if (!IsFlushable(heap, function)) return false;
// This function's code looks flushable. But we have to postpone the
// decision until we see all functions that point to the same
// SharedFunctionInfo because some of them might be optimized.
// That would make the nonoptimized version of the code nonflushable,
// because it is required for bailing out from optimized code.
heap-><API key>()->code_flusher()->AddCandidate(function);
return true;
}
static inline bool <API key>(Object* ctx) {
return ctx->IsContext() &&
!Context::cast(ctx)->global()->IsJSBuiltinsObject();
}
static void <API key>(Map* map, HeapObject* object) {
SharedFunctionInfo* shared = reinterpret_cast<SharedFunctionInfo*>(object);
if (shared-><API key>()) shared->DetachInitialMap();
FixedBodyVisitor<<API key>,
SharedFunctionInfo::BodyDescriptor,
void>::Visit(map, object);
}
static void <API key>(Heap* heap,
JSRegExp* re,
bool is_ascii) {
// Make sure that the fixed array is in fact initialized on the RegExp.
// We could potentially trigger a GC when initializing the RegExp.
if (HeapObject::cast(re->data())->map()->instance_type() !=
FIXED_ARRAY_TYPE) return;
// Make sure this is a RegExp that actually contains code.
if (re->TypeTagUnchecked() != JSRegExp::IRREGEXP) return;
Object* code = re->DataAtUnchecked(JSRegExp::code_index(is_ascii));
if (!code->IsSmi() &&
HeapObject::cast(code)->map()->instance_type() == CODE_TYPE) {
// Save a copy that can be reinstated if we need the code again.
re->SetDataAtUnchecked(JSRegExp::saved_code_index(is_ascii),
code,
heap);
// Saving a copy might create a pointer into compaction candidate
// that was not observed by marker. This might happen if JSRegExp data
// was marked through the compilation cache before marker reached JSRegExp
// object.
FixedArray* data = FixedArray::cast(re->data());
Object** slot = data->data_start() + JSRegExp::saved_code_index(is_ascii);
heap-><API key>()->
RecordSlot(slot, slot, code);
// Set a number in the 0-255 range to guarantee no smi overflow.
re->SetDataAtUnchecked(JSRegExp::code_index(is_ascii),
Smi::FromInt(heap->sweep_generation() & 0xff),
heap);
} else if (code->IsSmi()) {
int value = Smi::cast(code)->value();
// The regexp has not been compiled yet or there was a compilation error.
if (value == JSRegExp::kUninitializedValue ||
value == JSRegExp::<API key>) {
return;
}
// Check if we should flush now.
if (value == ((heap->sweep_generation() - <API key>) & 0xff)) {
re->SetDataAtUnchecked(JSRegExp::code_index(is_ascii),
Smi::FromInt(JSRegExp::kUninitializedValue),
heap);
re->SetDataAtUnchecked(JSRegExp::saved_code_index(is_ascii),
Smi::FromInt(JSRegExp::kUninitializedValue),
heap);
}
}
}
// Works by setting the current sweep_generation (as a smi) in the
// code object place in the data array of the RegExp and keeps a copy
// around that can be reinstated if we reuse the RegExp before flushing.
// If we did not use the code for <API key> mark sweep GCs
// we flush the code.
static void <API key>(Map* map, HeapObject* object) {
Heap* heap = map->GetHeap();
<API key>* collector = heap-><API key>();
if (!collector-><API key>()) {
VisitJSRegExpFields(map, object);
return;
}
JSRegExp* re = reinterpret_cast<JSRegExp*>(object);
// Flush code or set age on both ASCII and two byte code.
<API key>(heap, re, true);
<API key>(heap, re, false);
// Visit the fields of the RegExp, including the updated FixedArray.
VisitJSRegExpFields(map, object);
}
static void <API key>(Map* map,
HeapObject* object) {
<API key>* collector = map->GetHeap()-><API key>();
if (!collector-><API key>()) {
<API key>(map, object);
return;
}
<API key>(map, object, false);
}
static void <API key>(
Map* map, HeapObject* object, bool <API key>) {
Heap* heap = map->GetHeap();
SharedFunctionInfo* shared = reinterpret_cast<SharedFunctionInfo*>(object);
if (shared-><API key>()) shared->DetachInitialMap();
if (!<API key>) {
<API key> = IsFlushable(heap, shared);
if (<API key>) {
heap-><API key>()->code_flusher()->AddCandidate(shared);
}
}
<API key>(heap, object, <API key>);
}
static void VisitCodeEntry(Heap* heap, Address entry_address) {
Code* code = Code::cast(Code::<API key>(entry_address));
MarkBit mark = Marking::MarkBitFrom(code);
heap-><API key>()->MarkObject(code, mark);
heap-><API key>()->
RecordCodeEntrySlot(entry_address, code);
}
static void VisitGlobalContext(Map* map, HeapObject* object) {
FixedBodyVisitor<<API key>,
Context::<API key>,
void>::Visit(map, object);
<API key>* collector = map->GetHeap()-><API key>();
for (int idx = Context::FIRST_WEAK_SLOT;
idx < Context::<API key>;
++idx) {
Object** slot =
HeapObject::RawField(object, FixedArray::OffsetOfElementAt(idx));
collector->RecordSlot(slot, slot, *slot);
}
}
static void <API key>(Map* map, HeapObject* object) {
Heap* heap = map->GetHeap();
<API key>* collector = heap-><API key>();
if (!collector-><API key>()) {
VisitJSFunction(map, object);
return;
}
JSFunction* jsfunction = reinterpret_cast<JSFunction*>(object);
// The function must have a valid context and not be a builtin.
bool <API key> = false;
if (<API key>(jsfunction->unchecked_context())) {
<API key> = <API key>(heap, jsfunction);
}
if (!<API key>) {
Code* code = jsfunction->shared()->code();
MarkBit code_mark = Marking::MarkBitFrom(code);
collector->MarkObject(code, code_mark);
if (jsfunction->code()->kind() == Code::OPTIMIZED_FUNCTION) {
collector-><API key>(jsfunction->code());
}
}
<API key>(map,
reinterpret_cast<JSFunction*>(object),
<API key>);
}
static void VisitJSFunction(Map* map, HeapObject* object) {
<API key>(map,
reinterpret_cast<JSFunction*>(object),
false);
}
#define SLOT_ADDR(obj, offset) \
reinterpret_cast<Object**>((obj)->address() + offset)
static inline void <API key>(Map* map,
JSFunction* object,
bool <API key>) {
Heap* heap = map->GetHeap();
VisitPointers(heap,
HeapObject::RawField(object, JSFunction::kPropertiesOffset),
HeapObject::RawField(object, JSFunction::kCodeEntryOffset));
if (!<API key>) {
VisitCodeEntry(heap, object->address() + JSFunction::kCodeEntryOffset);
} else {
// Don't visit code object.
// Visit shared function info to avoid double checking of it's
// flushability.
SharedFunctionInfo* shared_info = object->unchecked_shared();
MarkBit shared_info_mark = Marking::MarkBitFrom(shared_info);
if (!shared_info_mark.Get()) {
Map* shared_info_map = shared_info->map();
MarkBit <API key> =
Marking::MarkBitFrom(shared_info_map);
heap-><API key>()->SetMark(shared_info, shared_info_mark);
heap-><API key>()->MarkObject(shared_info_map,
<API key>);
<API key>(shared_info_map,
shared_info,
true);
}
}
VisitPointers(
heap,
HeapObject::RawField(object,
JSFunction::kCodeEntryOffset + kPointerSize),
HeapObject::RawField(object,
JSFunction::<API key>));
// Don't visit the next function list field as it is a weak reference.
Object** next_function =
HeapObject::RawField(object, JSFunction::<API key>);
heap-><API key>()->RecordSlot(
next_function, next_function, *next_function);
}
static inline void VisitJSRegExpFields(Map* map,
HeapObject* object) {
int <API key> =
JSRegExp::kSize + kPointerSize * map->inobject_properties();
VisitPointers(map->GetHeap(),
SLOT_ADDR(object, JSRegExp::kPropertiesOffset),
SLOT_ADDR(object, <API key>));
}
static void <API key>(Heap* heap,
HeapObject* object,
bool <API key>) {
VisitPointer(heap, SLOT_ADDR(object, SharedFunctionInfo::kNameOffset));
if (!<API key>) {
VisitPointer(heap, SLOT_ADDR(object, SharedFunctionInfo::kCodeOffset));
}
VisitPointers(heap,
SLOT_ADDR(object, SharedFunctionInfo::kScopeInfoOffset),
SLOT_ADDR(object, SharedFunctionInfo::kSize));
}
#undef SLOT_ADDR
typedef void (*Callback)(Map* map, HeapObject* object);
static <API key><Callback> table_;
};
<API key><<API key>::Callback>
<API key>::table_;
class MarkingVisitor : public ObjectVisitor {
public:
explicit MarkingVisitor(Heap* heap) : heap_(heap) { }
void VisitPointer(Object** p) {
<API key>::VisitPointer(heap_, p);
}
void VisitPointers(Object** start, Object** end) {
<API key>::VisitPointers(heap_, start, end);
}
private:
Heap* heap_;
};
class CodeMarkingVisitor : public ThreadVisitor {
public:
explicit CodeMarkingVisitor(<API key>* collector)
: collector_(collector) {}
void VisitThread(Isolate* isolate, ThreadLocalTop* top) {
collector_-><API key>(isolate, top);
}
private:
<API key>* collector_;
};
class <API key> : public ObjectVisitor {
public:
explicit <API key>(<API key>* collector)
: collector_(collector) {}
void VisitPointers(Object** start, Object** end) {
for (Object** p = start; p < end; p++) VisitPointer(p);
}
void VisitPointer(Object** slot) {
Object* obj = *slot;
if (obj-><API key>()) {
SharedFunctionInfo* shared = reinterpret_cast<SharedFunctionInfo*>(obj);
MarkBit shared_mark = Marking::MarkBitFrom(shared);
MarkBit code_mark = Marking::MarkBitFrom(shared->code());
collector_->MarkObject(shared->code(), code_mark);
collector_->MarkObject(shared, shared_mark);
}
}
private:
<API key>* collector_;
};
void <API key>::<API key>(Code* code) {
// For optimized functions we should retain both non-optimized version
// of it's code and non-optimized version of all inlined functions.
// This is required to support bailing out from inlined code.
<API key>* data =
reinterpret_cast<<API key>*>(
code-><API key>());
FixedArray* literals = data->LiteralArray();
for (int i = 0, count = data-><API key>()->value();
i < count;
i++) {
JSFunction* inlined = reinterpret_cast<JSFunction*>(literals->get(i));
Code* inlined_code = inlined->shared()->code();
MarkBit inlined_code_mark = Marking::MarkBitFrom(inlined_code);
MarkObject(inlined_code, inlined_code_mark);
}
}
void <API key>::<API key>(Isolate* isolate,
ThreadLocalTop* top) {
for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
// Note: for the frame that has a pending lazy deoptimization
// StackFrame::unchecked_code will return a non-optimized code object for
// the outermost function and StackFrame::LookupCode will return
// actual optimized code object.
StackFrame* frame = it.frame();
Code* code = frame->unchecked_code();
MarkBit code_mark = Marking::MarkBitFrom(code);
MarkObject(code, code_mark);
if (frame->is_optimized()) {
<API key>(frame->LookupCode());
}
}
}
void <API key>::<API key>() {
ASSERT(heap() == Isolate::Current()->heap());
// TODO(1609) Currently incremental marker does not support code flushing.
if (!FLAG_flush_code || <API key>) {
EnableCodeFlushing(false);
return;
}
#ifdef <API key>
if (heap()->isolate()->debug()->IsLoaded() ||
heap()->isolate()->debug()->has_break_points()) {
EnableCodeFlushing(false);
return;
}
#endif
EnableCodeFlushing(true);
// Ensure that empty descriptor array is marked. Method MarkDescriptorArray
// relies on it being marked before any other descriptor array.
HeapObject* descriptor_array = heap()-><API key>();
MarkBit <API key> = Marking::MarkBitFrom(descriptor_array);
MarkObject(descriptor_array, <API key>);
// Make sure we are not referencing the code from the stack.
ASSERT(this == heap()-><API key>());
<API key>(heap()->isolate(),
heap()->isolate()->thread_local_top());
// Iterate the archived stacks in all threads to check if
// the code is referenced.
CodeMarkingVisitor <API key>(this);
heap()->isolate()->thread_manager()-><API key>(
&<API key>);
<API key> visitor(this);
heap()->isolate()->compilation_cache()->IterateFunctions(&visitor);
heap()->isolate()-><API key>()->Iterate(&visitor);
ProcessMarkingDeque();
}
// Visitor class for marking heap roots.
class RootMarkingVisitor : public ObjectVisitor {
public:
explicit RootMarkingVisitor(Heap* heap)
: collector_(heap-><API key>()) { }
void VisitPointer(Object** p) {
MarkObjectByPointer(p);
}
void VisitPointers(Object** start, Object** end) {
for (Object** p = start; p < end; p++) MarkObjectByPointer(p);
}
private:
void MarkObjectByPointer(Object** p) {
if (!(*p)->IsHeapObject()) return;
// Replace flat cons strings in place.
HeapObject* object = <API key>(p);
MarkBit mark_bit = Marking::MarkBitFrom(object);
if (mark_bit.Get()) return;
Map* map = object->map();
// Mark the object.
collector_->SetMark(object, mark_bit);
// Mark the map pointer and body, and push them on the marking stack.
MarkBit map_mark = Marking::MarkBitFrom(map);
collector_->MarkObject(map, map_mark);
<API key>::IterateBody(map, object);
// Mark all the objects reachable from the map and body. May leave
// overflowed objects in the heap.
collector_->EmptyMarkingDeque();
}
<API key>* collector_;
};
// Helper class for pruning the symbol table.
class SymbolTableCleaner : public ObjectVisitor {
public:
explicit SymbolTableCleaner(Heap* heap)
: heap_(heap), pointers_removed_(0) { }
virtual void VisitPointers(Object** start, Object** end) {
// Visit all HeapObject pointers in [start, end).
for (Object** p = start; p < end; p++) {
Object* o = *p;
if (o->IsHeapObject() &&
!Marking::MarkBitFrom(HeapObject::cast(o)).Get()) {
// Check if the symbol being pruned is an external symbol. We need to
// delete the associated external data as this symbol is going away.
// Since no objects have yet been moved we can safely access the map of
// the object.
if (o->IsExternalString()) {
heap_-><API key>(String::cast(*p));
}
// Set the entry to the_hole_value (as deleted).
*p = heap_->the_hole_value();
pointers_removed_++;
}
}
}
int PointersRemoved() {
return pointers_removed_;
}
private:
Heap* heap_;
int pointers_removed_;
};
// Implementation of WeakObjectRetainer for mark compact GCs. All marked objects
// are retained.
class <API key> : public WeakObjectRetainer {
public:
virtual Object* RetainAs(Object* object) {
if (Marking::MarkBitFrom(HeapObject::cast(object)).Get()) {
return object;
} else {
return NULL;
}
}
};
void <API key>::<API key>(HeapObject* object) {
ASSERT(IsMarked(object));
ASSERT(HEAP->Contains(object));
if (object->IsMap()) {
Map* map = Map::cast(object);
ClearCacheOnMap(map);
// When map collection is enabled we have to mark through map's transitions
// in a special way to make transition links weak.
// Only maps for subclasses of JSReceiver can have transitions.
STATIC_ASSERT(LAST_TYPE == <API key>);
if (collect_maps_ && map->instance_type() >= <API key>) {
MarkMapContents(map);
} else {
marking_deque_.PushBlack(map);
}
} else {
marking_deque_.PushBlack(object);
}
}
void <API key>::MarkMapContents(Map* map) {
// Mark prototype transitions array but don't push it into marking stack.
// This will make references from it weak. We will clean dead prototype
// transitions in <API key>.
FixedArray* <API key> = map-><API key>();
MarkBit mark = Marking::MarkBitFrom(<API key>);
if (!mark.Get()) {
mark.Set();
MemoryChunk::<API key>(<API key>->address(),
<API key>->Size());
}
Object** <API key> =
HeapObject::RawField(map, Map::<API key>);
Object* <API key> = *<API key>;
if (!<API key>->IsSmi()) {
MarkDescriptorArray(
reinterpret_cast<DescriptorArray*>(<API key>));
}
// Mark the Object* fields of the Map.
// Since the descriptor array has been marked already, it is fine
// that one of these fields contains a pointer to it.
Object** start_slot = HeapObject::RawField(map,
Map::<API key>);
Object** end_slot = HeapObject::RawField(map, Map::<API key>);
<API key>::VisitPointers(map->GetHeap(), start_slot, end_slot);
}
void <API key>::<API key>(HeapObject* accessors,
int offset) {
Object** slot = HeapObject::RawField(accessors, offset);
HeapObject* accessor = HeapObject::cast(*slot);
if (accessor->IsMap()) return;
RecordSlot(slot, slot, accessor);
MarkObjectAndPush(accessor);
}
void <API key>::MarkDescriptorArray(
DescriptorArray* descriptors) {
MarkBit descriptors_mark = Marking::MarkBitFrom(descriptors);
if (descriptors_mark.Get()) return;
// Empty descriptor array is marked as a root before any maps are marked.
ASSERT(descriptors != heap()-><API key>());
SetMark(descriptors, descriptors_mark);
FixedArray* contents = reinterpret_cast<FixedArray*>(
descriptors->get(DescriptorArray::kContentArrayIndex));
ASSERT(contents->IsHeapObject());
ASSERT(!IsMarked(contents));
ASSERT(contents->IsFixedArray());
ASSERT(contents->length() >= 2);
MarkBit contents_mark = Marking::MarkBitFrom(contents);
SetMark(contents, contents_mark);
// Contents contains (value, details) pairs. If the details say that the type
// of descriptor is MAP_TRANSITION, CONSTANT_TRANSITION,
// <API key> or NULL_DESCRIPTOR, we don't mark the value as
// live. Only for MAP_TRANSITION, <API key> and
// CONSTANT_TRANSITION is the value an Object* (a Map*).
for (int i = 0; i < contents->length(); i += 2) {
// If the pair (value, details) at index i, i+1 is not
// a transition or null descriptor, mark the value.
PropertyDetails details(Smi::cast(contents->get(i + 1)));
Object** slot = contents->data_start() + i;
if (!(*slot)->IsHeapObject()) continue;
HeapObject* value = HeapObject::cast(*slot);
RecordSlot(slot, slot, *slot);
switch (details.type()) {
case NORMAL:
case FIELD:
case CONSTANT_FUNCTION:
case HANDLER:
case INTERCEPTOR:
MarkObjectAndPush(value);
break;
case CALLBACKS:
if (!value->IsAccessorPair()) {
MarkObjectAndPush(value);
} else if (!<API key>(value)) {
<API key>(value, AccessorPair::kGetterOffset);
<API key>(value, AccessorPair::kSetterOffset);
}
break;
case ELEMENTS_TRANSITION:
// For maps with multiple elements transitions, the transition maps are
// stored in a FixedArray. Keep the fixed array alive but not the maps
// that it refers to.
if (value->IsFixedArray()) <API key>(value);
break;
case MAP_TRANSITION:
case CONSTANT_TRANSITION:
case NULL_DESCRIPTOR:
break;
}
}
// The DescriptorArray descriptors contains a pointer to its contents array,
// but the contents array is already marked.
marking_deque_.PushBlack(descriptors);
}
void <API key>::CreateBackPointers() {
HeapObjectIterator iterator(heap()->map_space());
for (HeapObject* next_object = iterator.Next();
next_object != NULL; next_object = iterator.Next()) {
if (next_object->IsMap()) { // Could also be FreeSpace object on free list.
Map* map = Map::cast(next_object);
STATIC_ASSERT(LAST_TYPE == <API key>);
if (map->instance_type() >= <API key>) {
map->CreateBackPointers();
} else {
ASSERT(map-><API key>() == heap()-><API key>());
}
}
}
}
// Fill the marking stack with overflowed objects returned by the given
// iterator. Stop when the marking stack is filled or the end of the space
// is reached, whichever comes first.
template<class T>
static void <API key>(Heap* heap,
MarkingDeque* marking_deque,
T* it) {
// The caller should ensure that the marking stack is initially not full,
// so that we don't waste effort pointlessly scanning for objects.
ASSERT(!marking_deque->IsFull());
Map* filler_map = heap-><API key>();
for (HeapObject* object = it->Next();
object != NULL;
object = it->Next()) {
MarkBit markbit = Marking::MarkBitFrom(object);
if ((object->map() != filler_map) && Marking::IsGrey(markbit)) {
Marking::GreyToBlack(markbit);
MemoryChunk::<API key>(object->address(), object->Size());
marking_deque->PushBlack(object);
if (marking_deque->IsFull()) return;
}
}
}
static inline int <API key>(uint32_t mark_bits, int* starts);
static void <API key>(MarkingDeque* marking_deque, Page* p) {
ASSERT(strcmp(Marking::kWhiteBitPattern, "00") == 0);
ASSERT(strcmp(Marking::kBlackBitPattern, "10") == 0);
ASSERT(strcmp(Marking::kGreyBitPattern, "11") == 0);
ASSERT(strcmp(Marking::<API key>, "01") == 0);
MarkBit::CellType* cells = p->markbits()->cells();
int last_cell_index =
Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(p->area_end())));
Address cell_base = p->area_start();
int cell_index = Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(cell_base)));
for (;
cell_index < last_cell_index;
cell_index++, cell_base += 32 * kPointerSize) {
ASSERT((unsigned)cell_index ==
Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(cell_base))));
const MarkBit::CellType current_cell = cells[cell_index];
if (current_cell == 0) continue;
const MarkBit::CellType next_cell = cells[cell_index + 1];
MarkBit::CellType grey_objects = current_cell &
((current_cell >> 1) | (next_cell << (Bitmap::kBitsPerCell - 1)));
int offset = 0;
while (grey_objects != 0) {
int trailing_zeros = CompilerIntrinsics::CountTrailingZeros(grey_objects);
grey_objects >>= trailing_zeros;
offset += trailing_zeros;
MarkBit markbit(&cells[cell_index], 1 << offset, false);
ASSERT(Marking::IsGrey(markbit));
Marking::GreyToBlack(markbit);
Address addr = cell_base + offset * kPointerSize;
HeapObject* object = HeapObject::FromAddress(addr);
MemoryChunk::<API key>(object->address(), object->Size());
marking_deque->PushBlack(object);
if (marking_deque->IsFull()) return;
offset += 2;
grey_objects >>= 2;
}
grey_objects >>= (Bitmap::kBitsPerCell - 1);
}
}
static void <API key>(Heap* heap,
MarkingDeque* marking_deque,
PagedSpace* space) {
if (!space-><API key>()) {
HeapObjectIterator it(space);
<API key>(heap, marking_deque, &it);
} else {
PageIterator it(space);
while (it.has_next()) {
Page* p = it.next();
<API key>(marking_deque, p);
if (marking_deque->IsFull()) return;
}
}
}
bool <API key>::<API key>(Object** p) {
Object* o = *p;
if (!o->IsHeapObject()) return false;
HeapObject* heap_object = HeapObject::cast(o);
MarkBit mark = Marking::MarkBitFrom(heap_object);
return !mark.Get();
}
void <API key>::MarkSymbolTable() {
SymbolTable* symbol_table = heap()->symbol_table();
// Mark the symbol table itself.
MarkBit symbol_table_mark = Marking::MarkBitFrom(symbol_table);
SetMark(symbol_table, symbol_table_mark);
// Explicitly mark the prefix.
MarkingVisitor marker(heap());
symbol_table->IteratePrefix(&marker);
ProcessMarkingDeque();
}
void <API key>::MarkRoots(RootMarkingVisitor* visitor) {
// Mark the heap roots including global variables, stack variables,
// etc., and all objects reachable from them.
heap()->IterateStrongRoots(visitor, VISIT_ONLY_STRONG);
// Handle the symbol table specially.
MarkSymbolTable();
// There may be overflowed objects in the heap. Visit them now.
while (marking_deque_.overflowed()) {
RefillMarkingDeque();
EmptyMarkingDeque();
}
}
void <API key>::MarkObjectGroups() {
List<ObjectGroup*>* object_groups =
heap()->isolate()->global_handles()->object_groups();
int last = 0;
for (int i = 0; i < object_groups->length(); i++) {
ObjectGroup* entry = object_groups->at(i);
ASSERT(entry != NULL);
Object*** objects = entry->objects_;
bool group_marked = false;
for (size_t j = 0; j < entry->length_; j++) {
Object* object = *objects[j];
if (object->IsHeapObject()) {
HeapObject* heap_object = HeapObject::cast(object);
MarkBit mark = Marking::MarkBitFrom(heap_object);
if (mark.Get()) {
group_marked = true;
break;
}
}
}
if (!group_marked) {
(*object_groups)[last++] = entry;
continue;
}
// An object in the group is marked, so mark as grey all white heap
// objects in the group.
for (size_t j = 0; j < entry->length_; ++j) {
Object* object = *objects[j];
if (object->IsHeapObject()) {
HeapObject* heap_object = HeapObject::cast(object);
MarkBit mark = Marking::MarkBitFrom(heap_object);
MarkObject(heap_object, mark);
}
}
// Once the entire group has been colored grey, set the object group
// to NULL so it won't be processed again.
entry->Dispose();
object_groups->at(i) = NULL;
}
object_groups->Rewind(last);
}
void <API key>::<API key>() {
List<ImplicitRefGroup*>* ref_groups =
heap()->isolate()->global_handles()->implicit_ref_groups();
int last = 0;
for (int i = 0; i < ref_groups->length(); i++) {
ImplicitRefGroup* entry = ref_groups->at(i);
ASSERT(entry != NULL);
if (!IsMarked(*entry->parent_)) {
(*ref_groups)[last++] = entry;
continue;
}
Object*** children = entry->children_;
// A parent object is marked, so mark all child heap objects.
for (size_t j = 0; j < entry->length_; ++j) {
if ((*children[j])->IsHeapObject()) {
HeapObject* child = HeapObject::cast(*children[j]);
MarkBit mark = Marking::MarkBitFrom(child);
MarkObject(child, mark);
}
}
// Once the entire group has been marked, dispose it because it's
// not needed anymore.
entry->Dispose();
}
ref_groups->Rewind(last);
}
// Mark all objects reachable from the objects on the marking stack.
// Before: the marking stack contains zero or more heap object pointers.
// After: the marking stack is empty, and all objects reachable from the
// marking stack have been marked, or are overflowed in the heap.
void <API key>::EmptyMarkingDeque() {
while (!marking_deque_.IsEmpty()) {
while (!marking_deque_.IsEmpty()) {
HeapObject* object = marking_deque_.Pop();
ASSERT(object->IsHeapObject());
ASSERT(heap()->Contains(object));
ASSERT(Marking::IsBlack(Marking::MarkBitFrom(object)));
Map* map = object->map();
MarkBit map_mark = Marking::MarkBitFrom(map);
MarkObject(map, map_mark);
<API key>::IterateBody(map, object);
}
// Process encountered weak maps, mark objects only reachable by those
// weak maps and repeat until fix-point is reached.
ProcessWeakMaps();
}
}
// Sweep the heap for overflowed objects, clear their overflow bits, and
// push them on the marking stack. Stop early if the marking stack fills
// before sweeping completes. If sweeping completes, there are no remaining
// overflowed objects in the heap so the overflow flag on the markings stack
// is cleared.
void <API key>::RefillMarkingDeque() {
ASSERT(marking_deque_.overflowed());
SemiSpaceIterator new_it(heap()->new_space());
<API key>(heap(), &marking_deque_, &new_it);
if (marking_deque_.IsFull()) return;
<API key>(heap(),
&marking_deque_,
heap()->old_pointer_space());
if (marking_deque_.IsFull()) return;
<API key>(heap(),
&marking_deque_,
heap()->old_data_space());
if (marking_deque_.IsFull()) return;
<API key>(heap(),
&marking_deque_,
heap()->code_space());
if (marking_deque_.IsFull()) return;
<API key>(heap(),
&marking_deque_,
heap()->map_space());
if (marking_deque_.IsFull()) return;
<API key>(heap(),
&marking_deque_,
heap()->cell_space());
if (marking_deque_.IsFull()) return;
LargeObjectIterator lo_it(heap()->lo_space());
<API key>(heap(),
&marking_deque_,
&lo_it);
if (marking_deque_.IsFull()) return;
marking_deque_.ClearOverflowed();
}
// Mark all objects reachable (transitively) from objects on the marking
// stack. Before: the marking stack contains zero or more heap object
// pointers. After: the marking stack is empty and there are no overflowed
// objects in the heap.
void <API key>::ProcessMarkingDeque() {
EmptyMarkingDeque();
while (marking_deque_.overflowed()) {
RefillMarkingDeque();
EmptyMarkingDeque();
}
}
void <API key>::<API key>() {
bool work_to_do = true;
ASSERT(marking_deque_.IsEmpty());
while (work_to_do) {
MarkObjectGroups();
<API key>();
work_to_do = !marking_deque_.IsEmpty();
ProcessMarkingDeque();
}
}
void <API key>::MarkLiveObjects() {
GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_MARK);
// The recursive GC marker detects when it is nearing stack overflow,
// and switches to a different marking system. JS interrupts interfere
// with the C stack limit check.
<API key> postpone(heap()->isolate());
bool <API key> = false;
IncrementalMarking* incremental_marking = heap_->incremental_marking();
if (<API key>) {
// Finalize the incremental marking and check whether we had an overflow.
// Both markers use grey color to mark overflowed objects so
// non-incremental marker can deal with them as if overflow
// occured during normal marking.
// But incremental marker uses a separate marking deque
// so we have to explicitly copy it's overflow state.
incremental_marking->Finalize();
<API key> =
incremental_marking->marking_deque()->overflowed();
incremental_marking->marking_deque()->ClearOverflowed();
} else {
// Abort any pending incremental activities e.g. incremental sweeping.
incremental_marking->Abort();
}
#ifdef DEBUG
ASSERT(state_ == PREPARE_GC);
state_ = MARK_LIVE_OBJECTS;
#endif
// The to space contains live objects, a page in from space is used as a
// marking stack.
Address marking_deque_start = heap()->new_space()->FromSpacePageLow();
Address marking_deque_end = heap()->new_space()->FromSpacePageHigh();
if (<API key>) {
marking_deque_end = marking_deque_start + 64 * kPointerSize;
}
marking_deque_.Initialize(marking_deque_start,
marking_deque_end);
ASSERT(!marking_deque_.overflowed());
if (<API key>) {
// There are overflowed objects left in the heap after incremental marking.
marking_deque_.SetOverflowed();
}
<API key>();
if (<API key>) {
// There is no write barrier on cells so we have to scan them now at the end
// of the incremental marking.
{
HeapObjectIterator cell_iterator(heap()->cell_space());
HeapObject* cell;
while ((cell = cell_iterator.Next()) != NULL) {
ASSERT(cell-><API key>());
if (IsMarked(cell)) {
int offset = <API key>::kValueOffset;
<API key>::VisitPointer(
heap(),
reinterpret_cast<Object**>(cell->address() + offset));
}
}
}
}
RootMarkingVisitor root_visitor(heap());
MarkRoots(&root_visitor);
// The objects reachable from the roots are marked, yet unreachable
// objects are unmarked. Mark objects reachable due to host
// application specific logic.
<API key>();
// The objects reachable from the roots or object groups are marked,
// yet unreachable objects are unmarked. Mark objects reachable
// only from weak global handles.
// First we identify nonlive weak handles and mark them as pending
// destruction.
heap()->isolate()->global_handles()->IdentifyWeakHandles(
&<API key>);
// Then we mark the objects and process the transitive closure.
heap()->isolate()->global_handles()->IterateWeakRoots(&root_visitor);
while (marking_deque_.overflowed()) {
RefillMarkingDeque();
EmptyMarkingDeque();
}
// Repeat host application specific marking to mark unmarked objects
// reachable from the weak roots.
<API key>();
AfterMarking();
}
void <API key>::AfterMarking() {
// Object literal map caches reference symbols (cache keys) and maps
// (cache values). At this point still useful maps have already been
// marked. Mark the keys for the alive values before we process the
// symbol table.
ProcessMapCaches();
// Prune the symbol table removing all symbols only pointed to by the
// symbol table. Cannot use symbol_table() here because the symbol
// table is marked.
SymbolTable* symbol_table = heap()->symbol_table();
SymbolTableCleaner v(heap());
symbol_table->IterateElements(&v);
symbol_table->ElementsRemoved(v.PointersRemoved());
heap()-><API key>.Iterate(&v);
heap()-><API key>.CleanUp();
// Process the weak references.
<API key> <API key>;
heap()-><API key>(&<API key>);
// Remove object groups after marking phase.
heap()->isolate()->global_handles()->RemoveObjectGroups();
heap()->isolate()->global_handles()-><API key>();
// Flush code from collected candidates.
if (<API key>()) {
code_flusher_->ProcessCandidates();
}
// Clean up dead objects from the runtime profiler.
heap()->isolate()->runtime_profiler()->RemoveDeadSamples();
}
void <API key>::ProcessMapCaches() {
Object* raw_context = heap()-><API key>;
while (raw_context != heap()->undefined_value()) {
Context* context = reinterpret_cast<Context*>(raw_context);
if (IsMarked(context)) {
HeapObject* raw_map_cache =
HeapObject::cast(context->get(Context::MAP_CACHE_INDEX));
// A map cache may be reachable from the stack. In this case
// it's already transitively marked and it's too late to clean
// up its parts.
if (!IsMarked(raw_map_cache) &&
raw_map_cache != heap()->undefined_value()) {
MapCache* map_cache = reinterpret_cast<MapCache*>(raw_map_cache);
int existing_elements = map_cache->NumberOfElements();
int used_elements = 0;
for (int i = MapCache::kElementsStartIndex;
i < map_cache->length();
i += MapCache::kEntrySize) {
Object* raw_key = map_cache->get(i);
if (raw_key == heap()->undefined_value() ||
raw_key == heap()->the_hole_value()) continue;
STATIC_ASSERT(MapCache::kEntrySize == 2);
Object* raw_map = map_cache->get(i + 1);
if (raw_map->IsHeapObject() && IsMarked(raw_map)) {
++used_elements;
} else {
// Delete useless entries with unmarked maps.
ASSERT(raw_map->IsMap());
map_cache->set_the_hole(i);
map_cache->set_the_hole(i + 1);
}
}
if (used_elements == 0) {
context->set(Context::MAP_CACHE_INDEX, heap()->undefined_value());
} else {
// Note: we don't actually shrink the cache here to avoid
// extra complexity during GC. We rely on subsequent cache
// usages (EnsureCapacity) to do this.
map_cache->ElementsRemoved(existing_elements - used_elements);
MarkBit map_cache_markbit = Marking::MarkBitFrom(map_cache);
MarkObject(map_cache, map_cache_markbit);
}
}
}
// Move to next element in the list.
raw_context = context->get(Context::NEXT_CONTEXT_LINK);
}
ProcessMarkingDeque();
}
void <API key>::ReattachInitialMaps() {
HeapObjectIterator map_iterator(heap()->map_space());
for (HeapObject* obj = map_iterator.Next();
obj != NULL;
obj = map_iterator.Next()) {
if (obj->IsFreeSpace()) continue;
Map* map = Map::cast(obj);
STATIC_ASSERT(LAST_TYPE == <API key>);
if (map->instance_type() < <API key>) continue;
if (map-><API key>()) {
JSFunction::cast(map->constructor())->shared()->AttachInitialMap(map);
}
}
}
void <API key>::<API key>() {
HeapObjectIterator map_iterator(heap()->map_space());
// Iterate over the map space, setting map transitions that go from
// a marked map to an unmarked map to null transitions. At the same time,
// set all the prototype fields of maps back to their original value,
// dropping the back pointers temporarily stored in the prototype field.
// Setting the prototype field requires following the linked list of
// back pointers, reversing them all at once. This allows us to find
// those maps with map transitions that need to be nulled, and only
// scan the descriptor arrays of those maps, not all maps.
// All of these actions are carried out only on maps of JSObjects
// and related subtypes.
for (HeapObject* obj = map_iterator.Next();
obj != NULL; obj = map_iterator.Next()) {
Map* map = reinterpret_cast<Map*>(obj);
MarkBit map_mark = Marking::MarkBitFrom(map);
if (map->IsFreeSpace()) continue;
ASSERT(map->IsMap());
// Only JSObject and subtypes have map transitions and back pointers.
STATIC_ASSERT(LAST_TYPE == LAST_JS_OBJECT_TYPE);
if (map->instance_type() < <API key>) continue;
if (map_mark.Get() &&
map-><API key>()) {
// This map is used for inobject slack tracking and has been detached
// from SharedFunctionInfo during the mark phase.
// Since it survived the GC, reattach it now.
map-><API key>()->unchecked_shared()->AttachInitialMap(map);
}
<API key>(map);
<API key>(map, map_mark);
}
}
void <API key>::<API key>(Map* map) {
int <API key> = map-><API key>();
FixedArray* <API key> = map-><API key>();
int <API key> = 0;
const int header = Map::<API key>;
const int proto_offset = header + Map::<API key>;
const int map_offset = header + Map::<API key>;
const int step = Map::<API key>;
for (int i = 0; i < <API key>; i++) {
Object* prototype = <API key>->get(proto_offset + i * step);
Object* cached_map = <API key>->get(map_offset + i * step);
if (IsMarked(prototype) && IsMarked(cached_map)) {
int proto_index = proto_offset + <API key> * step;
int map_index = map_offset + <API key> * step;
if (<API key> != i) {
<API key>->set_unchecked(
heap_,
proto_index,
prototype,
<API key>);
<API key>->set_unchecked(
heap_,
map_index,
cached_map,
SKIP_WRITE_BARRIER);
}
Object** slot =
HeapObject::RawField(<API key>,
FixedArray::OffsetOfElementAt(proto_index));
RecordSlot(slot, slot, prototype);
<API key>++;
}
}
if (<API key> != <API key>) {
map-><API key>(<API key>);
}
// Fill slots that became free with undefined value.
for (int i = <API key> * step;
i < <API key> * step;
i++) {
<API key>->set_undefined(heap_, header + i);
}
}
void <API key>::<API key>(Map* map,
MarkBit map_mark) {
// Follow the chain of back pointers to find the prototype.
Map* real_prototype = map;
while (real_prototype->IsMap()) {
real_prototype = reinterpret_cast<Map*>(real_prototype->prototype());
ASSERT(real_prototype->IsHeapObject());
}
// Follow back pointers, setting them to prototype, clearing map transitions
// when necessary.
Map* current = map;
bool current_is_alive = map_mark.Get();
bool on_dead_path = !current_is_alive;
while (current->IsMap()) {
Object* next = current->prototype();
// There should never be a dead map above a live map.
ASSERT(on_dead_path || current_is_alive);
// A live map above a dead map indicates a dead transition. This test will
// always be false on the first iteration.
if (on_dead_path && current_is_alive) {
on_dead_path = false;
current-><API key>(heap(), real_prototype);
}
Object** slot = HeapObject::RawField(current, Map::kPrototypeOffset);
*slot = real_prototype;
if (current_is_alive) RecordSlot(slot, slot, real_prototype);
current = reinterpret_cast<Map*>(next);
current_is_alive = Marking::MarkBitFrom(current).Get();
}
}
void <API key>::ProcessWeakMaps() {
Object* weak_map_obj = <API key>();
while (weak_map_obj != Smi::FromInt(0)) {
ASSERT(<API key>::IsMarked(HeapObject::cast(weak_map_obj)));
JSWeakMap* weak_map = reinterpret_cast<JSWeakMap*>(weak_map_obj);
ObjectHashTable* table = ObjectHashTable::cast(weak_map->table());
for (int i = 0; i < table->Capacity(); i++) {
if (<API key>::IsMarked(HeapObject::cast(table->KeyAt(i)))) {
Object* value = table->get(table->EntryToValueIndex(i));
<API key>::VisitPointer(heap(), &value);
table->set_unchecked(heap(),
table->EntryToValueIndex(i),
value,
<API key>);
}
}
weak_map_obj = weak_map->next();
}
}
void <API key>::ClearWeakMaps() {
Object* weak_map_obj = <API key>();
while (weak_map_obj != Smi::FromInt(0)) {
ASSERT(<API key>::IsMarked(HeapObject::cast(weak_map_obj)));
JSWeakMap* weak_map = reinterpret_cast<JSWeakMap*>(weak_map_obj);
ObjectHashTable* table = ObjectHashTable::cast(weak_map->table());
for (int i = 0; i < table->Capacity(); i++) {
if (!<API key>::IsMarked(HeapObject::cast(table->KeyAt(i)))) {
table->RemoveEntry(i);
}
}
weak_map_obj = weak_map->next();
weak_map->set_next(Smi::FromInt(0));
}
<API key>(Smi::FromInt(0));
}
// We scavange new space simultaneously with sweeping. This is done in two
// passes.
// The first pass migrates all alive objects from one semispace to another or
// promotes them to old space. Forwarding address is written directly into
// first word of object without any encoding. If object is dead we write
// NULL as a forwarding address.
// The second pass updates pointers to new space in all spaces. It is possible
// to encounter pointers to dead new space objects during traversal of pointers
// to new space. We should clear them to avoid encountering them during next
// pointer iteration. This is an issue if the store buffer overflows and we
// have to scan the entire old space, including dead objects, looking for
// pointers to new space.
void <API key>::MigrateObject(Address dst,
Address src,
int size,
AllocationSpace dest) {
HEAP_PROFILE(heap(), ObjectMoveEvent(src, dst));
if (dest == OLD_POINTER_SPACE || dest == LO_SPACE) {
Address src_slot = src;
Address dst_slot = dst;
ASSERT(IsAligned(size, kPointerSize));
for (int remaining = size / kPointerSize; remaining > 0; remaining
Object* value = Memory::Object_at(src_slot);
Memory::Object_at(dst_slot) = value;
if (heap_->InNewSpace(value)) {
heap_->store_buffer()->Mark(dst_slot);
} else if (value->IsHeapObject() && <API key>(value)) {
SlotsBuffer::AddTo(&<API key>,
&<API key>,
reinterpret_cast<Object**>(dst_slot),
SlotsBuffer::IGNORE_OVERFLOW);
}
src_slot += kPointerSize;
dst_slot += kPointerSize;
}
if (compacting_ && HeapObject::FromAddress(dst)->IsJSFunction()) {
Address code_entry_slot = dst + JSFunction::kCodeEntryOffset;
Address code_entry = Memory::Address_at(code_entry_slot);
if (Page::FromAddress(code_entry)-><API key>()) {
SlotsBuffer::AddTo(&<API key>,
&<API key>,
SlotsBuffer::CODE_ENTRY_SLOT,
code_entry_slot,
SlotsBuffer::IGNORE_OVERFLOW);
}
}
} else if (dest == CODE_SPACE) {
PROFILE(heap()->isolate(), CodeMoveEvent(src, dst));
heap()->MoveBlock(dst, src, size);
SlotsBuffer::AddTo(&<API key>,
&<API key>,
SlotsBuffer::<API key>,
dst,
SlotsBuffer::IGNORE_OVERFLOW);
Code::cast(HeapObject::FromAddress(dst))->Relocate(dst - src);
} else {
ASSERT(dest == OLD_DATA_SPACE || dest == NEW_SPACE);
heap()->MoveBlock(dst, src, size);
}
Memory::Address_at(src) = dst;
}
// Visitor for updating pointers from live objects in old spaces to new space.
// It does not expect to encounter pointers to dead objects.
class <API key>: public ObjectVisitor {
public:
explicit <API key>(Heap* heap) : heap_(heap) { }
void VisitPointer(Object** p) {
UpdatePointer(p);
}
void VisitPointers(Object** start, Object** end) {
for (Object** p = start; p < end; p++) UpdatePointer(p);
}
void <API key>(RelocInfo* rinfo) {
ASSERT(rinfo->rmode() == RelocInfo::EMBEDDED_OBJECT);
Object* target = rinfo->target_object();
VisitPointer(&target);
rinfo->set_target_object(target);
}
void VisitCodeTarget(RelocInfo* rinfo) {
ASSERT(RelocInfo::IsCodeTarget(rinfo->rmode()));
Object* target = Code::<API key>(rinfo->target_address());
VisitPointer(&target);
rinfo->set_target_address(Code::cast(target)->instruction_start());
}
void VisitDebugTarget(RelocInfo* rinfo) {
ASSERT((RelocInfo::IsJSReturn(rinfo->rmode()) &&
rinfo-><API key>()) ||
(RelocInfo::IsDebugBreakSlot(rinfo->rmode()) &&
rinfo-><API key>()));
Object* target = Code::<API key>(rinfo->call_address());
VisitPointer(&target);
rinfo->set_call_address(Code::cast(target)->instruction_start());
}
static inline void UpdateSlot(Heap* heap, Object** slot) {
Object* obj = *slot;
if (!obj->IsHeapObject()) return;
HeapObject* heap_obj = HeapObject::cast(obj);
MapWord map_word = heap_obj->map_word();
if (map_word.IsForwardingAddress()) {
ASSERT(heap->InFromSpace(heap_obj) ||
<API key>::<API key>(heap_obj));
HeapObject* target = map_word.ToForwardingAddress();
*slot = target;
ASSERT(!heap->InFromSpace(target) &&
!<API key>::<API key>(target));
}
}
private:
inline void UpdatePointer(Object** p) {
UpdateSlot(heap_, p);
}
Heap* heap_;
};
static void UpdatePointer(HeapObject** p, HeapObject* object) {
ASSERT(*p == object);
Address old_addr = object->address();
Address new_addr = Memory::Address_at(old_addr);
// The new space sweep will overwrite the map word of dead objects
// with NULL. In this case we do not need to transfer this entry to
// the store buffer which we are rebuilding.
if (new_addr != NULL) {
*p = HeapObject::FromAddress(new_addr);
} else {
// We have to zap this pointer, because the store buffer may overflow later,
// and then we have to scan the entire heap and we don't want to find
// spurious newspace pointers in the old space.
*p = reinterpret_cast<HeapObject*>(Smi::FromInt(0));
}
}
static String* <API key>(Heap* heap,
Object** p) {
MapWord map_word = HeapObject::cast(*p)->map_word();
if (map_word.IsForwardingAddress()) {
return String::cast(map_word.ToForwardingAddress());
}
return String::cast(*p);
}
bool <API key>::TryPromoteObject(HeapObject* object,
int object_size) {
Object* result;
if (object_size > Page::<API key>) {
MaybeObject* maybe_result =
heap()->lo_space()->AllocateRaw(object_size, NOT_EXECUTABLE);
if (maybe_result->ToObject(&result)) {
HeapObject* target = HeapObject::cast(result);
MigrateObject(target->address(),
object->address(),
object_size,
LO_SPACE);
heap()-><API key>()->tracer()->
<API key>(object_size);
return true;
}
} else {
OldSpace* target_space = heap()->TargetSpace(object);
ASSERT(target_space == heap()->old_pointer_space() ||
target_space == heap()->old_data_space());
MaybeObject* maybe_result = target_space->AllocateRaw(object_size);
if (maybe_result->ToObject(&result)) {
HeapObject* target = HeapObject::cast(result);
MigrateObject(target->address(),
object->address(),
object_size,
target_space->identity());
heap()-><API key>()->tracer()->
<API key>(object_size);
return true;
}
}
return false;
}
void <API key>::EvacuateNewSpace() {
// There are soft limits in the allocation code, designed trigger a mark
// sweep collection by failing allocations. But since we are already in
// a mark-sweep allocation, there is no sense in trying to trigger one.
AlwaysAllocateScope scope;
heap()-><API key>();
NewSpace* new_space = heap()->new_space();
// Store allocation range before flipping semispaces.
Address from_bottom = new_space->bottom();
Address from_top = new_space->top();
// Flip the semispaces. After flipping, to space is empty, from space has
// live objects.
new_space->Flip();
new_space->ResetAllocationInfo();
int survivors_size = 0;
// First pass: traverse all objects in inactive semispace, remove marks,
// migrate live objects and write forwarding addresses. This stage puts
// new entries in the store buffer and may cause some pages to be marked
// scan-on-scavenge.
SemiSpaceIterator from_it(from_bottom, from_top);
for (HeapObject* object = from_it.Next();
object != NULL;
object = from_it.Next()) {
MarkBit mark_bit = Marking::MarkBitFrom(object);
if (mark_bit.Get()) {
mark_bit.Clear();
// Don't bother decrementing live bytes count. We'll discard the
// entire page at the end.
int size = object->Size();
survivors_size += size;
// Aggressively promote young survivors to the old space.
if (TryPromoteObject(object, size)) {
continue;
}
// Promotion failed. Just migrate object to another semispace.
MaybeObject* allocation = new_space->AllocateRaw(size);
if (allocation->IsFailure()) {
if (!new_space->AddFreshPage()) {
// Shouldn't happen. We are sweeping linearly, and to-space
// has the same number of pages as from-space, so there is
// always room.
UNREACHABLE();
}
allocation = new_space->AllocateRaw(size);
ASSERT(!allocation->IsFailure());
}
Object* target = allocation->ToObjectUnchecked();
MigrateObject(HeapObject::cast(target)->address(),
object->address(),
size,
NEW_SPACE);
} else {
// Process the dead object before we write a NULL into its header.
LiveObjectList::ProcessNonLive(object);
// Mark dead objects in the new space with null in their map field.
Memory::Address_at(object->address()) = NULL;
}
}
heap_-><API key>(survivors_size);
new_space->set_age_mark(new_space->top());
}
void <API key>::<API key>(Page* p) {
AlwaysAllocateScope always_allocate;
PagedSpace* space = static_cast<PagedSpace*>(p->owner());
ASSERT(p-><API key>() && !p->WasSwept());
MarkBit::CellType* cells = p->markbits()->cells();
p->MarkSweptPrecisely();
int last_cell_index =
Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(p->area_end())));
Address cell_base = p->area_start();
int cell_index = Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(cell_base)));
int offsets[16];
for (;
cell_index < last_cell_index;
cell_index++, cell_base += 32 * kPointerSize) {
ASSERT((unsigned)cell_index ==
Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(cell_base))));
if (cells[cell_index] == 0) continue;
int live_objects = <API key>(cells[cell_index], offsets);
for (int i = 0; i < live_objects; i++) {
Address object_addr = cell_base + offsets[i] * kPointerSize;
HeapObject* object = HeapObject::FromAddress(object_addr);
ASSERT(Marking::IsBlack(Marking::MarkBitFrom(object)));
int size = object->Size();
MaybeObject* target = space->AllocateRaw(size);
if (target->IsFailure()) {
// OS refused to give us memory.
V8::<API key>("Evacuation");
return;
}
Object* target_object = target->ToObjectUnchecked();
MigrateObject(HeapObject::cast(target_object)->address(),
object_addr,
size,
space->identity());
ASSERT(object->map_word().IsForwardingAddress());
}
// Clear marking bits for current cell.
cells[cell_index] = 0;
}
p->ResetLiveBytes();
}
void <API key>::EvacuatePages() {
int npages = <API key>.length();
for (int i = 0; i < npages; i++) {
Page* p = <API key>[i];
ASSERT(p-><API key>() ||
p->IsFlagSet(Page::<API key>));
if (p-><API key>()) {
// During compaction we might have to request a new page.
// Check that space still have room for that.
if (static_cast<PagedSpace*>(p->owner())->CanExpand()) {
<API key>(p);
} else {
// Without room for expansion evacuation is not guaranteed to succeed.
// Pessimistically abandon unevacuated pages.
for (int j = i; j < npages; j++) {
Page* page = <API key>[j];
<API key>.DeallocateChain(page-><API key>());
page-><API key>();
page->SetFlag(Page::<API key>);
}
return;
}
}
}
}
class <API key> : public WeakObjectRetainer {
public:
virtual Object* RetainAs(Object* object) {
if (object->IsHeapObject()) {
HeapObject* heap_object = HeapObject::cast(object);
MapWord map_word = heap_object->map_word();
if (map_word.IsForwardingAddress()) {
return map_word.ToForwardingAddress();
}
}
return object;
}
};
static inline void UpdateSlot(ObjectVisitor* v,
SlotsBuffer::SlotType slot_type,
Address addr) {
switch (slot_type) {
case SlotsBuffer::CODE_TARGET_SLOT: {
RelocInfo rinfo(addr, RelocInfo::CODE_TARGET, 0, NULL);
rinfo.Visit(v);
break;
}
case SlotsBuffer::CODE_ENTRY_SLOT: {
v->VisitCodeEntry(addr);
break;
}
case SlotsBuffer::<API key>: {
HeapObject* obj = HeapObject::FromAddress(addr);
Code::cast(obj)->CodeIterateBody(v);
break;
}
case SlotsBuffer::DEBUG_TARGET_SLOT: {
RelocInfo rinfo(addr, RelocInfo::DEBUG_BREAK_SLOT, 0, NULL);
if (rinfo.<API key>()) rinfo.Visit(v);
break;
}
case SlotsBuffer::JS_RETURN_SLOT: {
RelocInfo rinfo(addr, RelocInfo::JS_RETURN, 0, NULL);
if (rinfo.<API key>()) rinfo.Visit(v);
break;
}
case SlotsBuffer::<API key>: {
RelocInfo rinfo(addr, RelocInfo::EMBEDDED_OBJECT, 0, NULL);
rinfo.Visit(v);
break;
}
default:
UNREACHABLE();
break;
}
}
enum SweepingMode {
SWEEP_ONLY,
<API key>
};
enum <API key> {
REBUILD_SKIP_LIST,
IGNORE_SKIP_LIST
};
// Sweep a space precisely. After this has been done the space can
// be iterated precisely, hitting only the live objects. Code space
// is always swept precisely because we want to be able to iterate
// over it. Map space is swept precisely, because it is not compacted.
// Slots in live objects pointing into evacuation candidates are updated
// if requested.
template<SweepingMode sweeping_mode, <API key> skip_list_mode>
static void SweepPrecisely(PagedSpace* space,
Page* p,
ObjectVisitor* v) {
ASSERT(!p-><API key>() && !p->WasSwept());
ASSERT_EQ(skip_list_mode == REBUILD_SKIP_LIST,
space->identity() == CODE_SPACE);
ASSERT((p->skip_list() == NULL) || (skip_list_mode == REBUILD_SKIP_LIST));
MarkBit::CellType* cells = p->markbits()->cells();
p->MarkSweptPrecisely();
int last_cell_index =
Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(p->area_end())));
Address free_start = p->area_start();
int cell_index =
Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(free_start)));
ASSERT(reinterpret_cast<intptr_t>(free_start) % (32 * kPointerSize) == 0);
Address object_address = free_start;
int offsets[16];
SkipList* skip_list = p->skip_list();
int curr_region = -1;
if ((skip_list_mode == REBUILD_SKIP_LIST) && skip_list) {
skip_list->Clear();
}
for (;
cell_index < last_cell_index;
cell_index++, object_address += 32 * kPointerSize) {
ASSERT((unsigned)cell_index ==
Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(object_address))));
int live_objects = <API key>(cells[cell_index], offsets);
int live_index = 0;
for ( ; live_objects != 0; live_objects
Address free_end = object_address + offsets[live_index++] * kPointerSize;
if (free_end != free_start) {
space->Free(free_start, static_cast<int>(free_end - free_start));
}
HeapObject* live_object = HeapObject::FromAddress(free_end);
ASSERT(Marking::IsBlack(Marking::MarkBitFrom(live_object)));
Map* map = live_object->map();
int size = live_object->SizeFromMap(map);
if (sweeping_mode == <API key>) {
live_object->IterateBody(map->instance_type(), size, v);
}
if ((skip_list_mode == REBUILD_SKIP_LIST) && skip_list != NULL) {
int new_region_start =
SkipList::RegionNumber(free_end);
int new_region_end =
SkipList::RegionNumber(free_end + size - kPointerSize);
if (new_region_start != curr_region ||
new_region_end != curr_region) {
skip_list->AddObject(free_end, size);
curr_region = new_region_end;
}
}
free_start = free_end + size;
}
// Clear marking bits for current cell.
cells[cell_index] = 0;
}
if (free_start != p->area_end()) {
space->Free(free_start, static_cast<int>(p->area_end() - free_start));
}
p->ResetLiveBytes();
}
static bool <API key>(Code* code, bool value) {
Page* p = Page::FromAddress(code->address());
if (p-><API key>() ||
p->IsFlagSet(Page::<API key>)) {
return false;
}
Address code_start = code->address();
Address code_end = code_start + code->Size();
uint32_t start_index = MemoryChunk::<API key>(code_start);
uint32_t end_index =
MemoryChunk::<API key>(code_end - kPointerSize);
Bitmap* b = p->markbits();
MarkBit start_mark_bit = b->MarkBitFromIndex(start_index);
MarkBit end_mark_bit = b->MarkBitFromIndex(end_index);
MarkBit::CellType* start_cell = start_mark_bit.cell();
MarkBit::CellType* end_cell = end_mark_bit.cell();
if (value) {
MarkBit::CellType start_mask = ~(start_mark_bit.mask() - 1);
MarkBit::CellType end_mask = (end_mark_bit.mask() << 1) - 1;
if (start_cell == end_cell) {
*start_cell |= start_mask & end_mask;
} else {
*start_cell |= start_mask;
for (MarkBit::CellType* cell = start_cell + 1; cell < end_cell; cell++) {
*cell = ~0;
}
*end_cell |= end_mask;
}
} else {
for (MarkBit::CellType* cell = start_cell ; cell <= end_cell; cell++) {
*cell = 0;
}
}
return true;
}
static bool <API key>(Address addr) {
// We did not record any slots in large objects thus
// we can safely go to the page from the slot address.
Page* p = Page::FromAddress(addr);
// First check owner's identity because old pointer and old data spaces
// are swept lazily and might still have non-zero mark-bits on some
// pages.
if (p->owner()->identity() != CODE_SPACE) return false;
// In code space only bits on evacuation candidates (but we don't record
// any slots on them) and under invalidated code objects are non-zero.
MarkBit mark_bit =
p->markbits()->MarkBitFromIndex(Page::<API key>(addr));
return mark_bit.Get();
}
void <API key>::InvalidateCode(Code* code) {
if (heap_->incremental_marking()->IsCompacting() &&
!<API key>(code)) {
ASSERT(compacting_);
// If the object is white than no slots were recorded on it yet.
MarkBit mark_bit = Marking::MarkBitFrom(code);
if (Marking::IsWhite(mark_bit)) return;
invalidated_code_.Add(code);
}
}
bool <API key>::MarkInvalidatedCode() {
bool code_marked = false;
int length = invalidated_code_.length();
for (int i = 0; i < length; i++) {
Code* code = invalidated_code_[i];
if (<API key>(code, true)) {
code_marked = true;
}
}
return code_marked;
}
void <API key>::<API key>() {
int length = invalidated_code_.length();
for (int i = 0; i < length; i++) {
if (!IsMarked(invalidated_code_[i])) invalidated_code_[i] = NULL;
}
}
void <API key>::<API key>(ObjectVisitor* visitor) {
int length = invalidated_code_.length();
for (int i = 0; i < length; i++) {
Code* code = invalidated_code_[i];
if (code != NULL) {
code->Iterate(visitor);
<API key>(code, false);
}
}
invalidated_code_.Rewind(0);
}
void <API key>::<API key>() {
bool <API key>;
{ GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_SWEEP_NEWSPACE);
<API key> = MarkInvalidatedCode();
EvacuateNewSpace();
}
{ GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_EVACUATE_PAGES);
EvacuatePages();
}
// Second pass: find pointers to new space and update them.
<API key> updating_visitor(heap());
{ GCTracer::Scope gc_scope(tracer_,
GCTracer::Scope::<API key>);
// Update pointers in to space.
SemiSpaceIterator to_it(heap()->new_space()->bottom(),
heap()->new_space()->top());
for (HeapObject* object = to_it.Next();
object != NULL;
object = to_it.Next()) {
Map* map = object->map();
object->IterateBody(map->instance_type(),
object->SizeFromMap(map),
&updating_visitor);
}
}
{ GCTracer::Scope gc_scope(tracer_,
GCTracer::Scope::<API key>);
// Update roots.
heap_->IterateRoots(&updating_visitor, <API key>);
LiveObjectList::IterateElements(&updating_visitor);
}
{ GCTracer::Scope gc_scope(tracer_,
GCTracer::Scope::<API key>);
<API key> scope(heap_,
heap_->store_buffer(),
&Heap::<API key>);
heap_->store_buffer()-><API key>(&UpdatePointer);
}
{ GCTracer::Scope gc_scope(tracer_,
GCTracer::Scope::<API key>);
SlotsBuffer::<API key>(heap_,
<API key>,
<API key>);
if (<API key>) {
PrintF(" migration slots buffer: %d\n",
SlotsBuffer::SizeOfChain(<API key>));
}
if (compacting_ && <API key>) {
// It's difficult to filter out slots recorded for large objects.
LargeObjectIterator it(heap_->lo_space());
for (HeapObject* obj = it.Next(); obj != NULL; obj = it.Next()) {
// LargeObjectSpace is not swept yet thus we have to skip
// dead objects explicitly.
if (!IsMarked(obj)) continue;
Page* p = Page::FromAddress(obj->address());
if (p->IsFlagSet(Page::<API key>)) {
obj->Iterate(&updating_visitor);
p->ClearFlag(Page::<API key>);
}
}
}
}
int npages = <API key>.length();
{ GCTracer::Scope gc_scope(
tracer_, GCTracer::Scope::<API key>);
for (int i = 0; i < npages; i++) {
Page* p = <API key>[i];
ASSERT(p-><API key>() ||
p->IsFlagSet(Page::<API key>));
if (p-><API key>()) {
SlotsBuffer::<API key>(heap_,
p->slots_buffer(),
<API key>);
if (<API key>) {
PrintF(" page %p slots buffer: %d\n",
reinterpret_cast<void*>(p),
SlotsBuffer::SizeOfChain(p->slots_buffer()));
}
// Important: skip list should be cleared only after roots were updated
// because root iteration traverses the stack and might have to find
// code objects from non-updated pc pointing into evacuation candidate.
SkipList* list = p->skip_list();
if (list != NULL) list->Clear();
} else {
if (FLAG_gc_verbose) {
PrintF("Sweeping 0x%" V8PRIxPTR " during evacuation.\n",
reinterpret_cast<intptr_t>(p));
}
PagedSpace* space = static_cast<PagedSpace*>(p->owner());
p->ClearFlag(MemoryChunk::<API key>);
switch (space->identity()) {
case OLD_DATA_SPACE:
SweepConservatively(space, p);
break;
case OLD_POINTER_SPACE:
SweepPrecisely<<API key>, IGNORE_SKIP_LIST>(
space, p, &updating_visitor);
break;
case CODE_SPACE:
SweepPrecisely<<API key>, REBUILD_SKIP_LIST>(
space, p, &updating_visitor);
break;
default:
UNREACHABLE();
break;
}
}
}
}
GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::<API key>);
// Update pointers from cells.
HeapObjectIterator cell_iterator(heap_->cell_space());
for (HeapObject* cell = cell_iterator.Next();
cell != NULL;
cell = cell_iterator.Next()) {
if (cell-><API key>()) {
Address value_address =
reinterpret_cast<Address>(cell) +
(<API key>::kValueOffset - kHeapObjectTag);
updating_visitor.VisitPointer(reinterpret_cast<Object**>(value_address));
}
}
// Update pointer from the global contexts list.
updating_visitor.VisitPointer(heap_-><API key>());
heap_->symbol_table()->Iterate(&updating_visitor);
// Update pointers from external string table.
heap_-><API key>(
&<API key>);
// Update JSFunction pointers from the runtime profiler.
heap()->isolate()->runtime_profiler()-><API key>(
&updating_visitor);
<API key> <API key>;
heap()-><API key>(&<API key>);
// Visit invalidated code (we ignored all slots on it) and clear mark-bits
// under it.
<API key>(&updating_visitor);
#ifdef DEBUG
if (FLAG_verify_heap) {
VerifyEvacuation(heap_);
}
#endif
<API key>.DeallocateChain(&<API key>);
ASSERT(<API key> == NULL);
for (int i = 0; i < npages; i++) {
Page* p = <API key>[i];
if (!p-><API key>()) continue;
PagedSpace* space = static_cast<PagedSpace*>(p->owner());
space->Free(p->area_start(), p->area_size());
p-><API key>(false);
<API key>.DeallocateChain(p-><API key>());
p-><API key>();
p->ResetLiveBytes();
space->ReleasePage(p);
}
<API key>.Rewind(0);
compacting_ = false;
}
static const int <API key> = 5;
static const int kStartTableLines = 171;
static const int <API key> = 127;
static const int <API key> = 126;
#define _ <API key>
#define X <API key>
// Mark-bit to object start offset table.
// The line is indexed by the mark bits in a byte. The first number on
// the line describes the number of live object starts for the line and the
// other numbers on the line describe the offsets (in words) of the object
// starts.
// Since objects are at least 2 words large we don't have entries for two
// consecutive 1 bits. All entries after 170 have at least 2 consecutive bits.
char kStartTable[kStartTableLines * <API key>] = {
0, _, _, _, _,
1, 0, _, _, _,
1, 1, _, _, _,
X, _, _, _, _,
1, 2, _, _, _,
2, 0, 2, _, _,
X, _, _, _, _,
X, _, _, _, _,
1, 3, _, _, _,
2, 0, 3, _, _,
2, 1, 3, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
1, 4, _, _, _,
2, 0, 4, _, _,
2, 1, 4, _, _,
X, _, _, _, _,
2, 2, 4, _, _,
3, 0, 2, 4, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
1, 5, _, _, _,
2, 0, 5, _, _,
2, 1, 5, _, _,
X, _, _, _, _,
2, 2, 5, _, _,
3, 0, 2, 5, _,
X, _, _, _, _,
X, _, _, _, _,
2, 3, 5, _, _,
3, 0, 3, 5, _,
3, 1, 3, 5, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
1, 6, _, _, _,
2, 0, 6, _, _,
2, 1, 6, _, _,
X, _, _, _, _,
2, 2, 6, _, _,
3, 0, 2, 6, _,
X, _, _, _, _,
X, _, _, _, _,
2, 3, 6, _, _,
3, 0, 3, 6, _,
3, 1, 3, 6, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
2, 4, 6, _, _,
3, 0, 4, 6, _,
3, 1, 4, 6, _,
X, _, _, _, _,
3, 2, 4, 6, _,
4, 0, 2, 4, 6,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _,
X, _, _, _, _, // 100
X, _, _, _, _, // 101
X, _, _, _, _, // 102
X, _, _, _, _, // 103
X, _, _, _, _, // 104
X, _, _, _, _, // 105
X, _, _, _, _, // 106
X, _, _, _, _, // 107
X, _, _, _, _, // 108
X, _, _, _, _, // 109
X, _, _, _, _, // 110
X, _, _, _, _, // 111
X, _, _, _, _, // 112
X, _, _, _, _, // 113
X, _, _, _, _, // 114
X, _, _, _, _, // 115
X, _, _, _, _, // 116
X, _, _, _, _, // 117
X, _, _, _, _, // 118
X, _, _, _, _, // 119
X, _, _, _, _, // 120
X, _, _, _, _, // 121
X, _, _, _, _, // 122
X, _, _, _, _, // 123
X, _, _, _, _, // 124
X, _, _, _, _, // 125
X, _, _, _, _, // 126
X, _, _, _, _, // 127
1, 7, _, _, _, // 128
2, 0, 7, _, _, // 129
2, 1, 7, _, _, // 130
X, _, _, _, _, // 131
2, 2, 7, _, _, // 132
3, 0, 2, 7, _, // 133
X, _, _, _, _, // 134
X, _, _, _, _, // 135
2, 3, 7, _, _, // 136
3, 0, 3, 7, _, // 137
3, 1, 3, 7, _, // 138
X, _, _, _, _, // 139
X, _, _, _, _, // 140
X, _, _, _, _, // 141
X, _, _, _, _, // 142
X, _, _, _, _, // 143
2, 4, 7, _, _, // 144
3, 0, 4, 7, _, // 145
3, 1, 4, 7, _, // 146
X, _, _, _, _, // 147
3, 2, 4, 7, _, // 148
4, 0, 2, 4, 7, // 149
X, _, _, _, _, // 150
X, _, _, _, _, // 151
X, _, _, _, _, // 152
X, _, _, _, _, // 153
X, _, _, _, _, // 154
X, _, _, _, _, // 155
X, _, _, _, _, // 156
X, _, _, _, _, // 157
X, _, _, _, _, // 158
X, _, _, _, _, // 159
2, 5, 7, _, _, // 160
3, 0, 5, 7, _, // 161
3, 1, 5, 7, _, // 162
X, _, _, _, _, // 163
3, 2, 5, 7, _, // 164
4, 0, 2, 5, 7, // 165
X, _, _, _, _, // 166
X, _, _, _, _, // 167
3, 3, 5, 7, _, // 168
4, 0, 3, 5, 7, // 169
4, 1, 3, 5, 7 // 170
};
#undef _
#undef X
// Takes a word of mark bits. Returns the number of objects that start in the
// range. Puts the offsets of the words in the supplied array.
static inline int <API key>(uint32_t mark_bits, int* starts) {
int objects = 0;
int offset = 0;
// No consecutive 1 bits.
ASSERT((mark_bits & 0x180) != 0x180);
ASSERT((mark_bits & 0x18000) != 0x18000);
ASSERT((mark_bits & 0x1800000) != 0x1800000);
while (mark_bits != 0) {
int byte = (mark_bits & 0xff);
mark_bits >>= 8;
if (byte != 0) {
ASSERT(byte < kStartTableLines); // No consecutive 1 bits.
char* table = kStartTable + byte * <API key>;
int <API key> = table[0];
ASSERT(<API key> != <API key>);
ASSERT(<API key> < <API key>);
for (int i = 0; i < <API key>; i++) {
starts[objects++] = offset + table[1 + i];
}
}
offset += 8;
}
return objects;
}
static inline Address DigestFreeStart(Address <API key>,
uint32_t free_start_cell) {
ASSERT(free_start_cell != 0);
// No consecutive 1 bits.
ASSERT((free_start_cell & (free_start_cell << 1)) == 0);
int offsets[16];
uint32_t cell = free_start_cell;
int offset_of_last_live;
if ((cell & 0x80000000u) != 0) {
// This case would overflow below.
offset_of_last_live = 31;
} else {
// Remove all but one bit, the most significant. This is an optimization
// that may or may not be worthwhile.
cell |= cell >> 16;
cell |= cell >> 8;
cell |= cell >> 4;
cell |= cell >> 2;
cell |= cell >> 1;
cell = (cell + 1) >> 1;
int live_objects = <API key>(cell, offsets);
ASSERT(live_objects == 1);
offset_of_last_live = offsets[live_objects - 1];
}
Address last_live_start =
<API key> + offset_of_last_live * kPointerSize;
HeapObject* last_live = HeapObject::FromAddress(last_live_start);
Address free_start = last_live_start + last_live->Size();
return free_start;
}
static inline Address StartOfLiveObject(Address block_address, uint32_t cell) {
ASSERT(cell != 0);
// No consecutive 1 bits.
ASSERT((cell & (cell << 1)) == 0);
int offsets[16];
if (cell == 0x80000000u) { // Avoid overflow below.
return block_address + 31 * kPointerSize;
}
uint32_t first_set_bit = ((cell ^ (cell - 1)) + 1) >> 1;
ASSERT((first_set_bit & cell) == first_set_bit);
int live_objects = <API key>(first_set_bit, offsets);
ASSERT(live_objects == 1);
USE(live_objects);
return block_address + offsets[0] * kPointerSize;
}
// Sweeps a space conservatively. After this has been done the larger free
// spaces have been put on the free list and the smaller ones have been
// ignored and left untouched. A free space is always either ignored or put
// on the free list, never split up into two parts. This is important
// because it means that any FreeSpace maps left actually describe a region of
// memory that can be ignored when scanning. Dead objects other than free
// spaces will not contain the free space map.
intptr_t <API key>::SweepConservatively(PagedSpace* space, Page* p) {
ASSERT(!p-><API key>() && !p->WasSwept());
MarkBit::CellType* cells = p->markbits()->cells();
p-><API key>();
int last_cell_index =
Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(p->area_end())));
int cell_index =
Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(p->area_start())));
intptr_t freed_bytes = 0;
// This is the start of the 32 word block that we are currently looking at.
Address block_address = p->area_start();
// Skip over all the dead objects at the start of the page and mark them free.
for (;
cell_index < last_cell_index;
cell_index++, block_address += 32 * kPointerSize) {
if (cells[cell_index] != 0) break;
}
size_t size = block_address - p->area_start();
if (cell_index == last_cell_index) {
freed_bytes += static_cast<int>(space->Free(p->area_start(),
static_cast<int>(size)));
ASSERT_EQ(0, p->LiveBytes());
return freed_bytes;
}
// Grow the size of the start-of-page free space a little to get up to the
// first live object.
Address free_end = StartOfLiveObject(block_address, cells[cell_index]);
// Free the first free space.
size = free_end - p->area_start();
freed_bytes += space->Free(p->area_start(),
static_cast<int>(size));
// The start of the current free area is represented in undigested form by
// the address of the last 32-word section that contained a live object and
// the marking bitmap for that cell, which describes where the live object
// started. Unless we find a large free space in the bitmap we will not
// digest this pair into a real address. We start the iteration here at the
// first word in the marking bit map that indicates a live object.
Address free_start = block_address;
uint32_t free_start_cell = cells[cell_index];
for ( ;
cell_index < last_cell_index;
cell_index++, block_address += 32 * kPointerSize) {
ASSERT((unsigned)cell_index ==
Bitmap::IndexToCell(
Bitmap::CellAlignIndex(
p-><API key>(block_address))));
uint32_t cell = cells[cell_index];
if (cell != 0) {
// We have a live object. Check approximately whether it is more than 32
// words since the last live object.
if (block_address - free_start > 32 * kPointerSize) {
free_start = DigestFreeStart(free_start, free_start_cell);
if (block_address - free_start > 32 * kPointerSize) {
// Now that we know the exact start of the free space it still looks
// like we have a large enough free space to be worth bothering with.
// so now we need to find the start of the first live object at the
// end of the free space.
free_end = StartOfLiveObject(block_address, cell);
freed_bytes += space->Free(free_start,
static_cast<int>(free_end - free_start));
}
}
// Update our undigested record of where the current free area started.
free_start = block_address;
free_start_cell = cell;
// Clear marking bits for current cell.
cells[cell_index] = 0;
}
}
// Handle the free space at the end of the page.
if (block_address - free_start > 32 * kPointerSize) {
free_start = DigestFreeStart(free_start, free_start_cell);
freed_bytes += space->Free(free_start,
static_cast<int>(block_address - free_start));
}
p->ResetLiveBytes();
return freed_bytes;
}
void <API key>::SweepSpace(PagedSpace* space, SweeperType sweeper) {
space-><API key>(sweeper == CONSERVATIVE ||
sweeper == LAZY_CONSERVATIVE);
space->ClearStats();
PageIterator it(space);
intptr_t freed_bytes = 0;
int pages_swept = 0;
intptr_t newspace_size = space->heap()->new_space()->Size();
bool <API key> = false;
bool unused_page_present = false;
intptr_t old_space_size = heap()->PromotedSpaceSize();
intptr_t space_left =
Min(heap()-><API key>(old_space_size),
heap()-><API key>(old_space_size)) - old_space_size;
while (it.has_next()) {
Page* p = it.next();
// Clear sweeping flags indicating that marking bits are still intact.
p->ClearSweptPrecisely();
p-><API key>();
if (p-><API key>()) {
ASSERT(<API key>.length() > 0);
continue;
}
if (p->IsFlagSet(Page::<API key>)) {
// Will be processed in <API key>.
continue;
}
// One unused page is kept, all further are released before sweeping them.
if (p->LiveBytes() == 0) {
if (unused_page_present) {
if (FLAG_gc_verbose) {
PrintF("Sweeping 0x%" V8PRIxPTR " released page.\n",
reinterpret_cast<intptr_t>(p));
}
// Adjust unswept free bytes because releasing a page expects said
// counter to be accurate for unswept pages.
space-><API key>(p);
space->ReleasePage(p);
continue;
}
unused_page_present = true;
}
if (<API key>) {
if (FLAG_gc_verbose) {
PrintF("Sweeping 0x%" V8PRIxPTR " lazily postponed.\n",
reinterpret_cast<intptr_t>(p));
}
space-><API key>(p);
continue;
}
switch (sweeper) {
case CONSERVATIVE: {
if (FLAG_gc_verbose) {
PrintF("Sweeping 0x%" V8PRIxPTR " conservatively.\n",
reinterpret_cast<intptr_t>(p));
}
SweepConservatively(space, p);
pages_swept++;
break;
}
case LAZY_CONSERVATIVE: {
if (FLAG_gc_verbose) {
PrintF("Sweeping 0x%" V8PRIxPTR " conservatively as needed.\n",
reinterpret_cast<intptr_t>(p));
}
freed_bytes += SweepConservatively(space, p);
pages_swept++;
if (space_left + freed_bytes > newspace_size) {
space->SetPagesToSweep(p->next_page());
<API key> = true;
} else {
if (FLAG_gc_verbose) {
PrintF("Only %" V8PRIdPTR " bytes freed. Still sweeping.\n",
freed_bytes);
}
}
break;
}
case PRECISE: {
if (FLAG_gc_verbose) {
PrintF("Sweeping 0x%" V8PRIxPTR " precisely.\n",
reinterpret_cast<intptr_t>(p));
}
if (space->identity() == CODE_SPACE) {
SweepPrecisely<SWEEP_ONLY, REBUILD_SKIP_LIST>(space, p, NULL);
} else {
SweepPrecisely<SWEEP_ONLY, IGNORE_SKIP_LIST>(space, p, NULL);
}
pages_swept++;
break;
}
default: {
UNREACHABLE();
}
}
}
if (FLAG_gc_verbose) {
PrintF("SweepSpace: %s (%d pages swept)\n",
AllocationSpaceName(space->identity()),
pages_swept);
}
// Give pages that are queued to be freed back to the OS.
heap()->FreeQueuedChunks();
}
void <API key>::SweepSpaces() {
GCTracer::Scope gc_scope(tracer_, GCTracer::Scope::MC_SWEEP);
#ifdef DEBUG
state_ = SWEEP_SPACES;
#endif
SweeperType how_to_sweep =
FLAG_lazy_sweeping ? LAZY_CONSERVATIVE : CONSERVATIVE;
if (FLAG_expose_gc) how_to_sweep = CONSERVATIVE;
if (sweep_precisely_) how_to_sweep = PRECISE;
// Noncompacting collections simply sweep the spaces to clear the mark
// bits and free the nonlive blocks (for old and map spaces). We sweep
// the map space last because freeing non-live maps overwrites them and
// the other spaces rely on possibly non-live maps to get the sizes for
// non-live objects.
SweepSpace(heap()->old_pointer_space(), how_to_sweep);
SweepSpace(heap()->old_data_space(), how_to_sweep);
<API key>();
SweepSpace(heap()->code_space(), PRECISE);
SweepSpace(heap()->cell_space(), PRECISE);
<API key>();
// <API key> depends on precise sweeping of map space to
// detect whether unmarked map became dead in this collection or in one
// of the previous ones.
SweepSpace(heap()->map_space(), PRECISE);
// Deallocate unmarked objects and clear marked bits for marked objects.
heap_->lo_space()->FreeUnmarkedObjects();
}
void <API key>::EnableCodeFlushing(bool enable) {
if (enable) {
if (code_flusher_ != NULL) return;
code_flusher_ = new CodeFlusher(heap()->isolate());
} else {
if (code_flusher_ == NULL) return;
delete code_flusher_;
code_flusher_ = NULL;
}
}
// TODO(1466) <API key> is not called currently.
// Our profiling tools do not expect intersections between
// code objects. We should either reenable it or change our tools.
void <API key>::<API key>(HeapObject* obj,
Isolate* isolate) {
#ifdef <API key>
if (obj->IsCode()) {
GDBJITInterface::RemoveCode(reinterpret_cast<Code*>(obj));
}
#endif
if (obj->IsCode()) {
PROFILE(isolate, CodeDeleteEvent(obj->address()));
}
}
void <API key>::Initialize() {
<API key>::Initialize();
}
bool SlotsBuffer::IsTypedSlot(ObjectSlot slot) {
return reinterpret_cast<uintptr_t>(slot) < <API key>;
}
bool SlotsBuffer::AddTo(<API key>* allocator,
SlotsBuffer** buffer_address,
SlotType type,
Address addr,
AdditionMode mode) {
SlotsBuffer* buffer = *buffer_address;
if (buffer == NULL || !buffer-><API key>()) {
if (mode == FAIL_ON_OVERFLOW && <API key>(buffer)) {
allocator->DeallocateChain(buffer_address);
return false;
}
buffer = allocator->AllocateBuffer(buffer);
*buffer_address = buffer;
}
ASSERT(buffer-><API key>());
buffer->Add(reinterpret_cast<ObjectSlot>(type));
buffer->Add(reinterpret_cast<ObjectSlot>(addr));
return true;
}
static inline SlotsBuffer::SlotType SlotTypeForRMode(RelocInfo::Mode rmode) {
if (RelocInfo::IsCodeTarget(rmode)) {
return SlotsBuffer::CODE_TARGET_SLOT;
} else if (RelocInfo::IsEmbeddedObject(rmode)) {
return SlotsBuffer::<API key>;
} else if (RelocInfo::IsDebugBreakSlot(rmode)) {
return SlotsBuffer::DEBUG_TARGET_SLOT;
} else if (RelocInfo::IsJSReturn(rmode)) {
return SlotsBuffer::JS_RETURN_SLOT;
}
UNREACHABLE();
return SlotsBuffer::<API key>;
}
void <API key>::RecordRelocSlot(RelocInfo* rinfo, Object* target) {
Page* target_page = Page::FromAddress(reinterpret_cast<Address>(target));
if (target_page-><API key>() &&
(rinfo->host() == NULL ||
!<API key>(rinfo->host()))) {
if (!SlotsBuffer::AddTo(&<API key>,
target_page-><API key>(),
SlotTypeForRMode(rinfo->rmode()),
rinfo->pc(),
SlotsBuffer::FAIL_ON_OVERFLOW)) {
<API key>(target_page);
}
}
}
void <API key>::RecordCodeEntrySlot(Address slot, Code* target) {
Page* target_page = Page::FromAddress(reinterpret_cast<Address>(target));
if (target_page-><API key>() &&
!<API key>(reinterpret_cast<Object**>(slot))) {
if (!SlotsBuffer::AddTo(&<API key>,
target_page-><API key>(),
SlotsBuffer::CODE_ENTRY_SLOT,
slot,
SlotsBuffer::FAIL_ON_OVERFLOW)) {
<API key>(target_page);
}
}
}
static inline SlotsBuffer::SlotType DecodeSlotType(
SlotsBuffer::ObjectSlot slot) {
return static_cast<SlotsBuffer::SlotType>(reinterpret_cast<intptr_t>(slot));
}
void SlotsBuffer::UpdateSlots(Heap* heap) {
<API key> v(heap);
for (int slot_idx = 0; slot_idx < idx_; ++slot_idx) {
ObjectSlot slot = slots_[slot_idx];
if (!IsTypedSlot(slot)) {
<API key>::UpdateSlot(heap, slot);
} else {
++slot_idx;
ASSERT(slot_idx < idx_);
UpdateSlot(&v,
DecodeSlotType(slot),
reinterpret_cast<Address>(slots_[slot_idx]));
}
}
}
void SlotsBuffer::<API key>(Heap* heap) {
<API key> v(heap);
for (int slot_idx = 0; slot_idx < idx_; ++slot_idx) {
ObjectSlot slot = slots_[slot_idx];
if (!IsTypedSlot(slot)) {
if (!<API key>(reinterpret_cast<Address>(slot))) {
<API key>::UpdateSlot(heap, slot);
}
} else {
++slot_idx;
ASSERT(slot_idx < idx_);
Address pc = reinterpret_cast<Address>(slots_[slot_idx]);
if (!<API key>(pc)) {
UpdateSlot(&v,
DecodeSlotType(slot),
reinterpret_cast<Address>(slots_[slot_idx]));
}
}
}
}
SlotsBuffer* <API key>::AllocateBuffer(SlotsBuffer* next_buffer) {
return new SlotsBuffer(next_buffer);
}
void <API key>::DeallocateBuffer(SlotsBuffer* buffer) {
delete buffer;
}
void <API key>::DeallocateChain(SlotsBuffer** buffer_address) {
SlotsBuffer* buffer = *buffer_address;
while (buffer != NULL) {
SlotsBuffer* next_buffer = buffer->next();
DeallocateBuffer(buffer);
buffer = next_buffer;
}
*buffer_address = NULL;
}
} } // namespace v8::internal |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE <API key> #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE CPP #-}
module Control.Distributed.Process.Serializable
( Serializable
, encodeFingerprint
, decodeFingerprint
, fingerprint
, sizeOfFingerprint
, Fingerprint
, showFingerprint
, SerializableDict(SerializableDict)
, TypeableDict(TypeableDict)
) where
import Data.Binary (Binary)
#if MIN_VERSION_base(4,7,0)
import Data.Typeable (Typeable)
import Data.Typeable.Internal (TypeRep(TypeRep), typeOf)
#else
import Data.Typeable (Typeable(..))
import Data.Typeable.Internal (TypeRep(TypeRep))
#endif
import Numeric (showHex)
import Control.Exception (throw)
import GHC.Fingerprint.Type (Fingerprint(..))
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Internal as BSI ( unsafeCreate
, inlinePerformIO
, toForeignPtr
)
import Foreign.Storable (pokeByteOff, peekByteOff, sizeOf)
import Foreign.ForeignPtr (withForeignPtr)
-- | Reification of 'Serializable' (see "Control.Distributed.Process.Closure")
data SerializableDict a where
SerializableDict :: Serializable a => SerializableDict a
deriving (Typeable)
-- | Reification of 'Typeable'.
data TypeableDict a where
TypeableDict :: Typeable a => TypeableDict a
deriving (Typeable)
-- | Objects that can be sent across the network
class (Binary a, Typeable a) => Serializable a
instance (Binary a, Typeable a) => Serializable a
-- | Encode type representation as a bytestring
encodeFingerprint :: Fingerprint -> ByteString
encodeFingerprint fp =
-- Since all CH nodes will run precisely the same binary, we don't have to
-- worry about cross-arch issues here (like endianness)
BSI.unsafeCreate sizeOfFingerprint $ \p -> pokeByteOff p 0 fp
-- | Decode a bytestring into a fingerprint. Throws an IO exception on failure
decodeFingerprint :: ByteString -> Fingerprint
decodeFingerprint bs
| BS.length bs /= sizeOfFingerprint =
throw $ userError "decodeFingerprint: Invalid length"
| otherwise = BSI.inlinePerformIO $ do
let (fp, offset, _) = BSI.toForeignPtr bs
withForeignPtr fp $ \p -> peekByteOff p offset
-- | Size of a fingerprint
sizeOfFingerprint :: Int
sizeOfFingerprint = sizeOf (undefined :: Fingerprint)
-- | The fingerprint of the typeRep of the argument
fingerprint :: Typeable a => a -> Fingerprint
fingerprint a = let TypeRep fp _ _ = typeOf a in fp
-- | Show fingerprint (for debugging purposes)
showFingerprint :: Fingerprint -> ShowS
showFingerprint (Fingerprint hi lo) =
showString "(" . showHex hi . showString "," . showHex lo . showString ")" |
#ifndef <API key>
#define <API key>
NPY_NO_EXPORT intp
parse_subindex(PyObject *op, intp *step_size, intp *n_steps, intp max);
NPY_NO_EXPORT int
parse_index(PyArrayObject *self, PyObject *op,
intp *dimensions, intp *strides, intp *offset_ptr);
NPY_NO_EXPORT PyObject
*iter_subscript(PyArrayIterObject *, PyObject *);
NPY_NO_EXPORT PyObject*
npy_iter_subscript(NpyArrayIterObject* self, PyObject* ind);
NPY_NO_EXPORT int
iter_ass_subscript(PyArrayIterObject *, PyObject *, PyObject *);
NPY_NO_EXPORT int
<API key>(NpyArrayIterObject* self, PyObject* ind, PyObject* val);
NPY_NO_EXPORT int
slice_GetIndices(PySliceObject *r, intp length,
intp *start, intp *stop, intp *step,
intp *slicelength);
#endif |
#include "elm/python/signalpy.h"
#include <boost/python/extract.hpp>
#include <boost/python/list.hpp>
#include <boost/python/str.hpp>
#define <API key> COOL_ARRAY_API
#define NO_IMPORT_ARRAY
#define <API key> NPY_1_7_API_VERSION
#include <numpy/ndarrayobject.h>
#include <opencv2/core/core.hpp>
#include "elm/python/arginfo.h"
#include "elm/python/stl_inl.h"
using std::string;
namespace bp=boost::python;
using namespace cv;
using namespace elm;
SignalPy::SignalPy()
: Signal()
{
}
bp::dict SignalPy::toPythonDict() const {
bp::dict d;
VecS names = FeatureNames();
for(VecS::const_iterator itr = names.begin();
itr != names.end();
++itr) {
string n = *itr;
VecMat feats = this->operator [](n);
d[n] = toPythonList(feats);
}
return d;
} |
<?php defined('SYSPATH') or die('No direct script access');
class <API key> extends Controller {
public function action_delete()
{
// validate
if (!$this->request->param('id')) return false;
// load hte object
$portfolio = ORM::factory('portfolio')->where('id', '=', $this->request->param('id'))->find();
$portfolio->deleted = time();
$portfolio->save();
echo ($portfolio);
}
public function action_category()
{
$mode = ($this->request->param('id')) ? 'edit' : 'add';
switch($mode) {
case 'edit':
$cat = ORM::factory('portfolio_category')->where('id', '=', $this->request->param('id'))->find();
break;
case 'add':
$cat = ORM::factory('portfolio_category');
}
$cat->category = $this->request->post('category');
$cat->portfolio_id = $this->request->post('portfolio_id');
$cat->save();
echo ($cat);
}
public function action_work()
{
$mode = ($this->request->param('id')) ? 'edit' : 'add';
// params
$now = time();
// load the work object
$work = ORM::factory('portfolio_work');
switch($mode) {
case 'edit':
$work->where('id', '=', $this->request->param('id'))->find();
break;
case 'add':
// set and save
$work->name = $this->request->post('name');
$work->description = $this->request->post('description');
$work->date = $this->request->post('date');
$work->created = $now;
$work->modified = $now;
if ($work->save()) {
echo "true";
}
break;
}
}
public function action_edit()
{
// set up the switch input
$mode = ($this->request->param('id')) ? 'edit' : 'add';
$interfaces_add_work = array();
// load the orm objects
switch($mode) {
case 'add':
$portfolio = ORM::factory('portfolio');
break;
case 'edit':
$portfolio = ORM::factory('portfolio', $this->request->param('id'));
}
$fields = array(
'name' => 'text'
);
$settings_fields = array(
);
if ($this->request->method() == 'POST') {
// validate
// define the settings array
$settings = $this->request->post('settings');
// load hte settings object
$portfolio_settings = $portfolio->settings->find_all();
$now = time();
switch($mode) {
case 'add':
$portfolio->name = $this->request->post('name');
$portfolio->created = $now;
$portfolio->modified = $now;
$portfolio->save();
// update the settings
Model_Portfolio::settings($settings);
break;
case 'edit':
$portfolio->name = $this->request->post('name');
$portfolio->modified = $now;
$portfolio->save();
break;
}
}
switch($mode) {
case'add':
// bind it to the template
$this->template->content = View::factory('back/portfolio/edit')
->bind('title', $title)
->set('settings', $portfolio->settings->find_all())
->set('settings_fields', $settings_fields)
->bind('mode', $mode)
->set('fields', $fields);
break;
case 'edit':
// set the interface params
foreach($portfolio->categories->find_all() as $category) {
$interfaces_add_work[$category->id] = View::factory('back/portfolio/interfaces/work')
->set('category', $category);
$<API key>[$category->id] = View::factory('back/portfolio/interfaces/category')
->set('category', $category);
}
$this->template->content = View::factory('back/portfolio/edit')
->bind('title', $title)
->set('fields', $fields)
->set('settings', $portfolio->settings->find_all())
->set('settings_fields', $settings_fields)
->set('<API key>', $portfolio->categories->find_all())
->set('interfaces_add_work', $interfaces_add_work)
->set('<API key>', $<API key>)
->set('totalcategories', $portfolio->categories->count_all())
->bind('mode', $mode)
->set('portfolio', $portfolio);
break;
}
}
} |
*> \brief \b CLA_GBRFSX_EXTENDED
*
* =========== DOCUMENTATION ===========
*
* Online html documentation available at
* http:
*
*> \htmlonly
*> Download CLA_GBRFSX_EXTENDED + dependencies
*> <a href="http:
*> [TGZ]</a>
*> <a href="http:
*> [ZIP]</a>
*> <a href="http:
*> [TXT]</a>
*> \endhtmlonly
*
* Definition:
* ===========
*
* SUBROUTINE CLA_GBRFSX_EXTENDED ( PREC_TYPE, TRANS_TYPE, N, KL, KU,
* NRHS, AB, LDAB, AFB, LDAFB, IPIV,
* COLEQU, C, B, LDB, Y, LDY,
* BERR_OUT, N_NORMS, ERR_BNDS_NORM,
* ERR_BNDS_COMP, RES, AYB, DY,
* Y_TAIL, RCOND, ITHRESH, RTHRESH,
* DZ_UB, IGNORE_CWISE, INFO )
*
* .. Scalar Arguments ..
* INTEGER INFO, LDAB, LDAFB, LDB, LDY, N, KL, KU, NRHS,
* $ PREC_TYPE, TRANS_TYPE, N_NORMS, ITHRESH
* LOGICAL COLEQU, IGNORE_CWISE
* REAL RTHRESH, DZ_UB
* ..
* .. Array Arguments ..
* INTEGER IPIV( * )
* COMPLEX AB( LDAB, * ), AFB( LDAFB, * ), B( LDB, * ),
* $ Y( LDY, * ), RES( * ), DY( * ), Y_TAIL( * )
* REAL C( * ), AYB(*), RCOND, BERR_OUT( * ),
* $ ERR_BNDS_NORM( NRHS, * ),
* $ ERR_BNDS_COMP( NRHS, * )
* ..
*
*
*> \par Purpose:
* =============
*>
*> \verbatim
*>
*> CLA_GBRFSX_EXTENDED improves the computed solution to a system of
*> linear equations by performing extra-precise iterative refinement
*> and provides error bounds and backward error estimates for the solution.
*> This subroutine is called by CGBRFSX to perform iterative refinement.
*> In addition to normwise error bound, the code provides maximum
*> componentwise error bound if possible. See comments for ERR_BNDS_NORM
*> and ERR_BNDS_COMP for details of the error bounds. Note that this
*> subroutine is only resonsible for setting the second fields of
*> ERR_BNDS_NORM and ERR_BNDS_COMP.
*> \endverbatim
*
* Arguments:
* ==========
*
*> \param[in] PREC_TYPE
*> \verbatim
*> PREC_TYPE is INTEGER
*> Specifies the intermediate precision to be used in refinement.
*> The value is defined by ILAPREC(P) where P is a CHARACTER and
*> P = 'S': Single
*> = 'D': Double
*> = 'I': Indigenous
*> = 'X', 'E': Extra
*> \endverbatim
*>
*> \param[in] TRANS_TYPE
*> \verbatim
*> TRANS_TYPE is INTEGER
*> Specifies the transposition operation on A.
*> The value is defined by ILATRANS(T) where T is a CHARACTER and
*> T = 'N': No transpose
*> = 'T': Transpose
*> = 'C': Conjugate transpose
*> \endverbatim
*>
*> \param[in] N
*> \verbatim
*> N is INTEGER
*> The number of linear equations, i.e., the order of the
*> matrix A. N >= 0.
*> \endverbatim
*>
*> \param[in] KL
*> \verbatim
*> KL is INTEGER
*> The number of subdiagonals within the band of A. KL >= 0.
*> \endverbatim
*>
*> \param[in] KU
*> \verbatim
*> KU is INTEGER
*> The number of superdiagonals within the band of A. KU >= 0
*> \endverbatim
*>
*> \param[in] NRHS
*> \verbatim
*> NRHS is INTEGER
*> The number of right-hand-sides, i.e., the number of columns of the
*> matrix B.
*> \endverbatim
*>
*> \param[in] AB
*> \verbatim
*> AB is COMPLEX array, dimension (LDAB,N)
*> On entry, the N-by-N matrix AB.
*> \endverbatim
*>
*> \param[in] LDAB
*> \verbatim
*> LDAB is INTEGER
*> The leading dimension of the array AB. LDAB >= max(1,N).
*> \endverbatim
*>
*> \param[in] AFB
*> \verbatim
*> AFB is COMPLEX array, dimension (LDAF,N)
*> The factors L and U from the factorization
*> A = P*L*U as computed by CGBTRF.
*> \endverbatim
*>
*> \param[in] LDAFB
*> \verbatim
*> LDAFB is INTEGER
*> The leading dimension of the array AF. LDAF >= max(1,N).
*> \endverbatim
*>
*> \param[in] IPIV
*> \verbatim
*> IPIV is INTEGER array, dimension (N)
*> The pivot indices from the factorization A = P*L*U
*> as computed by CGBTRF; row i of the matrix was interchanged
*> with row IPIV(i).
*> \endverbatim
*>
*> \param[in] COLEQU
*> \verbatim
*> COLEQU is LOGICAL
*> If .TRUE. then column equilibration was done to A before calling
*> this routine. This is needed to compute the solution and error
*> bounds correctly.
*> \endverbatim
*>
*> \param[in] C
*> \verbatim
*> C is REAL array, dimension (N)
*> The column scale factors for A. If COLEQU = .FALSE., C
*> is not accessed. If C is input, each element of C should be a power
*> of the radix to ensure a reliable solution and error estimates.
*> Scaling by powers of the radix does not cause rounding errors unless
*> the result underflows or overflows. Rounding errors during scaling
*> lead to refining with a matrix that is not equivalent to the
*> input matrix, producing error estimates that may not be
*> reliable.
*> \endverbatim
*>
*> \param[in] B
*> \verbatim
*> B is COMPLEX array, dimension (LDB,NRHS)
*> The right-hand-side matrix B.
*> \endverbatim
*>
*> \param[in] LDB
*> \verbatim
*> LDB is INTEGER
*> The leading dimension of the array B. LDB >= max(1,N).
*> \endverbatim
*>
*> \param[in,out] Y
*> \verbatim
*> Y is COMPLEX array, dimension (LDY,NRHS)
*> On entry, the solution matrix X, as computed by CGBTRS.
*> On exit, the improved solution matrix Y.
*> \endverbatim
*>
*> \param[in] LDY
*> \verbatim
*> LDY is INTEGER
*> The leading dimension of the array Y. LDY >= max(1,N).
*> \endverbatim
*>
*> \param[out] BERR_OUT
*> \verbatim
*> BERR_OUT is REAL array, dimension (NRHS)
*> On exit, BERR_OUT(j) contains the componentwise relative backward
*> error for right-hand-side j from the formula
*> max(i) ( abs(RES(i)) / ( abs(op(A_s))*abs(Y) + abs(B_s) )(i) )
*> where abs(Z) is the componentwise absolute value of the matrix
*> or vector Z. This is computed by CLA_LIN_BERR.
*> \endverbatim
*>
*> \param[in] N_NORMS
*> \verbatim
*> N_NORMS is INTEGER
*> Determines which error bounds to return (see ERR_BNDS_NORM
*> and ERR_BNDS_COMP).
*> If N_NORMS >= 1 return normwise error bounds.
*> If N_NORMS >= 2 return componentwise error bounds.
*> \endverbatim
*>
*> \param[in,out] ERR_BNDS_NORM
*> \verbatim
*> ERR_BNDS_NORM is REAL array, dimension
*> (NRHS, N_ERR_BNDS)
*> For each right-hand side, this array contains information about
*> various error bounds and condition numbers corresponding to the
*> normwise relative error, which is defined as follows:
*>
*> Normwise relative error in the ith solution vector:
*> max_j (abs(XTRUE(j,i) - X(j,i)))
*>
*> max_j abs(X(j,i))
*>
*> The array is indexed by the type of error information as described
*> below. There currently are up to three pieces of information
*> returned.
*>
*> The first index in ERR_BNDS_NORM(i,:) corresponds to the ith
*> right-hand side.
*>
*> The second index in ERR_BNDS_NORM(:,err) contains the following
*> three fields:
*> err = 1 "Trust/don't trust" boolean. Trust the answer if the
*> reciprocal condition number is less than the threshold
*> sqrt(n) * slamch('Epsilon').
*>
*> err = 2 "Guaranteed" error bound: The estimated forward error,
*> almost certainly within a factor of 10 of the true error
*> so long as the next entry is greater than the threshold
*> sqrt(n) * slamch('Epsilon'). This error bound should only
*> be trusted if the previous boolean is true.
*>
*> err = 3 Reciprocal condition number: Estimated normwise
*> reciprocal condition number. Compared with the threshold
*> sqrt(n) * slamch('Epsilon') to determine if the error
*> estimate is "guaranteed". These reciprocal condition
*> numbers are 1 / (norm(Z^{-1},inf) * norm(Z,inf)) for some
*> appropriately scaled matrix Z.
*> Let Z = S*A, where S scales each row by a power of the
*> radix so all absolute row sums of Z are approximately 1.
*>
*> This subroutine is only responsible for setting the second field
*> above.
*> See Lapack Working Note 165 for further details and extra
*> cautions.
*> \endverbatim
*>
*> \param[in,out] ERR_BNDS_COMP
*> \verbatim
*> ERR_BNDS_COMP is REAL array, dimension
*> (NRHS, N_ERR_BNDS)
*> For each right-hand side, this array contains information about
*> various error bounds and condition numbers corresponding to the
*> componentwise relative error, which is defined as follows:
*>
*> Componentwise relative error in the ith solution vector:
*> abs(XTRUE(j,i) - X(j,i))
*> max_j
*> abs(X(j,i))
*>
*> The array is indexed by the right-hand side i (on which the
*> componentwise relative error depends), and the type of error
*> information as described below. There currently are up to three
*> pieces of information returned for each right-hand side. If
*> componentwise accuracy is not requested (PARAMS(3) = 0.0), then
*> ERR_BNDS_COMP is not accessed. If N_ERR_BNDS .LT. 3, then at most
*> the first (:,N_ERR_BNDS) entries are returned.
*>
*> The first index in ERR_BNDS_COMP(i,:) corresponds to the ith
*> right-hand side.
*>
*> The second index in ERR_BNDS_COMP(:,err) contains the following
*> three fields:
*> err = 1 "Trust/don't trust" boolean. Trust the answer if the
*> reciprocal condition number is less than the threshold
*> sqrt(n) * slamch('Epsilon').
*>
*> err = 2 "Guaranteed" error bound: The estimated forward error,
*> almost certainly within a factor of 10 of the true error
*> so long as the next entry is greater than the threshold
*> sqrt(n) * slamch('Epsilon'). This error bound should only
*> be trusted if the previous boolean is true.
*>
*> err = 3 Reciprocal condition number: Estimated componentwise
*> reciprocal condition number. Compared with the threshold
*> sqrt(n) * slamch('Epsilon') to determine if the error
*> estimate is "guaranteed". These reciprocal condition
*> numbers are 1 / (norm(Z^{-1},inf) * norm(Z,inf)) for some
*> appropriately scaled matrix Z.
*> Let Z = S*(A*diag(x)), where x is the solution for the
*> current right-hand side and S scales each row of
*> A*diag(x) by a power of the radix so all absolute row
*> sums of Z are approximately 1.
*>
*> This subroutine is only responsible for setting the second field
*> above.
*> See Lapack Working Note 165 for further details and extra
*> cautions.
*> \endverbatim
*>
*> \param[in] RES
*> \verbatim
*> RES is COMPLEX array, dimension (N)
*> Workspace to hold the intermediate residual.
*> \endverbatim
*>
*> \param[in] AYB
*> \verbatim
*> AYB is REAL array, dimension (N)
*> Workspace.
*> \endverbatim
*>
*> \param[in] DY
*> \verbatim
*> DY is COMPLEX array, dimension (N)
*> Workspace to hold the intermediate solution.
*> \endverbatim
*>
*> \param[in] Y_TAIL
*> \verbatim
*> Y_TAIL is COMPLEX array, dimension (N)
*> Workspace to hold the trailing bits of the intermediate solution.
*> \endverbatim
*>
*> \param[in] RCOND
*> \verbatim
*> RCOND is REAL
*> Reciprocal scaled condition number. This is an estimate of the
*> reciprocal Skeel condition number of the matrix A after
*> equilibration (if done). If this is less than the machine
*> precision (in particular, if it is zero), the matrix is singular
*> to working precision. Note that the error may still be small even
*> if this number is very small and the matrix appears ill-
*> conditioned.
*> \endverbatim
*>
*> \param[in] ITHRESH
*> \verbatim
*> ITHRESH is INTEGER
*> The maximum number of residual computations allowed for
*> refinement. The default is 10. For 'aggressive' set to 100 to
*> permit convergence using approximate factorizations or
*> factorizations other than LU. If the factorization uses a
*> technique other than Gaussian elimination, the guarantees in
*> ERR_BNDS_NORM and ERR_BNDS_COMP may no longer be trustworthy.
*> \endverbatim
*>
*> \param[in] RTHRESH
*> \verbatim
*> RTHRESH is REAL
*> Determines when to stop refinement if the error estimate stops
*> decreasing. Refinement will stop when the next solution no longer
*> satisfies norm(dx_{i+1}) < RTHRESH * norm(dx_i) where norm(Z) is
*> the infinity norm of Z. RTHRESH satisfies 0 < RTHRESH <= 1. The
*> default value is 0.5. For 'aggressive' set to 0.9 to permit
*> convergence on extremely ill-conditioned matrices. See LAWN 165
*> for more details.
*> \endverbatim
*>
*> \param[in] DZ_UB
*> \verbatim
*> DZ_UB is REAL
*> Determines when to start considering componentwise convergence.
*> Componentwise convergence is only considered after each component
*> of the solution Y is stable, which we definte as the relative
*> change in each component being less than DZ_UB. The default value
*> is 0.25, requiring the first bit to be stable. See LAWN 165 for
*> more details.
*> \endverbatim
*>
*> \param[in] IGNORE_CWISE
*> \verbatim
*> IGNORE_CWISE is LOGICAL
*> If .TRUE. then ignore componentwise convergence. Default value
*> is .FALSE..
*> \endverbatim
*>
*> \param[out] INFO
*> \verbatim
*> INFO is INTEGER
*> = 0: Successful exit.
*> < 0: if INFO = -i, the ith argument to CGBTRS had an illegal
*> value
*> \endverbatim
*
* Authors:
* ========
*
*> \author Univ. of Tennessee
*> \author Univ. of California Berkeley
*> \author Univ. of Colorado Denver
*> \author NAG Ltd.
*
*> \date November 2011
*
*> \ingroup <API key>
*
* =====================================================================
SUBROUTINE CLA_GBRFSX_EXTENDED ( PREC_TYPE, TRANS_TYPE, N, KL, KU,
$ NRHS, AB, LDAB, AFB, LDAFB, IPIV,
$ COLEQU, C, B, LDB, Y, LDY,
$ BERR_OUT, N_NORMS, ERR_BNDS_NORM,
$ ERR_BNDS_COMP, RES, AYB, DY,
$ Y_TAIL, RCOND, ITHRESH, RTHRESH,
$ DZ_UB, IGNORE_CWISE, INFO )
*
* -- LAPACK computational routine (version 3.4.0) --
* -- LAPACK is a software package provided by Univ. of Tennessee, --
* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
* November 2011
*
* .. Scalar Arguments ..
INTEGER INFO, LDAB, LDAFB, LDB, LDY, N, KL, KU, NRHS,
$ PREC_TYPE, TRANS_TYPE, N_NORMS, ITHRESH
LOGICAL COLEQU, IGNORE_CWISE
REAL RTHRESH, DZ_UB
* ..
* .. Array Arguments ..
INTEGER IPIV( * )
COMPLEX AB( LDAB, * ), AFB( LDAFB, * ), B( LDB, * ),
$ Y( LDY, * ), RES( * ), DY( * ), Y_TAIL( * )
REAL C( * ), AYB(*), RCOND, BERR_OUT( * ),
$ ERR_BNDS_NORM( NRHS, * ),
$ ERR_BNDS_COMP( NRHS, * )
* ..
*
* =====================================================================
*
* .. Local Scalars ..
CHARACTER TRANS
INTEGER CNT, I, J, M, X_STATE, Z_STATE, Y_PREC_STATE
REAL YK, DYK, YMIN, NORMY, NORMX, NORMDX, DXRAT,
$ DZRAT, PREVNORMDX, PREV_DZ_Z, DXRATMAX,
$ DZRATMAX, DX_X, DZ_Z, FINAL_DX_X, FINAL_DZ_Z,
$ EPS, HUGEVAL, INCR_THRESH
LOGICAL INCR_PREC
COMPLEX ZDUM
* ..
* .. Parameters ..
INTEGER UNSTABLE_STATE, WORKING_STATE, CONV_STATE,
$ NOPROG_STATE, BASE_RESIDUAL, EXTRA_RESIDUAL,
$ EXTRA_Y
PARAMETER ( UNSTABLE_STATE = 0, WORKING_STATE = 1,
$ CONV_STATE = 2, NOPROG_STATE = 3 )
PARAMETER ( BASE_RESIDUAL = 0, EXTRA_RESIDUAL = 1,
$ EXTRA_Y = 2 )
INTEGER FINAL_NRM_ERR_I, FINAL_CMP_ERR_I, BERR_I
INTEGER RCOND_I, NRM_RCOND_I, NRM_ERR_I, CMP_RCOND_I
INTEGER CMP_ERR_I, PIV_GROWTH_I
PARAMETER ( FINAL_NRM_ERR_I = 1, FINAL_CMP_ERR_I = 2,
$ BERR_I = 3 )
PARAMETER ( RCOND_I = 4, NRM_RCOND_I = 5, NRM_ERR_I = 6 )
PARAMETER ( CMP_RCOND_I = 7, CMP_ERR_I = 8,
$ PIV_GROWTH_I = 9 )
INTEGER LA_LINRX_ITREF_I, LA_LINRX_ITHRESH_I,
$ LA_LINRX_CWISE_I
PARAMETER ( LA_LINRX_ITREF_I = 1,
$ LA_LINRX_ITHRESH_I = 2 )
PARAMETER ( LA_LINRX_CWISE_I = 3 )
INTEGER LA_LINRX_TRUST_I, LA_LINRX_ERR_I,
$ LA_LINRX_RCOND_I
PARAMETER ( LA_LINRX_TRUST_I = 1, LA_LINRX_ERR_I = 2 )
PARAMETER ( LA_LINRX_RCOND_I = 3 )
* ..
* .. External Subroutines ..
EXTERNAL CAXPY, CCOPY, CGBTRS, CGBMV, BLAS_CGBMV_X,
$ BLAS_CGBMV2_X, CLA_GBAMV, CLA_WWADDW, SLAMCH,
$ CHLA_TRANSTYPE, CLA_LIN_BERR
REAL SLAMCH
CHARACTER CHLA_TRANSTYPE
* ..
* .. Intrinsic Functions..
INTRINSIC ABS, MAX, MIN
* ..
* .. Statement Functions ..
REAL CABS1
* ..
* .. Statement Function Definitions ..
CABS1( ZDUM ) = ABS( REAL( ZDUM ) ) + ABS( AIMAG( ZDUM ) )
* ..
* .. Executable Statements ..
*
IF (INFO.NE.0) RETURN
TRANS = CHLA_TRANSTYPE(TRANS_TYPE)
EPS = SLAMCH( 'Epsilon' )
HUGEVAL = SLAMCH( 'Overflow' )
* Force HUGEVAL to Inf
HUGEVAL = HUGEVAL * HUGEVAL
* Using HUGEVAL may lead to spurious underflows.
INCR_THRESH = REAL( N ) * EPS
M = KL+KU+1
DO J = 1, NRHS
Y_PREC_STATE = EXTRA_RESIDUAL
IF ( Y_PREC_STATE .EQ. EXTRA_Y ) then
DO I = 1, N
Y_TAIL( I ) = 0.0
END DO
END IF
DXRAT = 0.0E+0
DXRATMAX = 0.0E+0
DZRAT = 0.0E+0
DZRATMAX = 0.0E+0
FINAL_DX_X = HUGEVAL
FINAL_DZ_Z = HUGEVAL
PREVNORMDX = HUGEVAL
PREV_DZ_Z = HUGEVAL
DZ_Z = HUGEVAL
DX_X = HUGEVAL
X_STATE = WORKING_STATE
Z_STATE = UNSTABLE_STATE
INCR_PREC = .FALSE.
DO CNT = 1, ITHRESH
*
* Compute residual RES = B_s - op(A_s) * Y,
* op(A) = A, A**T, or A**H depending on TRANS (and type).
*
CALL CCOPY( N, B( 1, J ), 1, RES, 1 )
IF ( Y_PREC_STATE .EQ. BASE_RESIDUAL ) THEN
CALL CGBMV( TRANS, M, N, KL, KU, (-1.0E+0,0.0E+0), AB,
$ LDAB, Y( 1, J ), 1, (1.0E+0,0.0E+0), RES, 1 )
ELSE IF ( Y_PREC_STATE .EQ. EXTRA_RESIDUAL ) THEN
CALL BLAS_CGBMV_X( TRANS_TYPE, N, N, KL, KU,
$ (-1.0E+0,0.0E+0), AB, LDAB, Y( 1, J ), 1,
$ (1.0E+0,0.0E+0), RES, 1, PREC_TYPE )
ELSE
CALL BLAS_CGBMV2_X( TRANS_TYPE, N, N, KL, KU,
$ (-1.0E+0,0.0E+0), AB, LDAB, Y( 1, J ), Y_TAIL, 1,
$ (1.0E+0,0.0E+0), RES, 1, PREC_TYPE )
END IF
! XXX: RES is no longer needed.
CALL CCOPY( N, RES, 1, DY, 1 )
CALL CGBTRS( TRANS, N, KL, KU, 1, AFB, LDAFB, IPIV, DY, N,
$ INFO )
*
* Calculate relative changes DX_X, DZ_Z and ratios DXRAT, DZRAT.
*
NORMX = 0.0E+0
NORMY = 0.0E+0
NORMDX = 0.0E+0
DZ_Z = 0.0E+0
YMIN = HUGEVAL
DO I = 1, N
YK = CABS1( Y( I, J ) )
DYK = CABS1( DY( I ) )
IF (YK .NE. 0.0) THEN
DZ_Z = MAX( DZ_Z, DYK / YK )
ELSE IF ( DYK .NE. 0.0 ) THEN
DZ_Z = HUGEVAL
END IF
YMIN = MIN( YMIN, YK )
NORMY = MAX( NORMY, YK )
IF ( COLEQU ) THEN
NORMX = MAX( NORMX, YK * C( I ) )
NORMDX = MAX(NORMDX, DYK * C(I))
ELSE
NORMX = NORMY
NORMDX = MAX( NORMDX, DYK )
END IF
END DO
IF ( NORMX .NE. 0.0 ) THEN
DX_X = NORMDX / NORMX
ELSE IF ( NORMDX .EQ. 0.0 ) THEN
DX_X = 0.0
ELSE
DX_X = HUGEVAL
END IF
DXRAT = NORMDX / PREVNORMDX
DZRAT = DZ_Z / PREV_DZ_Z
*
* Check termination criteria.
*
IF (.NOT.IGNORE_CWISE
$ .AND. YMIN*RCOND .LT. INCR_THRESH*NORMY
$ .AND. Y_PREC_STATE .LT. EXTRA_Y )
$ INCR_PREC = .TRUE.
IF ( X_STATE .EQ. NOPROG_STATE .AND. DXRAT .LE. RTHRESH )
$ X_STATE = WORKING_STATE
IF ( X_STATE .EQ. WORKING_STATE ) THEN
IF ( DX_X .LE. EPS ) THEN
X_STATE = CONV_STATE
ELSE IF ( DXRAT .GT. RTHRESH ) THEN
IF ( Y_PREC_STATE .NE. EXTRA_Y ) THEN
INCR_PREC = .TRUE.
ELSE
X_STATE = NOPROG_STATE
END IF
ELSE
IF ( DXRAT .GT. DXRATMAX ) DXRATMAX = DXRAT
END IF
IF ( X_STATE .GT. WORKING_STATE ) FINAL_DX_X = DX_X
END IF
IF ( Z_STATE .EQ. UNSTABLE_STATE .AND. DZ_Z .LE. DZ_UB )
$ Z_STATE = WORKING_STATE
IF ( Z_STATE .EQ. NOPROG_STATE .AND. DZRAT .LE. RTHRESH )
$ Z_STATE = WORKING_STATE
IF ( Z_STATE .EQ. WORKING_STATE ) THEN
IF ( DZ_Z .LE. EPS ) THEN
Z_STATE = CONV_STATE
ELSE IF ( DZ_Z .GT. DZ_UB ) THEN
Z_STATE = UNSTABLE_STATE
DZRATMAX = 0.0
FINAL_DZ_Z = HUGEVAL
ELSE IF ( DZRAT .GT. RTHRESH ) THEN
IF ( Y_PREC_STATE .NE. EXTRA_Y ) THEN
INCR_PREC = .TRUE.
ELSE
Z_STATE = NOPROG_STATE
END IF
ELSE
IF ( DZRAT .GT. DZRATMAX ) DZRATMAX = DZRAT
END IF
IF ( Z_STATE .GT. WORKING_STATE ) FINAL_DZ_Z = DZ_Z
END IF
*
* Exit if both normwise and componentwise stopped working,
* but if componentwise is unstable, let it go at least two
* iterations.
*
IF ( X_STATE.NE.WORKING_STATE ) THEN
IF ( IGNORE_CWISE ) GOTO 666
IF ( Z_STATE.EQ.NOPROG_STATE .OR. Z_STATE.EQ.CONV_STATE )
$ GOTO 666
IF ( Z_STATE.EQ.UNSTABLE_STATE .AND. CNT.GT.1 ) GOTO 666
END IF
IF ( INCR_PREC ) THEN
INCR_PREC = .FALSE.
Y_PREC_STATE = Y_PREC_STATE + 1
DO I = 1, N
Y_TAIL( I ) = 0.0
END DO
END IF
PREVNORMDX = NORMDX
PREV_DZ_Z = DZ_Z
*
* Update soluton.
*
IF ( Y_PREC_STATE .LT. EXTRA_Y ) THEN
CALL CAXPY( N, (1.0E+0,0.0E+0), DY, 1, Y(1,J), 1 )
ELSE
CALL CLA_WWADDW( N, Y(1,J), Y_TAIL, DY )
END IF
END DO
* Target of "IF (Z_STOP .AND. X_STOP)". Sun's f77 won't EXIT.
666 CONTINUE
*
* Set final_* when cnt hits ithresh.
*
IF ( X_STATE .EQ. WORKING_STATE ) FINAL_DX_X = DX_X
IF ( Z_STATE .EQ. WORKING_STATE ) FINAL_DZ_Z = DZ_Z
*
* Compute error bounds.
*
IF ( N_NORMS .GE. 1 ) THEN
ERR_BNDS_NORM( J, LA_LINRX_ERR_I ) =
$ FINAL_DX_X / (1 - DXRATMAX)
END IF
IF ( N_NORMS .GE. 2 ) THEN
ERR_BNDS_COMP( J, LA_LINRX_ERR_I ) =
$ FINAL_DZ_Z / (1 - DZRATMAX)
END IF
*
* Compute componentwise relative backward error from formula
* max(i) ( abs(R(i)) / ( abs(op(A_s))*abs(Y) + abs(B_s) )(i) )
* where abs(Z) is the componentwise absolute value of the matrix
* or vector Z.
*
* Compute residual RES = B_s - op(A_s) * Y,
* op(A) = A, A**T, or A**H depending on TRANS (and type).
*
CALL CCOPY( N, B( 1, J ), 1, RES, 1 )
CALL CGBMV( TRANS, N, N, KL, KU, (-1.0E+0,0.0E+0), AB, LDAB,
$ Y(1,J), 1, (1.0E+0,0.0E+0), RES, 1 )
DO I = 1, N
AYB( I ) = CABS1( B( I, J ) )
END DO
*
* Compute abs(op(A_s))*abs(Y) + abs(B_s).
*
CALL CLA_GBAMV( TRANS_TYPE, N, N, KL, KU, 1.0E+0,
$ AB, LDAB, Y(1, J), 1, 1.0E+0, AYB, 1 )
CALL CLA_LIN_BERR( N, N, 1, RES, AYB, BERR_OUT( J ) )
*
* End of loop for each RHS.
*
END DO
*
RETURN
END |
<?php
namespace ZendTest\Filter;
use ArrayObject;
use PHPUnit\Framework\TestCase;
use Zend\Filter\Exception;
use Zend\Filter\FilterPluginManager;
use Zend\Filter\Inflector as InflectorFilter;
use Zend\Filter\PregReplace;
use Zend\Filter\StringToLower;
use Zend\Filter\StringToUpper;
use Zend\Filter\Word\CamelCaseToDash;
use Zend\Filter\Word\<API key>;
use Zend\ServiceManager\ServiceManager;
class InflectorTest extends TestCase
{
/**
* @var InflectorFilter
*/
protected $inflector;
/**
* @var FilterPluginManager
*/
protected $broker;
/**
* Sets up the fixture, for example, open a network connection.
* This method is called before a test is executed.
*
* @return void
*/
public function setUp()
{
$this->inflector = new InflectorFilter();
$this->broker = $this->inflector->getPluginManager();
}
public function <API key>()
{
$broker = $this->inflector->getPluginManager();
$this->assertInstanceOf('Zend\Filter\FilterPluginManager', $broker);
}
public function <API key>()
{
$defaultManager = $this->inflector->getPluginManager();
$manager = new FilterPluginManager(new ServiceManager());
$this->inflector->setPluginManager($manager);
$receivedManager = $this->inflector->getPluginManager();
$this->assertNotSame($defaultManager, $receivedManager);
$this->assertSame($manager, $receivedManager);
}
public function <API key>()
{
$this->inflector->setTarget('foo/:bar/:baz');
$this->assertEquals('foo/:bar/:baz', $this->inflector->getTarget());
}
public function <API key>()
{
$this->assertNull($this->inflector->getTarget());
}
public function <API key>()
{
$inflector = new InflectorFilter('foo/:bar/:baz');
$this->assertEquals('foo/:bar/:baz', $inflector->getTarget());
}
public function <API key>()
{
$target = 'foo/:bar/:baz';
$this->inflector->setTargetReference($target);
$this->assertEquals('foo/:bar/:baz', $this->inflector->getTarget());
$target .= '/:bat';
$this->assertEquals('foo/:bar/:baz/:bat', $this->inflector->getTarget());
}
public function <API key>()
{
$rules = $this->inflector->getRules();
$this->assertEquals(0, count($rules));
$this->inflector->setFilterRule('controller', PregReplace::class);
$rules = $this->inflector->getRules('controller');
$this->assertEquals(1, count($rules));
$filter = $rules[0];
$this->assertInstanceOf('Zend\Filter\FilterInterface', $filter);
}
public function <API key>()
{
$rules = $this->inflector->getRules();
$this->assertEquals(0, count($rules));
$filter = new PregReplace();
$this->inflector->setFilterRule('controller', $filter);
$rules = $this->inflector->getRules('controller');
$this->assertEquals(1, count($rules));
$received = $rules[0];
$this->assertInstanceOf('Zend\Filter\FilterInterface', $received);
$this->assertSame($filter, $received);
}
public function <API key>()
{
$rules = $this->inflector->getRules();
$this->assertEquals(0, count($rules));
$this->inflector->setFilterRule('controller', [PregReplace::class, TestAsset\Alpha::class]);
$rules = $this->inflector->getRules('controller');
$this->assertEquals(2, count($rules));
$this->assertInstanceOf('Zend\Filter\FilterInterface', $rules[0]);
$this->assertInstanceOf('Zend\Filter\FilterInterface', $rules[1]);
}
public function <API key>()
{
$rules = $this->inflector->getRules();
$this->assertEquals(0, count($rules));
$this->inflector->setStaticRule('controller', 'foobar');
$rules = $this->inflector->getRules('controller');
$this->assertEquals('foobar', $rules);
}
public function <API key>()
{
$rules = $this->inflector->getRules();
$this->assertEquals(0, count($rules));
$this->inflector->setStaticRule('controller', 'foobar');
$rules = $this->inflector->getRules('controller');
$this->assertEquals('foobar', $rules);
$this->inflector->setStaticRule('controller', 'bazbat');
$rules = $this->inflector->getRules('controller');
$this->assertEquals('bazbat', $rules);
}
public function <API key>()
{
$rule = 'foobar';
$rules = $this->inflector->getRules();
$this->assertEquals(0, count($rules));
$this->inflector-><API key>('controller', $rule);
$rules = $this->inflector->getRules('controller');
$this->assertEquals('foobar', $rules);
$rule .= '/baz';
$rules = $this->inflector->getRules('controller');
$this->assertEquals('foobar/baz', $rules);
}
public function <API key>()
{
$rules = $this->inflector->getRules();
$this->assertEquals(0, count($rules));
$this->inflector->addRules([
':controller' => [PregReplace::class, TestAsset\Alpha::class],
'suffix' => 'phtml',
]);
$rules = $this->inflector->getRules();
$this->assertEquals(2, count($rules));
$this->assertEquals(2, count($rules['controller']));
$this->assertEquals('phtml', $rules['suffix']);
}
public function <API key>()
{
$this->inflector->setStaticRule('some-rules', 'some-value');
$rules = $this->inflector->getRules();
$this->assertEquals(1, count($rules));
$this->inflector->setRules([
':controller' => [PregReplace::class, TestAsset\Alpha::class],
'suffix' => 'phtml',
]);
$rules = $this->inflector->getRules();
$this->assertEquals(2, count($rules));
$this->assertEquals(2, count($rules['controller']));
$this->assertEquals('phtml', $rules['suffix']);
}
public function testGetRule()
{
$this->inflector->setFilterRule(':controller', [TestAsset\Alpha::class, StringToLower::class]);
$this->assertInstanceOf('Zend\Filter\StringToLower', $this->inflector->getRule('controller', 1));
$this->assertFalse($this->inflector->getRule('controller', 2));
}
public function <API key>()
{
$this->inflector
->setTarget(':controller/:action.:suffix')
->addRules([
':controller' => [CamelCaseToDash::class],
':action' => [CamelCaseToDash::class],
'suffix' => 'phtml'
]);
$filter = $this->inflector;
$filtered = $filter([
'controller' => 'FooBar',
'action' => 'bazBat'
]);
$this->assertEquals('Foo-Bar/baz-Bat.phtml', $filtered);
}
public function <API key>()
{
$this->assertEquals(':', $this->inflector-><API key>());
$this->inflector-><API key>('?=');
$this->assertEquals('?=', $this->inflector-><API key>());
}
public function <API key>()
{
$inflector = new InflectorFilter(
'?=##controller/?=##action.?=##suffix',
[
':controller' => [CamelCaseToDash::class],
':action' => [CamelCaseToDash::class],
'suffix' => 'phtml'
],
null,
'?=
);
$filtered = $inflector([
'controller' => 'FooBar',
'action' => 'bazBat'
]);
$this->assertEquals('Foo-Bar/baz-Bat.phtml', $filtered);
}
public function <API key>()
{
$this->assertEquals(':', $this->inflector-><API key>());
$this->inflector-><API key>('?=');
$this->assertEquals('?=', $this->inflector-><API key>());
}
public function <API key>()
{
$this->assertTrue($this->inflector-><API key>());
$this->inflector-><API key>(false);
$this->assertFalse($this->inflector-><API key>());
}
public function <API key>()
{
$inflector = new InflectorFilter(
'?=##controller/?=##action.?=##suffix',
[
':controller' => [CamelCaseToDash::class],
':action' => [CamelCaseToDash::class],
'suffix' => 'phtml'
],
true,
'?=
);
$this->expectException(Exception\RuntimeException::class);
$this-><API key>('perhaps a rule was not satisfied');
$filtered = $inflector(['controller' => 'FooBar']);
}
public function <API key>()
{
$inflector = new InflectorFilter(
'e:\path\to\:controller\:action.:suffix',
[
':controller' => [CamelCaseToDash::class, StringToLower::class],
':action' => [CamelCaseToDash::class],
'suffix' => 'phtml'
],
true,
':'
);
$filtered = $inflector(['controller' => 'FooBar', 'action' => 'MooToo']);
$this->assertEquals($filtered, 'e:\path\to\foo-bar\Moo-Too.phtml');
}
public function getOptions()
{
$options = [
'target' => '$controller/$action.$suffix',
'<API key>' => true,
'<API key>' => '$',
'rules' => [
':controller' => [
'rule1' => <API key>::class,
'rule2' => StringToLower::class,
],
':action' => [
'rule1' => CamelCaseToDash::class,
'rule2' => StringToUpper::class,
],
'suffix' => 'php'
],
];
return $options;
}
/**
* This method returns an ArrayObject instance in place of a
* Zend\Config\Config instance; the two are interchangeable, as inflectors
* consume the more general array or Traversable types.
*
* @return \Traversable
*/
public function getConfig()
{
$options = $this->getOptions();
return new ArrayObject($options);
}
// @<API key>
protected function _testOptions($inflector)
{
// @<API key>
$options = $this->getOptions();
$broker = $inflector->getPluginManager();
$this->assertEquals($options['target'], $inflector->getTarget());
$this->assertInstanceOf('Zend\Filter\FilterPluginManager', $broker);
$this->assertTrue($inflector-><API key>());
$this->assertEquals($options['<API key>'], $inflector-><API key>());
$rules = $inflector->getRules();
foreach (array_values($options['rules'][':controller']) as $key => $rule) {
$class = get_class($rules['controller'][$key]);
$this->assertContains($rule, $class);
}
foreach (array_values($options['rules'][':action']) as $key => $rule) {
$class = get_class($rules['action'][$key]);
$this->assertContains($rule, $class);
}
$this->assertEquals($options['rules']['suffix'], $rules['suffix']);
}
public function <API key>()
{
$config = $this->getConfig();
$inflector = new InflectorFilter();
$inflector->setOptions($config);
$this->_testOptions($inflector);
}
/**
* Added str_replace('\\', '\\\\', ..) to all processedParts values to disable backreferences
*
* @issue ZF-2538 <API key>::filter() fails with all numeric folder on Windows
*/
public function <API key>()
{
$inflector = new InflectorFilter(
':moduleDir' . DIRECTORY_SEPARATOR . ':controller' . DIRECTORY_SEPARATOR . ':action.:suffix',
[
':controller' => [CamelCaseToDash::class, StringToLower::class],
':action' => [CamelCaseToDash::class],
'suffix' => 'phtml'
],
true,
':'
);
$inflector->setStaticRule('moduleDir', 'C:\htdocs\public\cache\00\01\42\app\modules');
$filtered = $inflector([
'controller' => 'FooBar',
'action' => 'MooToo'
]);
$this->assertEquals(
$filtered,
'C:\htdocs\public\cache\00\01\42\app\modules'
. DIRECTORY_SEPARATOR
. 'foo-bar'
. DIRECTORY_SEPARATOR
. 'Moo-Too.phtml'
);
}
/**
* @issue ZF-2522
*/
public function <API key>()
{
$inflector = new InflectorFilter('something', [], false, false);
$this->assertFalse($inflector-><API key>());
$this->assertEquals($inflector-><API key>(), ':');
$inflector = new InflectorFilter('something', [], false, '
}
/**
* @issue ZF-2964
*/
public function <API key>()
{
$inflector = new InflectorFilter('abc');
$inflector->addRules([':foo' => []]);
$this->assertEquals($inflector(['fo' => 'bar']), 'abc');
}
/**
* @issue ZF-7544
*/
public function <API key>()
{
$rules = $this->inflector->getRules();
$this->assertEquals(0, count($rules));
$this->inflector->setFilterRule('controller', PregReplace::class);
$rules = $this->inflector->getRules('controller');
$this->assertEquals(1, count($rules));
$this->inflector->addFilterRule('controller', [TestAsset\Alpha::class, StringToLower::class]);
$rules = $this->inflector->getRules('controller');
$this->assertEquals(3, count($rules));
$this->_context = StringToLower::class;
$this->inflector-><API key>('context', $this->_context);
$this->inflector->addFilterRule('controller', [TestAsset\Alpha::class, StringToLower::class]);
$rules = $this->inflector->getRules('controller');
$this->assertEquals(5, count($rules));
}
/**
* @group ZF-8997
*/
public function <API key>()
{
$options = $this->getOptions();
$inflector = new InflectorFilter($options);
}
/**
* @group ZF-8997
*/
public function <API key>()
{
$options = $this->getOptions();
$inflector = new InflectorFilter();
$inflector->setOptions($options);
$this->_testOptions($inflector);
}
/**
* @group ZF-8997
*/
public function <API key>()
{
$config = $this->getConfig();
$inflector = new InflectorFilter($config);
$this->_testOptions($inflector);
}
/**
* @group ZF-8997
*/
public function <API key>()
{
$config = $this->getConfig();
$inflector = new InflectorFilter();
$inflector->setOptions($config);
$this->_testOptions($inflector);
}
} |
module Utils (
wordCount,
makeBatch,
accuracy
) where
import Control.Arrow ( (&&&) )
import Data.List ( sort, group, reverse, nub )
import Control.Monad ( join )
wordCount :: (Eq a, Ord a) => [a] -> [(a, Int)]
wordCount = map (head &&& length) . group . sort
makeBatch :: Int -> [a] -> [[a]]
makeBatch _ [] = []
makeBatch size xs = let (x, xs') = splitAt size xs in x:makeBatch size xs'
accuracy :: Eq a => [[a]] -> [[a]] -> Float
accuracy pred gold = realToFrac correct / realToFrac (length pred')
where correct = length $ filter (\(p, g) -> p == g) $ zip pred' gold'
pred' = join pred
gold' = join gold |
// <API key>: 2015 C. Ramakrishnan / Illposed Software
// <API key>: 2021 Robin Vobruba <hoijui.quaero@gmail.com>
// <API key>: BSD-3-Clause
package com.illposed.osc.argument.handler;
import com.illposed.osc.argument.OSCMidiMessage;
import com.illposed.osc.OSCParseException;
import com.illposed.osc.<API key>;
import java.util.Random;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class <API key> {
private final Logger log = LoggerFactory.getLogger(<API key>.class);
private static OSCMidiMessage reparse(final OSCMidiMessage orig)
throws <API key>, OSCParseException
{
return <API key>.reparse(
<API key>.INSTANCE,
OSCMidiMessage.NUM_CONTENT_BYTES,
orig);
}
private static void testReparse(final OSCMidiMessage orig)
throws <API key>, OSCParseException
{
Assert.assertEquals(orig, reparse(orig));
}
@Test(expected = <API key>.class)
public void testReparseNull() throws <API key>, OSCParseException {
final OSCMidiMessage orig = null;
Assert.assertEquals(orig, reparse(orig));
}
private static void testContent(final byte[] content) {
OSCMidiMessage.valueOf(content);
}
@Test(expected = <API key>.class)
public void <API key>() {
testContent(new byte[0]);
}
@Test(expected = <API key>.class)
public void testContentBytesOne() {
testContent(new byte[1]);
}
@Test(expected = <API key>.class)
public void testContentBytesTwo() {
testContent(new byte[2]);
}
@Test(expected = <API key>.class)
public void <API key>() {
testContent(new byte[3]);
}
@Test
public void <API key>() {
testContent(new byte[4]);
}
@Test(expected = <API key>.class)
public void <API key>() {
testContent(new byte[5]);
}
@Test
public void testReparseZeros() throws Exception {
testReparse(OSCMidiMessage.valueOf(new byte[] {0, 0, 0, 0}));
}
@Test
public void testReparsePositive() throws Exception {
testReparse(OSCMidiMessage.valueOf(new byte[] {127, 127, 127, 127}));
}
@Test
public void testReparseNegative() throws Exception {
testReparse(OSCMidiMessage.valueOf(new byte[] {-128, -128, -128, -128}));
}
@Test
public void testReparseRandom() throws Exception {
final long contentRandomSeed = new Random().nextLong();
log.debug("{}#testReparseRandom:contentRandomSeed: {}",
<API key>.class.getSimpleName(), contentRandomSeed);
final Random contentRandom = new Random(contentRandomSeed);
final byte[] content = new byte[4];
contentRandom.nextBytes(content);
testReparse(OSCMidiMessage.valueOf(content));
}
} |
module Data.Aeson.TH.Extra where
import Data.Aeson.TH
( defaultOptions
, Options(..)
)
import Data.String.Extra (dropL1)
prefixRemovedOpts :: Int -> Options
prefixRemovedOpts i = defaultOptions {fieldLabelModifier = dropL1 i} |
#!/usr/bin/env python
# Script which demonstrates how to find the best-fit
# parameters of a Voigt line-shape model
# Vog, 26 Mar 2012
import numpy
from matplotlib.pyplot import figure, show, rc
from scipy.special import wofz
from kapteyn import kmpfit
ln2 = numpy.log(2)
def voigt(x, y):
# The Voigt function is also the real part of
# w(z) = exp(-z^2) erfc(iz), the complex probability function,
# which is also known as the Faddeeva function. Scipy has
# implemented this function under the name wofz()
z = x + 1j*y
I = wofz(z).real
return I
def Voigt(nu, alphaD, alphaL, nu_0, A, a=0, b=0):
# The Voigt line shape in terms of its physical parameters
f = numpy.sqrt(ln2)
x = (nu-nu_0)/alphaD * f
y = alphaL/alphaD * f
backg = a + b*nu
V = A*f/(alphaD*numpy.sqrt(numpy.pi)) * voigt(x, y) + backg
return V
def funcV(p, x):
# Compose the Voigt line-shape
alphaD, alphaL, nu_0, I, a, b = p
return Voigt(x, alphaD, alphaL, nu_0, I, a, b)
def funcG(p, x):
# Model function is a gaussian
A, mu, sigma, zerolev = p
return( A * numpy.exp(-(x-mu)*(x-mu)/(2*sigma*sigma)) + zerolev )
def residualsV(p, data):
# Return weighted residuals of Voigt
x, y, err = data
return (y-funcV(p,x)) / err
def residualsG(p, data):
# Return weighted residuals of Gauss
x, y, err = data
return (y-funcG(p,x)) / err
# Data from simulated MUSE cube
x = numpy.array([854.05,854.18,854.31,854.44,854.57,854.7,854.83,854.96,\
855.09,855.22,855.35,855.48,855.61,855.74,855.87,856.0,\
856.13,856.26,856.39,856.52,856.65,856.78,856.91])
y = numpy.array([6.31683382764,6.41273839772,6.43047296256,6.37437933311,\
6.34883451462,6.30711287633,6.24409954622,6.09241716936,\
5.75421549752,5.20381929725,4.18020502292,3.64663145132,\
4.25251198746,5.23945118487,5.76701752096,6.06587703526,\
6.15751018003,6.25985588506,6.35063433647,6.41795488447,\
6.42002335563,6.35883554071,6.36915982142])
N = len(y)
err = numpy.ones(N)
A = -2
alphaD = 0.5
alphaL = 0.5
a = 6
b = 0
nu_0 = 855
p0 = [alphaD, alphaL, nu_0, A, a, b]
# Do the fit
fitter = kmpfit.Fitter(residuals=residualsV, data=(x,y,err))
fitter.parinfo = [{}, {}, {}, {}, {}, {'fixed':True}] # Take zero level fixed in fit
fitter.fit(params0=p0)
print("\n========= Fit results Voigt profile ==========")
print("Initial params:", fitter.params0)
print("Params: ", fitter.params)
print("Iterations: ", fitter.niter)
print("Function ev: ", fitter.nfev)
print("Uncertainties: ", fitter.xerror)
print("dof: ", fitter.dof)
print("chi^2, rchi2: ", fitter.chi2_min, fitter.rchi2_min)
print("stderr: ", fitter.stderr)
print("Status: ", fitter.status)
alphaD, alphaL, nu_0, I, a_back, b_back = fitter.params
c1 = 1.0692
c2 = 0.86639
hwhm = 0.5*(c1*alphaL+numpy.sqrt(c2*alphaL**2+4*alphaD**2))
print("\nFWHM Voigt profile: ", 2*hwhm)
f = numpy.sqrt(ln2)
Y = alphaL/alphaD * f
amp = I/alphaD*numpy.sqrt(ln2/numpy.pi)*voigt(0,Y)
print("Amplitude Voigt profile:", amp)
print("Area under profile: ", I)
# Fit the Gaussian model
p0 = [-3, 855, 0.5, 6.3]
fitterG = kmpfit.Fitter(residuals=residualsG, data=(x,y,err))
#fitterG.parinfo = [{}, {}, {}, {}, {}] # Take zero level fixed in fit
fitterG.fit(params0=p0)
print("\n========= Fit results Gaussian profile ==========")
print("Initial params:", fitterG.params0)
print("Params: ", fitterG.params)
print("Iterations: ", fitterG.niter)
print("Function ev: ", fitterG.nfev)
print("Uncertainties: ", fitterG.xerror)
print("dof: ", fitterG.dof)
print("chi^2, rchi2: ", fitterG.chi2_min, fitterG.rchi2_min)
print("stderr: ", fitterG.stderr)
print("Status: ", fitterG.status)
fwhmG = 2*numpy.sqrt(2*numpy.log(2))*fitterG.params[2]
print("FWHM Gaussian: ", fwhmG)
# Plot the result
rc('legend', fontsize=6)
fig = figure()
frame1 = fig.add_subplot(1,1,1)
xd = numpy.linspace(x.min(), x.max(), 200)
frame1.plot(x, y, 'bo', label="data")
label = "Model with Voigt function"
frame1.plot(xd, funcV(fitter.params,xd), 'g', label=label)
label = "Model with Gaussian function"
frame1.plot(xd, funcG(fitterG.params,xd), 'm', ls='--', label=label)
offset = a_back+b_back*nu_0
frame1.plot((nu_0-hwhm,nu_0+hwhm), (offset+amp/2,offset+amp/2), 'r', label='fwhm')
frame1.plot(xd, a_back+b_back*xd, "y", label='Background')
frame1.set_xlabel("$\\nu$")
frame1.set_ylabel("$\\phi(\\nu)$")
vals = (fitter.chi2_min, fitter.rchi2_min, fitter.dof)
title = "Profile data with Voigt- vs. Gaussian model"
frame1.set_title(title, y=1.05)
frame1.grid(True)
leg = frame1.legend(loc=3)
show() |
<nav class="navbar navbar-static-top navbar-default" role="navigation">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#header">
<span class="sr-only">Toggle navigation</span><span class="icon-bar"></span><span class="icon-bar"></span><span class="icon-bar"></span>
</button> <a class="navbar-brand" href="{% url 'admin:index' %}">Django & React Workshop</a>
</div>
<div class="collapse navbar-collapse" id="header">
<ul class="nav navbar-nav">
</ul>
</div>
</nav> |
# Generated by Django 2.1.7 on 2019-04-26 17:55
from django.db import migrations, models
from scheduler.models import RepeatableJob
from django.utils import timezone
from django_rq import job
@job("short")
def <API key>(apps, schema_editor):
job, created = RepeatableJob.objects.get_or_create(
callable="metaci.testresults.tasks.generate_summaries",
enabled=True,
name="<API key>",
queue="short",
defaults={
"interval": 30,
"interval_unit": "minutes",
"scheduled_time": timezone.now(),
},
)
def <API key>(apps, schema_editor):
RepeatableJob.objects.filter(name="<API key>").delete()
class Migration(migrations.Migration):
atomic = False
dependencies = [("testresults", "<API key>")]
operations = [
migrations.RunPython(
<API key>,
reverse_code=<API key>,
)
] |
package com.cflint;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import cfml.parsing.reporting.ParseException;
import com.cflint.config.CFLintPluginInfo.PluginInfoRule;
import com.cflint.config.CFLintPluginInfo.PluginInfoRule.PluginMessage;
import com.cflint.config.ConfigRuntime;
import com.cflint.plugins.core.VarScoper;
@RunWith(Parameterized.class)
public class <API key> {
final String tagName;
private CFLint cfBugs;
@Before
public void setUp(){
ConfigRuntime conf = new ConfigRuntime();
PluginInfoRule pluginRule = new PluginInfoRule();
pluginRule.setName("VarScoper");
conf.getRules().add(pluginRule);
PluginMessage pluginMessage = new PluginMessage("MISSING_VAR");
pluginMessage.setSeverity("ERROR");
pluginMessage.setMessageText("Variable ${variable} is not declared with a var statement.");
pluginRule.getMessages().add(pluginMessage);
cfBugs = new CFLint(conf,new VarScoper());
}
@Parameterized.Parameters(name = "{0}")
public static Collection primeNumbers() {
return Arrays.asList(new String[][] { new String[] { "CFStoredProc" }, new String[] { "CFQuery" },
new String[] { "CFFeed" }, new String[] { "CFDirectory" }, new String[] { "CFForm" },
new String[] { "CFFtp" }, new String[] { "CFObject" }, new String[] { "CFSearch" },
new String[] { "CFProcResult" }, new String[] { "CFPop" }, new String[] { "CFRegistry" },
new String[] { "CFReport" }, new String[] { "CFDBInfo" }, new String[] { "CFDocument" },
new String[] { "CFCollection" }, new String[] { "CFPdf" }, new String[] { "CFZip" },
new String[] { "CFLdap" } });
// return Arrays.asList(new String[] { new String[]{"CFStoredProc",
// "CFFeed", "CFFtp", "CFObject", "CFSearch",
// "CFProcResult", "CFPop", "CFRegistry", "CFReport", "CFDBInfo",
// "CFDocument", "CFCollection", "CFPdf",
// "CFZip", "CFLdap" });
}
public <API key>(final String tagName) {
super();
this.tagName = tagName;
}
@Test
public void testScope_Name() throws ParseException, IOException {
runTagAttrTest(tagName.toLowerCase(), "name", "xx");
setUp();
runTagAttrTest(tagName, "Name", "xx");
}
@Test
public void testScope_Name_Vard() throws ParseException, IOException {
runTagAttrTestVard(tagName.toLowerCase(), "name", "xx");
setUp();
runTagAttrTestVard(tagName, "Name", "xx");
}
public void runTagAttrTest(final String tag, final String attr, final String variable) throws ParseException,
IOException {
final String cfcSrc = "<cfcomponent>\r\n" + "<cffunction name=\"test\">\r\n" + " <" + tag + " " + attr
+ "=\"" + variable + "\">\r\n" + "</" + tag + ">\r\n" + "</cffunction>\r\n" + "</cfcomponent>";
cfBugs.process(cfcSrc, "test");
assertEquals(1, cfBugs.getBugs().getBugList().size());
List<BugInfo> result = cfBugs.getBugs().getBugList().values().iterator().next();
System.out.println(result);
assertEquals(1, result.size());
assertEquals("MISSING_VAR", result.get(0).getMessageCode());
assertEquals(variable, result.get(0).getVariable());
assertEquals(3, result.get(0).getLine());
assertEquals("test",result.get(0).getFunction());
assertEquals("test",result.get(0).getFilename());
assertEquals("<cfstoredproc name=\"xx\">\r\n</cfstoredproc>".replaceAll("cfstoredproc",tag).replaceAll("name",attr),
result.get(0).getExpression());
}
public void runTagAttrTestVard(final String tag, final String attr, final String variable) throws ParseException,
IOException {
final String cfcSrc = "<cfcomponent>\r\n" +
"<cffunction name=\"test\">\r\n" +
" <cfset var " + variable + "=123/>\r\n" +
" <" + tag + " " + attr + "=\"" + variable + "\">\r\n" +
" </" + tag + ">\r\n" +
"</cffunction>\r\n" + "</cfcomponent>";
cfBugs.process(cfcSrc, "test");
assertEquals(0, cfBugs.getBugs().getBugList().size());
}
} |
// This file is auto-generated from
// gpu/vulkan/generate_bindings.py
// It's formatted by clang-format using chromium coding style:
// clang-format -i -style=chromium filename
// DO NOT EDIT!
#include "gpu/vulkan/<API key>.h"
#include "base/logging.h"
#include "base/no_destructor.h"
namespace gpu {
<API key>* <API key>() {
static base::NoDestructor<<API key>> <API key>;
return <API key>.get();
}
<API key>::<API key>() = default;
<API key>::~<API key>() = default;
bool <API key>::<API key>() {
// <API key> must be handled specially since it gets its function
// pointer through base::<API key>(). Other Vulkan
// functions don't do this.
<API key> = reinterpret_cast<<API key>>(
base::<API key>(<API key>,
"<API key>"));
if (!<API key>)
return false;
<API key> =
reinterpret_cast<<API key>>(
<API key>(nullptr, "<API key>"));
// <API key> didn't exist in Vulkan 1.0, so we should
// proceed even if we fail to get <API key> pointer.
vkCreateInstanceFn = reinterpret_cast<<API key>>(
<API key>(nullptr, "vkCreateInstance"));
if (!vkCreateInstanceFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCreateInstance";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(nullptr,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(nullptr, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
return true;
}
bool <API key>::<API key>(
VkInstance vk_instance,
uint32_t api_version,
const gfx::ExtensionSet& enabled_extensions) {
vkCreateDeviceFn = reinterpret_cast<PFN_vkCreateDevice>(
<API key>(vk_instance, "vkCreateDevice"));
if (!vkCreateDeviceFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCreateDevice";
return false;
}
vkDestroyInstanceFn = reinterpret_cast<<API key>>(
<API key>(vk_instance, "vkDestroyInstance"));
if (!vkDestroyInstanceFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkDestroyInstance";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> = reinterpret_cast<<API key>>(
<API key>(vk_instance, "vkGetDeviceProcAddr"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkGetDeviceProcAddr";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
#if DCHECK_IS_ON()
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // DCHECK_IS_ON()
if (gfx::HasExtension(enabled_extensions, <API key>)) {
<API key> = reinterpret_cast<<API key>>(
<API key>(vk_instance, "vkDestroySurfaceKHR"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkDestroySurfaceKHR";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#if defined(USE_VULKAN_XLIB)
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
<API key> = reinterpret_cast<<API key>>(
<API key>(vk_instance, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(
vk_instance, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(USE_VULKAN_XLIB)
#if defined(OS_WIN)
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
<API key> = reinterpret_cast<<API key>>(
<API key>(vk_instance, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
<API key>(
vk_instance, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(OS_WIN)
#if defined(OS_ANDROID)
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(OS_ANDROID)
#if defined(OS_FUCHSIA)
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(OS_FUCHSIA)
if (api_version >= VK_API_VERSION_1_1) {
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
if (api_version >= VK_API_VERSION_1_1) {
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
} else if (gfx::HasExtension(
enabled_extensions,
<API key>)) {
<API key> =
reinterpret_cast<<API key>>(
<API key>(vk_instance,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
return true;
}
bool <API key>::<API key>(
VkDevice vk_device,
uint32_t api_version,
const gfx::ExtensionSet& enabled_extensions) {
// Device functions
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkAllocateMemoryFn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkAllocateMemory"));
if (!vkAllocateMemoryFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkAllocateMemory";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkBindBufferMemory"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkBindBufferMemory";
return false;
}
vkBindImageMemoryFn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkBindImageMemory"));
if (!vkBindImageMemoryFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkBindImageMemory";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkCmdCopyBufferFn = reinterpret_cast<PFN_vkCmdCopyBuffer>(
vkGetDeviceProcAddr(vk_device, "vkCmdCopyBuffer"));
if (!vkCmdCopyBufferFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCmdCopyBuffer";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkCmdEndRenderPass"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCmdEndRenderPass";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkCmdNextSubpassFn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkCmdNextSubpass"));
if (!vkCmdNextSubpassFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCmdNextSubpass";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkCreateBufferFn = reinterpret_cast<PFN_vkCreateBuffer>(
vkGetDeviceProcAddr(vk_device, "vkCreateBuffer"));
if (!vkCreateBufferFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCreateBuffer";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkCreateCommandPool"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCreateCommandPool";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkCreateFenceFn = reinterpret_cast<PFN_vkCreateFence>(
vkGetDeviceProcAddr(vk_device, "vkCreateFence"));
if (!vkCreateFenceFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCreateFence";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkCreateFramebuffer"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCreateFramebuffer";
return false;
}
vkCreateImageFn = reinterpret_cast<PFN_vkCreateImage>(
vkGetDeviceProcAddr(vk_device, "vkCreateImage"));
if (!vkCreateImageFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCreateImage";
return false;
}
vkCreateImageViewFn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkCreateImageView"));
if (!vkCreateImageViewFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCreateImageView";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkCreateRenderPass"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCreateRenderPass";
return false;
}
vkCreateSamplerFn = reinterpret_cast<PFN_vkCreateSampler>(
vkGetDeviceProcAddr(vk_device, "vkCreateSampler"));
if (!vkCreateSamplerFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCreateSampler";
return false;
}
vkCreateSemaphoreFn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkCreateSemaphore"));
if (!vkCreateSemaphoreFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkCreateSemaphore";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkDestroyBufferFn = reinterpret_cast<PFN_vkDestroyBuffer>(
vkGetDeviceProcAddr(vk_device, "vkDestroyBuffer"));
if (!vkDestroyBufferFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkDestroyBuffer";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkDestroyDeviceFn = reinterpret_cast<PFN_vkDestroyDevice>(
vkGetDeviceProcAddr(vk_device, "vkDestroyDevice"));
if (!vkDestroyDeviceFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkDestroyDevice";
return false;
}
vkDestroyFenceFn = reinterpret_cast<PFN_vkDestroyFence>(
vkGetDeviceProcAddr(vk_device, "vkDestroyFence"));
if (!vkDestroyFenceFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkDestroyFence";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkDestroyImageFn = reinterpret_cast<PFN_vkDestroyImage>(
vkGetDeviceProcAddr(vk_device, "vkDestroyImage"));
if (!vkDestroyImageFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkDestroyImage";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkDestroyImageView"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkDestroyImageView";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkDestroyRenderPass"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkDestroyRenderPass";
return false;
}
vkDestroySamplerFn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkDestroySampler"));
if (!vkDestroySamplerFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkDestroySampler";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkDestroySemaphore"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkDestroySemaphore";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkDeviceWaitIdleFn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkDeviceWaitIdle"));
if (!vkDeviceWaitIdleFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkDeviceWaitIdle";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkEndCommandBuffer"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkEndCommandBuffer";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkFreeMemoryFn = reinterpret_cast<PFN_vkFreeMemory>(
vkGetDeviceProcAddr(vk_device, "vkFreeMemory"));
if (!vkFreeMemoryFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkFreeMemory";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkGetDeviceQueueFn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkGetDeviceQueue"));
if (!vkGetDeviceQueueFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkGetDeviceQueue";
return false;
}
vkGetFenceStatusFn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkGetFenceStatus"));
if (!vkGetFenceStatusFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkGetFenceStatus";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkMapMemoryFn = reinterpret_cast<PFN_vkMapMemory>(
vkGetDeviceProcAddr(vk_device, "vkMapMemory"));
if (!vkMapMemoryFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkMapMemory";
return false;
}
vkQueueSubmitFn = reinterpret_cast<PFN_vkQueueSubmit>(
vkGetDeviceProcAddr(vk_device, "vkQueueSubmit"));
if (!vkQueueSubmitFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkQueueSubmit";
return false;
}
vkQueueWaitIdleFn = reinterpret_cast<PFN_vkQueueWaitIdle>(
vkGetDeviceProcAddr(vk_device, "vkQueueWaitIdle"));
if (!vkQueueWaitIdleFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkQueueWaitIdle";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkResetFencesFn = reinterpret_cast<PFN_vkResetFences>(
vkGetDeviceProcAddr(vk_device, "vkResetFences"));
if (!vkResetFencesFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkResetFences";
return false;
}
vkUnmapMemoryFn = reinterpret_cast<PFN_vkUnmapMemory>(
vkGetDeviceProcAddr(vk_device, "vkUnmapMemory"));
if (!vkUnmapMemoryFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkUnmapMemory";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkWaitForFencesFn = reinterpret_cast<PFN_vkWaitForFences>(
vkGetDeviceProcAddr(vk_device, "vkWaitForFences"));
if (!vkWaitForFencesFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkWaitForFences";
return false;
}
if (api_version >= VK_API_VERSION_1_1) {
vkGetDeviceQueue2Fn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkGetDeviceQueue2"));
if (!vkGetDeviceQueue2Fn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkGetDeviceQueue2";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#if defined(OS_ANDROID)
if (gfx::HasExtension(
enabled_extensions,
<API key>)) {
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(OS_ANDROID)
#if defined(OS_LINUX) || defined(OS_ANDROID)
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkGetSemaphoreFdKHR"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkGetSemaphoreFdKHR";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(OS_LINUX) || defined(OS_ANDROID)
#if defined(OS_WIN)
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(OS_WIN)
#if defined(OS_LINUX) || defined(OS_ANDROID)
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
vkGetMemoryFdKHRFn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkGetMemoryFdKHR"));
if (!vkGetMemoryFdKHRFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkGetMemoryFdKHR";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(OS_LINUX) || defined(OS_ANDROID)
#if defined(OS_WIN)
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(OS_WIN)
#if defined(OS_FUCHSIA)
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(OS_FUCHSIA)
#if defined(OS_FUCHSIA)
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(OS_FUCHSIA)
#if defined(OS_FUCHSIA)
if (gfx::HasExtension(enabled_extensions,
<API key>)) {
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device,
"<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> =
reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
}
#endif // defined(OS_FUCHSIA)
if (gfx::HasExtension(enabled_extensions, <API key>)) {
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
<API key> = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "<API key>"));
if (!<API key>) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "<API key>";
return false;
}
vkQueuePresentKHRFn = reinterpret_cast<<API key>>(
vkGetDeviceProcAddr(vk_device, "vkQueuePresentKHR"));
if (!vkQueuePresentKHRFn) {
DLOG(WARNING) << "Failed to bind vulkan entrypoint: "
<< "vkQueuePresentKHR";
return false;
}
}
return true;
}
} // namespace gpu |
package com.salesforce.keystone.roadrunner;
import com.google.protobuf.Message;
import com.salesforce.keystone.roadrunner.bytes.ByteConverter;
import com.salesforce.keystone.roadrunner.exception.<API key>;
import com.salesforce.keystone.roadrunner.header.RoadRunnerHeader;
import com.salesforce.keystone.roadrunner.msgmapper.MessageMapper;
import com.salesforce.keystone.roadrunner.nio.streams.<API key>;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.io.InputStream;
/**
* Serialize a road runner message from the
*/
public class <API key><T> {
private static final Log LOG = LogFactory.getLog(<API key>.class);
private final ByteConverter<T> converter;
private final MessageMapper mapper;
public <API key>(ByteConverter<T> converter, MessageMapper mapper) {
this.converter = converter;
this.mapper = mapper;
}
/**
* Deserialize the protobuf message in the message body
*
* @param header information about the message
* @param bytes bytes to read. assumed to be in the correct position to read the message body
* (e.g. skipped past the header)
* @return the deserialized message from the bytes, with the bytes incremented past the header
* @throws IOException if the message cannot be read
*/
public Message deserialize(RoadRunnerHeader header, T bytes)
throws IOException {
InputStream is = converter.toInputStream(bytes);
Message.Builder b = mapper.newInstance(header.msgId);
if (b == null) {
// this shouldn't happen unless the mapper returns different results between
// newInstance() and supportsMsgId()
if (LOG.isErrorEnabled()) {
LOG.error("Mapper " + mapper + " returned inconsistent results between " +
"newInstance() & supportsMsgId() this is a bug in the mapper implementation");
}
throw new <API key>(header.msgId);
}
b.clear();
if (mapper.<API key>()) {
b.mergeFrom(is, mapper.<API key>());
} else {
b.mergeFrom(is);
}
Message current = b.build();
if (LOG.isDebugEnabled()) {
LOG.info("received msgId=" + header.msgId + ", type=" + current.getClass()
.getSimpleName() + ", trailerLen=" + header.trailerLength);
}
return current;
}
} |
#!/usr/bin/ruby -w
require 'nokogiri'
require 'open-uri'
# All the documentation pages are attached to this URL
aws_doc_root = 'http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/'
def parse_page(url)
doc = Nokogiri::HTML(open(url))
# Extract the topic from the page
topic = doc.search('//h1[@class="topictitle"]')
h = {}
# properties are in a list (dl) as dt for the key and dd for the content
properties = doc.search('//div[@class="variablelist"]/dl')
properties.search('dt').each do |dt|
property = dt.text
# Let's assume the dd is the next element (risky but seems to work)
dd = dt.next_element
# the dd will have several paragraphs (p resources)
# go through each and find for the one containing the string 'Update requires' |
from django.contrib.auth import get_user_model
from django.views.generic import DetailView
from rest_framework import viewsets
from rest_framework import permissions
from rest_framework.decorators import detail_route, list_route
from rest_framework.response import Response
from .serializers import UserSerializer
class UserProfileView(DetailView):
model = get_user_model()
def get_object(self, queryset=None):
return self.request.user
# ViewSets define the view behavior.
class UserViewSet(viewsets.ModelViewSet):
permission_classes = [permissions.IsAuthenticated, ]
model = get_user_model()
serializer_class = UserSerializer
@list_route(methods=['get', ])
def me(self, request):
serializer = self.get_serializer(request.user)
return Response(serializer.data) |
<?php
namespace com\mohiva\test\elixir\document\expression\nodes;
use com\mohiva\elixir\document\expression\nodes\OperandNode;
use com\mohiva\elixir\document\expression\nodes\<API key>;
class <API key> extends \<API key> {
/**
* Test if the `evaluate` method returns the correct value for the operation.
*/
public function testEvaluate() {
$left = mt_rand(1, 100);
$right = mt_rand(1, 100);
$node = new <API key>(new OperandNode($left), new OperandNode($right));
$this->assertSame($left . ' >= ' . $right, $node->evaluate());
}
} |
import sys # pragma: no cover
from remoteappmanager.command_line_config import (
CommandLineConfig) # pragma: no cover
from remoteappmanager.environment_config import (
EnvironmentConfig) # pragma: no cover
from remoteappmanager.file_config import FileConfig # pragma: no cover
from tornado.options import print_help # pragma: no cover
from remoteappmanager.admin_application import (
AdminApplication) # pragma: no cover
def main(): # pragma: no cover
try:
command_line_config = CommandLineConfig()
command_line_config.parse_config()
file_config = FileConfig()
if command_line_config.config_file:
file_config.parse_config(command_line_config.config_file)
environment_config = EnvironmentConfig()
environment_config.parse_config()
except Exception as e:
print_help()
print("Error: {}".format(e))
sys.exit(1)
app = AdminApplication(
command_line_config,
file_config,
environment_config)
app.start() |
// @ts-nocheck
// TODO(crbug.com/1011811): Enable TypeScript compiler checks
import * as Common from '../common/common.js';
import {HeapProfilerModel} from './HeapProfilerModel.js'; // eslint-disable-line no-unused-vars
import {RuntimeModel} from './RuntimeModel.js';
import {SDKModelObserver, TargetManager} from './SDKModel.js'; // eslint-disable-line no-unused-vars
/**
* @implements {SDKModelObserver}
*/
export class IsolateManager extends Common.ObjectWrapper.ObjectWrapper {
constructor() {
super();
console.assert(!self.SDK.isolateManager, 'Use self.SDK.isolateManager singleton.');
/** @type {!Map<string, !Isolate>} */
this._isolates = new Map();
// _isolateIdByModel contains null while the isolateId is being retrieved.
/** @type {!Map<!RuntimeModel, ?string>} */
this._isolateIdByModel = new Map();
/** @type {!Set<!Observer>} */
this._observers = new Set();
TargetManager.instance().observeModels(RuntimeModel, this);
this._pollId = 0;
}
/**
* @param {!Observer} observer
*/
observeIsolates(observer) {
if (this._observers.has(observer)) {
throw new Error('Observer can only be registered once');
}
if (!this._observers.size) {
this._poll();
}
this._observers.add(observer);
for (const isolate of this._isolates.values()) {
observer.isolateAdded(isolate);
}
}
/**
* @param {!Observer} observer
*/
unobserveIsolates(observer) {
this._observers.delete(observer);
if (!this._observers.size) {
++this._pollId;
} // Stops the current polling loop.
}
/**
* @override
* @param {!RuntimeModel} model
*/
modelAdded(model) {
this._modelAdded(model);
}
/**
* @param {!RuntimeModel} model
*/
async _modelAdded(model) {
this._isolateIdByModel.set(model, null);
const isolateId = await model.isolateId();
if (!this._isolateIdByModel.has(model)) {
// The model has been removed during await.
return;
}
if (!isolateId) {
this._isolateIdByModel.delete(model);
return;
}
this._isolateIdByModel.set(model, isolateId);
let isolate = this._isolates.get(isolateId);
if (!isolate) {
isolate = new Isolate(isolateId);
this._isolates.set(isolateId, isolate);
}
isolate._models.add(model);
if (isolate._models.size === 1) {
for (const observer of this._observers) {
observer.isolateAdded(isolate);
}
} else {
for (const observer of this._observers) {
observer.isolateChanged(isolate);
}
}
}
/**
* @override
* @param {!RuntimeModel} model
*/
modelRemoved(model) {
const isolateId = this._isolateIdByModel.get(model);
this._isolateIdByModel.delete(model);
if (!isolateId) {
return;
}
const isolate = this._isolates.get(isolateId);
isolate._models.delete(model);
if (isolate._models.size) {
for (const observer of this._observers) {
observer.isolateChanged(isolate);
}
return;
}
for (const observer of this._observers) {
observer.isolateRemoved(isolate);
}
this._isolates.delete(isolateId);
}
/**
* @param {!RuntimeModel} model
* @return {?Isolate}
*/
isolateByModel(model) {
return this._isolates.get(this._isolateIdByModel.get(model) || '') || null;
}
/**
* @return {!IteratorIterable<!Isolate>}
*/
isolates() {
return this._isolates.values();
}
async _poll() {
const pollId = this._pollId;
while (pollId === this._pollId) {
await Promise.all(Array.from(this.isolates(), isolate => isolate._update()));
await new Promise(r => setTimeout(r, PollIntervalMs));
}
}
}
/**
* @interface
*/
export class Observer {
/**
* @param {!Isolate} isolate
*/
isolateAdded(isolate) {
}
/**
* @param {!Isolate} isolate
*/
isolateRemoved(isolate) {
}
/**
* @param {!Isolate} isolate
*/
isolateChanged(isolate) {
}
}
/** @enum {symbol} */
export const Events = {
MemoryChanged: Symbol('MemoryChanged')
};
export const MemoryTrendWindowMs = 120e3;
const PollIntervalMs = 2e3;
export class Isolate {
/**
* @param {string} id
*/
constructor(id) {
this._id = id;
/** @type {!Set<!RuntimeModel>} */
this._models = new Set();
this._usedHeapSize = 0;
const count = MemoryTrendWindowMs / PollIntervalMs;
this._memoryTrend = new MemoryTrend(count);
}
/**
* @return {string}
*/
id() {
return this._id;
}
/**
* @return {!Set<!RuntimeModel>}
*/
models() {
return this._models;
}
/**
* @return {?RuntimeModel}
*/
runtimeModel() {
return this._models.values().next().value || null;
}
/**
* @return {?HeapProfilerModel}
*/
heapProfilerModel() {
const runtimeModel = this.runtimeModel();
return runtimeModel && runtimeModel.heapProfilerModel();
}
async _update() {
const model = this.runtimeModel();
const usage = model && await model.heapUsage();
if (!usage) {
return;
}
this._usedHeapSize = usage.usedSize;
this._memoryTrend.add(this._usedHeapSize);
self.SDK.isolateManager.<API key>(Events.MemoryChanged, this);
}
/**
* @return {number}
*/
samplesCount() {
return this._memoryTrend.count();
}
/**
* @return {number}
*/
usedHeapSize() {
return this._usedHeapSize;
}
/**
* @return {number} bytes per millisecond
*/
<API key>() {
return this._memoryTrend.fitSlope();
}
/**
* @return {boolean}
*/
isMainThread() {
return this.runtimeModel().target().id() === 'main';
}
}
/**
* @unrestricted
*/
export class MemoryTrend {
/**
* @param {number} maxCount
*/
constructor(maxCount) {
this._maxCount = maxCount | 0;
this.reset();
}
reset() {
this._base = Date.now();
this._index = 0;
/** @type {!Array<number>} */
this._x = [];
/** @type {!Array<number>} */
this._y = [];
this._sx = 0;
this._sy = 0;
this._sxx = 0;
this._sxy = 0;
}
/**
* @return {number}
*/
count() {
return this._x.length;
}
/**
* @param {number} heapSize
* @param {number=} timestamp
*/
add(heapSize, timestamp) {
const x = typeof timestamp === 'number' ? timestamp : Date.now() - this._base;
const y = heapSize;
if (this._x.length === this._maxCount) {
// Turns into a cyclic buffer once it reaches the |_maxCount|.
const x0 = this._x[this._index];
const y0 = this._y[this._index];
this._sx -= x0;
this._sy -= y0;
this._sxx -= x0 * x0;
this._sxy -= x0 * y0;
}
this._sx += x;
this._sy += y;
this._sxx += x * x;
this._sxy += x * y;
this._x[this._index] = x;
this._y[this._index] = y;
this._index = (this._index + 1) % this._maxCount;
}
/**
* @return {number}
*/
fitSlope() {
// We use the linear regression model to find the slope.
const n = this.count();
return n < 2 ? 0 : (this._sxy - this._sx * this._sy / n) / (this._sxx - this._sx * this._sx / n);
}
} |
package com.esotericsoftware.kryo.serializers;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.<API key>;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.PriorityQueue;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.KryoException;
import com.esotericsoftware.kryo.NotNull;
import com.esotericsoftware.kryo.Registration;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.Util;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.esotericsoftware.kryo.util.ObjectMap;
import com.esotericsoftware.reflectasm.FieldAccess;
import static com.esotericsoftware.minlog.Log.*;
/** Serializes objects using direct field assignment. This is a very fast mechanism for serializing objects, often as good as
* {@link KryoSerializable}. FieldSerializer is many times smaller and faster than Java serialization. The fields should be public
* for optimal performance, which allows bytecode generation to be used instead of reflection.
* <p>
* FieldSerializer does not write header data, only the object data is stored. If the type of a field is not final (note
* primitives are final) then an extra byte is written for that field.
* @see Serializer
* @see Kryo#register(Class, Serializer)
* @author Nathan Sweet <misc@n4te.com> */
public class FieldSerializer extends Serializer {
private final Class type;
private final Kryo kryo;
private CachedField[] fields;
Object access;
private boolean fieldsCanBeNull = true, <API key> = true;
private boolean <API key> = true;
private boolean finalFieldTypes;
public FieldSerializer (Kryo kryo, Class type) {
this.kryo = kryo;
this.type = type;
rebuildCachedFields();
}
protected void rebuildCachedFields () {
if (type.isInterface()) {
fields = new CachedField[0]; // No fields to serialize.
return;
}
// Collect all fields.
ArrayList<Field> allFields = new ArrayList();
Class nextClass = type;
while (nextClass != Object.class) {
Collections.addAll(allFields, nextClass.getDeclaredFields());
nextClass = nextClass.getSuperclass();
}
ObjectMap context = kryo.getContext();
ArrayList<CachedField> asmFields = new ArrayList();
PriorityQueue<CachedField> cachedFields = new PriorityQueue(Math.max(1, allFields.size()), new Comparator<CachedField>() {
public int compare (CachedField o1, CachedField o2) {
// Fields are sorted by alpha so the order of the data is known.
return o1.field.getName().compareTo(o2.field.getName());
}
});
for (int i = 0, n = allFields.size(); i < n; i++) {
Field field = allFields.get(i);
int modifiers = field.getModifiers();
if (Modifier.isTransient(modifiers)) continue;
if (Modifier.isStatic(modifiers)) continue;
if (field.isSynthetic() && <API key>) continue;
if (!field.isAccessible()) {
if (!<API key>) continue;
try {
field.setAccessible(true);
} catch (<API key> ex) {
continue;
}
}
Optional optional = field.getAnnotation(Optional.class);
if (optional != null && !context.containsKey(optional.value())) continue;
Class fieldClass = field.getType();
CachedField cachedField = new CachedField();
cachedField.field = field;
if (fieldsCanBeNull)
cachedField.canBeNull = !fieldClass.isPrimitive() && !field.isAnnotationPresent(NotNull.class);
else
cachedField.canBeNull = false;
// Always use the same serializer for this field if the field's class is final.
if (kryo.isFinal(fieldClass) || finalFieldTypes) cachedField.fieldClass = fieldClass;
cachedFields.add(cachedField);
if (!Modifier.isFinal(modifiers) && Modifier.isPublic(modifiers) && Modifier.isPublic(fieldClass.getModifiers()))
asmFields.add(cachedField);
}
if (!Util.isAndroid && Modifier.isPublic(type.getModifiers()) && !asmFields.isEmpty()) {
// Use ReflectASM for any public fields.
try {
access = FieldAccess.get(type);
for (int i = 0, n = asmFields.size(); i < n; i++) {
CachedField cachedField = asmFields.get(i);
cachedField.accessIndex = ((FieldAccess)access).getIndex(cachedField.field.getName());
}
} catch (RuntimeException ignored) {
}
}
int fieldCount = cachedFields.size();
fields = new CachedField[fieldCount];
for (int i = 0; i < fieldCount; i++)
fields[i] = cachedFields.poll();
}
/** Sets the default value for {@link CachedField#setCanBeNull(boolean)}. Calling this method resets the {@link #getFields()
* cached fields}.
* @param fieldsCanBeNull False if none of the fields are null. Saves 0-1 byte per field. True if it is not known (default). */
public void setFieldsCanBeNull (boolean fieldsCanBeNull) {
this.fieldsCanBeNull = fieldsCanBeNull;
rebuildCachedFields();
}
/** Controls which fields are serialized. Calling this method resets the {@link #getFields() cached fields}.
* @param <API key> If true, all non-transient fields (inlcuding private fields) will be serialized and
* {@link Field#setAccessible(boolean) set as accessible} if necessary (default). If false, only fields in the public
* API will be serialized. */
public void <API key> (boolean <API key>) {
this.<API key> = <API key>;
rebuildCachedFields();
}
/** Controls if synthetic fields are serialized. Default is true. Calling this method resets the {@link #getFields() cached
* fields}.
* @param <API key> If true, only non-synthetic fields will be serialized. */
public void <API key> (boolean <API key>) {
this.<API key> = <API key>;
rebuildCachedFields();
}
/** Sets the default value for {@link CachedField#setClass(Class)} to the field's declared type. This allows FieldSerializer to
* be more efficient, since it knows field values will not be a subclass of their declared type. Default is false. Calling this
* method resets the {@link #getFields() cached fields}. */
public void setFixedFieldTypes (boolean finalFieldTypes) {
this.finalFieldTypes = finalFieldTypes;
rebuildCachedFields();
}
public void write (Kryo kryo, Output output, Object object) {
for (int i = 0, n = fields.length; i < n; i++) {
CachedField cachedField = fields[i];
try {
if (TRACE) trace("kryo", "Write field: " + cachedField + " (" + object.getClass().getName() + ")");
Object value = cachedField.get(object);
Serializer serializer = cachedField.serializer;
if (cachedField.fieldClass == null) {
if (value == null) {
kryo.writeClass(output, null);
continue;
}
Registration registration = kryo.writeClass(output, value.getClass());
if (serializer == null) serializer = registration.getSerializer();
kryo.writeObject(output, value, serializer);
} else {
if (serializer == null) cachedField.serializer = serializer = kryo.getSerializer(cachedField.fieldClass);
if (cachedField.canBeNull) {
kryo.writeObjectOrNull(output, value, serializer);
} else {
if (value == null) {
throw new KryoException("Field value is null but canBeNull is false: " + cachedField + " ("
+ object.getClass().getName() + ")");
}
kryo.writeObject(output, value, serializer);
}
}
} catch (<API key> ex) {
throw new KryoException("Error accessing field: " + cachedField + " (" + object.getClass().getName() + ")", ex);
} catch (KryoException ex) {
ex.addTrace(cachedField + " (" + object.getClass().getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
KryoException ex = new KryoException(runtimeEx);
ex.addTrace(cachedField + " (" + object.getClass().getName() + ")");
throw ex;
}
}
}
public void read (Kryo kryo, Input input, Object object) {
for (int i = 0, n = fields.length; i < n; i++) {
CachedField cachedField = fields[i];
try {
if (TRACE) trace("kryo", "Read field: " + cachedField + " (" + type.getName() + ")");
Object value = null;
Class concreteType = cachedField.fieldClass;
Serializer serializer = cachedField.serializer;
if (concreteType == null) {
Registration registration = kryo.readClass(input);
if (registration != null) { // Else value is null.
if (serializer == null) serializer = registration.getSerializer();
value = kryo.readObject(input, registration.getType(), serializer);
}
} else {
if (serializer == null) cachedField.serializer = serializer = kryo.getSerializer(concreteType);
if (cachedField.canBeNull)
value = kryo.readObjectOrNull(input, concreteType, serializer);
else
value = kryo.readObject(input, concreteType, serializer);
}
cachedField.set(object, value);
} catch (<API key> ex) {
throw new KryoException("Error accessing field: " + cachedField + " (" + type.getName() + ")", ex);
} catch (KryoException ex) {
ex.addTrace(cachedField + " (" + type.getName() + ")");
throw ex;
} catch (RuntimeException runtimeEx) {
KryoException ex = new KryoException(runtimeEx);
ex.addTrace(cachedField + " (" + type.getName() + ")");
throw ex;
}
}
}
/** Allows specific fields to be optimized. */
public CachedField getField (String fieldName) {
for (CachedField cachedField : fields)
if (cachedField.field.getName().equals(fieldName)) return cachedField;
throw new <API key>("Field \"" + fieldName + "\" not found on class: " + type.getName());
}
/** Removes a field so that it won't be serialized. */
public void removeField (String fieldName) {
for (int i = 0; i < fields.length; i++) {
CachedField cachedField = fields[i];
if (cachedField.field.getName().equals(fieldName)) {
CachedField[] newFields = new CachedField[fields.length - 1];
System.arraycopy(fields, 0, newFields, 0, i);
System.arraycopy(fields, i + 1, newFields, i, newFields.length - i);
fields = newFields;
return;
}
}
throw new <API key>("Field \"" + fieldName + "\" not found on class: " + type.getName());
}
public CachedField[] getFields () {
return fields;
}
/** Controls how a field will be serialized. */
public class CachedField {
Field field;
Class fieldClass;
Serializer serializer;
boolean canBeNull;
int accessIndex = -1;
/** @param fieldClass The concrete class of the values for this field. This saves 1-2 bytes. The serializer registered for the
* specified class will be used. Only set to a non-null value if the field type in the class definition is final
* or the values for this field will not vary. */
public void setClass (Class fieldClass) {
this.fieldClass = fieldClass;
this.serializer = null;
}
/** @param fieldClass The concrete class of the values for this field. This saves 1-2 bytes. Only set to a non-null value if
* the field type in the class definition is final or the values for this field will not vary. */
public void setClass (Class fieldClass, Serializer serializer) {
this.fieldClass = fieldClass;
this.serializer = serializer;
}
public void setSerializer (Serializer serializer) {
this.serializer = serializer;
}
public void setCanBeNull (boolean canBeNull) {
this.canBeNull = canBeNull;
}
public Field getField () {
return field;
}
public String toString () {
return field.getName();
}
Object get (Object object) throws <API key> {
if (accessIndex != -1) return ((FieldAccess)access).get(object, accessIndex);
return field.get(object);
}
void set (Object object, Object value) throws <API key> {
if (accessIndex != -1)
((FieldAccess)access).set(object, accessIndex, value);
else
field.set(object, value);
}
}
/** Indicates a field should be ignored when its declaring class is registered unless the {@link Kryo#getContext() context} has
* a value set for specified key. This can be useful to useful when a field must be serialized for one purpose, but not for
* another. Eg, a class for a networked application might have a field that should not be serialized and sent to clients, but
* should be serialized when stored on the server.
* @author Nathan Sweet <misc@n4te.com> */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
static public @interface Optional {
public String value();
}
} |
package org.chromium.chrome.browser.language.settings;
import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.accessibility.<API key>;
import android.view.accessibility.<API key>.<API key>;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import androidx.core.view.ViewCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.RecyclerView.ViewHolder;
import org.chromium.chrome.R;
import org.chromium.components.browser_ui.widget.dragreorder.<API key>;
import org.chromium.components.browser_ui.widget.dragreorder.DragStateDelegate;
import org.chromium.components.browser_ui.widget.listmenu.ListMenuButton;
import org.chromium.components.browser_ui.widget.listmenu.<API key>;
import java.util.ArrayList;
import java.util.List;
/**
* BaseAdapter for {@link RecyclerView}. It manages languages to list there.
*/
public class <API key> extends <API key><LanguageItem> {
/**
* Listener used to respond to click event on a language item.
*/
interface ItemClickListener {
/**
* @param item The clicked LanguageItem.
*/
void onLanguageClicked(LanguageItem item);
}
static class <API key> extends ViewHolder {
private TextView mTitle;
private TextView mDescription;
private ImageView mStartIcon;
private ListMenuButton mMoreButton;
<API key>(View view) {
super(view);
mTitle = view.findViewById(R.id.title);
mDescription = view.findViewById(R.id.description);
mStartIcon = view.findViewById(R.id.icon_view);
mMoreButton = view.findViewById(R.id.more);
}
/**
* Update the current {@link <API key>} with basic language info.
* @param item A {@link LanguageItem} with the language details.
*/
protected void updateLanguageInfo(LanguageItem item) {
mTitle.setText(item.getDisplayName());
// Avoid duplicate display names.
if (TextUtils.equals(item.getDisplayName(), item.<API key>())) {
mDescription.setVisibility(View.GONE);
} else {
mDescription.setVisibility(View.VISIBLE);
mDescription.setText(item.<API key>());
}
mMoreButton.<API key>(item.getDisplayName());
// The more button will become visible if <API key> is called.
mStartIcon.setVisibility(View.GONE);
mMoreButton.setVisibility(View.GONE);
}
/**
* Sets drawable for the icon at the beginning of this row with the given resId.
* @param iconResId The identifier of the drawable resource for the icon.
*/
void setStartIcon(@DrawableRes int iconResId) {
mStartIcon.setVisibility(View.VISIBLE);
mStartIcon.setImageResource(iconResId);
}
/**
* Sets up the menu button at the end of this row with a given delegate.
* @param delegate A {@link <API key>}.
*/
void <API key>(@NonNull <API key> delegate) {
mMoreButton.setVisibility(View.VISIBLE);
mMoreButton.setDelegate(delegate);
// Set item row end padding 0 when MenuButton is visible.
ViewCompat.setPaddingRelative(itemView, ViewCompat.getPaddingStart(itemView),
itemView.getPaddingTop(), 0, itemView.getPaddingBottom());
}
/**
* Set the OnClickListener for this row with a given callback.
* @param item The {@link LanguageItem} with language details.
* @param listener A {@link ItemClickListener} to respond to click event.
*/
void <API key>(LanguageItem item, @NonNull ItemClickListener listener) {
itemView.setOnClickListener(view -> listener.onLanguageClicked(item));
}
}
/**
* Keeps track of whether drag is enabled / active for language preference lists.
*/
private class <API key> implements DragStateDelegate {
private <API key> mA11yManager;
private <API key> mA11yListener;
private boolean mA11yEnabled;
public <API key>() {
mA11yManager =
(<API key>) mContext.getSystemService(Context.<API key>);
mA11yEnabled = mA11yManager.isEnabled();
mA11yListener = enabled -> {
mA11yEnabled = enabled;
<API key>();
};
mA11yManager.<API key>(mA11yListener);
}
// DragStateDelegate implementation
@Override
public boolean getDragEnabled() {
return !mA11yEnabled;
}
@Override
public boolean getDragActive() {
return getDragEnabled();
}
@Override
public void <API key>(boolean a11yEnabled) {
mA11yManager.<API key>(mA11yListener);
mA11yListener = null;
mA11yManager = null;
mA11yEnabled = a11yEnabled;
}
}
<API key>(Context context) {
super(context);
<API key>(new <API key>());
}
/**
* Show a drag indicator at the start of the row if applicable.
*
* @param holder The <API key> of the row.
*/
void <API key>(<API key> holder) {
// Quit if it's not applicable.
if (getItemCount() <= 1 || !mDragStateDelegate.getDragEnabled()) return;
assert mItemTouchHelper != null;
holder.setStartIcon(R.drawable.<API key>);
holder.mStartIcon.setOnTouchListener((v, event) -> {
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
mItemTouchHelper.startDrag(holder);
}
return false;
});
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View row = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.<API key>, viewGroup, false);
return new <API key>(row);
}
@Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
((<API key>) viewHolder).updateLanguageInfo(mElements.get(i));
}
@Override
protected void setOrder(List<LanguageItem> order) {
String[] codes = new String[order.size()];
for (int i = 0; i < order.size(); i++) {
codes[i] = order.get(i).getCode();
}
LanguagesManager.getInstance().setOrder(codes, false);
<API key>();
}
/**
* Sets the displayed languages (not the order of the user's preferred languages;
* see setOrder above).
*
* @param languages The language items to show.
*/
void <API key>(List<LanguageItem> languages) {
mElements = new ArrayList<>(languages);
<API key>();
}
@Override
protected boolean isActivelyDraggable(ViewHolder viewHolder) {
return <API key>(viewHolder);
}
@Override
protected boolean <API key>(ViewHolder viewHolder) {
return viewHolder instanceof <API key>;
}
@VisibleForTesting
public List<LanguageItem> getLanguageItemList() {
return mElements;
}
} |
#ifndef <API key>
#define <API key>
#include <deque>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/gtest_prod_util.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
#include "base/memory/singleton.h"
#include "base/metrics/histogram_macros.h"
#include "base/metrics/user_metrics.h"
#include "base/observer_list.h"
#include "base/values.h"
#include "build/build_config.h"
#include "content/common/content_export.h"
#include "content/public/browser/tts_controller.h"
#include "content/public/browser/<API key>.h"
#include "content/public/browser/tts_platform.h"
#include "services/data_decoder/public/cpp/data_decoder.h"
#include "url/gurl.h"
namespace content {
class BrowserContext;
// Singleton class that manages text-to-speech for all TTS engines and
// APIs, maintaining a queue of pending utterances and keeping
// track of all state.
class CONTENT_EXPORT TtsControllerImpl : public TtsController {
public:
// Get the single instance of this class.
static TtsControllerImpl* GetInstance();
// TtsController methods
bool IsSpeaking() override;
void SpeakOrEnqueue(std::unique_ptr<TtsUtterance> utterance) override;
void Stop() override;
void Stop(const GURL& source_url) override;
void Pause() override;
void Resume() override;
void OnTtsEvent(int utterance_id,
TtsEventType event_type,
int char_index,
int length,
const std::string& error_message) override;
void GetVoices(BrowserContext* browser_context,
std::vector<VoiceData>* out_voices) override;
void VoicesChanged() override;
void <API key>(<API key>* delegate) override;
void <API key>(<API key>* delegate) override;
void <API key>(<API key>* delegate) override;
void <API key>(TtsEngineDelegate* delegate) override;
TtsEngineDelegate* <API key>() override;
// Called directly by ~BrowserContext, because a raw BrowserContext pointer
// is stored in an Utterance.
void <API key>(BrowserContext* browser_context);
// Testing methods
void SetTtsPlatform(TtsPlatform* tts_platform) override;
int QueueSize() override;
// Strips SSML so that tags are not output by speech engine.
void StripSSML(
const std::string& utterance,
base::OnceCallback<void(const std::string&)> callback) override;
protected:
TtsControllerImpl();
~TtsControllerImpl() override;
private:
<API key>(TtsControllerTest, <API key>);
<API key>(TtsControllerTest, <API key>);
<API key>(TtsControllerTest,
<API key>);
<API key>(TtsControllerTest, <API key>);
friend struct base::<API key><TtsControllerImpl>;
// Get the platform TTS implementation (or injected mock).
TtsPlatform* GetTtsPlatform();
// Start speaking the given utterance. Will either take ownership of
// |utterance| or delete it if there's an error. Returns true on success.
void SpeakNow(std::unique_ptr<TtsUtterance> utterance);
void StopInternal(const GURL& source_url);
// Clear the utterance queue. If send_events is true, will send
// TTS_EVENT_CANCELLED events on each one.
void ClearUtteranceQueue(bool send_events);
// Finalize and delete the current utterance.
void <API key>();
// Start speaking the next utterance in the queue.
void SpeakNextUtterance();
// Updates the utterance to have default values for rate, pitch, and
// volume if they have not yet been set. On Chrome OS, defaults are
// pulled from user prefs, and may not be the same as other platforms.
void <API key>(TtsUtterance* utterance);
// Passed to Speak() as a callback.
void OnSpeakFinished(int utterance_id, bool success);
// Static helper methods for StripSSML.
static void StripSSMLHelper(
const std::string& utterance,
base::OnceCallback<void(const std::string&)> on_ssml_parsed,
data_decoder::DataDecoder::ValueOrError result);
static void PopulateParsedText(std::string* parsed_text,
const base::Value* element);
<API key>* <API key>();
<API key>* delegate_;
// A set of delegates that want to be notified when the voices change.
base::ObserverList<<API key>> <API key>;
// The current utterance being spoken.
std::unique_ptr<TtsUtterance> current_utterance_;
// Whether the queue is paused or not.
bool paused_;
// A pointer to the platform implementation of text-to-speech, for
// dependency injection.
TtsPlatform* tts_platform_;
// A queue of utterances to speak after the current one finishes.
std::deque<std::unique_ptr<TtsUtterance>> utterance_deque_;
<API key>(TtsControllerImpl);
};
} // namespace content
#endif // <API key> |
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_91) on Tue Dec 29 12:43:43 AEDT 2015 -->
<title>GOST3410Key (Bouncy Castle Library 1.54 API Specification)</title>
<meta name="date" content="2015-12-29">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="GOST3410Key (Bouncy Castle Library 1.54 API Specification)";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.54</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/bouncycastle/jce/interfaces/ElGamalPublicKey.html" title="interface in org.bouncycastle.jce.interfaces"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/bouncycastle/jce/interfaces/GOST3410Params.html" title="interface in org.bouncycastle.jce.interfaces"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/jce/interfaces/GOST3410Key.html" target="_top">Frames</a></li>
<li><a href="GOST3410Key.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<div class="subTitle">org.bouncycastle.jce.interfaces</div>
<h2 title="Interface GOST3410Key" class="title">Interface GOST3410Key</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Subinterfaces:</dt>
<dd><a href="../../../../org/bouncycastle/jce/interfaces/GOST3410PrivateKey.html" title="interface in org.bouncycastle.jce.interfaces">GOST3410PrivateKey</a>, <a href="../../../../org/bouncycastle/jce/interfaces/GOST3410PublicKey.html" title="interface in org.bouncycastle.jce.interfaces">GOST3410PublicKey</a></dd>
</dl>
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../org/bouncycastle/jcajce/provider/asymmetric/gost/<API key>.html" title="class in org.bouncycastle.jcajce.provider.asymmetric.gost"><API key></a>, <a href="../../../../org/bouncycastle/jcajce/provider/asymmetric/gost/BCGOST3410PublicKey.html" title="class in org.bouncycastle.jcajce.provider.asymmetric.gost">BCGOST3410PublicKey</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="strong">GOST3410Key</span></pre>
<div class="block">Main interface for a GOST 3410-94 key.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="method_summary">
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/bouncycastle/jce/interfaces/GOST3410Params.html" title="interface in org.bouncycastle.jce.interfaces">GOST3410Params</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/bouncycastle/jce/interfaces/GOST3410Key.html#getParameters()">getParameters</a></strong>()</code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="method_detail">
</a>
<h3>Method Detail</h3>
<a name="getParameters()">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>getParameters</h4>
<pre><a href="../../../../org/bouncycastle/jce/interfaces/GOST3410Params.html" title="interface in org.bouncycastle.jce.interfaces">GOST3410Params</a> getParameters()</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><em><b>Bouncy Castle Cryptography Library 1.54</b></em></div>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/bouncycastle/jce/interfaces/ElGamalPublicKey.html" title="interface in org.bouncycastle.jce.interfaces"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/bouncycastle/jce/interfaces/GOST3410Params.html" title="interface in org.bouncycastle.jce.interfaces"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/bouncycastle/jce/interfaces/GOST3410Key.html" target="_top">Frames</a></li>
<li><a href="GOST3410Key.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html> |
<?php
namespace Course\Service;
use \Doctrine\ORM\EntityManager;
use Zend\ServiceManager\<API key>;
use Zend\ServiceManager\<API key>;
abstract class AbstractFacade implements <API key>, IFacade {
/**
* @var \Doctrine\Orm\EntityManager
*/
protected $entityManager = null;
protected $eventManager;
protected $loggingService;
protected $cacheClass;
protected $serviceLocator;
public function getEventManager(){
return $this->eventManager;
}
public function setEventManager( $eventManager){
$this->eventManager = $eventManager;
}
/* (non-PHPdoc)
* @see \Front\ORM\<API key>::setEntityManager()
*/
public function setEntityManager(\Doctrine\ORM\EntityManager $entityManager)
{
$this->entityManager = $entityManager;
return $this;
}
/**
* @returns <API key>
*/
public function getServiceLocator()
{
return $this->serviceLocator;
}
public function setServiceLocator(<API key> $serviceLocator)
{
$this->serviceLocator = $serviceLocator;
}
/**
* Getting entity manager
*/
public function getEntityManager(){
return $this->entityManager;
}
public function find($repository, $id) {
return $this->entityManager->getRepository($repository)->find($id);
}
public function findAll($repository){
return $this->entityManager->getRepository($repository)->findAll();
}
/**
*
* @param unknown_type $entity
*/
public function persist($entity){
$this->entityManager->persist($entity);
$this->flush();
return $entity;
}
public function flush(){
$this->entityManager->flush();
}
} |
#include "remoting/test/fake_socket_factory.h"
#include <algorithm>
#include <cstddef>
#include <cstdlib>
#include <string>
#include "base/bind.h"
#include "base/callback.h"
#include "base/location.h"
#include "base/macros.h"
#include "base/numerics/math_constants.h"
#include "base/<API key>.h"
#include "base/threading/<API key>.h"
#include "base/time/time.h"
#include "net/base/io_buffer.h"
#include "remoting/base/leaky_bucket.h"
#include "third_party/webrtc/media/base/rtp_utils.h"
#include "third_party/webrtc/rtc_base/async_packet_socket.h"
#include "third_party/webrtc/rtc_base/socket.h"
#include "third_party/webrtc/rtc_base/time_utils.h"
namespace remoting {
namespace {
const int kPortRangeStart = 1024;
const int kPortRangeEnd = 65535;
double RandDouble() {
return static_cast<double>(std::rand()) / RAND_MAX;
}
double GetNormalRandom(double average, double stddev) {
// Based on Box-Muller transform, see
return average + stddev * sqrt(-2.0 * log(1.0 - RandDouble())) *
cos(RandDouble() * 2.0 * base::kPiDouble);
}
class FakeUdpSocket : public rtc::AsyncPacketSocket {
public:
FakeUdpSocket(<API key>* factory,
scoped_refptr<<API key>> dispatcher,
const rtc::SocketAddress& local_address);
~FakeUdpSocket() override;
void ReceivePacket(const rtc::SocketAddress& from,
const rtc::SocketAddress& to,
const scoped_refptr<net::IOBuffer>& data,
int data_size);
// rtc::AsyncPacketSocket interface.
rtc::SocketAddress GetLocalAddress() const override;
rtc::SocketAddress GetRemoteAddress() const override;
int Send(const void* data,
size_t data_size,
const rtc::PacketOptions& options) override;
int SendTo(const void* data,
size_t data_size,
const rtc::SocketAddress& address,
const rtc::PacketOptions& options) override;
int Close() override;
State GetState() const override;
int GetOption(rtc::Socket::Option option, int* value) override;
int SetOption(rtc::Socket::Option option, int value) override;
int GetError() const override;
void SetError(int error) override;
private:
<API key>* factory_;
scoped_refptr<<API key>> dispatcher_;
rtc::SocketAddress local_address_;
State state_;
<API key>(FakeUdpSocket);
};
FakeUdpSocket::FakeUdpSocket(<API key>* factory,
scoped_refptr<<API key>> dispatcher,
const rtc::SocketAddress& local_address)
: factory_(factory),
dispatcher_(dispatcher),
local_address_(local_address),
state_(STATE_BOUND) {
}
FakeUdpSocket::~FakeUdpSocket() {
factory_->OnSocketDestroyed(local_address_.port());
}
void FakeUdpSocket::ReceivePacket(const rtc::SocketAddress& from,
const rtc::SocketAddress& to,
const scoped_refptr<net::IOBuffer>& data,
int data_size) {
SignalReadPacket(this, data->data(), data_size, from, rtc::TimeMicros());
}
rtc::SocketAddress FakeUdpSocket::GetLocalAddress() const {
return local_address_;
}
rtc::SocketAddress FakeUdpSocket::GetRemoteAddress() const {
NOTREACHED();
return rtc::SocketAddress();
}
int FakeUdpSocket::Send(const void* data, size_t data_size,
const rtc::PacketOptions& options) {
NOTREACHED();
return EINVAL;
}
int FakeUdpSocket::SendTo(const void* data, size_t data_size,
const rtc::SocketAddress& address,
const rtc::PacketOptions& options) {
scoped_refptr<net::IOBuffer> buffer =
base::MakeRefCounted<net::IOBuffer>(data_size);
memcpy(buffer->data(), data, data_size);
base::TimeTicks now = base::TimeTicks::Now();
cricket::ApplyPacketOptions(reinterpret_cast<uint8_t*>(buffer->data()),
data_size, options.packet_time_params,
(now - base::TimeTicks()).InMicroseconds());
SignalSentPacket(this, rtc::SentPacket(options.packet_id, rtc::TimeMillis()));
dispatcher_->DeliverPacket(local_address_, address, buffer, data_size);
return data_size;
}
int FakeUdpSocket::Close() {
state_ = STATE_CLOSED;
return 0;
}
rtc::AsyncPacketSocket::State FakeUdpSocket::GetState() const {
return state_;
}
int FakeUdpSocket::GetOption(rtc::Socket::Option option, int* value) {
NOTIMPLEMENTED();
return -1;
}
int FakeUdpSocket::SetOption(rtc::Socket::Option option, int value) {
// All options are currently ignored.
return 0;
}
int FakeUdpSocket::GetError() const {
return 0;
}
void FakeUdpSocket::SetError(int error) {
NOTREACHED();
}
} // namespace
<API key>::PendingPacket::PendingPacket()
: data_size(0) {
}
<API key>::PendingPacket::PendingPacket(
const rtc::SocketAddress& from,
const rtc::SocketAddress& to,
const scoped_refptr<net::IOBuffer>& data,
int data_size)
: from(from), to(to), data(data), data_size(data_size) {
}
<API key>::PendingPacket::PendingPacket(
const PendingPacket& other) = default;
<API key>::PendingPacket::~PendingPacket() = default;
<API key>::<API key>(
<API key>* dispatcher)
: task_runner_(base::<API key>::Get()),
dispatcher_(dispatcher),
address_(dispatcher_->AllocateAddress()),
out_of_order_rate_(0.0),
next_port_(kPortRangeStart) {
dispatcher_->AddNode(this);
}
<API key>::~<API key>() {
CHECK(udp_sockets_.empty());
dispatcher_->RemoveNode(this);
}
void <API key>::OnSocketDestroyed(int port) {
DCHECK(task_runner_-><API key>());
udp_sockets_.erase(port);
}
void <API key>::SetBandwidth(int bandwidth, int max_buffer) {
DCHECK(task_runner_-><API key>());
if (bandwidth <= 0) {
leaky_bucket_.reset();
} else {
leaky_bucket_.reset(new LeakyBucket(max_buffer, bandwidth));
}
}
void <API key>::SetLatency(base::TimeDelta average,
base::TimeDelta stddev) {
DCHECK(task_runner_-><API key>());
latency_average_ = average;
latency_stddev_ = stddev;
}
rtc::AsyncPacketSocket* <API key>::CreateUdpSocket(
const rtc::SocketAddress& local_address,
uint16_t min_port,
uint16_t max_port) {
DCHECK(task_runner_-><API key>());
int port = -1;
if (min_port > 0 && max_port > 0) {
for (uint16_t i = min_port; i <= max_port; ++i) {
if (udp_sockets_.find(i) == udp_sockets_.end()) {
port = i;
break;
}
}
if (port < 0)
return nullptr;
} else {
do {
port = next_port_;
next_port_ =
(next_port_ >= kPortRangeEnd) ? kPortRangeStart : (next_port_ + 1);
} while (udp_sockets_.find(port) != udp_sockets_.end());
}
CHECK(local_address.ipaddr() == address_);
FakeUdpSocket* result =
new FakeUdpSocket(this, dispatcher_,
rtc::SocketAddress(local_address.ipaddr(), port));
udp_sockets_[port] = base::BindRepeating(&FakeUdpSocket::ReceivePacket,
base::Unretained(result));
return result;
}
rtc::AsyncPacketSocket* <API key>::<API key>(
const rtc::SocketAddress& local_address,
uint16_t min_port,
uint16_t max_port,
int opts) {
return nullptr;
}
rtc::AsyncPacketSocket* <API key>::<API key>(
const rtc::SocketAddress& local_address,
const rtc::SocketAddress& remote_address,
const rtc::ProxyInfo& proxy_info,
const std::string& user_agent,
const rtc::<API key>& opts) {
return nullptr;
}
rtc::<API key>*
<API key>::CreateAsyncResolver() {
return nullptr;
}
const scoped_refptr<base::<API key>>&
<API key>::GetThread() const {
return task_runner_;
}
const rtc::IPAddress& <API key>::GetAddress() const {
return address_;
}
void <API key>::ReceivePacket(
const rtc::SocketAddress& from,
const rtc::SocketAddress& to,
const scoped_refptr<net::IOBuffer>& data,
int data_size) {
DCHECK(task_runner_-><API key>());
DCHECK(to.ipaddr() == address_);
base::TimeDelta delay;
if (leaky_bucket_) {
base::TimeTicks now = base::TimeTicks::Now();
if (!leaky_bucket_->RefillOrSpill(data_size, now)) {
++<API key>;
// Drop the packet.
return;
}
delay = std::max(base::TimeDelta(), leaky_bucket_->GetEmptyTime() - now);
}
total_buffer_delay_ += delay;
if (delay > max_buffer_delay_)
max_buffer_delay_ = delay;
++<API key>;
if (latency_average_ > base::TimeDelta()) {
delay += base::TimeDelta::FromMillisecondsD(
GetNormalRandom(latency_average_.InMillisecondsF(),
latency_stddev_.InMillisecondsF()));
}
if (delay < base::TimeDelta())
delay = base::TimeDelta();
// Put the packet to the |pending_packets_| and post a task for
// DoReceivePackets(). Note that the DoReceivePackets() task posted here may
// deliver a different packet, not the one added to the queue here. This
// would happen if another task gets posted with a shorted delay or when
// |out_of_order_rate_| is greater than 0. It's implemented this way to
// decouple latency variability from out-of-order delivery.
PendingPacket packet(from, to, data, data_size);
pending_packets_.push_back(packet);
task_runner_->PostDelayedTask(
FROM_HERE,
base::BindOnce(&<API key>::DoReceivePacket,
weak_factory_.GetWeakPtr()),
delay);
}
void <API key>::DoReceivePacket() {
DCHECK(task_runner_-><API key>());
PendingPacket packet;
if (pending_packets_.size() > 1 && RandDouble() < out_of_order_rate_) {
auto it = pending_packets_.begin();
++it;
packet = *it;
pending_packets_.erase(it);
} else {
packet = pending_packets_.front();
pending_packets_.pop_front();
}
auto iter = udp_sockets_.find(packet.to.port());
if (iter == udp_sockets_.end()) {
// Invalid port number.
return;
}
iter->second.Run(packet.from, packet.to, packet.data, packet.data_size);
}
void <API key>::ResetStats() {
<API key> = 0;
<API key> = 0;
total_buffer_delay_ = base::TimeDelta();
max_buffer_delay_ = base::TimeDelta();
}
} // namespace remoting |
// <API key>.h
// barcamp
#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"
@class <API key>;
@class Place;
@interface <API key> : <API key> <<API key>>{
NSArray *allPlaces;
Place *selectedPlace;
MBProgressHUD *HUD;
@private
<API key> *unconfVC;
}
@property (nonatomic, retain) IBOutlet UITableView *tableView;
@end |
<?php
namespace User\Form;
use Zend\InputFilter\InputFilter;
class CreateAccountFilter extends InputFilter
{
public function __construct()
{
$this->add(array(
'name' => 'username',
'required' => true,
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'min' => 6,
'message'=> 'Tên đăng nhập quá ngắn, ít nhất phải %min% ký tự'
),
),
),
'filters' => array(
array('name' => 'StringTrim'),
),
));
$this->add(array(
'name' => 'password',
'required' => true,
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'min' => 6,
'message'=> 'Mật khẩu quá ngắn, ít nhất phải %min% ký tự'
),
),
),
'filters' => array(
array('name' => 'StringTrim'),
),
));
$this->add(array(
'name' => 'passwordVerify',
'required' => true,
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'min' => 6,
'message'=> 'Tên đăng nhập quá ngắn, ít nhất phải %min% ký tự'
),
),
array(
'name' => 'identical',
'options' => array(
'token' => 'password',
'message'=> 'Hai lần nhập mật khẩu không trùng khớp nhau'
)
),
),
'filters' => array(
array('name' => 'StringTrim'),
),
));
}
} |
package test;
import java.util.Collection;
import java.util.HashSet;
/**
* @author kalpana_thakur
*
*/
public class User
{
private Long id;
/**
* lastName.
*/
private String lastName;
/**
* firstName.
*/
private String firstName;
/**
* emailAddress.
*/
private String emailAddress;
/**
* activityStatus.
*/
private String activityStatus;
/**
* Role of the User
*/
private Collection<Object> roleCollection = new HashSet<Object>() ;
/**
* @return activityStatus
*/
public String getActivityStatus()
{
return activityStatus;
}
/**
* @param activityStatus : Activity status.
*/
public void setActivityStatus(String activityStatus)
{
this.activityStatus = activityStatus;
}
/**
* @return emailAddress
*/
public String getEmailAddress()
{
return emailAddress;
}
/**
* @param emailAddress :
*/
public void setEmailAddress(String emailAddress)
{
this.emailAddress = emailAddress;
}
/**
* @return firstName
*/
public String getFirstName()
{
return firstName;
}
/**
* @param firstName :
*/
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
/**
* @return lastName
*/
public String getLastName()
{
return lastName;
}
/**
* @param lastName :
*/
public void setLastName(String lastName)
{
this.lastName = lastName;
}
/**
* @return the roleCollection
*/
public Collection<Object> getRoleCollection()
{
return roleCollection;
}
/**
* @param roleCollection the roleCollection to set
*/
public void setRoleCollection(Collection<Object> roleCollection)
{
this.roleCollection = roleCollection;
}
/**
* @return identifier.
*/
public Long getId()
{
return id;
}
/**
* @param identifier :
*/
public void setId(Long identifier)
{
this.id = identifier;
}
/**
* orderCollection.
*/
private Collection<Object> orderCollection = new HashSet<Object>() ;
/**
* orderCollection.
* @return orderCollection
*/
public Collection<Object> getOrderCollection()
{
return orderCollection;
}
/**
* orderCollection.
* @param orderCollection orderCollection
*/
public void setOrderCollection(Collection<Object> orderCollection)
{
this.orderCollection = orderCollection;
}
} |
{-#LANGUAGE FlexibleInstances #-}
{-#LANGUAGE FlexibleContexts #-}
{-#LANGUAGE LambdaCase #-}
{-#LANGUAGE <API key> #-}
{-#LANGUAGE OverloadedStrings #-}
{-#LANGUAGE Rank2Types #-}
{-#LANGUAGE ScopedTypeVariables #-}
module Twilio.Types
( APIVersion(..)
, module X
-- * Misc
, makeTwilioRequest
, makeTwilioRequest'
, <API key>
, <API key>'
) where
import Control.Monad
import Control.Monad.Reader.Class
import Data.Aeson
import qualified Data.ByteString.Char8 as C
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import Network.HTTP.Client
import Control.Monad.Twilio
import Twilio.Types.AddressRequirement as X
import Twilio.Types.AuthToken as X
import Twilio.Types.Capability as X
import Twilio.Types.ISOCountryCode as X
import Twilio.Types.List as X
import Twilio.Types.PriceUnit as X
import Twilio.Types.SID as X
import Twilio.Internal.Parser
import Twilio.Internal.Request
data APIVersion
= API_2010_04_01
| API_2008_08_01
deriving Eq
instance Read APIVersion where
readsPrec _ = \case
"2010-04-01" -> return (API_2010_04_01, "")
"2008-08-01" -> return (API_2008_08_01, "")
_ -> mzero
instance Show APIVersion where
show API_2010_04_01 = "2010-04-01"
show API_2008_08_01 = "2008-08-01"
instance FromJSON APIVersion where
parseJSON (String "2010-04-01") = return API_2010_04_01
parseJSON (String "2008-08-01") = return API_2008_08_01
parseJSON _ = mzero
makeTwilioRequest' :: Monad m => Text -> TwilioT m Request
makeTwilioRequest' suffix = do
((accountSID, authToken), _) <- ask
let Just request = parseUrl . T.unpack $ baseURL <> suffix
return $ applyBasicAuth (C.pack . T.unpack $ getSID accountSID)
(C.pack . T.unpack $ getAuthToken authToken) request
makeTwilioRequest :: Monad m => Text -> TwilioT m Request
makeTwilioRequest suffix = do
((_, _), accountSID) <- ask
makeTwilioRequest' $ "/Accounts/" <> getSID accountSID <> suffix
<API key>' :: Monad m
=> Text
-> [(C.ByteString, C.ByteString)]
-> TwilioT m Request
<API key>' resourceURL params =
makeTwilioRequest' resourceURL <&> urlEncodedBody params
<API key> :: Monad m
=> Text
-> [(C.ByteString, C.ByteString)]
-> TwilioT m Request
<API key> resourceURL params =
makeTwilioRequest resourceURL <&> urlEncodedBody params |
#ifndef _PB_SYSHDR_WIN_H_
#define _PB_SYSHDR_WIN_H_
/* stdint.h subset */
#ifdef HAVE_STDINT_H
#include <stdint.h>
#else
/* You will need to modify these to match the word size of your platform. */
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef signed short int16_t;
typedef unsigned short uint16_t;
typedef signed int int32_t;
typedef unsigned int uint32_t;
typedef signed long long int64_t;
typedef unsigned long long uint64_t;
#endif
/* stddef.h subset */
#ifdef HAVE_STDDEF_H
#include <stddef.h>
#else
typedef uint32_t size_t;
#define offsetof(st, m) ((size_t)(&((st *)0)->m))
#ifndef NULL
#define NULL 0
#endif
#endif
/* stdbool.h subset */
#ifdef HAVE_STDBOOL_H
#include <stdbool.h>
#else
#ifndef __cplusplus
typedef int bool;
#define false 0
#define true 1
#endif
#endif
/* stdlib.h subset */
#ifdef PB_ENABLE_MALLOC
#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#else
void *realloc(void *ptr, size_t size);
void free(void *ptr);
#endif
#endif
/* string.h subset */
#ifdef HAVE_STRING_H
#include <string.h>
#else
#ifndef WIN32
/* Implementations are from the Public Domain C Library (PDCLib). */
static size_t strlen( const char * s )
{
size_t rc = 0;
while ( s[rc] )
{
++rc;
}
return rc;
}
static void * memcpy( void *s1, const void *s2, size_t n )
{
char * dest = (char *) s1;
const char * src = (const char *) s2;
while ( n
{
*dest++ = *src++;
}
return s1;
}
static void * memset( void * s, int c, size_t n )
{
unsigned char * p = (unsigned char *) s;
while ( n
{
*p++ = (unsigned char) c;
}
return s;
}
#else
#include <string.h>
#endif
#endif
#endif |
package generator
import (
"bytes"
"fmt"
"log"
"os"
"path"
"strings"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
google_protobuf "github.com/golang/protobuf/protoc-gen-go/descriptor"
plugin "github.com/golang/protobuf/protoc-gen-go/plugin"
)
//Generator will generate our template files
type Generator struct {
*bytes.Buffer
Request *plugin.<API key> // The input.
Response *plugin.<API key> // The output.
TemplateEngine string // mustache, all the time right now
}
// New creates a new generator
func New() *Generator {
return &Generator{
Buffer: new(bytes.Buffer),
Request: new(plugin.<API key>),
Response: new(plugin.<API key>),
TemplateEngine: "mustache",
}
}
// Error reports a problem, including an error, and exits the program.
func (g *Generator) Error(err error, msgs ...string) {
s := strings.Join(msgs, " ") + ":" + err.Error()
log.Print("<API key>: error:", s)
os.Exit(1)
}
// Fail reports a problem and exits the program.
func (g *Generator) Fail(msgs ...string) {
s := strings.Join(msgs, " ")
log.Print("<API key>: error:", s)
os.Exit(1)
}
// GenerateAllFiles generates the output for all the files we're outputting.
func (g *Generator) GenerateAllFiles() {
for _, fdesciptor := range g.Request.ProtoFile {
g.Response.File = append(g.Response.File, g.GenerateFile(fdesciptor))
}
}
// GenerateFile given a protobuf file descriptor will generate a template file
func (g *Generator) GenerateFile(fdesciptor *google_protobuf.FileDescriptorProto) *plugin.<API key> {
res := &plugin.<API key>{
Name: proto.String(fileName(*fdesciptor.Name, g.TemplateEngine)),
}
out := bytes.NewBufferString("// Code generated by <API key>.")
fmt.Fprintf(out, `
// source: %s
// DO NOT EDIT!
var templates = templates || {};
`, *fdesciptor.Name)
for _, msgType := range fdesciptor.MessageType {
fmt.Fprintf(out, "\ntemplates.%s = {\n", *msgType.Name)
// render form view
fmt.Fprintf(out, " form: '")
var includes []string
for _, field := range msgType.Field {
fmt.Fprintf(out, `<div class="form-group">`)
fmt.Fprintf(out, `<label for="%s">%s</label>`, *field.JsonName, *field.Name)
switch *field.Type {
case descriptor.<API key>,
descriptor.<API key>:
fmt.Fprintf(out, `<input class="form-control %s" id="%[1]s" name="%[1]s" type=number step=any value="{{%[1]s}}" >`, *field.JsonName)
case descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>:
fmt.Fprintf(out, `<input class="form-control %s" id="%[1]s" name="%[1]s" type=number step=1 value="{{%[1]s}}" >`, *field.JsonName)
case descriptor.<API key>,
descriptor.<API key>:
fmt.Fprintf(out, `<input class="form-control %s" id="%[1]s" name="%[1]s" type=number step=1 min=0 value="{{%[1]s}}" >`, *field.JsonName)
case descriptor.<API key>:
fmt.Fprintf(out, `<input class="form-control %s" id="%[1]s" name="%[1]s" type="checkbox" value="{{%[1]s}}" >`, *field.JsonName)
case descriptor.<API key>:
fmt.Fprintf(out, `<input class="form-control %s" id="%[1]s" name="%[1]s" type="text" value="{{%[1]s}}" >`, *field.JsonName)
case descriptor.<API key>:
n := getTypeNameName(field.GetTypeName())
fmt.Fprintf(out, `{{> %s}}`, n)
includes = append(includes, n)
case descriptor.<API key>:
fmt.Fprintf(out, `<select class="form-control %s" id="%[1]s" name="%[1]s">`, *field.JsonName)
fmt.Fprintf(out, `</select>`)
case descriptor.<API key>,
descriptor.<API key>:
//just ignore those
default:
g.Fail("unknown type ", field.GetName())
}
// fmt.Fprintf(out, `<small class="%sHelp" class="form-text text-muted">%s</small>`, *field.JsonName, ?Comment)
fmt.Fprintf(out, `</div>`)
}
fmt.Fprintf(out, "',\n")
fmt.Fprintf(out, " formIncludes: function() { return {")
for i, incl := range includes {
if i > 0 {
fmt.Fprintf(out, `, `)
}
fmt.Fprintf(out, "%s: templates.%[1]s.form", incl)
}
fmt.Fprintf(out, "} },\n")
// render form view
fmt.Fprintf(out, " tableHeader: '")
for _, field := range msgType.Field {
switch *field.Type {
case descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>:
fmt.Fprintf(out, `<th class="%s">%[1]s</th>`, *field.Name)
case descriptor.<API key>:
n := getTypeNameName(field.GetTypeName())
fmt.Fprintf(out, `{{> %s}}`, n)
case descriptor.<API key>,
descriptor.<API key>:
//just ignore those
default:
g.Fail("unknown type ", field.GetName())
}
}
fmt.Fprintf(out, "',\n")
fmt.Fprintf(out, " tableHeaderIncludes: function() { return {")
for i, incl := range includes {
if i > 0 {
fmt.Fprintf(out, `, `)
}
fmt.Fprintf(out, "%s: templates.%[1]s.tableHeader", incl)
}
fmt.Fprintf(out, "} },\n")
// render form view
fmt.Fprintf(out, " tableRow: '")
for _, field := range msgType.Field {
switch *field.Type {
case descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>,
descriptor.<API key>:
fmt.Fprintf(out, `<td class="%s">{{%[1]s}}</td>`, *field.Name)
case descriptor.<API key>:
n := getTypeNameName(field.GetTypeName())
fmt.Fprintf(out, `{{> %s}}`, n)
case descriptor.<API key>,
descriptor.<API key>:
//just ignore those
default:
g.Fail("unknown type ", field.GetName())
}
}
fmt.Fprintf(out, "',\n")
fmt.Fprintf(out, " tableRowIncludes: function() { return {")
for i, incl := range includes {
if i > 0 {
fmt.Fprintf(out, `, `)
}
fmt.Fprintf(out, "%s: templates.%[1]s.tableRow", incl)
}
fmt.Fprintf(out, "} }\n")
//end of file
fmt.Fprintf(out, "};\n")
}
res.Content = proto.String(out.String())
return res
}
// fileName returns the output name for the generated template file.
func fileName(name, engine string) string {
if ext := path.Ext(name); ext == ".proto" || ext == ".protodevel" {
name = name[:len(name)-len(ext)]
}
return name + ".pb." + engine + ".js"
}
func getTypeNameName(typeName string) (name string) {
idx := strings.LastIndex(typeName, ".")
if idx == -1 {
return typeName
}
return typeName[idx+1:]
} |
from django.test import Client
from questionnaire.forms.sections import SectionForm, SubSectionForm
from questionnaire.models import Questionnaire, Section, SubSection
from questionnaire.tests.base_test import BaseTest
class SectionsViewTest(BaseTest):
def setUp(self):
self.client = Client()
self.user, self.country = self.<API key>()
self.assign('can_view_users', self.user)
self.client.login(username=self.user.username, password='pass')
self.questionnaire = Questionnaire.objects.create(name="JRF 2013 Core English", year=2013)
self.url = '/questionnaire/entry/%s/section/new/' % self.questionnaire.id
self.form_data = {'name': 'New section',
'description': 'funny section',
'title': 'some title',
'questionnaire': self.questionnaire.id}
def <API key>(self):
response = self.client.get(self.url)
self.assertEqual(200, response.status_code)
templates = [template.name for template in response.templates]
self.assertIn("sections/subsections/new.html", templates)
self.assertIsNotNone(response.context['form'])
self.assertIsInstance(response.context['form'], SectionForm)
self.assertEqual("CREATE", response.context['btn_label'])
def <API key>(self):
self.failIf(Section.objects.filter(**self.form_data))
response = self.client.post(self.url, data=self.form_data)
section = Section.objects.get(**self.form_data)
self.failUnless(section)
self.assertRedirects(response, expected_url='/questionnaire/entry/%s/section/%s/' % (self.questionnaire.id ,section.id))
def <API key>(self):
Section.objects.create(name="Some", order=1, questionnaire=self.questionnaire)
form_data = self.form_data.copy()
form_data['name'] = 'Another section'
self.failIf(Section.objects.filter(**form_data))
response = self.client.post(self.url, data=form_data)
section = Section.objects.get(order=2, name=form_data['name'])
self.failUnless(section)
self.assertRedirects(response, expected_url='/questionnaire/entry/%s/section/%s/' % (self.questionnaire.id ,section.id))
def <API key>(self):
self.<API key>(self.url)
self.<API key>(self.url)
def test_post_invalid(self):
Section.objects.create(name="Some", order=1, questionnaire=self.questionnaire)
form_data = self.form_data.copy()
form_data['name'] = ''
self.failIf(Section.objects.filter(**form_data))
response = self.client.post(self.url, data=form_data)
section = Section.objects.filter(order=2, name=form_data['name'])
self.failIf(section)
self.assertIn('Section NOT created. See errors below.', response.content)
self.assertIsInstance(response.context['form'], SectionForm)
self.assertEqual("new-section-modal", response.context['id'])
self.assertEqual("CREATE", response.context['btn_label'])
class SubSectionsViewTest(BaseTest):
def setUp(self):
self.client = Client()
self.user, self.country = self.<API key>()
self.assign('<API key>', self.user)
self.client.login(username=self.user.username, password='pass')
self.questionnaire = Questionnaire.objects.create(name="JRF 2013 Core English", year=2013)
self.section = Section.objects.create(name="section", questionnaire=self.questionnaire, order=1)
self.url = '/questionnaire/entry/%s/section/%s/subsection/new/' % (self.questionnaire.id, self.section.id)
self.form_data = {
'description': 'funny section',
'title': 'some title',
}
def <API key>(self):
self.<API key>(self.url)
self.<API key>(self.url)
def <API key>(self):
response = self.client.get(self.url)
self.assertEqual(200, response.status_code)
templates = [template.name for template in response.templates]
self.assertIn("sections/subsections/new.html", templates)
self.assertIsNotNone(response.context['form'])
self.assertIsInstance(response.context['form'], SubSectionForm)
self.assertEqual("CREATE", response.context['btn_label'])
def <API key>(self):
self.failIf(SubSection.objects.filter(section=self.section, **self.form_data))
response = self.client.post(self.url, data=self.form_data)
subsection = SubSection.objects.filter(section=self.section, **self.form_data)
self.failUnless(subsection)
self.assertEqual(1, subsection.count())
self.assertIn('Subsection successfully created.', response.cookies['messages'].value)
self.assertRedirects(response,expected_url='/questionnaire/entry/%s/section/%s/' % (self.questionnaire.id ,self.section.id))
def <API key>(self):
SubSection.objects.create(title="Some", order=1, section=self.section)
form_data = self.form_data.copy()
form_data['title'] = 'Another subsection'
self.failIf(SubSection.objects.filter(section=self.section, **form_data))
response = self.client.post(self.url, data=form_data)
subsection = SubSection.objects.filter(order=2, title=form_data['title'])
self.failUnless(subsection)
self.assertEqual(1, subsection.count())
self.assertRedirects(response,expected_url='/questionnaire/entry/%s/section/%s/' % (self.questionnaire.id ,self.section.id))
def test_post_invalid(self):
SubSection.objects.create(title="Some", order=1, section=self.section)
form_data = self.form_data.copy()
form_data['title'] = ''
self.failIf(SubSection.objects.filter(section=self.section, **form_data))
response = self.client.post(self.url, data=form_data)
subsection = SubSection.objects.filter(order=2, title=form_data['title'])
self.failIf(subsection)
self.assertIn('Subsection NOT created. See errors below.', response.content)
self.assertIsInstance(response.context['form'], SubSectionForm)
self.assertEqual("<API key>", response.context['id'])
self.assertEqual("CREATE", response.context['btn_label']) |
namespace Platform.VirtualFileSystem
{
public interface IFileHashingService
: IHashingService
{
new IFile OperatingNode
{
get;
}
}
} |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.<API key> as art
art.process_dataset(N = 32 , FREQ = 'D', seed = 0, trendtype = "MovingAverage", cycle_length = 12, transform = "Integration", sigma = 0.0, exog_count = 100, ar_order = 0); |
// This file was generated by RobotBuilder. It contains sections of
// code that are automatically generated and assigned by robotbuilder.
// These sections will be updated in the future when you export to
// Java from RobotBuilder. Do not put any code or make any change in
// the blocks indicating autogenerated code or it will be lost on an
// update. Deleting the comments indicating the section will prevent
// it from being updated in the future.
package org.usfirst.frc3824.Competition2017.subsystems;
import org.usfirst.frc3824.Competition2017.Robot;
import org.usfirst.frc3824.Competition2017.Constants;
import org.usfirst.frc3824.Competition2017.RobotMap;
import org.usfirst.frc3824.Competition2017.Target;
import org.usfirst.frc3824.Competition2017.commands.*;
import edu.wpi.first.wpilibj.AnalogGyro;
import edu.wpi.first.wpilibj.AnalogInput;
import edu.wpi.first.wpilibj.Compressor;
import edu.wpi.first.wpilibj.Encoder;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj.PIDController;
import edu.wpi.first.wpilibj.PIDOutput;
import edu.wpi.first.wpilibj.RobotDrive;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.SpeedController;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
/**
* The Chassis class contains all the methods and members for the Chassis subassembly
*/
public class Chassis extends Subsystem
{
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=CONSTANTS
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
private final SpeedController driveLeft = RobotMap.chassisDriveLeft;
private final SpeedController driveRight = RobotMap.chassisDriveRight;
private final RobotDrive robotDrive = RobotMap.chassisRobotDrive;
private final AnalogInput ultrasound = RobotMap.chassisUltrasound;
private final AnalogGyro gyro = RobotMap.chassisGyro;
private final Encoder encoderLeft = RobotMap.chassisEncoderLeft;
private final Encoder encoderRight = RobotMap.chassisEncoderRight;
private final Solenoid transmission = RobotMap.chassisTransmission;
private final Compressor compressor = RobotMap.chassisCompressor;
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DECLARATIONS
// Parameter used for drive while running under PID Control. The values
// not set by the controller constructor can be set by a command directly
private double m_magnitude;
private boolean m_highGear;
// PID controller for driving based on Gyro
private PIDController angleGyroPID = new PIDController(Constants.<API key>,
Constants.<API key>,
Constants.<API key>,
gyro, new AnglePIDOutput());
private PIDController <API key> = new PIDController(Constants.<API key>,
Constants.<API key>,
Constants.<API key>,
encoderRight, new <API key>());
private PIDController <API key> = new PIDController(Constants.<API key>,
Constants.<API key>,
Constants.<API key>,
encoderLeft, new <API key>());
public Chassis()
{
// Configure angleEncoderPIDs
// SmartDashboard.putNumber("angleEncoderPID P", <API key>.getP());
// SmartDashboard.putNumber("angleEncoderPID I", <API key>.getI());
// SmartDashboard.putNumber("angleEncoderPID D", <API key>.getD());
// Set the encoder input value range
<API key>.setInputRange(Constants.<API key>, Constants.<API key>);
<API key>.setInputRange(Constants.<API key>, Constants.<API key>);
// Set the encoder output range
<API key>.setOutputRange(Constants.<API key>, Constants.<API key>);
<API key>.setOutputRange(Constants.<API key>, Constants.<API key>);
}
// Put methods for controlling this subsystem
// here. Call these from Commands.
public void initDefaultCommand()
{
// BEGIN AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
setDefaultCommand(new TeleopDrive());
// END AUTOGENERATED CODE, SOURCE=ROBOTBUILDER ID=DEFAULT_COMMAND
// Set the default command for a subsystem here.
// setDefaultCommand(new MySpecialCommand());
}
// Methods to call from commands
/*
* Method to stop the chassis drive motors and disable/reset pids
*/
public void <API key>()
{
// Initialize the gyro PID controller
angleGyroPID.disable();
angleGyroPID.reset();
<API key>.disable();
<API key>.reset();
<API key>.disable();
<API key>.reset();
// Reset the gyro angle
gyro.reset();
// Clear the drive magnitude
// Note: The calling routine must reset the magnitude to the desired value
m_magnitude = 0;
// Reset the drive encoders
encoderLeft.reset();
encoderRight.reset();
// Ensure the robot is stopped
Robot.chassis.robotDrive.arcadeDrive(0, 0);
}
/**
* Method to shift the drive train
*/
public void shiftGear(boolean gearHigh)
{
// Control the gear shift piston
transmission.set(gearHigh);
m_highGear = gearHigh;
}
/**
* Method to set the transmission to high gear
*/
public void setGearHigh()
{
// Set the transmission to high gear
m_highGear = true;
transmission.set(m_highGear);
}
/**
* Method to set the transmission to low gear
*/
public void setGearLow()
{
// Set the transmission to low gear
m_highGear = false;
transmission.set(m_highGear);
}
/**
* Method to return the state of the transmission
*/
public boolean isGearHigh()
{
return m_highGear;
}
/**
* Method to control the drive through the specified joystick
*/
public void driveWithJoystick(Joystick stick)
{
// Square twist to decrease sensitivity
double twist = stick.getTwist() * Constants.TWIST_MULTIPLIER;
// Determine if the twist is negative to allow restoring the sign
if (twist < 0)
{
// Remember to preserve direction, it is lost when squaring
twist = -1.0 * (twist * twist);
}
else
{
twist = twist * twist;
}
// Square forward/backward to decrease sensitivity
double moveValue = stick.getY();
if (moveValue < 0)
{
// Remember to preserve direction, it is lost when squaring
moveValue = -1.0 * (moveValue * moveValue);
}
else
{
moveValue = moveValue * moveValue;
}
// Determine if the robot "front" should be the back
if (stick.getRawButton(Constants.<API key>))
{
moveValue = -1.0 * moveValue; // reverse moveValue
}
// Drive with arcade control
Robot.chassis.robotDrive.arcadeDrive(moveValue, twist);
}
/**
* Method to configure the gyro based turn/drive straight PID controller
*/
public void driveStraightPID(double power, boolean highGear)
{
// Set the transmission to the specified gear
if (highGear == true)
{
setGearHigh();
}
else
{
setGearLow();
}
// Drive straight means keep current heading
startGyroPID(Constants.<API key>, Constants.<API key>,
Constants.<API key>, Constants.<API key>,
Constants.<API key>, getCurrentHeading());
// Update the drive power
m_magnitude = power;
}
/**
* Method to configure the gyro based turn/drive straight PID controller
*/
public void turnAnglePID(double desiredHeading, double power, boolean highGear)
{
// Set the transmission to the specified gear
if (highGear == true)
{
setGearHigh();
}
else
{
setGearLow();
}
// Turn to the desired heading current heading
startGyroPID(Constants.TURN_ANGLE_P,
Constants.TURN_ANGLE_I,
Constants.TURN_ANGLE_D,
Constants.<API key>,
Constants.<API key>, desiredHeading);
// Update the drive power
m_magnitude = power;
}
/**
* method to enable the encoderPID
*/
public void <API key>(double desiredEncoderValue)
{
// Reset other PIDS
<API key>();
// Set the desired Encoder values
<API key>(desiredEncoderValue);
// Enable the chassis PID position controllers
<API key>.enable();
<API key>.enable();
}
/**
* Method to update the encoder PID target value (heading)
*/
public void <API key>(double desiredEncoderValue)
{
// Update the chassis position set points
<API key>.setSetpoint(-desiredEncoderValue);
<API key>.setSetpoint(desiredEncoderValue);
}
/**
* Method to update the chassis encoders set points from the image target
*/
public void <API key>(Target target)
{
// Get the present set point
double encoderPosition = Robot.chassis.getEncoderSetpoint();
// Get the deviation from the target based on the camera image
double deviationFromTarget = target.deviationFromTarget();
// Determine which way to turn
if (deviationFromTarget < -Constants.<API key>)
{
encoderPosition += Constants.<API key>;
}
else if (deviationFromTarget > Constants.<API key>)
{
encoderPosition -= Constants.<API key>;
}
// If the deviation is really large, jog the encoder position a second time
if (deviationFromTarget < (-2 * Constants.<API key>))
{
encoderPosition += Constants.<API key>;
}
else if (deviationFromTarget > (2 * Constants.<API key>))
{
encoderPosition -= Constants.<API key>;
}
// Update the encode set points
<API key>(encoderPosition);
}
/**
* Method to get the encoder PID target value (heading)
*/
public double getEncoderSetpoint()
{
return <API key>.getSetpoint();
}
/**
*
* Method to get the encoder PID error
*/
public double <API key>()
{
return <API key>.getError();
}
/**
*
* Method to get the encoder PID error
*/
public double <API key>()
{
// Return the Right set point
// Note: The Left set point should just be the negative of the Left
return <API key>.getError();
}
/**
* Method to set the angle encoder PID controller PID values from the SmartDashboard
*/
public void <API key>()
{
double P = SmartDashboard.getNumber("angleEncoderPID P", <API key>.getP());
double I = SmartDashboard.getNumber("angleEncoderPID I", <API key>.getI());
double D = SmartDashboard.getNumber("angleEncoderPID D", <API key>.getD());
<API key>.setPID(P, I, D);
<API key>.setPID(P, I, D);
}
/**
* Method to update output power while under PID control ie. after startGyroPID() is called
*/
public void updateMagnitude(double magnitude)
{
// Update the drive magnitude
m_magnitude = magnitude;
}
// Methods to get values from chassis sensors
/**
* Method to return the present gyro angle
*/
public double getCurrentHeading()
{
// Return the present gyro heading
return gyro.getAngle();
}
/**
* Method to determine if the gyro angle is within the specified range
*/
public boolean gyroWithin(double threshold)
{
// SmartDashboard.putNumber("Error", angleGyroPID.getError());
// Return if the gyro is within the specified range
return Math.abs(angleGyroPID.getError()) < threshold;
}
/**
* Method to return the maximum of the two chassas wheel encoders
*/
public double getEncoderDistance()
{
// Return the maximum encoder distance in case the other is not working
return Math.max(encoderLeft.getDistance(), encoderRight.getDistance());
}
/**
* Compute the distance based on the ultrasonic sensor
*/
public double <API key>()
{
// Return the distance in inches
return ((Constants.ULTRASONIC_Y2 - Constants.ULTRASONIC_Y1) / (Constants.ULTRASONIC_X2 - Constants.ULTRASONIC_X1)) *
(ultrasound.getVoltage() - Constants.ULTRASONIC_X1) + Constants.ULTRASONIC_Y1;
}
// Private helpers
/**
* set chassis to be under PID control
*
* @param P
* @param I
* @param D
* @param minimumOutput
* @param maximumOutput
* @param tolerance
* @param desiredHeading
* (relative to current heading, 0 is keep current heading)
*/
private void startGyroPID(double P, double I, double D, double minimumOutput, double maximumOutput, double desiredHeading)
{
// reset other PIDS
<API key>();
// Initialize the Gryo angle PID parameters
angleGyroPID.setPID(P, I, D);
// Set the desired chassis heading
angleGyroPID.setSetpoint(desiredHeading);
// Limit the output power when turning
angleGyroPID.setOutputRange(minimumOutput, maximumOutput);
// Enable the Gyro PID
angleGyroPID.enable();
}
/**
* Method to set the desired heading
*/
public void <API key>(double desiredHeading)
{
// Set the desired chassis heading
angleGyroPID.setSetpoint(desiredHeading);
}
/**
* Class declaration for the PIDOutput
*/
private class AnglePIDOutput implements PIDOutput
{
/**
* Virtual function to receive the PID output and set the drive direction
*/
public void pidWrite(double PIDoutput)
{
// Drive the robot given the speed and direction
// Note: The Arcade drive expects a joystick which is negative forward
robotDrive.arcadeDrive(-m_magnitude, PIDoutput, false);
}
}
/**
* Class declaration for the PIDOutput
*/
public class <API key> implements PIDOutput
{
/**
* Virtual function to receive the PID output and set the drive direction
*/
public void pidWrite(double PIDoutput)
{
driveRight.set(PIDoutput + m_magnitude);
// SmartDashboard.putNumber("Right Output", PIDoutput);
}
}
/**
* Class declaration for the PIDOutput
*/
public class <API key> implements PIDOutput
{
/**
* Virtual function to receive the PID output and set the drive direction
*/
public void pidWrite(double PIDoutput)
{
driveLeft.set(-PIDoutput + m_magnitude);
// SmartDashboard.putNumber("Left Output", -PIDoutput);
}
}
} |
import { nullTranslator } from '@jupyterlab/translation';
import Input from '@material-ui/core/Input';
import { shallow } from 'enzyme';
import 'jest';
import * as React from 'react';
import {
CommitMessage,
ICommitMessageProps
} from '../../src/components/CommitMessage';
describe('CommitMessage', () => {
const trans = nullTranslator.load('jupyterlab_git');
const defaultProps: ICommitMessageProps = {
setSummary: () => {},
setDescription: () => {},
summary: '',
description: '',
trans: trans
};
it('should set a `title` attribute on the input element to provide a commit message summary', () => {
const props = defaultProps;
const component = shallow(<CommitMessage {...props} />);
const node = component.find(Input).first();
expect(node.prop('title').length > 0).toEqual(true);
});
it('should display placeholder text for the commit message description', () => {
const props = defaultProps;
const component = shallow(<CommitMessage {...props} />);
const node = component.find(Input).last();
expect(node.prop('placeholder')).toEqual('Description (optional)');
});
it('should set a `title` attribute on the input element to provide a commit message description', () => {
const props = defaultProps;
const component = shallow(<CommitMessage {...props} />);
const node = component.find(Input).last();
expect(node.prop('title').length > 0).toEqual(true);
});
it('should disable summary input if disabled is true', () => {
const props = { ...defaultProps, disabled: true };
const component = shallow(<CommitMessage {...props} />);
const node = component.find(Input).first();
expect(node.prop('disabled')).toEqual(true);
});
it('should disable description input if disabled is true', () => {
const props = { ...defaultProps, disabled: true };
const component = shallow(<CommitMessage {...props} />);
const node = component.find(Input).last();
expect(node.prop('disabled')).toEqual(true);
});
}); |
using System;
using System.Data;
using System.Data.OleDb;
namespace MyMeta.Sql
{
#if ENTERPRISE
using System.Runtime.InteropServices;
[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IDomains))]
#endif
public class SqlDomains : Domains
{
public SqlDomains()
{
}
override internal void LoadAll()
{
try
{
string select = "SELECT * FROM INFORMATION_SCHEMA.DOMAINS";
OleDbConnection cn = new OleDbConnection(dbRoot.ConnectionString);
cn.Open();
cn.ChangeDatabase("[" + this.Database.Name + "]");
OleDbDataAdapter adapter = new OleDbDataAdapter(select, cn);
DataTable metaData = new DataTable();
adapter.Fill(metaData);
cn.Close();
PopulateArray(metaData);
}
catch {}
}
}
} |
<?php defined('SYSPATH') or die('No direct script access.');
class <API key> extends <API key> {
public $assert_auth = array('login', 'editor');
public $assert_auth_actions = array(
'delete' => array('admin'),
);
public function action_index()
{
$pages = ORM::factory('page')->get_all();
$this->template->content = View::factory('admin/pages/content')
->bind('pages', $pages);
}
public function action_manage()
{
$this->template->content = View::factory('admin/forms/content')
->bind('post', $post)
->bind('select_page', $select_page)
->bind('select_status', $select_status)
->bind('errors', $errors);
// Get id if for edit
$id = (!empty($_POST)) ? $_POST['id'] : $this->request->param('id', FALSE);
// Load pages model
$contents = ORM::factory('content', $id);
// Load pulldowns
$select_page = ORM::factory('page')->get_for_pulldown();
$select_status = $contents->select_status;
if($contents->loaded())
{
$date_published = date('m/d/Y', $contents->date_published);
if ($contents->date_expired != 0) { $date_expired = date('m/d/Y', $contents->date_expired); } else { $date_expired = $contents->date_expired; }
$post['id'] = $contents->id;
$post['user_id'] = $this->_session->get('user_id');
$post['page_id'] = $contents->page_id;
$post['content_title'] = $contents->content_title;
$post['content'] = $contents->content;
$post['status'] = $contents->status;
$post['sort'] = $contents->sort;
$post['date_published'] = $date_published;
$post['date_expired'] = $date_expired;
}
if(!empty($_POST))
{
// Convert date
$_POST['user_id'] = $this->_session->get('user_id');
$_POST['date_published'] = strtotime($_POST['date_published']);
$_POST['date_expired'] = strtotime($_POST['date_expired']);
$values = Arr::extract($_POST, array('id', 'user_id', 'page_id', 'content_title', 'content', 'status', 'sort', 'date_published', 'date_expired'));
$contents->values($values);
try
{
$contents->save();
Session::instance()->set('message', 'You content has been added/updated. | <a href="content/manage/">Add Another</a>');
$this->request->redirect('/admin/content/');
}
catch (<API key> $e)
{
$errors = $e->errors('models');
$post = $values;
}
}
}
public function action_delete()
{
$id = $this->request->param('id', false);
$contents = ORM::factory('content', $id);
if($this->request->param('var', false) == 'Y3s')
{
$contents->delete();
Session::instance()->set('message', 'Item ' . $id . ' has been deleted.');
$this->request->redirect(url::site() . 'admin/content/');
}
else
{
Session::instance()->set('message', 'Are you sure you want to delete item ' . $id . '? <a href="' . url::site() . 'admin/content/delete/' . $id . '/Y3s">Yes</a>.');
$this->request->redirect(url::site() . 'admin/content/');
}
}
} |
<!DOCTYPE html>
<html>
<body>
<script type="module">
import './<API key>.js';
window.onmessage = async message => {
if (message.data !== 'Ready') {
return;
}
try {
await window.<API key>('https://play.google.com/billing');
parent.postMessage('Success', '*');
} catch (error) {
parent.postMessage('Failure: ' + error.name + ': ' + error.message, '*');
}
};
</script>
</body>
</html> |
#ifndef <API key>
#define <API key>
#include <memory>
#include "ash/ash_export.h"
#include "base/macros.h"
#include "cc/paint/paint_flags.h"
#include "ui/display/display.h"
#include "ui/gfx/animation/linear_animation.h"
#include "ui/views/animation/<API key>.h"
#include "ui/views/view.h"
#include "ui/views/widget/unique_widget_ptr.h"
namespace views {
class Label;
} // namespace views
namespace gfx {
class Animation;
} // namespace gfx
namespace ash {
class <API key>;
class HintBox;
// An overlay view used during touch calibration. This view is responsible for
// all animations and UX during touch calibration on all displays currently
// active on the device. The view on the display being calibrated is the primary
// touch calibration view.
// |TouchCalibratorView| acts as a state machine and has an API to toggle its
// state or get the current state.
class ASH_EXPORT TouchCalibratorView : public views::View,
public views::<API key> {
public:
// Different states of |TouchCalibratorView| in order.
enum State {
UNKNOWN = 0,
<API key>, // Transition state where the background is fading
DISPLAY_POINT_1, // Static state where the touch point is at its first
// location.
ANIMATING_1_TO_2, // Transition state when the touch point is being moved
// from one location to another.
DISPLAY_POINT_2, // Static state where the touch point is at its second
// location.
ANIMATING_2_TO_3,
DISPLAY_POINT_3, // Static state where the touch point is at its third
// location.
ANIMATING_3_TO_4,
DISPLAY_POINT_4, // Static state where the touch point is at its final
// location.
<API key>, // Transition state when the calibration complete
// message is being transitioned into view.
<API key>, // Static state when the calibration complete message
// is displayed to the user.
<API key> // Transition state where the background is fading
// out
};
// Only use this function to construct. This ensures a Widget is properly
// constructed and is set as the content view.
static views::UniqueWidgetPtr Create(const display::Display& target_display,
bool is_primary_view);
~TouchCalibratorView() override;
// views::View:
void OnPaint(gfx::Canvas* canvas) override;
void OnPaintBackground(gfx::Canvas* canvas) override;
// views::<API key>:
void AnimationEnded(const gfx::Animation* animation) override;
void AnimationProgressed(const gfx::Animation* animation) override;
void AnimationCanceled(const gfx::Animation* animation) override;
// Moves the touch calibrator view to its next state.
void AdvanceToNextState();
// Skips to the final state. Should be used to cancel calibration and hide all
// views from the screen with a smooth transition out animation.
void SkipToFinalState();
// Returns true if |location| is set by the end of this function call. If set,
// |location| will point to the center of the circle that the user sees during
// the touch calibration UX.
bool <API key>(gfx::Point* location);
// Skips/cancels any ongoing animation to its end.
void <API key>();
// Returns the current state of the view.
State state() { return state_; }
private:
TouchCalibratorView(const display::Display& target_display,
bool is_primary_view);
void InitViewContents();
void <API key>();
// Animate the given |view|'s layer to |end_position| and an optional
// |opacity|.
void <API key>(views::View* view,
base::TimeDelta duration,
gfx::Point end_position,
float opacity = 1.f);
// The target display on which this view is rendered on.
const display::Display display_;
// True if this view is on the display that is being calibrated.
bool is_primary_view_;
cc::PaintFlags flags_;
// Defines the bounds for the background animation.
gfx::RectF background_rect_;
// Text label indicating how to exit the touch calibration.
views::Label* exit_label_ = nullptr;
// Text label indicating the significance of the touch point on screen.
views::Label* tap_label_ = nullptr;
// Start and end opacity values used during the fade animation. This is set
// before the animation begins.
float <API key> = 0.0f;
float end_opacity_value_ = 0.0f;
// Linear animation used for various aniations including fade-in, fade out,
// and view translation.
std::unique_ptr<gfx::LinearAnimation> animator_;
// View responsible for displaying the animated circular icon that the user
// touches to calibrate the screen.
<API key>* throbber_circle_ = nullptr;
// A hint box displayed next to the first touch point to assist user with
// information about the next step.
HintBox* hint_box_view_ = nullptr;
// Final view containing the calibration complete message along with an icon.
views::View* <API key> = nullptr;
// View that contains the animated throbber circle and a text label informing
// the user to tap the circle to continue calibration.
views::View* touch_point_view_ = nullptr;
State state_ = UNKNOWN;
};
} // namespace ash
#endif // <API key> |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: <API key>.cpp
Label Definition File: <API key>.label.xml
Template File: <API key>.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: malloc Allocate data using malloc()
* GoodSource: Allocate data using new
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITGOOD
#include "std_testcase.h"
#include "<API key>.h"
namespace <API key>
{
<API key>::<API key>(twoIntsStruct * dataCopy)
{
data = dataCopy;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (twoIntsStruct *)malloc(100*sizeof(twoIntsStruct));
if (data == NULL) {exit(-1);}
}
<API key>::~<API key>()
{
/* FIX: Deallocate the memory using free() */
free(data);
}
}
#endif /* OMITGOOD */ |
<!DOCTYPE html>
<html xmlns="http:
<head>
<meta charset="utf-8" />
<title>statsmodels.sandbox.regression.gmm.GMM.gradient_momcond — statsmodels v0.10.1 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/graphviz.css" />
<script type="text/javascript" id="<API key>" data-url_root="../" src="../_static/<API key>.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="../_static/language_data.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=<API key>"></script>
<link rel="shortcut icon" href="../_static/<API key>.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.sandbox.regression.gmm.GMM.momcond_mean" href="statsmodels.sandbox.regression.gmm.GMM.momcond_mean.html" />
<link rel="prev" title="statsmodels.sandbox.regression.gmm.GMM.gmmobjective_cu" href="statsmodels.sandbox.regression.gmm.GMM.gmmobjective_cu.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../_static/closelabel.png"
$.facebox.settings.loadingImage = "../_static/loading.gif"
</script>
<script>
$(document).ready(function() {
$.getJSON("../../versions.json", function(versions) {
var dropdown = document.createElement("div");
dropdown.className = "dropdown";
var button = document.createElement("button");
button.className = "dropbtn";
button.innerHTML = "Other Versions";
var content = document.createElement("div");
content.className = "dropdown-content";
dropdown.appendChild(button);
dropdown.appendChild(content);
$(".header").prepend(dropdown);
for (var i = 0; i < versions.length; i++) {
if (versions[i].substring(0, 1) == "v") {
versions[i] = [versions[i], versions[i].substring(1)];
} else {
versions[i] = [versions[i], versions[i]];
};
};
for (var i = 0; i < versions.length; i++) {
var a = document.createElement("a");
a.innerHTML = versions[i][1];
a.href = "../../" + versions[i][0] + "/index.html";
a.title = versions[i][1];
$(".dropdown-content").append(a);
};
});
});
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/<API key>.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.sandbox.regression.gmm.GMM.momcond_mean.html" title="statsmodels.sandbox.regression.gmm.GMM.momcond_mean"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.sandbox.regression.gmm.GMM.gmmobjective_cu.html" title="statsmodels.sandbox.regression.gmm.GMM.gmmobjective_cu"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../gmm.html" >Generalized Method of Moments <code class="xref py py-mod docutils literal notranslate"><span class="pre">gmm</span></code></a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.sandbox.regression.gmm.GMM.html" accesskey="U">statsmodels.sandbox.regression.gmm.GMM</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="<API key>">
<h1>statsmodels.sandbox.regression.gmm.GMM.gradient_momcond<a class="headerlink" href="
<p>method</p>
<dl class="method">
<dt id="statsmodels.sandbox.regression.gmm.GMM.gradient_momcond">
<code class="sig-prename descclassname">GMM.</code><code class="sig-name descname">gradient_momcond</code><span class="sig-paren">(</span><em class="sig-param">params</em>, <em class="sig-param">epsilon=0.0001</em>, <em class="sig-param">centered=True</em><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/sandbox/regression/gmm.html
<dd><p>gradient of moment conditions</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><dl class="simple">
<dt><strong>params</strong><span class="classifier">ndarray</span></dt><dd><p>parameter at which the moment conditions are evaluated</p>
</dd>
<dt><strong>epsilon</strong><span class="classifier">float</span></dt><dd><p>stepsize for finite difference calculation</p>
</dd>
<dt><strong>centered</strong><span class="classifier">bool</span></dt><dd><p>This refers to the finite difference calculation. If <cite>centered</cite>
is true, then the centered finite difference calculation is
used. Otherwise the one-sided forward differences are used.</p>
</dd>
<dt><strong>TODO: looks like not used yet</strong></dt><dd><p>missing argument <cite>weights</cite></p>
</dd>
</dl>
</dd>
</dl>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="<API key>">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.sandbox.regression.gmm.GMM.gmmobjective_cu.html"
title="previous chapter">statsmodels.sandbox.regression.gmm.GMM.gmmobjective_cu</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.sandbox.regression.gmm.GMM.momcond_mean.html"
title="next chapter">statsmodels.sandbox.regression.gmm.GMM.momcond_mean</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.sandbox.regression.gmm.GMM.gradient_momcond.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" />
<input type="submit" value="Go" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
&
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2.
</div>
</body>
</html> |
<!DOCTYPE HTML PUBLIC "-
<!--NewPage
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_16) on Thu Aug 06 18:12:56 PDT 2009 -->
<TITLE>
All Classes (CaMachineLearning API)
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<FONT size="+1" CLASS="FrameHeadingFont">
<B>All Classes</B></FONT>
<BR>
<TABLE BORDER="0" WIDTH="100%" SUMMARY="">
<TR>
<TD NOWRAP><FONT CLASS="FrameItemFont"><A HREF="org/bioconductor/packages/caMachineLearning/service/globus/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.service.globus" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/client/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.client" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/client/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.client" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/service/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.service" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/common/<API key>.html" title="interface in org.bioconductor.packages.caMachineLearning.common" target="classFrame"><I><API key></I></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/service/globus/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.context.service.globus" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/client/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.context.client" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/client/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.context.client" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/common/<API key>.html" title="interface in org.bioconductor.packages.caMachineLearning.context.common" target="classFrame"><I><API key></I></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/common/<API key>.html" title="interface in org.bioconductor.packages.caMachineLearning.context.common" target="classFrame"><I><API key></I></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/service/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.context.service" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/service/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.context.service" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/service/globus/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.context.service.globus" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/service/globus/resource/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.context.service.globus.resource" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/service/globus/resource/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.context.service.globus.resource" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/service/globus/resource/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.context.service.globus.resource" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/context/service/globus/resource/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.context.service.globus.resource" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/common/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.common" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/common/CaMachineLearningI.html" title="interface in org.bioconductor.packages.caMachineLearning.common" target="classFrame"><I>CaMachineLearningI</I></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/service/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.service" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/service/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.service" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/service/globus/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.service.globus" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/service/globus/resource/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.service.globus.resource" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/service/globus/resource/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.service.globus.resource" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/service/globus/resource/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.service.globus.resource" target="classFrame"><API key></A>
<BR>
<A HREF="org/bioconductor/packages/caMachineLearning/service/globus/resource/<API key>.html" title="class in org.bioconductor.packages.caMachineLearning.service.globus.resource" target="classFrame"><API key></A>
<BR>
</FONT></TD>
</TR>
</TABLE>
</BODY>
</HTML> |
package eu.sarunas.atf.meta.sut;
import java.util.ArrayList;
import java.util.List;
public class Library extends Element implements ILibrary
{
public Library(Project project, String name, Object sourceElement)
{
super(name, sourceElement);
this.project = project;
};
public void addPackage(String packageName, Object sourceElement)
{
Package p = getPackage(packageName);
if (null == p)
{
p = new Package(this.project, packageName, sourceElement);
this.packages.add(p);
}
};
public Package getPackage(String packageName)
{
for (Package p : this.packages)
{
if (true == p.getName().equals(packageName))
{
return p;
}
}
return null;
};
public List<Package> getPackages()
{
return this.packages;
};
public Package getDefaultPackage()
{
Package p = getPackage("");
if (null == p)
{
addPackage("", null);
return getPackage("");
}
else
{
return p;
}
};
private Project project = null;
protected List<Package> packages = new ArrayList<Package>();
}; |
<!doctype html>
<!
Copyright (c) 2012, Motorola Mobility LLC.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of Motorola Mobility LLC 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>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Montage tests</title>
<!-- <meta http-equiv="refresh" content="1"> -->
<script src="../montage.js" data-module="run"></script>
<script src="support/jasmine-1.1.0.rc1/jasmine.js"></script>
<script src="support/reporters/trivial-html.js"></script>
<script src="support/reporters/jasmine.junit_reporter.js"></script>
<script src="support/js-beautify/beautify.js"></script>
<script src="support/spec-helper.js"></script>
<link rel="stylesheet" type="text/css" href="support/reporters/style.css">
<link rel="stylesheet" type="text/css" href="support/styles.css">
<script type="text/javascript">
jasmine.getEnv().addReporter(new jasmine.JUnitXmlReporter());
var __jasmine_reports = {};
function jasmineJunitReport(filename, text) {
console.log("Report: " + filename);
__jasmine_reports[filename] = text;
}
</script>
</head>
<body></body>
</html> |
import numpy as np
from holoviews.core.overlay import NdOverlay
from holoviews.core.spaces import HoloMap
from holoviews.element import Points
from .testplot import TestMPLPlot, mpl_renderer
from ..utils import ParamLogStream
try:
from matplotlib import pyplot
except:
pass
class TestPointPlot(TestMPLPlot):
def <API key>(self):
data = (np.arange(10), np.arange(10), list(map(chr, range(94,104))))
points = Points(data, vdims=['z']).opts(plot=dict(size_index=2))
with ParamLogStream() as log:
plot = mpl_renderer.get_plot(points)
log_msg = log.stream.read()
warning = ('%s: z dimension is not numeric, '
'cannot use to scale Points size.\n' % plot.name)
self.assertEqual(log_msg, warning)
def <API key>(self):
img = Points(([0, 1], [0, 3])).redim(y=dict(range=(1,2)))
plot = mpl_renderer.get_plot(img(plot=dict(colorbar=True, color_index=1)))
self.assertEqual(plot.handles['cbar'].extend, 'both')
def <API key>(self):
img = Points(([0, 1], [0, 3])).redim(y=dict(range=(1, None)))
plot = mpl_renderer.get_plot(img(plot=dict(colorbar=True, color_index=1)))
self.assertEqual(plot.handles['cbar'].extend, 'min')
def <API key>(self):
img = Points(([0, 1], [0, 3])).redim(y=dict(range=(None, 2)))
plot = mpl_renderer.get_plot(img(plot=dict(colorbar=True, color_index=1)))
self.assertEqual(plot.handles['cbar'].extend, 'max')
def <API key>(self):
img = Points(([0, 1], [0, 3])).opts(style=dict(clim=(None, None)))
plot = mpl_renderer.get_plot(img(plot=dict(colorbar=True, color_index=1)))
self.assertEqual(plot.handles['cbar'].extend, 'neither')
def <API key>(self):
opts = dict(fig_rcparams={'text.usetex': True})
points = Points(([0, 1], [0, 3])).opts(plot=opts)
mpl_renderer.get_plot(points)
self.assertFalse(pyplot.rcParams['text.usetex'])
def <API key>(self):
opts = dict(fig_rcparams={'grid.color': 'red'})
points = Points(([0, 1], [0, 3])).opts(plot=opts)
plot = mpl_renderer.get_plot(points)
ax = plot.state.axes[0]
lines = ax.get_xgridlines()
self.assertEqual(lines[0].get_color(), 'red')
def <API key>(self):
points = Points([1, 2, 3]).options(padding=0.1)
plot = mpl_renderer.get_plot(points)
x_range, y_range = plot.handles['axis'].get_xlim(), plot.handles['axis'].get_ylim()
self.assertEqual(x_range[0], -0.2)
self.assertEqual(x_range[1], 2.2)
self.assertEqual(y_range[0], 0.8)
self.assertEqual(y_range[1], 3.2)
def <API key>(self):
curve = Points([1, 2, 3]).options(padding=((0, 0.1), (0.1, 0.2)))
plot = mpl_renderer.get_plot(curve)
x_range, y_range = plot.handles['axis'].get_xlim(), plot.handles['axis'].get_ylim()
self.assertEqual(x_range[0], 0)
self.assertEqual(x_range[1], 2.2)
self.assertEqual(y_range[0], 0.8)
self.assertEqual(y_range[1], 3.4)
def <API key>(self):
points = Points([1, 2, 3]).redim.range(x=(0, 3)).options(padding=0.1)
plot = mpl_renderer.get_plot(points)
x_range, y_range = plot.handles['axis'].get_xlim(), plot.handles['axis'].get_ylim()
self.assertEqual(x_range[0], 0)
self.assertEqual(x_range[1], 3)
self.assertEqual(y_range[0], 0.8)
self.assertEqual(y_range[1], 3.2)
def <API key>(self):
points = Points([1, 2, 3]).redim.soft_range(x=(0, 3)).options(padding=0.1)
plot = mpl_renderer.get_plot(points)
x_range, y_range = plot.handles['axis'].get_xlim(), plot.handles['axis'].get_ylim()
self.assertEqual(x_range[0], -0.2)
self.assertEqual(x_range[1], 3)
self.assertEqual(y_range[0], 0.8)
self.assertEqual(y_range[1], 3.2)
def <API key>(self):
points = Points([1, 2, 3]).options(padding=(0.05, 0.1))
plot = mpl_renderer.get_plot(points)
x_range, y_range = plot.handles['axis'].get_xlim(), plot.handles['axis'].get_ylim()
self.assertEqual(x_range[0], -0.1)
self.assertEqual(x_range[1], 2.1)
self.assertEqual(y_range[0], 0.8)
self.assertEqual(y_range[1], 3.2)
def <API key>(self):
points = Points([1, 2, 3]).options(padding=0.1, aspect=2)
plot = mpl_renderer.get_plot(points)
x_range, y_range = plot.handles['axis'].get_xlim(), plot.handles['axis'].get_ylim()
self.assertEqual(x_range[0], -0.1)
self.assertEqual(x_range[1], 2.1)
self.assertEqual(y_range[0], 0.8)
self.assertEqual(y_range[1], 3.2)
def <API key>(self):
points = Points([(1, 1), (2, 2), (3,3)]).options(padding=0.1, logx=True)
plot = mpl_renderer.get_plot(points)
x_range, y_range = plot.handles['axis'].get_xlim(), plot.handles['axis'].get_ylim()
self.assertEqual(x_range[0], 0.89595845984076228)
self.assertEqual(x_range[1], 3.3483695221017129)
self.assertEqual(y_range[0], 0.8)
self.assertEqual(y_range[1], 3.2)
def <API key>(self):
points = Points([1, 2, 3]).options(padding=0.1, logy=True)
plot = mpl_renderer.get_plot(points)
x_range, y_range = plot.handles['axis'].get_xlim(), plot.handles['axis'].get_ylim()
self.assertEqual(x_range[0], -0.2)
self.assertEqual(x_range[1], 2.2)
self.assertEqual(y_range[0], 0.89595845984076228)
self.assertEqual(y_range[1], 3.3483695221017129)
def <API key>(self):
points = Points([(np.datetime64('2016-04-0%d' % i), i) for i in range(1, 4)]).options(
padding=0.1
)
plot = mpl_renderer.get_plot(points)
x_range, y_range = plot.handles['axis'].get_xlim(), plot.handles['axis'].get_ylim()
self.assertEqual(x_range[0], 736054.80000000005)
self.assertEqual(x_range[1], 736057.19999999995)
self.assertEqual(y_range[0], 0.8)
self.assertEqual(y_range[1], 3.2)
def <API key>(self):
points = Points([(np.datetime64('2016-04-0%d' % i), i) for i in range(1, 4)]).options(
padding=0.1, aspect=2
)
plot = mpl_renderer.get_plot(points)
x_range, y_range = plot.handles['axis'].get_xlim(), plot.handles['axis'].get_ylim()
self.assertEqual(x_range[0], 736054.90000000002)
self.assertEqual(x_range[1], 736057.09999999998)
self.assertEqual(y_range[0], 0.8)
self.assertEqual(y_range[1], 3.2)
def <API key>(self):
hmap = HoloMap({i: Points([1, 2, 3]).opts(s=i*10) for i in range(1, 3)})
plot = mpl_renderer.get_plot(hmap)
artist = plot.handles['artist']
plot.update((1,))
self.assertEqual(artist.get_sizes(), np.array([10]))
plot.update((2,))
self.assertEqual(artist.get_sizes(), np.array([20]))
# Styling mapping #
def test_point_color_op(self):
points = Points([(0, 0, '#000000'), (0, 1, '#FF0000'), (0, 2, '#00FF00')],
vdims='color').options(color='color')
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
self.assertEqual(artist.get_facecolors(),
np.array([[0, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1]]))
def <API key>(self):
points = HoloMap({0: Points([(0, 0, '#000000'), (0, 1, '#FF0000'), (0, 2, '#00FF00')],
vdims='color'),
1: Points([(0, 0, '#0000FF'), (0, 1, '#00FF00'), (0, 2, '#FF0000')],
vdims='color')}).options(color='color')
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
plot.update((1,))
self.assertEqual(artist.get_facecolors(),
np.array([[0, 0, 1, 1], [0, 1, 0, 1], [1, 0, 0, 1]]))
def <API key>(self):
points = Points([(0, 0, '#000000'), (0, 1, '#FF0000'), (0, 2, '#00FF00')],
vdims='color').options(edgecolors='color')
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
self.assertEqual(artist.get_edgecolors(),
np.array([[0, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1]]))
def <API key>(self):
points = HoloMap({0: Points([(0, 0, '#000000'), (0, 1, '#FF0000'), (0, 2, '#00FF00')],
vdims='color'),
1: Points([(0, 0, '#0000FF'), (0, 1, '#00FF00'), (0, 2, '#FF0000')],
vdims='color')}).options(edgecolors='color')
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
plot.update((1,))
self.assertEqual(artist.get_edgecolors(),
np.array([[0, 0, 1, 1], [0, 1, 0, 1], [1, 0, 0, 1]]))
def <API key>(self):
points = Points([(0, 0, '#000000'), (0, 1, '#FF0000'), (0, 2, '#00FF00')],
vdims='color').options(facecolors='color')
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
self.assertEqual(artist.get_facecolors(),
np.array([[0, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1]]))
def <API key>(self):
points = Points([(0, 0, 0), (0, 1, 1), (0, 2, 2)],
vdims='color').options(color='color')
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
self.assertEqual(artist.get_array(), np.array([0, 1, 2]))
self.assertEqual(artist.get_clim(), (0, 2))
def <API key>(self):
points = HoloMap({0: Points([(0, 0, 0), (0, 1, 1), (0, 2, 2)],
vdims='color'),
1: Points([(0, 0, 2.5), (0, 1, 3), (0, 2, 1.2)],
vdims='color')}).options(color='color', framewise=True)
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
self.assertEqual(artist.get_clim(), (0, 2))
plot.update((1,))
self.assertEqual(artist.get_array(), np.array([2.5, 3, 1.2]))
self.assertEqual(artist.get_clim(), (1.2, 3))
def <API key>(self):
points = Points([(0, 0, 'A'), (0, 1, 'B'), (0, 2, 'A')],
vdims='color').options(color='color')
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
self.assertEqual(artist.get_array(), np.array([0, 1, 0]))
self.assertEqual(artist.get_clim(), (0, 1))
def test_point_size_op(self):
points = Points([(0, 0, 1), (0, 1, 4), (0, 2, 8)],
vdims='size').options(s='size')
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
self.assertEqual(artist.get_sizes(), np.array([1, 4, 8]))
def <API key>(self):
points = HoloMap({0: Points([(0, 0, 3), (0, 1, 1), (0, 2, 2)],
vdims='size'),
1: Points([(0, 0, 2.5), (0, 1, 3), (0, 2, 1.2)],
vdims='size')}).options(s='size')
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
self.assertEqual(artist.get_sizes(), np.array([3, 1, 2]))
plot.update((1,))
self.assertEqual(artist.get_sizes(), np.array([2.5, 3, 1.2]))
def <API key>(self):
points = Points([(0, 0, 1), (0, 1, 4), (0, 2, 8)],
vdims='line_width').options(linewidth='line_width')
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
self.assertEqual(artist.get_linewidths(), [1, 4, 8])
def <API key>(self):
points = HoloMap({0: Points([(0, 0, 3), (0, 1, 1), (0, 2, 2)],
vdims='line_width'),
1: Points([(0, 0, 2.5), (0, 1, 3), (0, 2, 1.2)],
vdims='line_width')}).options(linewidth='line_width')
plot = mpl_renderer.get_plot(points)
artist = plot.handles['artist']
self.assertEqual(artist.get_linewidths(), [3, 1, 2])
plot.update((1,))
self.assertEqual(artist.get_linewidths(), [2.5, 3, 1.2])
def <API key>(self):
points = Points([(0, 0, 'circle'), (0, 1, 'triangle'), (0, 2, 'square')],
vdims='marker').options(marker='marker')
with self.assertRaises(Exception):
mpl_renderer.get_plot(points)
def test_point_alpha_op(self):
points = Points([(0, 0, 0), (0, 1, 0.2), (0, 2, 0.7)],
vdims='alpha').options(alpha='alpha')
with self.assertRaises(Exception):
mpl_renderer.get_plot(points)
def <API key>(self):
markers = ['d', 's']
overlay = NdOverlay({marker: Points(np.arange(i))
for i, marker in enumerate(markers)},
'Marker').options('Points', marker='Marker')
plot = mpl_renderer.get_plot(overlay)
for subplot, marker in zip(plot.subplots.values(), markers):
style = dict(subplot.style[subplot.cyclic_index])
style = subplot._apply_transforms(subplot.current_frame, {}, style)
self.assertEqual(style['marker'], marker)
def <API key>(self):
points = Points([(0, 0, 0), (0, 1, 1), (0, 2, 2)],
vdims='color').options(color='color', color_index='color')
with ParamLogStream() as log:
plot = mpl_renderer.get_plot(points)
log_msg = log.stream.read()
warning = ("%s: Cannot declare style mapping for 'color' option "
"and declare a color_index; ignoring the color_index.\n"
% plot.name)
self.assertEqual(log_msg, warning)
def <API key>(self):
points = Points([(0, 0, 0), (0, 1, 1), (0, 2, 2)],
vdims='size').options(s='size', size_index='size')
with ParamLogStream() as log:
plot = mpl_renderer.get_plot(points)
log_msg = log.stream.read()
warning = ("%s: Cannot declare style mapping for 's' option "
"and declare a size_index; ignoring the size_index.\n"
% plot.name)
self.assertEqual(log_msg, warning) |
// This file is part of the MFEM library. For more information and source code
// MFEM is free software; you can redistribute it and/or modify it under the
// CONTRIBUTING.md for details.
#include "bench.hpp"
#ifdef MFEM_USE_BENCHMARK
using namespace mfem;
// Default macro to register the tests
#define <API key>(x) BENCHMARK(x)->Arg(1);
// Base class, no virtuals
struct Base
{
void NoOperation()
{
int unused;
benchmark::DoNotOptimize(unused);
asm volatile("nop" : "=r" (unused));
}
};
static void Base(benchmark::State& state)
{
struct Base b;
for (auto _ : state) { b.NoOperation(); }
}
<API key>(Base);
// Base class, with virtuals
class Base_Virtuals
{
public:
virtual void NoOperation()
{
int unused;
benchmark::DoNotOptimize(unused);
asm volatile("nop" : "=r" (unused));
}
};
static void <API key>(benchmark::State& state)
{
// it will be resolved at compile time, so it can be inlined
Base_Virtuals b;
for (auto _ : state) { b.NoOperation(); }
}
<API key>(<API key>);
// Base derived class, with virtuals
class <API key>: public Base_Virtuals
{
public:
void NoOperation()
{
int unused;
benchmark::DoNotOptimize(unused);
asm volatile("nop" : "=r" (unused));
}
};
static void <API key>(benchmark::State& state)
{
// cannot be inlined through the pointer
Base_Virtuals *ptr = new <API key>();
for (auto _ : state) { ptr->NoOperation(); }
}
<API key>(<API key>);
// --benchmark_filter=all
int main(int argc, char *argv[])
{
mfem::Reporter mfem_reporter;
::benchmark::Initialize(&argc, argv);
if (::benchmark::<API key>(argc, argv)) { return 1; }
::benchmark::<API key>(&mfem_reporter);
return 0;
}
#endif // MFEM_USE_BENCHMARK |
CKEDITOR.plugins.setLang( 'table', 'no', {
border: 'Rammer',
caption: 'Tittel',
cell: {
menu: 'Celle',
insertBefore: 'Sett inn celle før',
insertAfter: 'Sett inn celle etter',
deleteCell: 'Slett celler',
merge: 'Slå sammen celler',
mergeRight: 'Slå sammen høyre',
mergeDown: 'Slå sammen ned',
splitHorizontal: 'Del celle horisontalt',
splitVertical: 'Del celle vertikalt',
title: 'Celleegenskaper',
cellType: 'Celletype',
rowSpan: 'Radspenn',
colSpan: 'Kolonnespenn',
wordWrap: 'Tekstbrytning',
hAlign: 'Horisontal justering',
vAlign: 'Vertikal justering',
alignBaseline: 'Grunnlinje',
bgColor: 'Bakgrunnsfarge',
borderColor: 'Rammefarge',
data: 'Data',
header: 'Overskrift',
yes: 'Ja',
no: 'Nei',
invalidWidth: 'Cellebredde må være et tall.',
invalidHeight: 'Cellehøyde må være et tall.',
invalidRowSpan: 'Radspenn må være et heltall.',
invalidColSpan: 'Kolonnespenn må være et heltall.',
chooseColor: 'Velg'
},
cellPad: 'Cellepolstring',
cellSpace: 'Cellemarg',
column: {
menu: 'Kolonne',
insertBefore: 'Sett inn kolonne før',
insertAfter: 'Sett inn kolonne etter',
deleteColumn: 'Slett kolonner'
},
columns: 'Kolonner',
deleteTable: 'Slett tabell',
headers: 'Overskrifter',
headersBoth: 'Begge',
headersColumn: 'Første kolonne',
headersNone: 'Ingen',
headersRow: 'Første rad',
invalidBorder: 'Rammestørrelse må være et tall.',
invalidCellPadding: 'Cellepolstring må være et positivt tall.',
invalidCellSpacing: 'Cellemarg må være et positivt tall.',
invalidCols: 'Antall kolonner må være et tall større enn 0.',
invalidHeight: 'Tabellhøyde må være et tall.',
invalidRows: 'Antall rader må være et tall større enn 0.',
invalidWidth: 'Tabellbredde må være et tall.',
menu: 'Egenskaper for tabell',
row: {
menu: 'Rader',
insertBefore: 'Sett inn rad før',
insertAfter: 'Sett inn rad etter',
deleteRow: 'Slett rader'
},
rows: 'Rader',
summary: 'Sammendrag',
title: 'Egenskaper for tabell',
toolbar: 'Tabell',
widthPc: 'prosent',
widthPx: 'piksler',
widthUnit: 'Bredde-enhet'
}); |
# OCCAM
# modification, are permitted provided that the following conditions are met:
# and/or other materials provided with the distribution.
# * Neither the name of SRI International nor the names of its contributors may
# be used to endorse or promote products derived from this software without
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# 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.
from occam import target
import sys
def readFile(fn):
if fn == '-':
return sys.stdin.read()
else:
return open(fn, 'r').read()
class RunTool (target.Target):
def usage(self):
return "%s args+" % self.name
def desc(self):
return """ Run the command in the occam environment."""
def run(self, cfg, flags, args):
if len(args) < 1:
raise target.ArgError()
# TODO : need to handle this...
assert False # not implemented
target.register('run', RunTool('run')) |
// Use of this source code is governed by a BSD-style
// +build !appengine
package main
import "net/http"
func getuser(w http.ResponseWriter, r *http.Request) string {
return "anonymous"
}
func signout(w http.ResponseWriter, r *http.Request) {
} |
import { assert } from '../../../platform/chai-web.js';
import { SingletonOpTypes } from '../../../crdt/lib-crdt.js';
import { StorageProxy, NoOpStorageProxy } from '../storage-proxy.js';
import { ProxyMessageType } from '../store-interface.js';
import { MockHandle, MockStoreInfo, MockStore } from '../testing/test-storage.js';
import { EntityType, SingletonType } from '../../../types/lib-types.js';
import { <API key> } from '../<API key>.js';
function getNoOpStorageProxy() {
return new NoOpStorageProxy();
}
const singletonEntityType = new SingletonType(EntityType.make([], {}));
const initialData = { values: { '1': { value: { id: 'e1' }, version: { A: 1 } } }, version: { A: 1 } };
describe('StorageProxy', async () => {
it('will apply and propagate operation', async () => {
const mockStoreInfo = new MockStoreInfo(singletonEntityType);
const mockStore = new MockStore(mockStoreInfo, initialData);
const storageProxy = new StorageProxy(new <API key>(mockStore));
// Register a handle to verify updates are sent back.
const handle = new MockHandle(storageProxy);
const op = {
type: SingletonOpTypes.Set,
value: { id: 'e2' },
actor: 'A',
versionMap: { A: 2 }
};
const result = await storageProxy.applyOp(op);
assert.isTrue(result);
assert.deepEqual(mockStore.lastCapturedMessage, {
type: ProxyMessageType.Operations,
operations: [op],
id: 1
});
await storageProxy.idle();
assert.deepEqual(handle.lastUpdate, op);
});
it('does not notify keepSynced handles if desynced', async () => {
// Don't pass any data to the MockStore.
const mockStore = new MockStore(new MockStoreInfo(singletonEntityType));
const storageProxy = new StorageProxy(new <API key>(mockStore));
// Register a keepSynced handle and a !keepSynced one.
const handle1 = new MockHandle(storageProxy);
handle1.configure({ keepSynced: true, notifyUpdate: true });
const handle2 = new MockHandle(storageProxy);
handle2.configure({ keepSynced: false, notifyUpdate: true });
// At this point the storage proxy has requested a sync but it is still not
// synchronized (as we did not pass any data to the mockStore).
const op = {
type: SingletonOpTypes.Set,
value: { id: 'e1' },
actor: 'A',
versionMap: { A: 2 }
};
await storageProxy.onMessage({ type: ProxyMessageType.Operations, operations: [op], id: 1 });
await storageProxy.idle();
// Only handle2 is notified as the proxy is not synchronized.
assert.isNull(handle1.lastUpdate);
assert.deepEqual(handle2.lastUpdate, op);
});
it('will sync if desynced before returning the particle view', async () => {
const mockStore = new MockStore(new MockStoreInfo(singletonEntityType), initialData);
const storageProxy = new StorageProxy(new <API key>(mockStore));
// Register a handle to verify updates are sent back.
const handle = new MockHandle(storageProxy);
// The first time we get the data, it will need to sync with the store.
const result = await storageProxy.getParticleView();
assert.deepEqual(result, { id: 'e1' });
assert.deepEqual(mockStore.lastCapturedMessage, { type: ProxyMessageType.SyncRequest, id: 1 });
await storageProxy.idle();
assert.isTrue(handle.onSyncCalled);
// Check that on subsequent data request, we don't need to sync.
mockStore.onProxyMessage = async (message) => {
assert.fail('should not need to sync');
};
await storageProxy.getParticleView();
});
it('can exchange models with the store', async () => {
const mockStore = new MockStore(new MockStoreInfo(singletonEntityType), initialData);
const storageProxy = new StorageProxy(new <API key>(mockStore));
// Registering a handle trigger the proxy to connect to the store and fetch the model.
const handle = new MockHandle(storageProxy);
assert.deepEqual(mockStore.lastCapturedMessage, { type: ProxyMessageType.SyncRequest, id: 1 });
const crdtData = {
values: { 'e3': { value: { id: 'e3' }, version: { A: 3 } } },
version: { A: 3 }
};
// Send a model to the proxy.
await storageProxy.onMessage({ type: ProxyMessageType.ModelUpdate, model: crdtData, id: 1 });
// Request model from the proxy.
await storageProxy.onMessage({ type: ProxyMessageType.SyncRequest, id: 1 });
assert.deepEqual(mockStore.lastCapturedMessage, { type: ProxyMessageType.ModelUpdate, id: 1, model: crdtData });
});
it('propagates exceptions to the store', async () => {
const mockStore = new MockStore(new MockStoreInfo(singletonEntityType), initialData);
const storageProxy = new StorageProxy(new <API key>(mockStore));
const handle = new MockHandle(storageProxy);
handle.onSync = () => {
throw new Error('something wrong');
};
await storageProxy.getParticleView();
await storageProxy.idle();
assert.equal(mockStore.<API key>.message, 'SystemException: exception Error raised when invoking system function <API key>::_dispatch on behalf of particle handle: something wrong');
});
});
describe('NoOpStorageProxy', () => {
it('overrides all methods in StorageProxy', async () => {
const mockStore = new MockStore(new MockStoreInfo(singletonEntityType));
const storageProxy = new StorageProxy(new <API key>(mockStore));
const noOpStorageProxy = getNoOpStorageProxy();
const properties = [];
let proto = Object.getPrototypeOf(storageProxy);
while (proto && proto !== Object.prototype) {
Object.getOwnPropertyNames(proto).forEach(name => {
const desc = Object.<API key>(proto, name);
if (desc && typeof desc.value === 'function') {
properties.push(name);
}
});
proto = Object.getPrototypeOf(proto);
}
/**
* Private properties can't be overidden; nor does it really make any sense
* to do so as they can only be called from within the class.
*/
const privateProperties = ['setSynchronized', 'clearSynchronized'];
const noOpProperties = Object.getOwnPropertyNames(Object.getPrototypeOf(noOpStorageProxy));
properties.forEach(property => {
if (privateProperties.includes(property)) {
return;
}
assert(noOpProperties.indexOf(property) !== -1, 'Missing function: ' + property);
});
});
});
//# sourceMappingURL=storage-proxy-test.js.map |
<!DOCTYPE html>
<html xmlns="http:
<head>
<meta charset="utf-8" />
<title>2018-10-30 conda-forge meeting — conda-forge 2020.12.21 documentation</title>
<link rel="stylesheet" href="../../_static/cloud.css" type="text/css" />
<link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Noticia+Text|Open+Sans|Droid+Sans+Mono" type="text/css" />
<script id="<API key>" data-url_root="../../" src="../../_static/<API key>.js"></script>
<script src="../../_static/jquery.js"></script>
<script src="../../_static/underscore.js"></script>
<script src="../../_static/doctools.js"></script>
<script src="../../_static/language_data.js"></script>
<script src="../../_static/jquery.cookie.js"></script>
<script src="../../_static/cloud.base.js"></script>
<script src="../../_static/cloud.js"></script>
<link rel="index" title="Index" href="../../genindex.html" />
<link rel="search" title="Search" href="../../search.html" />
<link rel="next" title="2018-10-02 conda-forge meeting" href="2018-10-02.html" />
<link rel="prev" title="2018-11-13 conda-forge meeting" href="2018-11-13.html" />
<meta name="viewport" content="width=device-width, initial-scale=1">
</head><body>
<div class="relbar-top">
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="2018-10-02.html" title="2018-10-02 conda-forge meeting"
accesskey="N">next</a> </li>
<li class="right" >
<a href="2018-11-13.html" title="2018-11-13 conda-forge meeting"
accesskey="P">previous</a> </li>
<li><a href="../../index.html">conda-forge 2020.12.21 documentation</a> »</li>
<li class="nav-item nav-item-1"><a href="../00_intro.html" >Organisation Documentation</a> »</li>
<li class="nav-item nav-item-2"><a href="00_intro.html" accesskey="U">Core team meeting minutes</a> »</li>
</ul>
</div>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="conda-forge-meeting">
<h1>2018-10-30 conda-forge meeting<a class="headerlink" href="
<p><strong>Pinned Items</strong></p>
<ul class="simple">
<li><p>Zoom instructions: <a class="reference external" href="https://paper.dropbox.com/doc/<API key>">+How to connect to zoom</a></p></li>
</ul>
<hr class="docutils" />
<p><strong>New items</strong></p>
<ul class="simple">
<li><p>migrate r-base to <strong>x.x</strong> and <strong>noarch: generic</strong>, see https://github.com/conda-forge/r-base-feedstock/pull/60</p>
<ul>
<li><p>Nobody in the meeting really knows anything about this. Follow up with Isuru, Ray, …?</p></li>
</ul>
</li>
</ul>
<p><strong>Previous items</strong></p>
<ul class="simple">
<li><p>Compiler rebuild status</p>
<ul>
<li><p>python done for both compiler stacks</p></li>
<li><p>~~pending: openblas (numeric stack currently held up)~~</p></li>
</ul>
</li>
</ul>
<div class="highlight-- Qt: try to build on Azure? notranslate"><div class="highlight"><pre><span></span>- New approach to reducing CI load https://github.com/conda-forge/conda-forge.github.io/issues/647
- Might be possible to not be totally insecure with work. But nobody is volunteering to do that work right now. :)
- Pushing PR builds to a staging channel might be a nice UX improvement so you can test anyway.
- Copying packages to gcc7 label https://github.com/conda-forge/conda-smithy/issues/892
- MPI metapackage
- Just wait for new conda 3.6 with strict channel priority, and then add main label to those builds
- Mergify = auto-merge version bump PRs when CIs pass?
- https://github.com/conda-forge/<API key>/issues/49
- Worry about bot not detecting dependency changes
- Definitely opt-in only at first
- One possibility: only after an approved review (so you can say “merge assuming CIs pass”)
- Add overlinking error flag by default?
</pre></div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="<API key>">
<p class="logo"><a href="../../index.html" title="index">
<img class="logo" src="../../_static/logo_black_on_trans.png" alt="Logo"/>
</a></p><div class="sphinx-toc sphinxlocaltoc">
<h3><a href="../../index.html">Overview</a></h3>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="../../user/00_intro.html">User Documentation</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../maintainer/00_intro.html">Maintainer Documentation</a></li>
<li class="toctree-l1 current"><a class="reference internal" href="../00_intro.html">Organisation Documentation</a><ul class="current">
<li class="toctree-l2"><a class="reference internal" href="../guidelines.html">Guidelines</a></li>
<li class="toctree-l2"><a class="reference internal" href="../governance.html">Governance</a></li>
<li class="toctree-l2"><a class="reference internal" href="../subteams.html">A list of current sub-teams</a></li>
<li class="toctree-l2"><a class="reference internal" href="../joining-the-team.html">Joining the team</a></li>
<li class="toctree-l2 current"><a class="reference internal" href="00_intro.html">Core team meeting minutes</a><ul class="current">
<li class="toctree-l3"><a class="reference internal" href="2020-11-18.html">2020-11-18 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-11-11.html">2020-11-11 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-11-03.html">2020-11-03 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-10-28.html">2020-10-28 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-10-21.html">2020-10-21 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-10-14.html">2020-10-14 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-10-07.html">2020-10-07 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-09-30.html">2020-09-30 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-09-16.html">2020-09-16 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-09-09.html">2020-09-09 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-09-02.html">2020-09-02 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-08-26.html">2020-08-26 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-08-19.html">2020-08-19 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-08-12.html">2020-08-12 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-08-05.html">2020-08-05 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-07.29.html">2020-07-29 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-07.22.html">2020-07-22 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-07-15.html">2020-07-15 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-07-08.html">2020-07-08 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-07-01.html">2020-07-01 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-06-22.html">2020-06-22 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-05-27.html">2020-05-27 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-05-13.html">2020-05-13 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-04-29.html">2020-04-29 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-04-15.html">2020-04-15 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-04-01.html">2020-04-01 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-03-18.html">2020-03-18 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-03-04.html">2020-03-04 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-02-19.html">2020-02-19 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-02-05.html">2020-02-05 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-01-22.html">2020-01-22 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2020-01-08.html">2020-01-08 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-11-12.html">2019-11-12 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-10-30.html">2019-10-30 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-10-16.html">2019-10-16 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-10-02.html">2019-10-02 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-09-18.html">2019-09-18 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-09-04.html">2019-09-04 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-08-07.html">2017-08-07 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-07-24.html">2017-07-24 conda-forge core meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-06-26.html">2019-06-26 core dev meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-06-12.html">2019-06-12 Meeting Notes</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-05-29.html">2019-05-29 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-05-15.html">2019-05-15 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-04-17.html">2019-04-17 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-04-03.html">2019-04-03 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-03-20.html">2019-03-20 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-03-06.html">2019-03-06 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-02-20.html">2019-02-20 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-02-06.html">2019-02-06 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-01-23.html">2019-01-23 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2019-01-09.html">2019-01-09 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-11-27.html">2018-11-27 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-11-13.html">2018-11-13 conda-forge meeting</a></li>
<li class="toctree-l3 current"><a class="current reference internal" href="#">2018-10-30 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-10-02.html">2018-10-02 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-09-18.html">2018-09-18 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-09-04.html">2018-09-04 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-08-21.html">2018-08-21 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-08-07.html">2018-08-07 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-07-24.html">2018-07-24 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-07-17.html">2018-07-17 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-06-26.html">2018-06-26 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-06-12.html">2018-06-12 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-05-29.html">2018-05-29 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-05-01.html">2018-05-01 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-04-17.html">2018-04-17 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-04-03.html">2018-04-03 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-03-20.html">2018-03-20 conda-forge meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-03-06.html">2018-03-06 meeting agenda</a></li>
<li class="toctree-l3"><a class="reference internal" href="2018-02-20.html">2018-02-20 meeting notes</a></li>
<li class="toctree-l3"><a class="reference internal" href="2017-11-16.html">2017-11-16 compiler meeting notes</a></li>
<li class="toctree-l3"><a class="reference internal" href="2017-11-16.html#<API key>">Adopting Anaconda compilers</a></li>
<li class="toctree-l3"><a class="reference internal" href="2017-11-16.html#<API key>">Compiler flag unification</a></li>
<li class="toctree-l3"><a class="reference internal" href="2017-11-16.html#<API key>">Conda-build 3: strategy for moving</a></li>
<li class="toctree-l3"><a class="reference internal" href="2017-11-16.html#<API key>">Fortran support on Windows</a></li>
<li class="toctree-l3"><a class="reference internal" href="2017-11-16.html#openmp-behavior">OpenMP behavior</a></li>
<li class="toctree-l3"><a class="reference internal" href="2017-08-11.html">2017-08-11: General Discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2017-05-10.html">conda-forge meetings</a></li>
<li class="toctree-l3"><a class="reference internal" href="2017-05-10.html#general-discussion">2017-05-10: General Discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2017-04-26.html">2017-04-26: General Discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2017-01-06.html">2017-01-06: General Discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-11-24.html">2016-11-24: General Discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-11-17.html">2016-11-17: Operational catchup</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-10-07.html">2016-10-07: General Discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-09-23.html">2016-09-23 (postponed from 16th): General Discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-09-09.html">2016-09-09: General discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-08-25.html">2016-08-25: General discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-08-12.html">2016-08-12: General discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-07-22.html">2016-07-22: General discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-06-24.html">2016-06-24: General discussion</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-06-09.html">2016-06-09: Compiler special meeting</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-06-03.html">2016-06-03</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-05-13.html">2016-05-13</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-05-09.html">2016-05-09 Exceptional meeting regarding build customization</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-04-29.html">2016-04-29</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-04-22.html">2016-04-22 Exceptional meeting regarding VC pinning mechanism</a></li>
<li class="toctree-l3"><a class="reference internal" href="2016-04-15.html">2016-04-15</a></li>
</ul>
</li>
<li class="toctree-l2"><a class="reference internal" href="../getting-in-touch.html">Getting in Touch</a></li>
</ul>
</li>
<li class="toctree-l1"><a class="reference internal" href="../../misc/00_intro.html">Miscellaneous</a></li>
<li class="toctree-l1"><a class="reference internal" href="../../contracting/00_intro.html">Contracting Information</a></li>
</ul>
</div>
<div class="sphinxprev">
<h4>Previous page</h4>
<p class="topless"><a href="2018-11-13.html"
title="Previous page">← 2018-11-13 conda-forge meeting</a></p>
</div>
<div class="sphinxnext">
<h4>Next page</h4>
<p class="topless"><a href="2018-10-02.html"
title="Next page">→ 2018-10-02 conda-forge meeting</a></p>
</div>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../../_sources/orga/minutes/2018-10-30.md.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../../search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" />
<input type="submit" value="Go" />
</form>
</div>
</div>
<script>$('#searchbox').show(0);</script>
</div>
</div>
<div class="<API key> no-js">
<button class="sidebar-toggle" id="sidebar-hide" title="Hide the sidebar menu">
«
<span class="show-for-small">hide menu</span>
</button>
<button class="sidebar-toggle" id="sidebar-show" title="Show the sidebar menu">
<span class="show-for-small">menu</span>
<span class="hide-for-small">sidebar</span>
»
</button>
</div>
<div class="clearer"></div>
</div>
<div class="relbar-bottom">
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="2018-10-02.html" title="2018-10-02 conda-forge meeting"
>next</a> </li>
<li class="right" >
<a href="2018-11-13.html" title="2018-11-13 conda-forge meeting"
>previous</a> </li>
<li><a href="../../index.html">conda-forge 2020.12.21 documentation</a> »</li>
<li class="nav-item nav-item-1"><a href="../00_intro.html" >Organisation Documentation</a> »</li>
<li class="nav-item nav-item-2"><a href="00_intro.html" >Core team meeting minutes</a> »</li>
</ul>
</div>
</div>
<div class="footer" role="contentinfo">
&
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.4.4.
</div>
<!-- cloud_sptheme 1.4 -->
</body>
</html> |
{% load staticfiles %}
{% load static %}
<section class="no-padding bg-primary" id="travel">
<div class="cd-scrolling-bg-top">
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<h2 class="section-heading text-center">{{travel_detail.title}}</h2>
<hr class="light">
{{travel_detail.body|safe}}
</div>
</div>
<div class="row">
<div class="col-md-offset-0">
{% for loc in hotel %}
<div class="col-md-4 text-center">
<h2><a href="{{loc.website}}">{{loc.title}}</a></h2>
<p>{{loc.description|safe}}</p>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</section> |
# coding=utf-8
from __future__ import unicode_literals, division
import sys
import logging
from subprocess import Popen, PIPE
import shutil
import os
import re
from os.path import join as pjoin
from PIL import Image
from django.utils.six import StringIO
from django.core import management
from django.core.files.storage import default_storage
from django.template.loader import render_to_string
from django.test.client import Client
from django.test import TestCase
from django.test.utils import override_settings
from sorl.thumbnail import default, get_thumbnail, delete
from sorl.thumbnail.conf import settings
from sorl.thumbnail.engines.pil_engine import Engine as PILEngine
from sorl.thumbnail.helpers import get_module_class, ThumbnailError
from sorl.thumbnail.images import ImageFile
from sorl.thumbnail.log import ThumbnailLogHandler
from sorl.thumbnail.parsers import parse_crop, parse_geometry
from sorl.thumbnail.templatetags.thumbnail import margin
from sorl.thumbnail.base import ThumbnailBackend
from .models import Item
from .storage import MockLoggingHandler
from .compat import unittest
from .utils import same_open_fd_count, <API key>
skip = unittest.skip
skipIf = unittest.skipIf
handler = ThumbnailLogHandler()
handler.setLevel(logging.ERROR)
logging.getLogger('sorl.thumbnail').addHandler(handler)
class BaseStorageTestCase(unittest.TestCase):
im = None
def setUp(self):
os.makedirs(settings.MEDIA_ROOT)
fn = pjoin(settings.MEDIA_ROOT, self.name)
Image.new('L', (100, 100)).save(fn)
self.im = ImageFile(self.name)
logger = logging.getLogger('slog')
logger.setLevel(logging.DEBUG)
handler = MockLoggingHandler(level=logging.DEBUG)
logger.addHandler(handler)
self.log = handler.messages['debug']
def tearDown(self):
shutil.rmtree(settings.MEDIA_ROOT)
class StorageTestCase(BaseStorageTestCase):
name = 'org.jpg'
def test_a_new(self):
get_thumbnail(self.im, '50x50')
actions = [
'open: org.jpg', # open the original for thumbnailing
# save the file
'save: test/cache/ca/1a/<API key>.jpg',
# check for filename
'get_available_name: test/cache/ca/1a/<API key>.jpg',
# called by get_available_name
'exists: test/cache/ca/1a/<API key>.jpg',
]
self.assertEqual(self.log, actions)
def test_b_cached(self):
get_thumbnail(self.im, '50x50')
self.assertEqual(self.log, []) # now this should all be in cache
def test_c_safe_methods(self):
im = default.kvstore.get(self.im)
im.url, im.x, im.y
self.assertEqual(self.log, [])
class <API key>(BaseStorageTestCase):
name = 'retina.jpg'
def setUp(self):
settings.<API key> = [1.5, 2]
super(<API key>, self).setUp()
def tearDown(self):
super(<API key>, self).tearDown()
settings.<API key> = []
def test_retina(self):
get_thumbnail(self.im, '50x50')
actions = [
# save regular resolution, same as in StorageTestCase
'open: retina.jpg',
'save: test/cache/19/10/<API key>.jpg',
'get_available_name: test/cache/19/10/<API key>.jpg',
'exists: test/cache/19/10/<API key>.jpg',
# save the 1.5x resolution version
'save: test/cache/19/10/<API key>@1.5x.jpg',
'get_available_name: test/cache/19/10/<API key>@1.5x.jpg',
'exists: test/cache/19/10/<API key>@1.5x.jpg',
# save the 2x resolution version
'save: test/cache/19/10/<API key>@2x.jpg',
'get_available_name: test/cache/19/10/<API key>@2x.jpg',
'exists: test/cache/19/10/<API key>@2x.jpg'
]
self.assertEqual(self.log, actions)
with open(pjoin(settings.MEDIA_ROOT, 'test/cache/19/10/<API key>@1.5x.jpg')) as fp:
engine = PILEngine()
self.assertEqual(engine.get_image_size(engine.get_image(ImageFile(file_=fp))), (75, 75))
class UrlStorageTestCase(unittest.TestCase):
def <API key>(self):
storage = get_module_class('sorl.thumbnail.images.UrlStorage')()
self.assertEqual(
storage.normalize_url('El jovencito emponzoñado de whisky, qué figura exhibe'),
'El%20jovencito%20emponzoado%20de%20whisky%2C%20qu%20figura%20exhibe'
)
class ParsersTestCase(unittest.TestCase):
def test_alias_crop(self):
crop = parse_crop('center', (500, 500), (400, 400))
self.assertEqual(crop, (50, 50))
crop = parse_crop('right', (500, 500), (400, 400))
self.assertEqual(crop, (100, 50))
def test_percent_crop(self):
crop = parse_crop('50% 0%', (500, 500), (400, 400))
self.assertEqual(crop, (50, 0))
crop = parse_crop('10% 80%', (500, 500), (400, 400))
self.assertEqual(crop, (10, 80))
def test_px_crop(self):
crop = parse_crop('200px 33px', (500, 500), (400, 400))
self.assertEqual(crop, (100, 33))
def test_bad_crop(self):
self.assertRaises(ThumbnailError, parse_crop, '-200px', (500, 500), (400, 400))
def test_geometry(self):
g = parse_geometry('222x30')
self.assertEqual(g, (222, 30))
g = parse_geometry('222')
self.assertEqual(g, (222, None))
g = parse_geometry('x999')
self.assertEqual(g, (None, 999))
class SimpleTestCaseBase(unittest.TestCase):
backend = None
engine = None
kvstore = None
def setUp(self):
self.backend = get_module_class(settings.THUMBNAIL_BACKEND)()
self.engine = get_module_class(settings.THUMBNAIL_ENGINE)()
self.kvstore = get_module_class(settings.THUMBNAIL_KVSTORE)()
if not os.path.exists(settings.MEDIA_ROOT):
os.makedirs(settings.MEDIA_ROOT)
dims = [
(500, 500),
(100, 100),
(200, 100),
]
for dim in dims:
name = '%sx%s.jpg' % dim
fn = pjoin(settings.MEDIA_ROOT, name)
im = Image.new('L', dim)
im.save(fn)
Item.objects.get_or_create(image=name)
def tearDown(self):
shutil.rmtree(settings.MEDIA_ROOT)
class SimpleTestCase(SimpleTestCaseBase):
def test_simple(self):
item = Item.objects.get(image='500x500.jpg')
t = self.backend.get_thumbnail(item.image, '400x300', crop='center')
self.assertEqual(t.x, 400)
self.assertEqual(t.y, 300)
t = self.backend.get_thumbnail(item.image, '1200x900', crop='13% 89%')
self.assertEqual(t.x, 1200)
self.assertEqual(t.y, 900)
def test_upscale(self):
item = Item.objects.get(image='100x100.jpg')
t = self.backend.get_thumbnail(item.image, '400x300', upscale=False)
self.assertEqual(t.x, 100)
self.assertEqual(t.y, 100)
t = self.backend.get_thumbnail(item.image, '400x300', upscale=True)
self.assertEqual(t.x, 300)
self.assertEqual(t.y, 300)
def <API key>(self):
item = Item.objects.get(image='200x100.jpg')
t = self.backend.get_thumbnail(item.image, '400x300', crop='center', upscale=False)
self.assertEqual(t.x, 200)
self.assertEqual(t.y, 100)
t = self.backend.get_thumbnail(item.image, '400x300', crop='center', upscale=True)
self.assertEqual(t.x, 400)
self.assertEqual(t.y, 300)
def test_kvstore(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
self.kvstore.delete_thumbnails(im)
th1 = self.backend.get_thumbnail(im, '50')
th2 = self.backend.get_thumbnail(im, 'x50')
th3 = self.backend.get_thumbnail(im, '20x20')
self.assertEqual(
set([th1.key, th2.key, th3.key]),
set(self.kvstore._get(im.key, identity='thumbnails'))
)
self.kvstore.delete_thumbnails(im)
self.assertEqual(
None,
self.kvstore._get(im.key, identity='thumbnails')
)
def test_is_portrait(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
th = self.backend.get_thumbnail(im, '50x200', crop='center')
self.assertEqual(th.is_portrait(), True)
th = self.backend.get_thumbnail(im, '500x2', crop='center')
self.assertEqual(th.is_portrait(), False)
def test_margin(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
self.assertEqual(margin(im, '1000x1000'), '250px 250px 250px 250px')
self.assertEqual(margin(im, '800x1000'), '250px 150px 250px 150px')
self.assertEqual(margin(im, '500x500'), '0px 0px 0px 0px')
self.assertEqual(margin(im, '500x501'), '0px 0px 1px 0px')
self.assertEqual(margin(im, '503x500'), '0px 2px 0px 1px')
self.assertEqual(margin(im, '300x300'), '-100px -100px -100px -100px')
def <API key>(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
self.kvstore.delete(im)
self.assertEqual(self.kvstore.get(im), None)
self.kvstore.set(im)
self.assertEqual(im.size, [500, 500])
def test_cleanup1(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
self.kvstore.delete_thumbnails(im)
th = self.backend.get_thumbnail(im, '3x3')
self.assertEqual(th.exists(), True)
th.delete()
self.assertEqual(th.exists(), False)
self.assertEqual(self.kvstore.get(th).x, 3)
self.assertEqual(self.kvstore.get(th).y, 3)
self.kvstore.cleanup()
self.assertEqual(self.kvstore.get(th), None)
self.kvstore.delete(im)
def test_cleanup2(self):
self.kvstore.clear()
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
th3 = self.backend.get_thumbnail(im, '27x27')
th4 = self.backend.get_thumbnail(im, '81x81')
def keys_test(x, y, z):
self.assertEqual(x, len(list(self.kvstore._find_keys(identity='image'))))
self.assertEqual(y, len(list(self.kvstore._find_keys(identity='thumbnails'))))
self.assertEqual(z, len(self.kvstore._get(im.key, identity='thumbnails') or []))
keys_test(3, 1, 2)
th3.delete()
keys_test(3, 1, 2)
self.kvstore.cleanup()
keys_test(2, 1, 1)
th4.delete()
keys_test(2, 1, 1)
self.kvstore.cleanup()
keys_test(1, 0, 0)
self.kvstore.clear()
keys_test(0, 0, 0)
def <API key>(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
self.assertEqual(im.serialize_storage(), 'thumbnail_tests.storage.TestStorage')
self.assertEqual(
ImageFile('http:
'sorl.thumbnail.images.UrlStorage',
)
self.assertEqual(
ImageFile('http:
'thumbnail_tests.storage.TestStorage',
)
self.assertEqual(
ImageFile('getit', default_storage).serialize_storage(),
'thumbnail_tests.storage.TestStorage',
)
@skipIf(sys.platform == 'darwin', 'quality is saved a different way on os x')
def test_quality(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
th = self.backend.get_thumbnail(im, '100x100', quality=50)
p1 = Popen(['identify', '-verbose', th.storage.path(th.name)], stdout=PIPE)
p2 = Popen(['grep', '-c', 'Quality: 50'], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close()
output = p2.communicate()[0].strip()
self.assertEqual(output.decode('utf-8'), '1')
def <API key>(self):
im = ImageFile(Item.objects.get(image='500x500.jpg').image)
default.kvstore.set(im)
self.assertEqual(
default.kvstore.get(im).serialize_storage(),
'thumbnail_tests.storage.TestStorage',
)
im = ImageFile('http://dummyimage.com/300x300/')
default.kvstore.set(im)
self.assertEqual(
default.kvstore.get(im).serialize_storage(),
'sorl.thumbnail.images.UrlStorage',
)
def test_abspath(self):
item = Item.objects.get(image='500x500.jpg')
image = ImageFile(item.image.path)
val = render_to_string('thumbnail20.html', {
'image': image,
}).strip()
im = self.backend.get_thumbnail(image, '32x32', crop='center')
self.assertEqual('<img src="%s">' % im.url, val)
def test_new_tag_style(self):
item = Item.objects.get(image='500x500.jpg')
image = ImageFile(item.image.path)
val = render_to_string('thumbnail20a.html', {
'image': image,
}).strip()
im = self.backend.get_thumbnail(image, '32x32', crop='center')
self.assertEqual('<img src="%s">' % im.url, val)
def test_html_filter(self):
text = '<img alt="A image!" src="http://dummyimage.com/800x800" />'
val = render_to_string('htmlfilter.html', {
'text': text,
}).strip()
self.assertEqual('<img alt="A image!" src="/media/test/cache/2e/35/<API key>.jpg" />',
val)
def <API key>(self):
text = ''
val = render_to_string('markdownfilter.html', {
'text': text,
}).strip()
self.assertEqual('', val)
class TemplateTestCaseA(SimpleTestCaseBase):
def test_model(self):
item = Item.objects.get(image='500x500.jpg')
val = render_to_string('thumbnail1.html', {
'item': item,
}).strip()
self.assertEqual(val, '<img style="margin:0px 0px 0px 0px" width="200" height="100">')
val = render_to_string('thumbnail2.html', {
'item': item,
}).strip()
self.assertEqual(val, '<img style="margin:0px 50px 0px 50px" width="100" height="100">')
def test_nested(self):
item = Item.objects.get(image='500x500.jpg')
val = render_to_string('thumbnail6.html', {
'item': item,
}).strip()
self.assertEqual(val, (
'<a href="/media/test/cache/ba/d7/<API key>.jpg">'
'<img src="/media/test/cache/c6/7a/<API key>.jpg" width="400" height="400">'
'</a>')
)
def <API key>(self):
item = Item.objects.get(image='500x500.jpg')
for j in range(0, 20):
# we could be lucky...
val0 = render_to_string('thumbnail7.html', {
'item': item,
}).strip()
val1 = render_to_string('thumbnail7a.html', {
'item': item,
}).strip()
self.assertEqual(val0, val1)
def test_options(self):
item = Item.objects.get(image='500x500.jpg')
options = {
'crop': "center",
'upscale': True,
'quality': 77,
}
val0 = render_to_string('thumbnail8.html', {
'item': item,
'options': options,
}).strip()
val1 = render_to_string('thumbnail8a.html', {
'item': item,
}).strip()
self.assertEqual(val0, val1)
def test_progressive(self):
im = Item.objects.get(image='500x500.jpg').image
th = self.backend.get_thumbnail(im, '100x100', progressive=True)
path = pjoin(settings.MEDIA_ROOT, th.name)
p = Popen(['identify', '-verbose', path], stdout=PIPE)
p.wait()
m = re.search('Interlace: JPEG', str(p.stdout.read()))
self.assertEqual(bool(m), True)
def test_nonprogressive(self):
im = Item.objects.get(image='500x500.jpg').image
th = self.backend.get_thumbnail(im, '100x100', progressive=False)
path = pjoin(settings.MEDIA_ROOT, th.name)
p = Popen(['identify', '-verbose', path], stdout=PIPE)
p.wait()
m = re.search('Interlace: None', str(p.stdout.read()))
self.assertEqual(bool(m), True)
def test_orientation(self):
data_dir = pjoin(settings.MEDIA_ROOT, 'data')
shutil.copytree(settings.DATA_ROOT, data_dir)
ref = Image.open(pjoin(data_dir, '1_topleft.jpg'))
top = ref.getpixel((14, 7))
left = ref.getpixel((7, 14))
engine = PILEngine()
def epsilon(x, y):
if isinstance(x, (tuple, list)):
x = sum(x) / len(x)
if isinstance(y, (tuple, list)):
y = sum(y) / len(y)
return abs(x - y)
data_images = (
'1_topleft.jpg',
'2_topright.jpg',
'3_bottomright.jpg',
'4_bottomleft.jpg',
'5_lefttop.jpg',
'6_righttop.jpg',
'7_rightbottom.jpg',
'8_leftbottom.jpg'
)
for name in data_images:
th = self.backend.get_thumbnail('data/%s' % name, '30x30')
im = engine.get_image(th)
self.assertLess(epsilon(top, im.getpixel((14, 7))), 10)
self.assertLess(epsilon(left, im.getpixel((7, 14))), 10)
exif = im._getexif()
if exif:
self.assertEqual(exif.get(0x0112), 1)
class TemplateTestCaseB(unittest.TestCase):
def tearDown(self):
try:
shutil.rmtree(settings.MEDIA_ROOT)
except Exception:
pass
def test_url(self):
val = render_to_string('thumbnail3.html', {}).strip()
self.assertEqual(val, '<img style="margin:0px 0px 0px 0px" width="20" height="20">')
def test_portrait(self):
val = render_to_string('thumbnail4.html', {
'source': 'http://dummyimage.com/120x100/',
'dims': 'x66',
}).strip()
self.assertEqual(val,
'<img src="/media/test/cache/7b/cd/<API key>.jpg" width="79" height="66" class="landscape">')
def test_empty(self):
val = render_to_string('thumbnail5.html', {}).strip()
self.assertEqual(val, '<p>empty</p>')
class <API key>(TestCase):
def test_empty_error(self):
with <API key>(settings, THUMBNAIL_DEBUG=False):
from django.core.mail import outbox
client = Client()
response = client.get('/thumbnail9.html')
self.assertEqual(response.content.strip(), b'<p>empty</p>')
self.assertEqual(outbox[0].subject, '[sorl-thumbnail] ERROR: /thumbnail9.html')
end = outbox[0].body.split('\n\n')[-2].split(':')[1].strip()
self.assertEqual(end, '[Errno 2] No such file or directory')
class CropTestCase(SimpleTestCaseBase):
def setUp(self):
super(CropTestCase, self).setUp()
# portrait
name = 'portrait.jpg'
fn = pjoin(settings.MEDIA_ROOT, name)
im = Image.new('L', (100, 200))
im.paste(255, (0, 0, 100, 100))
im.save(fn)
self.portrait = ImageFile(Item.objects.get_or_create(image=name)[0].image)
self.kvstore.delete(self.portrait)
# landscape
name = 'landscape.jpg'
fn = pjoin(settings.MEDIA_ROOT, name)
im = Image.new('L', (200, 100))
im.paste(255, (0, 0, 100, 100))
im.save(fn)
self.landscape = ImageFile(Item.objects.get_or_create(image=name)[0].image)
self.kvstore.delete(self.landscape)
def test_portrait_crop(self):
def mean_pixel(x, y):
values = im.getpixel((x, y))
if not isinstance(values, (tuple, list)):
values = [values]
return sum(values) / len(values)
for crop in ('center', '88% 50%', '50px'):
th = self.backend.get_thumbnail(self.portrait, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
self.assertEqual(mean_pixel(50, 0), 255)
self.assertEqual(mean_pixel(50, 45), 255)
self.assertEqual(250 <= mean_pixel(50, 49) <= 255, True, mean_pixel(50, 49))
self.assertEqual(mean_pixel(50, 55), 0)
self.assertEqual(mean_pixel(50, 99), 0)
for crop in ('top', '0%', '0px'):
th = self.backend.get_thumbnail(self.portrait, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
for x in range(0, 99, 10):
for y in range(0, 99, 10):
self.assertEqual(250 < mean_pixel(x, y) <= 255, True)
for crop in ('bottom', '100%', '100px'):
th = self.backend.get_thumbnail(self.portrait, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
for x in range(0, 99, 10):
for y in range(0, 99, 10):
self.assertEqual(0 <= mean_pixel(x, y) < 5, True)
def test_landscape_crop(self):
def mean_pixel(x, y):
values = im.getpixel((x, y))
if not isinstance(values, (tuple, list)):
values = [values]
return sum(values) / len(values)
for crop in ('center', '50% 200%', '50px 700px'):
th = self.backend.get_thumbnail(self.landscape, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
self.assertEqual(mean_pixel(0, 50), 255)
self.assertEqual(mean_pixel(45, 50), 255)
self.assertEqual(250 < mean_pixel(49, 50) <= 255, True)
self.assertEqual(mean_pixel(55, 50), 0)
self.assertEqual(mean_pixel(99, 50), 0)
for crop in ('left', '0%', '0px'):
th = self.backend.get_thumbnail(self.landscape, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
for x in range(0, 99, 10):
for y in range(0, 99, 10):
self.assertEqual(250 < mean_pixel(x, y) <= 255, True)
for crop in ('right', '100%', '100px'):
th = self.backend.get_thumbnail(self.landscape, '100x100', crop=crop)
engine = PILEngine()
im = engine.get_image(th)
for x in range(0, 99, 10):
for y in range(0, 99, 10):
self.assertEqual(0 <= mean_pixel(x, y) < 5, True)
def test_smart_crop(self):
# TODO: Complete test for smart crop
thumb = self.backend.get_thumbnail(
'32x32',
'data/white_border.jpg',
crop='smart')
def tearDown(self):
shutil.rmtree(settings.MEDIA_ROOT)
class DummyTestCase(TestCase):
def setUp(self):
self.backend = get_module_class(settings.THUMBNAIL_BACKEND)()
def test_dummy_tags(self):
settings.THUMBNAIL_DUMMY = True
val = render_to_string('thumbnaild1.html', {
'anything': 'AINO',
}).strip()
self.assertEqual(val, '<img style="margin:auto" width="200" height="100">')
val = render_to_string('thumbnaild2.html', {
'anything': None,
}).strip()
self.assertEqual(val, '<img src="http://dummyimage.com/300x200" width="300" height="200"><p>NOT</p>')
val = render_to_string('thumbnaild3.html', {
}).strip()
self.assertEqual(val, '<img src="http://dummyimage.com/600x400" width="600" height="400">')
settings.THUMBNAIL_DUMMY = False
class ModelTestCase(SimpleTestCaseBase):
def test_field1(self):
self.kvstore.clear()
item = Item.objects.get(image='100x100.jpg')
im = ImageFile(item.image)
self.assertEqual(None, self.kvstore.get(im))
self.backend.get_thumbnail(im, '27x27')
self.backend.get_thumbnail(im, '81x81')
self.assertNotEqual(None, self.kvstore.get(im))
self.assertEqual(3, len(list(self.kvstore._find_keys(identity='image'))))
self.assertEqual(1, len(list(self.kvstore._find_keys(identity='thumbnails'))))
class BackendTest(SimpleTestCaseBase):
def test_delete(self):
im1 = Item.objects.get(image='100x100.jpg').image
im2 = Item.objects.get(image='500x500.jpg').image
default.kvstore.get_or_set(ImageFile(im1))
# exists in kvstore and in storage
self.assertTrue(bool(default.kvstore.get(ImageFile(im1))))
self.assertTrue(ImageFile(im1).exists())
# delete
delete(im1)
self.assertFalse(bool(default.kvstore.get(ImageFile(im1))))
self.assertFalse(ImageFile(im1).exists())
default.kvstore.get_or_set(ImageFile(im2))
# exists in kvstore and in storage
self.assertTrue(bool(default.kvstore.get(ImageFile(im2))))
self.assertTrue(ImageFile(im2).exists())
# delete
delete(im2, delete_file=False)
self.assertFalse(bool(default.kvstore.get(ImageFile(im2))))
self.assertTrue(ImageFile(im2).exists())
class TestInputCase(unittest.TestCase):
def setUp(self):
if not os.path.exists(settings.MEDIA_ROOT):
os.makedirs(settings.MEDIA_ROOT)
self.name = 'åäö.jpg'
fn = pjoin(settings.MEDIA_ROOT, self.name)
im = Image.new('L', (666, 666))
im.save(fn)
def test_nonascii(self):
# also test the get_thumbnail shortcut
th = get_thumbnail(self.name, '200x200')
hash_file = '/media/test/cache/99/45/<API key>.jpg'
self.assertEqual(th.url, hash_file)
def tearDown(self):
shutil.rmtree(settings.MEDIA_ROOT)
@skipIf(sys.platform.startswith("win"), "Can't easily count descriptors on windows")
class TestDescriptors(unittest.TestCase):
"""Make sure we're not leaving open descriptors on file exceptions"""
engine = None
def setUp(self):
self.engine = get_module_class(settings.THUMBNAIL_ENGINE)()
def <API key>(self):
"""If source image does not exists, properly close all file descriptors"""
source = ImageFile('nonexistent.jpeg')
with same_open_fd_count(self):
with self.assertRaises(IOError):
self.engine.get_image(source)
def test_is_valid_image(self):
with same_open_fd_count(self):
self.engine.is_valid_image(b'invalidbinaryimage.jpg')
@skipIf('pgmagick_engine' in settings.THUMBNAIL_ENGINE and sys.version_info.major == 2,
'No output has been received in the last 10 minutes, this potentially indicates something wrong with the build itself.')
def test_write(self):
with same_open_fd_count(self):
with self.assertRaises(Exception):
self.engine.write(image=self.engine.get_image(StringIO(b'xxx')),
options={'format': 'JPEG', 'quality': 90, 'image_info': {}},
thumbnail=ImageFile('whatever_thumb.jpg', default.storage))
class CommandTests(SimpleTestCase):
def test_clear_action(self):
out = StringIO('')
management.call_command('thumbnail', 'clear', verbosity=1, stdout=out)
self.assertEqual(out.getvalue(), "Clear the Key Value Store ... [Done]\n")
def test_cleanup_action(self):
out = StringIO('')
management.call_command('thumbnail', 'cleanup', verbosity=1, stdout=out)
self.assertEqual(out.getvalue(), "Cleanup thumbnails ... [Done]\n")
class FakeFile(object):
"""
Used to test the _get_format method.
"""
def __init__(self, name):
self.name = name
@override_settings(<API key>=True,
THUMBNAIL_FORMAT='XXX')
class PreserveFormatTest(TestCase):
def setUp(self):
self.backend = ThumbnailBackend()
def <API key>(self):
self.assertEqual(self.backend._get_format(FakeFile('foo.jpg')), 'JPEG')
self.assertEqual(self.backend._get_format(FakeFile('foo.jpeg')), 'JPEG')
self.assertEqual(self.backend._get_format(FakeFile('foo.png')), 'PNG')
def <API key>(self):
self.assertEqual(self.backend._get_format(FakeFile('foo.ext.jpg')), 'JPEG')
def <API key>(self):
self.assertEqual(self.backend._get_format(FakeFile('foo.PNG')), 'PNG')
self.assertEqual(self.backend._get_format(FakeFile('foo.JPG')), 'JPEG')
def <API key>(self):
self.assertEqual(self.backend._get_format(FakeFile('foo.txt')), 'XXX')
def test_with_nonascii(self):
self.assertEqual(self.backend._get_format(FakeFile('.jpg')), 'JPEG') |
#include "device/fido/cable/v2_handshake.h"
#include "base/numerics/safe_math.h"
#include "base/strings/<API key>.h" // TODO REMOVE
#include "components/cbor/reader.h"
#include "components/cbor/writer.h"
#include "components/device_event_log/device_event_log.h"
#include "crypto/aead.h"
#include "device/fido/fido_constants.h"
#include "device/fido/fido_parsing_utils.h"
#include "third_party/boringssl/src/include/openssl/bytestring.h"
#include "third_party/boringssl/src/include/openssl/digest.h"
#include "third_party/boringssl/src/include/openssl/ec.h"
#include "third_party/boringssl/src/include/openssl/ec_key.h"
#include "third_party/boringssl/src/include/openssl/ecdh.h"
#include "third_party/boringssl/src/include/openssl/hkdf.h"
#include "third_party/boringssl/src/include/openssl/obj.h"
#include "third_party/boringssl/src/include/openssl/sha.h"
using device::fido_parsing_utils::CopyCBORBytestring;
namespace {
// Maximum value of a sequence number. Exceeding this causes all operations to
// return an error. This is assumed to be vastly larger than any caBLE exchange
// will ever reach.
constexpr uint32_t kMaxSequence = (1 << 24) - 1;
bool ConstructNonce(uint32_t counter, base::span<uint8_t, 12> out_nonce) {
if (counter > kMaxSequence) {
return false;
}
// Nonce is just a little-endian counter.
std::array<uint8_t, sizeof(counter)> counter_bytes;
memcpy(counter_bytes.data(), &counter, sizeof(counter));
std::copy(counter_bytes.begin(), counter_bytes.end(), out_nonce.begin());
std::fill(out_nonce.begin() + counter_bytes.size(), out_nonce.end(), 0);
return true;
}
CBS CBSFromSpan(base::span<const uint8_t> in) {
CBS cbs;
CBS_init(&cbs, in.data(), in.size());
return cbs;
}
bool CBS_get_span(CBS* cbs, base::span<const uint8_t>* out_span, size_t N) {
CBS contents;
if (!CBS_get_bytes(cbs, &contents, N)) {
return false;
}
*out_span =
base::span<const uint8_t>(CBS_data(&contents), CBS_len(&contents));
return true;
}
constexpr uint8_t kPairedPrologue[] = "caBLE handshake";
constexpr uint8_t kQRPrologue[] = "caBLE QR code handshake";
} // namespace
namespace device {
namespace cablev2 {
Crypter::Crypter(base::span<const uint8_t, 32> read_key,
base::span<const uint8_t, 32> write_key)
: read_key_(fido_parsing_utils::Materialize(read_key)),
write_key_(fido_parsing_utils::Materialize(write_key)) {}
Crypter::~Crypter() = default;
bool Crypter::Encrypt(std::vector<uint8_t>* message_to_encrypt) {
// Messages will be padded in order to round their length up to a multiple
// of kPaddingGranularity.
constexpr size_t kPaddingGranularity = 32;
static_assert(kPaddingGranularity > 0, "padding too small");
static_assert(kPaddingGranularity < 256, "padding too large");
static_assert((kPaddingGranularity & (kPaddingGranularity - 1)) == 0,
"padding must be a power of two");
// Padding consists of a some number of zero bytes appended to the message
// and the final byte in the message is the number of zeros.
base::CheckedNumeric<size_t> padded_size_checked = message_to_encrypt->size();
padded_size_checked += 1; // padding-length byte.
padded_size_checked = (padded_size_checked + kPaddingGranularity - 1) &
~(kPaddingGranularity - 1);
if (!padded_size_checked.IsValid()) {
NOTREACHED();
return false;
}
const size_t padded_size = padded_size_checked.ValueOrDie();
CHECK_GT(padded_size, message_to_encrypt->size());
const size_t num_zeros = padded_size - message_to_encrypt->size() - 1;
std::vector<uint8_t> padded_message(padded_size, 0);
memcpy(padded_message.data(), message_to_encrypt->data(),
message_to_encrypt->size());
// The number of added zeros has to fit in a single byte so it has to be
// less than 256.
DCHECK_LT(num_zeros, 256u);
padded_message[padded_message.size() - 1] = static_cast<uint8_t>(num_zeros);
std::array<uint8_t, 12> nonce;
if (!ConstructNonce(write_sequence_num_++, nonce)) {
return false;
}
crypto::Aead aes_key(crypto::Aead::AES_256_GCM);
aes_key.Init(write_key_);
DCHECK_EQ(nonce.size(), aes_key.NonceLength());
const uint8_t additional_data[2] = {
base::strict_cast<uint8_t>(device::<API key>::kMsg),
/*version=*/2};
std::vector<uint8_t> ciphertext =
aes_key.Seal(padded_message, nonce, additional_data);
message_to_encrypt->swap(ciphertext);
return true;
}
bool Crypter::Decrypt(<API key> command,
base::span<const uint8_t> ciphertext,
std::vector<uint8_t>* out_plaintext) {
std::array<uint8_t, 12> nonce;
if (!ConstructNonce(read_sequence_num_, nonce)) {
return false;
}
crypto::Aead aes_key(crypto::Aead::AES_256_GCM);
aes_key.Init(read_key_);
DCHECK_EQ(nonce.size(), aes_key.NonceLength());
const uint8_t additional_data[2] = {base::strict_cast<uint8_t>(command),
/*version=*/2};
base::Optional<std::vector<uint8_t>> plaintext =
aes_key.Open(ciphertext, nonce, additional_data);
if (!plaintext) {
return false;
}
read_sequence_num_++;
if (plaintext->empty()) {
FIDO_LOG(ERROR) << "Invalid caBLE message.";
return false;
}
const size_t padding_length = (*plaintext)[plaintext->size() - 1];
if (padding_length + 1 > plaintext->size()) {
FIDO_LOG(ERROR) << "Invalid caBLE message.";
return false;
}
plaintext->resize(plaintext->size() - padding_length - 1);
out_plaintext->swap(*plaintext);
return true;
}
bool Crypter::<API key>(const Crypter& other) const {
return read_key_ == other.write_key_ && write_key_ == other.read_key_;
}
HandshakeInitiator::HandshakeInitiator(
base::span<const uint8_t, 32> psk_gen_key,
base::span<const uint8_t, 8> nonce,
base::span<const uint8_t, <API key>> eid,
base::Optional<base::span<const uint8_t, kP256PointSize>> peer_identity,
base::Optional<base::span<const uint8_t, <API key>>>
local_seed)
: eid_(fido_parsing_utils::Materialize(eid)) {
DCHECK(peer_identity.has_value() ^ local_seed.has_value());
HKDF(psk_.data(), psk_.size(), EVP_sha256(), psk_gen_key.data(),
psk_gen_key.size(), /*salt=*/nonce.data(), nonce.size(),
/*info=*/nullptr, 0);
if (peer_identity) {
peer_identity_ = fido_parsing_utils::Materialize(*peer_identity);
}
if (local_seed) {
local_seed_ = fido_parsing_utils::Materialize(*local_seed);
}
}
HandshakeInitiator::~HandshakeInitiator() = default;
std::vector<uint8_t> HandshakeInitiator::BuildInitialMessage() {
if (peer_identity_) {
noise_.Init(Noise::HandshakeType::kNKpsk0);
noise_.MixHash(kPairedPrologue);
} else {
noise_.Init(Noise::HandshakeType::kKNpsk0);
noise_.MixHash(kQRPrologue);
}
noise_.MixKeyAndHash(psk_);
ephemeral_key_.reset(<API key>(<API key>));
const EC_GROUP* group = EC_KEY_get0_group(ephemeral_key_.get());
CHECK(EC_KEY_generate_key(ephemeral_key_.get()));
uint8_t <API key>[kP256PointSize];
CHECK_EQ(sizeof(<API key>),
EC_POINT_point2oct(
group, <API key>(ephemeral_key_.get()),
<API key>, <API key>,
sizeof(<API key>), /*ctx=*/nullptr));
noise_.MixHash(<API key>);
noise_.MixKey(<API key>);
if (peer_identity_) {
// If we know the identity of the peer from a previous interaction, NKpsk0
// is performed to ensure that other browsers, which may also know the PSK,
// cannot impersonate the authenticator.
bssl::UniquePtr<EC_POINT> peer_identity_point(EC_POINT_new(group));
uint8_t es_key[32];
CHECK(EC_POINT_oct2point(group, peer_identity_point.get(),
peer_identity_->data(), peer_identity_->size(),
/*ctx=*/nullptr));
CHECK(ECDH_compute_key(es_key, sizeof(es_key), peer_identity_point.get(),
ephemeral_key_.get(),
/*kdf=*/nullptr) == sizeof(es_key));
noise_.MixKey(es_key);
}
std::vector<uint8_t> ciphertext =
noise_.EncryptAndHash(base::span<const uint8_t>());
std::vector<uint8_t> handshake_message;
handshake_message.reserve(eid_.size() + sizeof(<API key>) +
ciphertext.size());
handshake_message.insert(handshake_message.end(), eid_.begin(), eid_.end());
handshake_message.insert(
handshake_message.end(), <API key>,
<API key> + sizeof(<API key>));
handshake_message.insert(handshake_message.end(), ciphertext.begin(),
ciphertext.end());
return handshake_message;
}
base::Optional<std::pair<std::unique_ptr<Crypter>,
base::Optional<std::unique_ptr<CableDiscoveryData>>>>
HandshakeInitiator::ProcessResponse(base::span<const uint8_t> response) {
if (response.size() < kP256PointSize) {
return base::nullopt;
}
auto peer_point_bytes = response.subspan(0, kP256PointSize);
auto ciphertext = response.subspan(kP256PointSize);
bssl::UniquePtr<EC_POINT> peer_point(
EC_POINT_new(EC_KEY_get0_group(ephemeral_key_.get())));
uint8_t shared_key_ee[32];
const EC_GROUP* group = EC_KEY_get0_group(ephemeral_key_.get());
if (!EC_POINT_oct2point(group, peer_point.get(), peer_point_bytes.data(),
peer_point_bytes.size(), /*ctx=*/nullptr) ||
ECDH_compute_key(shared_key_ee, sizeof(shared_key_ee), peer_point.get(),
ephemeral_key_.get(),
/*kdf=*/nullptr) != sizeof(shared_key_ee)) {
FIDO_LOG(DEBUG) << "Peer's P-256 point not on curve.";
return base::nullopt;
}
noise_.MixHash(peer_point_bytes);
noise_.MixKey(peer_point_bytes);
noise_.MixKey(shared_key_ee);
if (local_seed_) {
uint8_t shared_key_se[32];
bssl::UniquePtr<EC_KEY> identity_key(<API key>(
group, local_seed_->data(), local_seed_->size()));
if (ECDH_compute_key(shared_key_se, sizeof(shared_key_se), peer_point.get(),
identity_key.get(),
/*kdf=*/nullptr) != sizeof(shared_key_se)) {
return base::nullopt;
}
noise_.MixKey(shared_key_se);
}
auto plaintext = noise_.DecryptAndHash(ciphertext);
if (!plaintext || plaintext->empty() != peer_identity_.has_value()) {
FIDO_LOG(DEBUG) << "Invalid caBLE handshake message";
return base::nullopt;
}
base::Optional<std::unique_ptr<CableDiscoveryData>> discovery_data;
if (!peer_identity_) {
// Handshakes without a peer identity (i.e. KNpsk0 handshakes setup from a
// QR code) send a padded message in the reply. This message can,
// optionally, contain CBOR-encoded, long-term pairing information.
const size_t padding_length = (*plaintext)[plaintext->size() - 1];
if (padding_length + 1 > plaintext->size()) {
FIDO_LOG(DEBUG) << "Invalid padding in caBLE handshake message";
return base::nullopt;
}
plaintext->resize(plaintext->size() - padding_length - 1);
if (!plaintext->empty()) {
base::Optional<cbor::Value> pairing = cbor::Reader::Read(*plaintext);
if (!pairing || !pairing->is_map()) {
FIDO_LOG(DEBUG) << "CBOR parse failure in caBLE handshake message";
return base::nullopt;
}
auto future_discovery = std::make_unique<CableDiscoveryData>();
future_discovery->version = CableDiscoveryData::Version::V2;
future_discovery->v2.emplace();
future_discovery->v2->peer_identity.emplace();
const cbor::Value::MapValue& pairing_map(pairing->GetMap());
const auto name_it = pairing_map.find(cbor::Value(4));
if (!CopyCBORBytestring(&future_discovery->v2->eid_gen_key, pairing_map,
1) ||
!CopyCBORBytestring(&future_discovery->v2->psk_gen_key, pairing_map,
2) ||
!CopyCBORBytestring(&future_discovery->v2->peer_identity.value(),
pairing_map, 3) ||
name_it == pairing_map.end() || !name_it->second.is_string() ||
!EC_POINT_oct2point(group, peer_point.get(),
future_discovery->v2->peer_identity->data(),
future_discovery->v2->peer_identity->size(),
/*ctx=*/nullptr)) {
FIDO_LOG(DEBUG) << "CBOR structure error in caBLE handshake message";
return base::nullopt;
}
future_discovery->v2->peer_name = name_it->second.GetString();
discovery_data.emplace(std::move(future_discovery));
}
}
std::array<uint8_t, 32> read_key, write_key;
std::tie(write_key, read_key) = noise_.traffic_keys();
return std::make_pair(std::make_unique<cablev2::Crypter>(read_key, write_key),
std::move(discovery_data));
}
base::Optional<std::unique_ptr<Crypter>> RespondToHandshake(
base::span<const uint8_t, 32> psk_gen_key,
const NonceAndEID& nonce_and_eid,
const EC_KEY* identity,
const EC_POINT* peer_identity,
const CableDiscoveryData* pairing_data,
base::span<const uint8_t> in,
std::vector<uint8_t>* out_response) {
DCHECK(identity == nullptr || pairing_data == nullptr);
DCHECK(identity == nullptr ^ peer_identity == nullptr);
CBS cbs = CBSFromSpan(in);
base::span<const uint8_t> eid;
base::span<const uint8_t> peer_point_bytes;
base::span<const uint8_t> ciphertext;
if (!CBS_get_span(&cbs, &eid, device::<API key>) ||
!CBS_get_span(&cbs, &peer_point_bytes, kP256PointSize) ||
!CBS_get_span(&cbs, &ciphertext, 16) || CBS_len(&cbs) != 0) {
return base::nullopt;
}
if (eid.size() != nonce_and_eid.second.size() ||
memcmp(eid.data(), nonce_and_eid.second.data(), eid.size()) != 0) {
return base::nullopt;
}
Noise noise;
if (identity) {
noise.Init(device::Noise::HandshakeType::kNKpsk0);
noise.MixHash(kPairedPrologue);
} else {
noise.Init(device::Noise::HandshakeType::kKNpsk0);
noise.MixHash(kQRPrologue);
}
std::array<uint8_t, 32> psk;
HKDF(psk.data(), psk.size(), EVP_sha256(), psk_gen_key.data(),
psk_gen_key.size(),
/*salt=*/nonce_and_eid.first.data(), nonce_and_eid.first.size(),
/*info=*/nullptr, 0);
noise.MixKeyAndHash(psk);
noise.MixHash(peer_point_bytes);
noise.MixKey(peer_point_bytes);
bssl::UniquePtr<EC_KEY> ephemeral_key(
<API key>(<API key>));
const EC_GROUP* group = EC_KEY_get0_group(ephemeral_key.get());
CHECK(EC_KEY_generate_key(ephemeral_key.get()));
bssl::UniquePtr<EC_POINT> peer_point(EC_POINT_new(group));
if (!EC_POINT_oct2point(group, peer_point.get(), peer_point_bytes.data(),
peer_point_bytes.size(),
/*ctx=*/nullptr)) {
FIDO_LOG(DEBUG) << "Peer's P-256 point not on curve.";
return base::nullopt;
}
if (identity) {
uint8_t es_key[32];
if (ECDH_compute_key(es_key, sizeof(es_key), peer_point.get(), identity,
/*kdf=*/nullptr) != sizeof(es_key)) {
return base::nullopt;
}
noise.MixKey(es_key);
}
auto plaintext = noise.DecryptAndHash(ciphertext);
if (!plaintext || !plaintext->empty()) {
FIDO_LOG(DEBUG) << "Failed to decrypt handshake ciphertext.";
return base::nullopt;
}
uint8_t <API key>[kP256PointSize];
CHECK_EQ(sizeof(<API key>),
EC_POINT_point2oct(
group, <API key>(ephemeral_key.get()),
<API key>, <API key>,
sizeof(<API key>), /*ctx=*/nullptr));
noise.MixHash(<API key>);
noise.MixKey(<API key>);
uint8_t shared_key_ee[32];
if (ECDH_compute_key(shared_key_ee, sizeof(shared_key_ee), peer_point.get(),
ephemeral_key.get(),
/*kdf=*/nullptr) != sizeof(shared_key_ee)) {
return base::nullopt;
}
noise.MixKey(shared_key_ee);
if (peer_identity) {
uint8_t shared_key_se[32];
if (ECDH_compute_key(shared_key_se, sizeof(shared_key_se), peer_identity,
ephemeral_key.get(),
/*kdf=*/nullptr) != sizeof(shared_key_se)) {
return base::nullopt;
}
noise.MixKey(shared_key_se);
}
std::vector<uint8_t> my_ciphertext;
if (!identity) {
uint8_t my_plaintext[256];
memset(my_plaintext, 0, sizeof(my_plaintext));
if (pairing_data) {
cbor::Value::MapValue pairing;
pairing.emplace(1, pairing_data->v2->eid_gen_key);
pairing.emplace(2, pairing_data->v2->psk_gen_key);
pairing.emplace(3, pairing_data->v2->peer_identity.value());
pairing.emplace(4, pairing_data->v2->peer_name.value());
base::Optional<std::vector<uint8_t>> cbor_bytes =
cbor::Writer::Write(cbor::Value(std::move(pairing)));
if (!cbor_bytes || cbor_bytes->size() > sizeof(my_plaintext) - 1) {
FIDO_LOG(DEBUG) << "Pairing encoding failed or result too large.";
return base::nullopt;
}
memcpy(my_plaintext, cbor_bytes->data(), cbor_bytes->size());
my_plaintext[255] = sizeof(my_plaintext) - 1 - cbor_bytes->size();
} else {
my_plaintext[255] = 255;
}
my_ciphertext = noise.EncryptAndHash(my_plaintext);
} else {
my_ciphertext = noise.EncryptAndHash(base::span<const uint8_t>());
}
out_response->insert(
out_response->end(), <API key>,
<API key> + sizeof(<API key>));
out_response->insert(out_response->end(), my_ciphertext.begin(),
my_ciphertext.end());
std::array<uint8_t, 32> read_key, write_key;
std::tie(read_key, write_key) = noise.traffic_keys();
return std::make_unique<Crypter>(read_key, write_key);
}
} // namespace cablev2
} // namespace device |
package edu.wustl.common.querysuite.metadata.path;
import java.io.Serializable;
import java.util.List;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.wustl.common.querysuite.metadata.associations.IAssociation;
/**
* @version 1.0
* @created 22-Dec-2006 2:49:27 PM
*/
public interface IPath extends Serializable
{
/**
* @return the source entity of the path.
*/
EntityInterface getSourceEntity();
/**
* @return the target entity of the path.
*/
EntityInterface getTargetEntity();
/**
* If the source and target entities refer to classes, then<br>
* srcEntity of 1st assoc = getSourceEntity() and <br>
* targetEntity of last assoc = getTargetEntity().<br>
* But if the source entity and/or target entity refer to a category,
* then the above will not hold...<br> e.g. getSourceEntity()
* will return the category's entity, whereas the srcEntity of the
* 1st association will be the entity corresponding to a class within that category.
*/
List<IAssociation> <API key>();
/**
* @return true - if all intermediate associations are bidirectional; false otherwise.
*/
boolean isBidirectional();
/**
* Call iff isBidirectional() = true.
* @return if bidirectional, returns a reverse path.
* @throws java.lang.<API key> if the path is not bidirectional.
*/
IPath reverse();
} |
#include <ostream>
#include <string>
#include <utility>
#include "base/base64.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/strings/pattern.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/<API key>.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/scoped_feature_list.h"
#include "base/threading/thread_restrictions.h"
#include "base/threading/<API key>.h"
#include "build/build_config.h"
#include "content/browser/site_instance_impl.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/browser/storage_partition.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "content/public/test/<API key>.h"
#include "content/public/test/<API key>.h"
#include "content/public/test/<API key>.h"
#include "content/public/test/<API key>.h"
#include "content/public/test/test_utils.h"
#include "content/public/test/<API key>.h"
#include "content/shell/browser/shell.h"
#include "content/test/<API key>.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/test_support/test_utils.h"
#include "net/base/<API key>/<API key>.h"
#include "net/dns/mock_host_resolver.h"
#include "net/test/<API key>/<API key>.h"
#include "net/test/<API key>/<API key>.h"
#include "services/network/public/cpp/corb/corb_impl.h"
#include "services/network/public/cpp/features.h"
#include "services/network/public/cpp/<API key>.h"
#include "services/network/public/cpp/network_switches.h"
#include "services/network/test/<API key>.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "third_party/blink/public/common/web_preferences/web_preferences.h"
#include "third_party/blink/public/mojom/loader/resource_load_info.mojom-shared.h"
namespace content {
using testing::Not;
using testing::HasSubstr;
using Action = network::corb::<API key>::Action;
using CorbMimeType = network::corb::<API key>::MimeType;
using <API key> =
network::<API key>;
namespace {
enum CorbExpectations {
kShouldBeBlocked = 1 << 0,
kShouldBeSniffed = 1 << 1,
<API key> = 0,
<API key> = kShouldBeBlocked,
<API key> = kShouldBeSniffed,
<API key> = kShouldBeSniffed | kShouldBeBlocked,
};
std::ostream& operator<<(std::ostream& os, const CorbExpectations& value) {
if (value == 0) {
os << "(none)";
return os;
}
os << "( ";
if (0 != (value & kShouldBeBlocked))
os << "kShouldBeBlocked ";
if (0 != (value & kShouldBeSniffed))
os << "kShouldBeSniffed ";
os << ")";
return os;
}
// Ensure the correct histograms are incremented for blocking events.
// Assumes the resource type is XHR.
void InspectHistograms(const base::HistogramTester& histograms,
const CorbExpectations& expectations,
const std::string& resource_name) {
<API key>();
histograms.ExpectUniqueSample(
"NetworkService.URLLoader.<API key>",
network::<API key>::kCompatibleLock, 1);
CorbMimeType expected_mime_type = CorbMimeType::kInvalidMimeType;
if (base::MatchPattern(resource_name, "*.html")) {
expected_mime_type = CorbMimeType::kHtml;
} else if (base::MatchPattern(resource_name, "*.xml")) {
expected_mime_type = CorbMimeType::kXml;
} else if (base::MatchPattern(resource_name, "*.json")) {
expected_mime_type = CorbMimeType::kJson;
} else if (base::MatchPattern(resource_name, "*.txt")) {
expected_mime_type = CorbMimeType::kPlain;
} else if (base::MatchPattern(resource_name, "*.zip") ||
base::MatchPattern(resource_name, "*.pdf")) {
expected_mime_type = CorbMimeType::kNeverSniffed;
} else {
expected_mime_type = CorbMimeType::kOthers;
}
// Determine the appropriate histograms, including a start and end action
// (which are verified in unit tests), a read size if it was sniffed, and
// additional blocked metrics if it was blocked.
base::HistogramTester::CountsMap expected_counts;
std::string base = "SiteIsolation.XSD.Browser";
expected_counts[base + ".Action"] = 2;
if (0 != (expectations & kShouldBeBlocked)) {
expected_counts[base + ".Blocked.CanonicalMimeType"] = 1;
}
// Make sure that the expected metrics, and only those metrics, were
// incremented.
EXPECT_THAT(histograms.<API key>("SiteIsolation.XSD.Browser"),
testing::ContainerEq(expected_counts))
<< "For resource_name=" << resource_name
<< ", expectations=" << expectations;
// Determine if the bucket for the resource type (XHR) was incremented.
if (0 != (expectations & kShouldBeBlocked)) {
EXPECT_THAT(histograms.GetAllSamples(base + ".Blocked.CanonicalMimeType"),
testing::ElementsAre(
base::Bucket(static_cast<int>(expected_mime_type), 1)))
<< "The wrong CorbMimeType bucket was incremented.";
}
// SiteIsolation.XSD.Browser.Action should always include kResponseStarted.
histograms.ExpectBucketCount(base + ".Action",
static_cast<int>(Action::kResponseStarted), 1);
// Second value in SiteIsolation.XSD.Browser.Action depends on |expectations|.
Action expected_action = static_cast<Action>(-1);
if (expectations & kShouldBeBlocked) {
if (expectations & kShouldBeSniffed)
expected_action = Action::<API key>;
else
expected_action = Action::<API key>;
} else {
if (expectations & kShouldBeSniffed)
expected_action = Action::<API key>;
else
expected_action = Action::<API key>;
}
histograms.ExpectBucketCount(base + ".Action",
static_cast<int>(expected_action), 1);
}
// Gets contents of a file at //content/test/data/<dir>/<file>.
std::string GetTestFileContents(const char* dir, const char* file) {
base::<API key> allow_io;
base::FilePath path = GetTestFilePath(dir, file);
std::string result;
EXPECT_TRUE(ReadFileToString(path, &result));
return result;
}
// Helper for intercepting a resource request to the given URL and capturing the
// response headers and body.
// Note that after the request completes, the original requestor (e.g. the
// renderer) will see an injected request failure (this is easier to accomplish
// than forwarding the intercepted response to the original requestor),
class RequestInterceptor {
public:
// Start intercepting requests to |url_to_intercept|.
explicit RequestInterceptor(const GURL& url_to_intercept)
: url_to_intercept_(url_to_intercept),
interceptor_(
base::BindRepeating(&RequestInterceptor::InterceptorCallback,
base::Unretained(this))) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(url_to_intercept.is_valid());
<API key> = test_client_.CreateRemote();
}
~RequestInterceptor() {
<API key>(
network::mojom::URLResponseHead::New(), "",
network::<API key>(net::ERR_NOT_IMPLEMENTED));
}
// No copy constructor or assignment operator.
RequestInterceptor(const RequestInterceptor&) = delete;
RequestInterceptor& operator=(const RequestInterceptor&) = delete;
// Waits until a request gets intercepted and completed.
void <API key>() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(!request_completed_);
test_client_.RunUntilComplete();
// Read the intercepted response body into |body_|.
if (test_client_.completion_status().error_code == net::OK) {
base::RunLoop run_loop;
ReadBody(run_loop.QuitClosure());
run_loop.Run();
}
// Wait until IO cleanup completes.
<API key>(test_client_.response_head().Clone(),
body_, test_client_.completion_status());
// Mark the request as completed (for DCHECK purposes).
request_completed_ = true;
}
const network::<API key>& completion_status() const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(request_completed_);
return test_client_.completion_status();
}
const network::mojom::URLResponseHeadPtr& response_head() const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(request_completed_);
return test_client_.response_head();
}
const std::string& response_body() const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(request_completed_);
return body_;
}
void Verify(CorbExpectations expectations,
const std::string& <API key>) {
if (0 != (expectations & kShouldBeBlocked)) {
ASSERT_EQ(net::OK, completion_status().error_code);
// Verify that the body is empty.
EXPECT_EQ("", response_body());
EXPECT_EQ(0, completion_status().decoded_body_length);
// Verify that other response parts have been sanitized.
EXPECT_EQ(0u, response_head()->content_length);
const std::string& headers = response_head()->headers->raw_headers();
EXPECT_THAT(headers, Not(HasSubstr("Content-Length")));
EXPECT_THAT(headers, Not(HasSubstr("Content-Type")));
// Verify that the console message would have been printed.
EXPECT_TRUE(completion_status().<API key>);
} else {
ASSERT_EQ(net::OK, completion_status().error_code);
EXPECT_FALSE(completion_status().<API key>);
EXPECT_EQ(<API key>, response_body());
}
}
void <API key>(const url::Origin& request_initiator) {
<API key> = request_initiator;
}
void InjectFetchMode(network::mojom::RequestMode request_mode) {
<API key> = request_mode;
}
private:
void ReadBody(base::OnceClosure completion_callback) {
char buffer[128];
uint32_t num_bytes = sizeof(buffer);
MojoResult result = test_client_.response_body().ReadData(
buffer, &num_bytes, <API key>);
bool got_all_data = false;
switch (result) {
case MOJO_RESULT_OK:
if (num_bytes != 0) {
body_ += std::string(buffer, num_bytes);
got_all_data = false;
} else {
got_all_data = true;
}
break;
case <API key>:
// There is no data to be read or discarded (and the producer is still
// open).
got_all_data = false;
break;
case <API key>:
// The data pipe producer handle has been closed.
got_all_data = true;
break;
default:
CHECK(false) << "Unexpected mojo error: " << result;
got_all_data = true;
break;
}
if (!got_all_data) {
base::<API key>::Get()->PostTask(
FROM_HERE,
base::BindOnce(&RequestInterceptor::ReadBody, base::Unretained(this),
std::move(completion_callback)));
} else {
std::move(completion_callback).Run();
}
}
bool InterceptorCallback(<API key>::RequestParams* params) {
DCHECK(params);
if (url_to_intercept_ != params->url_request.url)
return false;
// Prevent more than one intercept.
if (<API key>)
return false;
<API key> = true;
<API key> = base::<API key>::Get();
// Modify |params| if requested.
if (<API key>.has_value())
params->url_request.request_initiator = <API key>;
if (<API key>.has_value())
params->url_request.mode = <API key>.value();
// Inject |test_client_| into the request.
DCHECK(!original_client_);
original_client_ = std::move(params->client);
test_client_remote_.Bind(std::move(<API key>));
<API key> =
std::make_unique<mojo::Receiver<network::mojom::URLLoaderClient>>(
test_client_remote_.get(),
params->client.<API key>());
// Forward the request to the original URLLoaderFactory.
return false;
}
void <API key>(
network::mojom::URLResponseHeadPtr response_head,
std::string response_body,
network::<API key> status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (cleanup_done_)
return;
if (<API key>) {
base::RunLoop run_loop;
<API key>->PostTaskAndReply(
FROM_HERE,
base::BindOnce(&RequestInterceptor::<API key>,
base::Unretained(this), std::move(response_head),
response_body, status),
run_loop.QuitClosure());
run_loop.Run();
}
cleanup_done_ = true;
}
void <API key>(
network::mojom::URLResponseHeadPtr response_head,
std::string response_body,
network::<API key> status) {
if (!<API key>)
return;
// Tell the |original_client_| that the request has completed (and that it
// can release its URLLoaderClient.
if (status.error_code == net::OK) {
original_client_->OnReceiveResponse(std::move(response_head));
mojo::<API key> producer_handle;
mojo::<API key> consumer_handle;
ASSERT_EQ(mojo::CreateDataPipe(response_body.size() + 1, producer_handle,
consumer_handle),
MOJO_RESULT_OK);
original_client_-><API key>(std::move(consumer_handle));
uint32_t num_bytes = response_body.size();
EXPECT_EQ(MOJO_RESULT_OK,
producer_handle->WriteData(response_body.data(), &num_bytes,
<API key>));
}
original_client_->OnComplete(status);
// Reset all temporary mojo bindings.
original_client_.reset();
<API key>.reset();
test_client_remote_.reset();
}
const GURL url_to_intercept_;
<API key> interceptor_;
absl::optional<url::Origin> <API key>;
absl::optional<network::mojom::RequestMode> <API key>;
// |<API key>| below is used to transition results of
// |test_client_.CreateRemote()| into IO thread.
mojo::PendingRemote<network::mojom::URLLoaderClient>
<API key>;
// UI thread state:
network::TestURLLoaderClient test_client_;
std::string body_;
bool request_completed_ = false;
bool cleanup_done_ = false;
// Interceptor thread state:
mojo::Remote<network::mojom::URLLoaderClient> original_client_;
bool <API key> = false;
scoped_refptr<base::<API key>> <API key>;
mojo::Remote<network::mojom::URLLoaderClient> test_client_remote_;
std::unique_ptr<mojo::Receiver<network::mojom::URLLoaderClient>>
<API key>;
};
} // namespace
// These tests verify that the browser process blocks cross-site HTML, XML,
// JSON, and some plain text responses when they are not otherwise permitted
// (e.g., by CORS). This ensures that such responses never end up in the
// renderer process where they might be accessible via a bug. Careful attention
// is paid to allow other cross-site resources necessary for rendering,
// including cases that may be mislabeled as blocked MIME type.
class <API key> : public ContentBrowserTest {
public:
<API key>() = default;
~<API key>() override = default;
// No copy constructor or assignment.
<API key>(const <API key>&) =
delete;
<API key>& operator=(
const <API key>&) = delete;
void SetUpCommandLine(base::CommandLine* command_line) override {
// EmbeddedTestServer::InitializeAndListen() initializes its |base_url_|
// which is required below. This cannot invoke Start() however as that kicks
// off the "EmbeddedTestServer IO Thread" which then races with
// Additionally the server should not be started prior to setting up
// <API key>(s) in some individual tests below.
ASSERT_TRUE(<API key>()->InitializeAndListen());
// Add a host resolver rule to map all outgoing requests to the test server.
// This allows us to use "real" hostnames and standard ports in URLs (i.e.,
// without having to inject the port number into all URLs), which we can use
// to create arbitrary SiteInstances.
command_line->AppendSwitchASCII(
network::switches::kHostResolverRules,
"MAP * " + <API key>()->host_port_pair().ToString() +
",EXCLUDE localhost");
}
};
enum class TestMode {
<API key>,
<API key>,
};
struct ImgTestParams {
const char* resource;
CorbExpectations expectations;
TestMode mode;
};
class <API key>
: public <API key>,
public testing::WithParamInterface<ImgTestParams> {
public:
<API key>() {
switch (GetParam().mode) {
case TestMode::<API key>:
<API key>.<API key>(
network::features::<API key>);
break;
case TestMode::<API key>:
<API key>.<API key>(
network::features::<API key>);
break;
}
}
~<API key>() override = default;
void VerifyImgRequest(std::string resource, CorbExpectations expectations) {
// Test from a http: origin.
VerifyImgRequest(resource, expectations,
GURL("http://foo.com/title1.html"));
// Test from a file: origin.
VerifyImgRequest(resource, expectations,
GetTestUrl(nullptr, "title1.html"));
}
void VerifyImgRequest(std::string resource,
CorbExpectations expectations,
GURL page_url) {
GURL resource_url(
std::string("http://cross-origin.com/site_isolation/" + resource));
SCOPED_TRACE(
base::StringPrintf("... while testing via <img src='%s'> from %s",
resource_url.spec().c_str(),
url::Origin::Create(page_url).Serialize().c_str()));
// Navigate to the test page while request interceptor is active.
RequestInterceptor interceptor(resource_url);
EXPECT_TRUE(NavigateToURL(shell(), page_url));
// Make sure that base::HistogramTester below starts with a clean slate.
<API key>();
// Issue the request that will be intercepted.
base::HistogramTester histograms;
const char kScriptTemplate[] = R"(
var img = document.createElement('img');
img.src = $1;
document.body.appendChild(img); )";
EXPECT_TRUE(ExecJs(shell(), JsReplace(kScriptTemplate, resource_url)));
interceptor.<API key>();
// Verify...
InspectHistograms(histograms, expectations, resource);
interceptor.Verify(expectations,
GetTestFileContents("site_isolation", resource.c_str()));
}
private:
base::test::ScopedFeatureList <API key>;
};
<API key>(<API key>, Test) {
<API key>()-><API key>();
const char* resource = GetParam().resource;
CorbExpectations expectations = GetParam().expectations;
VerifyImgRequest(resource, expectations);
}
#define IMG_TEST(tag, resource, expectations) \
<API key>( \
<API key>##tag, <API key>, \
::testing::Values(ImgTestParams{ \
resource, expectations, TestMode::<API key>})); \
<API key>( \
<API key>##tag, <API key>, \
::testing::Values(ImgTestParams{ \
resource, expectations, TestMode::<API key>}));
// The following are files under content/test/data/site_isolation. All
// should be disallowed for cross site XHR under the document blocking policy.
// valid.* - Correctly labeled HTML/XML/JSON files.
// *.txt - Plain text that sniffs as HTML, XML, or JSON.
// htmlN_dtd.* - Various HTML templates to test.
// json-prefixed* - parser-breaking prefixes
IMG_TEST(valid_html, "valid.html", <API key>)
IMG_TEST(valid_xml, "valid.xml", <API key>)
IMG_TEST(valid_json, "valid.json", <API key>)
IMG_TEST(html_txt, "html.txt", <API key>)
IMG_TEST(xml_txt, "xml.txt", <API key>)
IMG_TEST(json_txt, "json.txt", <API key>)
IMG_TEST(comment_valid_html, "comment_valid.html", <API key>)
IMG_TEST(html4_dtd_html, "html4_dtd.html", <API key>)
IMG_TEST(html4_dtd_txt, "html4_dtd.txt", <API key>)
IMG_TEST(html5_dtd_html, "html5_dtd.html", <API key>)
IMG_TEST(html5_dtd_txt, "html5_dtd.txt", <API key>)
IMG_TEST(json_js, "json.js", <API key>)
IMG_TEST(json_prefixed_1_js, "json-prefixed-1.js", <API key>)
IMG_TEST(json_prefixed_2_js, "json-prefixed-2.js", <API key>)
IMG_TEST(json_prefixed_3_js, "json-prefixed-3.js", <API key>)
IMG_TEST(json_prefixed_4_js, "json-prefixed-4.js", <API key>)
IMG_TEST(nosniff_json_js, "nosniff.json.js", <API key>)
IMG_TEST(<API key>,
"nosniff.json-prefixed.js",
<API key>)
// These files should be disallowed without sniffing.
// nosniff.* - Won't sniff correctly, but blocked because of nosniff.
IMG_TEST(nosniff_html, "nosniff.html", <API key>)
IMG_TEST(nosniff_xml, "nosniff.xml", <API key>)
IMG_TEST(nosniff_json, "nosniff.json", <API key>)
IMG_TEST(nosniff_txt, "nosniff.txt", <API key>)
IMG_TEST(fake_pdf, "fake.pdf", <API key>)
IMG_TEST(fake_zip, "fake.zip", <API key>)
// These files are allowed for XHR under the document blocking policy because
// the sniffing logic determines they are not actually documents.
// *js.* - JavaScript mislabeled as a document.
// jsonp.* - JSONP (i.e., script) mislabeled as a document.
// img.* - Contents that won't match the document label.
// valid.* - Correctly labeled responses of non-document types.
IMG_TEST(html_prefix_txt, "html-prefix.txt", <API key>)
IMG_TEST(js_html, "js.html", <API key>)
IMG_TEST(comment_js_html, "comment_js.html", <API key>)
IMG_TEST(js_xml, "js.xml", <API key>)
IMG_TEST(js_json, "js.json", <API key>)
IMG_TEST(js_txt, "js.txt", <API key>)
IMG_TEST(jsonp_html, "jsonp.html", <API key>)
IMG_TEST(jsonp_xml, "jsonp.xml", <API key>)
IMG_TEST(jsonp_json, "jsonp.json", <API key>)
IMG_TEST(jsonp_txt, "jsonp.txt", <API key>)
IMG_TEST(img_html, "img.html", <API key>)
IMG_TEST(img_xml, "img.xml", <API key>)
IMG_TEST(img_json, "img.json", <API key>)
IMG_TEST(img_txt, "img.txt", <API key>)
IMG_TEST(valid_js, "valid.js", <API key>)
IMG_TEST(json_list_js, "json-list.js", <API key>)
IMG_TEST(<API key>,
"nosniff.json-list.js",
<API key>)
IMG_TEST(<API key>,
"js-html-polyglot.html",
<API key>)
IMG_TEST(<API key>,
"js-html-polyglot2.html",
<API key>)
class <API key>
: public <API key>,
public testing::WithParamInterface<TestMode> {
public:
<API key>() {
switch (GetParam()) {
case TestMode::<API key>:
<API key>.<API key>(
network::features::<API key>);
break;
case TestMode::<API key>:
<API key>.<API key>(
network::features::<API key>);
break;
}
}
~<API key>() override = default;
private:
base::test::ScopedFeatureList <API key>;
};
// This test covers an aspect of <API key> (CORP, different
// from CORB) that cannot be covered by wpt/fetch/<API key>:
// whether blocking occurs *before* the response reaches the renderer process.
<API key>(<API key>,
<API key>) {
<API key>()-><API key>();
// Navigate to the test page while request interceptor is active.
GURL resource_url("http://cross-origin.com/site_isolation/png-corp.png");
RequestInterceptor interceptor(resource_url);
EXPECT_TRUE(NavigateToURL(shell(), GURL("http://foo.com/title1.html")));
// Issue the request that will be intercepted.
const char kScriptTemplate[] = R"(
var img = document.createElement('img');
img.src = $1;
document.body.appendChild(img); )";
EXPECT_TRUE(ExecJs(shell(), JsReplace(kScriptTemplate, resource_url)));
interceptor.<API key>();
// Verify that <API key> blocked the response before it
// reached the renderer process.
EXPECT_EQ(net::<API key>,
interceptor.completion_status().error_code);
EXPECT_EQ("", interceptor.response_body());
}
<API key>(<API key>, AllowCorsFetches) {
<API key>()-><API key>();
GURL foo_url("http://foo.com/<API key>/request.html");
EXPECT_TRUE(NavigateToURL(shell(), foo_url));
// These files should be allowed for XHR under the document blocking policy.
// cors.* - Correctly labeled documents with valid CORS headers.
const char* allowed_resources[] = {"cors.html", "cors.xml", "cors.json",
"cors.txt"};
for (const char* resource : allowed_resources) {
SCOPED_TRACE(base::StringPrintf("... while testing page: %s", resource));
// Make sure that base::HistogramTester below starts with a clean slate.
<API key>();
base::HistogramTester histograms;
// Fetch and verify results of the fetch.
EXPECT_EQ(false, EvalJs(shell(),
base::StringPrintf("sendRequest('%s');", resource),
<API key>));
InspectHistograms(histograms, <API key>, resource);
}
}
<API key>(<API key>,
<API key>) {
<API key>()-><API key>();
// LoadDataWithBaseURL is never subject to --site-per-process policy today
// (this API is only used by Android WebView [where OOPIFs have not shipped
// yet] and GuestView cases [which always hosts guests inside a renderer
// without an origin lock]). Therefore, skip the test in --site-per-process
// mode to avoid renderer kills which won't happen in practice as described
// above.
// Webview or WebView guests support OOPIFs and/or origin locks.
if (<API key>())
return;
// Navigate via LoadDataWithBaseURL.
const GURL base_url("http://foo.com");
const std::string data = "<html><body>foo</body></html>";
const GURL data_url = GURL("data:text/html;charset=utf-8," + data);
<API key> nav_observer(shell()->web_contents(), 1);
shell()->LoadDataWithBaseURL(base_url /* history_url */, data, base_url);
nav_observer.Wait();
// Fetch a same-origin resource.
GURL resource_url("http://foo.com/site_isolation/nosniff.html");
EXPECT_EQ(url::Origin::Create(resource_url),
shell()->web_contents()->GetMainFrame()-><API key>());
<API key>();
base::HistogramTester histograms;
std::string fetch_result =
EvalJs(shell(), JsReplace("fetch($1).then(response => response.text())",
resource_url))
.ExtractString();
fetch_result = std::string(TrimWhitespaceASCII(fetch_result, base::TRIM_ALL));
// Verify that the response was not blocked.
EXPECT_EQ("runMe({ \"name\" : \"chromium\" });", fetch_result);
InspectHistograms(histograms, <API key>,
"nosniff.html");
}
<API key>(<API key>, BackToAboutBlank) {
<API key>()-><API key>();
// Prepare to verify results of a fetch.
GURL resource_url("http://foo.com/title2.html");
const char* resource = "title2.html";
const char <API key>[] = R"(
fetch($1, {mode: 'no-cors'}).then(response => 'ok');
)";
std::string fetch_script = JsReplace(<API key>, resource_url);
// Navigate to the test page and open a popup via |window.open|, explicitly
// specifying 'about:blank' destination, so that we can go back to it later.
GURL initial_url("http://foo.com/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), initial_url));
<API key> popup_observer;
ASSERT_TRUE(ExecJs(shell(), "var popup = window.open('about:blank', '')"));
WebContents* popup = popup_observer.GetWebContents();
EXPECT_EQ(GURL(url::kAboutBlankURL),
popup->GetMainFrame()->GetLastCommittedURL());
EXPECT_EQ(shell()->web_contents()->GetMainFrame()-><API key>(),
popup->GetMainFrame()-><API key>());
EXPECT_EQ(url::Origin::Create(resource_url),
popup->GetMainFrame()-><API key>());
// Verify that CORB doesn't block same-origin request from the popup.
{
<API key>();
base::HistogramTester histograms;
ASSERT_EQ("ok", EvalJs(popup, fetch_script));
InspectHistograms(histograms, <API key>, resource);
}
// Navigate the popup and then go back to the 'about:blank' URL.
<API key> nav_observer(popup);
ASSERT_TRUE(ExecJs(shell(), "popup.location.href = '/title3.html'"));
nav_observer.<API key>();
<API key> back_observer(popup);
ASSERT_TRUE(ExecJs(shell(), "popup.history.back()"));
back_observer.<API key>();
EXPECT_EQ(GURL(url::kAboutBlankURL),
popup->GetMainFrame()->GetLastCommittedURL());
EXPECT_EQ(shell()->web_contents()->GetMainFrame()-><API key>(),
popup->GetMainFrame()-><API key>());
EXPECT_EQ(url::Origin::Create(resource_url),
popup->GetMainFrame()-><API key>());
// Verify that CORB doesn't block same-origin request from the popup.
{
<API key>();
base::HistogramTester histograms;
ASSERT_EQ("ok", EvalJs(popup, fetch_script));
InspectHistograms(histograms, <API key>, resource);
}
}
<API key>(<API key>, <API key>) {
// This webpage loads a cross-site HTML page in different targets such as
// <img>,<link>,<embed>, etc. Since the requested document is blocked, and one
// character string (' ') is returned instead, this tests that the renderer
// does not crash even when it receives a response body which is " ", whose
// length is different from what's described in "content-length" for such
// different targets.
// TODO(nick): Split up these cases, and add positive assertions here about
// what actually happens in these various resource-block cases.
<API key>()-><API key>();
GURL foo("http://foo.com/<API key>/request_target.html");
EXPECT_TRUE(NavigateToURL(shell(), foo));
// TODO(creis): Wait for all the subresources to load and ensure renderer
// process is still alive.
}
// Checks to see that CORB blocking applies to processes hosting error pages.
<API key>(<API key>,
<API key>) {
<API key>()-><API key>();
GURL error_url = <API key>()->GetURL("bar.com", "/close-socket");
GURL subresource_url =
<API key>()->GetURL("foo.com", "/site_isolation/json.js");
// Load |error_url| and expect a network error page.
<API key> observer(shell()->web_contents());
EXPECT_FALSE(NavigateToURL(shell(), error_url));
EXPECT_EQ(error_url, observer.last_navigation_url());
NavigationEntry* entry =
shell()->web_contents()->GetController().<API key>();
EXPECT_EQ(PAGE_TYPE_ERROR, entry->GetPageType());
// Add a <script> tag whose src is a CORB-protected resource. Expect no
// window.onerror to result, because no syntax error is generated by the empty
// response.
std::string script = R"((subresource_url => {
window.onerror = () => <API key>.send("CORB BYPASSED");
var script = document.createElement('script');
script.src = subresource_url;
script.onload = () => <API key>.send("CORB WORKED");
document.body.appendChild(script);
}))";
EXPECT_EQ("CORB WORKED",
EvalJs(shell(), script + "('" + subresource_url.spec() + "')",
<API key>));
}
<API key>(<API key>,
<API key>) {
<API key>()-><API key>();
// Prepare to intercept the network request at the IPC layer.
// This has to be done before the RenderFrameHostImpl is created.
// Note: we want to verify that the blocking prevents the data from being sent
// over IPC. Testing later (e.g. via Response/Headers Web APIs) might give a
// false sense of security, since some sanitization happens inside the
// renderer (e.g. via FetchResponseData::<API key>).
GURL bar_url("http://bar.com/<API key>/headers-test.json");
RequestInterceptor interceptor(bar_url);
// Navigate to the test page.
GURL foo_url("http://foo.com/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), foo_url));
// Issue the request that will be intercepted.
const char kScriptTemplate[] = R"(
var img = document.createElement('img');
img.src = $1;
document.body.appendChild(img); )";
EXPECT_TRUE(ExecJs(shell(), JsReplace(kScriptTemplate, bar_url)));
interceptor.<API key>();
// Verify that the response completed successfully, was blocked and was logged
// as having initially a non-empty body.
interceptor.Verify(<API key>,
"no resource body needed for blocking verification");
// Verify that all response headers have been removed by CORB.
const std::string& headers =
interceptor.response_head()->headers->raw_headers();
EXPECT_THAT(headers,
Not(HasSubstr("<API key>: https://other")));
EXPECT_THAT(headers, Not(HasSubstr("Cache-Control")));
EXPECT_THAT(headers, Not(HasSubstr("Content-Language")));
EXPECT_THAT(headers, Not(HasSubstr("Content-Length")));
EXPECT_THAT(headers, Not(HasSubstr("Content-Type")));
EXPECT_THAT(headers, Not(HasSubstr("Expires")));
EXPECT_THAT(headers, Not(HasSubstr("Last-Modified")));
EXPECT_THAT(headers, Not(HasSubstr("MySecretCookieKey")));
EXPECT_THAT(headers, Not(HasSubstr("MySecretCookieValue")));
EXPECT_THAT(headers, Not(HasSubstr("Pragma")));
EXPECT_THAT(headers, Not(HasSubstr("<API key>")));
EXPECT_THAT(headers, Not(HasSubstr("X-My-Secret-Header")));
// Verify that the body is empty.
EXPECT_EQ("", interceptor.response_body());
EXPECT_EQ(0, interceptor.completion_status().decoded_body_length);
// Verify that other response parts have been sanitized.
EXPECT_EQ(0u, interceptor.response_head()->content_length);
}
<API key>(<API key>,
<API key>) {
<API key>()-><API key>();
// Prepare to intercept the network request at the IPC layer.
// This has to be done before the RenderFrameHostImpl is created.
// Note: we want to verify that the blocking prevents the data from being sent
// over IPC. Testing later (e.g. via Response/Headers Web APIs) might give a
// false sense of security, since some sanitization happens inside the
// renderer (e.g. via FetchResponseData::<API key>).
GURL bar_url("http://bar.com/<API key>/headers-test.png");
RequestInterceptor interceptor(bar_url);
std::string png_body =
GetTestFileContents("<API key>", "headers-test.png");
// Navigate to the test page.
GURL foo_url("http://foo.com/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), foo_url));
// Issue the request that will be intercepted.
const char kScriptTemplate[] = R"(
var img = document.createElement('img');
img.src = $1;
document.body.appendChild(img); )";
EXPECT_TRUE(ExecJs(shell(), JsReplace(kScriptTemplate, bar_url)));
interceptor.<API key>();
// Verify that the response completed successfully, was blocked and was logged
// as having initially a non-empty body.
interceptor.Verify(<API key>, png_body);
// Verify that most response headers have been allowed by CORB.
const std::string& headers =
interceptor.response_head()->headers->raw_headers();
EXPECT_THAT(headers, HasSubstr("Cache-Control"));
EXPECT_THAT(headers, HasSubstr("Content-Length"));
EXPECT_THAT(headers, HasSubstr("Content-Type"));
EXPECT_THAT(headers, HasSubstr("Expires"));
EXPECT_THAT(headers, HasSubstr("Last-Modified"));
EXPECT_THAT(headers, HasSubstr("Pragma"));
EXPECT_THAT(headers, HasSubstr("<API key>"));
EXPECT_THAT(headers, HasSubstr("X-My-Secret-Header"));
// Verify that the body has been allowed by CORB.
EXPECT_EQ(png_body, interceptor.response_body());
EXPECT_EQ(static_cast<int64_t>(png_body.size()),
interceptor.completion_status().decoded_body_length);
EXPECT_EQ(static_cast<int64_t>(png_body.size()),
interceptor.response_head()->content_length);
// MAIN VERIFICATION: Verify that despite allowing the response in CORB, we
// stripped out the cookies (i.e. the cookies present in
// <API key>/headers-test.png.mock-http-headers).
// This verification helps ensure that no cross-origin secrets are disclosed
// in no-cors responses.
EXPECT_THAT(headers, Not(HasSubstr("<API key>")));
EXPECT_THAT(headers, Not(HasSubstr("<API key>")));
EXPECT_THAT(headers, Not(HasSubstr("My<API key>)));
EXPECT_THAT(headers, Not(HasSubstr("<API key>")));
}
<API key>(<API key>,
<API key>) {
<API key>()-><API key>();
// Prepare to intercept the network request at the IPC layer.
// This has to be done before the RenderFrameHostImpl is created.
// Note: we want to verify that the blocking prevents the data from being sent
// over IPC. Testing later (e.g. via Response/Headers Web APIs) might give a
// false sense of security, since some sanitization happens inside the
// renderer (e.g. via FetchResponseData::<API key>).
GURL foo_resource_url(
"http://foo.com/<API key>/headers-test.png");
RequestInterceptor interceptor(foo_resource_url);
std::string png_body =
GetTestFileContents("<API key>", "headers-test.png");
// Navigate to the test page.
GURL foo_url("http://foo.com/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), foo_url));
// Issue the request that will be intercepted.
const char kScriptTemplate[] = R"(
var img = document.createElement('img');
img.src = $1;
document.body.appendChild(img); )";
EXPECT_TRUE(ExecJs(shell(), JsReplace(kScriptTemplate, foo_resource_url)));
interceptor.<API key>();
// Verify that the response completed successfully, was blocked and was logged
// as having initially a non-empty body.
interceptor.Verify(<API key>, png_body);
// Verify that most response headers have been allowed by CORB.
const std::string& headers =
interceptor.response_head()->headers->raw_headers();
EXPECT_THAT(headers, HasSubstr("Cache-Control"));
EXPECT_THAT(headers, HasSubstr("Content-Length"));
EXPECT_THAT(headers, HasSubstr("Content-Type"));
EXPECT_THAT(headers, HasSubstr("Expires"));
EXPECT_THAT(headers, HasSubstr("Last-Modified"));
EXPECT_THAT(headers, HasSubstr("Pragma"));
EXPECT_THAT(headers, HasSubstr("<API key>"));
EXPECT_THAT(headers, HasSubstr("X-My-Secret-Header"));
// Verify that the body has been allowed by CORB.
EXPECT_EQ(png_body, interceptor.response_body());
EXPECT_EQ(static_cast<int64_t>(png_body.size()),
interceptor.completion_status().decoded_body_length);
EXPECT_EQ(static_cast<int64_t>(png_body.size()),
interceptor.response_head()->content_length);
// MAIN VERIFICATION: Verify that despite allowing the response in CORB, we
// stripped out the cookies (i.e. the cookies present in
// <API key>/headers-test.png.mock-http-headers).
// No security boundary is crossed in this test case (since this is a
// same-origin response), but for consistency we want to ensure that cookies
// are stripped in all IPCs.
EXPECT_THAT(headers, Not(HasSubstr("<API key>")));
EXPECT_THAT(headers, Not(HasSubstr("<API key>")));
EXPECT_THAT(headers, Not(HasSubstr("My<API key>)));
EXPECT_THAT(headers, Not(HasSubstr("<API key>")));
}
// SharedWorkers are also enabled on Android.
#if !defined(OS_ANDROID)
<API key>(<API key>, SharedWorker) {
<API key>()-><API key>();
// Prepare to intercept the network request at the IPC layer.
// This has to be done before the SharedWorkerHost is created.
GURL bar_url("http://bar.com/site_isolation/nosniff.json");
RequestInterceptor interceptor(bar_url);
// Navigate to the test page.
GURL foo_url("http://foo.com/title1.html");
EXPECT_TRUE(NavigateToURL(shell(), foo_url));
// Start a shared worker and wait until it says that it is ready.
const char <API key>[] = R"(
onconnect = function(e) {
const port = e.ports[0];
port.addEventListener('message', function(e) {
url = e.data;
fetch(url, {mode: 'no-cors'})
.then(_ => port.postMessage('FETCH SUCCEEDED'))
.catch(e => port.postMessage('FETCH ERROR: ' + e));
});
port.start();
port.postMessage('WORKER READY');
};
)";
std::string worker_script;
base::Base64Encode(JsReplace(<API key>, bar_url), &worker_script);
const char <API key>[] = R"(
new Promise(function (resolve, reject) {
const worker_url = 'data:application/javascript;base64,' + $1;
window.myWorker = new SharedWorker(worker_url);
window.<API key> = resolve;
window.myWorker.port.onmessage = function(e) {
window.<API key>(e.data);
};
});
)";
EXPECT_EQ("WORKER READY",
EvalJs(shell(), JsReplace(<API key>, worker_script)));
// Make sure that base::HistogramTester below starts with a clean slate.
<API key>();
base::HistogramTester histograms;
// Ask the shared worker to perform a cross-origin fetch.
const char kFetchStartTemplate[] = R"(
const fetch_url = $1;
window.<API key> = function(data) {
window.myWorkerResult = data;
}
window.myWorker.port.postMessage(fetch_url);
)";
EXPECT_TRUE(ExecJs(shell(), JsReplace(kFetchStartTemplate, bar_url)));
interceptor.<API key>();
interceptor.Verify(<API key>,
"no resource body needed for blocking verification");
// Wait for fetch result (really needed only without NetworkService, if no
// interceptor.<API key> was called above).
const char kFetchWait[] = R"(
new Promise(function (resolve, reject) {
if (window.myWorkerResult) {
resolve(window.myWorkerResult);
return;
}
window.<API key> = resolve;
});
)";
EXPECT_EQ("FETCH SUCCEEDED", EvalJs(shell(), kFetchWait));
// Verify that the response completed successfully, was blocked and was logged
// as having initially a non-empty body.
InspectHistograms(histograms, <API key>,
"nosniff.json");
}
#endif // !defined(OS_ANDROID)
<API key>(<API key>,
<API key>) {
// Prepare for intercepting the resource request for testing prefetching.
const char* <API key> = "/prefetch-test";
net::test_server::<API key> response(<API key>(),
<API key>);
// Navigate to a webpage containing a cross-origin frame.
<API key>()-><API key>();
GURL main_url(<API key>()->GetURL(
"a.com", "/<API key>.html?a(b)"));
EXPECT_TRUE(NavigateToURL(shell(), main_url));
// Make sure that base::HistogramTester below starts with a clean slate.
<API key>();
// Inject a cross-origin <link rel="prefetch" ...> into the main frame.
// TODO(lukasza): https://crbug.com/827633#c5: We might need to switch to
// listening to the onload event below (after/if CORB starts to consistently
// avoid injecting net errors).
<API key>();
base::HistogramTester histograms;
const char* <API key> = R"(
var link = document.createElement("link");
link.rel = "prefetch";
link.href = "/cross-site/b.com%s";
link.as = "fetch";
window.is_prefetch_done = false;
function <API key>() { window.is_prefetch_done = true }
link.onerror = <API key>;
document.<API key>('head')[0].appendChild(link);
)";
std::string <API key> = base::StringPrintf(
<API key>, <API key>);
EXPECT_TRUE(ExecJs(shell()->web_contents(), <API key>));
// Respond to the prefetch request in a way that:
// 1) will enable caching
// 2) won't finish until after CORB has blocked the response.
std::string response_bytes =
"HTTP/1.1 200 OK\r\n"
"Cache-Control: public, max-age=10\r\n"
"Content-Type: text/html\r\n"
"<API key>: nosniff\r\n"
"\r\n"
"<p>contents of the response</p>";
response.WaitForRequest();
response.Send(response_bytes);
// Verify that CORB blocked the response.
// TODO(lukasza): https://crbug.com/827633#c5: We might need to switch to
// listening to the onload event below (after/if CORB starts to consistently
// avoid injecting net errors).
std::string wait_script = R"(
function <API key>() { <API key>.send(123); }
if (window.is_prefetch_done) {
// Can notify immediately if |window.is_prefetch_done| has already been
// set by |<API key>|.
<API key>();
} else {
// Otherwise wait for CORB's empty response to reach the renderer.
link = document.<API key>('link')[0];
link.onerror = <API key>;
}
)";
EXPECT_EQ(123, EvalJs(shell()->web_contents(), wait_script,
<API key>));
InspectHistograms(histograms, <API key>, "x.html");
// Finish the HTTP response - this should store the response in the cache.
response.Done();
// Stop the HTTP server - this means the only way to get the response in
// the |fetch_script| below is to get it from the cache (e.g. if the request
// goes to the network there will be no HTTP server to handle it).
// Note that stopping the HTTP server is not strictly required for the test to
// be robust - <API key> handles only a single request, so
// wouldn't handle the |fetch_script| request even if the HTTP server was
// still running.
EXPECT_TRUE(<API key>()-><API key>());
// Verify that the cached response is available to the same-origin subframe
// (e.g. that the network cache in the browser process got populated despite
// CORB blocking).
const char* <API key> = R"(
fetch('%s')
.then(response => response.text())
.then(responseBody => {
<API key>.send(responseBody);
})
.catch(error => {
var errorMessage = 'error: ' + error;
console.log(errorMessage);
<API key>.send(errorMessage);
}); )";
std::string fetch_script =
base::StringPrintf(<API key>, <API key>);
EXPECT_EQ("<p>contents of the response</p>",
EvalJs(ChildFrameAt(shell()->web_contents(), 0), fetch_script,
<API key>));
}
<API key>(
<API key>,
<API key>,
::testing::Values(TestMode::<API key>));
<API key>(
<API key>,
<API key>,
::testing::Values(TestMode::<API key>));
// This test class sets up a service worker that can be used to try to respond
// to same-origin requests with cross-origin responses.
class <API key> : public ContentBrowserTest {
public:
<API key>()
: <API key>(net::EmbeddedTestServer::TYPE_HTTPS),
<API key>(net::EmbeddedTestServer::TYPE_HTTPS) {}
~<API key>() override {}
// No copy constructor or assignment operator.
<API key>(
const <API key>&) = delete;
<API key>& operator=(
const <API key>&) = delete;
void SetUpCommandLine(base::CommandLine* command_line) override {
<API key>(command_line);
ContentBrowserTest::SetUpCommandLine(command_line);
}
void SetUpOnMainThread() override {
<API key>(<API key>());
<API key>.<API key>(
GetTestDataFilePath());
ASSERT_TRUE(<API key>.Start());
<API key>.<API key>(
GetTestDataFilePath());
<API key>.SetSSLConfig(
net::EmbeddedTestServer::<API key>);
ASSERT_TRUE(<API key>.Start());
// Sanity check of test setup - the 2 https servers should be cross-site
// (the second server should have a different hostname because of the call
// to SetSSLConfig with <API key> argument).
ASSERT_FALSE(net::<API key>::SameDomainOrHost(
<API key>("/"), <API key>("/"),
net::<API key>::<API key>));
}
GURL <API key>(const std::string& path) {
return <API key>.GetURL(path);
}
GURL <API key>(const std::string& path) {
return <API key>.GetURL(path);
}
void <API key>() {
EXPECT_TRUE(<API key>.<API key>());
}
void SetUpServiceWorker() {
GURL url = <API key>(
"/<API key>/request.html");
ASSERT_TRUE(NavigateToURL(shell(), url));
// Register the service worker.
std::string script = R"(
navigator.serviceWorker
.register('/<API key>/service_worker.js')
.then(registration => navigator.serviceWorker.ready)
.then(function(r) { <API key>.send(true); })
.catch(function(e) {
console.log('error: ' + e);
<API key>.send(false);
}); )";
ASSERT_EQ(true, EvalJs(shell(), script, <API key>));
// Navigate again to the same URL - the service worker should be 1) active
// at this time (because of waiting for |navigator.serviceWorker.ready|
// above) and 2) controlling the current page (because of the reload).
ASSERT_TRUE(NavigateToURL(shell(), url));
ASSERT_EQ(true, EvalJs(shell(), "!!navigator.serviceWorker.controller"));
}
private:
// The test requires 2 https servers, because:
// 1. Service workers are only supported on secure origins.
// 2. One of tests requires fetching cross-origin resources from the
// original page and/or service worker - the target of the fetch needs to
// be a https server to avoid hitting the mixed content error.
net::EmbeddedTestServer <API key>;
net::EmbeddedTestServer <API key>;
};
<API key>(<API key>,
<API key>) {
SetUpServiceWorker();
// Make sure that the histograms generated by a service worker registration
// have been recorded.
<API key>();
// Build a script for XHR-ing a cross-origin, nosniff HTML document.
GURL cross_origin_url =
<API key>("/site_isolation/nosniff.txt");
const char* script_template = R"(
fetch('%s', { mode: 'no-cors' })
.then(response => response.text())
.then(responseText => {
<API key>.send(responseText);
})
.catch(error => {
var errorMessage = 'error: ' + error;
<API key>.send(errorMessage);
}); )";
std::string script =
base::StringPrintf(script_template, cross_origin_url.spec().c_str());
// Make sure that base::HistogramTester below starts with a clean slate.
<API key>();
// The service worker will forward the request to the network, but a response
// will be intercepted by the service worker and replaced with a new,
// artificial error.
base::HistogramTester histograms;
std::string response =
EvalJs(shell(), script, <API key>).ExtractString();
// Verify that CORB blocked the response from the network (from
// |<API key>|) to the service worker.
InspectHistograms(histograms, <API key>, "network.txt");
// Verify that the service worker replied with an expected error.
// Replying with an error means that CORB is only active once (for the
// initial, real network request) and therefore the test doesn't get
// confused (second successful response would have added noise to the
// histograms captured by the test).
EXPECT_EQ("error: TypeError: Failed to fetch", response);
}
// Test class to verify that --<API key> turns off CORB.
class <API key>
: public <API key> {
public:
<API key>() {}
~<API key>() override {}
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitch(switches::kDisableWebSecurity);
<API key>::SetUpCommandLine(command_line);
}
};
<API key>(<API key>,
DisableBlocking) {
<API key>()-><API key>();
GURL foo_url("http://foo.com/<API key>/request.html");
EXPECT_TRUE(NavigateToURL(shell(), foo_url));
ASSERT_EQ(false, EvalJs(shell(), "sendRequest(\"valid.html\");",
<API key>));
}
// Test class to verify that documents are blocked for isolated origins as well.
class <API key>
: public <API key> {
public:
<API key>() {}
~<API key>() override {}
void SetUpCommandLine(base::CommandLine* command_line) override {
command_line->AppendSwitchASCII(switches::kIsolateOrigins,
"http://bar.com");
<API key>::SetUpCommandLine(command_line);
}
};
<API key>(<API key>,
<API key>) {
<API key>()-><API key>();
if (<API key>())
return;
// isolated origin.
GURL foo_url("http://foo.com/<API key>/request.html");
EXPECT_TRUE(NavigateToURL(shell(), foo_url));
ASSERT_EQ(true, EvalJs(shell(), "sendRequest(\"valid.html\");",
<API key>));
}
<API key>(ContentBrowserTest, <API key>) {
ASSERT_TRUE(<API key>()->Start());
GURL test_url =
<API key>()->GetURL("/site_isolation/png-corp.png");
BrowserContext* browser_context =
shell()->web_contents()->GetBrowserContext();
StoragePartition* partition = browser_context-><API key>();
ASSERT_EQ(net::OK,
LoadBasicRequest(partition->GetNetworkContext(), test_url));
}
// This test class sets up a link element for webbundle subresource loading.
// e.g. <link rel=webbundle href=".../foo.wbn" resources="...">.
class <API key>
: public ContentBrowserTest,
public testing::WithParamInterface<std::string> {
public:
<API key>() {
<API key>.<API key>(features::<API key>);
}
~<API key>() override = default;
<API key>(
const <API key>&) = delete;
<API key>& operator=(
const <API key>&) = delete;
net::EmbeddedTestServer* https_server() { return &https_server_; }
static std::string DescribeParams(
const testing::TestParamInfo<ParamType>& info) {
return info.param;
}
protected:
void <API key>(const GURL& bundle_url,
const GURL subresource_url) {
// Navigate to the test page.
ASSERT_TRUE(
NavigateToURL(shell(), GURL("https://same-origin.test/title1.html")));
const char kScriptTemplate[] = R"(
const link = document.createElement('link');
link.rel = 'webbundle';
link.href = $1;
link.resources.add($2);
document.body.appendChild(link);
const img = document.createElement('img');
img.src = $2;
document.body.appendChild(img);
)";
// Insert a <link> element for webbundle subresoruce loading, and insert an
// <img> element which loads a resource from the webbundle.
ASSERT_TRUE(ExecJs(
shell(), JsReplace(kScriptTemplate, bundle_url, subresource_url)));
}
void SetUpOnMainThread() override {
ContentBrowserTest::SetUpOnMainThread();
mock_cert_verifier_.mock_cert_verifier()->set_default_result(net::OK);
}
void SetUpCommandLine(base::CommandLine* command_line) override {
ContentBrowserTest::SetUpCommandLine(command_line);
mock_cert_verifier_.SetUpCommandLine(command_line);
https_server_.<API key>(GetTestDataFilePath());
ASSERT_TRUE(https_server_.InitializeAndListen());
command_line->AppendSwitchASCII(
network::switches::kHostResolverRules,
"MAP * " + https_server_.host_port_pair().ToString() +
",EXCLUDE localhost");
}
void <API key>() override {
ContentBrowserTest::<API key>();
mock_cert_verifier_.<API key>();
}
void <API key>() override {
ContentBrowserTest::<API key>();
mock_cert_verifier_.<API key>();
}
private:
content::<API key> mock_cert_verifier_;
base::test::ScopedFeatureList <API key>;
net::EmbeddedTestServer https_server_{
net::EmbeddedTestServer::Type::TYPE_HTTPS};
};
// <API key> has 4 tests; a cartesian product of
// 1) cross-origin bundle, 2) same-origin bundle
// A). CORB-protected MIME type (e.g. text/json), B) other type (e.g. image/png)
<API key>(<API key>,
<API key>) {
https_server()-><API key>();
GURL bundle_url("https://cross-origin.test/web_bundle/cross_origin" +
GetParam() + ".wbn");
GURL subresource_url("https://cross-origin.test/web_bundle/resource.json");
RequestInterceptor interceptor(subresource_url);
<API key>(bundle_url, subresource_url);
interceptor.<API key>();
EXPECT_EQ(0, interceptor.completion_status().error_code);
EXPECT_EQ("", interceptor.response_body())
<< "JSON in a cross-origin webbundle should be blocked by CORB";
}
<API key>(<API key>,
<API key>) {
https_server()-><API key>();
GURL bundle_url("https://cross-origin.test/web_bundle/cross_origin" +
GetParam() + ".wbn");
GURL subresource_url("https://cross-origin.test/web_bundle/resource.png");
RequestInterceptor interceptor(subresource_url);
<API key>(bundle_url, subresource_url);
interceptor.<API key>();
EXPECT_EQ(0, interceptor.completion_status().error_code);
EXPECT_EQ("broken png", interceptor.response_body())
<< "PNG in a cross-origin webbundle should not be blocked";
}
<API key>(<API key>,
<API key>) {
https_server()-><API key>();
GURL bundle_url("https://same-origin.test/web_bundle/same_origin" +
GetParam() + ".wbn");
GURL subresource_url("https://same-origin.test/web_bundle/resource.json");
RequestInterceptor interceptor(subresource_url);
<API key>(bundle_url, subresource_url);
interceptor.<API key>();
EXPECT_EQ(0, interceptor.completion_status().error_code);
EXPECT_EQ("{ secret: 1 }", interceptor.response_body())
<< "JSON in a same-origin webbundle should not be blocked";
}
<API key>(<API key>,
<API key>) {
https_server()-><API key>();
GURL bundle_url("https://same-origin.test/web_bundle/same_origin" +
GetParam() + ".wbn");
GURL subresource_url("https://same-origin.test/web_bundle/resource.png");
RequestInterceptor interceptor(subresource_url);
<API key>(bundle_url, subresource_url);
interceptor.<API key>();
EXPECT_EQ(0, interceptor.completion_status().error_code);
EXPECT_EQ("broken png", interceptor.response_body())
<< "PNG in a same-origin webbundle should not be blocked";
}
<API key>(
<API key>,
<API key>,
testing::Values("_b1", "_b2"),
<API key>::DescribeParams);
} // namespace content |
// SeqAn - The Library for Sequence Analysis
// modification, are permitted provided that the following conditions are met:
// documentation and/or other materials provided with the distribution.
// * Neither the name of Knut Reinert or the FU Berlin nor the names of
// its contributors may be used to endorse or promote products derived
// 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 KNUT REINERT OR THE FU BERLIN 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.
// Code for Dna(5) to AminoAcid Translation
#ifndef <API key>
#define <API key>
namespace seqan {
// Forwards
// Tags, Classes, Enums
// Enum TranslationFrames
/*!
* @enum TranslationFrames
* @headerfile <seqan/translation.h>
* @brief Class Enum with frames for @link translate @endlink()
*
* @signature enum class TranslationFrames : uint8_t { ... };
*
* Please not that this is part of the translation module which requires C++11.
*
* @val TranslationFrames SINGLE_FRAME = 0;
* @brief Translate the sequence(s) "as is", n input sequences result in n output sequences.
*
* @val TranslationFrames <API key> = 1;
* @brief Translate the sequence(s) as well as their reverse complements (n -> * 2n).
*
* @val TranslationFrames WITH_FRAME_SHIFTS = 2;
* @brief Translate the sequence(s) as well as their shifted frames (n -> 3n).
*
* @val TranslationFrames SIX_FRAME = 3;
* @brief Equals (<API key> | WITH_FRAME_SHIFTS); shifted frames of original and reverse complement are
* translated (n -> 6n).
*/
enum TranslationFrames
{
SINGLE_FRAME = 0,
<API key> = 1,
WITH_FRAME_SHIFTS = 2,
SIX_FRAME = 3
};
// Tag Frames_ (internal)
template <uint8_t num>
struct Frames_
{};
// Metafunctions
// Metafunction ReverseComplement_
// type of the reverse complement of a string, also works with infixes and
// ModifiedStrings
template <typename T>
struct ReverseComplement_
{
typedef ModifiedString<
ModifiedString<T, ModView<
FunctorComplement<
typename Value<T>::Type > > >, ModReverse> Type;
};
// Functions
// Function _ord()
// returns ordValue of a DNA(5) or RNA(5) character
// for everything else (e.g. char) the character is converted to Dna5 first
template <typename T>
inline typename ValueSize<T>::Type
_ord(T const & c)
{
return ordValue(Dna5(c));
}
inline ValueSize<Dna>::Type
_ord(Dna const & c)
{
return ordValue(c);
}
inline ValueSize<Dna5>::Type
_ord(Dna5 const & c)
{
return ordValue(c);
}
inline ValueSize<Rna>::Type
_ord(Rna const & c)
{
return ordValue(c);
}
inline ValueSize<Rna5>::Type
_ord(Rna5 const & c)
{
return ordValue(c);
}
// Function _translateTriplet()
template <typename TOrd, GeneticCodeSpec CODE_SPEC>
inline AminoAcid
_translateTriplet(TOrd const & c1,
TOrd const & c2,
TOrd const & c3,
GeneticCode<CODE_SPEC> const & )
{
return (( c1 > 3 ) || ( c2 > 3 ) || ( c3 > 3 ) )
? 'X'
: <API key><
GeneticCode<CODE_SPEC> >::VALUE[c1][c2][c3];
}
// Function _translateString()
template <typename TOutString, typename TInString, GeneticCodeSpec CODE_SPEC>
inline void
_translateString(TOutString & target,
TInString const & source,
GeneticCode<CODE_SPEC> const & )
{
SEQAN_ASSERT_EQ(length(source)/3, length(target));
typedef typename Position<TInString>::Type TPos;
for (TPos i = 0; i+2 < length(source); i+=3)
{
target[i/3] = _translateTriplet(_ord(value(source, i )),
_ord(value(source, i+1)),
_ord(value(source, i+2)),
GeneticCode<CODE_SPEC>());
}
}
template <typename TOutString, typename TSpec, typename TInString, GeneticCodeSpec CODE_SPEC>
inline void
_translateString(Segment<TOutString, TSpec> <API key> target,
TInString const & source,
GeneticCode<CODE_SPEC> const & )
{
SEQAN_ASSERT_EQ(length(source)/3, length(target));
typedef typename Position<TInString>::Type TPos;
for (TPos i = 0; i+2 < length(source); i+=3)
{
target[i/3] = _translateTriplet(_ord(value(source, i )),
_ord(value(source, i+1)),
_ord(value(source, i+2)),
GeneticCode<CODE_SPEC>());
}
}
// Function _translateImplLoop()
// single frame
template <typename TSpec1, typename TSpec2, typename TSpec3, typename TInString,
GeneticCodeSpec CODE_SPEC>
inline void
_translateImplLoop(StringSet<String<AminoAcid, TSpec1>, TSpec2> & target,
unsigned const i,
StringSet<TInString, TSpec3> const & source,
GeneticCode<CODE_SPEC> const & ,
Frames_<1u> const & )
{
typedef GeneticCode<CODE_SPEC> TCode;
_translateString(target[i], source[i], TCode());
}
// with reverse complement
template <typename TSpec1, typename TSpec2, typename TSpec3, typename TInString,
GeneticCodeSpec CODE_SPEC>
inline void
_translateImplLoop(StringSet<String<AminoAcid, TSpec1>, TSpec2> & target,
unsigned const i,
StringSet<TInString, TSpec3> const & source,
GeneticCode<CODE_SPEC> const & ,
Frames_<2u> const & )
{
typedef typename Value<StringSet<TInString, TSpec3> const>::Type TVal;
typedef typename ReverseComplement_<TVal>::Type TRevComp;
typedef GeneticCode<CODE_SPEC> TCode;
if (i % 2)
{
TRevComp revComp(value(source, i/2));
_translateString(target[i], revComp, TCode());
}
else
{
_translateString(target[i], source[i/2], TCode());
}
}
// three frame
template <typename TSpec1, typename TSpec2, typename TSpec3, typename TInString,
GeneticCodeSpec CODE_SPEC>
inline void
_translateImplLoop(StringSet<String<AminoAcid, TSpec1>, TSpec2> & target,
unsigned const i,
StringSet<TInString, TSpec3> const & source,
GeneticCode<CODE_SPEC> const & ,
Frames_<3u> const & )
{
typedef GeneticCode<CODE_SPEC> TCode;
_translateString(target[i], suffix(source[i/3], i % 3), TCode());
}
// six frame
template <typename TSpec1, typename TSpec2, typename TSpec3, typename TInString,
GeneticCodeSpec CODE_SPEC>
inline void
_translateImplLoop(StringSet<String<AminoAcid, TSpec1>, TSpec2> & target,
unsigned const i,
StringSet<TInString, TSpec3> const & source,
GeneticCode<CODE_SPEC> const & ,
Frames_<6u> const & )
{
typedef typename Prefix<
typename Value<
StringSet<TInString, TSpec3> const>::Type>::Type TVal;
typedef typename ReverseComplement_<TVal>::Type TRevComp;
typedef GeneticCode<CODE_SPEC> TCode;
if ((i % 6) > 2)
{
TRevComp revComp(prefix(value(source, i/6),
length(value(source,i/6)) - (i % 3)));
_translateString(target[i], revComp, TCode());
}
else
{
_translateString(target[i], suffix(source[i/6], i % 3), TCode());
}
}
// Function <API key>()
template <typename TSource, typename TTarget, uint8_t frames,
GeneticCodeSpec CODE_SPEC>
inline void
<API key>(TTarget & target,
TSource const & source,
GeneticCode<CODE_SPEC> const & ,
Frames_<frames> const & ,
Parallel const & )
{
SEQAN_OMP_PRAGMA(parallel for schedule(dynamic))
for (int64_t i = 0; i < static_cast<int64_t>(length(target)); ++i)
_translateImplLoop(target, i, source, GeneticCode<CODE_SPEC>(),
Frames_<frames>());
}
template <typename TSource, typename TTarget, uint8_t frames,
GeneticCodeSpec CODE_SPEC>
inline void
<API key>(TTarget & target,
TSource const & source,
GeneticCode<CODE_SPEC> const & ,
Frames_<frames> const & ,
Serial const & )
{
typedef typename Size<TTarget>::Type TPos;
for (TPos i = 0; i < length(target); ++i)
_translateImplLoop(target, i, source, GeneticCode<CODE_SPEC>(),
Frames_<frames>());
}
// Function _translateImpl()
// general case
template <typename TSpec1, typename TSpec2, typename TSpec3, typename TInString,
typename TParallelism, GeneticCodeSpec CODE_SPEC, unsigned char n>
inline void
_translateImpl(StringSet<String<AminoAcid, TSpec1>, TSpec2> & target,
StringSet<TInString, TSpec3> const & source,
GeneticCode<CODE_SPEC> const & ,
Frames_<n> const & ,
TParallelism const & )
{
typedef typename Position<StringSet<TInString, TSpec3> >::Type TPos;
resize(target, length(source) * n, Exact());
for (TPos i = 0; i < length(target); ++i)
{
// current dnastring's length / 3 (3DNA -> 1 AA)
TPos len = length(source[i/n]) / 3;
// shorten for shifted frames
if (( n > 2 ) && ( length(source[i/n]) % 3 ) < ( i%3 ))
--len;
resize(target[i], len, Exact());
}
<API key>(target, source, GeneticCode<CODE_SPEC>(),
Frames_<n>(),
TParallelism());
}
// ConcatDirect specialization
template <typename TSpec1, typename TSpec3, typename TInString,
typename TParallelism, GeneticCodeSpec CODE_SPEC, unsigned char n>
inline void
_translateImpl(StringSet<String<AminoAcid,
TSpec1>, Owner<ConcatDirect<> > > & target,
StringSet<TInString, TSpec3> const & source,
GeneticCode<CODE_SPEC> const & ,
Frames_<n> const & ,
TParallelism const & )
{
typedef typename Position<StringSet<TInString, TSpec3> >::Type TPos;
resize(target.limits, length(source) * n + 1, Exact());
target.limits[0] = 0;
for (TPos i = 0; i+1 < length(target.limits); ++i)
{
// current dnastring's length / 3 (3DNA -> 1 AA)
TPos len = length(source[i/n]) / 3;
// shorten for shifted frames
if (( n > 2 ) && ( length(source[i/n]) % 3 ) < ( i%3 ))
--len;
target.limits[i+1] = target.limits[i] + len;
}
resize(target.concat, back(target.limits), Exact());
<API key>(target, source, GeneticCode<CODE_SPEC>(),
Frames_<n>(),
TParallelism());
}
// Function _translateInputWrap()
// stringset to stringset
template <typename TSpec1, typename TSpec2, typename TSpec3, typename TInString,
typename TParallelism, GeneticCodeSpec CODE_SPEC, unsigned char n>
inline void
_translateInputWrap(StringSet<String<AminoAcid, TSpec1>, TSpec2> & target,
StringSet<TInString, TSpec3> const & source,
GeneticCode<CODE_SPEC> const & ,
Frames_<n> const & ,
TParallelism const & )
{
_translateImpl(target, source, GeneticCode<CODE_SPEC>(), Frames_<n>(),
TParallelism());
}
// single string to stringset conversion
template <typename TSpec1, typename TSpec2, typename TInString,
typename TParallelism, GeneticCodeSpec CODE_SPEC, unsigned char n>
inline void
_translateInputWrap(StringSet<String<AminoAcid, TSpec1>, TSpec2> & target,
TInString const & source,
GeneticCode<CODE_SPEC> const & ,
Frames_<n> const & ,
TParallelism const & )
{
StringSet<TInString, Dependent<> > set;
appendValue(set, source);
_translateImpl(target, set, GeneticCode<CODE_SPEC>(), Frames_<n>(),
TParallelism());
}
//bail out because multiple frames don't fit in one string
template <typename TSpec1, typename TInString, typename TParallelism,
GeneticCodeSpec CODE_SPEC, unsigned char n>
inline void
_translateInputWrap(String<AminoAcid, TSpec1> & ,
TInString const & ,
GeneticCode<CODE_SPEC> const & ,
Frames_<n> const & ,
TParallelism const & )
{
SEQAN_FAIL("Implementation error, multiple frames selected, but only a "
"singe target string.");
}
// single string to single string conversion
template <typename TSpec1, typename TInString, typename TParallelism,
GeneticCodeSpec CODE_SPEC>
inline void
_translateInputWrap(String<AminoAcid, TSpec1> & target,
TInString const & source,
GeneticCode<CODE_SPEC> const & ,
Frames_<1> const & ,
TParallelism const & )
{
resize(target, length(source)/3, Exact());
_translateString(target, source, GeneticCode<CODE_SPEC>());
}
// Function translate()
/*!
* @fn translate
* @headerfile <seqan/translation.h>
* @brief translate sequences of Dna or Rna into amino acid alphabet, optionally with frames
* @signature int translate(target, source[, frames][, geneticCode][, TParallelism])
* @signature int translate(target, source[, frames][, geneticCodeSpec][, TParallelism])
*
* @param[out] target The amino acid sequence(s). @link StringSet @endlink of @link AminoAcid @endlink
* or @link String @endlink of @link AminoAcid @endlink if source is a single string
* and frames is <tt>SINGLE_FRAME</tt>.
* @param[in] source Source sequences @link String @endlink or @link StringSet @endlink.
* If the value type is not Dna, Dna5, Rna, Rna5 then it is converted
* to Dna5.
* @param[in] frame The @link TranslationFrames @endlink, defaults to SINGLE_FRAME.
* @param[in] geneticCode The @link GeneticCode @endlink to use, defaults
* to GeneticCode<CANONICAL>
* (use to specify GeneticCode at compile-time)
* @param[in] geneticCodeSpec The @link GeneticCodeSpec @endlink to use
* (use to specify GenetiCode at run-time)
* @param[in] TParallelism Whether to use SMP or not, see @link ParallelismTags @endlink .
*
* @return int 0 on success, and -1 on incompatible parameters (e.g. multiple frames but target type not StringSet).
*
* If OpenMP is supported by platform and TParallelism is not specified as
* "Serial", translation will be parallelized. The only exception is when doing
* single-frame translation of a single string -- which is never parallelized.
*
* The translation process is fastest when using <API key> for
* both input and output StringSets and when not having to convert the alphabet
* of the source, i.e. feeding AminoAcid-Strings, not CharStrings (although
* the latter is possible).
*
* Please note that specifying the GeneticCode at compile time avoids having
* unrequired conversion tables in memory. The implementation profits slightly
* from having <API key> defined.
* @section Example
*
* @code{.cpp}
* StringSet<Dna5String> dnaSeqs;
*
* // do something that fills up dnaSeqs, e.g. read from file or assign
*
* StringSet<String<AminoAcid>, Owner<ConcatDirect<> > > aaSeqs;
*
* translate(aaSeqs, dnaSeqs, SIX_FRAME);
*
* // do something with the aaSeqs
* @endcode
*
* @see TranslationFrames
* @see GeneticCode
*/
template <typename TTarget, typename TSource, typename TParallelism,
GeneticCodeSpec CODE_SPEC>
inline void
translate(TTarget & target,
TSource const & source,
TranslationFrames const frames,
GeneticCode<CODE_SPEC> const & ,
TParallelism const & )
{
typedef GeneticCode<CODE_SPEC> TCode;
switch (frames)
{
case SINGLE_FRAME:
return _translateInputWrap(target, source, TCode(), Frames_<1>(),
TParallelism());
case <API key>:
return _translateInputWrap(target, source, TCode(), Frames_<2>(),
TParallelism());
case WITH_FRAME_SHIFTS:
return _translateInputWrap(target, source, TCode(), Frames_<3>(),
TParallelism());
case SIX_FRAME:
return _translateInputWrap(target, source, TCode(), Frames_<6>(),
TParallelism());
}
}
template <typename TTarget, typename TSource, GeneticCodeSpec CODE_SPEC>
inline void
translate(TTarget & target,
TSource const & source,
TranslationFrames const frames,
GeneticCode<CODE_SPEC> const & )
{
return translate(target, source, frames, GeneticCode<CODE_SPEC>(),
Parallel());
}
template <typename TTarget, typename TSource, GeneticCodeSpec CODE_SPEC>
inline void
translate(TTarget & target,
TSource const & source,
GeneticCode<CODE_SPEC> const & )
{
return translate(target, source, SINGLE_FRAME,
GeneticCode<CODE_SPEC>(), Parallel());
}
template <typename TTarget, typename TSource>
inline void
translate(TTarget & target,
TSource const & source,
TranslationFrames const frames)
{
return translate(target, source, frames, GeneticCode<>(), Parallel());
}
template <typename TTarget, typename TSource>
inline void
translate(TTarget & target,
TSource const & source)
{
return translate(target, source, SINGLE_FRAME,
GeneticCode<>(), Parallel());
}
template <typename TTarget, typename TSource, typename TParallelism>
inline void
translate(TTarget & target,
TSource const & source,
TranslationFrames const frames,
TParallelism const & )
{
return translate(target, source, frames, GeneticCode<>(), TParallelism());
}
// Function translate() with run-time spec selection
template <typename TTarget, typename TSource, typename TParallelism,
GeneticCodeSpec currentSpec, typename TRestList>
inline void
_translate(TTarget & ,
TSource const & ,
TranslationFrames const ,
GeneticCodeSpec const & ,
TagList<GeneticCode<currentSpec>, TRestList> const & ,
TParallelism const & ,
True const & )
{
SEQAN_FAIL("Invalid genetic code translation table selected.\n");
}
// forward declare because of double-recursion
template <typename TTarget, typename TSource, typename TParallelism,
GeneticCodeSpec currentSpec, typename TRestList>
inline void
_translate(TTarget & target,
TSource const & source,
TranslationFrames const frames,
GeneticCodeSpec const & geneticCodeSpec,
TagList<GeneticCode<currentSpec>, TRestList> const & ,
TParallelism const & );
template <typename TTarget, typename TSource, typename TParallelism,
GeneticCodeSpec currentSpec, typename TRestList>
inline void
_translate(TTarget & target,
TSource const & source,
TranslationFrames const frames,
GeneticCodeSpec const & geneticCodeSpec,
TagList<GeneticCode<currentSpec>, TRestList> const & ,
TParallelism const & ,
False const & )
{
return _translate(target, source, frames, geneticCodeSpec, TRestList(),
TParallelism());
}
template <typename TTarget, typename TSource, typename TParallelism,
GeneticCodeSpec currentSpec, typename TRestList>
inline void
_translate(TTarget & target,
TSource const & source,
TranslationFrames const frames,
GeneticCodeSpec const & geneticCodeSpec,
TagList<GeneticCode<currentSpec>, TRestList> const & ,
TParallelism const & )
{
typedef TagList<GeneticCode<currentSpec>, TRestList> TTagList;
if (geneticCodeSpec == currentSpec)
return translate(target, source, frames, GeneticCode<currentSpec>(),
TParallelism());
return _translate(target, source, frames, geneticCodeSpec,
TTagList(), TParallelism(),
typename IsSameType<TRestList, void>::Type());
}
template <typename TTarget, typename TSource, typename TParallelism>
inline void
translate(TTarget & target,
TSource const & source,
TranslationFrames const frames,
GeneticCodeSpec const & geneticCodeSpec,
TParallelism const & )
{
return _translate(target, source, frames, geneticCodeSpec, GeneticCodes_(),
TParallelism());
}
// convenience
template <typename TTarget, typename TSource>
inline void
translate(TTarget & target,
TSource const & source,
TranslationFrames const frames,
GeneticCodeSpec const & geneticCode)
{
return translate(target, source, frames, geneticCode, Parallel());
}
}
#endif // <API key> |
layout: none
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http:
<channel>
<title>{{ page.title }} | {{ site.name }}</title>
<description>{{ site.description }}</description>
<link>{{ site.url }}</link>
<atom:link href="{{ page.baseurl }}" rel="self" type="application/rss+xml" />
{% for post in page.posts limit:10 %}
<item>
<title>{{ post.title }}</title>
<description>{{ post.content | xml_escape }}</description>
<pubDate>{{ post.date | date: "%a, %d %b %Y %H:%M:%S %z" }}</pubDate>
<link>{{ site.url }}{{ post.url }}</link>
<guid isPermaLink="true">{{ site.url }}{{ post.url }}</guid>
</item>
{% endfor %}
</channel>
</rss> |
<!DOCTYPE html>
{% load i18n %}
{% load static from staticfiles %}
{% load url from future %}
<html>
<head>
<meta charset="utf-8">
<title>Bakery – Cookiecutter Index</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{# TODO: only in debug build #}
{% if debug %}
<link rel="stylesheet/less" type="text/css" href="{% static 'less/vendor/bootstrap.less' %}" />
<link rel="stylesheet/less" type="text/css" href="{% static 'less/bakery.less' %}" />
{% else %}
<link rel="stylesheet" type="text/css" href="{% static 'css/vendor/bootstrap.min.css' %}" />
<link rel="stylesheet" type="text/css" href="{% static 'css/bakery.min.css' %}" />
{% endif %}
</head>
<body data-spy="scroll" data-target="#bakery_navbar">
<div id="wrap">
<div class="container">
<div class="page-header">
<nav role="navigation" class="navbar navbar-inverse navbar-fixed-top" id="bakery_navbar">
<div class="container">
<div class="navbar-header">
<button data-target=".navbar-collapse" data-toggle="collapse" class="navbar-toggle" type="button">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">
<h2 class="long shoutout">Bakery – where cookies are made!</h2>
<h2 class="short shoutout">Bakery!</h2>
<img src="{% static 'img/logo.svg' %}" height="80" class="img">
</a>
</div>
<div class="collapse navbar-collapse" id="bakery_navbar_nav">
<ul class="nav navbar-nav">
{% block header_nav %}{% endblock header_nav %}
</ul>
<form class="navbar-form navbar-left" role="search" action="/" method="GET">
<div class="form-group">
<input name="q" type="text" class="form-control" placeholder="{% trans "Search" %}">
</div>
<button type="submit" class="btn btn-primary">{% trans "Search" %}</button>
</form>
<ul class="nav navbar-nav navbar-right">
<li>
<a class="btn btn-default color2b" id="github-login" href="{% url 'cookies:add' %}"
title="Add your Cookie!">
Add your Cookie!
</a>
</li>
{% if request.user.is_authenticated %}
<span class="lead">Hey {{ request.user.get_display_name }}! <a href="{% url "auth:logout" %}">Logout!</a></span>
{% else %}
<li>
<a class="btn btn-default color2a" id="github-login" href="{% url 'social:begin' 'github' %}"
title="Sign in with Github">
Login with Github!
</a>
</li>
{% endif %}
</ul>
</div>
</div>
</nav>
</div>
{% block content %}{% endblock content %}
<nav class="navbar navbar-inverse navbar-fixed-bottom" role="navigation">
<div class="container">
<ul class="nav navbar-nav">
<li><a href="
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a href="https://github.com/muffins-on-dope/bakery">Fork on GitHub</a></li>
<li><a href="http://djangodash.com/">Created during the djangodash 2013</a></li>
</ul>
</div>
</nav>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="{% static 'js/vendor/jquery.min.js' %}" type="application/javascript"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="{% static 'js/vendor/bootstrap.min.js' %}" type="application/javascript"></script>
<script src="{% static 'js/vendor/less.min.js' %}"></script>
</body>
</html> |
#!/bin/bash
# No printf parameters
# Simple BASH script to run and time a series of GAMS jobs to compare the run
# time of binary vs clustered unit commitment both with and without capacity
# expansion decisions
# To actually submit the job use:
# qsub SCRIPT_NAME
# Version History
# Ver Date Time Who What
# 1 2011-10-08 04:20 bpalmintier Adapted from pbs_time1.sh v4
# 2 2011-10-08 21:00 bpalmintier Implemented use of scratch space
# IMPORTANT: The lines beginning #PBS set various queuing parameters, they are not simple comments
# name of submitted job, also name of output file unless specified
# The default job name is the name of this script, so here we surpress the job naming so
# we get unique names for all of our jobs
##PBS -N matlab_pbs
# Ask for all 1 node with 8 processors. this may or may not give
# exclusive access to a machine, but typically the queueing system will
# assign the 8 core machines first
# By requiring 20GB we ensure we get one of the machines with 24GB (or maybe a 12 core unit)
#PBS -l nodes=1:ppn=8,mem=20gb
# This option merges any error messages into output file
#PBS -j oe
# Select the queue based on maximum run times. options are:
# short 2hr
# medium 8hr
# long 24hr
# xlong 48hr, extendable to 168hr using -l walltime= option below
#PBS -q long
# And up the run time to the maximum of a full week (168 hrs)
##PBS -l walltime=168:00:00
echo "Node list:"
cat $PBS_NODEFILE
echo "Disk usage:"
df -h
#Set things up to load modules
source /etc/profile.d/modules.sh
#Load recent version of GAMS
module load gams/23.6.3
#Set path to gams in environment variable so MATLAB can read it
GAMS=`which gams`
export GAMS
#And load CPLEX
module load cplex
#Establish a working directory in scratch
#Will give error if it already exists, but script continues anyway
mkdir /scratch/b_p
#Clean anything out of our scratch folder (Assumes exclusive machine usage) |
<?php
// WARNING
// WARNING, Changes made to this file will be clobbered
// WARNING
// WARNING, Please make changes on poeditor instead of here
?>
subject: (Erinnerung) {if:transfer.files>1}Dateien stehen{else}Datei steht{endif} zum Download bereit
subject: (Erinnerung) {transfer.subject}
{alternative:plain}
Sehr geehrte Damen und Herren,
dies ist eine Erinnerung, dass die {if:transfer.files>1}folgenden Dateien{else}folgende Datei{endif} von {transfer.user_email} auf {cfg:site_name} hochgeladen {if:transfer.files>1}wurden{else}wurde{endif} und Ihnen die Erlaubnis zum herunterladen der Inhalte dieser {if:transfer.files>1}Dateien{else}Datei{endif} erteilt wurde:
{if:transfer.files>1}{each:transfer.files as file}
- {file.path} ({size:file.size})
{endeach}{else}
{transfer.files.first().path} ({size:transfer.files.first().size})
{endif}
Download-Link: {recipient.download_link}
Die Transaktion wird bis zum {date:transfer.expires} bestehen bleiben, nach dieser Zeit {if:transfer.files>1}werden die Dateien{else}wird die Datei{endif} automatisch gelöscht.
{if:transfer.message || transfer.subject}
Persönliche Nachricht von {transfer.user_email}: {transfer.subject}
{transfer.message}
{endif}
Mit freundlichen Grüßen,
{cfg:site_name}
{alternative:html}
<p>
Sehr geehrte Damen und Herren,
</p>
<p>
dies ist eine Erinnerung, dass die {if:transfer.files>1}folgenden Dateien{else}folgende Datei{endif} von <a href="mailto:{transfer.user_email}">{transfer.user_email}</a> auf <a href="{cfg:site_url}">{cfg:site_name}</a> hochgeladen {if:transfer.files>1}wurden{else}wurde{endif} und Ihnen die Erlaubnis zum herunterladen der Inhalte dieser {if:transfer.files>1}Dateien{else}Datei{endif} erteilt wurde.
</p>
<table rules="rows">
<thead>
<tr>
<th colspan="2">Transaktionsdetails</th>
</tr>
</thead>
<tbody>
<tr>
<td>Datei{if:transfer.files>1}en{endif}</td>
<td>
{if:transfer.files>1}
<ul>
{each:transfer.files as file}
<li>{file.path} ({size:file.size})</li>
{endeach}
</ul>
{else}
{transfer.files.first().path} ({size:transfer.files.first().size})
{endif}
</td>
</tr>
{if:transfer.files>1}
<tr>
<td>Dateiübertragungsgröße</td>
<td>{size:transfer.size}</td>
</tr>
{endif}
<tr>
<td>Gültigkeitsdatums</td>
<td>{date:transfer.expires}</td>
</tr>
<tr>
<td>Download-Link</td>
<td><a href="{recipient.download_link}">{recipient.download_link}</a></td>
</tr>
</tbody>
</table>
{if:transfer.message}
<p>
Persönliche Nachricht von {transfer.user_email}:
</p>
<p class="message">
{transfer.message}
</p>
{endif}
<p>
Mit freundlichen Grüßen,<br />
{cfg:site_name}
</p> |
module.exports = function init<TwitterConsumerkey>(config, db, app, passport) {
if (!config.auth.twitter) {
return null;
}
var twitterStrategy = require('passport-twitter').Strategy;
passport.use(new twitterStrategy(
config.auth.twitter,
function(token, tokenSecret, profile, done) {
profile.cid = profile.id;
// Get other profile info.
db.users.findOne({ cid: profile.cid }, function(err, found) {
if (err) {
throw err;
}
if (found) {
profile.username = found.username;
profile.email = found.email || '';
profile.kills = found.kills;
profile.deaths = found.deaths;
profile.shots = found.shots;
profile.client = found.client;
return done(null, profile);
} else {
// Create new user.
// Check if Twitter username is taken.
db.users.findOne({ username: profile.username }, function(err, _found) {
if (err) {
throw err;
}
profile.email = ''; // Twitter does not keep emails.
profile.kills = 0;
profile.deaths = 0;
profile.shots = 0;
profile.client = config.clientCodes.twitter;
profile.username = _found ? '' : profile.username; // If username is already taken, let the user decide on one later.
new db.user({
cid: profile.cid,
email: profile.email,
username: profile.username,
client: profile.client,
kills: profile.kills,
deaths: profile.deaths,
shots: profile.shots
}).save(function(err, newUser) {
if (err) {
throw err;
}
return done(null, newUser);
});
});
}
});
}
));
// Authenticate user on this path.
app.get('/auths/twitter', passport.authenticate('twitter'));
// Redirect user according to return value.
app.get('/auths/twitter/return', passport.authenticate('twitter', { failureRedirect: '/me/login/?error=Authentication Failed' }), function(req, res) {
res.redirect('/auths/twitter/success');
});
// Authentication successful.
app.get('/auths/twitter/success', function(req, res) {
if (req.user) {
if (!req.user.username) { // If they didn't set up their profile, set it up.
res.redirect('/me/profile/finalize');
} else {
res.redirect('/?error=Welcome back ' + req.user.username + '!');
}
} else {
res.redirect('/?error=Login First');
}
});
return null;
}; |
package com.xxmicloxx.znetworklib.codec;
public interface NetworkPacket extends Packet {
public CodecResult readNetwork(PacketReader reader);
public CodecResult writeNetwork(PacketWriter writer);
} |
<dom-module id="shared-style">
<template>
<style>
:root {
--card-border-color: rgba(0, 0, 0, 0.14);
--<API key>: 8px;
--card-max-width: 960px;
--card-min-width: 550px;
--<API key>: 20px;
--card-padding-side: 24px;
--card-sizing: {
margin: 0 auto;
max-width: var(--card-max-width);
min-width: var(--card-min-width);
padding: 0 var(--card-padding-side);
width: calc(100% - 2 * var(--card-padding-side));
};
--<API key>: 24px;
--item-height: 44px;
--primary-text-color: #333;
--<API key>: #757575;
--side-bar-width: 256px;
--<API key>: 101px;
--toolbar-height: 56px;
}
[hidden] {
display: none !important;
}
.card-title {
@apply(--layout-center);
@apply(--layout-horizontal);
-<API key>: 20px;
border-bottom: 1px solid var(--card-border-color);
border-radius: 2px 2px 0 0;
color: var(--primary-text-color);
font-size: 14px;
font-weight: 500;
height: 48px;
}
.centered-message {
align-items: center;
color: #b4b4b4;
display: flex;
flex: 1;
font-size: 14px;
font-weight: 500;
height: 100%;
justify-content: center;
}
.menu-item {
-webkit-user-select: none;
cursor: pointer;
font: inherit;
white-space: nowrap;
}
.website-icon {
-webkit-margin-end: 16px;
background-repeat: no-repeat;
background-size: 16px;
height: 16px;
width: 16px;
}
.website-title {
color: var(--primary-text-color);
overflow: hidden;
text-decoration: none;
text-overflow: ellipsis;
white-space: nowrap;
}
button.icon-button {
height: 36px;
width: 36px;
}
button.icon-button iron-icon {
color: var(--<API key>);
height: 20px;
width: 20px;
}
</style>
</template>
</dom-module> |
# Toggl Button Chrome extension
Add Toggl one-click time tracking to popular web tools.
## Compatible services
- [TeamWeek][2]
- [Pivotal tracker][3]
- [Github][4]
- [Asana][5]
- [Unfuddle][6]
- [Gitlab][7]
- [Trello][8]
- [Worksection][9]
- [Redbooth (old UI)][10]
- [Podio][11]
- [Basecamp][12]
- [JIRA (InCloud)][13]
- [Producteev][14]
- [Bitbucket][15]
- [Sifter][16]
- [Google Docs][17]
- [Redmine][18]
- [YouTrack (InCloud)][19]
- [CapsuleCRM][20]
- [Xero][21]
- [Zendesk][22]
- [Any.do][23]
- [Todoist][24]
- [Trac][25]
- [Wunderlist][26]
- [Toodledo][27]
- [Teamwork.com][28]
- [Google Mail][29]
- [Taiga][30]
- [HabitRPG][31]
- [Axosoft][32]
- [Countersoft Gemini][33]
- [Drupal][34]
- [Esa][35]
- [Help Scout][36]
- [Flow][37]
- [Sprintly][38]
- [Google Calendar][39]
- [TestRail][40]
- [Bugzilla][41]
- [Breeze][42]
- [BamBam][43]
- [GQueue][44]
- [Wrike][45]
- [Assembla][46]
- [Waffle][47]
- [Codeable][48]
- [Eventum][49]
- [VisualStudioOnline (TFS)][50]
## Installing from the Web Store
https://chrome.google.com/webstore/detail/toggl-button/<API key>
## Installing from Source
1. Clone the repository: `git clone git://github.com/toggl/toggl-button`
2. Navigate to `chrome://extensions/` and enable "Developer Mode".
3. Choose "Load unpacked extension..."
4. Open the src directory in the toggl-button directory you just cloned and follow the prompts to install.
## Change log
List of all the changes and added features can be found at http://toggl.github.io/toggl-button
## Using the Button
1. Log in to your [Toggl][1] account and keep yourself logged in (no need to keep the tab open).
2. Go to your [TeamWeek][2], [Pivotal Tracker][3], [Github][4], [Asana][5], [Unfuddle][6], [Gitlab][7],
[Trello][8], [Worksection][9], [Redbooth][10], [Podio][11], [Basecamp][12], [JIRA][13], [Producteev][14],
[Bitbucket][15], [Stifer][16], [Google Docs][17], [Redmine][18], [YouTrack][19], [CapsuleCRM][20],
[Xero][21], [Zendesk][22], [Any.do][23], [Todoist][24], [Trac][25], [Wunderlist][26], [Toodledo][27], [Teamwork.com][28], [Google Mail][29], [Taiga][30], [HabitRPG][31], [Axosoft][32], [Countersoft Gemini][33], [Drupal][34], [Esa][35], [Help Scout][36], [Flow][37], [Sprintly][38], [Google Calendar][39], [TestRail][40], [Bugzilla][41], [Breeze][42], [BamBam][43], [GQueue][44], [Wrike][45], [Assembla][46], [Waffle][47], [Codeable][48], [Eventum][49], [VisualStudioOnline][50] account and start your Toggl timer there.
Or start entry from the extension icon menu
3. To edit the running time entry
- Edit entry details from the post start popup that is shown right after you click the "Start timer" button
- Edit entry details from the extesnion icon menu by clicking the running duration
4. To stop the current running timer:
- Press the button again
- Stop the entry from the extension icon menu
- Start another time entry inside your account.
- Go to Toggl to stop or edit your time entry.
## Custom domains
If you use a setup, where one of the supported services is on a custom domain you can customize the extension to fit your needs. Here is a step by step guide on how to [add custom domain][98] to the extension.
## Contributing
Want to contribute? Great! Just fork the project, make your changes and open a [Pull Request][99]
Don't know how to start? Just check out the [user requested services][97] that have not yet been implemented, pick one and start hacking.
[1]: https:
[2]: https://teamweek.com/
[3]: https:
[4]: https://github.com/
[5]: http://asana.com/
[6]: http://unfuddle.com/
[7]: https://gitlab.com/
[8]: https://trello.com/
[9]: http://worksection.com/
[10]: https://redbooth.com/
[11]: https://podio.com/
[12]: https://basecamp.com/
[13]: https:
[14]: https:
[15]: https:
[16]: https:
[17]: https://docs.google.com/
[18]: http:
[19]: http:
[20]: http:
[21]: https:
[22]: https:
[23]: http:
[24]: https://todoist.com/
[25]: http://trac.edgewall.org/
[26]: https:
[27]: https:
[28]: https:
[29]: https://mail.google.com
[30]: https://taiga.io/
[31]: https://habitrpg.com
[32]: https:
[33]: https:
[34]: https:
[35]: https://esa.io
[36]: http:
[37]: http://getflow.com/
[38]: https://sprint.ly
[39]: https:
[40]: https://testrail.com
[41]: https://bugzilla.mozilla.org/
[42]: http:
[43]: https:
[44]: https:
[45]: https:
[46]: https:
[47]: https://waffle.io/
[48]: https:
[49]: https://launchpad.net/eventum
[50]: http:
[97]: https://github.com/toggl/toggl-button/wiki/<API key>
[98]: https://github.com/toggl/toggl-button/wiki/<API key>
[99]: https://github.com/toggl/toggl-button/pulls |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace xwalk
{
class TwoinoneTest
{
private TabletMonitor _monitor;
TwoinoneTest(TabletMonitor monitor)
{
_monitor = monitor;
_monitor.TabletModeDelegate = onTabletModeChanged;
}
void run()
{
// Fudge mainloop
int tick = 0;
while (true)
{
Thread.Sleep(500);
Console.Write(".");
tick++;
if (tick % 10 == 0)
{
Console.WriteLine("");
Console.WriteLine("Tablet mode " + _monitor.IsTablet);
}
}
}
void runEmulator(Emulator emulator)
{
// Fudge mainloop
int tick = 0;
while (true)
{
Thread.Sleep(500);
Console.Write(".");
tick++;
if (tick % 10 == 0)
{
Console.WriteLine("");
emulator.IsTablet = !_monitor.IsTablet;
}
}
}
private void onTabletModeChanged(bool isTablet)
{
Console.WriteLine("onTabletModeChanged: " + isTablet);
}
static void Main(string[] args)
{
Emulator emulator = new Emulator();
TabletMonitor monitor = <API key>.createMonitor(emulator);
TwoinoneTest test = new TwoinoneTest(monitor);
if (args.Length > 0 && args[0] == "emulator")
{
test.runEmulator(emulator);
}
else
{
test.run();
}
}
}
}
/*
}
static void run()
{
Emulator emulator = new Emulator();
TabletMonitor monitor = new TabletMonitor(emulator);
monitor.TabletModeDelegate = onTabletModeChanged;
monitor.start();
Console.WriteLine("Main: " + monitor.IsTablet);
}
static void runEmulator()
{
Emulator emulator = new Emulator();
TabletMonitor monitor = new TabletMonitor(emulator);
monitor.TabletModeDelegate = onTabletModeChanged;
monitor.start();
Console.WriteLine("Main: " + monitor.IsTablet);
}
}
}
*/ |
<?php defined('SYSPATH') OR die('No direct script access.');
abstract class Stats_Widget extends Kohana_Stats_Widget {} |
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
'Courses\Module' => __DIR__ . '/Module.php',
'Courses\Controller\IndexController' => __DIR__ . '/src/Courses/Controller/IndexController.php',
'Courses\Controller\CoureurController' => __DIR__ . '/src/Courses/Controller/CoureurController.php',
'Courses\Controller\CourseController' => __DIR__ . '/src/Courses/Controller/CourseController.php',
'CoursesTest\Framework\TestCase' => __DIR__ . '/tests/Courses/Framework/TestCase.php',
'CoursesTest\SampleTest' => __DIR__ . '/tests/Courses/SampleTest.php',
); |
/* This file contains the functions for converting C expressions
to different data types. The only entry point is `convert'.
Every language front end must have a `convert' function
but what kind of conversions it does will depend on the language. */
/* !kawai! */
#include "../gcc/config.h"
#include "../gcc/system.h"
#include "../gcc/tree.h"
#include "../gcc/flags.h"
#include "cp-tree.h"
#include "../gcc/convert.h"
#include "../gcc/toplev.h"
#include "decl.h"
/* end of !kawai! */
static tree <API key> PARAMS ((tree, tree, int));
static tree <API key> PARAMS ((tree, tree));
static tree build_up_reference PARAMS ((tree, tree, int, tree));
static void warn_ref_binding PARAMS ((tree, tree, tree));
/* Change of width--truncation and extension of integers or reals--
is represented with NOP_EXPR. Proper functioning of many things
assumes that no other conversions can be NOP_EXPRs.
Conversion between integer and pointer is represented with CONVERT_EXPR.
Converting integer to real uses FLOAT_EXPR
and real to integer uses FIX_TRUNC_EXPR.
Here is a list of all the functions that assume that widening and
narrowing is always done with a NOP_EXPR:
In convert.c, convert_to_integer.
In c-typeck.c, <API key> (boolean ops),
and <API key>.
In expr.c: expand_expr, for operands of a MULT_EXPR.
In fold-const.c: fold.
In tree.c: get_narrower and get_unwidened.
C++: in <API key>, converting between pointers may involve
adjusting them by a delta stored within the class definition. */
/* Subroutines of `convert'. */
/* if converting pointer to pointer
if dealing with classes, check for derived->base or vice versa
else if dealing with method pointers, delegate
else convert blindly
else if converting class, pass off to <API key>
else try C-style pointer conversion. If FORCE is true then allow
conversions via virtual bases (these are permitted by reinterpret_cast,
but not static_cast). */
static tree
<API key> (type, expr, force)
tree type, expr;
int force;
{
register tree intype = TREE_TYPE (expr);
register enum tree_code form;
tree rval;
if (IS_AGGR_TYPE (intype))
{
intype = complete_type (intype);
if (!COMPLETE_TYPE_P (intype))
{
error ("can't convert from incomplete type `%T' to `%T'",
intype, type);
return error_mark_node;
}
rval = <API key> (type, expr, 1);
if (rval)
{
if (rval == error_mark_node)
error ("conversion of `%E' from `%T' to `%T' is ambiguous",
expr, intype, type);
return rval;
}
}
/* Handle anachronistic conversions from (::*)() to cv void* or (*)(). */
if (TREE_CODE (type) == POINTER_TYPE
&& (TREE_CODE (TREE_TYPE (type)) == FUNCTION_TYPE
|| VOID_TYPE_P (TREE_TYPE (type))))
{
/* Allow an implicit this pointer for pointer to member
functions. */
if (TYPE_PTRMEMFUNC_P (intype))
{
tree fntype = TREE_TYPE (<API key> (intype));
tree decl = maybe_dummy_object (<API key> (fntype), 0);
expr = build (OFFSET_REF, fntype, decl, expr);
}
if (TREE_CODE (expr) == OFFSET_REF
&& TREE_CODE (TREE_TYPE (expr)) == METHOD_TYPE)
expr = resolve_offset_ref (expr);
if (TREE_CODE (TREE_TYPE (expr)) == METHOD_TYPE)
expr = build_addr_func (expr);
if (TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE)
{
if (TREE_CODE (TREE_TYPE (TREE_TYPE (expr))) == METHOD_TYPE)
if (pedantic || warn_pmf2ptr)
pedwarn ("converting from `%T' to `%T'", TREE_TYPE (expr),
type);
return build1 (NOP_EXPR, type, expr);
}
intype = TREE_TYPE (expr);
}
form = TREE_CODE (intype);
if (POINTER_TYPE_P (intype))
{
intype = TYPE_MAIN_VARIANT (intype);
if (TYPE_MAIN_VARIANT (type) != intype
&& TREE_CODE (type) == POINTER_TYPE
&& TREE_CODE (TREE_TYPE (type)) == RECORD_TYPE
&& IS_AGGR_TYPE (TREE_TYPE (type))
&& IS_AGGR_TYPE (TREE_TYPE (intype))
&& TREE_CODE (TREE_TYPE (intype)) == RECORD_TYPE)
{
enum tree_code code = PLUS_EXPR;
tree binfo;
/* Try derived to base conversion. */
binfo = lookup_base (TREE_TYPE (intype), TREE_TYPE (type),
ba_check, NULL);
if (!binfo)
{
/* Try base to derived conversion. */
binfo = lookup_base (TREE_TYPE (type), TREE_TYPE (intype),
ba_check, NULL);
code = MINUS_EXPR;
}
if (binfo == error_mark_node)
return error_mark_node;
if (binfo)
{
expr = build_base_path (code, expr, binfo, 0);
/* Add any qualifier conversions. */
if (!same_type_p (TREE_TYPE (TREE_TYPE (expr)),
TREE_TYPE (type)))
{
expr = build1 (NOP_EXPR, type, expr);
TREE_CONSTANT (expr) =
TREE_CONSTANT (TREE_OPERAND (expr, 0));
}
return expr;
}
}
if (TYPE_PTRMEM_P (type) && TYPE_PTRMEM_P (intype))
{
tree b1;
tree b2;
tree binfo;
enum tree_code code = PLUS_EXPR;
base_kind bk;
b1 = <API key> (TREE_TYPE (type));
b2 = <API key> (TREE_TYPE (intype));
binfo = lookup_base (b1, b2, ba_check, &bk);
if (!binfo)
{
binfo = lookup_base (b2, b1, ba_check, &bk);
code = MINUS_EXPR;
}
if (binfo == error_mark_node)
return error_mark_node;
if (bk == bk_via_virtual)
{
if (force)
warning ("pointer to member cast from `%T' to `%T' is via virtual base",
TREE_TYPE (intype), TREE_TYPE (type));
else
{
error ("pointer to member cast from `%T' to `%T' is via virtual base",
TREE_TYPE (intype), TREE_TYPE (type));
return error_mark_node;
}
/* This is a reinterpret cast, whose result is unspecified.
We choose to do nothing. */
return build1 (NOP_EXPR, type, expr);
}
if (TREE_CODE (expr) == PTRMEM_CST)
expr = <API key> (expr);
if (binfo)
expr = size_binop (code, convert (sizetype, expr),
BINFO_OFFSET (binfo));
}
else if (TYPE_PTRMEMFUNC_P (type))
{
error ("cannot convert `%E' from type `%T' to type `%T'",
expr, intype, type);
return error_mark_node;
}
rval = build1 (NOP_EXPR, type, expr);
TREE_CONSTANT (rval) = TREE_CONSTANT (expr);
return rval;
}
else if (TYPE_PTRMEMFUNC_P (type) && TYPE_PTRMEMFUNC_P (intype))
return build_ptrmemfunc (<API key> (type), expr, 0);
else if (TYPE_PTRMEMFUNC_P (intype))
{
error ("cannot convert `%E' from type `%T' to type `%T'",
expr, intype, type);
return error_mark_node;
}
my_friendly_assert (form != OFFSET_TYPE, 186);
if (integer_zerop (expr))
{
if (TYPE_PTRMEMFUNC_P (type))
return build_ptrmemfunc (<API key> (type), expr, 0);
if (TYPE_PTRMEM_P (type))
/* A NULL pointer-to-member is represented by -1, not by
zero. */
expr = build_int_2 (-1, -1);
else
expr = build_int_2 (0, 0);
TREE_TYPE (expr) = type;
/* Fix up the representation of -1 if appropriate. */
force_fit_type (expr, 0);
return expr;
}
if (INTEGRAL_CODE_P (form))
{
if (TYPE_PRECISION (intype) == POINTER_SIZE)
return build1 (CONVERT_EXPR, type, expr);
expr = cp_convert (type_for_size (POINTER_SIZE, 0), expr);
/* Modes may be different but sizes should be the same. */
if (GET_MODE_SIZE (TYPE_MODE (TREE_TYPE (expr)))
!= GET_MODE_SIZE (TYPE_MODE (type)))
/* There is supposed to be some integral type
that is the same width as a pointer. */
abort ();
return convert_to_pointer (type, expr);
}
if (type_unknown_p (expr))
return instantiate_type (type, expr, tf_error | tf_warning);
error ("cannot convert `%E' from type `%T' to type `%T'",
expr, intype, type);
return error_mark_node;
}
/* Like convert, except permit conversions to take place which
are not normally allowed due to access restrictions
(such as conversion from sub-type to private super-type). */
static tree
<API key> (type, expr)
tree type, expr;
{
register tree intype = TREE_TYPE (expr);
register enum tree_code form = TREE_CODE (intype);
if (form == POINTER_TYPE)
{
intype = TYPE_MAIN_VARIANT (intype);
if (TYPE_MAIN_VARIANT (type) != intype
&& TREE_CODE (TREE_TYPE (type)) == RECORD_TYPE
&& IS_AGGR_TYPE (TREE_TYPE (type))
&& IS_AGGR_TYPE (TREE_TYPE (intype))
&& TREE_CODE (TREE_TYPE (intype)) == RECORD_TYPE)
{
enum tree_code code = PLUS_EXPR;
tree binfo;
binfo = lookup_base (TREE_TYPE (intype), TREE_TYPE (type),
ba_ignore, NULL);
if (!binfo)
{
binfo = lookup_base (TREE_TYPE (type), TREE_TYPE (intype),
ba_ignore, NULL);
code = MINUS_EXPR;
}
if (binfo == error_mark_node)
return error_mark_node;
if (binfo)
{
expr = build_base_path (code, expr, binfo, 0);
/* Add any qualifier conversions. */
if (!same_type_p (TREE_TYPE (TREE_TYPE (expr)),
TREE_TYPE (type)))
{
expr = build1 (NOP_EXPR, type, expr);
TREE_CONSTANT (expr) =
TREE_CONSTANT (TREE_OPERAND (expr, 0));
}
return expr;
}
}
}
return <API key> (type, expr, 1);
}
/* We are passing something to a function which requires a reference.
The type we are interested in is in TYPE. The initial
value we have to begin with is in ARG.
FLAGS controls how we manage access checking.
DIRECT_BIND in FLAGS controls how any temporaries are generated.
If DIRECT_BIND is set, DECL is the reference we're binding to. */
static tree
build_up_reference (type, arg, flags, decl)
tree type, arg, decl;
int flags;
{
tree rval;
tree argtype = TREE_TYPE (arg);
tree target_type = TREE_TYPE (type);
tree stmt_expr = NULL_TREE;
my_friendly_assert (TREE_CODE (type) == REFERENCE_TYPE, 187);
if ((flags & DIRECT_BIND) && ! real_lvalue_p (arg))
{
/* Create a new temporary variable. We can't just use a TARGET_EXPR
here because it needs to live as long as DECL. */
tree targ = arg;
arg = build_decl (VAR_DECL, NULL_TREE, argtype);
DECL_ARTIFICIAL (arg) = 1;
TREE_USED (arg) = 1;
TREE_STATIC (arg) = TREE_STATIC (decl);
if (TREE_STATIC (decl))
{
/* Namespace-scope or local static; give it a mangled name. */
tree name = <API key> (decl);
DECL_NAME (arg) = name;
<API key> (arg, name);
arg = pushdecl_top_level (arg);
}
else
{
/* Automatic; make sure we handle the cleanup properly. */
<API key> (argtype);
arg = pushdecl (arg);
}
/* Process the initializer for the declaration. */
DECL_INITIAL (arg) = targ;
cp_finish_decl (arg, targ, NULL_TREE,
<API key>|DIRECT_BIND);
}
else if (!(flags & DIRECT_BIND) && ! lvalue_p (arg))
return get_target_expr (arg);
/* If we had a way to wrap this up, and say, if we ever needed its
address, transform all occurrences of the register, into a memory
reference we could win better. */
rval = build_unary_op (ADDR_EXPR, arg, 1);
if (rval == error_mark_node)
return error_mark_node;
if ((flags & LOOKUP_PROTECT)
&& TYPE_MAIN_VARIANT (argtype) != TYPE_MAIN_VARIANT (target_type)
&& IS_AGGR_TYPE (argtype)
&& IS_AGGR_TYPE (target_type))
{
/* We go through lookup_base for the access control. */
tree binfo = lookup_base (argtype, target_type, ba_check, NULL);
if (binfo == error_mark_node)
return error_mark_node;
if (binfo == NULL_TREE)
return error_not_base_type (target_type, argtype);
rval = build_base_path (PLUS_EXPR, rval, binfo, 1);
}
else
rval
= <API key> (build_pointer_type (target_type), rval);
rval = build1 (NOP_EXPR, type, rval);
TREE_CONSTANT (rval) = TREE_CONSTANT (TREE_OPERAND (rval, 0));
/* If we created and initialized a new temporary variable, add the
representation of that initialization to the RVAL. */
if (stmt_expr)
rval = build (COMPOUND_EXPR, TREE_TYPE (rval), stmt_expr, rval);
/* And return the result. */
return rval;
}
/* Subroutine of <API key>. REFTYPE is the target reference type.
INTYPE is the original rvalue type and DECL is an optional _DECL node
for diagnostics.
[dcl.init.ref] says that if an rvalue is used to
initialize a reference, then the reference must be to a
non-volatile const type. */
static void
warn_ref_binding (reftype, intype, decl)
tree reftype, intype, decl;
{
tree ttl = TREE_TYPE (reftype);
if (!<API key> (ttl))
{
const char *msg;
if (CP_TYPE_VOLATILE_P (ttl) && decl)
msg = "initialization of volatile reference type `%#T' from rvalue of type `%T'";
else if (CP_TYPE_VOLATILE_P (ttl))
msg = "conversion to volatile reference type `%#T' from rvalue of type `%T'";
else if (decl)
msg = "initialization of non-const reference type `%#T' from rvalue of type `%T'";
else
msg = "conversion to non-const reference type `%#T' from rvalue of type `%T'";
pedwarn (msg, reftype, intype);
}
}
/* For C++: Only need to do one-level references, but cannot
get tripped up on signed/unsigned differences.
DECL is either NULL_TREE or the _DECL node for a reference that is being
initialized. It can be error_mark_node if we don't know the _DECL but
we know it's an initialization. */
tree
<API key> (reftype, expr, convtype, flags, decl)
tree reftype, expr;
int convtype, flags;
tree decl;
{
register tree type = TYPE_MAIN_VARIANT (TREE_TYPE (reftype));
register tree intype = TREE_TYPE (expr);
tree rval = NULL_TREE;
tree rval_as_conversion = NULL_TREE;
int i;
if (TREE_CODE (type) == FUNCTION_TYPE && intype == unknown_type_node)
{
expr = instantiate_type (type, expr,
(flags & LOOKUP_COMPLAIN)
? tf_error | tf_warning : tf_none);
if (expr == error_mark_node)
return error_mark_node;
intype = TREE_TYPE (expr);
}
my_friendly_assert (TREE_CODE (intype) != REFERENCE_TYPE, 364);
intype = TYPE_MAIN_VARIANT (intype);
i = comp_target_types (type, intype, 0);
if (i <= 0 && (convtype & CONV_IMPLICIT) && IS_AGGR_TYPE (intype)
&& ! (flags & <API key>))
{
/* Look for a user-defined conversion to lvalue that we can use. */
rval_as_conversion
= <API key> (reftype, expr, 1);
if (rval_as_conversion && rval_as_conversion != error_mark_node
&& real_lvalue_p (rval_as_conversion))
{
expr = rval_as_conversion;
rval_as_conversion = NULL_TREE;
intype = type;
i = 1;
}
}
if (((convtype & CONV_STATIC) && i == -1)
|| ((convtype & CONV_IMPLICIT) && i == 1))
{
if (flags & LOOKUP_COMPLAIN)
{
tree ttl = TREE_TYPE (reftype);
tree ttr = lvalue_type (expr);
if (! real_lvalue_p (expr))
warn_ref_binding (reftype, intype, decl);
if (! (convtype & CONV_CONST)
&& !<API key> (ttl, ttr))
pedwarn ("conversion from `%T' to `%T' discards qualifiers",
ttr, reftype);
}
return build_up_reference (reftype, expr, flags, decl);
}
else if ((convtype & CONV_REINTERPRET) && lvalue_p (expr))
{
/* B* bp; A& ar = (A&)bp; is valid, but it's probably not what they
meant. */
if (TREE_CODE (intype) == POINTER_TYPE
&& (comptypes (TREE_TYPE (intype), type,
COMPARE_BASE | COMPARE_RELAXED )))
warning ("casting `%T' to `%T' does not dereference pointer",
intype, reftype);
rval = build_unary_op (ADDR_EXPR, expr, 0);
if (rval != error_mark_node)
rval = convert_force (build_pointer_type (TREE_TYPE (reftype)),
rval, 0);
if (rval != error_mark_node)
rval = build1 (NOP_EXPR, reftype, rval);
}
else
{
rval = <API key> (NULL_TREE, type, expr, flags,
"converting", 0, 0);
if (rval == NULL_TREE || rval == error_mark_node)
return rval;
warn_ref_binding (reftype, intype, decl);
rval = build_up_reference (reftype, rval, flags, decl);
}
if (rval)
{
/* If we found a way to convert earlier, then use it. */
return rval;
}
my_friendly_assert (TREE_CODE (intype) != OFFSET_TYPE, 189);
if (flags & LOOKUP_COMPLAIN)
error ("cannot convert type `%T' to type `%T'", intype, reftype);
if (flags & <API key>)
return NULL_TREE;
return error_mark_node;
}
/* We are using a reference VAL for its value. Bash that reference all the
way down to its lowest form. */
tree
<API key> (val)
tree val;
{
tree type = TREE_TYPE (val);
if (TREE_CODE (type) == OFFSET_TYPE)
type = TREE_TYPE (type);
if (TREE_CODE (type) == REFERENCE_TYPE)
return build_indirect_ref (val, NULL);
return val;
}
/* Implicitly convert the lvalue EXPR to another lvalue of type TOTYPE,
preserving cv-qualification. */
tree
convert_lvalue (totype, expr)
tree totype, expr;
{
totype = <API key> (totype, TYPE_QUALS (TREE_TYPE (expr)));
totype = <API key> (totype);
expr = <API key> (totype, expr, CONV_IMPLICIT, LOOKUP_NORMAL,
NULL_TREE);
return <API key> (expr);
}
/* C++ conversions, preference to static cast conversions. */
tree
cp_convert (type, expr)
tree type, expr;
{
return ocp_convert (type, expr, CONV_OLD_CONVERT, LOOKUP_NORMAL);
}
/* Conversion...
FLAGS indicates how we should behave. */
tree
ocp_convert (type, expr, convtype, flags)
tree type, expr;
int convtype, flags;
{
register tree e = expr;
register enum tree_code code = TREE_CODE (type);
if (e == error_mark_node
|| TREE_TYPE (e) == error_mark_node)
return error_mark_node;
complete_type (type);
complete_type (TREE_TYPE (expr));
e = decl_constant_value (e);
if (IS_AGGR_TYPE (type) && (convtype & CONV_FORCE_TEMP)
/* Some internal structures (vtable_entry_type, sigtbl_ptr_type)
don't go through finish_struct, so they don't have the synthesized
constructors. So don't force a temporary. */
&& <API key> (type))
/* We need a new temporary; don't take this shortcut. */;
else if (TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (TREE_TYPE (e)))
{
if (same_type_p (type, TREE_TYPE (e)))
/* The call to fold will not always remove the NOP_EXPR as
might be expected, since if one of the types is a typedef;
the comparsion in fold is just equality of pointers, not a
call to comptypes. We don't call fold in this case because
that can result in infinite recursion; fold will call
convert, which will call ocp_convert, etc. */
return e;
/* For complex data types, we need to perform componentwise
conversion. */
else if (TREE_CODE (type) == COMPLEX_TYPE)
return fold (convert_to_complex (type, e));
else
return fold (build1 (NOP_EXPR, type, e));
}
if (code == VOID_TYPE && (convtype & CONV_STATIC))
{
e = convert_to_void (e, /*implicit=*/NULL);
return e;
}
/* Just convert to the type of the member. */
if (code == OFFSET_TYPE)
{
type = TREE_TYPE (type);
code = TREE_CODE (type);
}
if (TREE_CODE (e) == OFFSET_REF)
e = resolve_offset_ref (e);
if (INTEGRAL_CODE_P (code))
{
tree intype = TREE_TYPE (e);
/* enum = enum, enum = int, enum = float, (enum)pointer are all
errors. */
if (TREE_CODE (type) == ENUMERAL_TYPE
&& ((ARITHMETIC_TYPE_P (intype) && ! (convtype & CONV_STATIC))
|| (TREE_CODE (intype) == POINTER_TYPE)))
{
pedwarn ("conversion from `%#T' to `%#T'", intype, type);
if (<API key>)
return error_mark_node;
}
if (IS_AGGR_TYPE (intype))
{
tree rval;
rval = <API key> (type, e, 1);
if (rval)
return rval;
if (flags & LOOKUP_COMPLAIN)
error ("`%#T' used where a `%T' was expected", intype, type);
if (flags & <API key>)
return NULL_TREE;
return error_mark_node;
}
if (code == BOOLEAN_TYPE)
{
tree fn = NULL_TREE;
/* Common Ada/Pascal programmer's mistake. We always warn
about this since it is so bad. */
if (TREE_CODE (expr) == FUNCTION_DECL)
fn = expr;
else if (TREE_CODE (expr) == ADDR_EXPR
&& TREE_CODE (TREE_OPERAND (expr, 0)) == FUNCTION_DECL)
fn = TREE_OPERAND (expr, 0);
if (fn && !DECL_WEAK (fn))
warning ("the address of `%D', will always be `true'", fn);
return <API key> (e);
}
return fold (convert_to_integer (type, e));
}
if (code == POINTER_TYPE || code == REFERENCE_TYPE
|| TYPE_PTRMEMFUNC_P (type))
return fold (<API key> (type, e, 0));
if (code == VECTOR_TYPE)
return fold (convert_to_vector (type, e));
if (code == REAL_TYPE || code == COMPLEX_TYPE)
{
if (IS_AGGR_TYPE (TREE_TYPE (e)))
{
tree rval;
rval = <API key> (type, e, 1);
if (rval)
return rval;
else
if (flags & LOOKUP_COMPLAIN)
error ("`%#T' used where a floating point value was expected",
TREE_TYPE (e));
}
if (code == REAL_TYPE)
return fold (convert_to_real (type, e));
else if (code == COMPLEX_TYPE)
return fold (convert_to_complex (type, e));
}
/* New C++ semantics: since assignment is now based on
memberwise copying, if the rhs type is derived from the
lhs type, then we may still do a conversion. */
if (IS_AGGR_TYPE_CODE (code))
{
tree dtype = TREE_TYPE (e);
tree ctor = NULL_TREE;
dtype = TYPE_MAIN_VARIANT (dtype);
/* Conversion between aggregate types. New C++ semantics allow
objects of derived type to be cast to objects of base type.
Old semantics only allowed this between pointers.
There may be some ambiguity between using a constructor
vs. using a type conversion operator when both apply. */
ctor = e;
if (<API key> (NULL_TREE, type))
return error_mark_node;
if ((flags & <API key>)
&& ! (IS_AGGR_TYPE (dtype) && DERIVED_FROM_P (type, dtype)))
/* For copy-initialization, first we create a temp of the proper type
with a user-defined conversion sequence, then we direct-initialize
the target with the temp (see [dcl.init]). */
ctor = <API key> (type, ctor, flags);
else
ctor = build_method_call (NULL_TREE,
<API key>,
build_tree_list (NULL_TREE, ctor),
TYPE_BINFO (type), flags);
if (ctor)
return build_cplus_new (type, ctor);
}
/* If TYPE or TREE_TYPE (E) is not on the permanent_obstack,
then it won't be hashed and hence compare as not equal,
even when it is. */
if (code == ARRAY_TYPE
&& TREE_TYPE (TREE_TYPE (e)) == TREE_TYPE (type)
&& index_type_equal (TYPE_DOMAIN (TREE_TYPE (e)), TYPE_DOMAIN (type)))
return e;
if (flags & LOOKUP_COMPLAIN)
error ("conversion from `%T' to non-scalar type `%T' requested",
TREE_TYPE (expr), type);
if (flags & <API key>)
return NULL_TREE;
return error_mark_node;
}
/* When an expression is used in a void context, its value is discarded and
no lvalue-rvalue and similar conversions happen [expr.static.cast/4,
stmt.expr/1, expr.comma/1]. This permits dereferencing an incomplete type
in a void context. The C++ standard does not define what an `access' to an
object is, but there is reason to beleive that it is the lvalue to rvalue
conversion -- if it were not, `*&*p = 1' would violate [expr]/4 in that it
accesses `*p' not to calculate the value to be stored. But, dcl.type.cv/8
indicates that volatile semantics should be the same between C and C++
where ever possible. C leaves it implementation defined as to what
constitutes an access to a volatile. So, we interpret `*vp' as a read of
the volatile object `vp' points to, unless that is an incomplete type. For
volatile references we do not do this interpretation, because that would
make it impossible to ignore the reference return value from functions. We
issue warnings in the confusing cases.
IMPLICIT is tells us the context of an implicit void conversion. */
tree
convert_to_void (expr, implicit)
tree expr;
const char *implicit;
{
if (expr == error_mark_node
|| TREE_TYPE (expr) == error_mark_node)
return error_mark_node;
if (!TREE_TYPE (expr))
return expr;
if (VOID_TYPE_P (TREE_TYPE (expr)))
return expr;
switch (TREE_CODE (expr))
{
case COND_EXPR:
{
/* The two parts of a cond expr might be separate lvalues. */
tree op1 = TREE_OPERAND (expr,1);
tree op2 = TREE_OPERAND (expr,2);
tree new_op1 = convert_to_void (op1, implicit);
tree new_op2 = convert_to_void (op2, implicit);
expr = build (COND_EXPR, TREE_TYPE (new_op1),
TREE_OPERAND (expr, 0), new_op1, new_op2);
break;
}
case COMPOUND_EXPR:
{
/* The second part of a compound expr contains the value. */
tree op1 = TREE_OPERAND (expr,1);
tree new_op1 = convert_to_void (op1, implicit);
if (new_op1 != op1)
{
tree t = build (COMPOUND_EXPR, TREE_TYPE (new_op1),
TREE_OPERAND (expr, 0), new_op1);
TREE_SIDE_EFFECTS (t) = TREE_SIDE_EFFECTS (expr);
<API key> (t) = <API key> (expr);
expr = t;
}
break;
}
case NON_LVALUE_EXPR:
case NOP_EXPR:
/* These have already decayed to rvalue. */
break;
case CALL_EXPR: /* we have a special meaning for volatile void fn() */
break;
case INDIRECT_REF:
{
tree type = TREE_TYPE (expr);
int is_reference = TREE_CODE (TREE_TYPE (TREE_OPERAND (expr, 0)))
== REFERENCE_TYPE;
int is_volatile = TYPE_VOLATILE (type);
int is_complete = COMPLETE_TYPE_P (complete_type (type));
if (is_volatile && !is_complete)
warning ("object of incomplete type `%T' will not be accessed in %s",
type, implicit ? implicit : "void context");
else if (is_reference && is_volatile)
warning ("object of type `%T' will not be accessed in %s",
TREE_TYPE (TREE_OPERAND (expr, 0)),
implicit ? implicit : "void context");
if (is_reference || !is_volatile || !is_complete)
expr = TREE_OPERAND (expr, 0);
break;
}
case VAR_DECL:
{
/* External variables might be incomplete. */
tree type = TREE_TYPE (expr);
int is_complete = COMPLETE_TYPE_P (complete_type (type));
if (TYPE_VOLATILE (type) && !is_complete)
warning ("object `%E' of incomplete type `%T' will not be accessed in %s",
expr, type, implicit ? implicit : "void context");
break;
}
case OFFSET_REF:
expr = resolve_offset_ref (expr);
break;
default:;
}
{
tree probe = expr;
if (TREE_CODE (probe) == ADDR_EXPR)
probe = TREE_OPERAND (expr, 0);
if (type_unknown_p (probe))
{
/* [over.over] enumerates the places where we can take the address
of an overloaded function, and this is not one of them. */
pedwarn ("%s cannot resolve address of overloaded function",
implicit ? implicit : "void cast");
}
else if (implicit && probe == expr && is_overloaded_fn (probe))
/* Only warn when there is no &. */
warning ("%s is a reference, not call, to function `%E'",
implicit, expr);
}
if (expr != error_mark_node && !VOID_TYPE_P (TREE_TYPE (expr)))
{
/* FIXME: This is where we should check for expressions with no
effects. At the moment we do that in both <API key>
and expand_expr_stmt -- inconsistently too. For the moment
leave implicit void conversions unadorned so that expand_expr_stmt
has a chance of detecting some of the cases. */
if (!implicit)
expr = build1 (CONVERT_EXPR, void_type_node, expr);
}
return expr;
}
/* Create an expression whose value is that of EXPR,
converted to type TYPE. The TREE_TYPE of the value
is always TYPE. This function implements all reasonable
conversions; callers should filter out those that are
not permitted by the language being compiled.
Most of this routine is from <API key>.
The backend cannot call cp_convert (what was convert) because
conversions to/from basetypes may involve memory references
(vbases) and adding or subtracting small values (multiple
inheritance), but it calls convert from the constant folding code
on subtrees of already built trees after it has ripped them apart.
Also, if we ever support range variables, we'll probably also have to
do a little bit more work. */
tree
convert (type, expr)
tree type, expr;
{
tree intype;
if (type == error_mark_node || expr == error_mark_node)
return error_mark_node;
intype = TREE_TYPE (expr);
if (POINTER_TYPE_P (type) && POINTER_TYPE_P (intype))
{
expr = decl_constant_value (expr);
return fold (build1 (NOP_EXPR, type, expr));
}
return ocp_convert (type, expr, CONV_OLD_CONVERT,
LOOKUP_NORMAL|<API key>);
}
/* Like cp_convert, except permit conversions to take place which
are not normally allowed due to access restrictions
(such as conversion from sub-type to private super-type). */
tree
convert_force (type, expr, convtype)
tree type;
tree expr;
int convtype;
{
register tree e = expr;
register enum tree_code code = TREE_CODE (type);
if (code == REFERENCE_TYPE)
return fold (<API key> (type, e, CONV_C_CAST, LOOKUP_COMPLAIN,
NULL_TREE));
else if (TREE_CODE (TREE_TYPE (e)) == REFERENCE_TYPE)
e = <API key> (e);
if (code == POINTER_TYPE)
return fold (<API key> (type, e));
/* From typeck.c <API key> */
if (((TREE_CODE (TREE_TYPE (e)) == POINTER_TYPE && TREE_CODE (e) == ADDR_EXPR
&& TREE_CODE (TREE_TYPE (e)) == POINTER_TYPE
&& TREE_CODE (TREE_TYPE (TREE_TYPE (e))) == METHOD_TYPE)
|| integer_zerop (e)
|| TYPE_PTRMEMFUNC_P (TREE_TYPE (e)))
&& TYPE_PTRMEMFUNC_P (type))
{
/* compatible pointer to member functions. */
return build_ptrmemfunc (<API key> (type), e, 1);
}
return ocp_convert (type, e, CONV_C_CAST|convtype, LOOKUP_NORMAL);
}
/* Convert an aggregate EXPR to type XTYPE. If a conversion
exists, return the attempted conversion. This may
return ERROR_MARK_NODE if the conversion is not
allowed (references private members, etc).
If no conversion exists, NULL_TREE is returned.
If (FOR_SURE & 1) is non-zero, then we allow this type conversion
to take place immediately. Otherwise, we build a SAVE_EXPR
which can be evaluated if the results are ever needed.
Changes to this functions should be mirrored in user_harshness.
FIXME: Ambiguity checking is wrong. Should choose one by the implicit
object parameter, or by the second standard conversion sequence if
that doesn't do it. This will probably wait for an overloading rewrite.
(jason 8/9/95) */
tree
<API key> (xtype, expr, for_sure)
tree xtype, expr;
int for_sure;
{
/* C++: check to see if we can convert this aggregate type
into the required type. */
return <API key>
(xtype, expr, for_sure ? LOOKUP_NORMAL : 0);
}
/* Convert the given EXPR to one of a group of types suitable for use in an
expression. DESIRES is a combination of various WANT_* flags (q.v.)
which indicates which types are suitable. If COMPLAIN is 1, complain
about ambiguity; otherwise, the caller will deal with it. */
tree
<API key> (desires, expr, complain)
int desires;
tree expr;
int complain;
{
tree basetype = TREE_TYPE (expr);
tree conv = NULL_TREE;
tree winner = NULL_TREE;
if (expr == null_node
&& (desires & WANT_INT)
&& !(desires & WANT_NULL))
warning ("converting NULL to non-pointer type");
if (TREE_CODE (expr) == OFFSET_REF)
expr = resolve_offset_ref (expr);
expr = <API key> (expr);
basetype = TREE_TYPE (expr);
if (basetype == error_mark_node)
return error_mark_node;
if (! IS_AGGR_TYPE (basetype))
switch (TREE_CODE (basetype))
{
case INTEGER_TYPE:
if ((desires & WANT_NULL) && null_ptr_cst_p (expr))
return expr;
/* else fall through... */
case BOOLEAN_TYPE:
return (desires & WANT_INT) ? expr : NULL_TREE;
case ENUMERAL_TYPE:
return (desires & WANT_ENUM) ? expr : NULL_TREE;
case REAL_TYPE:
return (desires & WANT_FLOAT) ? expr : NULL_TREE;
case POINTER_TYPE:
return (desires & WANT_POINTER) ? expr : NULL_TREE;
case FUNCTION_TYPE:
case ARRAY_TYPE:
return (desires & WANT_POINTER) ? default_conversion (expr)
: NULL_TREE;
default:
return NULL_TREE;
}
/* The code for conversions from class type is currently only used for
delete expressions. Other expressions are handled by build_new_op. */
if (! TYPE_HAS_CONVERSION (basetype))
return NULL_TREE;
for (conv = lookup_conversions (basetype); conv; conv = TREE_CHAIN (conv))
{
int win = 0;
tree candidate;
tree cand = TREE_VALUE (conv);
if (winner && winner == cand)
continue;
candidate = TREE_TYPE (TREE_TYPE (cand));
if (TREE_CODE (candidate) == REFERENCE_TYPE)
candidate = TREE_TYPE (candidate);
switch (TREE_CODE (candidate))
{
case BOOLEAN_TYPE:
case INTEGER_TYPE:
win = (desires & WANT_INT); break;
case ENUMERAL_TYPE:
win = (desires & WANT_ENUM); break;
case REAL_TYPE:
win = (desires & WANT_FLOAT); break;
case POINTER_TYPE:
win = (desires & WANT_POINTER); break;
default:
break;
}
if (win)
{
if (winner)
{
if (complain)
{
error ("ambiguous default type conversion from `%T'",
basetype);
error (" candidate conversions include `%D' and `%D'",
winner, cand);
}
return error_mark_node;
}
else
winner = cand;
}
}
if (winner)
{
tree type = TREE_TYPE (TREE_TYPE (winner));
if (TREE_CODE (type) == REFERENCE_TYPE)
type = TREE_TYPE (type);
return <API key> (type, expr, LOOKUP_NORMAL);
}
return NULL_TREE;
}
/* Implements integral promotion (4.1) and float->double promotion. */
tree
type_promotes_to (type)
tree type;
{
int type_quals;
if (type == error_mark_node)
return error_mark_node;
type_quals = cp_type_quals (type);
type = TYPE_MAIN_VARIANT (type);
/* bool always promotes to int (not unsigned), even if it's the same
size. */
if (type == boolean_type_node)
type = integer_type_node;
/* Normally convert enums to int, but convert wide enums to something
wider. */
else if (TREE_CODE (type) == ENUMERAL_TYPE
|| type == wchar_type_node)
{
int precision = MAX (TYPE_PRECISION (type),
TYPE_PRECISION (integer_type_node));
tree totype = type_for_size (precision, 0);
if (TREE_UNSIGNED (type)
&& ! int_fits_type_p (TYPE_MAX_VALUE (type), totype))
type = type_for_size (precision, 1);
else
type = totype;
}
else if (<API key> (type))
{
/* Retain unsignedness if really not getting bigger. */
if (TREE_UNSIGNED (type)
&& TYPE_PRECISION (type) == TYPE_PRECISION (integer_type_node))
type = unsigned_type_node;
else
type = integer_type_node;
}
else if (type == float_type_node)
type = double_type_node;
return <API key> (type, type_quals);
}
/* The routines below this point are carefully written to conform to
the standard. They use the same terminology, and follow the rules
closely. Although they are used only in pt.c at the moment, they
should presumably be used everywhere in the future. */
/* Attempt to perform qualification conversions on EXPR to convert it
to TYPE. Return the resulting expression, or error_mark_node if
the conversion was impossible. */
tree
<API key> (type, expr)
tree type;
tree expr;
{
if (TREE_CODE (type) == POINTER_TYPE
&& TREE_CODE (TREE_TYPE (expr)) == POINTER_TYPE
&& comp_ptr_ttypes (TREE_TYPE (type), TREE_TYPE (TREE_TYPE (expr))))
return build1 (NOP_EXPR, type, expr);
else
return error_mark_node;
} |
<?php
$get = Yii::$app->request->get();
?>
<aside class="aside-block col-lg-3 col-md-3 hidden-sm hidden-xs">
<form action="<?=\yii\helpers\Url::to('/tours/index/')?>" method="get">
<div class="<API key>">
<select class="selectpicker common-button common-button--thin" name="category">
<?php foreach($categories as $category): ?>
<option value="<?=$category->id?>" <?=@$get['category'] == $category->id ? 'selected="selected"':''?>><?=$category->title_ru?></option>
<?php endforeach; ?>
</select>
<select class="selectpicker common-button common-button--thin" name="city">
<?php foreach($cities as $city): ?>
<option value="<?=$city->id?>" <?=@$get['city'] == $city->id ? 'selected="selected"':''?>><?=$city->title_ru?></option>
<?php endforeach; ?>
</select>
</div> <!--<API key>-->
<div class="<API key>">
<div class="<API key>">
<p>Количество дней</p>
<label>От<input type="text" name="days_min" placeholder="" value="<?=@$get['days_min']?>"></label>
<label>До<input type="text" name="days_max" placeholder="" value="<?=@$get['days_max']?>"></label>
</div>
<div class="<API key>">
<p>Количество человек</p>
<label>От<input type="text" name="people_min" placeholder="" value="<?=@$get['people_min']?>"></label>
<label>До<input type="text" name="people_max" placeholder="" value="<?=@$get['people_max']?>"></label>
</div>
<div class="filter-btn-group <API key>">
<a href="<?=\yii\helpers\Url::to('/tours/')?>" id="clearToursFilter" type="button" class="<API key> btn common-button">Очистить</a>
<button type="submit" class="<API key> btn common-button">Показать</button>
</div>
</div>
</form>
</aside> |
package org.javasimon;
import org.javasimon.callback.Callback;
import org.javasimon.callback.CompositeCallback;
import org.javasimon.utils.SystemDebugCallback;
import java.io.<API key>;
import java.io.FileReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Collection;
/**
* SimonManager is static utility class providing so called "default {@link org.javasimon.Manager}.
* It is possible to create separate Manager, but it cannot be accessed via this convenient
* utility-like class. This option may be useful in Java EE environment when it's required to
* separate Simon trees across different applications. For majority of Java SE applications this
* class is recommended.
* <p/>
* SimonManager also provides configuration initialization via properties. To initialize configuration
* with the configuration file following option can be added to JVM executable:
* <pre>-Djavasimon.config.file=some-path/simon.config.xml</pre>
* To configure the SimonManager via resource that can be found on classpath:
* <pre>-Djavasimon.config.resource=org/javasimon/example/wannabe-config.xml</pre>
*
* @author <a href="mailto:virgo47@gmail.com">Richard "Virgo" Richter</a>
*/
public final class SimonManager {
/** Property name for the Simon configuration file is "javasimon.config.file". */
public static final String <API key> = "javasimon.config.file";
/** Property name for the Simon configuration resource is "javasimon.config.resource". */
public static final String <API key> = "javasimon.config.resource";
private static Manager manager = new SwitchingManager();
/** Calls {@link #init()}. */
static {
System.out.printf("init simonManager \n");
init();
}
/**
* Initializes the configuration facility for the default Simon Manager. Fetches exception
* if configuration resource or file is not found. This method does NOT clear the manager
* itself, only the configuration is reloaded. Method also preserves Callback setup.
*/
static void init() {
Callback <API key> = new SystemDebugCallback();
manager.callback().addCallback(<API key>); // just for reporting warnings, will be removed
try {
manager.configuration().clear();
String fileName = System.getProperty(<API key>);
if (fileName != null) {
try (FileReader fileReader = new FileReader(fileName)) {
manager.configuration().readConfig(fileReader);
}
}
String resourceName = System.getProperty(<API key>);
if (resourceName != null) {
InputStream is = SimonManager.class.getClassLoader().getResourceAsStream(resourceName);
if (is == null) {
throw new <API key>(resourceName);
}
manager.configuration().readConfig(new InputStreamReader(is));
}
} catch (Exception e) {
manager.callback().onManagerWarning("SimonManager initialization error", e);
}
manager.callback().removeCallback(<API key>);
}
private SimonManager() {
throw new AssertionError();
}
/**
* Returns Simon by its name if it exists.
*
* @param name name of the Simon
* @return Simon object
*/
public static Simon getSimon(String name) {
return manager.getSimon(name);
}
/**
* Destroys Simon or replaces it with UnknownSimon if it's necessary to preserve the hierarchy.
*
* @param name name of the Simon
*/
public static void destroySimon(String name) {
manager.destroySimon(name);
}
/**
* Returns existing Counter or creates new if necessary. "Anonymous" Counter can
* be obtained if null name is specified - then it is not added to the Simon hierarchy.
*
* @param name name of the Counter
* @return counter object
*/
public static Counter getCounter(String name) {
return manager.getCounter(name);
}
/**
* Returns existing Stopwatch or creates new if necessary. "Anonymous" Stopwatch can
* be obtained if null name is specified - then it is not added to the Simon hierarchy.
*
* @param name name of the Stopwatch
* @return stopwatch object
*/
public static Stopwatch getStopwatch(String name) {
return manager.getStopwatch(name);
}
/**
* Return existing Meter or create new if necessary.
* "Anonymous " meter will be obtained if null name is specified, then...
*/
public static Meter getMeter(String name)
{
return manager.getMeter(name);
}
/** Enables the Simon Manager. Enabled manager provides real Simons. */
public static void enable() {
manager.enable();
}
/** Disables the Simon Manager. Disabled manager provides null Simons that actually do nothing. */
public static void disable() {
manager.disable();
}
/**
* Returns true if the Simon Manager is enabled.
*
* @return true if the Simon Manager is enabled
*/
public static boolean isEnabled() {
return manager.isEnabled();
}
/**
* Returns root Simon. Type of the Simon is unknown at the start but it can be replaced
* by the real Simon later. Specific get method with root Simon name constant can be used
* in that case.
*
* @return root Simon
*/
public static Simon getRootSimon() {
return manager.getRootSimon();
}
/**
* Returns unmodifiable collection containing names of all existing Simons.
*
* @return collection of all Simon names
* @since 3.1
*/
public static Collection<String> getSimonNames() {
return manager.getSimonNames();
}
/**
* Returns collection containing all existing Simons accepted by specified {@link SimonFilter}.
* If {@code null} pattern is provided all Simons are returned in an unmodifiable Collection.
* Otherwise new collection with matching Simons is returned.
*
* @param simonFilter filter accepting the Simons to result collection
* @return collection of all Simons which pass the filter
* @see SimonPattern to find out more about possible patterns
* @since 3.1
*/
public static Collection<Simon> getSimons(SimonFilter simonFilter) {
return manager.getSimons(simonFilter);
}
/**
* Clears the SimonManager (ignored if manager is disabled). All Simons are lost,
* but configuration is preserved.
*/
public static void clear() {
manager.clear();
}
/**
* Accesses Simon callback.
*
* @return Simon callback
*/
public static CompositeCallback callback() {
return manager.callback();
}
/**
* Accesses configuration of this manager.
*
* @return configuration of this manager
*/
public static <API key> configuration() {
return manager.configuration();
}
/**
* Accesses default Simon Manager which is the switching manager.
*
* @return default Simon Manager
*/
public static Manager manager() {
return manager;
}
/**
* Method propagates message to manager's {@link org.javasimon.callback.Callback}. This allows user to report any
* message if they implement {@link org.javasimon.callback.Callback#onManagerMessage(String)}.
*
* @param message message text
*/
public static void message(String message) {
manager.message(message);
}
/**
* Method propagates warning to manager's {@link org.javasimon.callback.Callback}. This allows user to report any
* warning and/or exception if they implement {@link org.javasimon.callback.Callback#onManagerWarning(String, Exception)}.
*
* @param warning arbitrary warning message
* @param cause exception causing this warning
*/
public static void warning(String warning, Exception cause) {
manager.warning(warning, cause);
}
} |
#ifndef <API key>
#define <API key> 1
#include <stddef.h>
#include <stdbool.h>
typedef struct ringbuf *ringbuf_t;
ringbuf_t ringbuf_init(size_t initsize);
void ringbuf_dispose(ringbuf_t b);
bool ringbuf_empty(ringbuf_t b);
void ringbuf_clear(ringbuf_t b);
size_t ringbuf_count(ringbuf_t b);
size_t ringbuf_get(ringbuf_t b, unsigned char *data, size_t num);
size_t ringbuf_peek(ringbuf_t b, unsigned char *data, size_t num);
void ringbuf_put(ringbuf_t b, unsigned char *data, size_t num);
void ringbuf_dump(ringbuf_t b);
#endif /* <API key> */ |
from django_sprinkler.models import Program, Context
from datetime import datetime
import pytz, logging
from django.conf import settings
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG if settings.DEBUG else logging.INFO)
logger_watering = logging.getLogger("watering")
logger_watering.setLevel(logger.level)
def exec_step(ctxt, step=None):
if ctxt.state == "manual":
logger.info("State is manual, thus not acting")
return
for pstep in ctxt.active_program.steps.all():
if step == pstep:
#Arrancamos el aspersor que ha sido devuelto como activo
pstep.sprinkler.toggle(True)
continue
#apagamos el resto de aspersores
pstep.sprinkler.toggle(False)
def run():
ctxt = Context.objects.get_context()
program = ctxt.active_program
#check state
try:
if ctxt.state == 'manual':
next_step = None
elif ctxt.state in ('automatic', 'running_program'):
next_step = program.has_active_step()
elif ctxt.state == '3min_cicle':
startt = datetime.now(pytz.timezone(settings.TIME_ZONE)) \
if ctxt.start_at is None \
else ctxt.start_at
next_step = program.has_active_step(<API key>=startt, minutes=3)
elif ctxt.state == 'cicle':
startt = datetime.now(pytz.timezone(settings.TIME_ZONE)) \
if ctxt.start_at is None \
else ctxt.start_at
next_step = program.has_active_step(<API key>=startt)
exec_step(ctxt, next_step)
except Program.<API key> as ex:
return |
#include "chrome/utility/importer/ie_importer_win.h"
#include <ole2.h>
#include <intshcut.h>
#include <shlobj.h>
#include <stddef.h>
#include <urlhist.h>
#include <wininet.h>
#include <algorithm>
#include <map>
#include <string>
#include <vector>
#include "base/files/file_enumerator.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/strings/string16.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/<API key>.h"
#include "base/time/time.h"
#include "base/win/registry.h"
#include "base/win/scoped_co_mem.h"
#include "base/win/scoped_comptr.h"
#include "base/win/scoped_handle.h"
#include "base/win/scoped_propvariant.h"
#include "base/win/windows_version.h"
#include "chrome/common/importer/<API key>.h"
#include "chrome/common/importer/<API key>.h"
#include "chrome/common/importer/<API key>.h"
#include "chrome/common/importer/importer_bridge.h"
#include "chrome/common/importer/importer_data_types.h"
#include "chrome/common/importer/importer_url_row.h"
#include "chrome/common/importer/pstore_declarations.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/utility/importer/favicon_reencode.h"
#include "components/autofill/core/common/password_form.h"
#include "ui/base/l10n/l10n_util.h"
#include "url/gurl.h"
#include "url/url_constants.h"
namespace {
// Registry key paths from which we import IE settings.
const base::char16 kSearchScopePath[] =
L"Software\\Microsoft\\Internet Explorer\\SearchScopes";
const base::char16 kIEVersionKey[] =
L"Software\\Microsoft\\Internet Explorer";
const base::char16 kIEToolbarKey[] =
L"Software\\Microsoft\\Internet Explorer\\Toolbar";
// NTFS stream name of favicon image data.
const base::char16 kFaviconStreamName[] = L":favicon:$DATA";
// A struct that hosts the information of AutoComplete data in PStore.
struct AutoCompleteInfo {
base::string16 key;
std::vector<base::string16> data;
bool is_url;
};
// Gets the creation time of the given file or directory.
base::Time GetFileCreationTime(const base::string16& file) {
base::Time creation_time;
base::win::ScopedHandle file_handle(
CreateFile(file.c_str(), GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
NULL, OPEN_EXISTING,
<API key> | <API key>, NULL));
FILETIME creation_filetime;
if (!file_handle.IsValid())
return creation_time;
if (GetFileTime(file_handle.Get(), &creation_filetime, NULL, NULL))
creation_time = base::Time::FromFileTime(creation_filetime);
return creation_time;
}
// Safely read an object of type T from a raw sequence of bytes.
template <typename T>
bool BinaryRead(T* data, size_t offset, const std::vector<uint8_t>& blob) {
if (offset + sizeof(T) > blob.size())
return false;
memcpy(data, &blob[offset], sizeof(T));
return true;
}
// Safely read an ITEMIDLIST from a raw sequence of bytes.
// An ITEMIDLIST is a list of SHITEMIDs, terminated by a SHITEMID with
// .cb = 0. Here, before simply casting &blob[offset] to LPITEMIDLIST,
// we verify that the list structure is not overrunning the boundary of
// the binary blob.
LPCITEMIDLIST <API key>(size_t offset,
size_t idlist_size,
const std::vector<uint8_t>& blob) {
size_t head = 0;
while (true) {
// Use a USHORT instead of SHITEMID to avoid buffer over read.
USHORT id_cb;
if (head >= idlist_size || !BinaryRead(&id_cb, offset + head, blob))
return NULL;
if (id_cb == 0)
break;
head += id_cb;
}
return reinterpret_cast<LPCITEMIDLIST>(&blob[offset]);
}
// Compares the two bookmarks in the order of IE's Favorites menu.
// Returns true if rhs should come later than lhs (lhs < rhs).
struct <API key> {
bool operator()(const <API key>& lhs,
const <API key>& rhs) const {
static const uint32_t kNotSorted = 0xfffffffb; // IE uses this magic value.
base::FilePath lhs_prefix;
base::FilePath rhs_prefix;
for (size_t i = 0; i <= lhs.path.size() && i <= rhs.path.size(); ++i) {
const base::FilePath::StringType lhs_i =
(i < lhs.path.size() ? lhs.path[i] : lhs.title + L".url");
const base::FilePath::StringType rhs_i =
(i < rhs.path.size() ? rhs.path[i] : rhs.title + L".url");
lhs_prefix = lhs_prefix.Append(lhs_i);
rhs_prefix = rhs_prefix.Append(rhs_i);
if (lhs_i == rhs_i)
continue;
// The first path element that differs between the two.
std::map<base::FilePath, uint32_t>::const_iterator lhs_iter =
sort_index_->find(lhs_prefix);
std::map<base::FilePath, uint32_t>::const_iterator rhs_iter =
sort_index_->find(rhs_prefix);
uint32_t lhs_sort_index =
(lhs_iter == sort_index_->end() ? kNotSorted : lhs_iter->second);
uint32_t rhs_sort_index =
(rhs_iter == sort_index_->end() ? kNotSorted : rhs_iter->second);
if (lhs_sort_index != rhs_sort_index)
return lhs_sort_index < rhs_sort_index;
// If they have the same sort order, sort alphabetically.
return lhs_i < rhs_i;
}
return lhs.path.size() < rhs.path.size();
}
const std::map<base::FilePath, uint32_t>* sort_index_;
};
// IE stores the order of the Favorites menu in registry under:
// HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\MenuOrder\Favorites.
// The folder hierarchy of Favorites menu is directly mapped to the key
// hierarchy in the registry.
// If the order of the items in a folder is customized by user, the order is
// recorded in the REG_BINARY value named "Order" of the corresponding key.
// The content of the "Order" value is a raw binary dump of an array of the
// following data structure
// struct {
// uint32_t size; // Note that ITEMIDLIST is variably-sized.
// uint32_t sort_index; // 0 means this is the first item, 1 the second,
// ITEMIDLIST item_id;
// where each item_id should correspond to a favorites link file (*.url) in
// the current folder.
// gcc, in its infinite wisdom, only allows WARN_UNUSED_RESULT for prototypes.
// Clang, to be compatible with gcc, warns if WARN_UNUSED_RESULT is used in a
// non-gcc compatible manner (-Wgcc-compat). So even though gcc isn't used to
// build on Windows, declare some prototypes anyway to satisfy Clang's gcc
// compatibility warnings.
bool <API key>(const Importer* importer,
const std::vector<uint8_t>& blob,
const base::FilePath& path,
std::map<base::FilePath, uint32_t>* sort_index)
WARN_UNUSED_RESULT;
bool <API key>(const Importer* importer,
const std::vector<uint8_t>& blob,
const base::FilePath& path,
std::map<base::FilePath, uint32_t>* sort_index) {
static const int kItemCountOffset = 16;
static const int <API key> = 20;
// Read the number of items.
uint32_t item_count = 0;
if (!BinaryRead(&item_count, kItemCountOffset, blob))
return false;
// Traverse over the items.
size_t base_offset = <API key>;
for (uint32_t i = 0; i < item_count && !importer->cancelled(); ++i) {
static const int kSizeOffset = 0;
static const int kSortIndexOffset = 4;
static const int kItemIDListOffset = 8;
// Read the size (number of bytes) of the current item.
uint32_t item_size = 0;
if (!BinaryRead(&item_size, base_offset + kSizeOffset, blob) ||
base_offset + item_size <= base_offset || // checking overflow
base_offset + item_size > blob.size())
return false;
// Read the sort index of the current item.
uint32_t item_sort_index = 0;
if (!BinaryRead(&item_sort_index, base_offset + kSortIndexOffset, blob))
return false;
// Read the file name from the ITEMIDLIST structure.
LPCITEMIDLIST idlist = <API key>(
base_offset + kItemIDListOffset, item_size - kItemIDListOffset, blob);
TCHAR item_filename[MAX_PATH];
if (!idlist || !SHGetPathFromIDList(idlist, item_filename))
return false;
base::FilePath item_relative_path =
path.Append(base::FilePath(item_filename).BaseName());
// Record the retrieved information and go to the next item.
sort_index->insert(std::make_pair(item_relative_path, item_sort_index));
base_offset += item_size;
}
return true;
}
bool <API key>(
const Importer* importer,
const base::win::RegKey& key,
const base::FilePath& path,
std::map<base::FilePath, uint32_t>* sort_index) WARN_UNUSED_RESULT;
bool <API key>(
const Importer* importer,
const base::win::RegKey& key,
const base::FilePath& path,
std::map<base::FilePath, uint32_t>* sort_index) {
// Parse the order information of the current folder.
DWORD blob_length = 0;
if (key.ReadValue(L"Order", NULL, &blob_length, NULL) == ERROR_SUCCESS) {
std::vector<uint8_t> blob(blob_length);
if (blob_length > 0 &&
key.ReadValue(L"Order", reinterpret_cast<DWORD*>(&blob[0]),
&blob_length, NULL) == ERROR_SUCCESS) {
if (!<API key>(importer, blob, path, sort_index))
return false;
}
}
// Recursively parse subfolders.
for (base::win::RegistryKeyIterator child(key.Handle(), L"");
child.Valid() && !importer->cancelled();
++child) {
base::win::RegKey subkey(key.Handle(), child.Name(), KEY_READ);
if (subkey.Valid()) {
base::FilePath subpath(path.Append(child.Name()));
if (!<API key>(importer, subkey, subpath,
sort_index)) {
return false;
}
}
}
return true;
}
bool <API key>(const Importer* importer,
std::map<base::FilePath, uint32_t>* sort_index)
WARN_UNUSED_RESULT;
bool <API key>(const Importer* importer,
std::map<base::FilePath, uint32_t>* sort_index) {
base::string16 key_path(importer::<API key>());
base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_READ);
if (!key.Valid())
return false;
return <API key>(importer, key, base::FilePath(),
sort_index);
}
// Reads the sort order from registry. If failed, we don't touch the list
// and use the default (alphabetical) order.
void <API key>(
const Importer* importer,
std::vector<<API key>>* bookmarks) {
std::map<base::FilePath, uint32_t> sort_index;
if (!<API key>(importer, &sort_index))
return;
<API key> compare = {&sort_index};
std::sort(bookmarks->begin(), bookmarks->end(), compare);
}
// Reads an internet shortcut (*.url) |file| and returns a COM object
// representing it.
bool <API key>(
const base::string16& file,
base::win::ScopedComPtr<<API key>>* shortcut) {
base::win::ScopedComPtr<<API key>> url_locator;
if (FAILED(url_locator.CreateInstance(<API key>, NULL,
<API key>)))
return false;
base::win::ScopedComPtr<IPersistFile> persist_file;
if (FAILED(persist_file.QueryFrom(url_locator.get())))
return false;
// Loads the Internet Shortcut from persistent storage.
if (FAILED(persist_file->Load(file.c_str(), STGM_READ)))
return false;
std::swap(url_locator, *shortcut);
return true;
}
// Reads the URL stored in the internet shortcut.
GURL <API key>(<API key>* url_locator) {
base::win::ScopedCoMem<wchar_t> url;
// GetURL can return S_FALSE (FAILED(S_FALSE) is false) when url == NULL.
return (FAILED(url_locator->GetURL(&url)) || !url) ?
GURL() : GURL(url.get());
}
// Reads the URL of the favicon of the internet shortcut.
GURL <API key>(<API key>* url_locator) {
base::win::ScopedComPtr<IPropertySetStorage> <API key>;
if (FAILED(<API key>.QueryFrom(url_locator)))
return GURL();
base::win::ScopedComPtr<IPropertyStorage> property_storage;
if (FAILED(<API key>->Open(FMTID_Intshcut, STGM_READ,
property_storage.Receive()))) {
return GURL();
}
PROPSPEC properties[] = {{PRSPEC_PROPID, {PID_IS_ICONFILE}}};
// ReadMultiple takes a non-const array of PROPVARIANTs, but since this code
// only needs an array of size 1: a non-const pointer to |output| is
// equivalent.
base::win::ScopedPropVariant output;
// ReadMultiple can return S_FALSE (FAILED(S_FALSE) is false) when the
// property is not found, in which case output[0].vt is set to VT_EMPTY.
if (FAILED(property_storage->ReadMultiple(1, properties, output.Receive())) ||
output.get().vt != VT_LPWSTR)
return GURL();
return GURL(output.get().pwszVal);
}
// Reads the favicon imaga data in an NTFS alternate data stream. This is where
// IE7 and above store the data.
bool <API key>(const base::string16& file,
std::string* data) {
return base::ReadFileToString(
base::FilePath(file + kFaviconStreamName), data);
}
// Reads the favicon imaga data in the Internet cache. IE6 doesn't hold the data
// explicitly, but it might be found in the cache.
bool <API key>(const GURL& favicon_url, std::string* data) {
std::wstring url_wstring(base::UTF8ToWide(favicon_url.spec()));
DWORD info_size = 0;
<API key>(url_wstring.c_str(), NULL, &info_size, NULL, NULL,
NULL, 0);
if (GetLastError() != <API key>)
return false;
std::vector<char> buf(info_size);
<API key>* cache =
reinterpret_cast<<API key>*>(&buf[0]);
if (!<API key>(url_wstring.c_str(), cache, &info_size, NULL,
NULL, NULL, 0)) {
return false;
}
return base::ReadFileToString(base::FilePath(cache->lpszLocalFileName), data);
}
// Reads the binary image data of favicon of an internet shortcut file |file|.
// |favicon_url| read by <API key> is also needed to
// examine the IE cache.
bool <API key>(const base::string16& file,
const GURL& favicon_url,
std::vector<unsigned char>* data) {
std::string image_data;
if (!<API key>(file, &image_data) &&
!<API key>(favicon_url, &image_data)) {
return false;
}
const unsigned char* ptr =
reinterpret_cast<const unsigned char*>(image_data.c_str());
return importer::ReencodeFavicon(ptr, image_data.size(), data);
}
// Loads favicon image data and registers to |favicon_map|.
void UpdateFaviconMap(
const base::string16& url_file,
const GURL& url,
<API key>* url_locator,
std::map<GURL, favicon_base::FaviconUsageData>* favicon_map) {
GURL favicon_url = <API key>(url_locator);
if (!favicon_url.is_valid())
return;
std::map<GURL, favicon_base::FaviconUsageData>::iterator it =
favicon_map->find(favicon_url);
if (it != favicon_map->end()) {
// Known favicon URL.
it->second.urls.insert(url);
} else {
// New favicon URL. Read the image data and store.
favicon_base::FaviconUsageData usage;
if (<API key>(url_file, favicon_url, &usage.png_data)) {
usage.favicon_url = favicon_url;
usage.urls.insert(url);
favicon_map->insert(std::make_pair(favicon_url, usage));
}
}
}
} // namespace
// static
// {<API key>}
const GUID IEImporter::<API key> = {
0xe161255a, 0x37c3, 0x11d2,
{ 0xbc, 0xaa, 0x00, 0xc0, 0x4f, 0xd9, 0x29, 0xdb }
};
// {<API key>}
const GUID IEImporter::kUnittestGUID = {
0xa79029d6, 0x753e, 0x4e27,
{ 0xb8, 0x7, 0x3d, 0x46, 0xab, 0x15, 0x45, 0xdf }
};
IEImporter::IEImporter() : edge_import_mode_(false) {}
void IEImporter::StartImport(const importer::SourceProfile& source_profile,
uint16_t items,
ImporterBridge* bridge) {
edge_import_mode_ = source_profile.importer_type == importer::TYPE_EDGE;
bridge_ = bridge;
if (edge_import_mode_) {
// When using for Edge imports we only support Favorites.
DCHECK_EQ(items, importer::FAVORITES);
// As coming from untrusted source ensure items is correct.
items = importer::FAVORITES;
}
source_path_ = source_profile.source_path;
bridge_->NotifyStarted();
if ((items & importer::HOME_PAGE) && !cancelled()) {
bridge_->NotifyItemStarted(importer::HOME_PAGE);
ImportHomepage(); // Doesn't have a UI item.
bridge_->NotifyItemEnded(importer::HOME_PAGE);
}
// The order here is important!
if ((items & importer::HISTORY) && !cancelled()) {
bridge_->NotifyItemStarted(importer::HISTORY);
ImportHistory();
bridge_->NotifyItemEnded(importer::HISTORY);
}
if ((items & importer::FAVORITES) && !cancelled()) {
bridge_->NotifyItemStarted(importer::FAVORITES);
ImportFavorites();
bridge_->NotifyItemEnded(importer::FAVORITES);
}
if ((items & importer::SEARCH_ENGINES) && !cancelled()) {
bridge_->NotifyItemStarted(importer::SEARCH_ENGINES);
ImportSearchEngines();
bridge_->NotifyItemEnded(importer::SEARCH_ENGINES);
}
if ((items & importer::PASSWORDS) && !cancelled()) {
bridge_->NotifyItemStarted(importer::PASSWORDS);
// Always import IE6 passwords.
ImportPasswordsIE6();
if (CurrentIEVersion() >= 7)
ImportPasswordsIE7();
bridge_->NotifyItemEnded(importer::PASSWORDS);
}
bridge_->NotifyEnded();
}
IEImporter::~IEImporter() {
}
void IEImporter::ImportFavorites() {
FavoritesInfo info;
if (!GetFavoritesInfo(&info))
return;
BookmarkVector bookmarks;
favicon_base::<API key> favicons;
<API key>(info, &bookmarks, &favicons);
if (!bookmarks.empty() && !cancelled()) {
const base::string16& first_folder_name =
edge_import_mode_
? l10n_util::GetStringUTF16(<API key>)
: l10n_util::GetStringUTF16(<API key>);
bridge_->AddBookmarks(bookmarks, first_folder_name);
}
if (!favicons.empty() && !cancelled())
bridge_->SetFavicons(favicons);
}
void IEImporter::ImportHistory() {
const std::string kSchemes[] = {url::kHttpScheme,
url::kHttpsScheme,
url::kFtpScheme,
url::kFileScheme};
int total_schemes = arraysize(kSchemes);
base::win::ScopedComPtr<IUrlHistoryStg2> url_history_stg2;
if (FAILED(url_history_stg2.CreateInstance(CLSID_CUrlHistory, NULL,
<API key>))) {
return;
}
base::win::ScopedComPtr<IEnumSTATURL> enum_url;
if (SUCCEEDED(url_history_stg2->EnumUrls(enum_url.Receive()))) {
std::vector<ImporterURLRow> rows;
STATURL stat_url;
// IEnumSTATURL::Next() doesn't fill STATURL::dwFlags by default. Need to
// call IEnumSTATURL::SetFilter() with <API key> flag to
// specify how STATURL structure will be filled.
// The first argument of IEnumSTATURL::SetFilter() specifies the URL prefix
// that is used by IEnumSTATURL::Next() for filtering items by URL.
// So need to pass an empty string here to get all history items.
enum_url->SetFilter(L"", <API key>);
while (!cancelled() &&
enum_url->Next(1, &stat_url, NULL) == S_OK) {
base::string16 url_string;
if (stat_url.pwcsUrl) {
url_string = stat_url.pwcsUrl;
CoTaskMemFree(stat_url.pwcsUrl);
}
base::string16 title_string;
if (stat_url.pwcsTitle) {
title_string = stat_url.pwcsTitle;
CoTaskMemFree(stat_url.pwcsTitle);
}
GURL url(url_string);
// Skips the URLs that are invalid or have other schemes.
if (!url.is_valid() ||
(std::find(kSchemes, kSchemes + total_schemes, url.scheme()) ==
kSchemes + total_schemes))
continue;
ImporterURLRow row(url);
row.title = title_string;
row.last_visit = base::Time::FromFileTime(stat_url.ftLastVisited);
if (stat_url.dwFlags == <API key>) {
row.visit_count = 1;
row.hidden = false;
} else {
// dwFlags should only contain the <API key> bit per
// the filter set above.
DCHECK(!stat_url.dwFlags);
row.hidden = true;
}
rows.push_back(row);
}
if (!rows.empty() && !cancelled()) {
bridge_->SetHistoryItems(rows, importer::<API key>);
}
}
}
void IEImporter::ImportPasswordsIE6() {
GUID AutocompleteGUID = <API key>;
if (!source_path_.empty()) {
// We supply a fake GUID for testting.
AutocompleteGUID = kUnittestGUID;
}
// The <API key> function retrieves an interface pointer
// to a storage provider. But this function has no associated import
// library or header file, we must call it using the LoadLibrary()
// and GetProcAddress() functions.
typedef HRESULT (WINAPI *PStoreCreateFunc)(IPStore**, DWORD, DWORD, DWORD);
HMODULE pstorec_dll = LoadLibrary(L"pstorec.dll");
if (!pstorec_dll)
return;
PStoreCreateFunc <API key> =
(PStoreCreateFunc)GetProcAddress(pstorec_dll, "<API key>");
if (!<API key>) {
FreeLibrary(pstorec_dll);
return;
}
base::win::ScopedComPtr<IPStore, &IID_IPStore> pstore;
HRESULT result = <API key>(pstore.Receive(), 0, 0, 0);
if (result != S_OK) {
FreeLibrary(pstorec_dll);
return;
}
std::vector<AutoCompleteInfo> ac_list;
// Enumerates AutoComplete items in the protected database.
base::win::ScopedComPtr<IEnumPStoreItems, &<API key>> item;
result = pstore->EnumItems(0, &AutocompleteGUID,
&AutocompleteGUID, 0, item.Receive());
if (result != PST_E_OK) {
pstore.Release();
FreeLibrary(pstorec_dll);
return;
}
wchar_t* item_name;
while (!cancelled() && SUCCEEDED(item->Next(1, &item_name, 0))) {
DWORD length = 0;
unsigned char* buffer = NULL;
result = pstore->ReadItem(0, &AutocompleteGUID, &AutocompleteGUID,
item_name, &length, &buffer, NULL, 0);
if (SUCCEEDED(result)) {
AutoCompleteInfo ac;
ac.key = item_name;
base::string16 data;
data.insert(0, reinterpret_cast<wchar_t*>(buffer),
length / sizeof(wchar_t));
// The key name is always ended with ":StringData".
const wchar_t kDataSuffix[] = L":StringData";
size_t i = ac.key.rfind(kDataSuffix);
if (i != base::string16::npos && ac.key.substr(i) == kDataSuffix) {
ac.key.erase(i);
ac.is_url = (ac.key.find(L"://") != base::string16::npos);
ac_list.push_back(ac);
ac_list.back().data =
base::SplitString(data, base::string16(1, '\0'),
base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
}
CoTaskMemFree(buffer);
}
CoTaskMemFree(item_name);
}
// Releases them before unload the dll.
item.Release();
pstore.Release();
FreeLibrary(pstorec_dll);
size_t i;
for (i = 0; i < ac_list.size(); i++) {
if (!ac_list[i].is_url || ac_list[i].data.size() < 2)
continue;
GURL url(ac_list[i].key.c_str());
if (!(base::<API key>(url.scheme(), url::kHttpScheme) ||
base::<API key>(url.scheme(), url::kHttpsScheme))) {
continue;
}
autofill::PasswordForm form;
GURL::Replacements rp;
rp.ClearUsername();
rp.ClearPassword();
rp.ClearQuery();
rp.ClearRef();
form.origin = url.ReplaceComponents(rp);
form.username_value = ac_list[i].data[0];
form.password_value = ac_list[i].data[1];
form.signon_realm = url.GetOrigin().spec();
// Goes through the list to find out the username field
// of the web page.
size_t list_it, item_it;
for (list_it = 0; list_it < ac_list.size(); ++list_it) {
if (ac_list[list_it].is_url)
continue;
for (item_it = 0; item_it < ac_list[list_it].data.size(); ++item_it)
if (ac_list[list_it].data[item_it] == form.username_value) {
form.username_element = ac_list[list_it].key;
break;
}
}
bridge_->SetPasswordForm(form);
}
}
void IEImporter::ImportPasswordsIE7() {
base::string16 key_path(importer::GetIE7PasswordsKey());
base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_READ);
base::win::<API key> reg_iterator(HKEY_CURRENT_USER,
key_path.c_str());
importer::<API key> password_info;
while (reg_iterator.Valid() && !cancelled()) {
// Get the size of the encrypted data.
DWORD value_len = 0;
key.ReadValue(reg_iterator.Name(), NULL, &value_len, NULL);
if (value_len) {
// Query the encrypted data.
password_info.encrypted_data.resize(value_len);
if (key.ReadValue(reg_iterator.Name(),
&password_info.encrypted_data.front(),
&value_len, NULL) == ERROR_SUCCESS) {
password_info.url_hash = reg_iterator.Name();
password_info.date_created = base::Time::Now();
bridge_->AddIE7PasswordInfo(password_info);
}
}
++reg_iterator;
}
}
void IEImporter::ImportSearchEngines() {
// On IE, search engines are stored in the registry, under:
// Software\Microsoft\Internet Explorer\SearchScopes
// Each key represents a search engine. The URL value contains the URL and
// the DisplayName the name.
typedef std::map<std::string, base::string16> SearchEnginesMap;
SearchEnginesMap search_engines_map;
for (base::win::RegistryKeyIterator key_iter(HKEY_CURRENT_USER,
kSearchScopePath); key_iter.Valid(); ++key_iter) {
base::string16 sub_key_name = kSearchScopePath;
sub_key_name.append(L"\\").append(key_iter.Name());
base::win::RegKey sub_key(HKEY_CURRENT_USER, sub_key_name.c_str(),
KEY_READ);
base::string16 wide_url;
if ((sub_key.ReadValue(L"URL", &wide_url) != ERROR_SUCCESS) ||
wide_url.empty()) {
VLOG(1) << "No URL for IE search engine at " << key_iter.Name();
continue;
}
// For the name, we try the default value first (as Live Search uses a
// non displayable name in DisplayName, and the readable name under the
// default value).
base::string16 name;
if ((sub_key.ReadValue(NULL, &name) != ERROR_SUCCESS) || name.empty()) {
// Try the displayable name.
if ((sub_key.ReadValue(L"DisplayName", &name) != ERROR_SUCCESS) ||
name.empty()) {
VLOG(1) << "No name for IE search engine at " << key_iter.Name();
continue;
}
}
std::string url(base::WideToUTF8(wide_url));
SearchEnginesMap::iterator t_iter = search_engines_map.find(url);
if (t_iter == search_engines_map.end()) {
// First time we see that URL.
GURL gurl(url);
if (gurl.is_valid()) {
t_iter = search_engines_map.insert(std::make_pair(url, name)).first;
}
}
}
// ProfileWriter::AddKeywords() requires a vector and we have a map.
std::vector<importer::SearchEngineInfo> search_engines;
for (SearchEnginesMap::iterator i = search_engines_map.begin();
i != search_engines_map.end(); ++i) {
importer::SearchEngineInfo search_engine_info;
search_engine_info.url = base::UTF8ToUTF16(i->first);
search_engine_info.display_name = i->second;
search_engines.push_back(search_engine_info);
}
bridge_->SetKeywords(search_engines, true);
}
void IEImporter::ImportHomepage() {
const wchar_t* kIEHomepage = L"Start Page";
const wchar_t* kIEDefaultHomepage = L"Default_Page_URL";
base::string16 key_path(importer::GetIESettingsKey());
base::win::RegKey key(HKEY_CURRENT_USER, key_path.c_str(), KEY_READ);
base::string16 homepage_url;
if (key.ReadValue(kIEHomepage, &homepage_url) != ERROR_SUCCESS ||
homepage_url.empty())
return;
GURL homepage = GURL(homepage_url);
if (!homepage.is_valid())
return;
// Check to see if this is the default website and skip import.
base::win::RegKey keyDefault(HKEY_LOCAL_MACHINE, key_path.c_str(), KEY_READ);
base::string16 <API key>;
LONG result = keyDefault.ReadValue(kIEDefaultHomepage, &<API key>);
if (result == ERROR_SUCCESS && !<API key>.empty()) {
if (homepage.spec() == GURL(<API key>).spec())
return;
}
bridge_->AddHomePage(homepage);
}
bool IEImporter::GetFavoritesInfo(IEImporter::FavoritesInfo* info) {
if (!source_path_.empty()) {
// Source path exists during testing as well as when importing from Edge.
info->path = source_path_;
info->path = info->path.AppendASCII("Favorites");
info->links_folder = L"Links";
return true;
}
// IE stores the favorites in the Favorites under user profile's folder.
wchar_t buffer[MAX_PATH];
if (FAILED(SHGetFolderPath(NULL, CSIDL_FAVORITES, NULL,
SHGFP_TYPE_CURRENT, buffer)))
return false;
info->path = base::FilePath(buffer);
// There is a Links folder under Favorites folder in Windows Vista, but it
// is not recording in Vista's registry. So in Vista, we assume the Links
// folder is under Favorites folder since it looks like there is not name
// different in every language version of Windows Vista.
if (base::win::GetVersion() < base::win::VERSION_VISTA) {
// The Link folder name is stored in the registry.
DWORD buffer_length = sizeof(buffer);
base::win::RegKey reg_key(HKEY_CURRENT_USER, kIEToolbarKey, KEY_READ);
if (reg_key.ReadValue(L"LinksFolderName", buffer,
&buffer_length, NULL) != ERROR_SUCCESS)
return false;
info->links_folder = buffer;
} else {
info->links_folder = L"Links";
}
return true;
}
void IEImporter::<API key>(
const FavoritesInfo& info,
BookmarkVector* bookmarks,
favicon_base::<API key>* favicons) {
base::FilePath file;
std::vector<base::FilePath::StringType> file_list;
base::FilePath favorites_path(info.path);
// Favorites path length. Make sure it doesn't include the trailing \.
size_t favorites_path_len =
favorites_path.<API key>().value().size();
base::FileEnumerator file_enumerator(
favorites_path, true, base::FileEnumerator::FILES);
while (!(file = file_enumerator.Next()).value().empty() && !cancelled())
file_list.push_back(file.value());
// Keep the bookmarks in alphabetical order.
std::sort(file_list.begin(), file_list.end());
// Map from favicon URLs to the favicon data (the binary image data and the
// set of bookmark URLs referring to the favicon).
typedef std::map<GURL, favicon_base::FaviconUsageData> FaviconMap;
FaviconMap favicon_map;
for (std::vector<base::FilePath::StringType>::iterator it = file_list.begin();
it != file_list.end(); ++it) {
base::FilePath shortcut(*it);
if (!base::<API key>(shortcut.Extension(), ".url"))
continue;
// Skip the bookmark with invalid URL.
base::win::ScopedComPtr<<API key>> url_locator;
if (!<API key>(*it, &url_locator))
continue;
GURL url = <API key>(url_locator.get());
if (!url.is_valid())
continue;
// Skip default bookmarks. go.microsoft.com redirects to
// which URLs IE has as default, to some another sites.
// We expect that users will never themselves create bookmarks having this
// hostname.
if (url.host() == "go.microsoft.com")
continue;
// Read favicon.
UpdateFaviconMap(*it, url, url_locator.get(), &favicon_map);
// Make the relative path from the Favorites folder, without the basename.
// ex. Suppose that the Favorites folder is C:\Users\Foo\Favorites.
// C:\Users\Foo\Favorites\Foo.url -> ""
// C:\Users\Foo\Favorites\Links\Bar\Baz.url -> "Links\Bar"
base::FilePath::StringType relative_string =
shortcut.DirName().value().substr(favorites_path_len);
if (!relative_string.empty() &&
base::FilePath::IsSeparator(relative_string[0]))
relative_string = relative_string.substr(1);
base::FilePath relative_path(relative_string);
<API key> entry;
// Remove the dot, the file extension, and the directory path.
entry.title = shortcut.RemoveExtension().BaseName().value();
entry.url = url;
entry.creation_time = GetFileCreationTime(*it);
if (!relative_path.empty())
relative_path.GetComponents(&entry.path);
// Add the bookmark.
if (!entry.path.empty() && entry.path[0] == info.links_folder) {
// Bookmarks in the Link folder should be imported to the toolbar.
entry.in_toolbar = true;
}
bookmarks->push_back(entry);
}
if (!edge_import_mode_) {
// Reflect the menu order in IE.
<API key>(this, bookmarks);
}
// Record favicon data.
for (FaviconMap::iterator iter = favicon_map.begin();
iter != favicon_map.end(); ++iter)
favicons->push_back(iter->second);
}
int IEImporter::CurrentIEVersion() const {
static int version = -1;
if (version < 0) {
wchar_t buffer[128];
DWORD buffer_length = sizeof(buffer);
base::win::RegKey reg_key(HKEY_LOCAL_MACHINE, kIEVersionKey, KEY_READ);
LONG result = reg_key.ReadValue(L"Version", buffer, &buffer_length, NULL);
version = ((result == ERROR_SUCCESS)? _wtoi(buffer) : 0);
}
return version;
} |
<a name="2.0.0"></a>
# 2.0.0 (2017-07-25)
* chore(package): update dependencies ([e797438](https://github.com/RisingStack/cache/commit/e797438))
BREAKING CHANGE: drop Node v4 support
<a name="1.3.5"></a>
## 1.3.5 (2017-03-29)
feat
* feat(cache): allow zero expire, document (#12) 57c02fa
<a name="1.3.4"></a>
## 1.3.4 (2017-03-29)
chore
* chore(package): bump version to 1.3.4 caf5758
feat
* feat(example): fix example 2ba3b55
fix
* fix(cache): do not save without expire in refresh df6265d
* fix(cache): use createdAt 4013913
* fix(refresh): cache options merge d1e4e07
<a name="1.3.3"></a>
## 1.3.3 (2017-03-28)
chore
* chore(package): bump version to 1.3.3 ff2be34
* chore(package): update dependencies 80e3646
fix
* fix(cache): allow falsy values to be set b8065ff
<a name="1.3.2"></a>
## 1.3.2 (2017-03-07)
chore
* chore(package): bump version to 1.3.2 651cd91
fix
* fix(babel): revert babel preset change, remove spread in super instead (the cause is still unknown) 8e38576
<a name="1.3.1"></a>
## 1.3.1 (2017-03-07)
chore
* chore(package): bump version to 1.3.1 f76533b
fix
* fix(babel): use es2015 preset 40d6d53
<a name="1.3.0"></a>
# 1.3.0 (2017-03-07)
* feat(store, cache): add store error handler and get timeout 19ee994
chore
* chore(package): bump version to 1.3.0 0879f0c
* chore(package): update dependencies 9e0c332
<a name="1.2.0"></a>
# 1.2.0 (2017-02-28)
chore
* chore(package): bump version to 1.2.0 e892613
feat
* feat(error): no cache ebb0f71
<a name="1.1.1"></a>
## 1.1.1 (2017-02-08)
chore
* chore(package): bump version to 1.1.1 0efc8e4
fix
* fix(cache): stale and expired behaviour 8cd9eea
<a name="1.1.0"></a>
# 1.1.0 (2017-02-07)
chore
* chore(package): update version to 1.1.0 4c7feb8
feat
* feat(cache): only save value if expire is greater than 0 bbd8c9e
<a name="1.0.4"></a>
## 1.0.4 (2017-02-02)
chore
* chore(package): bump version to 1.0.4 881a2aa
fix
* fix(cache): set stores in wrap without nextTick d0b9654
<a name="1.0.3"></a>
## 1.0.3 (2017-02-01)
chore
* chore(package): bump version to 1.0.3 4eb03a7
fix
* fix(package): fix main field e462690
<a name="1.0.2"></a>
## 1.0.2 (2017-02-01)
chore
* chore(package): bump version to 1.0.2 8ccef09
fix
* fix(npm): fix publish a0fdfae
<a name="1.0.1"></a>
## 1.0.1 (2017-02-01)
chore
* chore(circle): add circleci test configuration 9c56f17
* chore(package): bump version to 1.0.1 a92ecf1
docs
* docs(package): add documentations and example dc94000
feat
* feat(cache): add option to set ttl on every result 7bc1543
* feat(cache): cache is an event emitter, emit store get error 829aaca
* feat(package): first implementation 8bcf242
* feat(package): update types 02d4671
* feat(stores): add LRU store b03538e
* feat(stores): add redis store b83f0be
fix
* fix(npm): add .npmignore 28c7cdb
* fix(package): fix build script 55c7f6a
refactor
* refactor(chore): remove .vscode ab9e2c9 |
<?php
return [
'class' => 'yii\db\Connection',
'dsn' => 'mysql:host=10.197.1.235:8889;dbname=programathon2016;',
'username' => 'local',
'password' => 'local',
'charset' => 'utf8',
]; |
/* Allows direct buffer access */
#define VTK_WRAPPING_CXX
#define <API key>
#include <vtkDataArrayWrap.h>
#include "<API key>.h"
#include "vtkObjectWrap.h"
#include "plus.h"
using namespace v8;
void <API key>::GetBuffer(const Nan::<API key><v8::Value>& info)
{
<API key> *wrapper = ObjectWrap::Unwrap<<API key>>(info.Holder());
vtkUnsignedIntArray *native = (vtkUnsignedIntArray *)wrapper->native.GetPointer();
if(info.Length() != 0)
{
Nan::ThrowError("Too many parameters.");
return;
}
Local<v8::ArrayBuffer> ab =
v8::ArrayBuffer::New(
v8::Isolate::GetCurrent(),
native->GetVoidPointer( 0 ),
native->GetDataSize() * native->GetDataTypeSize()
);
Local<v8::Uint16Array> at = v8::Uint16Array::New(ab, 0, native->GetDataSize());
info.GetReturnValue().Set(at);
} |
export default {"viewBox":"0 0 52 52","xmlns":"http: |
# imapfilter-docker
CentOS based image with imapfilter configured and setup to run your volume mounted imapfilter config files.
# Usage
`docker run -d -v ~/.imapfilter:/imapfilter/.imapfilter maxandersen/imapfilter-docker <password>`
[
{
return (equalIgnoringCase(name, ConnectSrc)
|| equalIgnoringCase(name, DefaultSrc)
|| equalIgnoringCase(name, FontSrc)
|| equalIgnoringCase(name, FrameSrc)
|| equalIgnoringCase(name, ImgSrc)
|| equalIgnoringCase(name, MediaSrc)
|| equalIgnoringCase(name, ObjectSrc)
|| equalIgnoringCase(name, ReportURI)
|| equalIgnoringCase(name, Sandbox)
|| equalIgnoringCase(name, ScriptSrc)
|| equalIgnoringCase(name, StyleSrc)
|| equalIgnoringCase(name, BaseURI)
|| equalIgnoringCase(name, ChildSrc)
|| equalIgnoringCase(name, FormAction)
|| equalIgnoringCase(name, FrameAncestors)
|| equalIgnoringCase(name, PluginTypes)
|| equalIgnoringCase(name, ReflectedXSS)
|| equalIgnoringCase(name, Referrer)
|| equalIgnoringCase(name, ManifestSrc)
|| equalIgnoringCase(name, <API key>)
|| equalIgnoringCase(name, <API key>));
}
static UseCounter::Feature getUseCounterType(<API key> type)
{
switch (type) {
case <API key>:
return UseCounter::<API key>;
case <API key>:
return UseCounter::<API key>;
}
ASSERT_NOT_REACHED();
return UseCounter::NumberOfFeatures;
}
static ReferrerPolicy <API key>(ReferrerPolicy a, ReferrerPolicy b)
{
if (a != b)
return ReferrerPolicyNever;
return a;
}
<API key>::<API key>()
: m_executionContext(nullptr)
, <API key>(false)
, <API key>(<API key>)
, <API key>(<API key>)
, m_sandboxMask(0)
, <API key>(false)
, m_referrerPolicy(<API key>)
, <API key>(SecurityContext::<API key>)
{
}
void <API key>::<API key>(ExecutionContext* executionContext)
{
m_executionContext = executionContext;
<API key>();
}
void <API key>::<API key>()
{
ASSERT(m_executionContext);
// Ensure that 'self' processes correctly.
m_selfProtocol = securityOrigin()->protocol();
m_selfSource = adoptPtr(new CSPSource(this, m_selfProtocol, securityOrigin()->host(), securityOrigin()->port(), String(), CSPSource::NoWildcard, CSPSource::NoWildcard));
// If we're in a Document, set the referrer policy, mixed content checking, and sandbox
// flags, then dump all the parsing error messages, then poke at histograms.
if (Document* document = this->document()) {
if (m_sandboxMask != SandboxNone) {
UseCounter::count(document, UseCounter::SandboxViaCSP);
document->enforceSandboxFlags(m_sandboxMask);
}
if (<API key>)
document-><API key>();
if (<API key>())
document->setReferrerPolicy(m_referrerPolicy);
if (<API key> > document-><API key>())
document-><API key>(<API key>);
for (const auto& consoleMessage : m_consoleMessages)
m_executionContext->addConsoleMessage(consoleMessage);
m_consoleMessages.clear();
for (const auto& policy : m_policies)
UseCounter::count(*document, getUseCounterType(policy->headerType()));
}
// We disable 'eval()' even in the case of report-only policies, and rely on the check in the
// V8Initializer::<API key> callback to determine whether the
// call should execute or not.
if (!<API key>.isNull())
m_executionContext->disableEval(<API key>);
}
<API key>::~<API key>()
{
}
Document* <API key>::document() const
{
return m_executionContext->isDocument() ? toDocument(m_executionContext) : nullptr;
}
void <API key>::copyStateFrom(const <API key>* other)
{
ASSERT(m_policies.isEmpty());
for (const auto& policy : other->m_policies)
<API key>(policy->header(), policy->headerType(), policy->headerSource());
}
void <API key>::copyPluginTypesFrom(const <API key>* other)
{
for (const auto& policy : other->m_policies) {
if (policy->hasPluginTypes()) {
<API key>(policy->pluginTypesText(), policy->headerType(), policy->headerSource());
}
}
}
void <API key>::didReceiveHeaders(const <API key>& headers)
{
if (!headers.<API key>().isEmpty())
<API key>(headers.<API key>(), <API key>, <API key>);
if (!headers.<API key>().isEmpty())
<API key>(headers.<API key>(), <API key>, <API key>);
}
void <API key>::didReceiveHeader(const String& header, <API key> type, <API key> source)
{
<API key>(header, type, source);
// This might be called after we've been bound to an execution context. For example, a <meta>
// element might be injected after page load.
if (m_executionContext)
<API key>();
}
void <API key>::<API key>(const String& header, <API key> type, <API key> source)
{
// If this is a report-only header inside a <meta> element, bail out.
if (source == <API key> && type == <API key> && <API key>()) {
<API key>(header);
return;
}
Vector<UChar> characters;
header.appendTo(characters);
const UChar* begin = characters.data();
const UChar* end = begin + characters.size();
// RFC2616, section 4.2 specifies that headers appearing multiple times can
// be combined with a comma. Walk the header string, and parse each comma
// separated chunk as a separate header.
const UChar* position = begin;
while (position < end) {
skipUntil<UChar>(position, end, ',');
// header1,header2 OR header1
OwnPtr<CSPDirectiveList> policy = CSPDirectiveList::create(this, begin, position, type, source);
if (type != <API key> && policy-><API key>()) {
// FIXME: We need a 'ReferrerPolicyUnset' enum to avoid confusing code like this.
m_referrerPolicy = <API key>() ? <API key>(m_referrerPolicy, policy->referrerPolicy()) : policy->referrerPolicy();
}
if (!policy->allowEval(0, SuppressReport) && <API key>.isNull())
<API key> = policy-><API key>();
m_policies.append(policy.release());
// Skip the comma, and begin the next header from the current position.
ASSERT(position == end || *position == ',');
skipExactly<UChar>(position, end, ',');
begin = position;
}
}
void <API key>::<API key>(bool value)
{
<API key> = value;
}
void <API key>::<API key>(const KURL& url)
{
// Create a temporary CSPSource so that 'self' expressions can be resolved before we bind to
// an execution context (for 'frame-ancestor' resolution, for example). This CSPSource will
// be overwritten when we bind this object to an execution context.
RefPtr<SecurityOrigin> origin = SecurityOrigin::create(url);
m_selfProtocol = origin->protocol();
m_selfSource = adoptPtr(new CSPSource(this, m_selfProtocol, origin->host(), origin->port(), String(), CSPSource::NoWildcard, CSPSource::NoWildcard));
}
const String& <API key>::deprecatedHeader() const
{
return m_policies.isEmpty() ? emptyString() : m_policies[0]->header();
}
<API key> <API key>::<API key>() const
{
return m_policies.isEmpty() ? <API key> : m_policies[0]->headerType();
}
template<bool (CSPDirectiveList::*allowed)(<API key>::ReportingStatus) const>
bool isAllowedByAll(const <API key>& policies, <API key>::ReportingStatus reportingStatus)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(reportingStatus))
return false;
}
return true;
}
template <bool (CSPDirectiveList::*allowed)(ScriptState* scriptState, <API key>::ReportingStatus, <API key>::ExceptionStatus) const>
bool <API key>(const <API key>& policies, ScriptState* scriptState, <API key>::ReportingStatus reportingStatus, <API key>::ExceptionStatus exceptionStatus)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(scriptState, reportingStatus, exceptionStatus))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(const String&, const WTF::OrdinalNumber&, <API key>::ReportingStatus) const>
bool <API key>(const <API key>& policies, const String& contextURL, const WTF::OrdinalNumber& contextLine, <API key>::ReportingStatus reportingStatus)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(contextURL, contextLine, reportingStatus))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(const String&, const WTF::OrdinalNumber&, <API key>::ReportingStatus, const String& content) const>
bool <API key>(const <API key>& policies, const String& contextURL, const WTF::OrdinalNumber& contextLine, <API key>::ReportingStatus reportingStatus, const String& content)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(contextURL, contextLine, reportingStatus, content))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(const String&) const>
bool <API key>(const <API key>& policies, const String& nonce)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(nonce))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(const CSPHashValue&) const>
bool <API key>(const <API key>& policies, const CSPHashValue& hashValue)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(hashValue))
return false;
}
return true;
}
template <bool (CSPDirectiveList::*allowFromURL)(const KURL&, <API key>::RedirectStatus, <API key>::ReportingStatus) const>
bool <API key>(const <API key>& policies, const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus)
{
if (SchemeRegistry::<API key>(url.protocol()))
return true;
for (const auto& policy : policies) {
if (!(policy.get()->*allowFromURL)(url, redirectStatus, reportingStatus))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(LocalFrame*, const KURL&, <API key>::ReportingStatus) const>
bool <API key>(const <API key>& policies, LocalFrame* frame, const KURL& url, <API key>::ReportingStatus reportingStatus)
{
for (const auto& policy : policies) {
if (!(policy.get()->*allowed)(frame, url, reportingStatus))
return false;
}
return true;
}
template<bool (CSPDirectiveList::*allowed)(const CSPHashValue&) const>
bool checkDigest(const String& source, uint8_t hashAlgorithmsUsed, const <API key>& policies)
{
// Any additions or subtractions from this struct should also modify the
// respective entries in the kSupportedPrefixes array in
// CSPSourceList::parseHash().
static const struct {
<API key> cspHashAlgorithm;
HashAlgorithm algorithm;
} kAlgorithmMap[] = {
{ <API key>, HashAlgorithmSha1 },
{ <API key>, HashAlgorithmSha256 },
{ <API key>, HashAlgorithmSha384 },
{ <API key>, HashAlgorithmSha512 }
};
// Only bother normalizing the source/computing digests if there are any checks to be done.
if (hashAlgorithmsUsed == <API key>)
return false;
StringUTF8Adaptor normalizedSource = normalizeSource(source);
for (const auto& algorithmMap : kAlgorithmMap) {
DigestValue digest;
if (algorithmMap.cspHashAlgorithm & hashAlgorithmsUsed) {
bool digestSuccess = computeDigest(algorithmMap.algorithm, normalizedSource.data(), normalizedSource.length(), digest);
if (digestSuccess && <API key><allowed>(policies, CSPHashValue(algorithmMap.cspHashAlgorithm, digest)))
return true;
}
}
return false;
}
bool <API key>::allowJavaScriptURLs(const String& contextURL, const WTF::OrdinalNumber& contextLine, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::allowJavaScriptURLs>(m_policies, contextURL, contextLine, reportingStatus);
}
bool <API key>::<API key>(const String& contextURL, const WTF::OrdinalNumber& contextLine, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::<API key>>(m_policies, contextURL, contextLine, reportingStatus);
}
bool <API key>::allowInlineScript(const String& contextURL, const WTF::OrdinalNumber& contextLine, const String& scriptContent, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::allowInlineScript>(m_policies, contextURL, contextLine, reportingStatus, scriptContent);
}
bool <API key>::allowInlineStyle(const String& contextURL, const WTF::OrdinalNumber& contextLine, const String& styleContent, <API key>::ReportingStatus reportingStatus) const
{
if (<API key>)
return true;
return <API key><&CSPDirectiveList::allowInlineStyle>(m_policies, contextURL, contextLine, reportingStatus, styleContent);
}
bool <API key>::allowEval(ScriptState* scriptState, <API key>::ReportingStatus reportingStatus, <API key>::ExceptionStatus exceptionStatus) const
{
return <API key><&CSPDirectiveList::allowEval>(m_policies, scriptState, reportingStatus, exceptionStatus);
}
String <API key>::<API key>() const
{
for (const auto& policy : m_policies) {
if (!policy->allowEval(0, SuppressReport))
return policy-><API key>();
}
return String();
}
bool <API key>::allowPluginType(const String& type, const String& typeAttribute, const KURL& url, <API key>::ReportingStatus reportingStatus) const
{
for (const auto& policy : m_policies) {
if (!policy->allowPluginType(type, typeAttribute, url, reportingStatus))
return false;
}
return true;
}
bool <API key>::<API key>(const Document& document, const String& type, const String& typeAttribute, const KURL& url, <API key>::ReportingStatus reportingStatus) const
{
if (document.<API key>() && !document.<API key>()->allowPluginType(type, typeAttribute, url))
return false;
// CSP says that a plugin document in a nested browsing context should
// inherit the plugin-types of its parent.
// FIXME: The plugin-types directive should be pushed down into the
// current document instead of reaching up to the parent for it here.
LocalFrame* frame = document.frame();
if (frame && frame->tree().parent() && frame->tree().parent()->isLocalFrame() && document.isPluginDocument()) {
<API key>* parentCSP = toLocalFrame(frame->tree().parent())->document()-><API key>();
if (parentCSP && !parentCSP->allowPluginType(type, typeAttribute, url))
return false;
}
return true;
}
bool <API key>::<API key>(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::<API key>>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::<API key>(const String& nonce) const
{
return <API key><&CSPDirectiveList::allowScriptNonce>(m_policies, nonce);
}
bool <API key>::allowStyleWithNonce(const String& nonce) const
{
return <API key><&CSPDirectiveList::allowStyleNonce>(m_policies, nonce);
}
bool <API key>::allowScriptWithHash(const String& source) const
{
return checkDigest<&CSPDirectiveList::allowScriptHash>(source, <API key>, m_policies);
}
bool <API key>::allowStyleWithHash(const String& source) const
{
return checkDigest<&CSPDirectiveList::allowStyleHash>(source, <API key>, m_policies);
}
void <API key>::<API key>(uint8_t algorithms)
{
<API key> |= algorithms;
}
void <API key>::<API key>(uint8_t algorithms)
{
<API key> |= algorithms;
}
bool <API key>::<API key>(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::<API key>>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::<API key>(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::<API key>>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::<API key>(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
if (SchemeRegistry::<API key>(url.protocol(), SchemeRegistry::PolicyAreaImage))
return true;
return <API key><&CSPDirectiveList::<API key>>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::<API key>(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
if (SchemeRegistry::<API key>(url.protocol(), SchemeRegistry::PolicyAreaStyle))
return true;
return <API key><&CSPDirectiveList::<API key>>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::allowFontFromSource(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::allowFontFromSource>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::<API key>(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::<API key>>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::<API key>(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::<API key>>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::allowFormAction(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::allowFormAction>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::allowBaseURI(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::allowBaseURI>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::<API key>(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
// CSP 1.1 moves workers from 'script-src' to the new 'child-src'. Measure the impact of this <API key> change.
if (Document* document = this->document()) {
UseCounter::count(*document, UseCounter::WorkerSubjectToCSP);
if (<API key><&CSPDirectiveList::<API key>>(m_policies, url, redirectStatus, SuppressReport) && !<API key><&CSPDirectiveList::<API key>>(m_policies, url, redirectStatus, SuppressReport))
UseCounter::count(*document, UseCounter::<API key>);
}
return <API key><&CSPDirectiveList::<API key>>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::<API key>(const KURL& url, <API key>::RedirectStatus redirectStatus, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::<API key>>(m_policies, url, redirectStatus, reportingStatus);
}
bool <API key>::allowAncestors(LocalFrame* frame, const KURL& url, <API key>::ReportingStatus reportingStatus) const
{
return <API key><&CSPDirectiveList::allowAncestors>(m_policies, frame, url, reportingStatus);
}
bool <API key>::isActive() const
{
return !m_policies.isEmpty();
}
<API key> <API key>::<API key>() const
{
<API key> disposition = ReflectedXSSUnset;
for (const auto& policy : m_policies) {
if (policy-><API key>() > disposition)
disposition = std::max(disposition, policy-><API key>());
}
return disposition;
}
bool <API key>::<API key>() const
{
for (const auto& policy : m_policies) {
if (policy-><API key>())
return true;
}
return false;
}
SecurityOrigin* <API key>::securityOrigin() const
{
return m_executionContext->securityContext().securityOrigin();
}
const KURL <API key>::url() const
{
return m_executionContext->contextURL();
}
KURL <API key>::completeURL(const String& url) const
{
return m_executionContext->contextCompleteURL(url);
}
void <API key>::enforceSandboxFlags(SandboxFlags mask)
{
m_sandboxMask |= mask;
}
void <API key>::<API key>()
{
<API key> = true;
}
void <API key>::<API key>(SecurityContext::<API key> policy)
{
if (policy > <API key>)
<API key> = policy;
}
static String <API key>(Document* document, const KURL& url)
{
if (!url.isValid())
return String();
if (!url.isHierarchical() || url.protocolIs("file"))
return url.protocol();
return document->securityOrigin()->canRequest(url) ? url.<API key>() : SecurityOrigin::create(url)->toString();
}
static void <API key>(<API key>& init, Document* document, const String& directiveText, const String& effectiveDirective, const KURL& blockedURL, const String& header)
{
if (equalIgnoringCase(effectiveDirective, <API key>::FrameAncestors)) {
// If this load was blocked via 'frame-ancestors', then the URL of |document| has not yet
// been initialized. In this case, we'll set both 'documentURI' and 'blockedURI' to the
// blocked document's URL.
init.setDocumentURI(blockedURL.string());
init.setBlockedURI(blockedURL.string());
} else {
init.setDocumentURI(document->url().string());
init.setBlockedURI(<API key>(document, blockedURL));
}
init.setReferrer(document->referrer());
init.<API key>(directiveText);
init.<API key>(effectiveDirective);
init.setOriginalPolicy(header);
init.setSourceFile(String());
init.setLineNumber(0);
init.setColumnNumber(0);
init.setStatusCode(0);
if (!SecurityOrigin::isSecure(document->url()) && document->loader())
init.setStatusCode(document->loader()->response().httpStatusCode());
RefPtrWillBeRawPtr<ScriptCallStack> stack = <API key>(1, false);
if (!stack)
return;
const ScriptCallFrame& callFrame = stack->at(0);
if (callFrame.lineNumber()) {
KURL source = KURL(ParsedURLString, callFrame.sourceURL());
init.setSourceFile(<API key>(document, source));
init.setLineNumber(callFrame.lineNumber());
init.setColumnNumber(callFrame.columnNumber());
}
}
void <API key>::reportViolation(const String& directiveText, const String& effectiveDirective, const String& consoleMessage, const KURL& blockedURL, const Vector<String>& reportEndpoints, const String& header, LocalFrame* contextFrame)
{
ASSERT((m_executionContext && !contextFrame) || (equalIgnoringCase(effectiveDirective, <API key>::FrameAncestors) && contextFrame));
// FIXME: Support sending reports from worker.
Document* document = contextFrame ? contextFrame->document() : this->document();
if (!document)
return;
LocalFrame* frame = document->frame();
if (!frame)
return;
<API key> violationData;
<API key>(violationData, document, directiveText, effectiveDirective, blockedURL, header);
frame->localDOMWindow()-><API key>(<API key>::create(EventTypeNames::<API key>, violationData));
if (reportEndpoints.isEmpty())
return;
// We need to be careful here when deciding what information to send to the
// report-uri. Currently, we send only the current document's URL and the
// directive that was violated. The document's URL is safe to send because
// it's the document itself that's requesting that it be sent. You could
// make an argument that we shouldn't send HTTPS document URLs to HTTP
// report-uris (for the same reasons that we supress the Referer in that
// case), but the Referer is sent implicitly whereas this request is only
// sent explicitly. As for which directive was violated, that's pretty
// harmless information.
RefPtr<JSONObject> cspReport = JSONObject::create();
cspReport->setString("document-uri", violationData.documentURI());
cspReport->setString("referrer", violationData.referrer());
cspReport->setString("violated-directive", violationData.violatedDirective());
cspReport->setString("effective-directive", violationData.effectiveDirective());
cspReport->setString("original-policy", violationData.originalPolicy());
cspReport->setString("blocked-uri", violationData.blockedURI());
if (!violationData.sourceFile().isEmpty() && violationData.lineNumber()) {
cspReport->setString("source-file", violationData.sourceFile());
cspReport->setNumber("line-number", violationData.lineNumber());
cspReport->setNumber("column-number", violationData.columnNumber());
}
cspReport->setNumber("status-code", violationData.statusCode());
RefPtr<JSONObject> reportObject = JSONObject::create();
reportObject->setObject("csp-report", cspReport.release());
String stringifiedReport = reportObject->toJSONString();
if (!<API key>(stringifiedReport))
return;
RefPtr<FormData> report = FormData::create(stringifiedReport.utf8());
for (const String& endpoint : reportEndpoints) {
// If we have a context frame we're dealing with 'frame-ancestors' and we don't have our
// own execution context. Use the frame's document to complete the endpoint URL, overriding
// its URL with the blocked document's URL.
ASSERT(!contextFrame || !m_executionContext);
ASSERT(!contextFrame || equalIgnoringCase(effectiveDirective, FrameAncestors));
KURL url = contextFrame ? frame->document()-><API key>(endpoint, blockedURL) : completeURL(endpoint);
PingLoader::sendViolationReport(frame, url, report, PingLoader::<API key>);
}
<API key>(stringifiedReport);
}
void <API key>::<API key>(const String& invalidValue)
{
logToConsole("The 'referrer' Content Security Policy directive has the invalid value \"" + invalidValue + "\". Valid values are \"no-referrer\", \"<API key>\", \"origin\", and \"unsafe-url\". Note that \"<API key>\" is not yet supported.");
}
void <API key>::<API key>(const String& header)
{
logToConsole("The report-only Content Security Policy '" + header + "' was delivered via a <meta> element, which is disallowed. The policy has been ignored.");
}
void <API key>::<API key>(const String& header)
{
logToConsole("The Content Security Policy '" + header + "' was delivered via a <meta> element outside the document's <head>, which is disallowed. The policy has been ignored.");
}
void <API key>::<API key>(const String& name, const String& value)
{
logToConsole("The Content Security Policy directive '" + name + "' should be empty, but was delivered with a value of '" + value + "'. The directive has been applied, and the value ignored.");
}
void <API key>::<API key>(const String& name)
{
logToConsole("The Content Security Policy directive '" + name + "' is ignored when delivered in a report-only policy.");
}
void <API key>::<API key>(const String& name)
{
DEFINE_STATIC_LOCAL(String, allow, ("allow"));
DEFINE_STATIC_LOCAL(String, options, ("options"));
DEFINE_STATIC_LOCAL(String, policyURI, ("policy-uri"));
DEFINE_STATIC_LOCAL(String, allowMessage, ("The 'allow' directive has been replaced with 'default-src'. Please use that directive instead, as 'allow' has no effect."));
DEFINE_STATIC_LOCAL(String, optionsMessage, ("The 'options' directive has been replaced with 'unsafe-inline' and 'unsafe-eval' source expressions for the 'script-src' and 'style-src' directives. Please use those directives instead, as 'options' has no effect."));
DEFINE_STATIC_LOCAL(String, policyURIMessage, ("The 'policy-uri' directive has been removed from the specification. Please specify a complete policy via the <API key> header."));
String message = "Unrecognized <API key> directive '" + name + "'.\n";
MessageLevel level = ErrorMessageLevel;
if (equalIgnoringCase(name, allow)) {
message = allowMessage;
} else if (equalIgnoringCase(name, options)) {
message = optionsMessage;
} else if (equalIgnoringCase(name, policyURI)) {
message = policyURIMessage;
} else if (isDirectiveName(name)) {
message = "The <API key> directive '" + name + "' is implemented behind a flag which is currently disabled.\n";
level = InfoMessageLevel;
}
logToConsole(message, level);
}
void <API key>::<API key>(const String& directiveName, const String& sourceExpression)
{
String message = "The Content Security Policy directive '" + directiveName + "' contains '" + sourceExpression + "' as a source expression. Did you mean '" + directiveName + " ...; " + sourceExpression + "...' (note the semicolon)?";
logToConsole(message);
}
void <API key>::<API key>(const String& name)
{
String message = "Ignoring duplicate <API key> directive '" + name + "'.\n";
logToConsole(message);
}
void <API key>::<API key>(const String& pluginType)
{
String message;
if (pluginType.isNull())
message = "'plugin-types' Content Security Policy directive is empty; all plugins will be blocked.\n";
else if (pluginType == "'none'")
message = "Invalid plugin type in 'plugin-types' Content Security Policy directive: '" + pluginType + "'. Did you mean to set the object-src directive to 'none'?\n";
else
message = "Invalid plugin type in 'plugin-types' Content Security Policy directive: '" + pluginType + "'.\n";
logToConsole(message);
}
void <API key>::<API key>(const String& invalidFlags)
{
logToConsole("Error while parsing the 'sandbox' Content Security Policy directive: " + invalidFlags);
}
void <API key>::<API key>(const String& invalidValue)
{
logToConsole("The 'reflected-xss' Content Security Policy directive has the invalid value \"" + invalidValue + "\". Valid values are \"allow\", \"filter\", and \"block\".");
}
void <API key>::<API key>(const String& directiveName, const String& value)
{
String message = "The value for Content Security Policy directive '" + directiveName + "' contains an invalid character: '" + value + "'. Non-whitespace characters outside ASCII 0x21-0x7E must be percent-encoded, as described in RFC 3986, section 2.1: http://tools.ietf.org/html/rfc3986#section-2.1.";
logToConsole(message);
}
void <API key>::<API key>(const String& directiveName, const String& value, const char invalidChar)
{
ASSERT(invalidChar == '#' || invalidChar == '?');
String ignoring = "The fragment identifier, including the '#', will be ignored.";
if (invalidChar == '?')
ignoring = "The query component, including the '?', will be ignored.";
String message = "The source list for Content Security Policy directive '" + directiveName + "' contains a source with an invalid path: '" + value + "'. " + ignoring;
logToConsole(message);
}
void <API key>::<API key>(const String& directiveName, const String& source)
{
String message = "The source list for Content Security Policy directive '" + directiveName + "' contains an invalid source: '" + source + "'. It will be ignored.";
if (equalIgnoringCase(source, "'none'"))
message = message + " Note that 'none' has no effect unless it is the only expression in the source list.";
logToConsole(message);
}
void <API key>::<API key>(const String& policy)
{
logToConsole("The Content Security Policy '" + policy + "' was delivered in report-only mode, but does not specify a 'report-uri'; the policy will have no effect. Please either add a 'report-uri' directive, or deliver the policy via the '<API key>' header.");
}
void <API key>::logToConsole(const String& message, MessageLevel level)
{
logToConsole(ConsoleMessage::create(<API key>, level, message));
}
void <API key>::logToConsole(<API key><ConsoleMessage> consoleMessage, LocalFrame* frame)
{
if (frame)
frame->document()->addConsoleMessage(consoleMessage);
else if (m_executionContext)
m_executionContext->addConsoleMessage(consoleMessage);
else
m_consoleMessages.append(consoleMessage);
}
void <API key>::<API key>(const String& directiveText) const
{
m_executionContext-><API key>(directiveText);
}
bool <API key>::<API key>() const
{
return <API key>::<API key>();
}
bool <API key>::urlMatchesSelf(const KURL& url) const
{
return m_selfSource->matches(url, DidNotRedirect);
}
bool <API key>::protocolMatchesSelf(const KURL& url) const
{
if (equalIgnoringCase("http", m_selfProtocol))
return url.<API key>();
return equalIgnoringCase(url.protocol(), m_selfProtocol);
}
bool <API key>::<API key>(const ExecutionContext* context)
{
if (context && context->isDocument()) {
const Document* document = toDocument(context);
if (document->frame())
return document->frame()->script().<API key>();
}
return false;
}
bool <API key>::<API key>(const String& report) const
{
// Collisions have no security impact, so we can save space by storing only the string's hash rather than the whole report.
return !<API key>.contains(report.impl()->hash());
}
void <API key>::<API key>(const String& report)
{
<API key>.add(report.impl()->hash());
}
} // namespace blink |
module Khipu
CERT_PROD = %q{
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>/f6C/5V/<API key>/OEiL
<API key>
0IXoiRuZWPh9JkbGyl/tSd/<API key>
xMqTGrujDnA3qF/<API key>
GlHX2hWyVJ2Tc+<API key>+/<API key>
<API key>+a6tv2E2yy/<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>+EUBBgkEAwEB/<API key>
K9TrKWkJH3is2H/<API key>
<API key>
<API key>==
--END CERTIFICATE
CERT_DEV = %q{
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>
<API key>+0IYrfbAPSRSX8u3+js786J
<API key>
CWZPU9RA4nFgJa/<API key>/J
<API key>/J5g86V9LPEt6h+<API key>
V6xiwkq+j+tNh5+<API key>
H9C0y7vZ/Mjm/<API key>
<API key>/nLYnPXQbpUhhJLvZbJd+Nl
<API key>//WdxHoa3lAPnY8IO+DgKp5dOMcKLopz+AX
<API key>/6YEDUJRa7D
fAUIip+ocbMykuUvnrNU/wUDRv8VbsIoMr+<API key>
I/hKy49jGW/<API key>+FsP4wuN8Rv
<API key>+kcqRFOJqWm7bmaDvZVJ
--END CERTIFICATE
end |
# Be sure to restart your server when you modify this file.
# Your secret key for verifying the integrity of signed cookies.
# If you change this key, all old signed cookies will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
FastFreddy::Application.config.secret_<API key><API key>' |
#define <API key> "MapProjection"
#define <API key> CL_ALL_FILE
#include "CoreDebugPrint.h"
#include "config.h"
#include "MapProjection/MapProjection.h"
#include "PixelBox.h"
#include "FixedPointType.h"
#include <algorithm>
#include "SphericalCamera.h"
#include "WGS84Coordinate.h"
#include "MC2Coordinate.h"
int32 MapProjection::s_topLat;
int32 MapProjection::s_bottomLat;
double MapProjection::s_maxScale;
#define <API key> 1800
using namespace std;
class ScopedCounter {
public:
ScopedCounter(int& c) : m_c(c) {
m_c++;
}
~ScopedCounter() {
m_c
}
private:
int& m_c;
};
MapProjection::
MapProjection() : TransformMatrix(),
m_screenSize(100,100),
<API key>( 1 ),
m_batchedEvent(<API key>::UNKNOWN)
{
<API key> = false;
m_angle = 0.0;
m_3dOn = false;
<API key> = 0;
MC2Coordinate lower( 664609150, 157263143 );
MC2Coordinate upper( 664689150, 157405144 );
MC2BoundingBox bbox(lower, upper);
setBoundingBox(bbox);
m_camera = new SphericalCamera(*this);
setProjectionType(MC2_PROJECTION);
}
MapProjection::
MapProjection(const MC2Coordinate& centerCoord,
int screenX, int screenY, double scale,
double angle) : TransformMatrix(), m_centerCoord(centerCoord),
m_screenSize(screenX, screenY),
m_scale(scale),
m_angle(angle),
<API key>( 1 ),
m_batchedEvent(<API key>::UNKNOWN)
{
<API key> = 0;
<API key> = false;
m_3dOn = false;
m_angle = 0.0;
m_camera = new SphericalCamera(*this);
setProjectionType(MC2_PROJECTION);
}
void
MapProjection::updateBBox()
{
if( <API key> ) {
m_camera->projectionUpdated();
m_bbox = m_camera->getBoundingBox();
return;
} else {
// static const double mc2scaletometer = 6378137.0*2.0*
// 3.<API key> / 4294967296.0;
// static const float meterstomc2scale = 1.0 / mc2scaletometer;
pair<float,float> widthAndHeight = getWidthAndHeight();
const float width = widthAndHeight.first;
const float height = widthAndHeight.second;
{
const int32 centerLat = getCenter().lat;
const float halfHeight = height * 0.5;
const int32 intHalfHeight = int32( halfHeight );
if ( halfHeight + centerLat > ( MAX_INT32 / 2 ) ) {
m_bbox.setMaxLat( MAX_INT32 / 2 );
} else {
m_bbox.setMaxLat( centerLat + intHalfHeight );
}
if ( centerLat - halfHeight < ( MIN_INT32 / 2 ) ) {
m_bbox.setMinLat( MIN_INT32 / 2 );
} else {
m_bbox.setMinLat( centerLat - intHalfHeight );
}
m_bbox.updateCosLat();
}
{
if ( width >= MAX_UINT32 - 1) {
m_bbox.setMinLon( MIN_INT32 );
m_bbox.setMaxLon( MAX_INT32 );
} else {
int32 intWidth = int32(width * 0.5 );
int32 centerLon = getCenter().lon;
m_bbox.setMinLon( centerLon - intWidth );
m_bbox.setMaxLon( centerLon + intWidth );
}
}
// MC2Coordinate coord1;
// <API key>( coord1,
// m_screenSize.getX(),
// getCosLat(getCenter().lat));
// MC2Coordinate coord2;
// <API key>( coord2,
// m_screenSize.getY(),
// getCosLat(getCenter().lat));
// MC2Coordinate coord3;
// <API key>( coord3,
// m_screenSize.getX(),
// m_screenSize.getY(),
// getCosLat(getCenter().lat));
// MC2Coordinate coord4;
// <API key>( coord4,
// getCosLat(getCenter().lat) );
#if 0
#ifdef __unix__
mc2dbg8 << "[TMH]: m_centerCoord = " << m_centerCoord
<< " and center of m_bbox = "
<< m_bbox.getCenter() << endl;
MC2Point corner1(0,0);
MC2Point corner2(corner1);
MC2Point corner3(corner2);
MC2Point corner4(corner3);
<API key>(corner1, coord1, getCosLat(getCenter().lat));
<API key>(corner2, coord2, getCosLat(getCenter().lat));
<API key>(corner3, coord3, getCosLat(getCenter().lat));
<API key>(corner4, coord4, getCosLat(getCenter().lat));
mc2dbg << "[TMH]: Corners are "
<< corner1.getX() << "," << corner1.getY() << " + "
<< corner2.getX() << "," << corner2.getY() << " + "
<< corner3.getX() << "," << corner3.getY() << " + "
<< corner4.getX() << "," << corner4.getY() << " + "
<< endl;
#endif
#endif
}
}
void
MapProjection::<API key>(<API key>::projectionEvent trigger)
{
// Constant forever
static const float mc2scaletometer = 6378137.0*2.0*
3.<API key> / 4294967296.0;
static const float meterstomc2scale = 1.0 / mc2scaletometer;
float radAngle = getAngle() / 180 * M_PI;
float maxScale = getCosLat( m_centerCoord.lat) * float(MAX_UINT32-1000) / (
( fabs( m_screenSize.getX() *
meterstomc2scale * cos(radAngle) ) +
fabs( m_screenSize.getY() *
meterstomc2scale * sin(radAngle) ) ) );
m_scale = MIN( (float)m_scale, maxScale );
const double invScale = 1.0/m_scale;
const double mc2scale = mc2scaletometer * invScale;
TransformMatrix::updateMatrix( m_angle, mc2scale, m_centerCoord,
m_screenSize.getX(),
m_screenSize.getY() );
updateBBox();
notifyListeners(trigger);
}
float64
MapProjection::<API key>( int screenXSize,
int screenYSize,
MC2BoundingBox& bbox )
{
static const double mc2scaletometer = 6378137.0*2.0*
3.<API key> / 4294967296.0;
// Strech out the bbox to fit the screen size.
// This is copied from GfxUtility. I don't want that dependency
// so I have copied it here. I might want to change it though.
int32 minLat = bbox.getMinLat();
int32 minLon = bbox.getMinLon();
int32 maxLat = bbox.getMaxLat();
int32 maxLon = bbox.getMaxLon();
int width = screenXSize;
int height = screenYSize;
// width and height should have same proportions as
// bbox.width and bbox.height
float64 bboxHeight = bbox.getHeight();
float64 bboxWidth = bbox.getWidth();
if ( bboxHeight == 0.0 ) {
bboxHeight = 1.0;
}
if ( bboxWidth == 0.0 ) {
bboxWidth = 1.0;
}
float64 factor = bboxHeight / bboxWidth * width / height;
if ( factor < 1 ) {
// Compensate for that the display is higher than the bbox
// height = uint16( height * factor );
int32 extraHeight =
int32( rint( ( (bboxHeight / factor ) -
bboxHeight ) / 2 ) );
minLat -= extraHeight;
maxLat += extraHeight;
} else {
// Compensate for that the display is wider than the bbox
// width = uint16( width / factor );
uint32 lonDiff = bbox.getLonDiff();
if ( lonDiff == 0 ) {
lonDiff = 1;
}
int32 extraWidth =
int32( rint( ( (lonDiff * factor ) -
lonDiff ) / 2 ) );
minLon -= extraWidth;
maxLon += extraWidth;
bbox.setMinLon( minLon );
bbox.setMaxLon( maxLon );
}
bbox.setMinLat( MAX( minLat, (int32) s_bottomLat ) );
bbox.setMaxLat( MIN( maxLat, (int32) s_topLat ) );
bbox.setMinLon( minLon );
bbox.setMaxLon( maxLon );
float64 scale =
double(bbox.getHeight() * mc2scaletometer) /
screenYSize; // unit meters map / pixel
// Ugglefix.
if ( scale < 0 || scale > s_maxScale ) {
scale = s_maxScale;
}
return scale;
}
MC2BoundingBox
MapProjection::setBoundingBox(const MC2BoundingBox& inbbox)
{
MC2BoundingBox bbox(inbbox);
// Set the scale
m_scale = <API key>( m_screenSize.getX(),
m_screenSize.getY(),
bbox );
// Save the corner
{
ScopedCounter c(<API key>());
setCenter( bbox.getCenter() );
}
<API key>(<API key>::MAP_BOUNDARIES_SET);
return bbox;
}
pair<int, int>
MapProjection::getScreenExtentMC2() const
{
static const double mc2scaletometer = 6378137.0*2.0*
3.<API key> / 4294967296.0;
static const float meterstomc2scale = 1.0 / mc2scaletometer;
const float width = m_screenSize.getX() * meterstomc2scale;
const float height = m_screenSize.getY() * meterstomc2scale;
return pair<int,int>( static_cast<int>( width ),
static_cast<int>( height ) );
}
pair<float,float>
MapProjection::getWidthAndHeight() const
{
static const double mc2scaletometer = 6378137.0*2.0*
3.<API key> / 4294967296.0;
static const float meterstomc2scale = 1.0 / mc2scaletometer;
const float radAngle = ( getAngle() ) / 180.0 * M_PI;
const float scale = getPixelScale() * meterstomc2scale;
const float b = m_screenSize.getX() * scale;
const float h = m_screenSize.getY() * scale;
const float width =
( fabs( b * cos(radAngle) ) +
fabs( h * sin(radAngle) ) ) / getCosLat();
const float height =
fabs( b * sin(radAngle) ) +
fabs( h * cos(radAngle) );
return pair<float,float>(width, height );
}
MC2BoundingBox
MapProjection::getDrawingBBox() const
{
if( <API key> ) {
m_camera->projectionUpdated();
return m_camera->getBoundingBox();
} else {
pair<float,float> widthAndHeight = getWidthAndHeight();
const float height = widthAndHeight.second;
const float width = widthAndHeight.first;
// Height
MC2BoundingBox bbox;
{
const int32 centerLat = getCenter().lat;
const float halfHeight = height * 0.5 ;
const int32 intHalfHeight = int32( halfHeight );
if ( halfHeight + centerLat > ( MAX_INT32 / 2 ) ) {
bbox.setMaxLat( MAX_INT32 / 2 );
} else {
bbox.setMaxLat( centerLat + intHalfHeight );
}
if ( centerLat - halfHeight < ( MIN_INT32 / 2 ) ) {
bbox.setMinLat( MIN_INT32 / 2 );
} else {
bbox.setMinLat( centerLat - intHalfHeight );
}
bbox.updateCosLat();
}
//Width
{
const int32 centerLon = getCenter().lon;
const float halfWidth = width * 0.5 ;
const int32 intHalfWidth = int32( halfWidth );
int MIN_NUM = MIN_INT32 + 1;
int MAX_NUM = MAX_INT32 - 1;
if ( halfWidth + centerLon > ( MAX_NUM ) ) {
bbox.setMaxLon( MAX_NUM );
} else {
bbox.setMaxLon( centerLon + intHalfWidth );
}
if ( centerLon - halfWidth < ( MIN_NUM ) ) {
bbox.setMinLon( MIN_NUM );
} else {
bbox.setMinLon( centerLon - intHalfWidth );
}
}
return bbox;
}
}
void
MapProjection::getDrawingBBoxes(std::vector<MC2BoundingBox>& outBoxes) const
{
if( <API key> ) {
m_camera->projectionUpdated();
MC2BoundingBox camBox = m_camera->getBoundingBox();
float minLon = camBox.getMinLon();
float maxLon = camBox.getMaxLon();
bool shouldSplit = minLon > maxLon;
if (!shouldSplit){
outBoxes.push_back(camBox);
} else {
// We split the cambox into two boxes, one on each
// side of the datum line.
MC2BoundingBox leftBox(MC2Coordinate(camBox.getMinLat(),
camBox.getMinLon()),
MC2Coordinate(camBox.getMaxLat(),
MAX_INT32));
MC2BoundingBox rightBox(MC2Coordinate(camBox.getMinLat(),
MIN_INT32),
MC2Coordinate(camBox.getMaxLat(),
camBox.getMaxLon()));
outBoxes.push_back(leftBox);
outBoxes.push_back(rightBox);
}
} else {
pair<float,float> widthAndHeight = getWidthAndHeight();
const float height = widthAndHeight.second;
// Height
MC2BoundingBox bbox;
{
const int32 centerLat = getCenter().lat;
const float halfHeight = height * 0.5 ;
const int32 intHalfHeight = int32( halfHeight );
if ( halfHeight + centerLat > ( MAX_INT32 / 2 ) ) {
bbox.setMaxLat( MAX_INT32 / 2 );
} else {
bbox.setMaxLat( centerLat + intHalfHeight );
}
if ( centerLat - halfHeight < ( MIN_INT32 / 2 ) ) {
bbox.setMinLat( MIN_INT32 / 2 );
} else {
bbox.setMinLat( centerLat - intHalfHeight );
}
bbox.updateCosLat();
}
// Widths
{
float width = MIN( widthAndHeight.first, float(MAX_UINT32) );
int32 centerLon = getCenter().lon;
int32 curMinLon = int32(int64(centerLon) - int64(width / 2) );
// Add bounding boxes until there is no width left
while ( width > 0.0 ) {
outBoxes.push_back( bbox );
MC2BoundingBox& curBox = outBoxes.back();
int32 curWidth = int32( MIN( width, float( MAX_INT32 / 4 ) ) );
if ( curWidth == 0 ) {
outBoxes.pop_back();
break;
}
curBox.setMinLon( curMinLon );
curBox.setMaxLon( curMinLon + curWidth );
if ( curBox.getMinLon() > curBox.getMaxLon() ) {
curBox.setMaxLon( MAX_INT32 );
curMinLon = MIN_INT32;
width -= ( curBox.getMaxLon() - curBox.getMinLon() );
} else {
curMinLon += curWidth;
width -= curWidth;
}
}
}
}
}
double
MapProjection::setPixelScale(double scale)
{
if(scale > <API key> && getAngle() != 0.0) {
setAngle(0.0);
}
double oldScale = m_scale;
#ifdef <API key>
if ( scale != m_scale ) {
// Truncate the scale so it will be easier to
// reproduce the same scale level.
double rintScale = rint( scale );
if ( rintScale != rint( m_scale ) ) {
m_scale = rintScale;
} else if ( scale < m_scale ) {
m_scale = rintScale - 1;
} else {
m_scale = rintScale + 1;
}
}
#else
m_scale = scale;
#endif
const double minScale = 0.1;
const double maxScale = s_maxScale;
if ( m_scale < minScale ) {
m_scale = minScale;
} else if ( m_scale > maxScale ) {
m_scale = maxScale;
}
if ( m_scale != oldScale ) {
<API key>(<API key>::SET_ZOOM);
}
return m_scale;
}
double
MapProjection::getPixelScale() const
{
return m_scale;
}
void
MapProjection::<API key>( uint32 factor )
{
factor = 1;
<API key> = factor;
<API key>(<API key>::<API key>);
}
uint32
MapProjection::<API key>() const
{
return <API key>;
}
double
MapProjection::<API key>( double scale )
{
setPixelScale( scale / double( <API key>() ) );
return <API key>();
}
double
MapProjection::<API key>() const
{
double scale = getPixelScale() * double( <API key>() );
if ( scale > s_maxScale ) {
scale = s_maxScale;
}
return scale;
}
double
MapProjection::zoom(double factor)
{
// Zoom is a higher level command which uses setPixelScale internally.
// Since setPixelScale notifies that a pixel scale has been set, we need
// to mute that event so that we can send the proper higher level event.
{
ScopedCounter c(<API key>());
setPixelScale( factor * getPixelScale() );
}
<API key>(<API key>::ZOOM);
return m_scale;
}
double
MapProjection::zoom(double factor,
const MC2Coordinate& zoomCoord,
const MC2Point& zoomPoint )
{
double newScale = 0.0;
// Zooming to point is an ever higher level command than zooming, so
// we need to use the same procedure here
{
ScopedCounter c(<API key>());
newScale = zoom( factor );
setPoint( zoomCoord, zoomPoint );
}
<API key>(<API key>::ZOOM_POINT);
return newScale;
}
void
MapProjection::setPixelBox( const MC2Point& oneCorner,
const MC2Point& otherCorner )
{
{
ScopedCounter c(<API key>());
PixelBox pixBox( oneCorner, otherCorner );
MC2BoundingBox bbox;
for( int i = 0; i < 4; ++i ) {
MC2Coordinate tmpCoord;
<API key>( tmpCoord, pixBox.getCorner(i) );
bbox.update( tmpCoord );
}
double oldangle = m_angle;
setAngle(0);
setBoundingBox( bbox );
setAngle( oldangle );
}
<API key>(<API key>::SCREEN_BOX_SET);
}
void
MapProjection::move(int deltaX,
int deltaY )
{
{
ScopedCounter c(<API key>());
// Translate the screen coordinates into lat/lon.
MC2Coordinate center;
<API key>(
center,
deltaX + (m_screenSize.getX() >> 1),
deltaY + (m_screenSize.getY() >> 1),
getCosLat( m_centerCoord.lat ) );
setCenter( center );
}
<API key>(<API key>::MOVE);
}
void
MapProjection::setCenter(const MC2Coordinate& newCenter)
{
MC2Coordinate prev = m_centerCoord;
m_centerCoord = newCenter;
if(m_centerCoord.lat + (m_bbox.getHeight()/2) > s_topLat) {
m_centerCoord.lat = s_topLat - (m_bbox.getHeight()/2);
} else if(m_centerCoord.lat - (m_bbox.getHeight()/2) < s_bottomLat) {
m_centerCoord.lat = s_bottomLat + (m_bbox.getHeight()/2);
}
if(prev != m_centerCoord) {
<API key>(<API key>::SET_CENTER);
}
}
void
MapProjection::setPoint(const MC2Coordinate& newCoord,
const MC2Point& screenPoint )
{
// Now set the center to that center coordinate. Will update
// all the members.
{
ScopedCounter c(<API key>());
// Translate the center to a screen coord.
MC2Point centerPoint(0,0);
<API key>( centerPoint,
m_centerCoord );
MC2Coordinate newCenter;
<API key>(screenPoint.getX(),
screenPoint.getY(),
centerPoint.getX(),
centerPoint.getY(),
newCoord,
newCenter);
setCenter( newCenter );
}
<API key>(<API key>::SET_POINT);
}
void
MapProjection::setAngle(double angleDeg)
{
m_angle = angleDeg;
if(m_scale > <API key>) {
m_angle = 0.0;
}
if(m_angle > 360) {
m_angle -= 360;
}
if(m_angle < 0) {
m_angle += 360;
}
<API key>(<API key>::SET_ANGLE);
}
void
MapProjection::setAngle(double angleDeg, const MC2Point& rotationPoint )
{
{
// Translate the center to a screen coord.
MC2Point centerPoint(0,0);
<API key>( centerPoint,
m_centerCoord );
int deltaX = centerPoint.getX() - rotationPoint.getX();
int deltaY = centerPoint.getY() - rotationPoint.getY();
ScopedCounter c(<API key>());
move(-deltaX, -deltaY);
setAngle( angleDeg );
move(deltaX, deltaY);
}
<API key>(<API key>::ROTATE_POINT);
}
double
MapProjection::getAngle() const
{
return m_angle;
}
void
MapProjection::setPoint(const MC2Coordinate& newCoord,
const MC2Point& screenPoint,
double angleDeg )
{
{
ScopedCounter c(<API key>());
setPoint( newCoord, screenPoint );
setAngle( angleDeg, screenPoint );
}
<API key>(<API key>::SET_POINT);
}
void
MapProjection::setScreenSize(const MC2Point& size)
{
if ( size != m_screenSize && size != MC2Point(0,0) ) {
m_screenSize = size;
m_pixelBoundingBox = PixelBox( MC2Point(0, 0),
MC2Point(size.getX(), size.getY()) );
<API key>(<API key>::SET_SCREEN_SIZE);
}
}
MC2Coordinate
MapProjection::calcLowerLeft() const
{
// Constant forever
static const double mc2scaletometer = 6378137.0*2.0*
3.<API key> / 4294967296.0;
const double invScale = 1.0/m_scale;
const double mc2scale = mc2scaletometer * invScale;
const int screenWidth = m_screenSize.getX();
const int screenHeight = m_screenSize.getY();
return MC2Coordinate( int32(double(m_centerCoord.lat) -
(1/mc2scale * screenHeight * 0.5)),
int32(double(m_centerCoord.lon) -
(1/mc2scale/getCosLat(m_centerCoord.lat) *
screenWidth * 0.5 ) ) );
}
bool MapProjection::get3dMode() const
{
return m_3dOn;
}
void MapProjection::set3dMode( bool on )
{
m_3dOn = on;
if( m_3dOn ) {
m_camera->setVariable3DMode(1.0f);
} else {
m_camera->setVariable3DMode(0.0f);
}
}
void MapProjection::setVariable3dMode(float step)
{
if (step == 0.0f){
m_3dOn = false;
} else {
m_3dOn = true;
}
m_camera->setVariable3DMode(step);
}
MC2BoundingBox MapProjection::getCenterBox() const
{
return MC2BoundingBox( getCenter(), 7 );
}
MC2Coordinate MapProjection::getCameraCenter() const
{
if( m_3dOn ) {
MC2Coordinate center;
<API key>( center,
(m_screenSize.getX() >> 1),
165 + (m_screenSize.getY() >> 1),
getCosLat( m_centerCoord.lat ) );
return center;
} else {
return m_centerCoord;
}
}
MC2BoundingBox MapProjection::getCameraCenterBox() const
{
return MC2BoundingBox( getCameraCenter(), 7 );
}
double MapProjection::getAspectRatio() const
{
const double w = m_screenSize.getX();
const double h = m_screenSize.getY();
return w / h;
}
void MapProjection::<API key>( bool enabled )
{
<API key> = enabled;
updateBBox();
}
bool MapProjection::usingFOVBoundingBox() const
{
return <API key>;
}
Camera& MapProjection::getCamera()
{
return *m_camera;
}
const Camera& MapProjection::getCamera() const
{
return *m_camera;
}
void MapProjection::cameraUpdated()
{
<API key>(<API key>::CAMERA_CHANGED);
}
void MapProjection::setProjectionType(projection_t projectionType)
{
m_projectionType = projectionType;
if (projectionType == MC2_PROJECTION) {
s_maxScale = 24000.0;
s_topLat = 912909609 ;
s_bottomLat = -912909609;
setCosLatEnabled(true);
} else if (projectionType == MERCATOR_PROJECTION) {
s_maxScale = 100000.0;
WFAPI::WGS84Coordinate topLatWgs(85.05112, 0);
MC2Coordinate topLatMC2(topLatWgs);
MercatorCoord topLatMerc(topLatMC2);
s_topLat = topLatMerc.lat;
s_bottomLat = -topLatMerc.lat;
setCosLatEnabled(false);
} else {
// Cannot happen!
// MC2_ASSERT(false);
}
}
const PixelBox& MapProjection::getPixelBoundingBox() const
{
return m_pixelBoundingBox;
}
void MapProjection::addListener( <API key>* listener )
{
m_listeners.push_back(listener);
}
void MapProjection::notifyListeners(<API key>::projectionEvent event)
{
if(!<API key>()) {
return;
}
for(<API key>::iterator itr = m_listeners.begin();
itr != m_listeners.end(); itr++)
{
(*itr)->projectionUpdated(event);
}
}
bool MapProjection::<API key>() const
{
return <API key> == 0;
}
int& MapProjection::<API key>()
{
return <API key>;
}
MapProjection::~MapProjection()
{
delete m_camera;
}
const char* <API key>::toString(projectionEvent event)
{
switch(event) {
case UNKNOWN:
return "UNKNOWN";
break;
case MOVE:
return "MOVE";
break;
case <API key>:
return "<API key>";
break;
case SET_CENTER:
return "SET_CENTER";
break;
case ZOOM:
return "ZOOM";
break;
case ZOOM_POINT:
return "ZOOM_POINT";
break;
case SET_ANGLE:
return "SET_ANGLE";
break;
case ROTATE_POINT:
return "ROTATE_POINT";
break;
case SET_ZOOM:
return "SET_ZOOM";
break;
case SET_POINT:
return "SET_POINT";
break;
case SCREEN_BOX_SET:
return "SCREEN_BOX_SET";
break;
case SET_SCREEN_SIZE:
return "SET_SCREEN_SIZE";
break;
case CAMERA_CHANGED:
return "CAMERA_CHANGED";
break;
case MAP_BOUNDARIES_SET:
return "MAP_BOUNDARIES_SET";
break;
default:
return "";
}
}
void MapProjection::printState() const
{
coreprintln("Current state:");
coreprintln("Center-coord: (%d, %d)",
m_centerCoord.lat, m_centerCoord.lon);
coreprintln("Scale: %lf", m_scale);
coreprintln("Angle: %lf", m_angle);
coreprintln("BBox: [(%d %d), (%d, %d)]",
m_bbox.getMaxLat(), m_bbox.getMinLon(),
m_bbox.getMinLat(), m_bbox.getMaxLon());
coreprintln("cosLat: %lf", getCosLat());
coreprintln("PixelBox: [(%d %d), (%d, %d)]",
m_pixelBoundingBox.getTopLeft().getX(),
m_pixelBoundingBox.getTopLeft().getY(),
m_pixelBoundingBox.getBottomRight().getX(),
m_pixelBoundingBox.getBottomRight().getY());
coreprintln("Screen-size: %dx%d",
m_screenSize.getX(), m_screenSize.getY());
// coreprintln("DPI correction factor: %u", <API key>);
// coreprintln("3D: %s", m_3dOn ? : "on" : "off");
// coreprintln("Use FOV bounding box: %d", <API key>);
// coreprintln("Camera: %p", m_camera);
}
void MapProjection::beginBatchedEvent(<API key>::projectionEvent event)
{
<API key>()++;
m_batchedEvent = event;
}
void MapProjection::endBatchedEvent()
{
<API key>()
notifyListeners(m_batchedEvent);
m_batchedEvent = <API key>::UNKNOWN;
}
MapProjection::projection_t MapProjection::getProjectionType() const
{
return m_projectionType;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.