repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
flod1/FacebookApi | src/FbBasic/GraphNodes/PageStartInfo.php | 655 | <?php
/**
* Created by IntelliJ IDEA.
* User: Besitzer
* Date: 12.09.2016
* Time: 08:00
*/
namespace FbBasic\GraphNodes;
use Facebook\GraphNodes\GraphNode;
class PageStartInfo extends GraphNode
{
protected static $graphObjectFields = [
"type",
"date",
];
/**
* @var array Maps object key names to Graph object types.
*/
protected static $graphObjectMap = [
'date' => '\FbBasic\GraphNodes\PageStartDate',
];
/**
* Getter for $graphObjectFields.
*
* @return array
*/
public static function getObjectFields()
{
return static::$graphObjectFields;
}
} | bsd-3-clause |
QuorumDMS/grapesjs | test/specs/style_manager/view/SectorView.js | 2422 | import SectorView from 'style_manager/view/SectorView';
import Sector from 'style_manager/model/Sector';
describe('SectorView', () => {
var fixtures;
var model;
var view;
beforeEach(() => {
model = new Sector();
view = new SectorView({
model
});
document.body.innerHTML = '<div id="fixtures"></div>';
fixtures = document.body.querySelector('#fixtures');
fixtures.appendChild(view.render().el);
});
afterEach(() => {
view.remove();
});
test('Rendered correctly', () => {
var sector = view.el;
expect(sector.querySelector('.title')).toBeTruthy();
var props = sector.querySelector('.properties');
expect(props).toBeTruthy();
expect(sector.classList.contains('open')).toEqual(true);
});
test('No properties', () => {
var props = view.el.querySelector('.properties');
expect(props.innerHTML).toEqual('');
});
test('Update on open', () => {
var sector = view.el;
var props = sector.querySelector('.properties');
model.set('open', false);
expect(sector.classList.contains('open')).toEqual(false);
expect(props.style.display).toEqual('none');
});
test('Toggle on click', () => {
var sector = view.el;
view.$el.find('.title').click();
expect(sector.classList.contains('open')).toEqual(false);
});
describe('Init with options', () => {
beforeEach(() => {
model = new Sector({
open: false,
name: 'TestName',
properties: [
{ type: 'integer' },
{ type: 'integer' },
{ type: 'integer' }
]
});
view = new SectorView({
model
});
//$fixture.empty().appendTo($fixtures);
//$fixture.html(view.render().el);
document.body.innerHTML = '<div id="fixtures"></div>';
fixtures = document.body.querySelector('#fixtures');
fixtures.appendChild(view.render().el);
});
test('Rendered correctly', () => {
var sector = view.el;
var props = sector.querySelector('.properties');
expect(sector.querySelector('.title').innerHTML).toContain('TestName');
expect(props).toBeTruthy();
expect(sector.classList.contains('open')).toEqual(false);
expect(props.style.display).toEqual('none');
});
test('Has properties', () => {
var props = view.el.querySelector('.properties');
expect(props.children.length).toEqual(3);
});
});
});
| bsd-3-clause |
Klutzdon/SIOTS_HHZX | WindowsUI.TQS/SystemForm/MessageDialog.cs | 1481 | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsUI.TQS.SystemForm
{
public partial class MessageDialog : Form
{
public MessageDialog()
{
InitializeComponent();
}
public void Show(string title , string message)
{
lblMessage.Text = FormatMessage(message);
lblTitle.Text = title;
this.ShowDialog();
}
public string FormatMessage(string message)
{
string returnStr = "";
if (message.Length > 15)
{
for (int index = 0; index < message.Length; index = index + 15)
{
int strLeng = 15;
if (message.Length - index < 15)
{
strLeng = message.Length - index;
}
returnStr += message.Substring(index, strLeng);
returnStr += "\r\n";
}
}
else
{
returnStr = message;
}
return returnStr;
}
public void SetNoCloseModel()
{
this.btnOK.Visible = false;
}
private void btnOK_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
| bsd-3-clause |
luotuo44/FlvExploere | Header.cpp | 908 | //Author: luotuo44@gmail.com
//Use of this source code is governed by a BSD-style license
#include"Header.h"
#include<string>
#include<exception>
#include<stdexcept>
#include<fstream>
#include<iostream>
#include"helper.h"
using uchar = unsigned char;
namespace FLV
{
Header::Header(std::ifstream &in)
: m_in(in)
{
}
void Header::parse()
{
std::string format(3, '\0');
m_in.read(&format[0], 3);
if(format != "FLV")
{
throw std::invalid_argument("not FLV format");
}
char version;
m_in.read(&version, 1);
m_version = static_cast<int>(version);
char flag;
m_in.read(&flag, 1);
m_has_video_stream = Helper::getNBits<1>(flag, 0);
m_has_audio_stream = Helper::getNBits<1>(flag, 2);
uchar header_size_arr[4];
m_in.read(reinterpret_cast<char*>(header_size_arr), 4);
m_header_size = Helper::getSizeValue(header_size_arr);
}
}
| bsd-3-clause |
rbelouin/go.js | src/models/board.js | 3222 | function initBoard() {
var Board = function(size) {
var range = _.range(size);
var board = {};
_.each(range, function(x) {
_.each(range, function(y) {
Board.setIntersection(board, x, y, Board.types.EMPTY);
});
});
return board;
}
Board.types = {
EMPTY: "EMPTY",
BLACK: "BLACK",
WHITE: "WHITE"
};
Board.clone = function(board) {
return _.clone(board, true);
};
Board.getIntersection = function(board, x, y) {
return board[x + "," + y];
};
Board.setIntersection = function(board, x, y, type) {
board[x + "," + y] = {
x: x,
y: y,
type: type
};
};
Board.getAndRemoveIntersection = function(board, x, y) {
var intersection = Board.getIntersection(board, x, y);
board[x + "," + y] = null;
delete board[x + "," + y];
return intersection;
};
Board.emptyIntersections = function(board, intersections) {
_.each(intersections, function(intersection) {
Board.setIntersection(board, intersection.x, intersection.y, Board.types.EMPTY);
});
return board;
};
Board.getNeighborIntersections = function(board, x, y) {
return _.compact([
Board.getIntersection(board, x, y - 1),
Board.getIntersection(board, x + 1, y),
Board.getIntersection(board, x, y + 1),
Board.getIntersection(board, x - 1, y)
]);
};
Board.getGroups = function(board) {
var getGroup = function(boardCopy) {
var addIntersectionToGroup = function(group, x, y) {
var neighbors = Board.getNeighborIntersections(boardCopy, x, y);
var initialNeighbors = Board.getNeighborIntersections(board, x, y);
var intersection = Board.getAndRemoveIntersection(boardCopy, x, y);
if(!intersection) {
return group;
}
else {
var newGroup = {
intersections: group.intersections.concat([intersection]),
neighborTypes: _.foldl(initialNeighbors, function(types, neighbor) {
return neighbor.type == intersection.type ? types : _.union(types, [neighbor.type]);
}, group.neighborTypes)
};
return _.foldl(neighbors, function(group, neighbor) {
return neighbor.type == intersection.type ? addIntersectionToGroup(group, neighbor.x, neighbor.y) : group;
}, newGroup);
}
};
var first = _.find(boardCopy, function() { return true; });
var emptyGroup = {intersections: [], neighborTypes: []};
return first && addIntersectionToGroup(emptyGroup, first.x, first.y);
};
var addGroup = function(groups, boardCopy) {
var group = getGroup(boardCopy);
if(!group) {
return groups;
}
else {
var groupType = group.intersections[0].type;
groups[groupType] = _.union(groups[groupType], [group]);
return addGroup(groups, boardCopy);
}
};
return addGroup({}, Board.clone(board));
};
Board.getEncircledGroups = function(groups) {
return _.mapValues(groups, function(typedGroups) {
return _.filter(typedGroups, function(group) {
return _.size(group.neighborTypes) == 1;
});
});
};
return Board;
}
| bsd-3-clause |
leesab/irods | iRODS/lib/api/include/phyBundleColl.hpp | 3540 | /*** Copyright (c), The Regents of the University of California ***
*** For more information please refer to files in the COPYRIGHT directory ***/
/* phyBundleColl.h - This file may be generated by a program or
* script
*/
#ifndef PHY_BUNDLE_COLL_HPP
#define PHY_BUNDLE_COLL_HPP
/* This is a Object File I/O call */
#include "rods.hpp"
#include "rcMisc.hpp"
#include "procApiRequest.hpp"
#include "apiNumber.hpp"
#include "initServer.hpp"
#include "structFileExtAndReg.hpp"
#include "miscUtil.hpp"
#define BUNDLE_RESC "bundleResc"
#define TAR_BUNDLE_TYPE "tar bundle"
#define BUNDLE_STR "bundle" // JMC - backport 4658
#define BUNDLE_RESC_CLASS "bundle"
#define MAX_BUNDLE_SIZE 4 /* 4 G */
#define MAX_SUB_FILE_CNT 5120 // JMC - backport 4480
typedef struct BunReplCache {
rodsLong_t dataId;
char objPath[MAX_NAME_LEN]; /* optional for ADMIN_KW */
char chksumStr[NAME_LEN]; // JMC - backport 4528
int srcReplNum;
struct BunReplCache *next;
} bunReplCache_t;
typedef struct BunReplCacheHeader {
int numSubFiles;
rodsLong_t totSubFileSize;
bunReplCache_t *bunReplCacheHead;
} bunReplCacheHeader_t;
typedef struct CurSubFileCond {
char collName[MAX_NAME_LEN];
char dataName[MAX_NAME_LEN];
rodsLong_t dataId;
char subPhyPath[MAX_NAME_LEN];
char cachePhyPath[MAX_NAME_LEN];
int cacheReplNum;
rodsLong_t subFileSize;
int bundled;
} curSubFileCond_t;
#if defined(RODS_SERVER)
#define RS_PHY_BUNDLE_COLL rsPhyBundleColl
/* prototype for the server handler */
int
rsPhyBundleColl( rsComm_t *rsComm,
structFileExtAndRegInp_t *phyBundleCollInp );
int
remotePhyBundleColl( rsComm_t *rsComm,
structFileExtAndRegInp_t *phyBundleCollInp, rodsServerHost_t *rodsServerHost );
int
_rsPhyBundleColl( rsComm_t *rsComm, structFileExtAndRegInp_t *phyBundleCollInp,
rescGrpInfo_t *rescGrpInfo );
int
createPhyBundleDataObj( rsComm_t *rsComm, char *collection, rescGrpInfo_t *rescGrpInfo,
const char* rescHier, dataObjInp_t *dataObjInp, char *dataType ); // JMC - backport 4658
int
createPhyBundleDir( rsComm_t *rsComm, char *bunFilePath,
char *outPhyBundleDir );
int
rsMkBundlePath( rsComm_t *rsComm, char *collection, char *outPath,
int myRanNum );
int
replDataObjForBundle( rsComm_t *rsComm, char *collName, char *dataName,
char *rescName, char* rescHier, char* destRescHier, int adminFlag, dataObjInfo_t *outCacheObjInfo );
int
isDataObjBundled( rsComm_t *rsComm, collEnt_t *collEnt );
int
setSubPhyPath( char *phyBunDir, rodsLong_t dataId, char *subBunPhyPath );
int
addSubFileToDir( curSubFileCond_t *curSubFileCond,
bunReplCacheHeader_t *bunReplCacheHeader );
int
replAndAddSubFileToDir( rsComm_t *rsComm, curSubFileCond_t *curSubFileCond,
char *myRescName, char *phyBunDir, bunReplCacheHeader_t *bunReplCacheHeader );
int
bundleAndRegSubFiles( rsComm_t *rsComm, int l1descInx, char *phyBunDir,
char *collection, bunReplCacheHeader_t *bunReplCacheHeader, int chksumFlag ); // JMC - backport 4528
int
phyBundle( rsComm_t *rsComm, dataObjInfo_t *dataObjInfo, char *phyBunDir,
char *collection, int oprType ); // JMC - backport 4643
#else
#define RS_PHY_BUNDLE_COLL NULL
#endif
/* prototype for the client call */
int
rcPhyBundleColl( rcComm_t *conn,
structFileExtAndRegInp_t *phyBundleCollInp );
#endif /* PHY_BUNDLE_COLL_H */
| bsd-3-clause |
NWebsec/NWebsec | src/NWebsec.Mvc.Common/Helpers/CspConfigurationOverrideHelper.cs | 8410 | // Copyright (c) André N. Klingsheim. See License.txt in the project root for license information.
using System;
using System.Security.Cryptography;
using NWebsec.Core.Common.HttpHeaders.Configuration;
using NWebsec.Core.Common.Web;
using NWebsec.Mvc.Common.Csp;
namespace NWebsec.Mvc.Common.Helpers
{
public class CspConfigurationOverrideHelper : ICspConfigurationOverrideHelper
{
private readonly IContextConfigurationHelper _contextConfigurationHelper;
private readonly ICspConfigMapper _configMapper;
private readonly ICspDirectiveOverrideHelper _cspDirectiveOverrideHelper;
public CspConfigurationOverrideHelper()
{
_cspDirectiveOverrideHelper = new CspDirectiveOverrideHelper();
_contextConfigurationHelper = new ContextConfigurationHelper();
_configMapper = new CspConfigMapper();
}
internal CspConfigurationOverrideHelper(IContextConfigurationHelper contextConfigurationHelper, ICspConfigMapper mapper, ICspDirectiveOverrideHelper directiveOverrideHelper)
{
_cspDirectiveOverrideHelper = directiveOverrideHelper;
_contextConfigurationHelper = contextConfigurationHelper;
_configMapper = mapper;
}
/*[CanBeNull]*/
public ICspConfiguration GetCspConfigWithOverrides(/*[NotNull]*/IHttpContextWrapper context, bool reportOnly)
{
var overrides = _contextConfigurationHelper.GetCspConfigurationOverride(context, reportOnly, true);
//No overrides
if (overrides == null)
{
return null;
}
var newConfig = new CspConfiguration(false);
var originalConfig = _contextConfigurationHelper.GetCspConfiguration(context, reportOnly);
//We might be "attributes only", so no other config around.
if (originalConfig != null)
{
_configMapper.MergeConfiguration(originalConfig, newConfig);
}
//Deal with header override
_configMapper.MergeOverrides(overrides, newConfig);
return newConfig;
}
internal void SetCspHeaderOverride(IHttpContextWrapper context, ICspHeaderConfiguration cspConfig, bool reportOnly)
{
var overrides = _contextConfigurationHelper.GetCspConfigurationOverride(context, reportOnly, false);
overrides.EnabledOverride = true;
overrides.Enabled = cspConfig.Enabled;
}
internal void SetCspDirectiveOverride(IHttpContextWrapper context, CspDirectives directive, CspDirectiveOverride config, bool reportOnly)
{
var overrides = _contextConfigurationHelper.GetCspConfigurationOverride(context, reportOnly, false);
var directiveToOverride = _configMapper.GetCspDirectiveConfig(overrides, directive);
if (directiveToOverride == null)
{
var baseConfig = _contextConfigurationHelper.GetCspConfiguration(context, reportOnly);
directiveToOverride = _configMapper.GetCspDirectiveConfigCloned(baseConfig, directive);
}
var newConfig = _cspDirectiveOverrideHelper.GetOverridenCspDirectiveConfig(config, directiveToOverride);
_configMapper.SetCspDirectiveConfig(overrides, directive, newConfig);
}
public void SetCspPluginTypesOverride(IHttpContextWrapper context, CspPluginTypesOverride config, bool reportOnly)
{
var overrides = _contextConfigurationHelper.GetCspConfigurationOverride(context, reportOnly, false);
var directiveToOverride = overrides.PluginTypesDirective;
if (directiveToOverride == null)
{
var baseConfig = _contextConfigurationHelper.GetCspConfiguration(context, reportOnly);
directiveToOverride = _configMapper.GetCspPluginTypesConfigCloned(baseConfig);
}
var newConfig = _cspDirectiveOverrideHelper.GetOverridenCspPluginTypesConfig(config, directiveToOverride);
overrides.PluginTypesDirective = newConfig;
}
internal void SetCspSandboxOverride(IHttpContextWrapper context, CspSandboxOverride config, bool reportOnly)
{
var overrides = _contextConfigurationHelper.GetCspConfigurationOverride(context, reportOnly, false);
var directiveToOverride = overrides.SandboxDirective;
if (directiveToOverride == null)
{
var baseConfig = _contextConfigurationHelper.GetCspConfiguration(context, reportOnly);
directiveToOverride = _configMapper.GetCspSandboxConfigCloned(baseConfig);
}
var newConfig = _cspDirectiveOverrideHelper.GetOverridenCspSandboxConfig(config, directiveToOverride);
overrides.SandboxDirective = newConfig;
}
public void SetCspMixedContentOverride(IHttpContextWrapper context, CspMixedContentOverride config, Boolean reportOnly)
{
var overrides = _contextConfigurationHelper.GetCspConfigurationOverride(context, reportOnly, false);
var directiveToOverride = overrides.MixedContentDirective;
if (directiveToOverride == null)
{
var baseConfig = _contextConfigurationHelper.GetCspConfiguration(context, reportOnly);
directiveToOverride = _configMapper.GetCspMixedContentConfigCloned(baseConfig);
}
var newConfig = _cspDirectiveOverrideHelper.GetOverridenCspMixedContentConfig(config, directiveToOverride);
overrides.MixedContentDirective = newConfig;
}
internal void SetCspReportUriOverride(IHttpContextWrapper context, ICspReportUriDirectiveConfiguration reportUriConfig, bool reportOnly)
{
var overrides = _contextConfigurationHelper.GetCspConfigurationOverride(context, reportOnly, false);
overrides.ReportUriDirective = reportUriConfig;
}
public string GetCspScriptNonce(IHttpContextWrapper context)
{
var overrides = _contextConfigurationHelper.GetCspConfigurationOverride(context, false, false);
if (overrides.ScriptSrcDirective != null && overrides.ScriptSrcDirective.Nonce != null)
{
return overrides.ScriptSrcDirective.Nonce;
}
var nonce = GenerateCspNonceValue();
SetCspDirectiveNonce(context, nonce, CspDirectives.ScriptSrc, false);
SetCspDirectiveNonce(context, nonce, CspDirectives.ScriptSrc, true);
return nonce;
}
public string GetCspStyleNonce(IHttpContextWrapper context)
{
var overrides = _contextConfigurationHelper.GetCspConfigurationOverride(context, false, false);
if (overrides.StyleSrcDirective != null && overrides.StyleSrcDirective.Nonce != null)
{
return overrides.StyleSrcDirective.Nonce;
}
var nonce = GenerateCspNonceValue();
SetCspDirectiveNonce(context, nonce, CspDirectives.StyleSrc, false);
SetCspDirectiveNonce(context, nonce, CspDirectives.StyleSrc, true);
return nonce;
}
private void SetCspDirectiveNonce(IHttpContextWrapper context, string nonce, CspDirectives directive, bool reportOnly)
{
var overrides = _contextConfigurationHelper.GetCspConfigurationOverride(context, reportOnly, false);
var directiveConfig = _configMapper.GetCspDirectiveConfig(overrides, directive);
if (directiveConfig == null)
{
var baseConfig = _contextConfigurationHelper.GetCspConfiguration(context, reportOnly);
directiveConfig = _configMapper.GetCspDirectiveConfigCloned(baseConfig, directive) ?? new CspDirectiveConfiguration();
_configMapper.SetCspDirectiveConfig(overrides, directive, directiveConfig);
}
directiveConfig.Nonce = nonce;
}
private string GenerateCspNonceValue()
{
using (var rng = RandomNumberGenerator.Create())
{
var nonceBytes = new byte[18];
rng.GetBytes(nonceBytes);
return Convert.ToBase64String(nonceBytes);
}
}
}
}
| bsd-3-clause |
handsomegyr/ent | module/Idatabase/src/Idatabase/Controller/StatisticController.php | 15311 | <?php
/**
* iDatabase项目内数据集合管理
*
* @author young
* @version 2013.11.19
*
*/
namespace Idatabase\Controller;
use My\Common\Controller\Action;
use Zend\Json\Json;
class StatisticController extends Action
{
private $_collection;
private $_collection_id;
private $_project_id;
private $_statistic;
private $_statistic_id;
private $_seriesType = array(
'column',
'line',
'pie'
);
public function init()
{
$this->_project_id = isset($_REQUEST['__PROJECT_ID__']) ? trim($_REQUEST['__PROJECT_ID__']) : '';
$this->_collection_id = isset($_REQUEST['__COLLECTION_ID__']) ? trim($_REQUEST['__COLLECTION_ID__']) : '';
$this->_statistic_id = isset($_REQUEST['__STATISTIC_ID__']) ? trim($_REQUEST['__STATISTIC_ID__']) : '';
if (empty($this->_project_id))
throw new \Exception('$this->_project_id值未设定');
if (empty($this->_collection_id))
throw new \Exception('$this->_collection_id值未设定');
$this->_statistic = $this->model('Idatabase\Model\Statistic');
}
/**
* 读取统计列表
*
* @author young
* @name 读取统计列表
* @version 2014.01.25 young
*/
public function indexAction()
{
$query = array(
'project_id' => $this->_project_id,
'collection_id' => $this->_collection_id
);
$datas = $this->_statistic->findAll($query);
return $this->rst($datas, 0, true);
}
/**
* 查询某一条统计信息
*
* @author young
* @name 查询某一条统计信息
* @version 2014.01.29 young
*/
public function getAction()
{
$cursor = $this->_statistic->find(array(
'_id' => myMongoId($this->_statistic_id)
));
$datas = iterator_to_array($cursor, false);
return $this->rst($datas, 0, true);
}
/**
* 添加统计信息
*
* @author young
* @name 添加统计信息
* @version 2014.01.25 young
*/
public function addAction()
{
$project_id = trim($this->params()->fromPost('__PROJECT_ID__', ''));
$collection_id = trim($this->params()->fromPost('__COLLECTION_ID__', ''));
$name = trim($this->params()->fromPost('name', ''));
$defaultQuery = trim($this->params()->fromPost('defaultQuery', ''));
$yAxisTitle = trim($this->params()->fromPost('yAxisTitle', '')); // Y轴名称
$yAxisType = trim($this->params()->fromPost('yAxisType', '')); // Y轴统计方法
$yAxisField = trim($this->params()->fromPost('yAxisField', '')); // Y轴统计字段
$xAxisTitle = trim($this->params()->fromPost('xAxisTitle', ''));
$xAxisType = trim($this->params()->fromPost('xAxisType', ''));
$xAxisField = trim($this->params()->fromPost('xAxisField', ''));
$seriesType = trim($this->params()->fromPost('seriesType', ''));
$seriesField = trim($this->params()->fromPost('seriesField', '')); // 用于pie
$maxShowNumber = intval($this->params()->fromPost('maxShowNumber', 100)); // 显示最大数量,防止饼状图太多
$isDashboard = filter_var($this->params()->fromPost('isDashboard', null), FILTER_VALIDATE_BOOLEAN); // 是否显示在控制面板
$dashboardTitle = trim($this->params()->fromPost('dashboardTitle', ''));
$dashboardQuery = trim($this->params()->fromPost('dashboardQuery', '')); // 控制面板附加查询条件
$statisticPeriod = intval($this->params()->fromPost('statisticPeriod', 24 * 3600)); // 控制面板显示周期
$colspan = intval($this->params()->fromPost('colspan', 1)); // 行显示是否合并
$priority = intval($this->params()->fromPost('priority', 0)); // 优先级
$interval = intval($this->params()->fromPost('interval', 3600)); // 统计执行间隔
if ($name == null) {
return $this->msg(false, '请填写统计名称');
}
if ($interval < 300) {
return $this->msg(false, '统计时间的间隔不得少于300秒');
}
if (! in_array($seriesType, $this->_seriesType, true)) {
return $this->msg(false, '请设定统计图表类型');
}
if ($seriesType !== 'pie') {
if (empty($yAxisTitle)) {
return $this->msg(false, '请设定Y轴统计名称');
}
if (empty($yAxisType)) {
return $this->msg(false, '请设定Y轴统计类型');
}
if (empty($yAxisField)) {
return $this->msg(false, '请设定Y轴统计字段');
}
if (empty($xAxisTitle)) {
return $this->msg(false, '请设定X轴统计名称');
}
if (empty($xAxisType)) {
return $this->msg(false, '请设定X轴统计类型');
}
if (empty($xAxisField)) {
return $this->msg(false, '请设定X轴统计字段');
}
} else {
if (empty($seriesField)) {
return $this->msg(false, '请设定饼形图统计属性');
}
}
if ($dashboardQuery !== '') {
if (isJson($dashboardQuery)) {
try {
$dashboardQuery = Json::decode($dashboardQuery, Json::TYPE_ARRAY);
} catch (\Exception $e) {
return $this->msg(false, '仪表盘统计条件的json格式错误');
}
} else {
return $this->msg(false, '仪表盘统计条件的json格式错误');
}
}
if ($defaultQuery !== '') {
if (isJson($defaultQuery)) {
try {
$defaultQuery = Json::decode($defaultQuery, Json::TYPE_ARRAY);
} catch (\Exception $e) {
return $this->msg(false, '默认统计条件的json格式错误');
}
} else {
return $this->msg(false, '默认统计条件的json格式错误');
}
}
$datas = array();
$datas['project_id'] = $project_id;
$datas['collection_id'] = $collection_id;
$datas['name'] = $name;
$datas['defaultQuery'] = $defaultQuery;
$datas['yAxisTitle'] = $yAxisTitle; // title string
$datas['yAxisType'] = $yAxisType; // [Numeric]
$datas['yAxisField'] = $yAxisField; // array()
$datas['xAxisTitle'] = $xAxisTitle; // title string
$datas['xAxisType'] = $xAxisType; // [Category|Time]
$datas['xAxisField'] = $xAxisField; // array()
$datas['seriesType'] = $seriesType; // [line|column|pie]
$datas['seriesField'] = $seriesField; // pie
$datas['seriesXField'] = $xAxisField; // 用于x轴显示
$datas['seriesYField'] = $yAxisField; // 用于y轴显示
$datas['maxShowNumber'] = $maxShowNumber;
$datas['isDashboard'] = $isDashboard;
$datas['dashboardTitle'] = ! empty($dashboardTitle) ? $dashboardTitle : $name;
$datas['dashboardQuery'] = $dashboardQuery;
$datas['statisticPeriod'] = $statisticPeriod;
$datas['colspan'] = $colspan;
$datas['priority'] = $priority;
$datas['interval'] = $interval;
$datas['dashboardOut'] = '';
$datas['lastExecuteTime'] = new \MongoDate(0);
$datas['resultExpireTime'] = new \MongoDate(0 + $interval);
$datas['isRunning'] = false;
$this->_statistic->insert($datas);
return $this->msg(true, '添加统计成功');
}
/**
* 编辑统计信息
*
* @author young
* @name 编辑统计信息
* @version 2014.01.25 young
*/
public function editAction()
{
$_id = trim($this->params()->fromPost('_id', ''));
$project_id = trim($this->params()->fromPost('__PROJECT_ID__', ''));
$collection_id = trim($this->params()->fromPost('__COLLECTION_ID__', ''));
$name = trim($this->params()->fromPost('name', ''));
$defaultQuery = trim($this->params()->fromPost('defaultQuery', ''));
$yAxisTitle = trim($this->params()->fromPost('yAxisTitle', '')); // Y轴名称
$yAxisType = trim($this->params()->fromPost('yAxisType', '')); // Y轴统计方法
$yAxisField = trim($this->params()->fromPost('yAxisField', '')); // Y轴统计字段
$xAxisTitle = trim($this->params()->fromPost('xAxisTitle', ''));
$xAxisType = trim($this->params()->fromPost('xAxisType', ''));
$xAxisField = trim($this->params()->fromPost('xAxisField', ''));
$seriesType = trim($this->params()->fromPost('seriesType', ''));
$seriesField = trim($this->params()->fromPost('seriesField', '')); // 用于pie
$maxShowNumber = intval($this->params()->fromPost('maxShowNumber', 100)); // 显示最大数量,防止饼状图太多
$isDashboard = filter_var($this->params()->fromPost('isDashboard', null), FILTER_VALIDATE_BOOLEAN); // 是否显示在控制面板
$dashboardTitle = trim($this->params()->fromPost('dashboardTitle', ''));
$dashboardQuery = trim($this->params()->fromPost('dashboardQuery', '')); // 控制面板附加查询条件
$statisticPeriod = intval($this->params()->fromPost('statisticPeriod', 24 * 3600)); // 控制面板显示周期
$colspan = intval($this->params()->fromPost('colspan', 1)); // 行显示是否合并
$priority = intval($this->params()->fromPost('priority', 0)); // 优先级
$interval = intval($this->params()->fromPost('interval', 3600)); // 统计执行间隔
if ($name == null) {
return $this->msg(false, '请填写统计名称');
}
if ($interval < 300) {
return $this->msg(false, '统计时间的间隔不得少于300秒');
}
if (! in_array($seriesType, $this->_seriesType, true)) {
return $this->msg(false, '请设定统计图表类型');
}
if ($seriesType !== 'pie') {
if (empty($yAxisTitle)) {
return $this->msg(false, '请设定Y轴统计名称');
}
if (empty($yAxisType)) {
return $this->msg(false, '请设定Y轴统计类型');
}
if (empty($yAxisField)) {
return $this->msg(false, '请设定Y轴统计字段');
}
if (empty($xAxisTitle)) {
return $this->msg(false, '请设定X轴统计名称');
}
if (empty($xAxisType)) {
return $this->msg(false, '请设定X轴统计类型');
}
if (empty($xAxisField)) {
return $this->msg(false, '请设定X轴统计字段');
}
} else {
if (empty($seriesField)) {
return $this->msg(false, '请设定饼形图统计属性');
}
}
if ($dashboardQuery !== '') {
if (isJson($dashboardQuery)) {
try {
$dashboardQuery = Json::decode($dashboardQuery, Json::TYPE_ARRAY);
} catch (\Exception $e) {
return $this->msg(false, '仪表盘统计条件的json格式错误');
}
} else {
return $this->msg(false, '仪表盘统计条件的json格式错误');
}
}
if ($defaultQuery !== '') {
if (isJson($defaultQuery)) {
try {
$defaultQuery = Json::decode($defaultQuery, Json::TYPE_ARRAY);
} catch (\Exception $e) {
return $this->msg(false, '默认统计条件的json格式错误');
}
} else {
return $this->msg(false, '默认统计条件的json格式错误');
}
}
$datas = array();
$datas['project_id'] = $project_id;
$datas['collection_id'] = $collection_id;
$datas['name'] = $name;
$datas['defaultQuery'] = $defaultQuery;
$datas['yAxisTitle'] = $yAxisTitle; // title string
$datas['yAxisType'] = $yAxisType; // [Numeric]
$datas['yAxisField'] = $yAxisField; // array()
$datas['xAxisTitle'] = $xAxisTitle; // title string
$datas['xAxisType'] = $xAxisType; // [Category|Time]
$datas['xAxisField'] = $xAxisField; // array()
$datas['seriesType'] = $seriesType; // [line|column|pie]
$datas['seriesField'] = $seriesField; // pie
$datas['seriesXField'] = $xAxisField; // 用于x轴显示
$datas['seriesYField'] = $yAxisField; // 用于y轴显示
$datas['maxShowNumber'] = $maxShowNumber;
$datas['isDashboard'] = $isDashboard;
$datas['dashboardTitle'] = ! empty($dashboardTitle) ? $dashboardTitle : $name;
$datas['dashboardQuery'] = $dashboardQuery;
$datas['statisticPeriod'] = $statisticPeriod;
$datas['colspan'] = $colspan;
$datas['priority'] = $priority;
$datas['interval'] = $interval;
$datas['lastExecuteTime'] = new \MongoDate(0);
$datas['resultExpireTime'] = new \MongoDate(0 + $interval);
$datas['isRunning'] = false;
$this->_statistic->update(array(
'_id' => myMongoId($_id)
), array(
'$set' => $datas
));
return $this->msg(true, '编辑统计成功');
}
/**
* 批量编辑统计信息
*
* @author young
* @name 批量编辑统计信息
* @version 2014.01.26 young
*/
public function saveAction()
{
return $this->msg(false, '本功能不支持批量编辑');
}
/**
* 删除统计信息
*
* @author young
* @name 删除统计信息
* @version 2014.01.25 young
*/
public function removeAction()
{
$_id = $this->params()->fromPost('_id', null);
try {
$_id = Json::decode($_id, Json::TYPE_ARRAY);
} catch (\Exception $e) {
return $this->msg(false, '无效的json字符串');
}
if (! is_array($_id)) {
return $this->msg(false, '请选择你要删除的项');
}
foreach ($_id as $row) {
$this->_statistic->remove(array(
'_id' => myMongoId($row),
'project_id' => $this->_project_id,
'collection_id' => $this->_collection_id
));
}
return $this->msg(true, '删除统计信息成功');
}
}
| bsd-3-clause |
knewter/ansuz | db/migrate/20080831171235_add_photo_albums_and_photo_album_photos.rb | 534 | class AddPhotoAlbumsAndPhotoAlbumPhotos < ActiveRecord::Migration
def self.up
create_table :photo_albums do |t|
t.string :name
end
create_table :photo_album_photos do |t|
t.integer :photo_album_id
t.string :title
t.text :caption
t.string :photo_album_photo_image_file_name
t.string :photo_album_photo_image_content_type
t.integer :photo_album_photo_image_file_size
end
end
def self.down
drop_table :photo_album_photos
drop_table :photo_albums
end
end
| bsd-3-clause |
xamarin/ServiceStack | src/ServiceStack.Common/ServiceModel/Serialization/XmlSerializableSerializer.cs | 1039 | using System;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using ServiceStack.DesignPatterns.Serialization;
using ServiceStack.ServiceModel.Support;
namespace ServiceStack.ServiceModel.Serialization
{
public class XmlSerializableSerializer : IStringSerializer
{
public static XmlSerializableSerializer Instance = new XmlSerializableSerializer();
public string Parse<XmlDto>(XmlDto from)
{
try
{
using (var ms = new MemoryStream())
{
using (XmlWriter xw = new XmlTextWriter(ms, Encoding.UTF8))
{
var ser = new XmlSerializerWrapper(from.GetType());
ser.WriteObject(xw, from);
xw.Flush();
ms.Seek(0, SeekOrigin.Begin);
using (var reader = new StreamReader(ms))
{
return reader.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
throw new SerializationException(string.Format("Error serializing object of type {0}", from.GetType().FullName), ex);
}
}
}
} | bsd-3-clause |
UniStuttgart-VISUS/megamol | plugins/infovis_gl/src/amort/BaseAmortizedRenderer2D.cpp | 5294 | #include "BaseAmortizedRenderer2D.h"
#include "mmcore/CoreInstance.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/utility/log/Log.h"
using namespace megamol;
using namespace megamol::infovis_gl;
using megamol::core::utility::log::Log;
BaseAmortizedRenderer2D::BaseAmortizedRenderer2D()
: Renderer2D()
, nextRendererSlot("nextRenderer", "connects to following Renderers, that will render in reduced resolution.")
, enabledParam("Enabled", "Turn on switch") {
this->nextRendererSlot.SetCompatibleCall<megamol::core_gl::view::CallRender2DGLDescription>();
this->MakeSlotAvailable(&this->nextRendererSlot);
this->enabledParam << new core::param::BoolParam(false);
this->MakeSlotAvailable(&enabledParam);
}
bool BaseAmortizedRenderer2D::create() {
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
Log::DefaultLog.WriteWarn("Ignore glError() from previous modules: %i", error);
}
auto const shaderOptions = msf::ShaderFactoryOptionsOpenGL(GetCoreInstance()->GetShaderPaths());
createImpl(shaderOptions);
return true;
}
void BaseAmortizedRenderer2D::release() {
releaseImpl();
}
bool BaseAmortizedRenderer2D::GetExtents(core_gl::view::CallRender2DGL& call) {
core_gl::view::CallRender2DGL* cr2d = this->nextRendererSlot.CallAs<core_gl::view::CallRender2DGL>();
if (cr2d == nullptr) {
return false;
}
if (!(*cr2d)(core_gl::view::CallRender2DGL::FnGetExtents)) {
return false;
}
cr2d->SetTimeFramesCount(call.TimeFramesCount());
cr2d->SetIsInSituTime(call.IsInSituTime());
call.AccessBoundingBoxes() = cr2d->GetBoundingBoxes();
return true;
}
bool BaseAmortizedRenderer2D::Render(core_gl::view::CallRender2DGL& call) {
core_gl::view::CallRender2DGL* cr2d = this->nextRendererSlot.CallAs<core_gl::view::CallRender2DGL>();
if (cr2d == nullptr) {
// Nothing to do really
return true;
}
cr2d->SetTime(call.Time());
cr2d->SetInstanceTime(call.InstanceTime());
cr2d->SetLastFrameTime(call.LastFrameTime());
cr2d->SetBackgroundColor(call.BackgroundColor());
cr2d->AccessBoundingBoxes() = call.GetBoundingBoxes();
cr2d->SetViewResolution(call.GetViewResolution());
if (this->enabledParam.Param<core::param::BoolParam>()->Value()) {
return renderImpl(*cr2d, call.GetFramebuffer(), call.GetCamera());
} else {
cr2d->SetFramebuffer(call.GetFramebuffer());
cr2d->SetCamera(call.GetCamera());
// send call to next renderer in line
(*cr2d)(core::view::AbstractCallRender::FnRender);
}
return true;
}
bool BaseAmortizedRenderer2D::OnMouseButton(
core::view::MouseButton button, core::view::MouseButtonAction action, core::view::Modifiers mods) {
auto* cr = this->nextRendererSlot.CallAs<megamol::core_gl::view::CallRender2DGL>();
if (cr) {
megamol::core::view::InputEvent evt;
evt.tag = megamol::core::view::InputEvent::Tag::MouseButton;
evt.mouseButtonData.button = button;
evt.mouseButtonData.action = action;
evt.mouseButtonData.mods = mods;
cr->SetInputEvent(evt);
return (*cr)(megamol::core_gl::view::CallRender2DGL::FnOnMouseButton);
}
return false;
}
bool BaseAmortizedRenderer2D::OnMouseMove(double x, double y) {
auto* cr = this->nextRendererSlot.CallAs<megamol::core_gl::view::CallRender2DGL>();
if (cr) {
megamol::core::view::InputEvent evt;
evt.tag = megamol::core::view::InputEvent::Tag::MouseMove;
evt.mouseMoveData.x = x;
evt.mouseMoveData.y = y;
cr->SetInputEvent(evt);
return (*cr)(megamol::core_gl::view::CallRender2DGL::FnOnMouseMove);
}
return false;
}
bool BaseAmortizedRenderer2D::OnMouseScroll(double dx, double dy) {
auto* cr = this->nextRendererSlot.CallAs<megamol::core_gl::view::CallRender2DGL>();
if (cr) {
megamol::core::view::InputEvent evt;
evt.tag = megamol::core::view::InputEvent::Tag::MouseScroll;
evt.mouseScrollData.dx = dx;
evt.mouseScrollData.dy = dy;
cr->SetInputEvent(evt);
return (*cr)(megamol::core_gl::view::CallRender2DGL::FnOnMouseScroll);
}
return false;
}
bool BaseAmortizedRenderer2D::OnChar(unsigned int codePoint) {
auto* cr = this->nextRendererSlot.CallAs<megamol::core_gl::view::CallRender2DGL>();
if (cr) {
megamol::core::view::InputEvent evt;
evt.tag = megamol::core::view::InputEvent::Tag::Char;
evt.charData.codePoint = codePoint;
cr->SetInputEvent(evt);
return (*cr)(megamol::core_gl::view::CallRender2DGL::FnOnChar);
}
return false;
}
bool BaseAmortizedRenderer2D::OnKey(
megamol::core::view::Key key, megamol::core::view::KeyAction action, megamol::core::view::Modifiers mods) {
auto* cr = this->nextRendererSlot.CallAs<megamol::core_gl::view::CallRender2DGL>();
if (cr) {
megamol::core::view::InputEvent evt;
evt.tag = megamol::core::view::InputEvent::Tag::Key;
evt.keyData.key = key;
evt.keyData.action = action;
evt.keyData.mods = mods;
cr->SetInputEvent(evt);
return (*cr)(megamol::core_gl::view::CallRender2DGL::FnOnKey);
}
return false;
}
| bsd-3-clause |
Cristianohh/PrecompiledShaders | src/timer.cpp | 2850 | /* Copyright (c) 2014, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "timer.h"
#include <stdlib.h>
#include <sys/time.h>
#include <stdio.h>
#include <time.h>
static struct timespec _time_difference(struct timespec a, struct timespec b)
{
struct timespec temp;
temp.tv_sec = a.tv_sec-b.tv_sec;
temp.tv_nsec = a.tv_nsec-b.tv_nsec;
return temp;
}
struct Timer
{
struct timespec start_time;
struct timespec prev_time;
};
Timer* create_timer(void)
{
Timer* timer = (Timer*)calloc(1, sizeof(*timer));
reset_timer(timer);
return timer;
}
void destroy_timer(Timer* timer)
{
free(timer);
}
void reset_timer(Timer* timer)
{
struct timespec time;
clock_gettime(CLOCK_MONOTONIC, &time);
timer->prev_time = timer->start_time = time;
}
double get_delta_time(Timer* timer)
{
struct timespec time;
struct timespec diff;
clock_gettime(CLOCK_MONOTONIC, &time);
diff = _time_difference(time, timer->prev_time);
timer->prev_time = time;
return diff.tv_sec + diff.tv_nsec*1.0/1000000000;
}
double get_running_time(Timer* timer)
{
struct timespec time;
struct timespec diff;
clock_gettime(CLOCK_MONOTONIC, &time);
diff = _time_difference(time, timer->start_time);
return diff.tv_sec + diff.tv_nsec*1.0/1000000000;
} | bsd-3-clause |
md5555/ec | util/config_option_check.py | 4095 | #!/usr/bin/python2
# Copyright 2015 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Configuration Option Checker.
Script to ensure that all configuration options for the Chrome EC are defined
in config.h.
"""
from __future__ import print_function
import re
import os
import argparse
def find_files_to_check(args):
"""Returns a list of files to check."""
file_list = []
if args.all_files:
cwd = os.getcwd()
for (dirpath, dirnames, filenames) in os.walk(cwd, topdown=True):
# Ignore the build and private directories (taken from .gitignore)
if 'build' in dirnames:
dirnames.remove('build')
if 'private' in dirnames:
dirnames.remove('private')
for f in filenames:
# Only consider C source and assembler files.
if f.endswith(('.c', '.h', '.inc', '.S')):
file_list.append(os.path.join(dirpath, f))
else:
# Form list from presubmit environment variable.
file_list = os.environ['PRESUBMIT_FILES'].split()
return file_list
def obtain_current_config_options():
"""Obtains current config options from include/config.h"""
config_options = []
config_option_re = re.compile(r'\s+(CONFIG_[a-zA-Z0-9_]*)\s*')
with open('include/config.h', 'r') as config_file:
for line in config_file:
match = re.search(config_option_re, line)
if match:
if match.group(1) not in config_options:
config_options.append(match.group(1))
return config_options
def print_missing_config_options(file_list, config_options):
"""Searches through all files in file_list for missing config options."""
missing_config_option = False
print_banner = True
# Determine longest CONFIG_* length to be used for formatting.
max_option_length = max(len(option) for option in config_options)
config_option_re = re.compile(r'\s+(CONFIG_[a-zA-Z0-9_]*)\s*')
for f in file_list:
with open(f, 'r') as cur_file:
line_num = 0
for line in cur_file:
line_num += 1
match = re.search(config_option_re, line)
if match:
if match.group(1) not in config_options:
missing_config_option = True
# Print the banner once.
if print_banner:
print('Please add all new config options to include/config.h' \
' along with a description of the option.\n\n' \
'The following config options were found to be missing ' \
'from include/config.h.\n')
print_banner = False
# Print the misssing config option.
print('> %-*s %s:%s' % (max_option_length, match.group(1), f,
line_num))
return missing_config_option
def main():
"""Searches through specified source files for missing config options.
Checks through specified C source and assembler file (not in the build/ and
private/ directories) for CONFIG_* options. Then checks to make sure that
all CONFIG_* options are defined in include/config.h. Finally, reports any
missing config options. By default, it will check just the files in the CL.
To check all files in EC code base, run with the flag --all_files.
"""
# Create argument options to specify checking either all the files in the EC
# code base or just the files in the CL.
parser = argparse.ArgumentParser(description='configuration option checker.')
parser.add_argument('--all_files', help='check all files in EC code base',
action='store_true')
args = parser.parse_args()
# Create list of files to search.
file_list = find_files_to_check(args)
# Obtain config options from include/config.h.
config_options = obtain_current_config_options()
# Find any missing config options from file list and print them.
missing_opts = print_missing_config_options(file_list, config_options)
if missing_opts:
print('\nIt may also be possible that you have a typo.')
os.sys.exit(1)
if __name__ == '__main__':
main()
| bsd-3-clause |
hscstudio/osyawwal2 | frontend/modules/student/controllers/TrainingScheduleTrainerController.php | 4451 | <?php
namespace frontend\modules\student\controllers;
use Yii;
use frontend\models\TrainingScheduleTrainer;
use frontend\modules\student\models\TrainingScheduleTrainerSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
/**
* TrainingScheduleTrainerController implements the CRUD actions for TrainingScheduleTrainer model.
*/
class TrainingScheduleTrainerController extends Controller
{
public $layout = '@hscstudio/heart/views/layouts/column2';
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
];
}
/**
* Lists all TrainingScheduleTrainer models.
* @return mixed
*/
public function actionIndex($training_id=NULL,$training_student_id=NULL)
{
$id = base64_decode(\hscstudio\heart\helpers\Kalkun::HexToAscii($training_id));
$id2 = base64_decode(\hscstudio\heart\helpers\Kalkun::HexToAscii($training_student_id));
$training_class_id = \frontend\models\TrainingClassStudent::findOne(['training_id'=>$id,'training_student_id'=>$id2])->training_class_id;
$searchModel = new TrainingScheduleTrainerSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams,$training_class_id);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'training_id' => $training_id,
'training_class_id' => $training_class_id,
'training_student_id' => $training_student_id,
]);
}
/**
* Displays a single TrainingScheduleTrainer model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new TrainingScheduleTrainer model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new TrainingScheduleTrainer();
if ($model->load(Yii::$app->request->post())){
if($model->save()) {
Yii::$app->getSession()->setFlash('success', 'New data have saved.');
}
else{
Yii::$app->getSession()->setFlash('error', 'New data is not saved.');
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
/**
* Updates an existing TrainingScheduleTrainer model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id
* @return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post())) {
if($model->save()) {
Yii::$app->getSession()->setFlash('success', 'Data have updated.');
}
else{
Yii::$app->getSession()->setFlash('error', 'Data is not updated.');
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing TrainingScheduleTrainer model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
/*if($this->findModel($id)->delete()) {
Yii::$app->getSession()->setFlash('success', 'Data have deleted.');
}
else{
Yii::$app->getSession()->setFlash('error', 'Data is not deleted.');
}*/
return $this->redirect(['index']);
}
/**
* Finds the TrainingScheduleTrainer model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return TrainingScheduleTrainer the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = TrainingScheduleTrainer::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
| bsd-3-clause |
ansidev/zf2-beginner | resources/local_files/bjyprofiler.local.php | 1802 | <?php
$dbParams = array(
'database' => 'zend_two',
'username' => 'root',
'password' => 'root',
'hostname' => 'localhost',
// buffer_results - only for mysqli buffered queries, skip for others
'options' => array('buffer_results' => true)
);
return array(
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter' => function ($sm) use ($dbParams) {
$adapter = new BjyProfiler\Db\Adapter\ProfilingAdapter(array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname='.$dbParams['database'].';host='.$dbParams['hostname'],
'database' => $dbParams['database'],
'username' => $dbParams['username'],
'password' => $dbParams['password'],
'hostname' => $dbParams['hostname'],
));
if (php_sapi_name() == 'cli') {
$logger = new Zend\Log\Logger();
// write queries profiling info to stdout in CLI mode
$writer = new Zend\Log\Writer\Stream('php://output');
$logger->addWriter($writer, Zend\Log\Logger::DEBUG);
$adapter->setProfiler(new BjyProfiler\Db\Profiler\LoggingProfiler($logger));
} else {
$adapter->setProfiler(new BjyProfiler\Db\Profiler\Profiler());
}
if (isset($dbParams['options']) && is_array($dbParams['options'])) {
$options = $dbParams['options'];
} else {
$options = array();
}
$adapter->injectProfilingStatementPrototype($options);
return $adapter;
},
),
),
); | bsd-3-clause |
sharaf84/digi | frontend/controllers/StoreController.php | 4491 | <?php
namespace frontend\controllers;
use Yii;
use yii\web\NotFoundHttpException;
use common\models\custom\Product;
use frontend\models\SearchForm;
use frontend\models\ProductForm;
/**
* Store controller
*/
class StoreController extends \frontend\components\BaseController {
/**
* Search Product
* @param string $slug of category or brand
*/
public function actionSearch($slug = null) {
$oProductQuery = Product::find();
$oSearchForm = new SearchForm();
$escape = ['%' => '\%', '_' => '\_', '\\' => '\\\\'];
if ($oSearchForm->load(Yii::$app->request->get()) && $oSearchForm->validate()) {
if ($oSearchForm->key) {
$oProductQuery->leftJoin('`base_tree` AS `category`', '`product`.`category_id` = `category`.`id`');
$oProductQuery->leftJoin('`base_tree` AS `brand`', '`product`.`brand_id` = `brand`.`id`');
$oProductQuery->andWhere('
`product`.`title` LIKE :key OR
`product`.`brief` LIKE :key OR
`product`.`description` LIKE :key OR
`category`.`name` LIKE :key OR
`brand`.`name` LIKE :key', [':key' => ('%' . strtr($oSearchForm->key, $escape) . '%')]
);
}
$oSearchForm->alpha and $oProductQuery->andWhere('`product`.`title` LIKE :alpha', [':alpha' => (strtr($oSearchForm->alpha, $escape) . '%')]);
}
if ($slug) {
if (!$oSearchForm->key) {
$oProductQuery->leftJoin('`base_tree` AS `category`', '`product`.`category_id` = `category`.`id`');
$oProductQuery->leftJoin('`base_tree` AS `brand`', '`product`.`brand_id` = `brand`.`id`');
}
$oProductQuery->andWhere('`category`.`slug`=:slug OR `brand`.`slug`=:slug', [':slug' => $slug]);
}
$oProductsDP = new \yii\data\ActiveDataProvider([
'query' => $oProductQuery->parents(),
'sort' => [
'defaultOrder' => ['sort' => SORT_ASC, 'id' => SORT_DESC]
],
'pagination' => [
'pageSize' => 5,
],
]);
$this->view->params['searchKey'] = $oSearchForm->key;
return $this->render('search', [
'slug' => $slug,
'oSearchForm' => $oSearchForm,
'oProductsDP' => $oProductsDP,
'bestSellerProducts' => Product::getBestSeller(4),
]);
}
/**
* View Product
* @param string $slug
*/
public function actionProduct($slug) {
$oProduct = Product::find()->parents()->andWhere(['slug' => $slug])->with('firstMedia', 'category', 'childs')->one();
if (!$oProduct)
throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
$oChildProduct = null;
$flavors = $colors = $colorsOptions = [];
$oProductForm = new ProductForm();
if ($oProductForm->load(Yii::$app->request->get()) && $oProductForm->validate()) {
$oProductQuery = Product::find()
->childs($oProduct->id)
->with('media')
->andWhere(['size_id' => $oProductForm->size]);
if ($oProductForm->flavor) {
$oChildProduct = $oProductQuery->andWhere(['flavor_id' => $oProductForm->flavor])->one();
} elseif ($oProductForm->color) {
$oChildProduct = $oProductQuery->andWhere(['color' => $oProductForm->color])->one();
}
if ($oProduct->isAccessory()) {
$colors = $oProduct->getChildsColors($oProductForm->size);
foreach (array_keys($colors) as $color)
$colorsOptions[$color] = ['style' => "background:$color; color:$color;"];
} else {
$flavors = $oProduct->getChildsFlavors($oProductForm->size);
}
}
return $this->render('product', [
'oProduct' => $oProduct,
'oChildProduct' => $oChildProduct,
'oProductForm' => $oProductForm,
'sizes' => $oProduct->getChildsSizes(),
'flavors' => $flavors,
'colors' => $colors,
'colorsOptions' => $colorsOptions,
'relatedProducts' => $oProduct->getRelated(4)
]);
}
}
| bsd-3-clause |
NCIP/cagrid-grid-incubation | grid-incubation/test/projects/workflowHelper/resources/CreateArrayService/src/org/cagrid/introduce/createarrayservice/client/CreateArrayServiceClientBase.java | 3884 | /**
*============================================================================
* The Ohio State University Research Foundation, Emory University,
* the University of Minnesota Supercomputing Institute
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-grid-incubation/LICENSE.txt for details.
*============================================================================
**/
/**
*============================================================================
*============================================================================
**/
package org.cagrid.introduce.createarrayservice.client;
import java.io.InputStream;
import java.rmi.RemoteException;
import javax.xml.namespace.QName;
import java.util.Calendar;
import java.util.List;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.client.AxisClient;
import org.apache.axis.client.Stub;
import org.apache.axis.configuration.FileProvider;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.axis.types.URI.MalformedURIException;
import org.globus.gsi.GlobusCredential;
import org.globus.wsrf.NotifyCallback;
import org.globus.wsrf.NotificationConsumerManager;
import org.globus.wsrf.container.ContainerException;
import org.oasis.wsrf.lifetime.ImmediateResourceTermination;
import org.oasis.wsrf.lifetime.WSResourceLifetimeServiceAddressingLocator;
import org.cagrid.introduce.createarrayservice.stubs.CreateArrayServicePortType;
import org.cagrid.introduce.createarrayservice.stubs.service.CreateArrayServiceAddressingLocator;
import org.cagrid.introduce.createarrayservice.common.CreateArrayServiceI;
import gov.nih.nci.cagrid.introduce.security.client.ServiceSecurityClient;
/**
* This class is autogenerated, DO NOT EDIT GENERATED GRID SERVICE ACCESS METHODS.
*
* This client is generated automatically by Introduce to provide a clean unwrapped API to the
* service.
*
* On construction the class instance will contact the remote service and retrieve it's security
* metadata description which it will use to configure the Stub specifically for each method call.
*
* @created by Introduce Toolkit version 1.2
*/
public abstract class CreateArrayServiceClientBase extends ServiceSecurityClient {
protected CreateArrayServicePortType portType;
protected Object portTypeMutex;
protected NotificationConsumerManager consumer = null;
protected EndpointReferenceType consumerEPR = null;
public CreateArrayServiceClientBase(String url, GlobusCredential proxy) throws MalformedURIException, RemoteException {
super(url,proxy);
initialize();
}
public CreateArrayServiceClientBase(EndpointReferenceType epr, GlobusCredential proxy) throws MalformedURIException, RemoteException {
super(epr,proxy);
initialize();
}
private void initialize() throws RemoteException {
this.portTypeMutex = new Object();
this.portType = createPortType();
}
private CreateArrayServicePortType createPortType() throws RemoteException {
CreateArrayServiceAddressingLocator locator = new CreateArrayServiceAddressingLocator();
// attempt to load our context sensitive wsdd file
InputStream resourceAsStream = getClass().getResourceAsStream("client-config.wsdd");
if (resourceAsStream != null) {
// we found it, so tell axis to configure an engine to use it
EngineConfiguration engineConfig = new FileProvider(resourceAsStream);
// set the engine of the locator
locator.setEngine(new AxisClient(engineConfig));
}
CreateArrayServicePortType port = null;
try {
port = locator.getCreateArrayServicePortTypePort(getEndpointReference());
} catch (Exception e) {
throw new RemoteException("Unable to locate portType:" + e.getMessage(), e);
}
return port;
}
}
| bsd-3-clause |
tommy-u/enable | kiva/agg/tests/rgba_test_case.py | 1650 | import unittest
from numpy import array, ones
from kiva import agg
from test_utils import Utils
class RgbaTestCase(unittest.TestCase, Utils):
def test_init(self):
m = agg.Rgba()
def test_init1(self):
m = agg.Rgba(.5,.5,.5)
desired = array((.5,.5,.5,1.0))
self.assertRavelEqual(m.asarray(),desired)
def test_init_from_array1(self):
a = ones(3,'d') * .8
m = agg.Rgba(a)
desired = ones(4,'d') * .8
desired[3] = 1.0
result = m.asarray()
self.assertRavelEqual(result, desired)
def test_init_from_array2(self):
a = ones(4,'d') * .8
m = agg.Rgba(a)
desired = ones(4,'d') * .8
result = m.asarray()
self.assertRavelEqual(result, desired)
def test_init_from_array3(self):
a = ones(5,'d')
try:
m = agg.Rgba(a)
except ValueError:
pass # can't init from array that isn't 6 element.
def test_init_from_array4(self):
a = ones((2,3),'d')
try:
m = agg.Rgba(a)
except ValueError:
pass # can't init from array that isn't 1d.
def test_gradient(self):
first = agg.Rgba(0.,0.,0.,0.)
second = agg.Rgba(1.,1.,1.,1.)
actual = first.gradient(second,.5).asarray()
desired = array((.5,.5,.5,.5))
self.assertRavelEqual(actual, desired)
def test_pre(self):
first = agg.Rgba(1.0,1.0,1.0,0.5)
actual = first.premultiply().asarray()
desired = array((.5,.5,.5,.5))
self.assertRavelEqual(actual, desired)
if __name__ == "__main__":
unittest.main()
| bsd-3-clause |
mmerzlyakov/tourbook | views/city/view.php | 1176 | <?php
\app\libs\Language::select();
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model app\models\City */
$this->title = $model->name;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Cities'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="city-view">
<h1>Preview: <?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->id, 'country_id' => $model->country_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id, 'country_id' => $model->country_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'country_id',
'name',
'description:ntext',
'full_description:ntext',
'status',
],
]) ?>
</div>
| bsd-3-clause |
leok7v/android-monospaced-table | src/android/mono/table/etc/Numbers.java | 14362 | /*
* Adopted from original package private: java.lang.RealToString.java
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.mono.table.etc;
import static android.mono.table.etc.util.*;
public class Numbers {
private static final ThreadLocal<Numbers> INSTANCE = new ThreadLocal<Numbers>() {
@Override protected Numbers initialValue() {
return new Numbers();
}
};
public static final long[] LONG_POWERS_OF_TEN = new long[] {
1L,
10L,
100L,
1000L,
10000L,
100000L,
1000000L,
10000000L,
100000000L,
1000000000L,
10000000000L,
100000000000L,
1000000000000L,
10000000000000L,
100000000000000L,
1000000000000000L,
10000000000000000L,
100000000000000000L,
1000000000000000000L,
};
public static final char[] DIGITS = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'A', 'B', 'C', 'D', 'E', 'F'
};
public static final int Double_EXPONENT_BIAS = 1023;
public static final int Double_MANTISSA_BITS = 52;
public static final long Double_SIGN_MASK = 0x8000000000000000L;
public static final long Double_EXPONENT_MASK = 0x7ff0000000000000L;
public static final long Double_MANTISSA_MASK = 0x000fffffffffffffL;
private static final double invLogOfTenBaseTwo = Math.log(2.0) / Math.log(10.0);
private static final Text INFINITY = wrap("Infinity");
private static final Text NEGATIVE_INFINITY = wrap("-Infinity");
private static final Text NaN = wrap("NaN");
private static final Text ZERO = wrap("0.0");
private static final Text NEGATIVE_ZERO = wrap("0.0");
private static final Text SMALLEST_DOUBLE = wrap("4.9E-324");
private static final Text NEGATIVE_SMALLEST_DOUBLE = wrap("-4.9E-324");
private int firstK;
private final char[] num = new char[64];
/**
* An array of decimal digits, filled by longDigitGenerator or bigIntDigitGenerator.
*/
private final int[] digits = new int[64];
/**
* Number of valid entries in 'digits'.
*/
private int digitCount;
private Numbers() {
}
public static Numbers getInstance() {
return INSTANCE.get();
}
private static Text wrap(String s) {
Text text = new Text(s.length());
text.append(s);
return text;
}
public static long parseLong(CharSequence s) {
return parse(s, 0, s.length(), 10);
}
public static long parseLong(CharSequence s, int offset, int length) {
return parse(s, offset, length, 10);
}
private static long parse(CharSequence s, int offset, int length, int radix) {
int start = offset;
int end = offset + length;
while (offset < end && Character.isWhitespace(s.charAt(offset))) {
offset++;
}
boolean negative = offset < end && s.charAt(offset) == '-';
if (negative) {
offset++;
}
if (offset >= end) {
throw invalidLong(s, start, length);
}
long max = Long.MIN_VALUE / radix;
long result = 0;
while (offset < end) {
int digit = Character.digit(s.charAt(offset++), radix);
if (digit == -1) {
throw invalidLong(s, start, length);
}
if (max > result) {
throw invalidLong(s, start, length);
}
long next = result * radix - digit;
if (next > result) {
throw invalidLong(s, start, length);
}
result = next;
}
if (!negative) {
result = -result;
if (result < 0) {
throw invalidLong(s, start, length);
}
}
return result;
}
private static NumberFormatException invalidLong(CharSequence s, int offset, int length) {
char[] ca = new char[length];
for (int i = 0; i < length; i++) {
ca[i] = s.charAt(offset + i);
}
return new NumberFormatException("Invalid long: \"" + new String(ca) + "\"");
}
public void appendLong(Text text, long v, int radix) {
if (radix < Character.MIN_RADIX || radix > 16) {
radix = 10;
}
/*
* If i is positive, negate it. This is the opposite of what one might
* expect. It is necessary because the range of the negative values is
* strictly larger than that of the positive values: there is no
* positive value corresponding to Integer.MIN_VALUE.
*/
boolean negative = v < 0;
if (!negative) {
v = -v;
}
int bufLen = num.length; // Max chars in result (conservative)
int cursor = bufLen;
do {
long q = v / radix;
num[--cursor] = DIGITS[(int)(radix * q - v)];
v = q;
} while (v != 0);
if (negative) {
num[--cursor] = '-';
}
for (int i = cursor; i < bufLen; i++) {
text.append(num[i]);
}
}
private static Text resultOrSideEffect(Text text, Text s) {
if (text != null) {
text.append(s);
return text;
}
return s;
}
public Text appendDouble(Text text, double d) {
return convertDouble(text, d);
}
private Text convertDouble(Text text, double inputNumber) {
assertion(text != null);
long inputNumberBits = Double.doubleToRawLongBits(inputNumber);
boolean positive = (inputNumberBits & Double_SIGN_MASK) == 0;
int e = (int) ((inputNumberBits & Double_EXPONENT_MASK) >> Double_MANTISSA_BITS);
long f = inputNumberBits & Double_MANTISSA_MASK;
boolean mantissaIsZero = f == 0;
Text quickResult = null;
if (e == 2047) {
if (mantissaIsZero) {
quickResult = positive ? INFINITY : NEGATIVE_INFINITY;
} else {
quickResult = NaN;
}
} else if (e == 0) {
if (mantissaIsZero) {
quickResult = positive ? ZERO : NEGATIVE_ZERO;
} else if (f == 1) {
// special case to increase precision even though 2 * Double_MIN_VALUE is 1.0e-323
quickResult = positive ? SMALLEST_DOUBLE : NEGATIVE_SMALLEST_DOUBLE;
}
}
if (quickResult != null) {
return resultOrSideEffect(text, quickResult);
}
int p = Double_EXPONENT_BIAS + Double_MANTISSA_BITS; // the power offset (precision)
int pow;
int numBits = Double_MANTISSA_BITS;
if (e == 0) {
pow = 1 - p; // a denormalized number
long ff = f;
while ((ff & 0x0010000000000000L) == 0) {
ff = ff << 1;
numBits--;
}
} else {
// 0 < e < 2047
// a "normalized" number
f = f | 0x0010000000000000L;
pow = e - p;
}
firstK = digitCount = 0;
if (-59 < pow && pow < 6 || (pow == -59 && !mantissaIsZero)) {
longDigitGenerator(f, pow, e == 0, mantissaIsZero, numBits);
} else {
bigIntDigitGenerator(f, pow, e == 0, numBits);
}
if (inputNumber >= 1e7D || inputNumber <= -1e7D
|| (inputNumber > -1e-3D && inputNumber < 1e-3D)) {
freeFormatExponential(text, positive);
} else {
freeFormat(text, positive);
}
return text;
}
public Text appendFloat(Text text, float f) {
return convertFloat(text, f);
}
public static final int Float_EXPONENT_BIAS = 127;
public static final int Float_MANTISSA_BITS = 23;
public static final int Float_SIGN_MASK = 0x80000000;
public static final int Float_EXPONENT_MASK = 0x7f800000;
public static final int Float_MANTISSA_MASK = 0x007fffff;
public Text convertFloat(Text text, float inputNumber) {
assertion(text != null);
int inputNumberBits = Float.floatToRawIntBits(inputNumber);
boolean positive = (inputNumberBits & Float_SIGN_MASK) == 0;
int e = (inputNumberBits & Float_EXPONENT_MASK) >> Float_MANTISSA_BITS;
int f = inputNumberBits & Float_MANTISSA_MASK;
boolean mantissaIsZero = f == 0;
Text quickResult = null;
if (e == 255) {
if (mantissaIsZero) {
quickResult = positive ? INFINITY : NEGATIVE_INFINITY;
} else {
quickResult = NaN;
}
} else if (e == 0 && mantissaIsZero) {
quickResult = positive ? ZERO : NEGATIVE_ZERO;
}
if (quickResult != null) {
return resultOrSideEffect(text, quickResult);
}
int p = Float_EXPONENT_BIAS + Float_MANTISSA_BITS; // the power offset (precision)
int pow;
int numBits = Float_MANTISSA_BITS;
if (e == 0) {
pow = 1 - p; // a denormalized number
if (f < 8) { // want more precision with smallest values
f = f << 2;
pow -= 2;
}
int ff = f;
while ((ff & 0x00800000) == 0) {
ff = ff << 1;
numBits--;
}
} else {
// 0 < e < 255
// a "normalized" number
f = f | 0x00800000;
pow = e - p;
}
firstK = digitCount = 0;
if (-59 < pow && pow < 35 || (pow == -59 && !mantissaIsZero)) {
longDigitGenerator(f, pow, e == 0, mantissaIsZero, numBits);
} else {
bigIntDigitGenerator(f, pow, e == 0, numBits);
}
if (inputNumber >= 1e7f || inputNumber <= -1e7f
|| (inputNumber > -1e-3f && inputNumber < 1e-3f)) {
freeFormatExponential(text, positive);
} else {
freeFormat(text, positive);
}
return text;
}
private void freeFormatExponential(Text text, boolean positive) {
int digitIndex = 0;
if (!positive) {
text.append('-');
}
text.append((char)('0' + digits[digitIndex++]));
text.append('.');
int k = firstK;
int exponent = k;
while (true) {
k--;
if (digitIndex >= digitCount) {
break;
}
text.append((char)('0' + digits[digitIndex++]));
}
if (k == exponent - 1) {
text.append('0');
}
text.append('E');
text.append(exponent, 10);
}
private void freeFormat(Text text, boolean positive) {
int digitIndex = 0;
if (!positive) {
text.append('-');
}
int k = firstK;
if (k < 0) {
text.append('0');
text.append('.');
for (int i = k + 1; i < 0; ++i) {
text.append('0');
}
}
int U = digits[digitIndex++];
do {
if (U != -1) {
text.append((char)('0' + U));
} else if (k >= -1) {
text.append('0');
}
if (k == 0) {
text.append('.');
}
k--;
U = digitIndex < digitCount ? digits[digitIndex++] : -1;
} while (U != -1 || k >= -1);
}
private native void bigIntDigitGenerator(long f, int e, boolean isDenormalized, int p);
private void longDigitGenerator(long f, int e, boolean isDenormalized, boolean mantissaIsZero, int p) {
long R, S, M;
if (e >= 0) {
M = 1l << e;
if (!mantissaIsZero) {
R = f << (e + 1);
S = 2;
} else {
R = f << (e + 2);
S = 4;
}
} else {
M = 1;
if (isDenormalized || !mantissaIsZero) {
R = f << 1;
S = 1l << (1 - e);
} else {
R = f << 2;
S = 1l << (2 - e);
}
}
int k = (int) Math.ceil((e + p - 1) * invLogOfTenBaseTwo - 1e-10);
if (k > 0) {
S = S * LONG_POWERS_OF_TEN[k];
} else if (k < 0) {
long scale = LONG_POWERS_OF_TEN[-k];
R = R * scale;
M = M == 1 ? scale : M * scale;
}
if (R + M > S) { // was M_plus
firstK = k;
} else {
firstK = k - 1;
R = R * 10;
M = M * 10;
}
boolean low, high;
int U;
while (true) {
// Set U to floor(R/S) and R to the remainder, using *unsigned* 64-bit division
U = 0;
for (int i = 3; i >= 0; i--) {
long remainder = R - (S << i);
if (remainder >= 0) {
R = remainder;
U += 1 << i;
}
}
low = R < M; // was M_minus
high = R + M > S; // was M_plus
if (low || high) {
break;
}
R = R * 10;
M = M * 10;
digits[digitCount++] = U;
}
if (low && !high) {
digits[digitCount++] = U;
} else if (high && !low) {
digits[digitCount++] = U + 1;
} else if ((R << 1) < S) {
digits[digitCount++] = U;
} else {
digits[digitCount++] = U + 1;
}
}
}
| bsd-3-clause |
youtube/cobalt | third_party/v8/test/cctest/wasm/test-grow-memory.cc | 4661 | // Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/wasm/wasm-objects-inl.h"
#include "src/wasm/wasm-opcodes.h"
#include "src/wasm/wasm-module-builder.h"
#include "test/cctest/cctest.h"
#include "test/cctest/manually-externalized-buffer.h"
#include "test/common/wasm/flag-utils.h"
#include "test/common/wasm/test-signatures.h"
#include "test/common/wasm/wasm-macro-gen.h"
#include "test/common/wasm/wasm-module-runner.h"
namespace v8 {
namespace internal {
namespace wasm {
namespace test_grow_memory {
using testing::CompileAndInstantiateForTesting;
using v8::internal::testing::ManuallyExternalizedBuffer;
namespace {
void ExportAsMain(WasmFunctionBuilder* f) {
f->builder()->AddExport(CStrVector("main"), f);
}
#define EMIT_CODE_WITH_END(f, code) \
do { \
f->EmitCode(code, sizeof(code)); \
f->Emit(kExprEnd); \
} while (false)
void Cleanup(Isolate* isolate = CcTest::InitIsolateOnce()) {
// By sending a low memory notifications, we will try hard to collect all
// garbage and will therefore also invoke all weak callbacks of actually
// unreachable persistent handles.
reinterpret_cast<v8::Isolate*>(isolate)->LowMemoryNotification();
}
} // namespace
TEST(GrowMemDetaches) {
{
Isolate* isolate = CcTest::InitIsolateOnce();
HandleScope scope(isolate);
Handle<WasmMemoryObject> memory_object =
WasmMemoryObject::New(isolate, 16, 100, SharedFlag::kNotShared)
.ToHandleChecked();
Handle<JSArrayBuffer> buffer(memory_object->array_buffer(), isolate);
int32_t result = WasmMemoryObject::Grow(isolate, memory_object, 0);
CHECK_EQ(16, result);
CHECK_NE(*buffer, memory_object->array_buffer());
CHECK(buffer->was_detached());
}
Cleanup();
}
TEST(Externalized_GrowMemMemSize) {
{
Isolate* isolate = CcTest::InitIsolateOnce();
HandleScope scope(isolate);
Handle<WasmMemoryObject> memory_object =
WasmMemoryObject::New(isolate, 16, 100, SharedFlag::kNotShared)
.ToHandleChecked();
ManuallyExternalizedBuffer external(
handle(memory_object->array_buffer(), isolate));
int32_t result = WasmMemoryObject::Grow(isolate, memory_object, 0);
CHECK_EQ(16, result);
CHECK_NE(*external.buffer_, memory_object->array_buffer());
CHECK(external.buffer_->was_detached());
}
Cleanup();
}
TEST(Run_WasmModule_Buffer_Externalized_GrowMem) {
{
Isolate* isolate = CcTest::InitIsolateOnce();
HandleScope scope(isolate);
TestSignatures sigs;
v8::internal::AccountingAllocator allocator;
Zone zone(&allocator, ZONE_NAME);
WasmModuleBuilder* builder = zone.New<WasmModuleBuilder>(&zone);
WasmFunctionBuilder* f = builder->AddFunction(sigs.i_v());
ExportAsMain(f);
byte code[] = {WASM_GROW_MEMORY(WASM_I32V_1(6)), WASM_DROP,
WASM_MEMORY_SIZE};
EMIT_CODE_WITH_END(f, code);
ZoneBuffer buffer(&zone);
builder->WriteTo(&buffer);
testing::SetupIsolateForWasmModule(isolate);
ErrorThrower thrower(isolate, "Test");
const Handle<WasmInstanceObject> instance =
CompileAndInstantiateForTesting(
isolate, &thrower, ModuleWireBytes(buffer.begin(), buffer.end()))
.ToHandleChecked();
Handle<WasmMemoryObject> memory_object(instance->memory_object(), isolate);
// Fake the Embedder flow by externalizing the array buffer.
ManuallyExternalizedBuffer external1(
handle(memory_object->array_buffer(), isolate));
// Grow using the API.
uint32_t result = WasmMemoryObject::Grow(isolate, memory_object, 4);
CHECK_EQ(16, result);
CHECK(external1.buffer_->was_detached()); // growing always detaches
CHECK_EQ(0, external1.buffer_->byte_length());
CHECK_NE(*external1.buffer_, memory_object->array_buffer());
// Fake the Embedder flow by externalizing the array buffer.
ManuallyExternalizedBuffer external2(
handle(memory_object->array_buffer(), isolate));
// Grow using an internal Wasm bytecode.
result = testing::CallWasmFunctionForTesting(isolate, instance, "main", 0,
nullptr);
CHECK_EQ(26, result);
CHECK(external2.buffer_->was_detached()); // growing always detaches
CHECK_EQ(0, external2.buffer_->byte_length());
CHECK_NE(*external2.buffer_, memory_object->array_buffer());
}
Cleanup();
}
} // namespace test_grow_memory
} // namespace wasm
} // namespace internal
} // namespace v8
#undef EMIT_CODE_WITH_END
| bsd-3-clause |
Yeti-Robotics/UltimateAscent | src/org/yetirobotics/yeti2013/Climber.java | 1823 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.yetirobotics.yeti2013;
import edu.wpi.first.wpilibj.*;
/**
* Climbinator
*
* CCCCCC LL IIIIII MMM MMM BBBBBBB IIIIII NN NN AAA TTTTTTTT OOOOOOOO RRRRRRR
* CC LL II MMM MMM BB BBB II NNNN NN AA AA TT OO OO RR RRR
* CC LL II MM MM MM BBBBBBB II NN NNNNN AA AA TT OO OO RRRRRRR
* CC LL II MM MM BB BBB II NN NNN AAAAAAAAA TT OO OO RR RRR
* CCCCCC LLLLLL II MM MM BBBBBBB IIIIII NN NN AA AA TT OOOOOOOO RR RR
*
* @author pureFloat
*/
public class Climber {
Relay winchSpike;
DigitalInput climberSwitch;
DoubleSolenoid climberPiston;
public Climber(int climberPiston1, int climberPiston2) {
climberPiston = new DoubleSolenoid(climberPiston1, climberPiston2);
//winchSpike = new Relay(winchSpikePos);
//climberSwitch = new DigitalInput(climberSwitchPos);
}
public void climbUp(){
climberPiston.set(DoubleSolenoid.Value.kForward);
System.out.println("climbing up");
/*if(climberSwitch.get()!= true)
{
winchSpike.set(Relay.Value.kOff);
System.out.println("closed");
}
else
{
winchSpike.set(Relay.Value.kReverse);
System.out.println("open");
}*/
}
public void climbDown(){
climberPiston.set(DoubleSolenoid.Value.kReverse);
System.out.println("climbing down");
//winchSpike.set(Relay.Value.kForward);
}
public void stop() {
climberPiston.set(DoubleSolenoid.Value.kOff);
//winchSpike.set(Relay.Value.kOff);
}
//public boolean getSwitchTop() {
//return climberSwitch.get();
//}
} | bsd-3-clause |
tiestvilee/WipQueue | test/org/wipqueue/consumerthread/WipConsumerThreadFactoryDefaultTest.java | 5661 | package org.wipqueue.consumerthread;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.wipqueue.queue.WipQueueImpl;
import org.wipqueue.WipStrategy;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.given;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.MockitoAnnotations.initMocks;
/**
* copyright Tiest Vilee 2012
* Date: 02/04/2012
* Time: 16:45
*/
public class WipConsumerThreadFactoryDefaultTest {
@Mock
private WipStrategy strategy;
@Mock
private WipQueueImpl<String, String> queue;
@Mock
private WipConsumerThreadFactory<String,String> consumerThreadFactory;
ThrottledConsumerThreadFactory<String, String> factory;
@Before
public void setup() {
initMocks(this);
factory = new ThrottledConsumerThreadFactory<String, String>(consumerThreadFactory, 10);
given(consumerThreadFactory.newConsumer((WipQueueImpl) any(), (WipStrategy) any())).willReturn(true);
}
@Test
public void startConsumersShouldDelegate() {
factory.startConsumers(queue, strategy, 3);
verify(consumerThreadFactory).startConsumers(queue, strategy, 3);
}
@Test
public void newConsumerShouldDelegate() {
factory.newConsumer(queue, strategy);
verify(consumerThreadFactory).newConsumer(queue, strategy);
}
@Test
public void consumerCountShouldDelegate() {
factory.consumerCount();
verify(consumerThreadFactory).consumerCount();
}
@Test
public void stopConsumerShouldDelegate() {
factory.stopConsumer();
verify(consumerThreadFactory).stopConsumer();
}
@Test
public void waitToStartShouldDelegate() throws InterruptedException {
factory.waitToStart();
verify(consumerThreadFactory).waitToStart();
}
@Test
public void givenAConsumerIsCurrentlyBeingCreatedWhenNewConsumerIsCalledThenNothingShouldHappen() {
// given
factory.newConsumer(queue, strategy);
// when
assertThat(factory.newConsumer(null, null), is(false));
// then
verify(consumerThreadFactory, times(1)).newConsumer(queue, strategy);
verify(consumerThreadFactory, never()).newConsumer(null, null);
}
@Test
public void givenManyConsumersAreCurrentlyBeingCreatedWhenNewConsumerIsCalledThenNothingShouldHappen() {
// given
factory.startConsumers(queue, strategy, 3);
// when
assertThat(factory.newConsumer(null, null), is(false));
// then
verify(consumerThreadFactory, times(1)).startConsumers(queue, strategy, 3);
verify(consumerThreadFactory, never()).newConsumer(null, null);
}
@Test
public void givenAConsumerHasRecentlyBeenCreatedWhenSufficientTimeHasPassedThenANewConsumerCanBeCreated() throws Exception {
// given
factory.newConsumer(queue, strategy);
// when
Thread.sleep(20);
// then
assertThat(factory.newConsumer(null, null), is(true));
// then
verify(consumerThreadFactory, times(1)).newConsumer(queue, strategy);
verify(consumerThreadFactory, times(1)).newConsumer(null, null);
}
// @Test
// public void givenManyConsumersAreCurrentlyBeingCreatedWhenNewConsumerIsCalledThenNothingShouldHappen() {
// WipConsumerThreadFactoryDefault<String, String> factory = new WipConsumerThreadFactoryDefault<String, String>(consumerFactory, wipQueueThreadFactory, 1000);
//
// given(wipQueueThread.isStarted()).willReturn(false); // will never start
// factory.startConsumers(queue, strategy, 5);
//
// factory.newConsumer(queue, strategy);
//
// verify(wipQueueThreadFactory, times(5)).newAndRunningWipQueueThread(strategy, queue, consumer);
// assertThat(factory.consumerCount(), is(5));
// }
// @Test
// public void givenAConsumerHasRecentlyBeenCreatedWhenNewConsumerIsCalledThenNothingShouldHappen() {
// WipConsumerThreadFactoryDefault<String, String> factory = new WipConsumerThreadFactoryDefault<String, String>(consumerFactory, wipQueueThreadFactory, 1000);
//
// given(wipQueueThread.isStarted()).willReturn(true); // will immediately start
// factory.newConsumer(queue, strategy);
//
// factory.newConsumer(queue, strategy);
//
// verify(wipQueueThreadFactory, times(1)).newAndRunningWipQueueThread(strategy, queue, consumer);
// assertThat(factory.consumerCount(), is(1));
// }
// @Test
// public void givenAConsumerHasRecentlyBeenStoppedWhenNewConsumerIsCalledThenNothingShouldHappen() throws InterruptedException {
// WipConsumerThreadFactoryDefault<String, String> factory = new WipConsumerThreadFactoryDefault<String, String>(consumerFactory, wipQueueThreadFactory, 5);
//
// given(wipQueueThread.isStarted()).willReturn(true); // will immediately start
// factory.newConsumer(queue, strategy);
// Thread.sleep(10);
//
// factory.stopConsumer();
//
// // when
// factory.newConsumer(queue, strategy);
//
// verify(wipQueueThreadFactory, times(1)).newAndRunningWipQueueThread(strategy, queue, consumer); // only the first new
// assertThat(factory.consumerCount(), is(0)); // the first was removed, but the second was added too soon after the stop
// }
@Test
public void shouldWaitForConsumersToStart() {
// pain
}
}
| bsd-3-clause |
jeffseif/queens | queens/matrix.py | 3974 | from queens import PREFIXES
from queens.link import Link
class Matrix:
"""A data structure for DLX (dancing links algorithm X). (Doubly-linked)
head Links link to a list of column Links -- corresponding to constraints
for the set cover problem. Column Links additionally link to rows which
link to their own list of contraints they cover -- corresponding to choices
or possible configurations which assemble to a solution.
"""
def __init__(self, size):
self.size = size
self.solution = []
self.make_primary_columns()
self.make_secondary_columns()
self.make_and_attach_rows()
def make_primary_columns(self):
self.primary = Link(name='primary')
self.primary.attach(self.primary, 'right')
previous = self.primary
for prefix in PREFIXES[: 2]:
for index in range(self.size):
name = (prefix, index)
column = Link(name=name)
column.attach(column, 'up')
previous.attach(column, 'right')
previous = column
def make_secondary_columns(self):
self.secondary = Link(name='secondary')
self.secondary.attach(self.secondary, 'right')
previous = self.secondary
for prefix in PREFIXES[2:]:
for index in range(2 * self.size - 1):
name = (prefix, index)
column = Link(name=name)
column.attach(column, 'up')
previous.attach(column, 'right')
previous = column
def make_and_attach_rows(self):
for index in range(self.size):
for jndex in range(self.size):
names = self.get_names_from_ij(self.size, index, jndex)
previous = None
for column in self.column_link_iter():
if column.name in names:
row = Link(column=column, name=column.name)
column.attach(row, 'up')
column.size += 1
if previous is None:
row.attach(row, 'right')
else:
previous.attach(row, 'right')
previous = row
@staticmethod
def get_names_from_ij(size, index, jndex):
return (
# Rank
(PREFIXES[0], index),
# File
(PREFIXES[1], jndex),
# Diagonal a
(PREFIXES[2], index + jndex),
# Diagonal b
(PREFIXES[3], size - 1 - index + jndex),
)
def column_link_iter(self):
for head in (self.primary, self.secondary):
yield from head.loop('right')
def print_columns(self):
print(','.join(map(str, self.column_link_iter())))
def print_column_rows(self):
for column in self.column_link_iter():
print('{}:'.format(column), ','.join(map(str, column.loop('down'))))
def solve(self):
yield from self.search(self.primary, self.solution)
def search(self, head, solution):
"""The heart of the DLX algorithm."""
column = head.right
if column == head:
yield solution
return
else:
column = self.find_column_of_smallest_size(head)
column.cover()
for row in column.loop('down'):
solution.append(row)
for link in row.loop('right'):
link.column.cover()
yield from self.search(head, solution)
for link in solution.pop().loop('left'):
link.column.uncover()
column.uncover()
@staticmethod
def find_column_of_smallest_size(head):
size = int(1e9)
smallest = None
for column in head.loop('right'):
if column.size < size:
size = column.size
smallest = column
return smallest
| bsd-3-clause |
hperadin/dsl-compiler-client | CommandLineClient/src/main/java/com/dslplatform/compiler/client/parameters/PostgresConnection.java | 13461 | package com.dslplatform.compiler.client.parameters;
import com.dslplatform.compiler.client.CompileParameter;
import com.dslplatform.compiler.client.Context;
import com.dslplatform.compiler.client.ExitException;
import org.postgresql.core.*;
import java.sql.*;
import java.util.*;
import java.util.regex.*;
public enum PostgresConnection implements CompileParameter {
INSTANCE;
@Override
public String getAlias() {
return "postgres";
}
@Override
public String getUsage() {
return "connection_string";
}
private static final String CACHE_NAME = "postgres_dsl_cache";
public static Map<String, String> getDatabaseDsl(final Context context) throws ExitException {
return getDatabaseDslAndVersion(context).dsl;
}
static String extractPostgresVersion(final String version, final Context context) {
final Matcher matcher = Pattern.compile("^\\w+\\s+(\\d+\\.\\d+)").matcher(version);
if (!matcher.find()) {
context.warning("Unable to detect Postgres version. Found version info: " + version);
return "";
}
return matcher.group(1);
}
public static DatabaseInfo getDatabaseDslAndVersion(final Context context) throws ExitException {
final DatabaseInfo cache = context.load(CACHE_NAME);
if (cache != null) {
return cache;
}
final String value = context.get(INSTANCE);
final String connectionString = "jdbc:postgresql://" + value;
Connection conn;
Statement stmt;
final String postgres;
try {
conn = DriverManager.getConnection(connectionString);
stmt = conn.createStatement();
final ResultSet pgVersion = stmt.executeQuery("SELECT version()");
if (pgVersion.next()) {
postgres = extractPostgresVersion(pgVersion.getString(1), context);
} else {
postgres = "";
}
pgVersion.close();
} catch (SQLException e) {
context.error("Error opening connection to " + connectionString);
context.error(e);
throw new ExitException();
}
final DatabaseInfo emptyResult = new DatabaseInfo("Postgres", "", postgres, new HashMap<String, String>());
final boolean hasNewTable;
try {
final ResultSet migrationExist =
stmt.executeQuery(
"SELECT EXISTS(SELECT 1 FROM pg_tables WHERE schemaname = '-DSL-' AND tablename = 'database_migration') AS new_name, " +
"EXISTS(SELECT 1 FROM pg_tables WHERE schemaname = '-NGS-' AND tablename = 'database_migration') AS old_name");
final boolean hasOldTable;
if (migrationExist.next()) {
hasNewTable = migrationExist.getBoolean(1);
hasOldTable = migrationExist.getBoolean(2);
} else {
hasNewTable = false;
hasOldTable = false;
}
migrationExist.close();
if (!hasNewTable && !hasOldTable) {
stmt.close();
conn.close();
context.cache(CACHE_NAME, emptyResult);
return emptyResult;
}
} catch (SQLException ex) {
context.error("Error checking for migration table in -DSL- schema");
context.error(ex);
cleanup(conn, context);
throw new ExitException();
}
try {
final ResultSet lastMigration = hasNewTable
? stmt.executeQuery("SELECT dsls, version FROM \"-DSL-\".database_migration ORDER BY ordinal DESC LIMIT 1")
: stmt.executeQuery("SELECT dsls, version FROM \"-NGS-\".database_migration ORDER BY ordinal DESC LIMIT 1");
final String lastDsl;
final String compiler;
if (lastMigration.next()) {
lastDsl = lastMigration.getString(1);
compiler = lastMigration.getString(2);
} else {
lastDsl = compiler = "";
}
lastMigration.close();
stmt.close();
conn.close();
if (lastDsl != null && lastDsl.length() > 0) {
final Map<String, String> dslMap = DatabaseInfo.convertToMap(lastDsl, context);
final DatabaseInfo result = new DatabaseInfo("Postgres", compiler, postgres, dslMap);
context.cache(CACHE_NAME, result);
return result;
}
} catch (SQLException ex) {
context.error("Error loading previous DSL from migration table in -DSL- schema");
context.error(ex);
cleanup(conn, context);
throw new ExitException();
}
context.cache(CACHE_NAME, emptyResult);
return emptyResult;
}
public static void execute(final Context context, final String sql) throws ExitException {
final String connectionString = "jdbc:postgresql://" + context.get(INSTANCE);
Connection conn;
final BaseStatement stmt;
try {
conn = DriverManager.getConnection(connectionString);
stmt = (BaseStatement) conn.createStatement();
} catch (SQLException e) {
context.error("Error opening connection to " + connectionString);
context.error(e);
throw new ExitException();
}
try {
try {
final long startAt = System.currentTimeMillis();
final boolean[] isDone = new boolean[1];
final boolean[] hasErrors = new boolean[1];
final Thread waitResp = new Thread(new Runnable() {
@Override
public void run() {
try {
stmt.executeWithFlags(sql, QueryExecutor.QUERY_EXECUTE_AS_SIMPLE);
hasErrors[0] = false;
} catch (Exception ex) {
context.error(ex);
hasErrors[0] = true;
}
isDone[0] = true;
}
});
waitResp.start();
waitResp.join(100);
int timeout = 0;
while (!isDone[0] && timeout < 600) {
timeout += 1;
waitResp.join(1000);
if (timeout == 10) {
context.warning("Query execution is taking a long time...");
} else if (timeout % 10 == 0) {
context.warning("Still waiting...");
}
if (!isDone[0] && (timeout % 30 == 0) && context.canInteract()) {
String response = context.ask("Abort executing query [y/N]?");
if ("y".equalsIgnoreCase(response)) {
if (!isDone[0]) {
context.error("Canceled SQL script execution");
throw new ExitException();
}
}
}
}
final long endAt = System.currentTimeMillis();
if (hasErrors[0]) {
context.error("Error executing SQL script.");
throw new ExitException();
} else if (isDone[0]) {
context.log("Script executed in " + (endAt - startAt) + "ms");
} else {
context.error("Failed to execute script. Timeout out waiting.");
throw new ExitException();
}
} catch (Exception ex) {
context.error("Error executing SQL script");
context.error(ex);
throw new ExitException();
}
} finally {
try {
conn.close();
} catch (Exception ignore) {
}
}
}
private static void cleanup(final Connection conn, final Context context) {
try {
conn.close();
} catch (SQLException ex2) {
context.error("Error cleaning up connection.");
context.error(ex2);
}
}
private static Properties parse(final String connectionString) {
final int questionIndex = connectionString.indexOf('?');
if (questionIndex == -1) {
return new Properties();
}
final String[] args = connectionString.substring(questionIndex + 1).split("&");
final Properties map = new Properties();
for (final String a : args) {
final String[] vals = a.split("=");
if (vals.length != 2) {
return null;
}
map.put(vals[0], vals[1]);
}
return map;
}
private static boolean testConnection(final Context context) throws ExitException {
final String connectionString = context.get(INSTANCE);
try {
final Connection conn = DriverManager.getConnection("jdbc:postgresql://" + connectionString);
final Statement stmt = conn.createStatement();
stmt.execute(";");
stmt.close();
conn.close();
} catch (SQLException e) {
if (context.canInteract()) {
context.warning("Error connecting to the database.");
context.warning(e);
} else {
context.error("Error connecting to the database.");
context.error(e);
}
final boolean dbDoesntExists = "3D000".equals(e.getSQLState());
final boolean dbMissingPassword = "08004".equals(e.getSQLState());
final boolean dbWrongPassword = "28P01".equals(e.getSQLState());
final Properties args = parse(connectionString);
if (args == null) {
context.show();
context.error("Invalid connection string provided: " + connectionString);
context.show("Example connection string: 127.0.0.1:5432/RevenjDb?user=postgres&password=secret");
return false;
}
if (dbDoesntExists && context.contains(Force.INSTANCE) && context.contains(ApplyMigration.INSTANCE)
&& args.containsKey("user") && args.containsKey("password")) {
final int sl = connectionString.indexOf("/");
final String dbName = connectionString.substring(sl + 1, connectionString.indexOf("?"));
if (!context.canInteract()) {
context.show("Trying to create new database " + dbName + " due to force option");
} else {
final String answer = context.ask("Create a new database " + dbName + " (y/N):");
if (!"y".equalsIgnoreCase(answer)) {
throw new ExitException();
}
}
try {
final StringBuilder newCs = new StringBuilder(connectionString.substring(0, sl + 1));
newCs.append("postgres?");
for (final Map.Entry<Object, Object> kv : args.entrySet()) {
newCs.append(kv.getKey()).append("=").append(kv.getValue());
newCs.append("&");
}
final Connection conn = DriverManager.getConnection("jdbc:postgresql://" + newCs.toString());
final Statement stmt = conn.createStatement();
stmt.execute("CREATE DATABASE \"" + dbName + "\"");
stmt.close();
conn.close();
} catch (SQLException ex) {
context.error("Error creating new database: " + dbName);
context.error(ex);
return false;
}
return true;
} else if (!context.canInteract()) {
if (dbMissingPassword) {
context.show();
context.error("Password not sent. Since interaction is not available, password must be sent as argument.");
context.show("Example connection string: my.server.com:5432/MyDatabase?user=user&password=password");
} else if (dbDoesntExists) {
context.show();
context.error("Database not found. Since interaction is not available and both force and apply option are not enabled, existing database must be used.");
} else if (dbWrongPassword) {
context.show();
context.error("Please provide correct password to access Postgres database.");
}
throw new ExitException();
} else if (dbDoesntExists) {
context.show();
if (context.contains(ApplyMigration.INSTANCE)) {
context.error("Database not found. Since force option is not enabled, existing database must be used.");
} else {
context.error("Database not found. Use both force and apply to both create a new database and apply migration to it.");
}
return false;
}
if (args.getProperty("password") != null) {
final String answer = context.ask("Retry database connection with different credentials (y/N):");
if (!"y".equalsIgnoreCase(answer)) {
return false;
}
} else {
final String user = args.getProperty("user");
final String question;
if (user != null) {
question = "Postgres username (" + user + "): ";
} else {
question = "Postgres username: ";
}
final String value = context.ask(question);
if (value.length() > 0) {
args.put("user", value);
} else if (user == null) {
context.error("Username not provided");
throw new ExitException();
}
}
final char[] pass = context.askSecret("Postgres password: ");
args.put("password", new String(pass));
final int questionIndex = connectionString.indexOf('?');
final String newCs = questionIndex == -1
? connectionString + "?"
: connectionString.substring(0, questionIndex + 1);
final StringBuilder csBuilder = new StringBuilder(newCs);
for (final Map.Entry<Object, Object> kv : args.entrySet()) {
csBuilder.append(kv.getKey()).append("=").append(kv.getValue());
csBuilder.append("&");
}
context.put(INSTANCE, csBuilder.toString());
return testConnection(context);
}
return true;
}
@Override
public boolean check(final Context context) throws ExitException {
if (!context.contains(INSTANCE)) {
return true;
}
final String value = context.get(INSTANCE);
if (value == null || !value.contains("/")) {
context.error("Invalid connection string defined. An example: localhost:5433/DbRevenj?user=postgres&password=password");
throw new ExitException();
}
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException ex) {
context.error("Error loading Postgres driver.");
throw new ExitException();
}
return testConnection(context);
}
@Override
public void run(final Context context) {
}
@Override
public String getShortDescription() {
return "Connection string to Postgres database. To create an SQL migration a database with previous DSL must be provided";
}
@Override
public String getDetailedDescription() {
return "Previous version of DSL is required for various actions, such as diff and SQL migration.\n" +
"Connection string can be passed from the properties file or as command argument.\n" +
"If password is not defined in the connection string and console is available, it will prompt for database credentials.\n" +
"\n" +
"Example connection strings:\n" +
"\n" +
"\tlocalhost/mydb\n" +
"\tlocalhost/Database?user=postgres\n" +
"\tserver:5432/DB?user=migration&password=secret&ssl=true\n" +
"\n" +
"More info about connection strings can be found on PostgreSQL JDBC site: http://jdbc.postgresql.org/documentation/93/connect.html\n" +
"Connection string is defined without the jdbc:postgresql:// part";
}
}
| bsd-3-clause |
dtmo/jfiglet | src/test/java/com/github/dtmo/jfiglet/LayoutOptionsTest.java | 1993 | package com.github.dtmo.jfiglet;
import static org.junit.Assert.*;
import org.junit.Test;
import com.github.dtmo.jfiglet.LayoutOptions;
public class LayoutOptionsTest {
@Test
public void testIsIncludedIn() {
// 24463 = binary (msb) 101111110001111 (lsb)
assertTrue(LayoutOptions.islayoutOptionSelected(LayoutOptions.HORIZONTAL_EQUAL_CHARACTER_SMUSHING, 24463)); // (1),
assertTrue(LayoutOptions.islayoutOptionSelected(LayoutOptions.HORIZONTAL_UNDERSCORE_SMUSHING, 24463)); // (2),
assertTrue(LayoutOptions.islayoutOptionSelected(LayoutOptions.HORIZONTAL_HIERARCHY_SMUSHING, 24463)); // (4),
assertTrue(LayoutOptions.islayoutOptionSelected(LayoutOptions.HORIZONTAL_OPPOSITE_PAIR_SMUSHING, 24463)); // (8),
assertFalse(LayoutOptions.islayoutOptionSelected(LayoutOptions.HORIZONTAL_BIG_X_SMUSHING, 24463)); // (16),
assertFalse(LayoutOptions.islayoutOptionSelected(LayoutOptions.HORIZONTAL_HARDBLANK_SMUSHING, 24463)); // (32),
assertFalse(LayoutOptions.islayoutOptionSelected(LayoutOptions.HORIZONTAL_FITTING_BY_DEFAULT, 24463)); // (64),
assertTrue(LayoutOptions.islayoutOptionSelected(LayoutOptions.HORIZONTAL_SMUSHING_BY_DEFAULT, 24463)); // (128),
assertTrue(LayoutOptions.islayoutOptionSelected(LayoutOptions.VERTICAL_EQUAL_CHARACTER_SMUSHING, 24463)); // (256),
assertTrue(LayoutOptions.islayoutOptionSelected(LayoutOptions.VERTICAL_UNDERSCORE_SMUSHING, 24463)); // (512),
assertTrue(LayoutOptions.islayoutOptionSelected(LayoutOptions.VERTICAL_HIERARCHY_SMUSHING, 24463)); // (1024),
assertTrue(LayoutOptions.islayoutOptionSelected(LayoutOptions.VERTICAL_HORIZONTAL_LINE_SMUSHING, 24463)); // (2048),
assertTrue(LayoutOptions.islayoutOptionSelected(LayoutOptions.VERTICAL_VERTICAL_LINE_SMUSHING, 24463)); // (4096),
assertFalse(LayoutOptions.islayoutOptionSelected(LayoutOptions.VERTICAL_FITTING_BY_DEFAULT, 24463)); // (8192),
assertTrue(LayoutOptions.islayoutOptionSelected(LayoutOptions.VERTICAL_SMUSHING_BY_DEFAULT, 24463)); // (16384);
}
}
| bsd-3-clause |
Phoenix1708/t2-server-jar-android-0.1 | src/main/java/uk/org/taverna/server/client/InputPort.java | 3231 | /*
* Copyright (c) 2012 The University of Manchester, UK.
*
* 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 names of The University of Manchester nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package uk.org.taverna.server.client;
import java.io.File;
import java.io.FileNotFoundException;
/**
*
* @author Robert Haines
*
*/
public final class InputPort extends Port {
private String value;
private String filename;
private boolean remoteFile;
InputPort(Run run, String name, int depth) {
super(run, name, depth);
value = null;
filename = null;
remoteFile = false;
}
public String getValue() {
return value;
}
public void setValue(String value) {
if (run.isInitialized()) {
filename = null;
remoteFile = false;
this.value = value;
}
}
public File getFile() {
return new File(filename);
}
public String getFileName() {
return filename;
}
public void setFile(File file) throws FileNotFoundException {
if (run.isInitialized()) {
if (file.isFile() && file.canRead()) {
value = null;
remoteFile = false;
this.filename = file.getAbsolutePath();
} else {
throw new FileNotFoundException("File '"
+ file.getAbsolutePath()
+ "' either does not exist or is not readable.");
}
}
}
public void setRemoteFile(String filename) {
if (run.isInitialized()) {
value = null;
this.filename = filename;
remoteFile = true;
}
}
public boolean isFile() {
return !(filename == null);
}
public boolean isRemoteFile() {
return isFile() && remoteFile;
}
public boolean isBaclava() {
return run.isBaclavaInput();
}
public boolean isSet() {
return !(value == null) || isFile() || isBaclava();
}
}
| bsd-3-clause |
chikkutechie/glexamples | android/gles_3_helloworld/src/com/example/gles_3_helloworld/GLES3View.java | 4372 | package com.example.gles_3_helloworld;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.opengl.GLES30;
import android.opengl.GLSurfaceView;
import android.util.Log;
public class GLES3View extends GLSurfaceView implements GLSurfaceView.Renderer {
private static final String TAG = "GLES_3_HELLOWORLD";
private static final String VertexShader =
"#version 300 es \n" +
"layout(location = 0) in vec4 aPosition; \n" +
"void main() \n" +
"{ \n" +
" gl_Position = aPosition; \n" +
"} \n" +
" \n";
private static final String FragmentShader =
"#version 300 es \n" +
"precision mediump float; \n" +
"out vec4 fragColor; \n" +
"void main() \n" +
"{ \n" +
" fragColor = vec4(1.0f, 1.0f, 0.0f, 1.0f); \n" +
"} \n" +
"";
final int mPosLoc = 0;
int mProgram;
FloatBuffer mVerticesBuffer;
public GLES3View(Context context) {
super(context);
// setup EGL configurations
setEGLConfigChooser(8, 8, 8, 8, 16, 0);
setEGLContextClientVersion(2);
setRenderer(this);
}
private void init() {
GLES30.glClearColor(0.5f, 0.5f, 0.5f, 1f);
mProgram = createProgram(VertexShader, FragmentShader);
// vertices
float vertices[] = {
-0.75f, -0.75f,
0.75f, -0.75f,
0.75f, 0.75f,
-0.75f, 0.75f
};
// create the float buffer
ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
vbb.order(ByteOrder.nativeOrder());
mVerticesBuffer = vbb.asFloatBuffer();
mVerticesBuffer.put(vertices);
mVerticesBuffer.position(0);
}
private void draw() {
GLES30.glClear(GLES30.GL_COLOR_BUFFER_BIT);
GLES30.glUseProgram(mProgram);
GLES30.glVertexAttribPointer(mPosLoc, 2, GLES30.GL_FLOAT, false, 0, mVerticesBuffer);
GLES30.glEnableVertexAttribArray(mPosLoc);
GLES30.glDrawArrays(GLES30.GL_TRIANGLE_FAN, 0, 4);
}
private int loadShader(int shaderType, String source) {
Log.d(TAG, source);
int shader = GLES30.glCreateShader(shaderType);
if (shader != 0) {
// compile the shader
GLES30.glShaderSource(shader, source);
GLES30.glCompileShader(shader);
int[] compiled = new int[1];
GLES30.glGetShaderiv(shader, GLES30.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0) {
Log.e(TAG, GLES30.glGetShaderInfoLog(shader));
GLES30.glDeleteShader(shader);
shader = 0;
}
}
return shader;
}
private int createProgram(String vertexSource, String fragmentSource) {
int vertexShader = loadShader(GLES30.GL_VERTEX_SHADER, vertexSource);
if (vertexShader == 0) {
return 0;
}
int pixelShader = loadShader(GLES30.GL_FRAGMENT_SHADER, fragmentSource);
if (pixelShader == 0) {
return 0;
}
int program = GLES30.glCreateProgram();
if (program != 0) {
GLES30.glAttachShader(program, vertexShader);
GLES30.glAttachShader(program, pixelShader);
GLES30.glLinkProgram(program);
int []linkStatus = {0};
GLES30.glGetProgramiv(program, GLES30.GL_LINK_STATUS, linkStatus, 0);
if (linkStatus[0] != 1) {
Log.e(TAG, GLES30.glGetProgramInfoLog(program));
GLES30.glDeleteProgram(program);
program = 0;
}
}
return program;
}
public void onDrawFrame(GL10 gl) {
draw();
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
GLES30.glViewport(0, 0, width, height);
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
init();
}
}
| bsd-3-clause |
vanadium/go.jiri | cmd/jiri/project.go | 8579 | // Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bytes"
"fmt"
"path/filepath"
"regexp"
"sort"
"strings"
"text/template"
"v.io/jiri"
"v.io/jiri/project"
"v.io/x/lib/cmdline"
)
var (
branchesFlag bool
cleanupBranchesFlag bool
noPristineFlag bool
checkDirtyFlag bool
showNameFlag bool
formatFlag string
)
func init() {
cmdProjectClean.Flags.BoolVar(&cleanupBranchesFlag, "branches", false, "Delete all non-master branches.")
cmdProjectList.Flags.BoolVar(&branchesFlag, "branches", false, "Show project branches.")
cmdProjectList.Flags.BoolVar(&noPristineFlag, "nopristine", false, "If true, omit pristine projects, i.e. projects with a clean master branch and no other branches.")
cmdProjectShellPrompt.Flags.BoolVar(&checkDirtyFlag, "check-dirty", true, "If false, don't check for uncommitted changes or untracked files. Setting this option to false is dangerous: dirty master branches will not appear in the output.")
cmdProjectShellPrompt.Flags.BoolVar(&showNameFlag, "show-name", false, "Show the name of the current repo.")
cmdProjectInfo.Flags.StringVar(&formatFlag, "f", "{{.Project.Name}}", "The go template for the fields to display.")
}
// cmdProject represents the "jiri project" command.
var cmdProject = &cmdline.Command{
Name: "project",
Short: "Manage the jiri projects",
Long: "Manage the jiri projects.",
Children: []*cmdline.Command{cmdProjectClean, cmdProjectInfo, cmdProjectList, cmdProjectShellPrompt},
}
// cmdProjectClean represents the "jiri project clean" command.
var cmdProjectClean = &cmdline.Command{
Runner: jiri.RunnerFunc(runProjectClean),
Name: "clean",
Short: "Restore jiri projects to their pristine state",
Long: "Restore jiri projects back to their master branches and get rid of all the local branches and changes.",
ArgsName: "<project ...>",
ArgsLong: "<project ...> is a list of projects to clean up.",
}
func runProjectClean(jirix *jiri.X, args []string) (e error) {
localProjects, err := project.LocalProjects(jirix, project.FullScan)
if err != nil {
return err
}
var projects project.Projects
if len(args) > 0 {
for _, arg := range args {
p, err := localProjects.FindUnique(arg)
if err != nil {
fmt.Fprintf(jirix.Stderr(), "Error finding local project %q: %v.\n", p.Name, err)
} else {
projects[p.Key()] = p
}
}
} else {
projects = localProjects
}
if err := project.CleanupProjects(jirix, projects, cleanupBranchesFlag); err != nil {
return err
}
return nil
}
// cmdProjectList represents the "jiri project list" command.
var cmdProjectList = &cmdline.Command{
Runner: jiri.RunnerFunc(runProjectList),
Name: "list",
Short: "List existing jiri projects and branches",
Long: "Inspect the local filesystem and list the existing projects and branches.",
}
// runProjectList generates a listing of local projects.
func runProjectList(jirix *jiri.X, _ []string) error {
states, err := project.GetProjectStates(jirix, noPristineFlag)
if err != nil {
return err
}
var keys project.ProjectKeys
for key := range states {
keys = append(keys, key)
}
sort.Sort(keys)
for _, key := range keys {
state := states[key]
if noPristineFlag {
pristine := len(state.Branches) == 1 && state.CurrentBranch == "master" && !state.HasUncommitted && !state.HasUntracked
if pristine {
continue
}
}
fmt.Fprintf(jirix.Stdout(), "name=%q remote=%q path=%q\n", state.Project.Name, state.Project.Remote, state.Project.Path)
if branchesFlag {
for _, branch := range state.Branches {
s := " "
if branch.Name == state.CurrentBranch {
s += "* "
}
s += branch.Name
if branch.HasGerritMessage {
s += " (exported to gerrit)"
}
fmt.Fprintf(jirix.Stdout(), "%v\n", s)
}
}
}
return nil
}
// cmdProjectInfo represents the "jiri project info" command.
var cmdProjectInfo = &cmdline.Command{
Runner: jiri.RunnerFunc(runProjectInfo),
Name: "info",
Short: "Provided structured input for existing jiri projects and branches",
Long: `
Inspect the local filesystem and provide structured info on the existing projects
and branches. Projects are specified using regular expressions that are matched
against project keys. If no command line arguments are provided the project
that the contains the current directory is used, or if run from outside
of a given project, all projects will be used. The information to be
displayed is specified using a go template, supplied via the -f flag, that is
executed against the v.io/jiri/project.ProjectState structure. This structure
currently has the following fields: ` + fmt.Sprintf("%#v", project.ProjectState{}),
ArgsName: "<project-keys>...",
ArgsLong: "<project-keys>... a list of project keys, as regexps, to apply the specified format to",
}
// runProjectInfo provides structured info on local projects.
func runProjectInfo(jirix *jiri.X, args []string) error {
tmpl, err := template.New("info").Parse(formatFlag)
if err != nil {
return fmt.Errorf("failed to parse template %q: %v", formatFlag, err)
}
regexps := []*regexp.Regexp{}
if len(args) > 0 {
regexps = make([]*regexp.Regexp, len(args), len(args))
for i, a := range args {
re, err := regexp.Compile(a)
if err != nil {
return fmt.Errorf("failed to compile regexp %v: %v", a, err)
}
regexps[i] = re
}
}
dirty := false
for _, slow := range []string{"HasUncommitted", "HasUntracked"} {
if strings.Contains(formatFlag, slow) {
dirty = true
break
}
}
var states map[project.ProjectKey]*project.ProjectState
var keys project.ProjectKeys
if len(args) == 0 {
currentProjectKey, err := project.CurrentProjectKey(jirix)
if err != nil {
return err
}
state, err := project.GetProjectState(jirix, currentProjectKey, true)
if err != nil {
// jiri was run from outside of a project so let's
// use all available projects.
states, err = project.GetProjectStates(jirix, dirty)
if err != nil {
return err
}
for key := range states {
keys = append(keys, key)
}
} else {
states = map[project.ProjectKey]*project.ProjectState{
currentProjectKey: state,
}
keys = append(keys, currentProjectKey)
}
} else {
var err error
states, err = project.GetProjectStates(jirix, dirty)
if err != nil {
return err
}
for key := range states {
for _, re := range regexps {
if re.MatchString(string(key)) {
keys = append(keys, key)
break
}
}
}
}
sort.Sort(keys)
for _, key := range keys {
state := states[key]
out := &bytes.Buffer{}
if err = tmpl.Execute(out, state); err != nil {
return jirix.UsageErrorf("invalid format")
}
fmt.Fprintln(jirix.Stdout(), out.String())
}
return nil
}
// cmdProjectShellPrompt represents the "jiri project shell-prompt" command.
var cmdProjectShellPrompt = &cmdline.Command{
Runner: jiri.RunnerFunc(runProjectShellPrompt),
Name: "shell-prompt",
Short: "Print a succinct status of projects suitable for shell prompts",
Long: `
Reports current branches of jiri projects (repositories) as well as an
indication of each project's status:
* indicates that a repository contains uncommitted changes
% indicates that a repository contains untracked files
`,
}
func runProjectShellPrompt(jirix *jiri.X, args []string) error {
states, err := project.GetProjectStates(jirix, checkDirtyFlag)
if err != nil {
return err
}
var keys project.ProjectKeys
for key := range states {
keys = append(keys, key)
}
sort.Sort(keys)
// Get the key of the current project.
currentProjectKey, err := project.CurrentProjectKey(jirix)
if err != nil {
return err
}
var statuses []string
for _, key := range keys {
state := states[key]
status := ""
if checkDirtyFlag {
if state.HasUncommitted {
status += "*"
}
if state.HasUntracked {
status += "%"
}
}
short := state.CurrentBranch + status
long := filepath.Base(states[key].Project.Name) + ":" + short
if key == currentProjectKey {
if showNameFlag {
statuses = append([]string{long}, statuses...)
} else {
statuses = append([]string{short}, statuses...)
}
} else {
pristine := state.CurrentBranch == "master"
if checkDirtyFlag {
pristine = pristine && !state.HasUncommitted && !state.HasUntracked
}
if !pristine {
statuses = append(statuses, long)
}
}
}
fmt.Println(strings.Join(statuses, ","))
return nil
}
| bsd-3-clause |
javelinjs/spark | core/src/main/scala/spark/Logging.scala | 1876 | package spark
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* Utility trait for classes that want to log data. Creates a SLF4J logger for the class and allows
* logging messages at different levels using methods that only evaluate parameters lazily if the
* log level is enabled.
*/
trait Logging {
// Make the log field transient so that objects with Logging can
// be serialized and used on another machine
@transient
private var log_ : Logger = null
// Method to get or create the logger for this object
def log: Logger = {
if (log_ == null) {
var className = this.getClass().getName()
// Ignore trailing $'s in the class names for Scala objects
if (className.endsWith("$")) {
className = className.substring(0, className.length - 1)
}
log_ = LoggerFactory.getLogger(className)
}
return log_
}
// Log methods that take only a String
def logInfo(msg: => String) = if (log.isInfoEnabled) log.info(msg)
def logDebug(msg: => String) = if (log.isDebugEnabled) log.debug(msg)
def logWarning(msg: => String) = if (log.isWarnEnabled) log.warn(msg)
def logError(msg: => String) = if (log.isErrorEnabled) log.error(msg)
// Log methods that take Throwables (Exceptions/Errors) too
def logInfo(msg: => String, throwable: Throwable) =
if (log.isInfoEnabled) log.info(msg)
def logDebug(msg: => String, throwable: Throwable) =
if (log.isDebugEnabled) log.debug(msg)
def logWarning(msg: => String, throwable: Throwable) =
if (log.isWarnEnabled) log.warn(msg, throwable)
def logError(msg: => String, throwable: Throwable) =
if (log.isErrorEnabled) log.error(msg, throwable)
// Method for ensuring that logging is initialized, to avoid having multiple
// threads do it concurrently (as SLF4J initialization is not thread safe).
def initLogging() { log }
}
| bsd-3-clause |
novafloss/django-aggtrigg | django_aggtrigg/dbcommands.py | 2186 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2014 Rodolphe Quiédeville <rodolphe@quiedeville.org>
#
# 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 django-aggtrigg nor the names of its contributors
# may be used to endorse or promote products derived from this software
# without specific prior written permission.
#
import logging
import sys
from django.db import connections
def execute_raw(sql, database='default'):
"""Execute a raw SQL command
sql (string) : SQL command
database (string): the database name configured in settings
"""
try:
cursor = connections[database].cursor()
cursor.execute(sql)
cursor.close()
return 0
except:
logging.error('Cant execute %s' % (sql))
sys.stderr.write('Cant execute [%s]\n' % (sql))
sys.exit(1)
def lookup(sql, params=None, database='default'):
"""Execute a raw SQL command
sql (string) : SQL command
database (string): the database name configured in settings
"""
try:
cursor = connections[database].cursor()
cursor.execute(sql, params)
row = cursor.fetchone()
cursor.close()
return row[0]
except:
logging.error('Cant execute %s' % (sql))
sys.stderr.write("%s\n" % (mogrify(sql, params)))
return False
def mogrify(sql, params=None, database='default'):
"""Mogrify a command
sql (string) : SQL command
database (string): the database name configured in settings
"""
cursor = connections[database].cursor()
try:
return cursor.mogrify(sql, params)
except AttributeError:
# SQLite has no mogrify function
return "%s -> %s" % (sql, params)
| bsd-3-clause |
LUKKIEN/django-form-designer | form_designer/migrations/0002_auto__chg_field_formdefinitionfield_initial.py | 8545 | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Changing field 'FormDefinitionField.initial'
db.alter_column('form_designer_formdefinitionfield', 'initial', self.gf('django.db.models.fields.TextField')(null=True, blank=True))
def backwards(self, orm):
# Changing field 'FormDefinitionField.initial'
db.alter_column('form_designer_formdefinitionfield', 'initial', self.gf('django.db.models.fields.CharField')(max_length=255, null=True, blank=True))
models = {
'cms.cmsplugin': {
'Meta': {'object_name': 'CMSPlugin'},
'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'language': ('django.db.models.fields.CharField', [], {'max_length': '5', 'db_index': 'True'}),
'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
'publisher_is_draft': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'db_index': 'True', 'blank': 'True'}),
'publisher_public': ('django.db.models.fields.related.OneToOneField', [], {'related_name': "'publisher_draft'", 'unique': 'True', 'null': 'True', 'to': "orm['cms.CMSPlugin']"}),
'publisher_state': ('django.db.models.fields.SmallIntegerField', [], {'default': '0', 'db_index': 'True'}),
'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
},
'cms.placeholder': {
'Meta': {'object_name': 'Placeholder'},
'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'})
},
'form_designer.cmsformdefinition': {
'Meta': {'object_name': 'CMSFormDefinition', 'db_table': "'cmsplugin_cmsformdefinition'", '_ormbases': ['cms.CMSPlugin']},
'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
'form_definition': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['form_designer.FormDefinition']"})
},
'form_designer.formdefinition': {
'Meta': {'object_name': 'FormDefinition'},
'action': ('django.db.models.fields.URLField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'allow_get_initial': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'error_message': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'form_template_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'log_data': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'mail_from': ('form_designer.fields.TemplateCharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'mail_subject': ('form_designer.fields.TemplateCharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'mail_to': ('form_designer.fields.TemplateCharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'message_template': ('form_designer.fields.TemplateTextField', [], {'null': 'True', 'blank': 'True'}),
'method': ('django.db.models.fields.CharField', [], {'default': "'POST'", 'max_length': '10'}),
'name': ('django.db.models.fields.SlugField', [], {'unique': 'True', 'max_length': '255', 'db_index': 'True'}),
'submit_label': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'success_clear': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'success_message': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'success_redirect': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'form_designer.formdefinitionfield': {
'Meta': {'object_name': 'FormDefinitionField'},
'choice_labels': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'choice_model': ('form_designer.fields.ModelNameField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'choice_model_empty_label': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'choice_values': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'decimal_places': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'field_class': ('django.db.models.fields.CharField', [], {'max_length': '32'}),
'form_definition': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['form_designer.FormDefinition']"}),
'help_text': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'include_result': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'initial': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
'label': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'max_digits': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'max_length': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'max_value': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'min_length': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'min_value': ('django.db.models.fields.FloatField', [], {'null': 'True', 'blank': 'True'}),
'name': ('django.db.models.fields.SlugField', [], {'max_length': '255', 'db_index': 'True'}),
'position': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
'regex': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'required': ('django.db.models.fields.BooleanField', [], {'default': 'True', 'blank': 'True'}),
'widget': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'null': 'True', 'blank': 'True'})
},
'form_designer.formlog': {
'Meta': {'object_name': 'FormLog'},
'created': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
'data': ('picklefield.fields.PickledObjectField', [], {'null': 'True', 'blank': 'True'}),
'form_definition': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['form_designer.FormDefinition']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'})
}
}
complete_apps = ['form_designer']
| bsd-3-clause |
versionone/VersionOne.Integration.IntelliJ-IDEA | src/com/versionone/integration/idea/AbstractModel.java | 2830 | /*(c) Copyright 2008, VersionOne, Inc. All rights reserved. (c)*/
package com.versionone.integration.idea;
import com.versionone.common.sdk.IDataLayer;
import com.versionone.common.sdk.Workitem;
import com.versionone.common.sdk.PropertyValues;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
/**
* Abstract model for Details view
*/
public abstract class AbstractModel extends AbstractTableModel {
protected final IDataLayer dataLayer;
protected final Configuration configuration;
public AbstractModel(IDataLayer dataLayer) {
this.dataLayer = dataLayer;
configuration = Configuration.getInstance();
}
protected abstract PropertyValues getAvailableValuesAt(int rowIndex, int columnIndex);
public abstract String getColumnName(int column);
public abstract boolean isCellEditable(int rowIndex, int columnIndex);
protected abstract Configuration.ColumnSetting getRowSettings(int rowIndex);
public abstract boolean isRowChanged(int row);
public TableCellEditor getCellEditor(int row, int col, JTable parent) {
Workitem item = getWorkitem();
Configuration.ColumnSetting rowSettings = getRowSettings(row);
if (rowTypeMatches(rowSettings, Configuration.AssetDetailSettings.STRING_TYPE, Configuration.AssetDetailSettings.EFFORT_TYPE)) {
boolean isReadOnly = rowSettings.readOnly || item.isPropertyReadOnly(rowSettings.attribute);
return EditorFactory.createTextFieldEditor(!isReadOnly);
} else if (rowTypeMatches(rowSettings, Configuration.AssetDetailSettings.LIST_TYPE)) {
return EditorFactory.createComboBoxEditor(item, rowSettings.attribute, getValueAt(row, col));
} else if (rowTypeMatches(rowSettings, Configuration.AssetDetailSettings.MULTI_VALUE_TYPE)) {
return EditorFactory.createMultivalueEditor(item, dataLayer, rowSettings.attribute, parent);
} else if (rowTypeMatches(rowSettings, Configuration.AssetDetailSettings.RICH_TEXT_TYPE)) {
return EditorFactory.createRichEditor(item, rowSettings.attribute, parent);
}
return EditorFactory.createTextFieldEditor(false);
}
private boolean rowTypeMatches(Configuration.ColumnSetting settings, String... types) {
for(String type : types) {
if(settings.type.equals(type)) {
return true;
}
}
return false;
}
@Override
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
if (!getRowSettings(rowIndex).readOnly) {
getWorkitem().setProperty(getRowSettings(rowIndex).attribute, aValue);
fireTableCellUpdated(rowIndex, columnIndex);
}
}
protected abstract Workitem getWorkitem();
} | bsd-3-clause |
rachelleannmorales/aboitiz | vendor/ivan-novakov/php-openid-connect-client/tests/unit/InoOicClientTest/Entity/AbstractEntityTest.php | 4126 | <?php
namespace InoOicClientTest\Entity;
use InoOicClient\Entity\AbstractEntity;
class AbstractEntityTest extends \PHPUnit_Framework_TestCase
{
/**
* @var AbstractEntity
*/
protected $entity = null;
public function setUp()
{
include_once TESTS_ROOT . '/_files/AbstractEntitySubclass.php';
$this->entity = $this->getMockForAbstractClass('InoOicClient\Entity\AbstractEntity');
}
public function testMagicGetter()
{
$value = 'test value';
$property = 'foo_bar';
$camelCase = 'FooBar';
$this->assertNull($this->entity->getFooBar());
$this->entity->fromArray(array(
$property => $value
));
$mapper = $this->createMapperMock();
$mapper->expects($this->once())
->method('camelCaseToProperty')
->with($camelCase)
->will($this->returnValue($property));
$this->entity->setPropertyMapper($mapper);
$this->assertSame($value, $this->entity->getFooBar());
}
public function testMagicSetter()
{
$value = 'test value';
$property = 'foo_bar';
$camelCase = 'FooBar';
$this->assertNull($this->entity->getProperty($property));
$mapper = $this->createMapperMock();
$mapper->expects($this->any())
->method('camelCaseToProperty')
->with($camelCase)
->will($this->returnValue($property));
$mapper->expects($this->any())
->method('propertyToCamelCase')
->with($property)
->will($this->returnValue($camelCase));
$this->entity->setPropertyMapper($mapper);
$this->entity->setFooBar($value);
$properties = $this->entity->toArray();
$this->assertArrayHasKey($property, $properties);
$this->assertSame($value, $properties[$property]);
}
public function testInvalidMagicCall()
{
$this->setExpectedException('InoOicClient\Entity\Exception\InvalidMethodException');
$this->entity->someInvalidCall();
}
public function testFromArray()
{
$properties = array(
'foo' => 'bar'
);
$this->entity->fromArray($properties);
$this->assertSame($properties, $this->entity->toArray());
}
public function testFromArrayWithMerge()
{
$properties = array(
'foo' => 'bar'
);
$newProperties = array(
'foo2' => 'bar2'
);
$finalProperties = array(
'foo' => 'bar',
'foo2' => 'bar2'
);
$this->entity->fromArray($properties);
$this->assertSame($properties, $this->entity->toArray());
$this->entity->fromArray($newProperties);
$this->assertSame($finalProperties, $this->entity->toArray());
}
public function testFromArrayWithReplace()
{
$properties = array(
'foo' => 'bar'
);
$newProperties = array(
'foo2' => 'bar2'
);
$this->entity->fromArray($properties);
$this->assertSame($properties, $this->entity->toArray());
$this->entity->fromArray($newProperties, true);
$this->assertSame($newProperties, $this->entity->toArray());
}
public function testSetUnknownProperty()
{
$entity = new \AbstractEntitySubclass();
$entity->setBar('something');
$this->assertNull($entity->getBar());
}
public function testGetUnknownProperty()
{
$entity = new \AbstractEntitySubclass();
$this->assertNull($entity->getBar());
}
public function testSetKnownProperty()
{
$value = 'testvalue';
$entity = new \AbstractEntitySubclass();
$entity->setFoo($value);
$this->assertSame($value, $entity->getFoo());
}
protected function createMapperMock()
{
$mapper = $this->getMock('InoOicClient\Entity\PropertyMapperInterface');
return $mapper;
}
}
| bsd-3-clause |
xin3liang/platform_external_chromium_org_third_party_skia | src/lazy/SkCachingPixelRef.cpp | 3199 | /*
* Copyright 2013 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkCachingPixelRef.h"
#include "SkBitmapCache.h"
bool SkCachingPixelRef::Install(SkImageGenerator* generator,
SkBitmap* dst) {
SkImageInfo info;
SkASSERT(dst != NULL);
if ((NULL == generator)
|| !(generator->getInfo(&info))
|| !dst->setInfo(info)) {
SkDELETE(generator);
return false;
}
SkAutoTUnref<SkCachingPixelRef> ref(SkNEW_ARGS(SkCachingPixelRef,
(info, generator, dst->rowBytes())));
dst->setPixelRef(ref);
return true;
}
SkCachingPixelRef::SkCachingPixelRef(const SkImageInfo& info,
SkImageGenerator* generator,
size_t rowBytes)
: INHERITED(info)
, fImageGenerator(generator)
, fErrorInDecoding(false)
, fScaledCacheId(NULL)
, fRowBytes(rowBytes) {
SkASSERT(fImageGenerator != NULL);
}
SkCachingPixelRef::~SkCachingPixelRef() {
SkDELETE(fImageGenerator);
SkASSERT(NULL == fScaledCacheId);
// Assert always unlock before unref.
}
bool SkCachingPixelRef::onNewLockPixels(LockRec* rec) {
if (fErrorInDecoding) {
return false; // don't try again.
}
const SkImageInfo& info = this->info();
SkBitmap bitmap;
SkASSERT(NULL == fScaledCacheId);
fScaledCacheId = SkBitmapCache::FindAndLock(this->getGenerationID(), info.fWidth, info.fHeight,
&bitmap);
if (NULL == fScaledCacheId) {
// Cache has been purged, must re-decode.
if (!bitmap.allocPixels(info, fRowBytes)) {
fErrorInDecoding = true;
return false;
}
SkAutoLockPixels autoLockPixels(bitmap);
if (!fImageGenerator->getPixels(info, bitmap.getPixels(), fRowBytes)) {
fErrorInDecoding = true;
return false;
}
fScaledCacheId = SkBitmapCache::AddAndLock(this->getGenerationID(),
info.fWidth, info.fHeight, bitmap);
SkASSERT(fScaledCacheId != NULL);
}
// Now bitmap should contain a concrete PixelRef of the decoded
// image.
SkAutoLockPixels autoLockPixels(bitmap);
void* pixels = bitmap.getPixels();
SkASSERT(pixels != NULL);
// At this point, the autoLockPixels will unlockPixels()
// to remove bitmap's lock on the pixels. We will then
// destroy bitmap. The *only* guarantee that this pointer
// remains valid is the guarantee made by
// SkScaledImageCache that it will not destroy the *other*
// bitmap (SkScaledImageCache::Rec.fBitmap) that holds a
// reference to the concrete PixelRef while this record is
// locked.
rec->fPixels = pixels;
rec->fColorTable = NULL;
rec->fRowBytes = bitmap.rowBytes();
return true;
}
void SkCachingPixelRef::onUnlockPixels() {
SkASSERT(fScaledCacheId != NULL);
SkScaledImageCache::Unlock( static_cast<SkScaledImageCache::ID*>(fScaledCacheId));
fScaledCacheId = NULL;
}
| bsd-3-clause |
kotmonstr/kotmonstr | frontend/modules/banner/views/default/upload.php | 1072 | <?php
//$this->registerJsFile('/js/custom/uploader.js');
// with UI
use dosamigos\fileupload\FileUploadUI;
?>
<div id="content">
<div class="outer">
<div class="inner bg-light lter">
<div id="collapse4" class="body">
<!--Begin Datatables-->
<div class="image-index">
<?=
FileUploadUI::widget([
'model' => new \common\models\Banner,
'attribute' => 'file',
'url' => ['/banner/upload-submit'],
'gallery' => false,
'fieldOptions' => [
'accept' => 'image/*'
],
]);
?>
<div id="progress">
<div class="bar" style="width: 0%;"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<style>
.bar {
height: 18px;
background: green;
}
</style> | bsd-3-clause |
talkingrobots/NIFTi_OCU | nifti_user/ocu/src/Displays/PointCloud2Display.cpp | 6513 | /*
* Copyright (c) 2008, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
//#include "point_cloud2_display.h"
//#include "point_cloud_transformers.h"
//#include "rviz/visualization_manager.h"
////#include "rviz/properties/property.h"
////#include "rviz/properties/property_manager.h"
//#include "rviz/frame_manager.h"
//#include "rviz/validate_floats.h"
#include <ros/time.h>
#include "ogre_tools/point_cloud.h"
#include "FloatValidator.h"
#include "Displays/Transformers/PointCloud/AxisColorPCTransformer.h"
#include "Displays/Transformers/PointCloud/IntensityPCTransformer.h"
#include "Displays/Transformers/PointCloud/PointCloudTransformer.h"
#include <tf/transform_listener.h>
#include <OGRE/OgreSceneNode.h>
#include <OGRE/OgreSceneManager.h>
#include "Displays/Transformers/FrameTransformer.h"
#include "Displays/PointCloud2Display.h"
namespace rviz
{
PointCloud2Display::PointCloud2Display( const std::string& name, Ogre::SceneManager* sceneMgr, FrameTransformer* frameTransformer, ros::CallbackQueueInterface* updateQueue, ros::CallbackQueueInterface* threadQueue )
: PointCloudBase( name, sceneMgr, frameTransformer, updateQueue, threadQueue )
, tf_filter_(*frameTransformer->getTFClient(), "", 10, threaded_nh_)
{
tf_filter_.connectInput(sub_);
tf_filter_.registerCallback(&PointCloud2Display::incomingCloudCallback, this);
frameTransformer->registerFilterForTransformStatusCheck(tf_filter_, this);
// Configures the transformers to something nice for NIFTi
AxisColorPCTransformer* axisColorTransformer = (AxisColorPCTransformer*) transformers["Axis"];
axisColorTransformer->setAxis(1); // 1 is along the Z axis
axisColorTransformer->setAutoComputeBounds(true);
axisColorTransformer->setUseFixedFrame(true);
((IntensityPCTransformer*)transformers["Intensity"])->setAutoComputeIntensityBounds(true);
// /point_map with Intensity is kind of useful
// /point_map with RGB8 is the real scene
// //setTopic("/nifti_point_cloud"); // Topic from Y2
// setTopic("/point_map");
// //setTopic("/scan_point_cloud_color");
// setStyle(ogre_tools::PointCloud::RM_POINTS);
// setAlpha(1);
// setDecayTime(0); // The points will stay 30 seconds
// setXYZTransformer("XYZ");
// setColorTransformer("Intensity");
}
PointCloud2Display::~PointCloud2Display()
{
unsubscribe();
tf_filter_.clear();
}
void PointCloud2Display::setTopic( const std::string& topic )
{
unsubscribe();
topic_ = topic;
reset();
subscribe();
causeRender();
}
void PointCloud2Display::onEnable()
{
PointCloudBase::onEnable();
subscribe();
}
void PointCloud2Display::onDisable()
{
unsubscribe();
tf_filter_.clear();
PointCloudBase::onDisable();
}
void PointCloud2Display::subscribe()
{
if ( !isEnabled() )
{
return;
}
sub_.subscribe(threaded_nh_, topic_, 2);
}
void PointCloud2Display::unsubscribe()
{
sub_.unsubscribe();
}
void PointCloud2Display::incomingCloudCallback(const sensor_msgs::PointCloud2ConstPtr& cloud)
{
// Filter any nan values out of the cloud. Any nan values that make it through to PointCloudBase
// will get their points put off in lala land, but it means they still do get processed/rendered
// which can be a big performance hit
sensor_msgs::PointCloud2Ptr filtered(new sensor_msgs::PointCloud2);
int32_t xi = PointCloudTransformer::findChannelIndex(cloud, "x");
int32_t yi = PointCloudTransformer::findChannelIndex(cloud, "y");
int32_t zi = PointCloudTransformer::findChannelIndex(cloud, "z");
if (xi == -1 || yi == -1 || zi == -1)
{
return;
}
const uint32_t xoff = cloud->fields[xi].offset;
const uint32_t yoff = cloud->fields[yi].offset;
const uint32_t zoff = cloud->fields[zi].offset;
const uint32_t point_step = cloud->point_step;
const size_t point_count = cloud->width * cloud->height;
filtered->data.resize(cloud->data.size());
if (point_count == 0)
{
return;
}
uint32_t output_count = 0;
const uint8_t* ptr = &cloud->data.front();
for (size_t i = 0; i < point_count; ++i)
{
float x = *reinterpret_cast<const float*>(ptr + xoff);
float y = *reinterpret_cast<const float*>(ptr + yoff);
float z = *reinterpret_cast<const float*>(ptr + zoff);
if (FloatValidator::validateFloats(Ogre::Vector3(x, y, z)))
{
memcpy(&filtered->data.front() + (output_count * point_step), ptr, point_step);
++output_count;
}
ptr += point_step;
}
filtered->header = cloud->header;
filtered->fields = cloud->fields;
filtered->data.resize(output_count * point_step);
filtered->height = 1;
filtered->width = output_count;
filtered->is_bigendian = cloud->is_bigendian;
filtered->point_step = point_step;
filtered->row_step = output_count;
addMessage(filtered);
}
void PointCloud2Display::targetFrameChanged()
{
}
void PointCloud2Display::fixedFrameChanged()
{
tf_filter_.setTargetFrame( fixed_frame_ );
PointCloudBase::fixedFrameChanged();
}
} // namespace rviz
| bsd-3-clause |
exponentjs/exponent | android/ReactAndroid/src/main/java/com/facebook/react/ReactRootView.java | 30162 | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react;
import static com.facebook.infer.annotation.ThreadConfined.UI;
import static com.facebook.react.uimanager.common.UIManagerType.DEFAULT;
import static com.facebook.react.uimanager.common.UIManagerType.FABRIC;
import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import androidx.annotation.Nullable;
import com.facebook.common.logging.FLog;
import com.facebook.infer.annotation.Assertions;
import com.facebook.infer.annotation.ThreadConfined;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.CatalystInstance;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactMarker;
import com.facebook.react.bridge.ReactMarkerConstants;
import com.facebook.react.bridge.ReactSoftException;
import com.facebook.react.bridge.UIManager;
import com.facebook.react.bridge.UiThreadUtil;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
import com.facebook.react.common.annotations.VisibleForTesting;
import com.facebook.react.config.ReactFeatureFlags;
import com.facebook.react.modules.appregistry.AppRegistry;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.facebook.react.modules.deviceinfo.DeviceInfoModule;
import com.facebook.react.surface.ReactStage;
import com.facebook.react.uimanager.DisplayMetricsHolder;
import com.facebook.react.uimanager.IllegalViewOperationException;
import com.facebook.react.uimanager.JSTouchDispatcher;
import com.facebook.react.uimanager.PixelUtil;
import com.facebook.react.uimanager.ReactRoot;
import com.facebook.react.uimanager.RootView;
import com.facebook.react.uimanager.UIManagerHelper;
import com.facebook.react.uimanager.UIManagerModule;
import com.facebook.react.uimanager.common.UIManagerType;
import com.facebook.react.uimanager.events.EventDispatcher;
import com.facebook.systrace.Systrace;
/**
* Default root view for catalyst apps. Provides the ability to listen for size changes so that a UI
* manager can re-layout its elements. It delegates handling touch events for itself and child views
* and sending those events to JS by using JSTouchDispatcher. This view is overriding {@link
* ViewGroup#onInterceptTouchEvent} method in order to be notified about the events for all of its
* children and it's also overriding {@link ViewGroup#requestDisallowInterceptTouchEvent} to make
* sure that {@link ViewGroup#onInterceptTouchEvent} will get events even when some child view start
* intercepting it. In case when no child view is interested in handling some particular touch
* event, this view's {@link View#onTouchEvent} will still return true in order to be notified about
* all subsequent touch events related to that gesture (in case when JS code wants to handle that
* gesture).
*/
public class ReactRootView extends FrameLayout implements RootView, ReactRoot {
/** Listener interface for react root view events */
public interface ReactRootViewEventListener {
/** Called when the react context is attached to a ReactRootView. */
void onAttachedToReactInstance(ReactRootView rootView);
}
private static final String TAG = "ReactRootView";
private @Nullable ReactInstanceManager mReactInstanceManager;
private @Nullable String mJSModuleName;
private @Nullable Bundle mAppProperties;
private @Nullable String mInitialUITemplate;
private @Nullable CustomGlobalLayoutListener mCustomGlobalLayoutListener;
private @Nullable ReactRootViewEventListener mRootViewEventListener;
private int mRootViewTag;
private boolean mIsAttachedToInstance;
private boolean mShouldLogContentAppeared;
private @Nullable JSTouchDispatcher mJSTouchDispatcher;
private final ReactAndroidHWInputDeviceHelper mAndroidHWInputDeviceHelper =
new ReactAndroidHWInputDeviceHelper(this);
private boolean mWasMeasured = false;
private int mWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
private int mHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
private int mLastWidth = 0;
private int mLastHeight = 0;
private int mLastOffsetX = Integer.MIN_VALUE;
private int mLastOffsetY = Integer.MIN_VALUE;
private @UIManagerType int mUIManagerType = DEFAULT;
public ReactRootView(Context context) {
super(context);
init();
}
public ReactRootView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public ReactRootView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setClipChildren(false);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.onMeasure");
try {
boolean measureSpecsUpdated =
widthMeasureSpec != mWidthMeasureSpec || heightMeasureSpec != mHeightMeasureSpec;
mWidthMeasureSpec = widthMeasureSpec;
mHeightMeasureSpec = heightMeasureSpec;
int width = 0;
int height = 0;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
if (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
int childSize =
child.getLeft()
+ child.getMeasuredWidth()
+ child.getPaddingLeft()
+ child.getPaddingRight();
width = Math.max(width, childSize);
}
} else {
width = MeasureSpec.getSize(widthMeasureSpec);
}
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) {
for (int i = 0; i < getChildCount(); i++) {
View child = getChildAt(i);
int childSize =
child.getTop()
+ child.getMeasuredHeight()
+ child.getPaddingTop()
+ child.getPaddingBottom();
height = Math.max(height, childSize);
}
} else {
height = MeasureSpec.getSize(heightMeasureSpec);
}
setMeasuredDimension(width, height);
mWasMeasured = true;
// Check if we were waiting for onMeasure to attach the root view.
if (mReactInstanceManager != null && !mIsAttachedToInstance) {
attachToReactInstanceManager();
} else if (measureSpecsUpdated || mLastWidth != width || mLastHeight != height) {
updateRootLayoutSpecs(true, mWidthMeasureSpec, mHeightMeasureSpec);
}
mLastWidth = width;
mLastHeight = height;
} finally {
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
@Override
public void onChildStartedNativeGesture(MotionEvent androidEvent) {
if (mReactInstanceManager == null
|| !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
FLog.w(TAG, "Unable to dispatch touch to JS as the catalyst instance has not been attached");
return;
}
if (mJSTouchDispatcher == null) {
FLog.w(TAG, "Unable to dispatch touch to JS before the dispatcher is available");
return;
}
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
UIManagerModule uiManager = reactContext.getNativeModule(UIManagerModule.class);
if (uiManager != null) {
EventDispatcher eventDispatcher = uiManager.getEventDispatcher();
mJSTouchDispatcher.onChildStartedNativeGesture(androidEvent, eventDispatcher);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
dispatchJSTouchEvent(ev);
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
dispatchJSTouchEvent(ev);
super.onTouchEvent(ev);
// In case when there is no children interested in handling touch event, we return true from
// the root view in order to receive subsequent events related to that gesture
return true;
}
@Override
protected void dispatchDraw(Canvas canvas) {
try {
super.dispatchDraw(canvas);
} catch (StackOverflowError e) {
// Adding special exception management for StackOverflowError for logging purposes.
// This will be removed in the future.
handleException(e);
}
}
@Override
public boolean dispatchKeyEvent(KeyEvent ev) {
if (mReactInstanceManager == null
|| !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
FLog.w(TAG, "Unable to handle key event as the catalyst instance has not been attached");
return super.dispatchKeyEvent(ev);
}
mAndroidHWInputDeviceHelper.handleKeyEvent(ev);
return super.dispatchKeyEvent(ev);
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
if (mReactInstanceManager == null
|| !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
FLog.w(
TAG,
"Unable to handle focus changed event as the catalyst instance has not been attached");
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
return;
}
mAndroidHWInputDeviceHelper.clearFocus();
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
}
@Override
public void requestChildFocus(View child, View focused) {
if (mReactInstanceManager == null
|| !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
FLog.w(
TAG,
"Unable to handle child focus changed event as the catalyst instance has not been attached");
super.requestChildFocus(child, focused);
return;
}
mAndroidHWInputDeviceHelper.onFocusChanged(focused);
super.requestChildFocus(child, focused);
}
private void dispatchJSTouchEvent(MotionEvent event) {
if (mReactInstanceManager == null
|| !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
FLog.w(TAG, "Unable to dispatch touch to JS as the catalyst instance has not been attached");
return;
}
if (mJSTouchDispatcher == null) {
FLog.w(TAG, "Unable to dispatch touch to JS before the dispatcher is available");
return;
}
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
UIManagerModule uiManager = reactContext.getNativeModule(UIManagerModule.class);
if (uiManager != null) {
EventDispatcher eventDispatcher = uiManager.getEventDispatcher();
mJSTouchDispatcher.handleTouchEvent(event, eventDispatcher);
}
}
@Override
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
// Override in order to still receive events to onInterceptTouchEvent even when some other
// views disallow that, but propagate it up the tree if possible.
if (getParent() != null) {
getParent().requestDisallowInterceptTouchEvent(disallowIntercept);
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
// No-op in non-Fabric since UIManagerModule handles actually laying out children.
// In Fabric, update LayoutSpecs just so we update the offsetX and offsetY.
if (mWasMeasured && getUIManagerType() == FABRIC) {
updateRootLayoutSpecs(false, mWidthMeasureSpec, mHeightMeasureSpec);
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (mIsAttachedToInstance) {
removeOnGlobalLayoutListener();
getViewTreeObserver().addOnGlobalLayoutListener(getCustomGlobalLayoutListener());
}
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mIsAttachedToInstance) {
removeOnGlobalLayoutListener();
}
}
private void removeOnGlobalLayoutListener() {
getViewTreeObserver().removeOnGlobalLayoutListener(getCustomGlobalLayoutListener());
}
@Override
public void onViewAdded(View child) {
super.onViewAdded(child);
if (mShouldLogContentAppeared) {
mShouldLogContentAppeared = false;
if (mJSModuleName != null) {
ReactMarker.logMarker(ReactMarkerConstants.CONTENT_APPEARED, mJSModuleName, mRootViewTag);
}
}
}
@Override
public ViewGroup getRootViewGroup() {
return this;
}
/** {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle)} */
public void startReactApplication(ReactInstanceManager reactInstanceManager, String moduleName) {
startReactApplication(reactInstanceManager, moduleName, null);
}
/** {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle, String)} */
public void startReactApplication(
ReactInstanceManager reactInstanceManager,
String moduleName,
@Nullable Bundle initialProperties) {
startReactApplication(reactInstanceManager, moduleName, initialProperties, null);
}
/**
* Schedule rendering of the react component rendered by the JS application from the given JS
* module (@{param moduleName}) using provided {@param reactInstanceManager} to attach to the JS
* context of that manager. Extra parameter {@param launchOptions} can be used to pass initial
* properties for the react component.
*/
@ThreadConfined(UI)
public void startReactApplication(
ReactInstanceManager reactInstanceManager,
String moduleName,
@Nullable Bundle initialProperties,
@Nullable String initialUITemplate) {
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "startReactApplication");
try {
UiThreadUtil.assertOnUiThread();
// TODO(6788889): Use POJO instead of bundle here, apparently we can't just use WritableMap
// here as it may be deallocated in native after passing via JNI bridge, but we want to reuse
// it in the case of re-creating the catalyst instance
Assertions.assertCondition(
mReactInstanceManager == null,
"This root view has already been attached to a catalyst instance manager");
mReactInstanceManager = reactInstanceManager;
mJSModuleName = moduleName;
mAppProperties = initialProperties;
mInitialUITemplate = initialUITemplate;
mReactInstanceManager.createReactContextInBackground();
} finally {
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
@Override
public int getWidthMeasureSpec() {
return mWidthMeasureSpec;
}
@Override
public int getHeightMeasureSpec() {
return mHeightMeasureSpec;
}
@Override
public void setShouldLogContentAppeared(boolean shouldLogContentAppeared) {
mShouldLogContentAppeared = shouldLogContentAppeared;
}
@Nullable
@Override
public String getSurfaceID() {
Bundle appProperties = getAppProperties();
return appProperties != null ? appProperties.getString("surfaceID") : null;
}
public static Point getViewportOffset(View v) {
int[] locationInWindow = new int[2];
v.getLocationInWindow(locationInWindow);
// we need to subtract visibleWindowCoords - to subtract possible window insets, split
// screen or multi window
Rect visibleWindowFrame = new Rect();
v.getWindowVisibleDisplayFrame(visibleWindowFrame);
locationInWindow[0] -= visibleWindowFrame.left;
locationInWindow[1] -= visibleWindowFrame.top;
return new Point(locationInWindow[0], locationInWindow[1]);
}
/**
* Call whenever measure specs change, or if you want to force an update of offsetX/offsetY. If
* measureSpecsChanged is false and the offsetX/offsetY don't change, updateRootLayoutSpecs will
* not be called on the UIManager as a perf optimization.
*
* @param measureSpecsChanged
* @param widthMeasureSpec
* @param heightMeasureSpec
*/
private void updateRootLayoutSpecs(
boolean measureSpecsChanged, final int widthMeasureSpec, final int heightMeasureSpec) {
if (mReactInstanceManager == null) {
FLog.w(TAG, "Unable to update root layout specs for uninitialized ReactInstanceManager");
return;
}
final ReactContext reactApplicationContext = mReactInstanceManager.getCurrentReactContext();
if (reactApplicationContext != null) {
@Nullable
UIManager uiManager =
UIManagerHelper.getUIManager(reactApplicationContext, getUIManagerType());
// Ignore calling updateRootLayoutSpecs if UIManager is not properly initialized.
if (uiManager != null) {
// In Fabric only, get position of view within screen
int offsetX = 0;
int offsetY = 0;
if (getUIManagerType() == FABRIC) {
Point viewportOffset = getViewportOffset(this);
offsetX = viewportOffset.x;
offsetY = viewportOffset.y;
}
if (measureSpecsChanged || offsetX != mLastOffsetX || offsetY != mLastOffsetY) {
uiManager.updateRootLayoutSpecs(
getRootViewTag(), widthMeasureSpec, heightMeasureSpec, offsetX, offsetY);
}
mLastOffsetX = offsetX;
mLastOffsetY = offsetY;
}
}
}
/**
* Unmount the react application at this root view, reclaiming any JS memory associated with that
* application. If {@link #startReactApplication} is called, this method must be called before the
* ReactRootView is garbage collected (typically in your Activity's onDestroy, or in your
* Fragment's onDestroyView).
*/
@ThreadConfined(UI)
public void unmountReactApplication() {
UiThreadUtil.assertOnUiThread();
// Stop surface in Fabric.
// Calling FabricUIManager.stopSurface causes the C++ Binding.stopSurface
// to be called synchronously over the JNI, which causes an empty tree
// to be committed via the Scheduler, which will cause mounting instructions
// to be queued up and synchronously executed to delete and remove
// all the views in the hierarchy.
if (mReactInstanceManager != null && ReactFeatureFlags.enableStopSurfaceOnRootViewUnmount) {
final ReactContext reactApplicationContext = mReactInstanceManager.getCurrentReactContext();
if (reactApplicationContext != null && getUIManagerType() == FABRIC) {
@Nullable
UIManager uiManager =
UIManagerHelper.getUIManager(reactApplicationContext, getUIManagerType());
if (uiManager != null) {
// TODO T48186892: remove when resolved
FLog.e(
TAG,
"stopSurface for surfaceId: " + this.getId(),
new RuntimeException("unmountReactApplication"));
if (getId() == NO_ID) {
ReactSoftException.logSoftException(
TAG,
new RuntimeException(
"unmountReactApplication called on ReactRootView with invalid id"));
} else {
uiManager.stopSurface(this.getId());
}
}
}
}
if (mReactInstanceManager != null && mIsAttachedToInstance) {
mReactInstanceManager.detachRootView(this);
mIsAttachedToInstance = false;
}
mReactInstanceManager = null;
mShouldLogContentAppeared = false;
}
@Override
public void onStage(int stage) {
switch (stage) {
case ReactStage.ON_ATTACH_TO_INSTANCE:
onAttachedToReactInstance();
break;
default:
break;
}
}
public void onAttachedToReactInstance() {
// Create the touch dispatcher here instead of having it always available, to make sure
// that all touch events are only passed to JS after React/JS side is ready to consume
// them. Otherwise, these events might break the states expected by JS.
// Note that this callback was invoked from within the UI thread.
mJSTouchDispatcher = new JSTouchDispatcher(this);
if (mRootViewEventListener != null) {
mRootViewEventListener.onAttachedToReactInstance(this);
}
}
public void setEventListener(ReactRootViewEventListener eventListener) {
mRootViewEventListener = eventListener;
}
@Override
public String getJSModuleName() {
return Assertions.assertNotNull(mJSModuleName);
}
@Override
public @Nullable Bundle getAppProperties() {
return mAppProperties;
}
@Override
public @Nullable String getInitialUITemplate() {
return mInitialUITemplate;
}
@ThreadConfined(UI)
public void setAppProperties(@Nullable Bundle appProperties) {
UiThreadUtil.assertOnUiThread();
mAppProperties = appProperties;
if (getRootViewTag() != 0) {
runApplication();
}
}
/**
* Calls into JS to start the React application. Can be called multiple times with the same
* rootTag, which will re-render the application from the root.
*/
@Override
public void runApplication() {
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.runApplication");
try {
if (mReactInstanceManager == null || !mIsAttachedToInstance) {
return;
}
ReactContext reactContext = mReactInstanceManager.getCurrentReactContext();
if (reactContext == null) {
return;
}
CatalystInstance catalystInstance = reactContext.getCatalystInstance();
String jsAppModuleName = getJSModuleName();
if (mWasMeasured) {
updateRootLayoutSpecs(true, mWidthMeasureSpec, mHeightMeasureSpec);
}
WritableNativeMap appParams = new WritableNativeMap();
appParams.putDouble("rootTag", getRootViewTag());
@Nullable Bundle appProperties = getAppProperties();
if (appProperties != null) {
appParams.putMap("initialProps", Arguments.fromBundle(appProperties));
}
mShouldLogContentAppeared = true;
catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams);
} finally {
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
/**
* Is used by unit test to setup mIsAttachedToWindow flags, that will let this view to be properly
* attached to catalyst instance by startReactApplication call
*/
@VisibleForTesting
/* package */ void simulateAttachForTesting() {
mIsAttachedToInstance = true;
mJSTouchDispatcher = new JSTouchDispatcher(this);
}
private CustomGlobalLayoutListener getCustomGlobalLayoutListener() {
if (mCustomGlobalLayoutListener == null) {
mCustomGlobalLayoutListener = new CustomGlobalLayoutListener();
}
return mCustomGlobalLayoutListener;
}
private void attachToReactInstanceManager() {
Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachToReactInstanceManager");
if (mIsAttachedToInstance) {
return;
}
try {
mIsAttachedToInstance = true;
Assertions.assertNotNull(mReactInstanceManager).attachRootView(this);
getViewTreeObserver().addOnGlobalLayoutListener(getCustomGlobalLayoutListener());
} finally {
Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE);
}
}
@Override
protected void finalize() throws Throwable {
super.finalize();
Assertions.assertCondition(
!mIsAttachedToInstance,
"The application this ReactRootView was rendering was not unmounted before the "
+ "ReactRootView was garbage collected. This usually means that your application is "
+ "leaking large amounts of memory. To solve this, make sure to call "
+ "ReactRootView#unmountReactApplication in the onDestroy() of your hosting Activity or in "
+ "the onDestroyView() of your hosting Fragment.");
}
public int getRootViewTag() {
return mRootViewTag;
}
public void setRootViewTag(int rootViewTag) {
mRootViewTag = rootViewTag;
}
@Override
public void handleException(final Throwable t) {
if (mReactInstanceManager == null || mReactInstanceManager.getCurrentReactContext() == null) {
throw new RuntimeException(t);
}
Exception e = new IllegalViewOperationException(t.getMessage(), this, t);
mReactInstanceManager.getCurrentReactContext().handleException(e);
}
public void setIsFabric(boolean isFabric) {
mUIManagerType = isFabric ? FABRIC : DEFAULT;
}
@Override
public @UIManagerType int getUIManagerType() {
return mUIManagerType;
}
@Nullable
public ReactInstanceManager getReactInstanceManager() {
return mReactInstanceManager;
}
/* package */ void sendEvent(String eventName, @Nullable WritableMap params) {
if (mReactInstanceManager != null) {
mReactInstanceManager
.getCurrentReactContext()
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
}
private class CustomGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
private final Rect mVisibleViewArea;
private final int mMinKeyboardHeightDetected;
private int mKeyboardHeight = 0;
private int mDeviceRotation = 0;
/* package */ CustomGlobalLayoutListener() {
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(getContext().getApplicationContext());
mVisibleViewArea = new Rect();
mMinKeyboardHeightDetected = (int) PixelUtil.toPixelFromDIP(60);
}
@Override
public void onGlobalLayout() {
if (mReactInstanceManager == null
|| !mIsAttachedToInstance
|| mReactInstanceManager.getCurrentReactContext() == null) {
return;
}
checkForKeyboardEvents();
checkForDeviceOrientationChanges();
checkForDeviceDimensionsChanges();
}
private void checkForKeyboardEvents() {
getRootView().getWindowVisibleDisplayFrame(mVisibleViewArea);
final int heightDiff =
DisplayMetricsHolder.getWindowDisplayMetrics().heightPixels - mVisibleViewArea.bottom;
boolean isKeyboardShowingOrKeyboardHeightChanged =
mKeyboardHeight != heightDiff && heightDiff > mMinKeyboardHeightDetected;
if (isKeyboardShowingOrKeyboardHeightChanged) {
mKeyboardHeight = heightDiff;
sendEvent(
"keyboardDidShow",
createKeyboardEventPayload(
PixelUtil.toDIPFromPixel(mVisibleViewArea.bottom),
PixelUtil.toDIPFromPixel(mVisibleViewArea.left),
PixelUtil.toDIPFromPixel(mVisibleViewArea.width()),
PixelUtil.toDIPFromPixel(mKeyboardHeight)));
return;
}
boolean isKeyboardHidden = mKeyboardHeight != 0 && heightDiff <= mMinKeyboardHeightDetected;
if (isKeyboardHidden) {
mKeyboardHeight = 0;
sendEvent(
"keyboardDidHide",
createKeyboardEventPayload(
PixelUtil.toDIPFromPixel(mLastHeight),
0,
PixelUtil.toDIPFromPixel(mVisibleViewArea.width()),
0));
}
}
private void checkForDeviceOrientationChanges() {
final int rotation =
((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay()
.getRotation();
if (mDeviceRotation == rotation) {
return;
}
mDeviceRotation = rotation;
DisplayMetricsHolder.initDisplayMetrics(getContext().getApplicationContext());
emitOrientationChanged(rotation);
}
private void checkForDeviceDimensionsChanges() {
// DeviceInfoModule caches the last dimensions emitted to JS, so we don't need to check here.
emitUpdateDimensionsEvent();
}
private void emitOrientationChanged(final int newRotation) {
String name;
double rotationDegrees;
boolean isLandscape = false;
switch (newRotation) {
case Surface.ROTATION_0:
name = "portrait-primary";
rotationDegrees = 0.0;
break;
case Surface.ROTATION_90:
name = "landscape-primary";
rotationDegrees = -90.0;
isLandscape = true;
break;
case Surface.ROTATION_180:
name = "portrait-secondary";
rotationDegrees = 180.0;
break;
case Surface.ROTATION_270:
name = "landscape-secondary";
rotationDegrees = 90.0;
isLandscape = true;
break;
default:
return;
}
WritableMap map = Arguments.createMap();
map.putString("name", name);
map.putDouble("rotationDegrees", rotationDegrees);
map.putBoolean("isLandscape", isLandscape);
sendEvent("namedOrientationDidChange", map);
}
private void emitUpdateDimensionsEvent() {
DeviceInfoModule deviceInfo =
mReactInstanceManager.getCurrentReactContext().getNativeModule(DeviceInfoModule.class);
if (deviceInfo != null) {
deviceInfo.emitUpdateDimensionsEvent();
}
}
private WritableMap createKeyboardEventPayload(
double screenY, double screenX, double width, double height) {
WritableMap keyboardEventParams = Arguments.createMap();
WritableMap endCoordinates = Arguments.createMap();
endCoordinates.putDouble("height", height);
endCoordinates.putDouble("screenX", screenX);
endCoordinates.putDouble("width", width);
endCoordinates.putDouble("screenY", screenY);
keyboardEventParams.putMap("endCoordinates", endCoordinates);
keyboardEventParams.putString("easing", "keyboard");
keyboardEventParams.putDouble("duration", 0);
return keyboardEventParams;
}
}
}
| bsd-3-clause |
lloydmeta/mygengo-java | com/mygengo/client/payloads/Payload.java | 380 | package com.mygengo.client.payloads;
import org.json.JSONObject;
import com.mygengo.client.exceptions.MyGengoException;
public abstract class Payload
{
/**
* Create a JSONObject representing this payload object
* @return the JSONObject created
* @throws MyGengoException
*/
public abstract JSONObject toJSONObject() throws MyGengoException;
}
| bsd-3-clause |
hanxiao84322/coach_system | views/admin/activity-category/index.php | 961 | <?php
use yii\helpers\Html;
use yii\grid\GridView;
/* @var $this yii\web\View */
/* @var $searchModel app\models\ActivityCategorySearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = '活动类别设置';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="activity-category-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('创建活动类别', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'name',
'create_time',
'create_user',
'update_time',
// 'update_user',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
</div>
| bsd-3-clause |
theislab/scanpy | scanpy/preprocessing/_distributed.py | 427 | import numpy as np
# install dask if available
try:
import dask.array as da
except ImportError:
da = None
def materialize_as_ndarray(a):
"""Convert distributed arrays to ndarrays."""
if type(a) in (list, tuple):
if da is not None and any(isinstance(arr, da.Array) for arr in a):
return da.compute(*a, sync=True)
return tuple(np.asarray(arr) for arr in a)
return np.asarray(a)
| bsd-3-clause |
ephes/django-indieweb | tests/test_token_endpoint.py | 3104 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_django-indieweb
------------
Tests for `django-indieweb` auth endpoint.
"""
from datetime import timedelta
from urllib.parse import unquote
from urllib.parse import parse_qs
from django.test import TestCase
from django.conf import settings
from django.contrib.auth.models import User
from django.urls import reverse
from indieweb import models
class TestIndiewebTokenEndpoint(TestCase):
def setUp(self):
self.username = "foo"
self.email = "foo@example.org"
self.password = "password"
self.auth_code = "authkey"
self.redirect_uri = "https://webapp.example.org/auth/callback"
self.state = 1234567890
self.me = "http://example.org"
self.client_id = "https://webapp.example.org"
self.scope = "post"
self.user = User.objects.create_user(self.username, self.email, self.password)
self.auth = models.Auth.objects.create(
owner=self.user,
key=self.auth_code,
state=self.state,
me=self.me,
scope=self.scope,
client_id=self.client_id,
)
self.endpoint_url = reverse("indieweb:token")
def test_wrong_auth_code(self):
"""Assert we can't get a token with the wrong auth code."""
payload = {
"redirect_uri": self.redirect_uri,
"code": "wrong_key",
"state": self.state,
"me": self.me,
"scope": self.scope,
"client_id": self.client_id,
}
response = self.client.post(self.endpoint_url, data=payload)
self.assertEqual(response.status_code, 401)
self.assertTrue("error" in response.content.decode("utf-8"))
def test_correct_auth_code(self):
"""Assert we get a token when the auth code is correct."""
payload = {
"redirect_uri": self.redirect_uri,
"code": self.auth_code,
"state": self.state,
"me": self.me,
"scope": self.scope,
"client_id": self.client_id,
}
response = self.client.post(self.endpoint_url, data=payload)
self.assertEqual(response.status_code, 201)
data = parse_qs(unquote(response.content.decode("utf-8")))
self.assertTrue("access_token" in data)
def test_auth_code_timeout(self):
"""Assert we can't get a token when the auth code is outdated."""
payload = {
"redirect_uri": self.redirect_uri,
"code": self.auth_code,
"state": self.state,
"me": self.me,
"scope": self.scope,
"client_id": self.client_id,
}
timeout = getattr(settings, "INDIWEB_AUTH_CODE_TIMEOUT", 60)
to_old_delta = timedelta(seconds=(timeout + 1))
self.auth.created = self.auth.created - to_old_delta
self.auth.save()
response = self.client.post(self.endpoint_url, data=payload)
self.assertEqual(response.status_code, 401)
self.assertTrue("error" in response.content.decode("utf-8"))
| bsd-3-clause |
kodiers/yii2build | frontend/views/site/index.php | 6981 | <?php
use \yii\bootstrap\Modal;
use kartik\social\FacebookPlugin;
use \yii\bootstrap\Collapse;
use \yii\bootstrap\Alert;
use \yii\helpers\Html;
/* @var $this yii\web\View */
$this->title = 'Yii2 build';
?>
<div class="site-index">
<div class="jumbotron">
<?php
if (Yii::$app->user->isGuest) {
echo Html::a('Get Started today', ['site/signup'], ['class' => ['btn btn-lg btn-success']]);
}
?>
<h1>Yii 2 build!<i class="fa fa-plug"></i> </h1>
<p class="lead">Use this Yii2 Template to start Projects.</p>
<br>
<?php
echo FacebookPlugin::widget(['type' => FacebookPlugin::LIKE, 'settings' => []]);
?>
<!-- <p><a class="btn btn-lg btn-success" href="http://www.yiiframework.com">Get started with Yii</a></p>-->
</div>
<?php
echo Collapse::widget([
'items' => [
[
'label' => 'Top Features',
'content' => FacebookPlugin::widget([
'type' => FacebookPlugin::SHARE,
'settings' => ['href' => 'http://localhost:8888','width'=>'350']
]),
],
[
'label' => 'Top Resources',
'content' => FacebookPlugin::widget([
'type' => FacebookPlugin::SHARE,
'settings' => ['href' => 'http://localhost:8888','width'=>'350']
]),
],
]
]);
Modal::begin([
'header' => '<h2>Latest Comments</h2>',
'toggleButton' => ['label' => 'comments'],
]);
echo FacebookPlugin::widget([
'type' => FacebookPlugin::COMMENT,
'settings' => ['href' => 'http://localhost:8888','width'=>'350']
]);
Modal::end();
?>
<br>
<br>
<?php
echo Alert::widget([
'options' => [
'class' => 'alert-info',
],
'body' => 'Launch your project like a rocket...',
]);
?>
<div class="body-content">
<div class="row">
<div class="col-lg-4">
<h2>Free</h2>
<p>
<?php
if (!Yii::$app->user->isGuest) {
echo Yii::$app->user->identity->username . ' is doing cool stuff. ';
}
?>
</p>
<p>
Starting with this free, open source Yii 2 template and it will save you
a lot of time. You can deliver projects to the customer quickly, with
a lot of boilerplate already taken care of for you, so you can concentrate
on the complicated stuff.
</p>
<p>
<a class="btn btn-default" href="http://www.yiiframework.com/doc/">
Yii Documentation »
</a>
</p>
<?php
echo FacebookPlugin::widget([
'type' => FacebookPlugin::LIKE,
'settings' => []
]);
?>
</div>
<div class="col-lg-4">
<h2>Advantages</h2>
<p>
Ease of use is a huge advantage. We've simplifiled RBAC and given you Free/Paid
user type out of the box. The Social plugins are so quick and easy to install,
you will love it!
</p>
<p>
<a class="btn btn-default" href="http://www.yiiframework.com/forum/">
Yii Forum »</a>
</p>
<?php
echo FacebookPlugin::widget([
'type'=>FacebookPlugin::COMMENT,
'settings' => ['href'=>'http://www.yii2build.com','width'=>'350']
]);
?>
</div>
<div class="col-lg-4">
<h2>Code Quick, Code Right!</h2>
<p>
Leverage the power of the awesome Yii 2 framework with this enhanced template.
Based Yii 2's advanced template, you get a full frontend and backend
implementation that features rich UI for backend management.
</p>
<p>
<a class="btn btn-default" href="http://www.yiiframework.com/extensions/">
Yii Extensions »</a>
</p>
</div>
</div>
</div>
<!-- <div class="body-content">-->
<!---->
<!-- <div class="row">-->
<!-- <div class="col-lg-4">-->
<!-- <h2>Heading</h2>-->
<!---->
<!-- <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et-->
<!-- dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip-->
<!-- ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu-->
<!-- fugiat nulla pariatur.</p>-->
<!---->
<!-- <p><a class="btn btn-default" href="http://www.yiiframework.com/doc/">Yii Documentation »</a></p>-->
<!-- </div>-->
<!-- <div class="col-lg-4">-->
<!-- <h2>Heading</h2>-->
<!---->
<!-- <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et-->
<!-- dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip-->
<!-- ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu-->
<!-- fugiat nulla pariatur.</p>-->
<!---->
<!-- <p><a class="btn btn-default" href="http://www.yiiframework.com/forum/">Yii Forum »</a></p>-->
<!-- </div>-->
<!-- <div class="col-lg-4">-->
<!-- <h2>Heading</h2>-->
<!---->
<!-- <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et-->
<!-- dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip-->
<!-- ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu-->
<!-- fugiat nulla pariatur.</p>-->
<!---->
<!-- <p><a class="btn btn-default" href="http://www.yiiframework.com/extensions/">Yii Extensions »</a></p>-->
<!-- </div>-->
<!-- </div>-->
<!---->
<!-- </div>-->
</div>
| bsd-3-clause |
lightster/lstr-silex-config | src/Lstr/Silex/Config/ConfigServiceProvider.php | 603 | <?php
/*
* Lstr/Silex source code
*
* Copyright Matt Light <matt.light@lightdatasys.com>
*
* For copyright and licensing information, please view the LICENSE
* that is distributed with this source code.
*/
namespace Lstr\Silex\Config;
use Silex\Application;
use Silex\ServiceProviderInterface;
class ConfigServiceProvider implements ServiceProviderInterface
{
public function register(Application $app)
{
$app['lstr.config'] = $app->share(function ($app) {
return new ConfigService($app);
});
}
public function boot(Application $app)
{
}
}
| bsd-3-clause |
HTeamCoder/LichtuanVMU | backend/views/nhanvien/sinhnhat.php | 2393 | <?php
use yii\helpers\Html;
use yii\grid\GridView;
$this->title = Yii::t('app', 'Sinh nhật của cán bộ');
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="nhanvien-view">
<p>
<?= Html::a(Yii::t('app', 'Cài đặt hiển thị'), ['time'], ['class' => 'btn btn-primary']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'summary' => "<h3 class='text-center'>Danh sách cán bộ có ngày sinh nhật hôm nay</h3>",
'emptyText'=>'<p class="text-center"><strong class="text-danger">Không tìm thấy kết quả nào</strong></p>',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'attribute'=>'ten',
'label'=>'Họ tên',
'value'=>function($model)
{
return $model['ten'];
},
'filter'=>false
],
[
'attribute'=>'tuoi',
'label'=>'Tuổi',
'value'=>function($model)
{
return $model['tuoi'];
},
'filter'=>false
],
[
'attribute'=>'donvi',
'label'=>'Đơn vị',
'value'=>function($model)
{
return $model['donvi'];
},
'filter'=>false
],
[
'attribute'=>'trinhdo',
'label'=>'Trình độ',
'value'=>function($model)
{
return $model['trinhdo'];
},
'filter'=>false
],
[
'attribute'=>'ngaysinh',
'label'=>'Ngày sinh',
'value'=>function($model)
{
return $model['ngaysinh'];
},
'filter'=>false
],
[
'attribute'=>'gioitinh',
'label'=>'Giới tính',
'value'=>function($model)
{
return $model['gioitinh'];
},
'filter'=>false
],
],
]); ?>
</div> | bsd-3-clause |
the-ms/engine | assets/AppAsset.php | 651 | <?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace app\assets;
use yii\web\AssetBundle;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class AppAsset extends AssetBundle
{
public $basePath = '@webroot';
public $baseUrl = '@web';
public $css = [
'css/site.css',
];
public $js = [
'js/site.js',
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
'yii\bootstrap\BootstrapPluginAsset',
'\app\assets\LightBoxAsset',
];
}
| bsd-3-clause |
edgsv/proyectoasi2 | models/Solicitud.php | 3119 | <?php
namespace app\models;
use yii\helpers\ArrayHelper;
use Yii;
/**
* This is the model class for table "solicitud".
*
* @property integer $id_solicitud
* @property string $fecha
* @property string $telefono
* @property string $email
* @property string $nombre
* @property string $direccion
* @property string $observacion
* @property integer $id_estado
* @property integer $id_fuente
* @property integer $id_usuario
* @property string $referencia
* @property integer $id_ruta
*
* @property Estado $idEstado
* @property Fuente $idFuente
* @property Ruta $idRuta
*/
class Solicitud extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'solicitud';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['telefono','nombre','direccion','observacion','comentario', 'id_colonia'], 'required'],
[['id_colonia'], 'integer'],
[['fecha'], 'safe'],
[['telefono', 'email', 'nombre', 'direccion', 'observacion', 'referencia'], 'string'],
['email', 'filter', 'filter' => 'trim'],
['email', 'email'],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id_solicitud' => 'No. de Ref.',
'fecha' => 'Fecha',
'telefono' => 'Telefono',
'email' => 'Email',
'nombre' => 'Nombre',
'direccion' => 'Direccion',
'observacion' => 'Observacion',
'id_estado' => 'Estado',
'id_fuente' => 'Fuente',
'id_usuario' => 'Ingresó',
'referencia' => 'Punto de Referencia',
'id_colonia' => 'Colonia',
'comentario' => 'Comentario',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getIdEstado()
{
return $this->hasMany(Estado::className(), ['estado' => 'estado']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getIdFuente()
{
return $this->hasOne(Fuente::className(), ['id_fuente' => 'id_fuente']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getIdRuta()
{
return $this->hasOne(Ruta::className(), ['id_ruta' => 'id_ruta']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getIdColonia()
{
return $this->hasOne(Colonia::className(), ['id_colonia' => 'id_colonia']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getIdUsuario()
{
return $this->hasMany(Usuario::className(), ['id_usuario' => 'id_usuario']);
}
public function getMenuRutas()
{
return ArrayHelper::map(Ruta::find()->all(), 'id_ruta', 'nombre');
}
public function getMenuColonias()
{
return ArrayHelper::map(Colonia::find()->all(), 'id_colonia', 'nombre');
}
}
| bsd-3-clause |
smartdevicelink/sdl_atf_test_scripts | test_scripts/API/ATF_DeleteFile.lua | 89261 | Test = require('connecttest')
require('cardinalities')
local events = require('events')
local mobile_session = require('mobile_session')
local mobile = require('mobile_connection')
local tcp = require('tcp_connection')
local file_connection = require('file_connection')
---------------------------------------------------------------------------------------------
-----------------------------Required Shared Libraries---------------------------------------
---------------------------------------------------------------------------------------------
require('user_modules/AppTypes')
local commonTestCases = require('user_modules/shared_testcases/commonTestCases')
local commonSteps = require('user_modules/shared_testcases/commonSteps')
local commonFunctions = require('user_modules/shared_testcases/commonFunctions')
local policyTable = require('user_modules/shared_testcases/testCasesForPolicyTable')
APIName = "DeleteFile" -- use for above required scripts.
local iTimeout = 5000
local str255Chars = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
local appID0
local iPutFile_SpaceAvailable = 0
local iSpaceAvailable_BeforePutFile = 0
config.deviceMAC = "12ca17b49af2289436f303e0166030a21e525d266e209267433801a8fd4071a0"
local appIDAndDeviceMac = config.application1.registerAppInterfaceParams.fullAppID.. "_" .. config.deviceMAC.. "/"
--local strAppFolder = config.SDLStoragePath..appIDAndDeviceMac
strAppFolder = config.pathToSDL .. "storage/"..appIDAndDeviceMac
--Process different audio states for media and non-media application
local audibleState
if commonFunctions:isMediaApp() then
audibleState = "AUDIBLE"
else
audibleState = "NOT_AUDIBLE"
end
---------------------------------------------------------------------------------------------
-------------------------------------------Common functions-------------------------------------
---------------------------------------------------------------------------------------------
--Description: Function used to check file is existed on expected path
--file_name: file want to check
function file_check(file_name)
local file_found=io.open(file_name, "r")
if file_found==nil then
return false
else
return true
end
end
-- Test case sending request and checking results in case SUCCESS
local function TC_DeleteFile_SUCCESS(self, strTestCaseName, strFileName, strFileType)
Test[strTestCaseName] = function(self)
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = strFileName
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved",
{
fileName = strAppFolder .. strFileName,
fileType = strFileType,
appID = self.applications[config.application1.registerAppInterfaceParams.appName]
})
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", info = nil })
:ValidIf (function(_,data)
if data.payload.spaceAvailable == nil then
commonFunctions:printError("spaceAvailable parameter is missed")
return false
else
if file_check(strAppFolder .. strFileName) == true then
print(" \27[36m File is not delete from storage \27[0m ")
return false
else
return true
end
end
end)
end
end
-- Test case sending request and checking results and spaceAvailable in case SUCCESS
local function TC_DeleteFile_Check_spaceAvailable_SUCCESS(self, strTestCaseName, strFileName, strFileType)
Test[strTestCaseName] = function(self)
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = strFileName
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved",
{
fileName = strAppFolder .. strFileName,
fileType = strFileType,
appID = self.applications[config.application1.registerAppInterfaceParams.appName]
})
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", spaceAvailable = iSpaceAvailable_BeforePutFile, info = nil})
:Do(function(_,data)
--Store spaceAvailable value
--iSpaceAvailable_BeforePutFile = data.payload.spaceAvailable
--commonFunctions:printError("DeleteFile:spaceAvailable: " .. data.payload.spaceAvailable )
end)
end
end
-- Put file to prepare for delete file step.
function putfile(self, strFileName, strFileType, blnPersistentFile, blnSystemFile, strFileNameOnMobile)
local strTestCaseName, strSyncFileName, strFileNameOnLocal1
if type(strFileName) == "table" then
strTestCaseName = "PutFile_"..strFileName.reportName
strSyncFileName = strFileName.fileName
elseif type(strFileName) == "string" then
strTestCaseName = "PutFile_"..strFileName
strSyncFileName = strFileName
else
commonFunctions:printError("Error: putfile function, strFileName is wrong value type: " .. tostring(strFileName))
end
if strFileNameOnMobile ==nil then
strFileNameOnMobile = "action.png"
end
Test[strTestCaseName] = function(self)
--mobile side: sending Futfile request
local cid = self.mobileSession:SendRPC("PutFile",
{
syncFileName = strSyncFileName,
fileType = strFileType,
persistentFile = blnPersistentFile,
systemFile = blnSystemFile
},
"files/"..strFileNameOnMobile)
--mobile side: expect Futfile response
EXPECT_RESPONSE(cid, { success = true})
:Do(function(_,data)
--Store spaceAvailable value
iPutFile_SpaceAvailable = data.payload.spaceAvailable
end)
:ValidIf(function(_, data)
if file_check(strAppFolder .. strSyncFileName) == false and systemFile == false then
print(" \27[36m File is not put to storage \27[0m ")
return false
else
return true
end
end)
end
end
local function ExpectOnHMIStatusWithAudioStateChanged(self, request, timeout, level)
if request == nil then request = "BOTH" end
if level == nil then level = "FULL" end
if timeout == nil then timeout = 10000 end
if
level == "FULL" then
if
self.isMediaApplication == true or
Test.appHMITypes["NAVIGATION"] == true then
if request == "BOTH" then
--mobile side: OnHMIStatus notifications
EXPECT_NOTIFICATION("OnHMIStatus",
{ hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"},
{ hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "VRSESSION"},
{ hmiLevel = level, audioStreamingState = "ATTENUATED", systemContext = "VRSESSION"},
{ hmiLevel = level, audioStreamingState = "ATTENUATED", systemContext = "HMI_OBSCURED"},
{ hmiLevel = level, audioStreamingState = "AUDIBLE", systemContext = "HMI_OBSCURED"},
{ hmiLevel = level, audioStreamingState = "AUDIBLE", systemContext = "MAIN"})
:Times(6)
elseif request == "VR" then
--mobile side: OnHMIStatus notification
EXPECT_NOTIFICATION("OnHMIStatus",
{ systemContext = "MAIN", hmiLevel = level, audioStreamingState = "ATTENUATED" },
{ systemContext = "MAIN", hmiLevel = level, audioStreamingState = "NOT_AUDIBLE" },
{ systemContext = "VRSESSION", hmiLevel = level, audioStreamingState = "NOT_AUDIBLE" },
{ systemContext = "VRSESSION", hmiLevel = level, audioStreamingState = "AUDIBLE" },
{ systemContext = "MAIN", hmiLevel = level, audioStreamingState = "AUDIBLE" })
:Times(5)
:Timeout(timeout)
elseif request == "MANUAL" then
--mobile side: OnHMIStatus notification
EXPECT_NOTIFICATION("OnHMIStatus",
{ systemContext = "MAIN", hmiLevel = level, audioStreamingState = "ATTENUATED" },
{ systemContext = "HMI_OBSCURED", hmiLevel = level, audioStreamingState = "ATTENUATED" },
{ systemContext = "HMI_OBSCURED", hmiLevel = level, audioStreamingState = "AUDIBLE" },
{ systemContext = "MAIN", hmiLevel = level, audioStreamingState = "AUDIBLE" })
:Times(4)
:Timeout(timeout)
end
elseif
self.isMediaApplication == false then
if request == "BOTH" then
--mobile side: OnHMIStatus notifications
EXPECT_NOTIFICATION("OnHMIStatus",
{ hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "VRSESSION"},
{ hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "HMI_OBSCURED"},
{ hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"})
:Times(3)
:Timeout(timeout)
elseif request == "VR" then
--any OnHMIStatusNotifications
EXPECT_NOTIFICATION("OnHMIStatus",
{ systemContext = "VRSESSION", hmiLevel = level, audioStreamingState = "NOT_AUDIBLE" },
{ systemContext = "MAIN", hmiLevel = level, audioStreamingState = "NOT_AUDIBLE" })
:Times(2)
:Timeout(timeout)
elseif request == "MANUAL" then
--mobile side: OnHMIStatus notification
EXPECT_NOTIFICATION("OnHMIStatus",
{ hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "HMI_OBSCURED"},
{ hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"})
:Times(2)
end
end
elseif
level == "LIMITED" then
if
self.isMediaApplication == true or
Test.appHMITypes["NAVIGATION"] == true then
if request == "BOTH" then
--mobile side: OnHMIStatus notifications
EXPECT_NOTIFICATION("OnHMIStatus",
{ hmiLevel = level, audioStreamingState = "NOT_AUDIBLE", systemContext = "MAIN"},
{ hmiLevel = level, audioStreamingState = "ATTENUATED", systemContext = "MAIN"},
{ hmiLevel = level, audioStreamingState = "AUDIBLE", systemContext = "MAIN"})
:Times(3)
elseif request == "VR" then
--mobile side: OnHMIStatus notification
EXPECT_NOTIFICATION("OnHMIStatus",
{ systemContext = "MAIN", hmiLevel = level, audioStreamingState = "ATTENUATED" },
{ systemContext = "MAIN", hmiLevel = level, audioStreamingState = "NOT_AUDIBLE" },
{ systemContext = "MAIN", hmiLevel = level, audioStreamingState = "AUDIBLE" })
:Times(3)
:Timeout(timeout)
elseif request == "MANUAL" then
--mobile side: OnHMIStatus notification
EXPECT_NOTIFICATION("OnHMIStatus",
{ systemContext = "MAIN", hmiLevel = level, audioStreamingState = "ATTENUATED" },
{ systemContext = "MAIN", hmiLevel = level, audioStreamingState = "AUDIBLE" })
:Times(2)
:Timeout(timeout)
end
elseif
self.isMediaApplication == false then
EXPECT_NOTIFICATION("OnHMIStatus")
:Times(0)
DelayedExp(1000)
end
elseif
level == "BACKGROUND" then
EXPECT_NOTIFICATION("OnHMIStatus")
:Times(0)
DelayedExp(1000)
end
end
local function SendOnSystemContext(self, ctx)
self.hmiConnection:SendNotification("UI.OnSystemContext",{ appID = self.applications[config.application1.registerAppInterfaceParams.appName], systemContext = ctx })
end
---------------------------------------------------------------------------------------------
-------------------------------------------Preconditions-------------------------------------
---------------------------------------------------------------------------------------------
commonSteps:DeleteLogsFileAndPolicyTable()
--Print new line to separate new test cases group
commonFunctions:newTestCasesGroup("Preconditions")
--1. Activate application
commonSteps:ActivationApp()
--2. Update policy to allow request
--TODO: Will be updated after policy flow implementation
--policyTable:precondition_updatePolicy_AllowFunctionInHmiLeves({"BACKGROUND", "FULL", "LIMITED", "NONE"})
policyTable:Precondition_updatePolicy_By_overwriting_preloaded_pt("files/ptu_general.json")
---------------------------------------------------------------------------------------------
-----------------------------------------I TEST BLOCK----------------------------------------
--CommonRequestCheck: Check of mandatory/conditional request's parameters (mobile protocol)--
---------------------------------------------------------------------------------------------
--Check:
-- request with all parameters
-- request with only mandatory parameters
-- request with all combinations of conditional-mandatory parameters (if exist)
-- request with one by one conditional parameters (each case - one conditional parameter)
-- request with missing mandatory parameters one by one (each case - missing one mandatory parameter)
-- request with all parameters are missing
-- request with fake parameters (fake - not from protocol, from another request)
-- request is sent with invalid JSON structure
-- different conditions of correlationID parameter (invalid, several the same etc.)
--Write NewTestBlock to ATF log
function Test:NewTestBlock()
commonFunctions:printError("****************************** I TEST BLOCK: Check of mandatory/conditional request's parameters (mobile protocol) ******************************")
end
--Begin test suit PositiveRequestCheck
--Description:
-- request with all parameters
-- request with only mandatory parameters
-- request with all combinations of conditional-mandatory parameters (if exist)
-- request with one by one conditional parameters (each case - one conditional parameter)
-- request with missing mandatory parameters one by one (each case - missing one mandatory parameter)
-- request with all parameters are missing
-- request with fake parameters (fake - not from protocol, from another request)
-- request is sent with invalid JSON structure
-- different conditions of correlationID parameter (invalid, several the same etc.)
--Begin test case PositiveRequestCheck.1
--Description: check request with all parameters
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150
--Verification criteria:
--Precondition: PutFile
putfile(self, "test.png", "GRAPHIC_PNG")
TC_DeleteFile_SUCCESS(self, "DeleteFile_test.png", "test.png", "GRAPHIC_PNG")
--End test case CommonRequestCheck.1
--Begin test case PositiveRequestCheck.2
--Description: check request with only mandatory parameters --> The same as CommonRequestCheck.1
--End test case PositiveRequestCheck.2
--Skipped CommonRequestCheck.3-4: There next checks are not applicable:
-- request with all combinations of conditional-mandatory parameters (if exist)
-- request with one by one conditional parameters (each case - one conditional parameter)
--Begin test case CommonRequestCheck.5
--Description: This test is intended to check request with missing mandatory parameters one by one (each case - missing one mandatory parameter)
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-715
--Verification criteria: SDL responses invalid data
function Test:DeleteFile_missing_mandatory_parameters_syncFileName_INVALID_DATA()
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
})
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA", info = nil})
:Timeout(iTimeout)
end
--End test case CommonRequestCheck.5
--Begin test case PositiveRequestCheck.6
--Description: check request with all parameters are missing
--> The same as PositiveRequestCheck.5
--End test case PositiveRequestCheck.6
--Begin test case PositiveRequestCheck.7
--Description: check request with fake parameters (fake - not from protocol, from another request)
--Begin test case CommonRequestCheck.7.1
--Description: Check request with fake parameters
--Requirement id in JAMA/or Jira ID: APPLINK-4518
--Verification criteria: According to xml tests by Ford team all fake parameters should be ignored by SDL
--Precondition: PutFile
putfile(self, "test.png", "GRAPHIC_PNG")
function Test:DeleteFile_FakeParameters_SUCCESS()
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
fakeParameter = 123,
syncFileName = "test.png"
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved",
{
fileName = strAppFolder .. "test.png",
fileType = "GRAPHIC_PNG",
appID = self.applications[config.application1.registerAppInterfaceParams.appName]
})
:ValidIf(function(_,data)
if data.params.fakeParameter then
commonFunctions:printError(" SDL re-sends fake parameters to HMI in BasicCommunication.OnFileRemoved")
return false
else
return true
end
end)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
end
--End test case CommonRequestCheck.7.1
--Begin test case CommonRequestCheck.7.2
--Description: Check request with parameters of other request
--Requirement id in JAMA/or Jira ID: APPLINK-4518
--Verification criteria: SDL ignores parameters of other request
--Precondition: PutFile
putfile(self, "test.png", "GRAPHIC_PNG")
function Test:DeleteFile_ParametersOfOtherRequest_SUCCESS()
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = "test.png",
ttsChunks = {
TTSChunk =
{
text ="SpeakFirst",
type ="TEXT",
},
TTSChunk =
{
text ="SpeakSecond",
type ="TEXT",
}
}
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved",
{
fileName = strAppFolder .. "test.png",
fileType = "GRAPHIC_PNG",
appID = self.applications[config.application1.registerAppInterfaceParams.appName]
})
:ValidIf(function(_,data)
if data.params.ttsChunks then
commonFunctions:printError(" SDL re-sends parameters of other request to HMI in BasicCommunication.OnFileRemoved")
return false
else
return true
end
end)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
end
--End test case CommonRequestCheck.7.2
--End test case PositiveRequestCheck.7
--Begin test case CommonRequestCheck.8.
--Description: Check request is sent with invalid JSON structure
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-715
--Verification criteria: The request with wrong JSON syntax is sent, the response comes with INVALID_DATA result code.
--Precondition: PutFile
putfile(self, "test.png", "GRAPHIC_PNG")
-- missing ':' after syncFileName
--payload = '{"syncFileName":"test.png"}'
local payload = '{"syncFileName" "test.png"}'
commonTestCases:VerifyInvalidJsonRequest(33, payload)
--End test case CommonRequestCheck.8
--Begin test case CommonRequestCheck.9
--Description: check request correlation Id is duplicated
--Requirement id in JAMA/or Jira ID:
--Verification criteria: SDL responses SUCCESS
--Precondition: PutFile
putfile(self, "test1.png", "GRAPHIC_PNG")
putfile(self, "test2.png", "GRAPHIC_PNG")
function Test:DeleteFile_Duplicated_CorrelationID_SUCCESS()
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = "test1.png"
})
local msg =
{
serviceType = 7,
frameInfo = 0,
rpcType = 0,
rpcFunctionId = 33, --DeleteFileID
rpcCorrelationId = cid,
payload = '{"syncFileName":"test2.png"}'
}
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved",
{
fileName = strAppFolder .. "test1.png",
fileType = "GRAPHIC_PNG",
appID = self.applications[config.application1.registerAppInterfaceParams.appName]
},
{
fileName = strAppFolder .. "test2.png",
fileType = "GRAPHIC_PNG",
appID = self.applications[config.application1.registerAppInterfaceParams.appName]
}
)
:Times(2)
:Do(function(exp,data)
if exp.occurences == 1 then
self.mobileSession:Send(msg)
end
end)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS"})
:Times(2)
end
--End test case CommonRequestCheck.9
-----------------------------------------------------------------------------------------
--End test suit PositiveRequestCheck
---------------------------------------------------------------------------------------------
----------------------------------------II TEST BLOCK----------------------------------------
----------------------------------------Positive cases---------------------------------------
---------------------------------------------------------------------------------------------
--=================================================================================--
--------------------------------Positive request check-------------------------------
--=================================================================================--
--check of each request parameter value in bound and boundary conditions
--Write NewTestBlock to ATF log
function Test:NewTestBlock()
commonFunctions:printError("****************************** II TEST BLOCK: Positive request check ******************************")
end
--Begin test suit PositiveRequestCheck
--Description: check of each request parameter value in bound and boundary conditions
--Begin test case PositiveRequestCheck.1
--Description: Check request with syncFileName parameter value in bound and boundary conditions
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150
--Verification criteria: DeleteFile response is SUCCESS
arrFileType = {"GRAPHIC_BMP", "GRAPHIC_JPEG", "GRAPHIC_PNG", "AUDIO_WAVE", "AUDIO_MP3", "AUDIO_AAC", "BINARY", "JSON"}
arrPersistentFile = {false, true}
arrSystemFile = {false}
arrFileName = {
{fileName = "a", reportName = "min_length_a"},
{fileName = "test", reportName = "middle_length_test"},
{fileName = str255Chars, reportName = "max_length_255_characters"}
}
for j = 1, #arrFileName do
for n = 1, #arrFileType do
for m = 1, #arrPersistentFile do
for i = 1, #arrSystemFile do
-- Precondition
Test["ListFiles"] = function(self)
--mobile side: sending ListFiles request
local cid = self.mobileSession:SendRPC("ListFiles", {} )
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid,
{
success = true,
resultCode = "SUCCESS"
}
)
:Do(function(_,data)
--Store spaceAvailable value
iSpaceAvailable_BeforePutFile = data.payload.spaceAvailable
--commonFunctions:printError("ListFiles: spaceAvailable: " .. data.payload.spaceAvailable)
end)
end
--Precondition: PutFile
putfile(self, arrFileName[j], arrFileType[n], arrPersistentFile[m], arrSystemFile[i])
strTestCaseName = "DeleteFile_" .. tostring(arrFileName[j].reportName) .. "_FileType_" .. tostring(arrFileType[n]) .. "_PersistentFile_" .. tostring(arrPersistentFile[m]) .. "_SystemFile_" .. tostring(arrSystemFile[i])
TC_DeleteFile_Check_spaceAvailable_SUCCESS(self, strTestCaseName, arrFileName[j].fileName, arrFileType[n])
end
end
end
end
--End test suit PositiveRequestCheck.1
--End test suit PositiveRequestCheck
--=================================================================================--
--------------------------------Positive response check------------------------------
--=================================================================================--
--------Checks-----------
-- parameters with values in boundary conditions
--Write NewTestBlock to ATF log
function Test:NewTestBlock()
commonFunctions:printError("****************************** II TEST BLOCK: Positive response check ******************************")
commonFunctions:printError("There is no response from HMI for this request. => Skipped this part.")
os.execute("sleep "..tonumber(5))
end
--Begin test suit PositiveResponseCheck
--Description: Check positive responses
--There is response from HMI => Ignore this check.
--End test suit PositiveResponseCheck
----------------------------------------------------------------------------------------------
----------------------------------------III TEST BLOCK----------------------------------------
----------------------------------------Negative cases----------------------------------------
----------------------------------------------------------------------------------------------
--=================================================================================--
---------------------------------Negative request check------------------------------
--=================================================================================--
--------Checks-----------
-- outbound values
-- invalid values(empty, missing, nonexistent, duplicate, invalid characters)
-- parameters with wrong type
-- invalid json
--Write NewTestBlock to ATF log
function Test:NewTestBlock()
commonFunctions:printError("****************************** III TEST BLOCK: Negative request check ******************************")
end
--Begin test suit NegativeRequestCheck
--Description: check of each request parameter value out of bound, missing, with wrong type, empty, duplicate etc.
--Begin test case NegativeRequestCheck.1
--Description: check of syncFileName parameter value out bound
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150 -> SDLAQ-CRS-715
--Verification criteria: SDL returns INVALID_DATA
--Begin test case NegativeRequestCheck.1.1
--Description: check of syncFileName parameter value out lower bound
function Test:DeleteFile_empty_outLowerBound_INVALID_DATA()
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = ""
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} )
:Timeout(iTimeout)
:Times(0)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil})
end
--End test case NegativeRequestCheck.1.1
--Begin test case NegativeRequestCheck.1.2
--Description: check of syncFileName parameter value out upper bound (256 characters)
function Test:DeleteFile_outUpperBound_OfPutFileName_256_INVALID_DATA()
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = str255Chars .. "x"
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} )
:Timeout(iTimeout)
:Times(0)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil})
end
--End test case NegativeRequestCheck.1.2
--Begin test case NegativeRequestCheck.1.3
--Description: check of syncFileName parameter value out upper bound (501 characters)
function Test:DeleteFile_outUpperBound_501_INVALID_DATA()
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = str255Chars .. str255Chars .. "x"
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} )
:Timeout(iTimeout)
:Times(0)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil})
end
--End test case NegativeRequestCheck.1.3
--End test case NegativeRequestCheck.1
--Begin test case NegativeRequestCheck.2
--Description: check of syncFileName parameter is invalid values(empty, missing, nonexistent, duplicate, invalid characters)
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150 -> SDLAQ-CRS-715
--Verification criteria: SDL returns INVALID_DATA
--Begin test case NegativeRequestCheck.2.1
--Description: check of syncFileName parameter is invalid values(empty)
--It is covered in out lower bound case
--End test case NegativeRequestCheck.2.1
--Begin test case NegativeRequestCheck.2.2
--Description: check of syncFileName parameter is invalid values(missing)
--It is covered by DeleteFile_missing_mandatory_parameters_syncFileName_INVALID_DATA
--End test case NegativeRequestCheck.2.2
--Begin test case NegativeRequestCheck.2.3
--Description: check of syncFileName parameter is invalid values(nonexistent)
Test["DeleteFile_syncFileName_nonexistentValue_INVALID_DATA"] = function(self)
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = "nonexistentValue"
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {})
:Timeout(iTimeout)
:Times(0)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil})
:Timeout(iTimeout)
end
--End test case NegativeRequestCheck.2.3
--Begin test case NegativeRequestCheck.2.4
--Description: check of syncFileName parameter is invalid values(duplicate)
--It is not applicable
--End test case NegativeRequestCheck.2.4
--Begin test case NegativeRequestCheck.2.5
--Description: check of syncFileName parameter is invalid values(invalid characters)
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-715, APPLINK-8083
--Verification criteria: SDL returns INVALID_DATA
--Begin test case NegativeRequestCheck.2.5.1
--Description: newline character
--Precondition
putfile(self, "test1.png", "GRAPHIC_PNG")
Test["DeleteFile_syncFileName_invalid_characters_newline_INVALID_DATA"] = function(self)
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = "te\nst1.png"
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} )
:Timeout(iTimeout)
:Times(0)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil})
:Timeout(12000)
end
--End test case NegativeRequestCheck.2.5.1
--Begin test case NegativeRequestCheck.2.5.2
--Description: newline character
Test["DeleteFile_syncFileName_invalid_characters_tab_INVALID_DATA"] = function(self)
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = "te\tst1.png"
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} )
:Timeout(iTimeout)
:Times(0)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil})
:Timeout(12000)
end
--End test case NegativeRequestCheck.2.5.2
--End test case NegativeRequestCheck.2.5
--End test case NegativeRequestCheck.2
--Begin test case NegativeRequestCheck.3
--Description: check of syncFileName parameter is wrong type
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150 -> SDLAQ-CRS-715
--Verification criteria: SDL returns INVALID_DATA
Test["DeleteFile_syncFileName_wrongType_INVALID_DATA"] = function(self)
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = 123
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved",
{
syncFileName = "ON\nSCREEN_PRESETS"
})
:Timeout(iTimeout)
:Times(0)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, {success = false, resultCode = "INVALID_DATA", info = nil})
:Timeout(iTimeout)
end
--End test case NegativeRequestCheck.3
--Begin test case NegativeRequestCheck.4
--Description: request is invalid json
--payload = '{"syncFileName":"test.png"}'
local Payload = '{"syncFileName", "test.png"}'
commonTestCases:VerifyInvalidJsonRequest(33, Payload)
--End test case NegativeRequestCheck.4
--Begin test case NegativeRequestCheck.5
--Description: Delete system file.
--Requirement id in JAMA/or Jira ID: APPLINK-14119
--Verification criteria: SDL returns INVALID_DATA
arrFileType = {"GRAPHIC_BMP", "GRAPHIC_JPEG", "GRAPHIC_PNG", "AUDIO_WAVE", "AUDIO_MP3", "AUDIO_AAC", "BINARY", "JSON"}
arrPersistentFile = {false, true}
--Defect: APPLINK-14212: DeleteFile response: spaceAvailable parameter is wrong value
arrSystemFile = {true}
arrFileName = {
{fileName = "a", reportName = "min_length_a"},
{fileName = "test", reportName = "middle_length_test"},
{fileName = str255Chars, reportName = "max_length_255_characters"}
}
for j = 1, #arrFileName do
for n = 1, #arrFileType do
for m = 1, #arrPersistentFile do
for i = 1, #arrSystemFile do
--Precondition: PutFile
putfile(self, arrFileName[j], arrFileType[n], arrPersistentFile[m], arrSystemFile[i])
strTestCaseName = "DeleteFile_" .. tostring(arrFileName[j].reportName) .. "_FileType_" .. tostring(arrFileType[n]) .. "_PersistentFile_" .. tostring(arrPersistentFile[m]) .. "_SystemFile_" .. tostring(arrSystemFile[i])
Test[strTestCaseName] = function(self)
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = arrFileName[j].fileName
})
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, { success = false, resultCode = "INVALID_DATA"})
end
end
end
end
end
--End test case NegativeRequestCheck.5
--End test suit NegativeRequestCheck
--=================================================================================--
---------------------------------Negative response check------------------------------
--=================================================================================--
--------Checks-----------
-- outbound values
-- invalid values(empty, missing, nonexistent, invalid characters)
-- parameters with wrong type
-- invalid json
--Write NewTestBlock to ATF log
function Test:NewTestBlock()
commonFunctions:printError("****************************** III TEST BLOCK: Negative response check ******************************")
commonFunctions:printError("There is no response from HMI for this request. => Skipped this part.")
end
--Begin test suit NegativeResponseCheck
--Description: check of each request parameter value out of bound, missing, with wrong type, empty, duplicate etc.
--There is no response from HMI for this request. => Skipped this part.
--End test suit NegativeResponseCheck
----------------------------------------------------------------------------------------------
----------------------------------------IV TEST BLOCK-----------------------------------------
---------------------------------------Result code check--------------------------------------
----------------------------------------------------------------------------------------------
--Check all uncovered pairs resultCodes+success
--Write NewTestBlock to ATF log
function Test:NewTestBlock()
commonFunctions:printError("****************************** IV TEST BLOCK: Result code check ******************************")
end
--Begin test suit ResultCodeCheck
--Description: check result code of response to Mobile (SDLAQ-CRS-713)
--Begin test case ResultCodeCheck.1
--Description: Check resultCode: SUCCESS
--It is covered by test case CommonRequestCheck.1
--End test case resultCodeCheck.1
--Begin test case resultCodeCheck.2
--Description: Check resultCode: INVALID_DATA
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-715
--Verification criteria: SDL response INVALID_DATA resultCode to Mobile
-- It is covered by DeleteFile_empty_outLowerBound_INVALID_DATA
--End test case resultCodeCheck.2
--Begin test case resultCodeCheck.3
--Description: Check resultCode: OUT_OF_MEMORY
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-716
--Verification criteria: SDL returns OUT_OF_MEMORY result code for DeleteFile request IN CASE SDL lacks memory RAM for executing it.
--ToDo: Can not check this case.
--End test case resultCodeCheck.3
--Begin test case resultCodeCheck.4
--Description: Check resultCode: TOO_MANY_PENDING_REQUESTS
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-717
--Verification criteria: The system has more than 1000 requests at a time that haven't been responded yet.The system sends the responses with TOO_MANY_PENDING_REQUESTS error code for all further requests, until there are less than 1000 requests at a time that have not been responded by the system yet.
--Move to another script: ATF_DeleteFile_TOO_MANY_PENDING_REQUESTS.lua
--End test case resultCodeCheck.4
--Begin test case resultCodeCheck.5
--Description: Check resultCode: APPLICATION_NOT_REGISTERED
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-718
--Verification criteria: SDL sends APPLICATION_NOT_REGISTERED result code when the app sends a request within the same connection before RegisterAppInterface has been performed yet.
-- Unregister application
commonSteps:UnregisterApplication()
--Send DeleteFile when application not registered yet.
function Test:DeleteFile_resultCode_APPLICATION_NOT_REGISTERED()
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = "test.png"
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} )
:Timeout(iTimeout)
:Times(0)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, {success = false, resultCode = "APPLICATION_NOT_REGISTERED", info = nil})
:Timeout(iTimeout)
end
-- Register application again
commonSteps:RegisterAppInterface()
--ToDo: Work around to help script continnue running due to error with UnregisterApplication and RegisterAppInterface again. Remove it when it is not necessary.
commonSteps:RegisterAppInterface()
-- Activate app again
commonSteps:ActivationApp()
--End test case resultCodeCheck.5
--Begin test case resultCodeCheck.6
--Description: Check resultCode: REJECTED
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-719, SDLAQ-CRS-2281
--Verification criteria:
--1. In case app in HMI level of NONE sends DeleteFile_request AND the number of requests more than value of 'DeleteFileRequest' param defined in .ini file SDL must respond REJECTED result code to this mobile app
-- Precondition 1: Put 6 files
putfile(self, "test1.png", "GRAPHIC_PNG")
putfile(self, "test2.png", "GRAPHIC_PNG")
putfile(self, "test3.png", "GRAPHIC_PNG")
putfile(self, "test4.png", "GRAPHIC_PNG")
putfile(self, "test5.png", "GRAPHIC_PNG")
putfile(self, "test6.png", "GRAPHIC_PNG")
-- Precondition 2: Change app to NONE HMI level
commonSteps:DeactivateAppToNoneHmiLevel()
-- Precondition 3: Send DeleteFile 5 times
TC_DeleteFile_SUCCESS(self, "DeleteFile_NONE_HMI_LEVEL_test1_png_SUCCESS", "test1.png", "GRAPHIC_PNG")
TC_DeleteFile_SUCCESS(self, "DeleteFile_NONE_HMI_LEVEL_test2_png_SUCCESS", "test2.png", "GRAPHIC_PNG")
TC_DeleteFile_SUCCESS(self, "DeleteFile_NONE_HMI_LEVEL_test3_png_SUCCESS", "test3.png", "GRAPHIC_PNG")
TC_DeleteFile_SUCCESS(self, "DeleteFile_NONE_HMI_LEVEL_test4_png_SUCCESS", "test4.png", "GRAPHIC_PNG")
TC_DeleteFile_SUCCESS(self, "DeleteFile_NONE_HMI_LEVEL_test5_png_SUCCESS", "test5.png", "GRAPHIC_PNG")
Test["DeleteFile_NONE_HMI_LEVEL_test6_png_REJECTED"] = function(self)
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = "test6.png"
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved", {} )
:Times(0)
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, { success = false, resultCode = "REJECTED" })
end
-- Activate app again
commonSteps:ActivationApp()
TC_DeleteFile_SUCCESS(self, "DeleteFile_FULL_HMI_LEVEL_test6_png_SUCCESS", "test6.png", "GRAPHIC_PNG")
--End test case resultCodeCheck.6
--Begin test case resultCodeCheck.7
--Description: Check resultCode: GENERIC_ERROR
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-720
--Verification criteria: GENERIC_ERROR comes as a result code in response when all other codes aren't applicable or the unknown issue occurred.
--ToDo: Don't know how to produce this case.
--End test case resultCodeCheck.7
--Begin test case resultCodeCheck.8
--Description: Check resultCode: UNSUPPORTED_REQUEST
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-1041 (APPLINK-9867 question)
--Verification criteria: The platform doesn't support file operations, the UNSUPPORTED_REQUEST responseCode is obtained. General request result is success=false.
--ToDo: This requirement is not applicable because current SDL supports DeleteFile API
--End test case resultCodeCheck.8
--End test suit resultCodeCheck
----------------------------------------------------------------------------------------------
-----------------------------------------V TEST BLOCK-----------------------------------------
---------------------------------------HMI negative cases-------------------------------------
----------------------------------------------------------------------------------------------
--------Checks-----------
-- requests without responses from HMI
-- invalid structure of response
-- several responses from HMI to one request
-- fake parameters
-- HMI correlation id check
-- wrong response with correct HMI id
--Write NewTestBlock to ATF log
function Test:NewTestBlock()
commonFunctions:printError("****************************** V TEST BLOCK: HMI negative cases ******************************")
commonFunctions:printError("There is no response from HMI for this request. => Skipped this part.")
end
--Begin test suit HMINegativeCheck
--Description: Check negative response from HMI
--There is no response from HMI for this request. => Skipped this part.
--End test suit HMINegativeCheck
----------------------------------------------------------------------------------------------
-----------------------------------------VI TEST BLOCK----------------------------------------
-------------------------Sequence with emulating of user's action(s)--------------------------
----------------------------------------------------------------------------------------------
-- Check different request sequence with timeout, emulating of user's actions
--Write NewTestBlock to ATF log
function Test:NewTestBlock()
commonFunctions:printError("****************************** VI TEST BLOCK: Sequence with emulating of user's action(s) ******************************")
end
--Begin test suit SequenceCheck
--Description: TC's checks SDL behavior by processing
-- different request sequence with timeout
-- with emulating of user's actions
--Begin test case SequenceCheck.1
--Description: Check scenario in test case TC_DeleteFile_01: Delete files from SDL Core with next file types:
-- GRAPHIC_BMP
-- GRAPHIC_JPEG
-- GRAPHIC_PNG
-- AUDIO_WAVE
-- AUDIO_MP3
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-150
--Verification criteria: DeleteFile request is sent for a file already stored in the app's local cache on SDL (app's folder on SDL) and not marked as persistent file on SDL during current ignition/session cycle, the result of the request is deleting the corresponding file from the app's folder on SDL.
-- Precondition: PutFile icon_bmp.bmp, icon_jpg.jpeg, icon_png.png, tone_wave.wav, tone_mp3.mp3
putfile(self, "icon_bmp.bmp", "GRAPHIC_BMP", false, false, "icon_bmp.bmp")
putfile(self, "icon_jpg.jpeg", "GRAPHIC_JPEG", false, false, "icon_jpg.jpeg")
putfile(self, "icon_png.png", "GRAPHIC_PNG", false, false, "icon_png.png")
putfile(self, "tone_wave.wav", "AUDIO_WAVE", false, false, "tone_wave.wav")
putfile(self, "tone_mp3.mp3", "AUDIO_MP3", false, false, "tone_mp3.mp3")
Test["ListFile_ContainsPutFiles"] = function(self)
--mobile side: sending ListFiles request
local cid = self.mobileSession:SendRPC("ListFiles", {} )
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid,
{
success = true,
resultCode = "SUCCESS",
filenames =
{
"icon_bmp.bmp",
"icon_jpg.jpeg",
"icon_png.png",
"tone_mp3.mp3",
"tone_wave.wav"
}
}
)
end
TC_DeleteFile_SUCCESS(self, "TC_DeleteFile_01_icon_bmp.bmp", "icon_bmp.bmp", "GRAPHIC_BMP")
TC_DeleteFile_SUCCESS(self, "TC_DeleteFile_01_icon_jpg.jpeg", "icon_jpg.jpeg", "GRAPHIC_JPEG")
TC_DeleteFile_SUCCESS(self, "TC_DeleteFile_01_icon_png.png", "icon_png.png", "GRAPHIC_PNG")
TC_DeleteFile_SUCCESS(self, "TC_DeleteFile_01_tone_wave.wav", "tone_wave.wav", "AUDIO_WAVE")
TC_DeleteFile_SUCCESS(self, "TC_DeleteFile_01_tone_mp3.mp3", "tone_mp3.mp3", "AUDIO_MP3")
Test["ListFile_WihtoutDeletedFiles"] = function(self)
--mobile side: sending ListFiles request
local cid = self.mobileSession:SendRPC("ListFiles", {} )
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid,
{
success = true,
resultCode = "SUCCESS"
}
)
:ValidIf(function(_,data)
local removedFileNames =
{
"icon_bmp.bmp",
"icon_jpg.jpeg",
"icon_png.png",
"tone_mp3.mp3",
"tone_wave.wav"
}
local blnResult = true
if data.payload.filenames ~= nil then
for i = 1, #removedFileNames do
for j =1, #data.payload.filenames do
if removedFileNames[i] == data.payload.filenames[j] then
commonFunctions:printError("Failed: " .. removedFileNames[i] .. " is still in result of ListFiles request")
blnResult = false
break
end
end
end
else
print( " \27[32m ListFiles response came without filenames \27[0m " )
return true
end
return blnResult
end)
end
--End test case SequenceCheck.1
----------------------------------------------------------------------------------------------
--Print new line to separate new test cases
commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_01")
--Begin test case SequenceCheck.2
--Description: Cover TC_OnFileRemoved_01
--Requirement id in JAMA/or Jira ID: SDLAQ-TC-329
--Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing app icon to default after deleting file which was set for app icon. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types).
local function TC_OnFileRemoved_01(imageFile, imageTypeValue)
putfile(self, imageFile, imageTypeValue,_,_,imageFile)
function Test:SetAppIcon()
--mobile side: sending SetAppIcon request
local cid = self.mobileSession:SendRPC("SetAppIcon",{ syncFileName = imageFile })
--hmi side: expect UI.SetAppIcon request
EXPECT_HMICALL("UI.SetAppIcon",
{
appID = self.applications[config.application1.registerAppInterfaceParams.appName],
syncFileName =
{
imageType = "DYNAMIC",
value = strAppFolder .. imageFile
}
})
:Do(function(_,data)
--hmi side: sending UI.SetAppIcon response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect SetAppIcon response
EXPECT_RESPONSE(cid, { resultCode = "SUCCESS", success = true })
end
TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue)
end
local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"},
{fileName = "action.bmp", fileType ="GRAPHIC_BMP"},
{fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}}
for i=1,#imageFile do
TC_OnFileRemoved_01(imageFile[i].fileName, imageFile[i].fileType)
end
--End test case SequenceCheck.2
----------------------------------------------------------------------------------------------
--Print new line to separate new test cases
commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_02")
--Begin test case SequenceCheck.3
--Description: Cover TC_OnFileRemoved_02
--Requirement id in JAMA/or Jira ID: SDLAQ-TC-330
--Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing Show image to default after deleting file which was set for Show image. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types).
local function TC_OnFileRemoved_02(imageFile, imageTypeValue)
putfile(self, imageFile, imageTypeValue,_,_,imageFile)
function Test:Show()
--mobile side: sending Show request
local cidShow = self.mobileSession:SendRPC("Show", {
mediaClock = "12:34",
mainField1 = "Show Line 1",
mainField2 = "Show Line 2",
mainField3 = "Show Line 3",
mainField4 = "Show Line 4",
graphic =
{
value = imageFile,
imageType = "DYNAMIC"
},
secondaryGraphic =
{
value = imageFile,
imageType = "DYNAMIC"
},
statusBar = "new status bar",
mediaTrack = "Media Track"
})
--hmi side: expect UI.Show request
EXPECT_HMICALL("UI.Show", {
graphic =
{
imageType = "DYNAMIC",
value = strAppFolder..imageFile
},
secondaryGraphic =
{
imageType = "DYNAMIC",
value = strAppFolder..imageFile
},
showStrings =
{
{
fieldName = "mainField1",
fieldText = "Show Line 1"
},
{
fieldName = "mainField2",
fieldText = "Show Line 2"
},
{
fieldName = "mainField3",
fieldText = "Show Line 3"
},
{
fieldName = "mainField4",
fieldText = "Show Line 4"
},
{
fieldName = "mediaClock",
fieldText = "12:34"
},
{
fieldName = "mediaTrack",
fieldText = "Media Track"
},
{
fieldName = "statusBar",
fieldText = "new status bar"
}
}
})
:Do(function(_,data)
--hmi side: sending UI.Show response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect Show response
EXPECT_RESPONSE(cidShow, { success = true, resultCode = "SUCCESS" })
end
TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue)
end
local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"},
{fileName = "action.bmp", fileType ="GRAPHIC_BMP"},
{fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}}
for i=1,#imageFile do
TC_OnFileRemoved_02(imageFile[i].fileName, imageFile[i].fileType)
end
--End test case SequenceCheck.3
-----------------------------------------------------------------------------------------
--Print new line to separate new test cases
commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_03")
--Begin test case SequenceCheck.4
--Description: Cover TC_OnFileRemoved_03
--Requirement id in JAMA/or Jira ID: SDLAQ-TC-331
--Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the Command icon to default after deleting file which was set for the icon of this Command. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types).
function Test:AddSubMenu()
--mobile side: sending AddSubMenu request
local cid = self.mobileSession:SendRPC("AddSubMenu",
{
menuID = 10,
position = 500,
menuName ="TestMenu"
})
--hmi side: expect UI.AddSubMenu request
EXPECT_HMICALL("UI.AddSubMenu",
{
menuID = 10,
menuParams = {
position = 500,
menuName ="TestMenu"
}
})
:Do(function(_,data)
--hmi side: sending UI.AddSubMenu response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect AddSubMenu response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
--mobile side: expect OnHashChange notification
EXPECT_NOTIFICATION("OnHashChange")
end
local function TC_OnFileRemoved_03(imageFile, imageTypeValue, commandID)
putfile(self, imageFile, imageTypeValue,_,_,imageFile)
function Test:AddCommand()
--mobile side: sending AddCommand request
local cid = self.mobileSession:SendRPC("AddCommand",
{
cmdID = commandID,
menuParams =
{
parentID = 10,
position = 0,
menuName ="TestCommand"..commandID
},
cmdIcon =
{
value = imageFile,
imageType ="DYNAMIC"
}
})
--hmi side: expect UI.AddCommand request
EXPECT_HMICALL("UI.AddCommand",
{
cmdID = commandID,
cmdIcon =
{
value = strAppFolder..imageFile,
imageType = "DYNAMIC"
},
menuParams =
{
parentID = 10,
position = 0,
menuName ="TestCommand"..commandID
}
})
:Do(function(_,data)
--hmi side: sending UI.AddCommand response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect AddCommand response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
--mobile side: expect OnHashChange notification
EXPECT_NOTIFICATION("OnHashChange")
end
function Test:OpenOptionsMenu()
SendOnSystemContext(self,"MENU")
EXPECT_NOTIFICATION("OnHMIStatus",{ hmiLevel = "FULL", audioStreamingState = audibleState, systemContext = "MENU"})
end
TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue)
function Test:BackToMain()
SendOnSystemContext(self,"MAIN")
EXPECT_NOTIFICATION("OnHMIStatus",{ hmiLevel = "FULL", audioStreamingState = audibleState, systemContext = "MAIN"})
end
end
local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"},
{fileName = "action.bmp", fileType ="GRAPHIC_BMP"},
{fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}}
for i=1,#imageFile do
TC_OnFileRemoved_03(imageFile[i].fileName, imageFile[i].fileType, i+10)
end
--End test case SequenceCheck.4
-----------------------------------------------------------------------------------------
--Print new line to separate new test cases
commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_04")
--Begin test case SequenceCheck.5
--Description: Cover TC_OnFileRemoved_04
--Requirement id in JAMA/or Jira ID: SDLAQ-TC-332
--Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the SoftButton icon to default after deleting file which was set for the icon of this SoftButton. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types).
local function TC_OnFileRemoved_04(imageFile, imageTypeValue)
putfile(self, imageFile, imageTypeValue,_,_,imageFile)
function Test:ShowWithSoftButton()
--mobile side: sending Show request
local cidShow = self.mobileSession:SendRPC("Show", {
mediaClock = "12:34",
mainField1 = "Show Line 1",
mainField2 = "Show Line 2",
mainField3 = "Show Line 3",
mainField4 = "Show Line 4",
graphic =
{
value = imageFile,
imageType = "DYNAMIC"
},
secondaryGraphic =
{
value = imageFile,
imageType = "DYNAMIC"
},
statusBar = "new status bar",
mediaTrack = "Media Track",
softButtons =
{
{
text = "",
systemAction = "DEFAULT_ACTION",
type = "IMAGE",
isHighlighted = true,
image =
{
imageType = "DYNAMIC",
value = imageFile
},
softButtonID = 1
}
}
})
--hmi side: expect UI.Show request
EXPECT_HMICALL("UI.Show", {
graphic =
{
imageType = "DYNAMIC",
value = strAppFolder..imageFile
},
secondaryGraphic =
{
imageType = "DYNAMIC",
value = strAppFolder..imageFile
},
showStrings =
{
{
fieldName = "mainField1",
fieldText = "Show Line 1"
},
{
fieldName = "mainField2",
fieldText = "Show Line 2"
},
{
fieldName = "mainField3",
fieldText = "Show Line 3"
},
{
fieldName = "mainField4",
fieldText = "Show Line 4"
},
{
fieldName = "mediaClock",
fieldText = "12:34"
},
{
fieldName = "mediaTrack",
fieldText = "Media Track"
},
{
fieldName = "statusBar",
fieldText = "new status bar"
}
},
softButtons =
{
{
systemAction = "DEFAULT_ACTION",
type = "IMAGE",
isHighlighted = true,
--[[ TODO: update after resolving APPLINK-16052
image =
{
imageType = "DYNAMIC",
value = strAppFolder..imageFile
},]]
softButtonID = 1
}
}
})
:Do(function(_,data)
--hmi side: sending UI.Show response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect Show response
EXPECT_RESPONSE(cidShow, { success = true, resultCode = "SUCCESS" })
end
TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue)
end
local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"},
{fileName = "action.bmp", fileType ="GRAPHIC_BMP"},
{fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}}
for i=1,#imageFile do
TC_OnFileRemoved_04(imageFile[i].fileName, imageFile[i].fileType)
end
--End test case SequenceCheck.5
-----------------------------------------------------------------------------------------
--Print new line to separate new test cases
commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_05")
--Begin test case SequenceCheck.6
--Description: Cover TC_OnFileRemoved_05
--Requirement id in JAMA/or Jira ID: SDLAQ-TC-333
--Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the Turn icon of TurnList to default after deleting file which was set for the icon of this Turn. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types).
local function TC_OnFileRemoved_05(imageFile, imageTypeValue)
putfile(self, imageFile, imageTypeValue,_,_,imageFile)
function Test:UpdateTurnList()
--mobile side: send UpdateTurnList request
local CorIdUpdateTurnList = self.mobileSession:SendRPC("UpdateTurnList", {
turnList =
{
{
navigationText ="Text",
turnIcon =
{
value = imageFile,
imageType ="DYNAMIC",
}
}
}
})
--hmi side: expect Navigation.UpdateTurnList request
EXPECT_HMICALL("Navigation.UpdateTurnList"--[[ TODO: update after resolving APPLINK-16052,
{
turnList =
{
{
navigationText =
{
fieldText = "Text",
fieldName = "turnText"
},
turnIcon =
{
value =strAppFolder..imageFile,
imageType ="DYNAMIC",
}
}
}
}]])
:Do(function(_,data)
--hmi side: send Navigation.UpdateTurnList response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS",{})
end)
--mobile side: expect UpdateTurnList response
EXPECT_RESPONSE(CorIdUpdateTurnList, { success = true, resultCode = "SUCCESS" })
end
TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue)
end
local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"},
{fileName = "action.bmp", fileType ="GRAPHIC_BMP"},
{fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}}
for i=1,#imageFile do
TC_OnFileRemoved_05(imageFile[i].fileName, imageFile[i].fileType)
end
--End test case SequenceCheck.6
-----------------------------------------------------------------------------------------
--Print new line to separate new test cases
commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_06")
--Begin test case SequenceCheck.7
--Description: Cover TC_OnFileRemoved_06
--Requirement id in JAMA/or Jira ID: SDLAQ-TC-334
--Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the Turn icon, Next Turn icon to default after deleting file which was set for the Turn icon and Next Turn icon. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types).
local function TC_OnFileRemoved_06(imageFile, imageTypeValue)
putfile(self, imageFile, imageTypeValue,_,_,imageFile)
function Test:ShowConstantTBT()
--mobile side: sending ShowConstantTBT request
cid = self.mobileSession:SendRPC("ShowConstantTBT", {
navigationText1 ="navigationText1",
navigationText2 ="navigationText2",
eta ="12:34",
totalDistance ="100miles",
turnIcon =
{
value =imageFile,
imageType ="DYNAMIC",
},
nextTurnIcon =
{
value =imageFile,
imageType ="DYNAMIC",
},
distanceToManeuver = 50.5,
distanceToManeuverScale = 100.5,
maneuverComplete = false,
softButtons =
{
{
type ="BOTH",
text ="Close",
image =
{
value =imageFile,
imageType ="DYNAMIC",
},
isHighlighted = true,
softButtonID = 44,
systemAction ="DEFAULT_ACTION",
},
},
})
--hmi side: expect Navigation.ShowConstantTBT request
EXPECT_HMICALL("Navigation.ShowConstantTBT", {
navigationTexts = {
{
fieldName = "navigationText1",
fieldText = "navigationText1"
},
{
fieldName = "navigationText2",
fieldText = "navigationText2"
},
{
fieldName = "ETA",
fieldText = "12:34"
},
{
fieldName = "totalDistance",
fieldText = "100miles"
}
},
turnIcon =
{
value =strAppFolder..imageFile,
imageType ="DYNAMIC",
},
nextTurnIcon =
{
value =strAppFolder..imageFile,
imageType ="DYNAMIC",
},
distanceToManeuver = 50.5,
distanceToManeuverScale = 100.5,
maneuverComplete = false,
softButtons =
{
{
type ="BOTH",
text ="Close",
--[[ TODO: update after resolving APPLINK-16052
image =
{
value =strAppFolder..imageFile,
imageType ="DYNAMIC",
}, ]]
isHighlighted = true,
softButtonID = 44,
systemAction ="DEFAULT_ACTION",
},
},
})
:Do(function(_,data)
--hmi side: sending Navigation.ShowConstantTBT response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect SetGlobalProperties response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
end
TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue)
end
local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"},
{fileName = "action.bmp", fileType ="GRAPHIC_BMP"},
{fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}}
for i=1,#imageFile do
TC_OnFileRemoved_06(imageFile[i].fileName, imageFile[i].fileType)
end
--End test case SequenceCheck.7
-----------------------------------------------------------------------------------------
--Print new line to separate new test cases
commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_07")
--Begin test case SequenceCheck.8
--Description: Cover TC_OnFileRemoved_07
--Requirement id in JAMA/or Jira ID: SDLAQ-TC-335
--Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the VRHelp Item icon to default after deleting file which was set for the VRHelp Item icon. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types).
local function TC_OnFileRemoved_07(imageFile, imageTypeValue)
putfile(self, imageFile, imageTypeValue,_,_,imageFile)
function Test:SetGlobalProperties()
--mobile side: sending SetGlobalProperties request
cid = self.mobileSession:SendRPC("SetGlobalProperties", {
menuTitle = "Menu Title",
timeoutPrompt =
{
{
text = "Timeout prompt",
type = "TEXT"
}
},
vrHelp =
{
{
position = 1,
image =
{
value = imageFile,
imageType = "DYNAMIC"
},
text = "Help me!"
}
},
menuIcon =
{
value = imageFile,
imageType = "DYNAMIC"
},
helpPrompt =
{
{
text = "Help prompt",
type = "TEXT"
}
},
vrHelpTitle = "New VR help title",
keyboardProperties =
{
keyboardLayout = "QWERTY",
keypressMode = "SINGLE_KEYPRESS",
limitedCharacterList =
{
"a"
},
language = "EN-US",
autoCompleteText = "Daemon, Freedom"
}
})
--hmi side: expect TTS.SetGlobalProperties request
EXPECT_HMICALL("TTS.SetGlobalProperties",
{
timeoutPrompt =
{
{
text = "Timeout prompt",
type = "TEXT"
}
},
helpPrompt =
{
{
text = "Help prompt",
type = "TEXT"
}
}
})
:Do(function(_,data)
--hmi side: sending TTS.SetGlobalProperties response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
:Timeout(iTimeout)
--hmi side: expect UI.SetGlobalProperties request
EXPECT_HMICALL("UI.SetGlobalProperties",
{
menuTitle = "Menu Title",
vrHelp =
{
{
position = 1,
--[[ TODO: update after resolving APPLINK-16052
image =
{
imageType = "DYNAMIC",
value = strAppFolder .. imageFile
},]]
text = "Help me!"
}
},
menuIcon =
{
imageType = "DYNAMIC",
value = strAppFolder .. imageFile
},
vrHelpTitle = "New VR help title",
keyboardProperties =
{
keyboardLayout = "QWERTY",
keypressMode = "SINGLE_KEYPRESS",
--[[ TODO: update after resolving APPLINK-16047
limitedCharacterList =
{
"a"
},]]
language = "EN-US",
autoCompleteText = "Daemon, Freedom"
}
})
:Do(function(_,data)
--hmi side: sending UI.SetGlobalProperties response
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
:Timeout(iTimeout)
--mobile side: expect SetGlobalProperties response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS"})
:Timeout(iTimeout)
end
function Test:OpenVRMenu()
SendOnSystemContext(self,"VRSESSION")
EXPECT_NOTIFICATION("OnHMIStatus",{ hmiLevel = "FULL", audioStreamingState = audibleState, systemContext = "VRSESSION"})
end
TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue)
function Test:BackToMain()
SendOnSystemContext(self,"MAIN")
EXPECT_NOTIFICATION("OnHMIStatus",{ hmiLevel = "FULL", audioStreamingState = audibleState, systemContext = "MAIN"})
end
end
local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"},
{fileName = "action.bmp", fileType ="GRAPHIC_BMP"},
{fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}}
for i=1,#imageFile do
TC_OnFileRemoved_07(imageFile[i].fileName, imageFile[i].fileType)
end
--End test case SequenceCheck.8
-----------------------------------------------------------------------------------------
--Print new line to separate new test cases
commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_08")
--Begin test case SequenceCheck.9
--Description: Cover TC_OnFileRemoved_08
--Requirement id in JAMA/or Jira ID: SDLAQ-TC-336
--Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the Choice icon to default after deleting file, which was set for the Choice icon, during PerformInteraction. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types).
local function TC_OnFileRemoved_08(imageFile, imageTypeValue, idValue)
putfile(self, imageFile, imageTypeValue,_,_,imageFile)
function Test:CreateInteractionChoiceSet()
--mobile side: sending CreateInteractionChoiceSet request
local cid = self.mobileSession:SendRPC("CreateInteractionChoiceSet",
{
interactionChoiceSetID = idValue,
choiceSet =
{
{
choiceID = idValue,
menuName ="Choice"..idValue,
vrCommands =
{
"VRChoice"..idValue,
},
image =
{
value =imageFile,
imageType ="DYNAMIC",
},
}
}
})
--hmi side: expect VR.AddCommand request
EXPECT_HMICALL("VR.AddCommand",
{
cmdID = idValue,
appID = self.applications[config.application1.registerAppInterfaceParams.appName],
type = "Choice",
vrCommands = {"VRChoice"..idValue}
})
:Do(function(_,data)
--hmi side: sending VR.AddCommand response
grammarIDValue = data.params.grammarID
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect CreateInteractionChoiceSet response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
--mobile side: expect OnHashChange notification
EXPECT_NOTIFICATION("OnHashChange")
end
function Test:PerformInteraction()
local paramsSend = {
initialText = "StartPerformInteraction",
initialPrompt = {
{
text = " Make your choice ",
type = "TEXT",
}
},
interactionMode = "MANUAL_ONLY",
interactionChoiceSetIDList =
{
idValue
},
helpPrompt = {
{
text = " Help Prompt ",
type = "TEXT",
}
},
timeoutPrompt = {
{
text = " Time out ",
type = "TEXT",
}
},
timeout = 5000,
vrHelp = {
{
text = " New VRHelp ",
position = 1,
image = {
value = strAppFolder..imageFile,
imageType = "DYNAMIC",
}
}
},
interactionLayout = "ICON_ONLY"
}
--mobile side: sending PerformInteraction request
cid = self.mobileSession:SendRPC("PerformInteraction", paramsSend)
--hmi side: expect VR.PerformInteraction request
EXPECT_HMICALL("VR.PerformInteraction",
{
helpPrompt = paramsSend.helpPrompt,
initialPrompt = paramsSend.initialPrompt,
timeout = paramsSend.timeout,
timeoutPrompt = paramsSend.timeoutPrompt
})
:Do(function(_,data)
--Send notification to start TTS
self.hmiConnection:SendNotification("TTS.Started")
self.hmiConnection:SendError(data.id, data.method, "TIMED_OUT", "Perform Interaction error response.")
end)
--hmi side: expect UI.PerformInteraction request
EXPECT_HMICALL("UI.PerformInteraction",
{
timeout = paramsSend.timeout,
choiceSet = {
{
choiceID = idValue,
--[[ TODO: update after resolving APPLINK-16052
image =
{
value = strAppFolder..imageFile,
imageType = "DYNAMIC",
},]]
menuName = "Choice"..idValue
}
},
initialText =
{
fieldName = "initialInteractionText",
fieldText = paramsSend.initialText
}
})
:Do(function(_,data)
SendOnSystemContext(self,"HMI_OBSCURED")
--mobile side: sending DeleteFile request
local cid = self.mobileSession:SendRPC("DeleteFile",
{
syncFileName = imageFile
})
--hmi side: expect BasicCommunication.OnFileRemoved request
EXPECT_HMINOTIFICATION("BasicCommunication.OnFileRemoved",
{
fileName = strAppFolder .. imageFile,
fileType = imageTypeValue,
appID = self.applications[config.application1.registerAppInterfaceParams.appName]
})
--mobile side: expect DeleteFile response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS", info = nil })
:ValidIf (function(_,data)
if data.payload.spaceAvailable == nil then
commonFunctions:printError("spaceAvailable parameter is missed")
return false
else
if file_check(strAppFolder .. imageFile) == true then
print(" \27[36m File is not delete from storage \27[0m ")
return false
else
return true
end
end
end)
local function uiResponse()
--hmi side: send UI.PerformInteraction response
self.hmiConnection:SendError(data.id, data.method, "TIMED_OUT", "Perform Interaction error response.")
--Send notification to stop TTS
self.hmiConnection:SendNotification("TTS.Stopped")
SendOnSystemContext(self,"MAIN")
end
RUN_AFTER(uiResponse, 1000)
end)
--mobile side: OnHMIStatus notifications
ExpectOnHMIStatusWithAudioStateChanged(self, "MANUAL",_, "FULL")
--mobile side: expect PerformInteraction response
EXPECT_RESPONSE(cid, { success = false, resultCode = "TIMED_OUT"})
end
end
local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"},
{fileName = "action.bmp", fileType ="GRAPHIC_BMP"},
{fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}}
for i=1,#imageFile do
TC_OnFileRemoved_08(imageFile[i].fileName, imageFile[i].fileType, i+20)
end
--End test case SequenceCheck.9
-----------------------------------------------------------------------------------------
--Print new line to separate new test cases
commonFunctions:newTestCasesGroup("Test case: TC_OnFileRemoved_09")
--Begin test case SequenceCheck.10
--Description: Cover TC_OnFileRemoved_09
--Requirement id in JAMA/or Jira ID: SDLAQ-TC-338
--Verification criteria: Checking sending OnFileRemoved notification by Core to HMI and changing the Choice icon to default after deleting file, which was set for the Choice icon, before PerformInteraction. (Checking for GRAPHIC_BMP, GRAPHIC_JPEG, GRAPHIC_PNG image types).
local function TC_OnFileRemoved_09(imageFile, imageTypeValue, idValue)
putfile(self, imageFile, imageTypeValue,_,_,imageFile)
function Test:CreateInteractionChoiceSet()
--mobile side: sending CreateInteractionChoiceSet request
local cid = self.mobileSession:SendRPC("CreateInteractionChoiceSet",
{
interactionChoiceSetID = idValue,
choiceSet =
{
{
choiceID = idValue,
menuName ="Choice"..idValue,
vrCommands =
{
"VRChoice"..idValue,
},
image =
{
value =imageFile,
imageType ="DYNAMIC",
},
}
}
})
--hmi side: expect VR.AddCommand request
EXPECT_HMICALL("VR.AddCommand",
{
cmdID = idValue,
appID = self.applications[config.application1.registerAppInterfaceParams.appName],
type = "Choice",
vrCommands = {"VRChoice"..idValue}
})
:Do(function(_,data)
--hmi side: sending VR.AddCommand response
grammarIDValue = data.params.grammarID
self.hmiConnection:SendResponse(data.id, data.method, "SUCCESS", {})
end)
--mobile side: expect CreateInteractionChoiceSet response
EXPECT_RESPONSE(cid, { success = true, resultCode = "SUCCESS" })
--mobile side: expect OnHashChange notification
EXPECT_NOTIFICATION("OnHashChange")
end
TC_DeleteFile_SUCCESS(self, "DeleteFile_"..imageFile, imageFile, imageTypeValue)
function Test:PerformInteraction()
local paramsSend = {
initialText = "StartPerformInteraction",
initialPrompt = {
{
text = " Make your choice ",
type = "TEXT",
}
},
interactionMode = "MANUAL_ONLY",
interactionChoiceSetIDList =
{
idValue
},
helpPrompt = {
{
text = " Help Prompt ",
type = "TEXT",
}
},
timeoutPrompt = {
{
text = " Time out ",
type = "TEXT",
}
},
timeout = 5000,
interactionLayout = "ICON_ONLY"
}
--mobile side: sending PerformInteraction request
cid = self.mobileSession:SendRPC("PerformInteraction", paramsSend)
--hmi side: expect VR.PerformInteraction request
EXPECT_HMICALL("VR.PerformInteraction",
{
helpPrompt = paramsSend.helpPrompt,
initialPrompt = paramsSend.initialPrompt,
timeout = paramsSend.timeout,
timeoutPrompt = paramsSend.timeoutPrompt
})
:Do(function(_,data)
--Send notification to start TTS
self.hmiConnection:SendNotification("TTS.Started")
self.hmiConnection:SendError(data.id, data.method, "TIMED_OUT", "Perform Interaction error response.")
end)
--hmi side: expect UI.PerformInteraction request
EXPECT_HMICALL("UI.PerformInteraction",
{
timeout = paramsSend.timeout,
choiceSet = {
{
choiceID = idValue,
--[[ TODO: update after resolving APPLINK-16052
image =
{
value = strAppFolder..imageFile,
imageType = "DYNAMIC",
},]]
menuName = "Choice"..idValue
}
},
initialText =
{
fieldName = "initialInteractionText",
fieldText = paramsSend.initialText
}
})
:Do(function(_,data)
--hmi side: send UI.PerformInteraction response
SendOnSystemContext(self,"HMI_OBSCURED")
self.hmiConnection:SendError(data.id, data.method, "TIMED_OUT", "Perform Interaction error response.")
--Send notification to stop TTS
self.hmiConnection:SendNotification("TTS.Stopped")
SendOnSystemContext(self,"MAIN")
end)
--mobile side: OnHMIStatus notifications
ExpectOnHMIStatusWithAudioStateChanged(self, "MANUAL",_, "FULL")
--mobile side: expect PerformInteraction response
EXPECT_RESPONSE(cid, { success = false, resultCode = "TIMED_OUT"})
end
end
local imageFile = {{fileName = "action.png", fileType ="GRAPHIC_PNG"},
{fileName = "action.bmp", fileType ="GRAPHIC_BMP"},
{fileName = "action.jpeg", fileType ="GRAPHIC_JPEG"}}
for i=1,#imageFile do
TC_OnFileRemoved_09(imageFile[i].fileName, imageFile[i].fileType, i+30)
end
--End test case SequenceCheck.10
--End test suit SequenceCheck
----------------------------------------------------------------------------------------------
-----------------------------------------VII TEST BLOCK---------------------------------------
--------------------------------------Different HMIStatus-------------------------------------
----------------------------------------------------------------------------------------------
-- processing of request/response in different HMIlevels, SystemContext, AudioStreamingState
--Write NewTestBlock to ATF log
function Test:NewTestBlock()
commonFunctions:printError("****************************** VII TEST BLOCK: Different HMIStatus ******************************")
end
--Begin test suit DifferentHMIlevel
--Description: processing API in different HMILevel
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-810
--Verification criteria: DeleteFile is allowed in NONE, LIMITED, BACKGROUND and FULL HMI level
--Begin test case DifferentHMIlevel.1
--Description: Check DeleteFile request when application is in NONE HMI level
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-810
--Verification criteria: DeleteFile is allowed in NONE HMI level
-- Precondition 1: Change app to NONE HMI level
commonSteps:DeactivateAppToNoneHmiLevel()
-- Precondition 2: PutFile
putfile(self, "test.png", "GRAPHIC_PNG")
TC_DeleteFile_SUCCESS(self, "DeleteFile_HMI_Level_NONE_SUCCESS", "test.png", "GRAPHIC_PNG")
--Postcondition: Activate app
commonSteps:ActivationApp()
--End test case DifferentHMIlevel.1
--Begin test case DifferentHMIlevel.2
--Description: Check DeleteFile request when application is in LIMITED HMI level
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-810
--Verification criteria: DeleteFile is allowed in LIMITED HMI level
if commonFunctions:isMediaApp() then
-- Precondition 1: Change app to LIMITED
commonSteps:ChangeHMIToLimited()
-- Precondition 2: Put file
putfile(self, "test.png", "GRAPHIC_PNG")
TC_DeleteFile_SUCCESS(self, "DeleteFile_HMI_Level_LIMITED_SUCCESS", "test.png", "GRAPHIC_PNG")
end
--End test case DifferentHMIlevel.2
--Begin test case DifferentHMIlevel.3
--Description: Check DeleteFile request when application is in BACKGOUND HMI level
--Requirement id in JAMA/or Jira ID: SDLAQ-CRS-810
--Verification criteria: DeleteFile is allowed in BACKGOUND HMI level
-- Precondition 1: Change app to BACKGOUND HMI level
commonTestCases:ChangeAppToBackgroundHmiLevel()
-- Precondition 2: Put file
putfile(self, "test.png", "GRAPHIC_PNG")
TC_DeleteFile_SUCCESS(self, "DeleteFile_HMI_Level_BACKGROUND_SUCCESS", "test.png", "GRAPHIC_PNG")
--End test case DifferentHMIlevel.3
--End test suit DifferentHMIlevel
--Postcondition: restore sdl_preloaded_pt.json
policyTable:Restore_preloaded_pt()
return Test
| bsd-3-clause |
eclipsesource/tabris-js | src/tabris/CanvasContext.js | 9943 | import {colorArrayToString} from './util-colors';
import {getNativeObject} from './util';
import Color from './Color';
import {fontStringToObject, fontObjectToString} from './util-fonts';
import ImageData from './ImageData';
import GC from './GC';
import {hint, toValueString} from './Console';
import ImageBitmap from './ImageBitmap';
export default class CanvasContext {
/**
* @param {GC} gc
*/
constructor(gc) {
Object.defineProperties(this, {
_gc: {enumerable: false, writable: false, value: gc},
_state: {enumerable: false, writable: true, value: createState()},
_savedStates: {enumerable: false, writable: false, value: []}
});
this.canvas = {
width: 0,
height: 0,
style: {}
};
for (const name in properties) {
defineProperty(this, name);
}
}
measureText(text) {
// TODO: delegate to native function, once it is implemented (#56)
return {width: text.length * 5 + 5};
}
// ImageData operations
getImageData(x, y, width, height) {
checkRequiredArgs(arguments, 4, 'CanvasContext.getImageData');
this._gc.flush();
// TODO check validity of args
const array = this._gc.getImageData(x, y, width, height);
return new ImageData(array, width, height);
}
putImageData(imageData, x, y) {
checkRequiredArgs(arguments, 3, 'CanvasContext.putImageData');
this._gc.flush();
this._gc.putImageData(imageData, x, y);
}
createImageData(width, height) {
if (arguments[0] instanceof ImageData) {
const data = arguments[0];
width = data.width;
height = data.height;
} else {
checkRequiredArgs(arguments, 2, 'CanvasContext.createImageData');
}
return new ImageData(width, height);
}
_init(width, height) {
this.canvas.width = width;
this.canvas.height = height;
this._gc.init({width, height});
}
}
/** @typedef {{[Key in keyof typeof properties]: any}} State */
Object.defineProperty(CanvasContext.prototype, '_gc', {
enumerable: false, value: (/** @type {GC} */(null))
});
Object.defineProperty(CanvasContext.prototype, '_state', {
enumerable: false, writable: true, value: (/** @type {State} */(null))
});
Object.defineProperty(CanvasContext.prototype, '_savedStates', {
enumerable: false, writable: false, value: (/** @type {State[]} */(null))
});
// State operations
defineMethod('save', 0, /** @this {CanvasContext} */ function() {
this._savedStates.push(Object.assign({}, this._state));
});
defineMethod('restore', 0, /** @this {CanvasContext} */ function() {
this._state = this._savedStates.pop() || this._state;
});
// Path operations
defineMethod('beginPath');
defineMethod('closePath');
defineMethod('lineTo', 2, /** @this {CanvasContext} */ function(x, y) {
this._gc.addDouble(x, y);
});
defineMethod('moveTo', 2, /** @this {CanvasContext} */ function(x, y) {
this._gc.addDouble(x, y);
});
defineMethod('bezierCurveTo', 6, /** @this {CanvasContext} */ function(cp1x, cp1y, cp2x, cp2y, x, y) {
this._gc.addDouble(cp1x, cp1y, cp2x, cp2y, x, y);
});
defineMethod('quadraticCurveTo', 4, /** @this {CanvasContext} */ function(cpx, cpy, x, y) {
this._gc.addDouble(cpx, cpy, x, y);
});
defineMethod('rect', 4, /** @this {CanvasContext} */ function(x, y, width, height) {
this._gc.addDouble(x, y, width, height);
});
defineMethod('arc', 5, /** @this {CanvasContext} */ function(x, y, radius, startAngle, endAngle, anticlockwise) {
this._gc.addDouble(x, y, radius, startAngle, endAngle);
this._gc.addBoolean(!!anticlockwise);
});
defineMethod('arcTo', 5, /** @this {CanvasContext} */ function(x1, y1, x2, y2, radius) {
this._gc.addDouble(x1, y1, x2, y2, radius);
});
// Transformations
defineMethod('scale', 2, /** @this {CanvasContext} */ function(x, y) {
this._gc.addDouble(x, y);
});
defineMethod('rotate', 1, /** @this {CanvasContext} */ function(angle) {
this._gc.addDouble(angle);
});
defineMethod('translate', 2, /** @this {CanvasContext} */ function(x, y) {
this._gc.addDouble(x, y);
});
defineMethod('transform', 6, /** @this {CanvasContext} */ function(a, b, c, d, e, f) {
this._gc.addDouble(a, b, c, d, e, f);
});
defineMethod('setTransform', 6, /** @this {CanvasContext} */ function(a, b, c, d, e, f) {
this._gc.addDouble(a, b, c, d, e, f);
});
// Drawing operations
defineMethod('clearRect', 4, /** @this {CanvasContext} */ function(x, y, width, height) {
this._gc.addDouble(x, y, width, height);
});
defineMethod('fillRect', 4, /** @this {CanvasContext} */ function(x, y, width, height) {
this._gc.addDouble(x, y, width, height);
});
defineMethod('strokeRect', 4, /** @this {CanvasContext} */ function(x, y, width, height) {
this._gc.addDouble(x, y, width, height);
});
defineMethod('fillText', 3, /** @this {CanvasContext} */ function(text, x, y /* , maxWidth */) {
this._gc.addString(text);
this._gc.addBoolean(false, false, false);
this._gc.addDouble(x, y);
});
defineMethod('strokeText', 3, /** @this {CanvasContext} */ function(text, x, y /* , maxWidth */) {
this._gc.addString(text);
this._gc.addBoolean(false, false, false);
this._gc.addDouble(x, y);
});
defineMethod('fill');
defineMethod('stroke');
defineMethod('drawImage', 3, /** @this {CanvasContext} */ function(image, x1, y1, w1, h1, x2, y2, w2, h2) {
if (!(image instanceof ImageBitmap)) {
throw new TypeError('First argument of CanvasContext.drawImage must be of type ImageBitmap');
}
this._gc.addString(getNativeObject(image).cid);
if (arguments.length === 9) {
this._gc.addDouble(x1, y1, w1, h1, x2, y2, w2, h2);
} else if (arguments.length === 5) {
this._gc.addDouble(0, 0, image.width, image.height, x1, y1, w1, h1);
} else if (arguments.length === 3) {
this._gc.addDouble(0, 0, image.width, image.height, x1, y1, image.width, image.height);
} else {
throw new TypeError(arguments.length + ' is not a valid argument count for any overload of Canvas.drawImage.');
}
});
CanvasContext.getContext = function(canvas, width, height) {
if (!canvas._gc) {
const gc = new GC({parent: canvas});
canvas.on('_dispose', () => gc.dispose());
Object.defineProperty(canvas, '_gc', {
enumerable: false,
writable: false,
value: gc
});
}
if (!canvas._ctx) {
Object.defineProperty(canvas, '_ctx', {
enumerable: false,
writable: false,
value: new CanvasContext(canvas._gc)
});
}
canvas._ctx._init(width, height);
return canvas._ctx;
};
const properties = {
lineWidth: {
init: 1,
encode(value) {
if (!isNaN(value) && value > 0) {
return value;
}
throw new Error(`Invalid value ${toValueString(value)}`);
},
decode: passThrough,
addOperations(value) {
this._gc.addDouble(value);
}
},
lineCap: {
init: 'butt',
values: toObject(['butt', 'round', 'square']),
encode: checkValue,
decode: passThrough,
addOperations(value) {
this._gc.addString(value);
}
},
lineJoin: {
init: 'miter',
values: toObject(['bevel', 'miter', 'round']),
encode: checkValue,
decode: passThrough,
addOperations(value) {
this._gc.addString(value);
}
},
fillStyle: {
init: [0, 0, 0, 255],
encode: value => Color.from(value).toArray(),
decode: colorArrayToString,
addOperations(value) {
this._gc.addInt(value[0], value[1], value[2], value[3]);
}
},
strokeStyle: {
init: [0, 0, 0, 255],
encode: value => Color.from(value).toArray(),
decode: colorArrayToString,
addOperations(value) {
this._gc.addInt(value[0], value[1], value[2], value[3]);
}
},
textAlign: {
init: 'start',
values: toObject(['start', 'end', 'left', 'right', 'center']),
encode: checkValue,
decode: passThrough,
addOperations(value) {
this._gc.addString(value);
}
},
textBaseline: {
init: 'alphabetic',
values: toObject(['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom']),
encode: checkValue,
decode: passThrough,
addOperations(value) {
this._gc.addString(value);
}
},
font: {
init: {family: ['sans-serif'], size: 12, weight: 'normal', style: 'normal'},
encode: fontStringToObject,
decode: fontObjectToString,
addOperations(font) {
this._gc.addString(font.family.join(', '), font.style, font.weight);
this._gc.addDouble(font.size);
}
}
};
function passThrough(value) {
return value;
}
/** @this {{values: any[]}} */
function checkValue(value) {
if (value in this.values) {
return value;
}
throw new Error(`Invalid value ${toValueString(value)}`);
}
function toObject(array) {
const obj = {};
array.forEach((name) => {
obj[name] = true;
});
return obj;
}
function createState() {
const state = {};
for (const name in properties) {
state[name] = properties[name].init;
}
return state;
}
/**
* @param {string} name
* @param {number=} reqArgCount
* @param {((this: CanvasContext, ...args: any[]) => any)=} fn
*/
function defineMethod(name, reqArgCount, fn) {
CanvasContext.prototype[name] = /** @this {CanvasContext} */ function() {
checkRequiredArgs(arguments, reqArgCount, 'CanvasContext.' + name);
this._gc.addOperation(name);
if (fn) {
fn.apply(this, arguments);
}
};
}
function defineProperty(context, name) {
const prop = properties[name];
Object.defineProperty(context, name, {
get() {
return prop.decode(context._state[name]);
},
set(value) {
try {
context._state[name] = prop.encode(value);
context._gc.addOperation(name);
prop.addOperations.call(context, context._state[name]);
} catch (error) {
hint(context, 'Unsupported value for ' + name + ': ' + value);
}
}
});
}
function checkRequiredArgs(args, nr, name) {
if (args.length < nr) {
throw new Error('Not enough arguments to ' + name);
}
}
| bsd-3-clause |
rzara/lutece-core | src/java/fr/paris/lutece/util/annotation/AnnotationUtil.java | 3036 | /*
* Copyright (c) 2002-2021, City of Paris
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright notice
* and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice
* and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of 'Mairie de Paris' nor 'Lutece' 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 HOLDERS 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.
*
* License 1.0
*/
package fr.paris.lutece.util.annotation;
import fr.paris.lutece.portal.service.spring.SpringContextService;
import fr.paris.lutece.portal.service.util.AppException;
import java.lang.annotation.Annotation;
import java.util.Set;
/**
*
* Allow classpath scanning for annotations
*
*/
public final class AnnotationUtil
{
private static final IAnnotationDB ANNOTATION_DB = SpringContextService.getBean( "annotationDB" );
static
{
// check annotation db
if ( ANNOTATION_DB == null )
{
throw new AppException( "Bean annotationDB is not correctly set. Please check you core_context.xml configuration." );
}
ANNOTATION_DB.init( );
}
/**
* Empty constructor
*/
private AnnotationUtil( )
{
// nothing
}
/**
* Finds all classes with the given annotation
*
* @param annotationType
* the annotation class
* @return all classes founds
*/
public static Set<String> find( Class<? extends Annotation> annotationType )
{
return ANNOTATION_DB.getClassesName( annotationType );
}
/**
* Finds all classes with the given annotation
*
* @param strAnnotation
* the annotation class name
* @return all classes founds
*/
public static Set<String> find( String strAnnotation )
{
return ANNOTATION_DB.getClassesName( strAnnotation );
}
}
| bsd-3-clause |
chromium2014/src | chrome/browser/autocomplete/autocomplete_result_unittest.cc | 34584 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/autocomplete/autocomplete_result.h"
#include <vector>
#include "base/memory/scoped_ptr.h"
#include "base/metrics/field_trial.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/autocomplete/autocomplete_match.h"
#include "chrome/browser/autocomplete/autocomplete_provider.h"
#include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
#include "chrome/browser/omnibox/omnibox_field_trial.h"
#include "chrome/browser/search_engines/template_url_service_test_util.h"
#include "chrome/test/base/testing_profile.h"
#include "components/autocomplete/autocomplete_input.h"
#include "components/autocomplete/autocomplete_match_type.h"
#include "components/metrics/proto/omnibox_event.pb.h"
#include "components/search_engines/template_url_prepopulate_data.h"
#include "components/search_engines/template_url_service.h"
#include "components/variations/entropy_provider.h"
#include "components/variations/variations_associated_data.h"
#include "testing/gtest/include/gtest/gtest.h"
using metrics::OmniboxEventProto;
namespace {
struct AutocompleteMatchTestData {
std::string destination_url;
AutocompleteMatch::Type type;
};
const AutocompleteMatchTestData kVerbatimMatches[] = {
{ "http://search-what-you-typed/",
AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED },
{ "http://url-what-you-typed/", AutocompleteMatchType::URL_WHAT_YOU_TYPED },
};
const AutocompleteMatchTestData kNonVerbatimMatches[] = {
{ "http://search-history/", AutocompleteMatchType::SEARCH_HISTORY },
{ "http://history-title/", AutocompleteMatchType::HISTORY_TITLE },
};
// Adds |count| AutocompleteMatches to |matches|.
void PopulateAutocompleteMatchesFromTestData(
const AutocompleteMatchTestData* data,
size_t count,
ACMatches* matches) {
ASSERT_TRUE(matches != NULL);
for (size_t i = 0; i < count; ++i) {
AutocompleteMatch match;
match.destination_url = GURL(data[i].destination_url);
match.relevance =
matches->empty() ? 1300 : (matches->back().relevance - 100);
match.allowed_to_be_default_match = true;
match.type = data[i].type;
matches->push_back(match);
}
}
} // namespace
class AutocompleteResultTest : public testing::Test {
public:
struct TestData {
// Used to build a url for the AutocompleteMatch. The URL becomes
// "http://" + ('a' + |url_id|) (e.g. an ID of 2 yields "http://b").
int url_id;
// ID of the provider.
int provider_id;
// Relevance score.
int relevance;
// Duplicate matches.
std::vector<AutocompleteMatch> duplicate_matches;
};
AutocompleteResultTest() {
// Destroy the existing FieldTrialList before creating a new one to avoid
// a DCHECK.
field_trial_list_.reset();
field_trial_list_.reset(new base::FieldTrialList(
new metrics::SHA1EntropyProvider("foo")));
chrome_variations::testing::ClearAllVariationParams();
}
virtual void SetUp() OVERRIDE {
#if defined(OS_ANDROID)
TemplateURLPrepopulateData::InitCountryCode(
std::string() /* unknown country code */);
#endif
test_util_.SetUp();
test_util_.VerifyLoad();
}
virtual void TearDown() OVERRIDE {
test_util_.TearDown();
}
// Configures |match| from |data|.
static void PopulateAutocompleteMatch(const TestData& data,
AutocompleteMatch* match);
// Adds |count| AutocompleteMatches to |matches|.
static void PopulateAutocompleteMatches(const TestData* data,
size_t count,
ACMatches* matches);
// Asserts that |result| has |expected_count| matches matching |expected|.
void AssertResultMatches(const AutocompleteResult& result,
const TestData* expected,
size_t expected_count);
// Creates an AutocompleteResult from |last| and |current|. The two are
// merged by |CopyOldMatches| and compared by |AssertResultMatches|.
void RunCopyOldMatchesTest(const TestData* last, size_t last_size,
const TestData* current, size_t current_size,
const TestData* expected, size_t expected_size);
protected:
TemplateURLServiceTestUtil test_util_;
private:
scoped_ptr<base::FieldTrialList> field_trial_list_;
DISALLOW_COPY_AND_ASSIGN(AutocompleteResultTest);
};
// static
void AutocompleteResultTest::PopulateAutocompleteMatch(
const TestData& data,
AutocompleteMatch* match) {
match->provider = reinterpret_cast<AutocompleteProvider*>(data.provider_id);
match->fill_into_edit = base::IntToString16(data.url_id);
std::string url_id(1, data.url_id + 'a');
match->destination_url = GURL("http://" + url_id);
match->relevance = data.relevance;
match->allowed_to_be_default_match = true;
match->duplicate_matches = data.duplicate_matches;
}
// static
void AutocompleteResultTest::PopulateAutocompleteMatches(
const TestData* data,
size_t count,
ACMatches* matches) {
for (size_t i = 0; i < count; ++i) {
AutocompleteMatch match;
PopulateAutocompleteMatch(data[i], &match);
matches->push_back(match);
}
}
void AutocompleteResultTest::AssertResultMatches(
const AutocompleteResult& result,
const TestData* expected,
size_t expected_count) {
ASSERT_EQ(expected_count, result.size());
for (size_t i = 0; i < expected_count; ++i) {
AutocompleteMatch expected_match;
PopulateAutocompleteMatch(expected[i], &expected_match);
const AutocompleteMatch& match = *(result.begin() + i);
EXPECT_EQ(expected_match.provider, match.provider) << i;
EXPECT_EQ(expected_match.relevance, match.relevance) << i;
EXPECT_EQ(expected_match.destination_url.spec(),
match.destination_url.spec()) << i;
}
}
void AutocompleteResultTest::RunCopyOldMatchesTest(
const TestData* last, size_t last_size,
const TestData* current, size_t current_size,
const TestData* expected, size_t expected_size) {
AutocompleteInput input(base::ASCIIToUTF16("a"), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::INVALID_SPEC, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
ACMatches last_matches;
PopulateAutocompleteMatches(last, last_size, &last_matches);
AutocompleteResult last_result;
last_result.AppendMatches(last_matches);
last_result.SortAndCull(input, test_util_.model());
ACMatches current_matches;
PopulateAutocompleteMatches(current, current_size, ¤t_matches);
AutocompleteResult current_result;
current_result.AppendMatches(current_matches);
current_result.SortAndCull(input, test_util_.model());
current_result.CopyOldMatches(input, last_result, test_util_.model());
AssertResultMatches(current_result, expected, expected_size);
}
// Assertion testing for AutocompleteResult::Swap.
TEST_F(AutocompleteResultTest, Swap) {
AutocompleteResult r1;
AutocompleteResult r2;
// Swap with empty shouldn't do anything interesting.
r1.Swap(&r2);
EXPECT_EQ(r1.end(), r1.default_match());
EXPECT_EQ(r2.end(), r2.default_match());
// Swap with a single match.
ACMatches matches;
AutocompleteMatch match;
match.relevance = 1;
match.allowed_to_be_default_match = true;
AutocompleteInput input(base::ASCIIToUTF16("a"), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::INVALID_SPEC, false, false, false,
true, ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
matches.push_back(match);
r1.AppendMatches(matches);
r1.SortAndCull(input, test_util_.model());
EXPECT_EQ(r1.begin(), r1.default_match());
EXPECT_EQ("http://a/", r1.alternate_nav_url().spec());
r1.Swap(&r2);
EXPECT_TRUE(r1.empty());
EXPECT_EQ(r1.end(), r1.default_match());
EXPECT_TRUE(r1.alternate_nav_url().is_empty());
ASSERT_FALSE(r2.empty());
EXPECT_EQ(r2.begin(), r2.default_match());
EXPECT_EQ("http://a/", r2.alternate_nav_url().spec());
}
// Tests that if the new results have a lower max relevance score than last,
// any copied results have their relevance shifted down.
TEST_F(AutocompleteResultTest, CopyOldMatches) {
TestData last[] = {
{ 0, 0, 1000 },
{ 1, 0, 500 },
};
TestData current[] = {
{ 2, 0, 400 },
};
TestData result[] = {
{ 2, 0, 400 },
{ 1, 0, 399 },
};
ASSERT_NO_FATAL_FAILURE(
RunCopyOldMatchesTest(last, ARRAYSIZE_UNSAFE(last),
current, ARRAYSIZE_UNSAFE(current),
result, ARRAYSIZE_UNSAFE(result)));
}
// Tests that matches are copied correctly from two distinct providers.
TEST_F(AutocompleteResultTest, CopyOldMatches2) {
TestData last[] = {
{ 0, 0, 1000 },
{ 1, 1, 500 },
{ 2, 0, 400 },
{ 3, 1, 300 },
};
TestData current[] = {
{ 4, 0, 1100 },
{ 5, 1, 550 },
};
TestData result[] = {
{ 4, 0, 1100 },
{ 5, 1, 550 },
{ 2, 0, 400 },
{ 3, 1, 300 },
};
ASSERT_NO_FATAL_FAILURE(
RunCopyOldMatchesTest(last, ARRAYSIZE_UNSAFE(last),
current, ARRAYSIZE_UNSAFE(current),
result, ARRAYSIZE_UNSAFE(result)));
}
// Tests that matches with empty destination URLs aren't treated as duplicates
// and culled.
TEST_F(AutocompleteResultTest, SortAndCullEmptyDestinationURLs) {
TestData data[] = {
{ 1, 0, 500 },
{ 0, 0, 1100 },
{ 1, 0, 1000 },
{ 0, 0, 1300 },
{ 0, 0, 1200 },
};
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
matches[1].destination_url = GURL();
matches[3].destination_url = GURL();
matches[4].destination_url = GURL();
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::INVALID_SPEC, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
// Of the two results with the same non-empty destination URL, the
// lower-relevance one should be dropped. All of the results with empty URLs
// should be kept.
ASSERT_EQ(4U, result.size());
EXPECT_TRUE(result.match_at(0)->destination_url.is_empty());
EXPECT_EQ(1300, result.match_at(0)->relevance);
EXPECT_TRUE(result.match_at(1)->destination_url.is_empty());
EXPECT_EQ(1200, result.match_at(1)->relevance);
EXPECT_TRUE(result.match_at(2)->destination_url.is_empty());
EXPECT_EQ(1100, result.match_at(2)->relevance);
EXPECT_EQ("http://b/", result.match_at(3)->destination_url.spec());
EXPECT_EQ(1000, result.match_at(3)->relevance);
}
TEST_F(AutocompleteResultTest, SortAndCullDuplicateSearchURLs) {
// Register a template URL that corresponds to 'foo' search engine.
TemplateURLData url_data;
url_data.short_name = base::ASCIIToUTF16("unittest");
url_data.SetKeyword(base::ASCIIToUTF16("foo"));
url_data.SetURL("http://www.foo.com/s?q={searchTerms}");
test_util_.model()->Add(new TemplateURL(url_data));
TestData data[] = {
{ 0, 0, 1300 },
{ 1, 0, 1200 },
{ 2, 0, 1100 },
{ 3, 0, 1000 },
{ 4, 1, 900 },
};
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
matches[0].destination_url = GURL("http://www.foo.com/s?q=foo");
matches[1].destination_url = GURL("http://www.foo.com/s?q=foo2");
matches[2].destination_url = GURL("http://www.foo.com/s?q=foo&oq=f");
matches[3].destination_url = GURL("http://www.foo.com/s?q=foo&aqs=0");
matches[4].destination_url = GURL("http://www.foo.com/");
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::INVALID_SPEC, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
// We expect the 3rd and 4th results to be removed.
ASSERT_EQ(3U, result.size());
EXPECT_EQ("http://www.foo.com/s?q=foo",
result.match_at(0)->destination_url.spec());
EXPECT_EQ(1300, result.match_at(0)->relevance);
EXPECT_EQ("http://www.foo.com/s?q=foo2",
result.match_at(1)->destination_url.spec());
EXPECT_EQ(1200, result.match_at(1)->relevance);
EXPECT_EQ("http://www.foo.com/",
result.match_at(2)->destination_url.spec());
EXPECT_EQ(900, result.match_at(2)->relevance);
}
TEST_F(AutocompleteResultTest, SortAndCullWithMatchDups) {
// Register a template URL that corresponds to 'foo' search engine.
TemplateURLData url_data;
url_data.short_name = base::ASCIIToUTF16("unittest");
url_data.SetKeyword(base::ASCIIToUTF16("foo"));
url_data.SetURL("http://www.foo.com/s?q={searchTerms}");
test_util_.model()->Add(new TemplateURL(url_data));
AutocompleteMatch dup_match;
dup_match.destination_url = GURL("http://www.foo.com/s?q=foo&oq=dup");
std::vector<AutocompleteMatch> dups;
dups.push_back(dup_match);
TestData data[] = {
{ 0, 0, 1300, dups },
{ 1, 0, 1200 },
{ 2, 0, 1100 },
{ 3, 0, 1000, dups },
{ 4, 1, 900 },
{ 5, 0, 800 },
};
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
matches[0].destination_url = GURL("http://www.foo.com/s?q=foo");
matches[1].destination_url = GURL("http://www.foo.com/s?q=foo2");
matches[2].destination_url = GURL("http://www.foo.com/s?q=foo&oq=f");
matches[3].destination_url = GURL("http://www.foo.com/s?q=foo&aqs=0");
matches[4].destination_url = GURL("http://www.foo.com/");
matches[5].destination_url = GURL("http://www.foo.com/s?q=foo2&oq=f");
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::INVALID_SPEC, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
// Expect 3 unique results after SortAndCull().
ASSERT_EQ(3U, result.size());
// Check that 3rd and 4th result got added to the first result as dups
// and also duplicates of the 4th match got copied.
ASSERT_EQ(4U, result.match_at(0)->duplicate_matches.size());
const AutocompleteMatch* first_match = result.match_at(0);
EXPECT_EQ(matches[2].destination_url,
first_match->duplicate_matches.at(1).destination_url);
EXPECT_EQ(dup_match.destination_url,
first_match->duplicate_matches.at(2).destination_url);
EXPECT_EQ(matches[3].destination_url,
first_match->duplicate_matches.at(3).destination_url);
// Check that 6th result started a new list of dups for the second result.
ASSERT_EQ(1U, result.match_at(1)->duplicate_matches.size());
EXPECT_EQ(matches[5].destination_url,
result.match_at(1)->duplicate_matches.at(0).destination_url);
}
TEST_F(AutocompleteResultTest, SortAndCullWithDemotionsByType) {
// Add some matches.
ACMatches matches;
const AutocompleteMatchTestData data[] = {
{ "http://history-url/", AutocompleteMatchType::HISTORY_URL },
{ "http://search-what-you-typed/",
AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED },
{ "http://history-title/", AutocompleteMatchType::HISTORY_TITLE },
{ "http://search-history/", AutocompleteMatchType::SEARCH_HISTORY },
};
PopulateAutocompleteMatchesFromTestData(data, arraysize(data), &matches);
// Demote the search history match relevance score.
matches.back().relevance = 500;
// Add a rule demoting history-url and killing history-title.
{
std::map<std::string, std::string> params;
params[std::string(OmniboxFieldTrial::kDemoteByTypeRule) + ":3:*"] =
"1:50,7:100,2:0"; // 3 == HOME_PAGE
ASSERT_TRUE(chrome_variations::AssociateVariationParams(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "A", params));
}
base::FieldTrialList::CreateFieldTrial(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "A");
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::HOME_PAGE, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
// Check the new ordering. The history-title results should be omitted.
// We cannot check relevance scores because the matches are sorted by
// demoted relevance but the actual relevance scores are not modified.
ASSERT_EQ(3u, result.size());
EXPECT_EQ("http://search-what-you-typed/",
result.match_at(0)->destination_url.spec());
EXPECT_EQ("http://history-url/",
result.match_at(1)->destination_url.spec());
EXPECT_EQ("http://search-history/",
result.match_at(2)->destination_url.spec());
}
TEST_F(AutocompleteResultTest, SortAndCullWithMatchDupsAndDemotionsByType) {
// Add some matches.
ACMatches matches;
const AutocompleteMatchTestData data[] = {
{ "http://search-what-you-typed/",
AutocompleteMatchType::SEARCH_WHAT_YOU_TYPED },
{ "http://dup-url/", AutocompleteMatchType::HISTORY_URL },
{ "http://dup-url/", AutocompleteMatchType::NAVSUGGEST },
{ "http://search-url/", AutocompleteMatchType::SEARCH_SUGGEST },
{ "http://history-url/", AutocompleteMatchType::HISTORY_URL },
};
PopulateAutocompleteMatchesFromTestData(data, arraysize(data), &matches);
// Add a rule demoting HISTORY_URL.
{
std::map<std::string, std::string> params;
params[std::string(OmniboxFieldTrial::kDemoteByTypeRule) + ":8:*"] =
"1:50"; // 8 == INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS
ASSERT_TRUE(chrome_variations::AssociateVariationParams(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "C", params));
}
base::FieldTrialList::CreateFieldTrial(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "C");
{
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(
base::string16(), base::string16::npos, base::string16(), GURL(),
OmniboxEventProto::INSTANT_NTP_WITH_FAKEBOX_AS_STARTING_FOCUS, false,
false, false, true,
ChromeAutocompleteSchemeClassifier(test_util_.profile()));
result.SortAndCull(input, test_util_.model());
// The NAVSUGGEST dup-url stay above search-url since the navsuggest
// variant should not be demoted.
ASSERT_EQ(4u, result.size());
EXPECT_EQ("http://search-what-you-typed/",
result.match_at(0)->destination_url.spec());
EXPECT_EQ("http://dup-url/",
result.match_at(1)->destination_url.spec());
EXPECT_EQ(AutocompleteMatchType::NAVSUGGEST,
result.match_at(1)->type);
EXPECT_EQ("http://search-url/",
result.match_at(2)->destination_url.spec());
EXPECT_EQ("http://history-url/",
result.match_at(3)->destination_url.spec());
}
}
TEST_F(AutocompleteResultTest, SortAndCullReorderForDefaultMatch) {
TestData data[] = {
{ 0, 0, 1300 },
{ 1, 0, 1200 },
{ 2, 0, 1100 },
{ 3, 0, 1000 }
};
{
// Check that reorder doesn't do anything if the top result
// is already a legal default match (which is the default from
// PopulateAutocompleteMatches()).
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::HOME_PAGE, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
AssertResultMatches(result, data, 4);
}
{
// Check that reorder swaps up a result appropriately.
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
matches[0].allowed_to_be_default_match = false;
matches[1].allowed_to_be_default_match = false;
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::HOME_PAGE, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
ASSERT_EQ(4U, result.size());
EXPECT_EQ("http://c/", result.match_at(0)->destination_url.spec());
EXPECT_EQ("http://a/", result.match_at(1)->destination_url.spec());
EXPECT_EQ("http://b/", result.match_at(2)->destination_url.spec());
EXPECT_EQ("http://d/", result.match_at(3)->destination_url.spec());
}
}
TEST_F(AutocompleteResultTest, SortAndCullWithDisableInlining) {
TestData data[] = {
{ 0, 0, 1300 },
{ 1, 0, 1200 },
{ 2, 0, 1100 },
{ 3, 0, 1000 }
};
{
// Check that with the field trial disabled, we keep keep the first match
// first even if it has an inline autocompletion.
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
matches[0].inline_autocompletion = base::ASCIIToUTF16("completion");
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::HOME_PAGE, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
AssertResultMatches(result, data, 4);
}
// Enable the field trial to disable inlining.
{
std::map<std::string, std::string> params;
params[OmniboxFieldTrial::kDisableInliningRule] = "true";
ASSERT_TRUE(chrome_variations::AssociateVariationParams(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "D", params));
}
base::FieldTrialList::CreateFieldTrial(
OmniboxFieldTrial::kBundledExperimentFieldTrialName, "D");
{
// Now the first match should be demoted past the second.
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
matches[0].inline_autocompletion = base::ASCIIToUTF16("completion");
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::HOME_PAGE, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
ASSERT_EQ(4U, result.size());
EXPECT_EQ("http://b/", result.match_at(0)->destination_url.spec());
EXPECT_EQ("http://a/", result.match_at(1)->destination_url.spec());
EXPECT_EQ("http://c/", result.match_at(2)->destination_url.spec());
EXPECT_EQ("http://d/", result.match_at(3)->destination_url.spec());
}
{
// But if there was no inline autocompletion on the first match, then
// the order should stay the same. This is true even if there are
// inline autocompletions elsewhere.
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
matches[2].inline_autocompletion = base::ASCIIToUTF16("completion");
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::HOME_PAGE, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
AssertResultMatches(result, data, 4);
}
{
// Try a more complicated situation.
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
matches[0].allowed_to_be_default_match = false;
matches[1].inline_autocompletion = base::ASCIIToUTF16("completion");
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::HOME_PAGE, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
ASSERT_EQ(4U, result.size());
EXPECT_EQ("http://c/", result.match_at(0)->destination_url.spec());
EXPECT_EQ("http://a/", result.match_at(1)->destination_url.spec());
EXPECT_EQ("http://b/", result.match_at(2)->destination_url.spec());
EXPECT_EQ("http://d/", result.match_at(3)->destination_url.spec());
}
{
// Try another complicated situation.
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
matches[0].inline_autocompletion = base::ASCIIToUTF16("completion");
matches[1].allowed_to_be_default_match = false;
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::HOME_PAGE, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
ASSERT_EQ(4U, result.size());
EXPECT_EQ("http://c/", result.match_at(0)->destination_url.spec());
EXPECT_EQ("http://a/", result.match_at(1)->destination_url.spec());
EXPECT_EQ("http://b/", result.match_at(2)->destination_url.spec());
EXPECT_EQ("http://d/", result.match_at(3)->destination_url.spec());
}
{
// Check that disaster doesn't strike if we can't demote the top inline
// autocompletion because every match either has a completion or isn't
// allowed to be the default match. In this case, we should leave
// everything untouched.
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
matches[0].inline_autocompletion = base::ASCIIToUTF16("completion");
matches[1].allowed_to_be_default_match = false;
matches[2].allowed_to_be_default_match = false;
matches[3].inline_autocompletion = base::ASCIIToUTF16("completion");
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::HOME_PAGE, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
AssertResultMatches(result, data, 4);
}
{
// Check a similar situation, except in this case the top match is not
// allowed to the default match, so it still needs to be demoted so we
// get a legal default match first. That match will have an inline
// autocompletion because we don't have any better options.
ACMatches matches;
PopulateAutocompleteMatches(data, arraysize(data), &matches);
matches[0].allowed_to_be_default_match = false;
matches[1].inline_autocompletion = base::ASCIIToUTF16("completion");
matches[2].allowed_to_be_default_match = false;
matches[3].inline_autocompletion = base::ASCIIToUTF16("completion");
AutocompleteResult result;
result.AppendMatches(matches);
AutocompleteInput input(base::string16(), base::string16::npos,
base::string16(), GURL(),
OmniboxEventProto::HOME_PAGE, false, false, false,
true,
ChromeAutocompleteSchemeClassifier(
test_util_.profile()));
result.SortAndCull(input, test_util_.model());
ASSERT_EQ(4U, result.size());
EXPECT_EQ("http://b/", result.match_at(0)->destination_url.spec());
EXPECT_EQ("http://a/", result.match_at(1)->destination_url.spec());
EXPECT_EQ("http://c/", result.match_at(2)->destination_url.spec());
EXPECT_EQ("http://d/", result.match_at(3)->destination_url.spec());
}
}
TEST_F(AutocompleteResultTest, ShouldHideTopMatch) {
base::FieldTrialList::CreateFieldTrial("InstantExtended",
"Group1 hide_verbatim:1");
ACMatches matches;
// Case 1: Top match is a verbatim match.
PopulateAutocompleteMatchesFromTestData(kVerbatimMatches, 1, &matches);
AutocompleteResult result;
result.AppendMatches(matches);
EXPECT_TRUE(result.ShouldHideTopMatch());
matches.clear();
result.Reset();
// Case 2: If the verbatim first match is followed by another verbatim match,
// don't hide the top verbatim match.
PopulateAutocompleteMatchesFromTestData(kVerbatimMatches,
arraysize(kVerbatimMatches),
&matches);
result.AppendMatches(matches);
EXPECT_FALSE(result.ShouldHideTopMatch());
matches.clear();
result.Reset();
// Case 3: Top match is not a verbatim match. Do not hide the top match.
PopulateAutocompleteMatchesFromTestData(kNonVerbatimMatches, 1, &matches);
PopulateAutocompleteMatchesFromTestData(kVerbatimMatches,
arraysize(kVerbatimMatches),
&matches);
result.AppendMatches(matches);
EXPECT_FALSE(result.ShouldHideTopMatch());
}
TEST_F(AutocompleteResultTest, ShouldHideTopMatchAfterCopy) {
base::FieldTrialList::CreateFieldTrial("InstantExtended",
"Group1 hide_verbatim:1");
ACMatches matches;
// Case 1: Top match is a verbatim match followed by only copied matches.
PopulateAutocompleteMatchesFromTestData(kVerbatimMatches,
arraysize(kVerbatimMatches),
&matches);
for (size_t i = 1; i < arraysize(kVerbatimMatches); ++i)
matches[i].from_previous = true;
AutocompleteResult result;
result.AppendMatches(matches);
EXPECT_TRUE(result.ShouldHideTopMatch());
result.Reset();
// Case 2: The copied matches are then followed by a non-verbatim match.
PopulateAutocompleteMatchesFromTestData(kNonVerbatimMatches, 1, &matches);
result.AppendMatches(matches);
EXPECT_TRUE(result.ShouldHideTopMatch());
result.Reset();
// Case 3: The copied matches are instead followed by a verbatim match.
matches.back().from_previous = true;
PopulateAutocompleteMatchesFromTestData(kVerbatimMatches, 1, &matches);
result.AppendMatches(matches);
EXPECT_FALSE(result.ShouldHideTopMatch());
}
TEST_F(AutocompleteResultTest, DoNotHideTopMatch_FieldTrialFlagDisabled) {
// This test config is identical to ShouldHideTopMatch test ("Case 1") except
// that the "hide_verbatim" flag is disabled in the field trials.
base::FieldTrialList::CreateFieldTrial("InstantExtended",
"Group1 hide_verbatim:0");
ACMatches matches;
PopulateAutocompleteMatchesFromTestData(kVerbatimMatches, 1, &matches);
AutocompleteResult result;
result.AppendMatches(matches);
// Field trial flag "hide_verbatim" is disabled. Do not hide top match.
EXPECT_FALSE(result.ShouldHideTopMatch());
}
TEST_F(AutocompleteResultTest, TopMatchIsStandaloneVerbatimMatch) {
ACMatches matches;
AutocompleteResult result;
result.AppendMatches(matches);
// Case 1: Result set is empty.
EXPECT_FALSE(result.TopMatchIsStandaloneVerbatimMatch());
// Case 2: Top match is not a verbatim match.
PopulateAutocompleteMatchesFromTestData(kNonVerbatimMatches, 1, &matches);
result.AppendMatches(matches);
EXPECT_FALSE(result.TopMatchIsStandaloneVerbatimMatch());
result.Reset();
matches.clear();
// Case 3: Top match is a verbatim match.
PopulateAutocompleteMatchesFromTestData(kVerbatimMatches, 1, &matches);
result.AppendMatches(matches);
EXPECT_TRUE(result.TopMatchIsStandaloneVerbatimMatch());
result.Reset();
matches.clear();
// Case 4: Standalone verbatim match found in AutocompleteResult.
PopulateAutocompleteMatchesFromTestData(kVerbatimMatches, 1, &matches);
PopulateAutocompleteMatchesFromTestData(kNonVerbatimMatches, 1, &matches);
result.AppendMatches(matches);
EXPECT_TRUE(result.TopMatchIsStandaloneVerbatimMatch());
result.Reset();
matches.clear();
// Case 5: Multiple verbatim matches found in AutocompleteResult.
PopulateAutocompleteMatchesFromTestData(kVerbatimMatches,
arraysize(kVerbatimMatches),
&matches);
result.AppendMatches(matches);
EXPECT_FALSE(result.ShouldHideTopMatch());
}
| bsd-3-clause |
seong889/lucida | lucida/speechrecognition/common/src/ivectorbin/ivector-extractor-est.cc | 2293 | // ivectorbin/ivector-extractor-est.cc
// Copyright 2013 Daniel Povey
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "util/common-utils.h"
#include "ivector/ivector-extractor.h"
#include "thread/kaldi-thread.h"
int main(int argc, char *argv[]) {
try {
typedef kaldi::int32 int32;
using namespace kaldi;
const char *usage =
"Do model re-estimation of iVector extractor (this is\n"
"the update phase of a single pass of E-M)\n"
"Usage: ivector-extractor-est [options] <model-in> <stats-in> <model-out>\n";
bool binary = true;
IvectorExtractorEstimationOptions update_opts;
kaldi::ParseOptions po(usage);
po.Register("binary", &binary, "Write output in binary mode");
po.Register("num-threads", &g_num_threads,
"Number of threads used in update");
update_opts.Register(&po);
po.Read(argc, argv);
if (po.NumArgs() != 3) {
po.PrintUsage();
exit(1);
}
std::string model_rxfilename = po.GetArg(1),
stats_rxfilename = po.GetArg(2),
model_wxfilename = po.GetArg(3);
KALDI_LOG << "Reading model";
IvectorExtractor extractor;
ReadKaldiObject(model_rxfilename, &extractor);
KALDI_LOG << "Reading statistics";
IvectorExtractorStats stats;
ReadKaldiObject(stats_rxfilename, &stats);
stats.Update(update_opts, &extractor);
WriteKaldiObject(extractor, model_wxfilename, binary);
KALDI_LOG << "Updated model and wrote it to "
<< model_wxfilename;
return 0;
} catch(const std::exception &e) {
std::cerr << e.what() << '\n';
return -1;
}
}
| bsd-3-clause |
Isaack90/parse-server | src/LiveQuery/ParseWebSocketServer.js | 1091 | import logger from '../logger';
const typeMap = new Map([['disconnect', 'close']]);
export class ParseWebSocketServer {
server: Object;
constructor(server: any, onConnect: Function, websocketTimeout: number = 10 * 1000) {
const WebSocketServer = require('ws').Server;
const wss = new WebSocketServer({ server: server });
wss.on('listening', () => {
logger.info('Parse LiveQuery Server starts running');
});
wss.on('connection', (ws) => {
onConnect(new ParseWebSocket(ws));
// Send ping to client periodically
const pingIntervalId = setInterval(() => {
if (ws.readyState == ws.OPEN) {
ws.ping();
} else {
clearInterval(pingIntervalId);
}
}, websocketTimeout);
});
this.server = wss;
}
}
export class ParseWebSocket {
ws: any;
constructor(ws: any) {
this.ws = ws;
}
on(type: string, callback): void {
const wsType = typeMap.has(type) ? typeMap.get(type) : type;
this.ws.on(wsType, callback);
}
send(message: any): void {
this.ws.send(message);
}
}
| bsd-3-clause |
biocore/tax2tree | t2t/validate.py | 4049 | #!/usr/bin/env python
from collections import defaultdict
from operator import add
from functools import reduce
from t2t.nlevel import (determine_rank_order,
make_consensus_tree,
load_consensus_map)
from t2t.util import unzip
class ParseError(Exception):
pass
def check_parse(line):
"""Make sure the line can parse into (id_, [some,thing])"""
try:
id_, initial = line.strip().split('\t')
except ValueError:
raise ParseError("Unable to split in tab")
parsed = tuple([n.strip() for n in initial.split(";")])
if not len(parsed):
raise ParseError("Line appears to not have a taxonomy")
return (id_, parsed)
def check_n_levels(parsed, n):
"""Make sure there are n levels in parsed"""
if len(parsed) == n:
return True
else:
return False
def find_gap(parsed):
"""Find a gap else -1"""
reduced = [p.split('__')[-1] for p in parsed]
end_found = False
end_idx = -1
for idx, n in enumerate(reduced):
if n and end_found:
break
if not n:
end_found = True
end_idx = idx
return end_idx if end_idx != len(parsed) - 1 else -1
def check_gap(parsed):
return find_gap(parsed) == -1
def check_prefixes(parsed, expected_prefixes):
"""Make sure each rank has the expected prefix"""
for name, prefix in zip(parsed, expected_prefixes):
try:
obs, level_name = name.split('__', 1)
except ValueError:
return False
if obs != prefix:
return False
return True
def cache_tipnames(t):
"""cache tipnames on the internal nodes"""
for n in t.postorder(include_self=True):
if n.is_tip():
n.tip_names = [n.name]
else:
n.tip_names = reduce(add, [c.tip_names for c in n.children])
def get_polyphyletic(cons):
"""get polyphyletic groups and a representative tip"""
tips, taxonstrings = unzip(cons.items())
tree, lookup = make_consensus_tree(taxonstrings, False, tips=tips)
cache_tipnames(tree)
names = {}
for n in tree.non_tips():
if n.name is None:
continue
if (n.name, n.Rank) not in names:
names[(n.name, n.Rank)] = {}
if n.parent is not None:
names[(n.name, n.Rank)][n.parent.name] = n.tip_names[0]
return names
def hierarchy_errors(tax_lines):
"""Get errors in the taxonomy hierarchy"""
conmap = load_consensus_map(tax_lines, False)
names = get_polyphyletic(conmap)
errors = []
for (name, rank), parents in names.iteritems():
if len(parents) > 1:
err = {'Taxon': name, 'Rank': rank, 'Parents': parents}
errors.append(err)
return errors
def flat_errors(tax_lines):
"""Flat file errors"""
inc_prefix = 'Incorrect prefixes'
inc_nlevel = 'Incorrect number of levels'
inc_gap = 'Gaps in taxonomy'
seed_con = tax_lines[0].strip().split('\t')[1]
rank_order = determine_rank_order(seed_con)
nlevels = len(rank_order)
errors = defaultdict(list)
errors_seen = defaultdict(set)
for line in tax_lines:
id_, parsed = check_parse(line)
if not check_prefixes(parsed, rank_order):
if parsed not in errors_seen[inc_prefix]:
errors_seen[inc_prefix].add(parsed)
errors[inc_prefix].append(id_)
if not check_n_levels(parsed, nlevels):
if parsed not in errors_seen[inc_nlevel]:
errors_seen[inc_nlevel].add(parsed)
errors[inc_nlevel].append(id_)
if not check_gap(parsed):
gap_idx = find_gap(parsed)
taxon_following_gap = gap_idx + 1
# another +1 as the slice is exclusive
if parsed[:taxon_following_gap + 1] not in errors_seen[inc_gap]:
errors_seen[inc_gap].add(parsed[:taxon_following_gap + 1])
errors['Gaps in taxonomy'].append(id_)
return errors
| bsd-3-clause |
leifurhauks/grpc | src/python/grpcio/tests/unit/framework/interfaces/base/test_cases.py | 10566 | # Copyright 2015, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
# * Neither the name of Google Inc. nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""Tests of the base interface of RPC Framework."""
from __future__ import division
import logging
import random
import threading
import time
import unittest
from grpc.framework.foundation import logging_pool
from grpc.framework.interfaces.base import base
from grpc.framework.interfaces.base import utilities
from tests.unit.framework.common import test_constants
from tests.unit.framework.interfaces.base import _control
from tests.unit.framework.interfaces.base import test_interfaces
_SYNCHRONICITY_VARIATION = (('Sync', False), ('Async', True))
_EMPTY_OUTCOME_KIND_DICT = {
outcome_kind: 0 for outcome_kind in base.Outcome.Kind}
class _Serialization(test_interfaces.Serialization):
def serialize_request(self, request):
return request + request
def deserialize_request(self, serialized_request):
return serialized_request[:len(serialized_request) // 2]
def serialize_response(self, response):
return response * 3
def deserialize_response(self, serialized_response):
return serialized_response[2 * len(serialized_response) // 3:]
def _advance(quadruples, operator, controller):
try:
for quadruple in quadruples:
operator.advance(
initial_metadata=quadruple[0], payload=quadruple[1],
completion=quadruple[2], allowance=quadruple[3])
except Exception as e: # pylint: disable=broad-except
controller.failed('Exception on advance: %e' % e)
class _Operator(base.Operator):
def __init__(self, controller, on_advance, pool, operator_under_test):
self._condition = threading.Condition()
self._controller = controller
self._on_advance = on_advance
self._pool = pool
self._operator_under_test = operator_under_test
self._pending_advances = []
def set_operator_under_test(self, operator_under_test):
with self._condition:
self._operator_under_test = operator_under_test
pent_advances = self._pending_advances
self._pending_advances = []
pool = self._pool
controller = self._controller
if pool is None:
_advance(pent_advances, operator_under_test, controller)
else:
pool.submit(_advance, pent_advances, operator_under_test, controller)
def advance(
self, initial_metadata=None, payload=None, completion=None,
allowance=None):
on_advance = self._on_advance(
initial_metadata, payload, completion, allowance)
if on_advance.kind is _control.OnAdvance.Kind.ADVANCE:
with self._condition:
pool = self._pool
operator_under_test = self._operator_under_test
controller = self._controller
quadruple = (
on_advance.initial_metadata, on_advance.payload,
on_advance.completion, on_advance.allowance)
if pool is None:
_advance((quadruple,), operator_under_test, controller)
else:
pool.submit(_advance, (quadruple,), operator_under_test, controller)
elif on_advance.kind is _control.OnAdvance.Kind.DEFECT:
raise ValueError(
'Deliberately raised exception from Operator.advance (in a test)!')
class _ProtocolReceiver(base.ProtocolReceiver):
def __init__(self):
self._condition = threading.Condition()
self._contexts = []
def context(self, protocol_context):
with self._condition:
self._contexts.append(protocol_context)
class _Servicer(base.Servicer):
"""A base.Servicer with instrumented for testing."""
def __init__(self, group, method, controllers, pool):
self._condition = threading.Condition()
self._group = group
self._method = method
self._pool = pool
self._controllers = list(controllers)
def service(self, group, method, context, output_operator):
with self._condition:
controller = self._controllers.pop(0)
if group != self._group or method != self._method:
controller.fail(
'%s != %s or %s != %s' % (group, self._group, method, self._method))
raise base.NoSuchMethodError(None, None)
else:
operator = _Operator(
controller, controller.on_service_advance, self._pool,
output_operator)
outcome = context.add_termination_callback(
controller.service_on_termination)
if outcome is not None:
controller.service_on_termination(outcome)
return utilities.full_subscription(operator, _ProtocolReceiver())
class _OperationTest(unittest.TestCase):
def setUp(self):
if self._synchronicity_variation:
self._pool = logging_pool.pool(test_constants.POOL_SIZE)
else:
self._pool = None
self._controller = self._controller_creator.controller(
self._implementation, self._randomness)
def tearDown(self):
if self._synchronicity_variation:
self._pool.shutdown(wait=True)
else:
self._pool = None
def test_operation(self):
invocation = self._controller.invocation()
if invocation.subscription_kind is base.Subscription.Kind.FULL:
test_operator = _Operator(
self._controller, self._controller.on_invocation_advance,
self._pool, None)
subscription = utilities.full_subscription(
test_operator, _ProtocolReceiver())
else:
# TODO(nathaniel): support and test other subscription kinds.
self.fail('Non-full subscriptions not yet supported!')
servicer = _Servicer(
invocation.group, invocation.method, (self._controller,), self._pool)
invocation_end, service_end, memo = self._implementation.instantiate(
{(invocation.group, invocation.method): _Serialization()}, servicer)
try:
invocation_end.start()
service_end.start()
operation_context, operator_under_test = invocation_end.operate(
invocation.group, invocation.method, subscription, invocation.timeout,
initial_metadata=invocation.initial_metadata, payload=invocation.payload,
completion=invocation.completion)
test_operator.set_operator_under_test(operator_under_test)
outcome = operation_context.add_termination_callback(
self._controller.invocation_on_termination)
if outcome is not None:
self._controller.invocation_on_termination(outcome)
except Exception as e: # pylint: disable=broad-except
self._controller.failed('Exception on invocation: %s' % e)
self.fail(e)
while True:
instruction = self._controller.poll()
if instruction.kind is _control.Instruction.Kind.ADVANCE:
try:
test_operator.advance(
*instruction.advance_args, **instruction.advance_kwargs)
except Exception as e: # pylint: disable=broad-except
self._controller.failed('Exception on instructed advance: %s' % e)
elif instruction.kind is _control.Instruction.Kind.CANCEL:
try:
operation_context.cancel()
except Exception as e: # pylint: disable=broad-except
self._controller.failed('Exception on cancel: %s' % e)
elif instruction.kind is _control.Instruction.Kind.CONCLUDE:
break
invocation_stop_event = invocation_end.stop(0)
service_stop_event = service_end.stop(0)
invocation_stop_event.wait()
service_stop_event.wait()
invocation_stats = invocation_end.operation_stats()
service_stats = service_end.operation_stats()
self._implementation.destantiate(memo)
self.assertTrue(
instruction.conclude_success, msg=instruction.conclude_message)
expected_invocation_stats = dict(_EMPTY_OUTCOME_KIND_DICT)
expected_invocation_stats[
instruction.conclude_invocation_outcome_kind] += 1
self.assertDictEqual(expected_invocation_stats, invocation_stats)
expected_service_stats = dict(_EMPTY_OUTCOME_KIND_DICT)
expected_service_stats[instruction.conclude_service_outcome_kind] += 1
self.assertDictEqual(expected_service_stats, service_stats)
def test_cases(implementation):
"""Creates unittest.TestCase classes for a given Base implementation.
Args:
implementation: A test_interfaces.Implementation specifying creation and
destruction of the Base implementation under test.
Returns:
A sequence of subclasses of unittest.TestCase defining tests of the
specified Base layer implementation.
"""
random_seed = hash(time.time())
logging.warning('Random seed for this execution: %s', random_seed)
randomness = random.Random(x=random_seed)
test_case_classes = []
for synchronicity_variation in _SYNCHRONICITY_VARIATION:
for controller_creator in _control.CONTROLLER_CREATORS:
name = ''.join(
(synchronicity_variation[0], controller_creator.name(), 'Test',))
test_case_classes.append(
type(name, (_OperationTest,),
{'_implementation': implementation,
'_randomness': randomness,
'_synchronicity_variation': synchronicity_variation[1],
'_controller_creator': controller_creator,
'__module__': implementation.__module__,
}))
return test_case_classes
| bsd-3-clause |
jaredgary/Bienes | views/tb-bn-gestiones-solicitudes/_form.php | 1126 | <?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\models\TbBnSolicitudDescargo;
use app\models\TbBnEstadoSolicitud;
/* @var $this yii\web\View */
/* @var $model app\models\TbBnGestionesSolicitudes */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="tb-bn-gestiones-solicitudes-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'CodigoSolicitud')->dropDownList(
\yii\helpers\ArrayHelper::map(TbBnSolicitudDescargo::find()->all(),'CodigoSolicitud', 'CodigoSolicitud'),
['prompt' => 'Seleccione el código de la solicitud']
) ?>
<?= $form->field($model, 'CodigoEstado')->dropDownList(
\yii\helpers\ArrayHelper::map(TbBnEstadoSolicitud::find()->all(),'CodigoEstado', 'Estado'),
['prompt' => 'Seleccione el estado de la solicitud']
) ?>
<?= $form->field($model, 'Observaciones')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
| bsd-3-clause |
datamicroscopes/common | bin/perf_group.cpp | 4222 | #include <microscopes/common/random_fwd.hpp>
#include <microscopes/models/distributions.hpp>
#include <microscopes/models/noop.hpp>
#include <microscopes/common/recarray/dataview.hpp>
#include <microscopes/common/timer.hpp>
#include <random>
#include <iostream>
using namespace std;
using namespace distributions;
using namespace microscopes;
using namespace microscopes::common;
using namespace microscopes::common::recarray;
int
main(void)
{
rng_t r(73);
const size_t D = 1000;
// create fake data
bool data[D];
for (size_t i = 0; i < D; i++)
data[i] = bernoulli_distribution(0.5)(r);
vector<runtime_type> types(D, runtime_type(TYPE_B));
row_accessor acc( reinterpret_cast<const uint8_t *>(&data[0]), nullptr, &types);
// no-op pointers
vector<shared_ptr<models::hypers>> noop_shares;
for (size_t i = 0; i < D; i++)
noop_shares.emplace_back(models::noop_model().create_hypers());
vector<shared_ptr<models::group>> noop_groups;
for (const auto &px : noop_shares)
noop_groups.emplace_back(px->create_group(r));
// pointers
vector<shared_ptr<models::hypers>> shares;
for (size_t i = 0; i < D; i++) {
shares.emplace_back(models::distributions_model<BetaBernoulli>().create_hypers());
shares.back()->get_hp_mutator("alpha").set<float>(2.0);
shares.back()->get_hp_mutator("beta").set<float>(2.0);
}
vector<shared_ptr<models::group>> groups;
for (const auto &px : shares)
groups.emplace_back(px->create_group(r));
// all in 1
unique_ptr< models::distributions_hypers<BetaBernoulli> [] > combined_shares(
new models::distributions_hypers<BetaBernoulli> [ D ]);
for (size_t i = 0; i < D; i++) {
combined_shares[i].get_hp_mutator("alpha").set<float>(2.0);
combined_shares[i].get_hp_mutator("beta").set<float>(2.0);
}
unique_ptr< models::distributions_group<BetaBernoulli> []> combined_groups(
new models::distributions_group<BetaBernoulli> [D]);
for (size_t i = 0; i < D; i++)
combined_groups[i].repr_.init(combined_shares[i].repr_, r);
vector< models::hypers * > px_shares;
for (size_t i = 0; i < D; i++)
px_shares.emplace_back(&combined_shares[i]);
vector< models::group * > px_groups;
for (size_t i = 0; i < D; i++)
px_groups.emplace_back(&combined_groups[i]);
const size_t niters = 100000;
float score = 0.;
{
timer tt;
for (size_t n = 0; n < niters; n++) {
acc.reset();
for (size_t i = 0; i < acc.nfeatures(); i++, acc.bump())
noop_groups[i]->add_value(*noop_shares[i], acc.get(), r);
acc.reset();
for (size_t i = 0; i < acc.nfeatures(); i++, acc.bump())
noop_groups[i]->remove_value(*noop_shares[i], acc.get(), r);
acc.reset();
for (size_t i = 0; i < acc.nfeatures(); i++, acc.bump())
score += noop_groups[i]->score_value(*noop_shares[i], acc.get(), r);
}
cout << "sec/iter: " << (tt.lap_ms() / float(niters)) << endl;
cout << "ignore: " << score << endl;
}
{
timer tt;
for (size_t n = 0; n < niters; n++) {
acc.reset();
for (size_t i = 0; i < acc.nfeatures(); i++, acc.bump())
groups[i]->add_value(*shares[i], acc.get(), r);
acc.reset();
for (size_t i = 0; i < acc.nfeatures(); i++, acc.bump())
groups[i]->remove_value(*shares[i], acc.get(), r);
acc.reset();
for (size_t i = 0; i < acc.nfeatures(); i++, acc.bump())
score += groups[i]->score_value(*shares[i], acc.get(), r);
}
cout << "sec/iter: " << (tt.lap_ms() / float(niters)) << endl;
cout << "ignore: " << score << endl;
}
{
timer tt;
for (size_t n = 0; n < niters; n++) {
acc.reset();
for (size_t i = 0; i < acc.nfeatures(); i++, acc.bump())
px_groups[i]->add_value(*px_shares[i], acc.get(), r);
acc.reset();
for (size_t i = 0; i < acc.nfeatures(); i++, acc.bump())
px_groups[i]->remove_value(*px_shares[i], acc.get(), r);
acc.reset();
for (size_t i = 0; i < acc.nfeatures(); i++, acc.bump())
score += px_groups[i]->score_value(*px_shares[i], acc.get(), r);
}
cout << "sec/iter: " << (tt.lap_ms() / float(niters)) << endl;
cout << "ignore: " << score << endl;
}
return 0;
}
| bsd-3-clause |
SerebryanskiySergei/FacultySite | views/call-shedule/create.php | 435 | <?php
use yii\helpers\Html;
/* @var $this yii\web\View */
/* @var $model app\models\CallShedule */
$this->title = 'Create Call Shedule';
$this->params['breadcrumbs'][] = ['label' => 'Call Shedules', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="call-shedule-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
]) ?>
</div>
| bsd-3-clause |
nwjs/chromium.src | media/base/renderer_factory_selector_unittest.cc | 4405 | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include "base/bind.h"
#include "base/macros.h"
#include "media/base/overlay_info.h"
#include "media/base/renderer_factory_selector.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace media {
class RendererFactorySelectorTest : public testing::Test {
public:
class FakeFactory : public RendererFactory {
public:
explicit FakeFactory(RendererType type) : type_(type) {}
std::unique_ptr<Renderer> CreateRenderer(
const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner,
const scoped_refptr<base::TaskRunner>& worker_task_runner,
AudioRendererSink* audio_renderer_sink,
VideoRendererSink* video_renderer_sink,
RequestOverlayInfoCB request_overlay_info_cb,
const gfx::ColorSpace& target_color_space) override {
return nullptr;
}
RendererType factory_type() { return type_; }
private:
RendererType type_;
};
RendererFactorySelectorTest() = default;
RendererFactorySelectorTest(const RendererFactorySelectorTest&) = delete;
RendererFactorySelectorTest& operator=(const RendererFactorySelectorTest&) =
delete;
void AddBaseFactory(RendererType type) {
selector_.AddBaseFactory(type, std::make_unique<FakeFactory>(type));
}
void AddFactory(RendererType type) {
selector_.AddFactory(type, std::make_unique<FakeFactory>(type));
}
void AddConditionalFactory(RendererType type) {
condition_met_map_[type] = false;
selector_.AddConditionalFactory(
type, std::make_unique<FakeFactory>(type),
base::BindRepeating(&RendererFactorySelectorTest::IsConditionMet,
base::Unretained(this), type));
}
RendererType GetCurrentlySelectedRendererType() {
return reinterpret_cast<FakeFactory*>(selector_.GetCurrentFactory())
->factory_type();
}
bool IsConditionMet(RendererType type) {
DCHECK(condition_met_map_.count(type));
return condition_met_map_[type];
}
protected:
RendererFactorySelector selector_;
std::map<RendererType, bool> condition_met_map_;
};
TEST_F(RendererFactorySelectorTest, SingleFactory) {
AddBaseFactory(RendererType::kDefault);
EXPECT_EQ(RendererType::kDefault, GetCurrentlySelectedRendererType());
}
TEST_F(RendererFactorySelectorTest, MultipleFactory) {
AddBaseFactory(RendererType::kDefault);
AddFactory(RendererType::kMojo);
EXPECT_EQ(RendererType::kDefault, GetCurrentlySelectedRendererType());
selector_.SetBaseRendererType(RendererType::kMojo);
EXPECT_EQ(RendererType::kMojo, GetCurrentlySelectedRendererType());
}
TEST_F(RendererFactorySelectorTest, ConditionalFactory) {
AddBaseFactory(RendererType::kDefault);
AddFactory(RendererType::kMojo);
AddConditionalFactory(RendererType::kCourier);
EXPECT_EQ(RendererType::kDefault, GetCurrentlySelectedRendererType());
condition_met_map_[RendererType::kCourier] = true;
EXPECT_EQ(RendererType::kCourier, GetCurrentlySelectedRendererType());
selector_.SetBaseRendererType(RendererType::kMojo);
EXPECT_EQ(RendererType::kCourier, GetCurrentlySelectedRendererType());
condition_met_map_[RendererType::kCourier] = false;
EXPECT_EQ(RendererType::kMojo, GetCurrentlySelectedRendererType());
}
TEST_F(RendererFactorySelectorTest, MultipleConditionalFactories) {
AddBaseFactory(RendererType::kDefault);
AddConditionalFactory(RendererType::kFlinging);
AddConditionalFactory(RendererType::kCourier);
EXPECT_EQ(RendererType::kDefault, GetCurrentlySelectedRendererType());
condition_met_map_[RendererType::kFlinging] = false;
condition_met_map_[RendererType::kCourier] = true;
EXPECT_EQ(RendererType::kCourier, GetCurrentlySelectedRendererType());
condition_met_map_[RendererType::kFlinging] = true;
condition_met_map_[RendererType::kCourier] = false;
EXPECT_EQ(RendererType::kFlinging, GetCurrentlySelectedRendererType());
// It's up to the implementation detail to decide which one to use.
condition_met_map_[RendererType::kFlinging] = true;
condition_met_map_[RendererType::kCourier] = true;
EXPECT_TRUE(GetCurrentlySelectedRendererType() == RendererType::kFlinging ||
GetCurrentlySelectedRendererType() == RendererType::kCourier);
}
} // namespace media
| bsd-3-clause |
FedorSmirnov/apartment_controller | config/application.config.php | 2505 | <?php
return array (
// This should be an array of module namespaces used in the application.
'modules' => array (
'ZfcBase',
'ZfcUser',
'Application',
'Apartment',
'AlbumRest',
'ApartmentRest',
'Album'
)
,
// These are various options for the listeners attached to the ModuleManager
'module_listener_options' => array (
// This should be an array of paths in which modules reside.
// If a string key is provided, the listener will consider that a module
// namespace, the value of that key the specific path to that module's
// Module class.
'module_paths' => array (
'./module',
'./vendor'
),
// An array of paths from which to glob configuration files after
// modules are loaded. These effectively override configuration
// provided by modules themselves. Paths may use GLOB_BRACE notation.
'config_glob_paths' => array (
'config/autoload/{,*.}{global,local}.php'
)
// Whether or not to enable a configuration cache.
// If enabled, the merged configuration will be cached and used in
// subsequent requests.
// 'config_cache_enabled' => $booleanValue,
)
// The key used to create the configuration cache file name.
// 'config_cache_key' => $stringKey,
)
// Whether or not to enable a module class map cache.
// If enabled, creates a module class map cache which will be used
// by in future requests, to reduce the autoloading process.
// 'module_map_cache_enabled' => $booleanValue,
// The key used to create the class map cache file name.
// 'module_map_cache_key' => $stringKey,
// The path in which to cache merged configuration.
// 'cache_dir' => $stringPath,
// Whether or not to enable modules dependency checking.
// Enabled by default, prevents usage of modules that depend on other modules
// that weren't loaded.
// 'check_dependencies' => true,
// Used to create an own service manager. May contain one or more child arrays.
// 'service_listener_options' => array(
// array(
// 'service_manager' => $stringServiceManagerName,
// 'config_key' => $stringConfigKey,
// 'interface' => $stringOptionalInterface,
// 'method' => $stringRequiredMethodName,
// ),
// )
// Initial configuration with which to seed the ServiceManager.
// Should be compatible with Zend\ServiceManager\Config.
// 'service_manager' => array(),
;
| bsd-3-clause |
vtkio/vtk | src/test/java/vtk/web/decorating/components/AggregatedFeedsComponentTest.java | 4561 | /* Copyright (c) 2007, University of Oslo, Norway
* 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 the University of Oslo nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package vtk.web.decorating.components;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import static org.junit.Assert.*;
import vtk.util.cache.ContentCacheLoader;
import vtk.web.decorating.components.AggregatedFeedsComponent.MissingPublishedDateException;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import org.junit.Test;
public class AggregatedFeedsComponentTest {
@SuppressWarnings("unchecked")
@Test
public void sorting() throws Exception {
List<SyndEntry> entries = new FeedLoader().load("feed1.xml").getEntries();
AggregatedFeedsComponent component = new AggregatedFeedsComponent();
component.sort(entries);
assertEquals("Newest", entries.get(0).getTitle());
assertEquals("Oldest", entries.get(1).getTitle());
}
@SuppressWarnings("unchecked")
@Test
public void missingPubDate() throws Exception {
List<SyndEntry> entries = new FeedLoader().load("missingPubDate.xml").getEntries();
AggregatedFeedsComponent component = new AggregatedFeedsComponent();
try {
component.sort(entries);
fail("Should fail on missing published date");
} catch (MissingPublishedDateException e) {
assertEquals("Missing", e.getEntry().getTitle());
}
}
private class FeedLoader implements ContentCacheLoader<String, SyndFeed> {
@Override
public SyndFeed load(String identifier) throws Exception {
return getFeed(getClass().getResourceAsStream(identifier));
}
private SyndFeed getFeed(InputStream stream) throws IOException, IllegalArgumentException, FeedException {
XmlReader xmlReader = new XmlReader(stream);
SyndFeedInput input = new SyndFeedInput();
return input.build(xmlReader);
}
}
// private void run(String[] urlArray) {
//
// List<SyndEntry> entries = new ArrayList<SyndEntry>();
// Map<SyndEntry, SyndFeed> feedMapping = new HashMap<SyndEntry, SyndFeed>();
//
// ContentCache cache = new ContentCache();
// cache.setName("lala");
// cache.setCacheLoader(new FeedLoader());
// cache.afterPropertiesSet();
// AggregatedFeedsComponent component = new AggregatedFeedsComponent();
// component.setContentCache(cache);
// component.parseFeeds(null, entries, feedMapping, urlArray);
// component.sort(entries);
// write(entries, feedMapping);
// }
// private void write(List<SyndEntry> entries, Map<SyndEntry, SyndFeed> feedMapping) {
// for (SyndEntry entry : entries) {
// System.out.println(entry.getPublishedDate() + " " + feedMapping.get(entry).getTitle());
// }
//
// }
}
| bsd-3-clause |
JianpingZeng/xcc | xcc/test/juliet/testcases/CWE127_Buffer_Underread/s02/CWE127_Buffer_Underread__malloc_char_memcpy_81a.cpp | 2794 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE127_Buffer_Underread__malloc_char_memcpy_81a.cpp
Label Definition File: CWE127_Buffer_Underread__malloc.label.xml
Template File: sources-sink-81a.tmpl.cpp
*/
/*
* @description
* CWE: 127 Buffer Under-read
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sinks: memcpy
* BadSink : Copy data to string using memcpy
* Flow Variant: 81 Data flow: data passed in a parameter to an virtual method called via a reference
*
* */
#include "std_testcase.h"
#include "CWE127_Buffer_Underread__malloc_char_memcpy_81.h"
namespace CWE127_Buffer_Underread__malloc_char_memcpy_81
{
#ifndef OMITBAD
void bad()
{
char * data;
data = NULL;
{
char * dataBuffer = (char *)malloc(100*sizeof(char));
if (dataBuffer == NULL) {exit(-1);}
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FLAW: Set data pointer to before the allocated memory buffer */
data = dataBuffer - 8;
}
const CWE127_Buffer_Underread__malloc_char_memcpy_81_base& baseObject = CWE127_Buffer_Underread__malloc_char_memcpy_81_bad();
baseObject.action(data);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
data = NULL;
{
char * dataBuffer = (char *)malloc(100*sizeof(char));
if (dataBuffer == NULL) {exit(-1);}
memset(dataBuffer, 'A', 100-1);
dataBuffer[100-1] = '\0';
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
}
const CWE127_Buffer_Underread__malloc_char_memcpy_81_base& baseObject = CWE127_Buffer_Underread__malloc_char_memcpy_81_goodG2B();
baseObject.action(data);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace CWE127_Buffer_Underread__malloc_char_memcpy_81; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| bsd-3-clause |
hughsons/saltwaterfish | auth_views.py | 7433 | from django.contrib.auth import *
from django.http import *
from forms import *
from django.template.loader import get_template
from django.template import Context
from django.utils.decorators import method_decorator
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required
from django.views.generic.base import TemplateView, View
from django.views.decorators.csrf import csrf_exempt
import logging, random, hashlib, datetime
from models import *
from django.core.context_processors import csrf
def GetRecaptcha(request):
value = random.randrange(10000, 99999, 1)
request.session['ReCaptcha'] = value
return value
@csrf_exempt
def CustomerLoginClassold(request):
if request.method == 'POST':
if 'target' in request.POST:
target_page = request.POST['target']
else:
target_page = "/myaccount"
#logout(request)
customer_list=""
form = LoginForm(request.POST)
if form.is_valid():
logging.info('Form Is clean')
email = form.cleaned_data['username']
password = form.cleaned_data['password']
if form.cleaned_data['recaptcha'] == str(request.session['ReCaptcha']):
customer_list = customers.objects.filter(email = email,
pass_field= password, custenabled=1)
if customer_list:
t = customers.objects.get(email = email,
pass_field= password, custenabled=1)
t.lastlogindate = datetime.datetime.now()
t.save()
request.session['IsLogin'] = True
request.session['Customer'] = customer_list[0]
success = True
logging.info('LoginfoMessage:: %s',customer_list[0])
return HttpResponseRedirect(target_page)
else:
request.session['ErrorMessage'] = "Invalid User name or Password."
return HttpResponseRedirect('/login#forget')
else:
request.session['ErrorMessage'] = "Recaptcha is not matched."
return HttpResponseRedirect('/login')
else:
request.session['ErrorMessage'] = "Invalid Form data."
return HttpResponseRedirect('/login#forget')
else:
request.session['ErrorMessage'] = "Form submission is not as expected."
return HttpResponseRedirect('/login#forget')
@csrf_exempt
def CustomerLoginClass(request):
if request.method == 'POST':
if 'target' in request.POST:
target_page = request.POST['target']
else:
target_page = "/myaccount"
#logout(request)
customer_list=""
form = LoginForm(request.POST)
if form.is_valid():
logging.info('Form Is clean')
email = form.cleaned_data['username']
password = form.cleaned_data['password']
customer_list = customers.objects.filter(email = email,
pass_field= password, custenabled=1)
if customer_list:
t = customers.objects.get(email = email,
pass_field= password, custenabled=1)
t.lastlogindate = datetime.datetime.now()
t.save()
request.session['IsLogin'] = True
request.session['Customer'] = customer_list[0]
success = True
logging.info('LoginfoMessage:: %s',customer_list[0])
return HttpResponseRedirect(target_page)
else:
request.session['ErrorMessage'] = "Invalid User name or Password."
return HttpResponseRedirect('/login#forget')
else:
request.session['ErrorMessage'] = "Invalid Form data."
return HttpResponseRedirect('/login#forget')
else:
request.session['ErrorMessage'] = "Form submission is not as expected."
return HttpResponseRedirect('/login#forget')
@csrf_exempt
def AdminLoginClass(request):
if request.method == 'POST':
logout(request)
customer_list=""
form = LoginForm(request.POST)
if form.is_valid():
logging.info('Form Is clean')
username = form.cleaned_data['username']
password = form.cleaned_data['password']
staff_list = Admins.objects.filter(username = username,
pass_field= hashlib.md5(password).hexdigest())
if staff_list:
t = Admins.objects.get(username = username,
pass_field= hashlib.md5(password).hexdigest())
t.lastlogin = datetime.datetime.now()
t.save()
request.session['IsLogin'] = True
request.session['Staff_username'] = username
request.session['Staff_password'] = password
request.session['Staff'] = staff_list[0]
success = True
logging.info('LoginfoMessage:: %s',request.session['Staff_password'])
return HttpResponseRedirect('/apanel')
else:
return HttpResponseRedirect('/alogin')
else:
return HttpResponseRedirect('/alogin')
else:
return HttpResponseRedirect('/alogin')
@csrf_exempt
def loginpage(request):
state = "Please log in below..."
t = get_template('login.htm')
recaptcha = "https://chart.googleapis.com/chart?chst=d_text_outline&chld=FFCC33|16|h|FF0000|b|%s" %GetRecaptcha(request)
#recaptcha2 = "https://chart.googleapis.com/chart?chst=d_text_outline&chld=FFCC33|16|h|FF0000|b|%s" %GetRecaptcha(request)
default_message = ""
error_message1, error_message2 = "", ""
#logging.info('Fetch Started:: %s', request.session["ErrorMessage"])
if 'message' in request.GET:
default_message = request.GET['message']
#if 'error' in request.GET:
# error_message = request.GET['error']
error_message = ""
if "ErrorMessage" in request.session:
error_message1 = request.session["ErrorMessage"]
del request.session["ErrorMessage"]
if "ErrorMessage2" in request.session:
error_message2 = request.session["ErrorMessage2"]
del request.session["ErrorMessage2"]
c = Context({
'title': "SaltwaterFish :: Login",
'form': LoginForm(),
'forgotform':ForgetPwdForm,
'recaptcha':recaptcha,
'recaptcha2':recaptcha,
'message2': default_message,
'error_message1': error_message1,
'error_message2': error_message2
})
c.update(csrf(request))
return HttpResponse(t.render(c))
def Adminloginpage(request):
state = "Please log in below..."
t = get_template('admin_login.htm')
recaptcha = "https://chart.googleapis.com/chart?chst=d_text_outline&chld=FFCC33|16|h|FF0000|b|%s" %GetRecaptcha(request)
c = Context({
'title': "Adminstration Area",
'form': LoginForm(),
})
return HttpResponse(t.render(c))
def logout_view(request):
if "CartItems" in request.session:
del request.session["CartItems"]
logout(request)
return HttpResponseRedirect('/login')
| bsd-3-clause |
krishagni/openspecimen | www/app/modules/administrative/shipment/detail.js | 341 | angular.module('os.administrative.shipment.detail', ['os.administrative.models'])
.controller('ShipmentDetailCtrl', function($scope, shipment, Util) {
function init() {
$scope.shipment = shipment;
}
$scope.downloadReport = function() {
Util.downloadReport(shipment, 'shipments');
}
init();
});
| bsd-3-clause |
graczyk/tumblrmash | test.py | 3252 | import pytumblr
import json
import random
import copy
from flask_oauth import OAuth
from flask import *
app = Flask(__name__)
setupdone = False
app.secret_key = 'people who think they know everything really like lisp'
oauth = OAuth()
credentials = json.loads(open('tumblr_credentials.json', 'r').read())
tumblr = oauth.remote_app('tumblr',
base_url='api.tumblr.com/v2',
request_token_url='http://www.tumblr.com/oauth/request_token',
access_token_url='http://www.tumblr.com/oauth/access_token',
authorize_url='http://www.tumblr.com/oauth/authorize',
consumer_key=credentials["consumer_key"],
consumer_secret=credentials["consumer_secret"]
)
@app.route('/top')
def total():
if 'tumblr_token' not in session:
return render_template("login.html")
dict2 = {}
dict2 = copy.deepcopy(pics)
for x in dict2.keys():
if dict2[x] == 0:
del dict2[x]
newlist = sorted(dict2.items(), key=lambda x: x[1]) #this is neat
return render_template("top.html", pics=reversed(newlist))
@app.route('/contact')
def contact():
#do something with this later, probably a github link
return render_template("contact.html")
@app.route('/update', methods=['GET', 'POST'])
def update():
if request.method == 'POST':
pics[request.form["action"]] += 1
return mash()
@app.route('/')
def mash():
if 'tumblr_token' not in session:
return render_template("login.html")
if not setupdone:
setup()
pic1 = random.choice(pics.keys())
pic2 = random.choice(pics.keys())
return render_template("hello.html", pic1 = pic1, pic2 = pic2)
def setup():
client = pytumblr.TumblrRestClient(credentials["consumer_key"], credentials["consumer_secret"], session["tumblr_token"][0], session["tumblr_token"][1])
following = client.following()
#create list of blogs, put in list
blogs = following["blogs"]
tosearch = []
for blog in blogs:
tosearch.append(blog["url"])
#create dictionary with original picture URLs and set the count to 0
global pics #this is awful
pics = {}
for blog in tosearch:
resp = client.posts(blog[7:].rstrip('/'), type='photo', tag='me')
for post in resp["posts"]:
for orig in post["photos"]:
pics[orig["original_size"]["url"]] = 0
global setupdone
setupdone = True
@app.route('/login', methods=['GET','POST'])
def login():
if session.has_key('tumblr_token'):
session.pop('tumblr_token', None)
return tumblr.authorize(callback=url_for('oauth_authorized',
next=request.args.get('next') or request.referrer or None))
@app.route('/logout')
def logout():
session.pop('tumblr_token', None)
global setupdone
setupdone = False
return redirect(url_for('mash'))
#i'm really not entirely sure why i need this
@tumblr.tokengetter
def get_token():
return session.get('tumblr_token')
@app.route('/oauth-authorized')
@tumblr.authorized_handler
def oauth_authorized(resp):
session['tumblr_token'] = (
resp['oauth_token'],
resp['oauth_token_secret']
)
return redirect(url_for('mash'))
if __name__ == '__main__':
app.run(debug=True)
| bsd-3-clause |
goddardl/gander | src/GanderTest/CommonTest.cpp | 3085 | //////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2013, Luke Goddard. 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 Luke Goddard nor the names of any
// other contributors to this software may be used to endorse or
// promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <cstdlib>
#include "Gander/Common.h"
#include "GanderTest/CommonTest.h"
#include "boost/test/floating_point_comparison.hpp"
#include "boost/test/test_tools.hpp"
using namespace Gander;
using namespace Gander::Test;
using namespace boost;
using namespace boost::unit_test;
namespace Gander
{
namespace Test
{
struct CommonTest
{
void testDataTypeSizes()
{
BOOST_CHECK_EQUAL( int( 1 ), int( sizeof( int8 ) ) );
BOOST_CHECK_EQUAL( int( 1 ), int( sizeof( int8u ) ) );
BOOST_CHECK_EQUAL( int( 2 ), int( sizeof( int16 ) ) );
BOOST_CHECK_EQUAL( int( 2 ), int( sizeof( int16u ) ) );
BOOST_CHECK_EQUAL( int( 4 ), int( sizeof( int32 ) ) );
BOOST_CHECK_EQUAL( int( 4 ), int( sizeof( int32u ) ) );
BOOST_CHECK_EQUAL( int( 8 ), int( sizeof( int64 ) ) );
BOOST_CHECK_EQUAL( int( 8 ), int( sizeof( int64u ) ) );
}
};
struct CommonTestSuite : public boost::unit_test::test_suite
{
CommonTestSuite() : boost::unit_test::test_suite( "CommonTestSuite" )
{
boost::shared_ptr<CommonTest> instance( new CommonTest() );
add( BOOST_CLASS_TEST_CASE( &CommonTest::testDataTypeSizes, instance ) );
}
};
void addCommonTest( boost::unit_test::test_suite *test )
{
test->add( new CommonTestSuite( ) );
}
} // namespace ImageTest
} // namespace Gander
| bsd-3-clause |
nusmql/bwp | frontend/controllers/SiteController.php | 5572 | <?php
namespace frontend\controllers;
use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use frontend\components\AuthHandler;
/**
* Site controller
*/
class SiteController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout', 'signup'],
'rules' => [
[
'actions' => ['signup'],
'allow' => true,
'roles' => ['?'],
],
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
/**
* @inheritdoc
*/
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
'auth' => [
'class' => 'yii\authclient\AuthAction',
'successCallback' => [$this, 'onAuthSuccess'],
],
];
}
/**
* Displays homepage.
*
* @return mixed
*/
public function actionIndex()
{
return $this->render('index');
}
/**
* Logs in a user.
*
* @return mixed
*/
public function actionLogin()
{
if (!Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm();
if ($model->load(Yii::$app->request->post()) && $model->login()) {
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
/**
* Logs out the current user.
*
* @return mixed
*/
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
/**
* Displays contact page.
*
* @return mixed
*/
public function actionContact()
{
$model = new ContactForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
} else {
Yii::$app->session->setFlash('error', 'There was an error sending your message.');
}
return $this->refresh();
} else {
return $this->render('contact', [
'model' => $model,
]);
}
}
/**
* Displays about page.
*
* @return mixed
*/
public function actionAbout()
{
return $this->render('about');
}
/**
* Signs user up.
*
* @return mixed
*/
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
/**
* Requests password reset.
*
* @return mixed
*/
public function actionRequestPasswordReset()
{
$model = new PasswordResetRequestForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
if ($model->sendEmail()) {
Yii::$app->session->setFlash('success', 'Check your email for further instructions.');
return $this->goHome();
} else {
Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for the provided email address.');
}
}
return $this->render('requestPasswordResetToken', [
'model' => $model,
]);
}
/**
* Resets password.
*
* @param string $token
* @return mixed
* @throws BadRequestHttpException
*/
public function actionResetPassword($token)
{
try {
$model = new ResetPasswordForm($token);
} catch (InvalidParamException $e) {
throw new BadRequestHttpException($e->getMessage());
}
if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
Yii::$app->session->setFlash('success', 'New password saved.');
return $this->goHome();
}
return $this->render('resetPassword', [
'model' => $model,
]);
}
public function onAuthSuccess($client)
{
(new AuthHandler($client))->handle();
}
}
| bsd-3-clause |
WaveBlocks/WaveBlocks | testsuite/basic_diagonal/test_quartic_oscillator_two_fourier.py | 431 | algorithm = "fourier"
potential = {}
potential["potential"] = [["1/4 * sigma * x**4", 0 ],
[0 , "1/4 * sigma * x**4"]]
potential["defaults"] = {"sigma":"0.05"}
T = 6
dt = 0.01
eps = 0.1
f = 3.0
ngn = 4096
basis_size = 64
P = 2.0j
Q = 0.5
S = 0.0
parameters = [ (P, Q, S, -0.5, 2.0), (P, Q, S, -0.5, 2.0) ]
coefficients = [[(0, 1.0)], [(0, 1.0)]]
write_nth = 2
| bsd-3-clause |
rust-lang/rust-bindgen | tests/expectations/tests/issue-739-pointer-wide-bitfield.rs | 5946 | #![allow(
dead_code,
non_snake_case,
non_camel_case_types,
non_upper_case_globals
)]
#[repr(C)]
#[derive(Copy, Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct __BindgenBitfieldUnit<Storage> {
storage: Storage,
}
impl<Storage> __BindgenBitfieldUnit<Storage> {
#[inline]
pub const fn new(storage: Storage) -> Self {
Self { storage }
}
}
impl<Storage> __BindgenBitfieldUnit<Storage>
where
Storage: AsRef<[u8]> + AsMut<[u8]>,
{
#[inline]
pub fn get_bit(&self, index: usize) -> bool {
debug_assert!(index / 8 < self.storage.as_ref().len());
let byte_index = index / 8;
let byte = self.storage.as_ref()[byte_index];
let bit_index = if cfg!(target_endian = "big") {
7 - (index % 8)
} else {
index % 8
};
let mask = 1 << bit_index;
byte & mask == mask
}
#[inline]
pub fn set_bit(&mut self, index: usize, val: bool) {
debug_assert!(index / 8 < self.storage.as_ref().len());
let byte_index = index / 8;
let byte = &mut self.storage.as_mut()[byte_index];
let bit_index = if cfg!(target_endian = "big") {
7 - (index % 8)
} else {
index % 8
};
let mask = 1 << bit_index;
if val {
*byte |= mask;
} else {
*byte &= !mask;
}
}
#[inline]
pub fn get(&self, bit_offset: usize, bit_width: u8) -> u64 {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().len());
debug_assert!(
(bit_offset + (bit_width as usize)) / 8 <=
self.storage.as_ref().len()
);
let mut val = 0;
for i in 0..(bit_width as usize) {
if self.get_bit(i + bit_offset) {
let index = if cfg!(target_endian = "big") {
bit_width as usize - 1 - i
} else {
i
};
val |= 1 << index;
}
}
val
}
#[inline]
pub fn set(&mut self, bit_offset: usize, bit_width: u8, val: u64) {
debug_assert!(bit_width <= 64);
debug_assert!(bit_offset / 8 < self.storage.as_ref().len());
debug_assert!(
(bit_offset + (bit_width as usize)) / 8 <=
self.storage.as_ref().len()
);
for i in 0..(bit_width as usize) {
let mask = 1 << i;
let val_bit_is_set = val & mask == mask;
let index = if cfg!(target_endian = "big") {
bit_width as usize - 1 - i
} else {
i
};
self.set_bit(index + bit_offset, val_bit_is_set);
}
}
}
#[repr(C)]
#[repr(align(8))]
#[derive(Debug, Default, Copy, Clone)]
pub struct Foo {
pub _bitfield_align_1: [u64; 0],
pub _bitfield_1: __BindgenBitfieldUnit<[u8; 32usize]>,
}
#[test]
fn bindgen_test_layout_Foo() {
assert_eq!(
::std::mem::size_of::<Foo>(),
32usize,
concat!("Size of: ", stringify!(Foo))
);
assert_eq!(
::std::mem::align_of::<Foo>(),
8usize,
concat!("Alignment of ", stringify!(Foo))
);
}
impl Foo {
#[inline]
pub fn m_bitfield(&self) -> ::std::os::raw::c_ulong {
unsafe {
::std::mem::transmute(self._bitfield_1.get(0usize, 64u8) as u64)
}
}
#[inline]
pub fn set_m_bitfield(&mut self, val: ::std::os::raw::c_ulong) {
unsafe {
let val: u64 = ::std::mem::transmute(val);
self._bitfield_1.set(0usize, 64u8, val as u64)
}
}
#[inline]
pub fn m_bar(&self) -> ::std::os::raw::c_ulong {
unsafe {
::std::mem::transmute(self._bitfield_1.get(64usize, 64u8) as u64)
}
}
#[inline]
pub fn set_m_bar(&mut self, val: ::std::os::raw::c_ulong) {
unsafe {
let val: u64 = ::std::mem::transmute(val);
self._bitfield_1.set(64usize, 64u8, val as u64)
}
}
#[inline]
pub fn foo(&self) -> ::std::os::raw::c_ulong {
unsafe {
::std::mem::transmute(self._bitfield_1.get(128usize, 1u8) as u64)
}
}
#[inline]
pub fn set_foo(&mut self, val: ::std::os::raw::c_ulong) {
unsafe {
let val: u64 = ::std::mem::transmute(val);
self._bitfield_1.set(128usize, 1u8, val as u64)
}
}
#[inline]
pub fn bar(&self) -> ::std::os::raw::c_ulong {
unsafe {
::std::mem::transmute(self._bitfield_1.get(192usize, 64u8) as u64)
}
}
#[inline]
pub fn set_bar(&mut self, val: ::std::os::raw::c_ulong) {
unsafe {
let val: u64 = ::std::mem::transmute(val);
self._bitfield_1.set(192usize, 64u8, val as u64)
}
}
#[inline]
pub fn new_bitfield_1(
m_bitfield: ::std::os::raw::c_ulong,
m_bar: ::std::os::raw::c_ulong,
foo: ::std::os::raw::c_ulong,
bar: ::std::os::raw::c_ulong,
) -> __BindgenBitfieldUnit<[u8; 32usize]> {
let mut __bindgen_bitfield_unit: __BindgenBitfieldUnit<[u8; 32usize]> =
Default::default();
__bindgen_bitfield_unit.set(0usize, 64u8, {
let m_bitfield: u64 = unsafe { ::std::mem::transmute(m_bitfield) };
m_bitfield as u64
});
__bindgen_bitfield_unit.set(64usize, 64u8, {
let m_bar: u64 = unsafe { ::std::mem::transmute(m_bar) };
m_bar as u64
});
__bindgen_bitfield_unit.set(128usize, 1u8, {
let foo: u64 = unsafe { ::std::mem::transmute(foo) };
foo as u64
});
__bindgen_bitfield_unit.set(192usize, 64u8, {
let bar: u64 = unsafe { ::std::mem::transmute(bar) };
bar as u64
});
__bindgen_bitfield_unit
}
}
| bsd-3-clause |
naohisas/KVS | Source/Core/FileFormat/BDML/MeasurementTag.cpp | 1364 | /*****************************************************************************/
/**
* @file MeasurementTag.cpp
* @author Naohisa Sakamoto
*/
/*****************************************************************************/
#include "MeasurementTag.h"
#include "XML.h"
namespace kvs
{
namespace bdml
{
MeasurementTag::MeasurementTag():
Tag("measurement")
{
m_objectRef = "";
}
void MeasurementTag::print( std::ostream& os, const kvs::Indent& indent ) const
{
os << indent << "Object ref.: " << m_objectRef << std::endl;
if ( m_line.exists() )
{
os << indent << "Line entity:" << std::endl;
m_line.print( os, indent.nextIndent() );
}
if ( m_property.exists() )
{
os << indent << "Property:" << std::endl;
m_property.print( os, indent.nextIndent() );
}
}
bool MeasurementTag::read( const Node* parent )
{
if ( !Tag::read( parent ) ) { return false; }
Tag objectRef_tag("objectRef");
if ( objectRef_tag.read( this->node() ) ) { m_objectRef = NodeValue<std::string>( objectRef_tag.node() ); }
if ( m_line.exists( this->node() ) ) { if ( !m_line.read( this->node() ) ) { return false; } }
if ( m_property.exists( this->node() ) ) { if ( !m_property.read( this->node() ) ) { return false; } }
return true;
}
} // end of namespace bdml
} // end of namespace kvs
| bsd-3-clause |
AqlaSolutions/JustLogic | Assets/JustLogicUnits/Generated/GUI/Event/JLGUIEventGetDelta.cs | 2179 | /*
This file is a part of JustLogic product which is distributed under
the BSD 3-clause "New" or "Revised" License
Copyright (c) 2015. All rights reserved.
Authors: Vladyslav Taranov.
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 JustLogic 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.
*/
using JustLogic.Core;
using System.Collections.Generic;
using UnityEngine;
[UnitMenu("GUI/Event/Get Delta")]
[UnitFriendlyName("GUIEvent.Get Delta")]
[UnitUsage(typeof(Vector2), HideExpressionInActionsList = true)]
public class JLGUIEventGetDelta : JLExpression
{
[Parameter(ExpressionType = typeof(Event))]
public JLExpression OperandValue;
public override object GetAnyResult(IExecutionContext context)
{
Event opValue = OperandValue.GetResult<Event>(context);
return opValue.delta;
}
}
| bsd-3-clause |
jfterpstra/bluebottle | bluebottle/recurring_donations/mails.py | 1426 | from babel.dates import format_date
from babel.numbers import format_currency
from django.utils import translation
from django.utils.translation import ugettext_lazy as _
from bluebottle.utils.email_backend import send_mail
from tenant_extras.utils import TenantLanguage
def mail_monthly_donation_processed_notification(monthly_order):
cur_language = translation.get_language()
receiver = monthly_order.user
with TenantLanguage(receiver.primary_language):
subject = _("Thank you for your monthly support")
translation.activate(cur_language)
send_mail(
template_name='recurring_donations/mails/monthly_donation.mail',
subject=subject,
to=receiver,
order=monthly_order,
receiver_first_name=receiver.first_name.capitalize(),
link='/go/projects',
date=format_date(locale='nl_NL'),
amount=format_currency(monthly_order.amount, 'EUR', locale='nl_NL')
)
def mail_project_funded_monthly_donor_notification(receiver, project):
with TenantLanguage(receiver.primary_language):
subject = _("Congratulations: project completed!")
send_mail(
template_name='recurring_donations/mails/project_full_monthly_donor.mail',
subject=subject,
receiver_first_name=receiver.first_name.capitalize(),
to=receiver,
project=project,
link='/go/projects/{0}'.format(project.slug)
)
| bsd-3-clause |
AsenNikolov80/magnet | views/site/_delete-place.php | 314 | <?php
/**
* Created by PhpStorm.
* User: Asen
* Date: 25.11.2016 г.
* Time: 23:13
*/
/* @var $place \app\models\Place */
?>
Сигурни ли сте, че искате да премахнете обекта <strong><?= $place->name ?></strong>?
<input type="hidden" id="placeId" value="<?= $place->id ?>">
| bsd-3-clause |
colour-science/colour-hdri | colour_hdri/plotting/tonemapping.py | 2790 | # -*- coding: utf-8 -*-
"""
Tonemapping Operators Plotting
==============================
Defines the tonemapping operators plotting objects:
- :func:`colour_hdri.plotting.plot_tonemapping_operator_image`
"""
import matplotlib
import matplotlib.ticker
import numpy as np
from colour.plotting import (
CONSTANTS_COLOUR_STYLE,
artist,
override_style,
render,
)
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2015-2021 - Colour Developers'
__license__ = 'New BSD License - https://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = 'Colour Developers'
__email__ = 'colour-developers@colour-science.org'
__status__ = 'Production'
__all__ = [
'plot_tonemapping_operator_image',
]
@override_style()
def plot_tonemapping_operator_image(
image,
luminance_function,
log_scale=False,
cctf_encoding=CONSTANTS_COLOUR_STYLE.colour.colourspace.cctf_encoding,
**kwargs):
"""
Plots given tonemapped image with superimposed luminance mapping function.
Parameters
----------
image : array_like
Tonemapped image to plot.
luminance_function : callable
Luminance mapping function.
log_scale : bool, optional
Use a log scale for plotting the luminance mapping function.
cctf_encoding : callable, optional
Encoding colour component transfer function / opto-electronic
transfer function used for plotting.
Other Parameters
----------------
\\**kwargs : dict, optional
{:func:`colour.plotting.render`},
Please refer to the documentation of the previously listed definition.
Returns
-------
tuple
Current figure and axes.
"""
settings = {'uniform': True}
settings.update(kwargs)
figure, axes = artist(**settings)
shape = image.shape
bounding_box = [0, 1, 0, 1]
image = np.clip(cctf_encoding(image), 0, 1)
axes.imshow(
image,
aspect=shape[0] / shape[1],
extent=bounding_box,
interpolation='nearest')
axes.plot(
np.linspace(0, 1, len(luminance_function)),
luminance_function,
color='red')
settings = {
'axes': axes,
'bounding_box': bounding_box,
'x_ticker': True,
'y_ticker': True,
'x_label': 'Input Luminance',
'y_label': 'Output Luminance',
}
settings.update(kwargs)
if log_scale:
settings.update({
'x_label': '$log_2$ Input Luminance',
'x_ticker_locator': matplotlib.ticker.AutoMinorLocator(0.5)
})
matplotlib.pyplot.gca().set_xscale('log', basex=2)
matplotlib.pyplot.gca().xaxis.set_major_formatter(
matplotlib.ticker.ScalarFormatter())
return render(**settings)
| bsd-3-clause |
endlessm/chromium-browser | chromecast/media/audio/capture_service/capture_service_receiver.cc | 9246 | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chromecast/media/audio/capture_service/capture_service_receiver.h"
#include <memory>
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/message_loop/message_pump_type.h"
#include "base/synchronization/waitable_event.h"
#include "base/threading/sequenced_task_runner_handle.h"
#include "chromecast/media/audio/capture_service/constants.h"
#include "chromecast/media/audio/capture_service/message_parsing_utils.h"
#include "chromecast/media/audio/mixer_service/audio_socket_service.h"
#include "chromecast/net/small_message_socket.h"
#include "media/base/limits.h"
#include "net/base/io_buffer.h"
#include "net/socket/stream_socket.h"
// Helper macro to post tasks to the io thread. It is safe to use unretained
// |this|, since |this| owns the thread.
#define ENSURE_ON_IO_THREAD(method, ...) \
if (!task_runner_->RunsTasksInCurrentSequence()) { \
task_runner_->PostTask( \
FROM_HERE, base::BindOnce(&CaptureServiceReceiver::method, \
base::Unretained(this), ##__VA_ARGS__)); \
return; \
}
namespace chromecast {
namespace media {
class CaptureServiceReceiver::Socket : public SmallMessageSocket::Delegate {
public:
Socket(std::unique_ptr<net::StreamSocket> socket,
capture_service::StreamType stream_type,
int sample_rate,
int channels,
int frames_per_buffer,
::media::AudioInputStream::AudioInputCallback* input_callback);
~Socket() override;
private:
// SmallMessageSocket::Delegate implementation:
void OnSendUnblocked() override;
void OnError(int error) override;
void OnEndOfStream() override;
bool OnMessage(char* data, size_t size) override;
bool SendRequest();
void OnInactivityTimeout();
bool HandleAudio(int64_t timestamp);
void ReportErrorAndStop();
SmallMessageSocket socket_;
const capture_service::StreamType stream_type_;
const int sample_rate_;
const std::unique_ptr<::media::AudioBus> audio_bus_;
::media::AudioInputStream::AudioInputCallback* input_callback_;
scoped_refptr<net::IOBufferWithSize> buffer_;
DISALLOW_COPY_AND_ASSIGN(Socket);
};
CaptureServiceReceiver::Socket::Socket(
std::unique_ptr<net::StreamSocket> socket,
capture_service::StreamType stream_type,
int sample_rate,
int channels,
int frames_per_buffer,
::media::AudioInputStream::AudioInputCallback* input_callback)
: socket_(this, std::move(socket)),
stream_type_(stream_type),
sample_rate_(sample_rate),
audio_bus_(::media::AudioBus::Create(channels, frames_per_buffer)),
input_callback_(input_callback) {
DCHECK(input_callback_);
if (!SendRequest()) {
ReportErrorAndStop();
return;
}
socket_.ReceiveMessages();
}
CaptureServiceReceiver::Socket::~Socket() = default;
bool CaptureServiceReceiver::Socket::SendRequest() {
capture_service::PacketInfo info;
info.message_type = capture_service::MessageType::kAck;
info.stream_info.stream_type = stream_type_;
info.stream_info.sample_rate = sample_rate_;
info.stream_info.num_channels = audio_bus_->channels();
info.stream_info.frames_per_buffer = audio_bus_->frames();
// Format and timestamp doesn't matter in the request.
info.stream_info.sample_format = capture_service::SampleFormat::LAST_FORMAT;
info.timestamp_us = 0;
buffer_ =
capture_service::MakeMessage(info, nullptr /* data */, 0 /* data_size */);
if (!buffer_) {
return false;
}
if (socket_.SendBuffer(buffer_.get(), buffer_->size())) {
buffer_ = nullptr;
}
return true;
}
void CaptureServiceReceiver::Socket::OnSendUnblocked() {
if (buffer_ && socket_.SendBuffer(buffer_.get(), buffer_->size())) {
buffer_ = nullptr;
}
}
void CaptureServiceReceiver::Socket::ReportErrorAndStop() {
if (input_callback_) {
input_callback_->OnError();
}
input_callback_ = nullptr;
}
void CaptureServiceReceiver::Socket::OnError(int error) {
LOG(INFO) << "Socket error from " << this << ": " << error;
ReportErrorAndStop();
}
void CaptureServiceReceiver::Socket::OnEndOfStream() {
LOG(ERROR) << "Got EOS " << this;
ReportErrorAndStop();
}
bool CaptureServiceReceiver::Socket::OnMessage(char* data, size_t size) {
capture_service::PacketInfo info;
if (!capture_service::ReadHeader(data, size, &info)) {
ReportErrorAndStop();
return false;
}
if (info.message_type != capture_service::MessageType::kAudio) {
LOG(WARNING) << "Received non-audio message, ignored.";
return true;
}
DCHECK_EQ(info.stream_info.stream_type, stream_type_);
if (!capture_service::ReadDataToAudioBus(info.stream_info, data, size,
audio_bus_.get())) {
ReportErrorAndStop();
return false;
}
return HandleAudio(info.timestamp_us);
}
bool CaptureServiceReceiver::Socket::HandleAudio(int64_t timestamp) {
if (!input_callback_) {
LOG(INFO) << "Received audio before stream metadata; ignoring";
return false;
}
input_callback_->OnData(
audio_bus_.get(),
base::TimeTicks() + base::TimeDelta::FromMicroseconds(timestamp),
/* volume =*/1.0);
return true;
}
// static
constexpr base::TimeDelta CaptureServiceReceiver::kConnectTimeout;
CaptureServiceReceiver::CaptureServiceReceiver(
capture_service::StreamType stream_type,
int sample_rate,
int channels,
int frames_per_buffer)
: stream_type_(stream_type),
sample_rate_(sample_rate),
channels_(channels),
frames_per_buffer_(frames_per_buffer),
io_thread_(__func__) {
base::Thread::Options options;
options.message_pump_type = base::MessagePumpType::IO;
// TODO(b/137106361): Tweak the thread priority once the thread priority for
// speech processing gets fixed.
options.priority = base::ThreadPriority::DISPLAY;
CHECK(io_thread_.StartWithOptions(options));
task_runner_ = io_thread_.task_runner();
DCHECK(task_runner_);
}
CaptureServiceReceiver::~CaptureServiceReceiver() {
Stop();
io_thread_.Stop();
}
void CaptureServiceReceiver::Start(
::media::AudioInputStream::AudioInputCallback* input_callback) {
ENSURE_ON_IO_THREAD(Start, input_callback);
std::string path = capture_service::kDefaultUnixDomainSocketPath;
int port = capture_service::kDefaultTcpPort;
StartWithSocket(input_callback, AudioSocketService::Connect(path, port));
}
void CaptureServiceReceiver::StartWithSocket(
::media::AudioInputStream::AudioInputCallback* input_callback,
std::unique_ptr<net::StreamSocket> connecting_socket) {
ENSURE_ON_IO_THREAD(StartWithSocket, input_callback,
std::move(connecting_socket));
DCHECK(!connecting_socket_);
DCHECK(!socket_);
connecting_socket_ = std::move(connecting_socket);
int result = connecting_socket_->Connect(
base::BindOnce(&CaptureServiceReceiver::OnConnected,
base::Unretained(this), input_callback));
if (result != net::ERR_IO_PENDING) {
task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&CaptureServiceReceiver::OnConnected,
base::Unretained(this), input_callback, result));
return;
}
task_runner_->PostDelayedTask(
FROM_HERE,
base::BindOnce(&CaptureServiceReceiver::OnConnectTimeout,
base::Unretained(this), input_callback),
kConnectTimeout);
}
void CaptureServiceReceiver::OnConnected(
::media::AudioInputStream::AudioInputCallback* input_callback,
int result) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
DCHECK_NE(result, net::ERR_IO_PENDING);
if (!connecting_socket_) {
return;
}
if (result == net::OK) {
socket_ = std::make_unique<Socket>(std::move(connecting_socket_),
stream_type_, sample_rate_, channels_,
frames_per_buffer_, input_callback);
} else {
LOG(INFO) << "Connecting failed: " << net::ErrorToString(result);
input_callback->OnError();
connecting_socket_.reset();
}
}
void CaptureServiceReceiver::OnConnectTimeout(
::media::AudioInputStream::AudioInputCallback* input_callback) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
if (!connecting_socket_) {
return;
}
LOG(ERROR) << __func__;
input_callback->OnError();
connecting_socket_.reset();
}
void CaptureServiceReceiver::Stop() {
base::WaitableEvent finished;
StopOnTaskRunner(&finished);
finished.Wait();
}
void CaptureServiceReceiver::StopOnTaskRunner(base::WaitableEvent* finished) {
ENSURE_ON_IO_THREAD(StopOnTaskRunner, finished);
connecting_socket_.reset();
socket_.reset();
finished->Signal();
}
void CaptureServiceReceiver::SetTaskRunnerForTest(
scoped_refptr<base::SequencedTaskRunner> task_runner) {
task_runner_ = std::move(task_runner);
}
} // namespace media
} // namespace chromecast
| bsd-3-clause |
cafephin/mygeneration | src/mymeta/PostgreSQL8/Procedure.cs | 1602 | using System;
using System.Data;
using Npgsql;
namespace MyMeta.PostgreSQL8
{
#if ENTERPRISE
using System.Runtime.InteropServices;
[ComVisible(true), ClassInterface(ClassInterfaceType.AutoDual), ComDefaultInterface(typeof(IProcedure))]
#endif
public class PostgreSQL8Procedure : Procedure
{
internal string _specific_name = "";
public PostgreSQL8Procedure()
{
}
public override IParameters Parameters
{
get
{
if(null == _parameters)
{
_parameters = (PostgreSQL8Parameters)this.dbRoot.ClassFactory.CreateParameters();
_parameters.Procedure = this;
_parameters.dbRoot = this.dbRoot;
string query = "select * from information_schema.parameters where specific_schema = '" +
this.Database.SchemaName + "' and specific_name = '" + (string)this._row["specific_name"] + "'";
NpgsqlConnection cn = ConnectionHelper.CreateConnection(this.dbRoot, this.Database.Name);
DataTable metaData = new DataTable();
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter(query, cn);
adapter.Fill(metaData);
cn.Close();
metaData.Columns["udt_name"].ColumnName = "TYPE_NAME";
metaData.Columns["data_type"].ColumnName = "TYPE_NAMECOMPLETE";
if(metaData.Columns.Contains("TYPE_NAME"))
_parameters.f_TypeName = metaData.Columns["TYPE_NAME"];
if(metaData.Columns.Contains("TYPE_NAMECOMPLETE"))
_parameters.f_TypeNameComplete = metaData.Columns["TYPE_NAMECOMPLETE"];
_parameters.PopulateArray(metaData);
}
return _parameters;
}
}
private PostgreSQL8Parameters _parameters = null;
}
}
| bsd-3-clause |
cemarchi/biosphere | Src/BioAnalyzer/DataAccess/Entities/GenePrioritization/DataIntegrationItem.py | 1829 | from typing import Dict
from Src.Core.Entity.EntityBase import EntityBase
class DataIntegrationItem(EntityBase):
"""description of class"""
def __init__(self, **kargs):
"""
:param kargs:
"""
self.__status = kargs.get('status', None)
self.__element_id = kargs.get('element_id', None)
self.__corr_value = kargs.get('corr_value', None)
@property
def status(self) -> Dict[str, int]:
"""description of property"""
return self.__status
@status.setter
def status(self, value: Dict[str, int]):
"""
:param value:
:return:
"""
self.__status = value
@property
def element_id(self) -> int:
"""description of property"""
return self.__element_id
@element_id.setter
def element_id(self, value: int):
"""
:param value:
:return:
"""
self.__element_id = value
@property
def corr_value(self) -> float:
"""description of property"""
return self.__corr_value
@corr_value.setter
def corr_value(self, value: float):
"""
:param value:
:return:
"""
self.__corr_value = value
def validate(self):
if not self.__status:
raise ValueError('status is required.')
if not self.__element_id:
raise ValueError('id_entrez is required.')
if not self.__corr_value:
raise ValueError('exp_level_value is required.')
def as_dict(self) -> Dict:
return {
'element_id': self.__element_id,
'status': [{'data_type': data_type,
'status': status} for data_type, status in self.__status.items()],
'corr_value': self.__corr_value}
| bsd-3-clause |
sakrejda/protostan | src/protostan/lang/compiler.hpp | 1113 | #include <stan/proto/compile.pb.h>
#include <stan/lang/compiler.hpp>
#include <iostream>
#include <sstream>
#include <string>
namespace stan {
namespace proto {
stan::proto::StanCompileResponse compile(
const stan::proto::StanCompileRequest& request) {
stan::proto::StanCompileResponse response;
std::ostringstream err_stream;
std::istringstream stan_stream(request.model_code());
std::ostringstream cpp_stream;
response.set_state(stan::proto::StanCompileResponse::ERROR);
try {
bool valid_model = stan::lang::compile(&err_stream,
stan_stream,
cpp_stream,
request.model_name());
response.set_messages(err_stream.str());
if (valid_model) {
response.set_state(stan::proto::StanCompileResponse::SUCCESS);
response.set_cpp_code(cpp_stream.str());
}
} catch(const std::exception& e) {
response.set_messages(e.what());
}
return response;
}
}
}
| bsd-3-clause |
mitodl/micromasters | static/js/containers/DashboardPage.js | 33187 | // @flow
/* global SETTINGS: false */
import DocumentTitle from "react-document-title"
import React from "react"
import Card from "@material-ui/core/Card"
import PropTypes from "prop-types"
import type { Dispatch } from "redux"
import { connect } from "react-redux"
import _ from "lodash"
import moment from "moment"
import R from "ramda"
import Dialog from "@material-ui/core/Dialog"
import DialogTitle from "@material-ui/core/DialogTitle"
import DialogContent from "@material-ui/core/DialogContent"
import DialogActions from "@material-ui/core/DialogActions"
import Alert from "react-bootstrap/lib/Alert"
import ProgramEnrollmentDialog from "../components/ProgramEnrollmentDialog"
import Loader from "../components/Loader"
import { calculatePrices, isFreeCoupon } from "../lib/coupon"
import {
FETCH_SUCCESS,
FETCH_PROCESSING,
FETCH_FAILURE,
checkout
} from "../actions"
import {
updateCourseStatus,
fetchDashboard,
clearDashboard
} from "../actions/dashboard"
import { clearProfile } from "../actions/profile"
import { addProgramEnrollment } from "../actions/programs"
import {
COUPON_CONTENT_TYPE_COURSE,
COUPON_CONTENT_TYPE_PROGRAM,
FA_TERMINAL_STATUSES,
FA_PENDING_STATUSES,
TOAST_SUCCESS,
TOAST_FAILURE,
STATUS_OFFERED,
STATUS_CAN_UPGRADE,
STATUS_PENDING_ENROLLMENT,
STATUS_NOT_PASSED,
STATUS_PASSED,
STATUS_CURRENTLY_ENROLLED,
STATUS_PAID_BUT_NOT_ENROLLED
} from "../constants"
import {
setToastMessage,
setConfirmSkipDialogVisibility,
setDocsInstructionsVisibility,
setCouponNotificationVisibility,
setPaymentTeaserDialogVisibility,
setEnrollCourseDialogVisibility,
setCalculatePriceDialogVisibility,
setExamEnrollmentDialogVisibility,
setSelectedExamCouponCourse,
setEnrollSelectedCourseRun,
showDialog,
hideDialog,
setShowExpandedCourseStatus,
setEnrollProgramDialogError,
setEnrollProgramDialogVisibility,
setEnrollSelectedProgram
} from "../actions/ui"
import { showEnrollPayLaterSuccessMessage } from "../actions/course_enrollments"
import { clearCalculatorEdit } from "../actions/financial_aid"
import { findCourseRun } from "../util/util"
import CourseListCard from "../components/dashboard/CourseListCard"
import DashboardUserCard from "../components/dashboard/DashboardUserCard"
import FinancialAidCard from "../components/dashboard/FinancialAidCard"
import FinalExamCard from "../components/dashboard/FinalExamCard"
import ErrorMessage from "../components/ErrorMessage"
import LearnersInProgramCard from "../components/LearnersInProgramCard"
import ProgressWidget from "../components/ProgressWidget"
import DiscussionCard from "../components/DiscussionCard"
import { clearCoupons, fetchCoupons } from "../actions/coupons"
import {
setDocumentSentDate,
updateDocumentSentDate
} from "../actions/documents"
import {
startCalculatorEdit,
updateCalculatorEdit
} from "../actions/financial_aid"
import { setTimeoutActive } from "../actions/order_receipt"
import { attachCoupon, setRecentlyAttachedCoupon } from "../actions/coupons"
import { COURSE_EMAIL_TYPE } from "../components/email/constants"
import { COURSE_TEAM_EMAIL_CONFIG } from "../components/email/lib"
import { withEmailDialog } from "../components/email/hoc"
import { singleBtnDialogActions } from "../components/inputs/util"
import { skipFinancialAid } from "../actions/financial_aid"
import { currencyForCountry } from "../lib/currency"
import DocsInstructionsDialog from "../components/DocsInstructionsDialog"
import CouponNotificationDialog from "../components/CouponNotificationDialog"
import CourseEnrollmentDialog from "../components/CourseEnrollmentDialog"
import { INCOME_DIALOG } from "./FinancialAidCalculator"
import { processCheckout } from "./OrderSummaryPage"
import { getOwnDashboard, getOwnCoursePrices } from "../reducers/util"
import { actions } from "../lib/redux_rest"
import { wait } from "../util/util"
import { CALCULATOR_DIALOG } from "./FinancialAidCalculator"
import { gradeDetailPopupKey } from "../components/dashboard/courses/Grades"
import type { UIState } from "../reducers/ui"
import type { OrderReceiptState } from "../reducers/order_receipt"
import type { DocumentsState } from "../reducers/documents"
import type {
CoursePrices,
DashboardState,
ProgramLearners
} from "../flow/dashboardTypes"
import type { AllEmailsState } from "../flow/emailTypes"
import type {
AvailableProgram,
AvailableProgramsState
} from "../flow/enrollmentTypes"
import type { FinancialAidState } from "../reducers/financial_aid"
import type { CouponsState } from "../reducers/coupons"
import type { ProfileGetResult } from "../flow/profileTypes"
import type { Course, CourseRun, Program } from "../flow/programTypes"
import type { Coupon } from "../flow/couponTypes"
import type { RestState } from "../flow/restTypes"
import type { Post } from "../flow/discussionTypes"
import type { ExamEnrollmentResponse } from "../flow/enrollmentTypes"
import PersonalCoursePriceDialog from "../components/dashboard/PersonalCoursePriceDialog"
import ExamEnrollmentDialog from "../components/dashboard/ExamEnrollmentDialog"
const isFinishedProcessing = R.contains(R.__, [FETCH_SUCCESS, FETCH_FAILURE])
export type GradeType = "COURSE_GRADE" | "EXAM_GRADE"
export const COURSE_GRADE: GradeType = "COURSE_GRADE"
export const EXAM_GRADE: GradeType = "EXAM_GRADE"
class DashboardPage extends React.Component {
static contextTypes = {
router: PropTypes.object.isRequired
}
props: {
coupons: CouponsState,
profile: ProfileGetResult,
currentProgramEnrollment: AvailableProgram,
programs: AvailableProgramsState,
dashboard: DashboardState,
prices: RestState<CoursePrices>,
programLearners: RestState<ProgramLearners>,
dispatch: Dispatch,
ui: UIState,
email: AllEmailsState,
documents: DocumentsState,
orderReceipt: OrderReceiptState,
financialAid: FinancialAidState,
location: Object,
openEmailComposer: (emailType: string, emailOpenParams: any) => void,
discussionsFrontpage: RestState<Array<Post>>
}
componentDidMount() {
this.updateRequirements()
}
componentDidUpdate() {
this.updateRequirements()
const program = this.getCurrentlyEnrolledProgram()
if (this.shouldSkipFinancialAid() && program !== undefined) {
this.skipFinancialAid(program.id)
}
}
componentWillUnmount() {
const { dispatch, programLearners } = this.props
dispatch(clearDashboard(SETTINGS.user.username))
dispatch(actions.prices.clear(SETTINGS.user.username))
_.forEach(R.keys(programLearners), id =>
dispatch(actions.programLearners.clear(id))
)
dispatch(clearCoupons())
}
openCourseContactDialog = (course: Course, canContactCourseTeam: boolean) => {
const { dispatch, openEmailComposer } = this.props
if (canContactCourseTeam) {
openEmailComposer(COURSE_EMAIL_TYPE, course)
} else {
dispatch(setPaymentTeaserDialogVisibility(true))
}
}
closePaymentTeaserDialog = () => {
const { dispatch } = this.props
dispatch(setPaymentTeaserDialogVisibility(false))
}
handleOrderSuccess = (course: Course): void => {
const {
dispatch,
ui: { toastMessage }
} = this.props
const firstRun: ?CourseRun = course.runs.length > 0 ? course.runs[0] : null
if (_.isNil(toastMessage)) {
if (firstRun && firstRun.status === STATUS_PAID_BUT_NOT_ENROLLED) {
dispatch(
setToastMessage({
title: "Course Enrollment",
message: `Something went wrong. You paid for this course '${
course.title
}' but are not enrolled.`,
icon: TOAST_FAILURE
})
)
} else {
dispatch(
setToastMessage({
title: "Order Complete!",
message: `You are now enrolled in ${course.title}`,
icon: TOAST_SUCCESS
})
)
}
}
this.context.router.push("/dashboard/")
}
handleOrderCancellation = (): void => {
const {
dispatch,
ui: { toastMessage }
} = this.props
if (_.isNil(toastMessage)) {
dispatch(
setToastMessage({
message: "Order was cancelled",
icon: TOAST_FAILURE
})
)
}
this.context.router.push("/dashboard/")
}
handleOrderPending = (run: CourseRun): void => {
const { dispatch } = this.props
dispatch(
updateCourseStatus(
SETTINGS.user.username,
run.course_id,
STATUS_PENDING_ENROLLMENT
)
)
if (!this.props.orderReceipt.timeoutActive) {
wait(3000).then(() => {
const { orderReceipt } = this.props
dispatch(setTimeoutActive(false))
const deadline = moment(orderReceipt.initialTime).add(2, "minutes")
const now = moment()
if (now.isBefore(deadline)) {
dispatch(fetchDashboard(SETTINGS.user.username, true))
} else {
dispatch(
setToastMessage({
message: "Order was not processed",
icon: TOAST_FAILURE
})
)
}
})
dispatch(setTimeoutActive(true))
}
}
updateRequirements = () => {
this.fetchDashboard()
this.fetchCoursePrices()
this.fetchProgramLearners()
this.handleCoupon()
this.fetchCoupons()
this.handleOrderStatus()
this.fetchDiscussionsFrontpage()
this.checkFinancialAidError()
}
checkFinancialAidError = () => {
const {
financialAid: { fetchError },
dispatch
} = this.props
if (fetchError && fetchError.message === "Profile is not complete") {
dispatch(clearProfile(SETTINGS.user.username))
this.context.router.push(`/profile/`)
dispatch(hideDialog(INCOME_DIALOG))
dispatch(clearCalculatorEdit())
}
}
fetchDashboard() {
const { dashboard, dispatch } = this.props
if (dashboard.fetchStatus === undefined) {
dispatch(fetchDashboard(SETTINGS.user.username)).catch(() => {
/* Promise rejected */
})
}
}
fetchCoursePrices() {
const { prices, dispatch } = this.props
if (prices.getStatus === undefined) {
dispatch(actions.prices.get(SETTINGS.user.username)).catch(() => {
/* Promise rejected */
})
}
}
fetchProgramLearners() {
const { programLearners, dispatch } = this.props
const program = this.getCurrentlyEnrolledProgram()
if (
program !== undefined &&
R.pathEq([program.id, "getStatus"], undefined, programLearners)
) {
dispatch(actions.programLearners.get(program.id)).catch(() => {
/* Promise rejected */
})
}
}
fetchCoupons() {
const { coupons, dispatch } = this.props
if (coupons.fetchGetStatus === undefined) {
dispatch(fetchCoupons()).catch(() => {
/* Promise rejected */
})
}
}
handleOrderStatus = () => {
const {
dashboard,
location: { query }
} = this.props
if (dashboard.fetchStatus !== FETCH_SUCCESS) {
// wait until we have access to the dashboard
return
}
const courseKey = query.course_key
if (query.status === "receipt") {
const [courseRun, course] = findCourseRun(
dashboard.programs,
run => run !== null && run.course_id === courseKey
)
if (courseRun === null || course === null) {
// could not find course to handle order status for
return
}
switch (courseRun.status) {
case STATUS_CAN_UPGRADE:
case STATUS_OFFERED:
// user is directed to the order receipt page but order is not yet fulfilled
this.handleOrderPending(courseRun)
break
case STATUS_NOT_PASSED:
case STATUS_PASSED:
case STATUS_CURRENTLY_ENROLLED:
case STATUS_PAID_BUT_NOT_ENROLLED:
this.handleOrderSuccess(course)
break
default:
// do nothing, a timeout was set to check back later
break
}
} else if (query.status === "cancel") {
this.handleOrderCancellation()
}
}
fetchDiscussionsFrontpage() {
const { dispatch, discussionsFrontpage } = this.props
if (
SETTINGS.FEATURES.DISCUSSIONS_POST_UI &&
SETTINGS.open_discussions_redirect_url &&
!discussionsFrontpage.loaded &&
!discussionsFrontpage.processing
) {
dispatch(actions.discussionsFrontpage.get()).catch(() => {
/* Promise rejected */
})
}
}
handleCoupon = () => {
const {
coupons,
dispatch,
location: { query }
} = this.props
if (!query.coupon) {
// If there's no coupon code in the URL query parameters,
// there's nothing to do.
return
}
if (coupons.fetchPostStatus !== undefined) {
// If we've already launched a POST request to attach this coupon
// to this user, don't launch another one.
return
}
if (
coupons.fetchGetStatus === FETCH_PROCESSING ||
coupons.fetchGetStatus === undefined
) {
/*
Abort to avoid the following race condition:
1. launch first fetchCoupons() API request
2. launch attachCoupon() API request
3. attachCoupon() returns, launch second fetchCoupons() API request
4. second fetchCoupons() returns, updates Redux store with accurate information
5. first fetchCoupons() finally returns, updates Redux store with stale information
Ideally, it would be nice to abort the first fetchCoupons() API request
in this case, but fetches can't be aborted. Instead, we will abort
this function (by returning early), and rely on being called again in the
future.
*/
return
}
dispatch(attachCoupon(query.coupon)).then(
result => {
this.setRecentlyAttachedCoupon(result.coupon)
this.setCouponNotificationVisibility(true)
this.context.router.push("/dashboard/")
// update coupon state in Redux
dispatch(fetchCoupons())
},
() => {
dispatch(
setToastMessage({
title: "Coupon failed",
message: "This coupon code is invalid or does not exist.",
icon: TOAST_FAILURE
})
)
this.context.router.push("/dashboard/")
}
)
}
openFinancialAidCalculator = () => {
const {
dispatch,
currentProgramEnrollment,
profile: {
profile: { country }
}
} = this.props
dispatch(startCalculatorEdit(currentProgramEnrollment.id))
if (country) {
const currencyPrediction = currencyForCountry(country)
dispatch(updateCalculatorEdit({ currency: currencyPrediction }))
}
dispatch(showDialog(CALCULATOR_DIALOG))
}
setDocumentSentDate = (newDate: string): void => {
const { dispatch } = this.props
dispatch(setDocumentSentDate(newDate))
}
getCurrentlyEnrolledProgram = () => {
const { currentProgramEnrollment, dashboard } = this.props
if (_.isNil(currentProgramEnrollment) || _.isNil(dashboard)) {
return undefined
}
return dashboard.programs.find(
program => program.id === currentProgramEnrollment.id
)
}
skipFinancialAid = (programId: number): any => {
const { dispatch, financialAid } = this.props
const program = this.getCurrentlyEnrolledProgram()
if (
program &&
program.financial_aid_user_info &&
!FA_TERMINAL_STATUSES.includes(
program.financial_aid_user_info.application_status
) &&
financialAid.fetchSkipStatus === undefined
) {
return dispatch(skipFinancialAid(programId)).then(
() => {
this.setConfirmSkipDialogVisibility(false)
},
() => {
this.setConfirmSkipDialogVisibility(false)
dispatch(
setToastMessage({
message: "Failed to skip financial aid.",
icon: TOAST_FAILURE
})
)
}
)
}
}
setConfirmSkipDialogVisibility = bool => {
const { dispatch } = this.props
dispatch(setConfirmSkipDialogVisibility(bool))
}
setExamEnrollmentDialogVisibility = bool => {
const { dispatch } = this.props
dispatch(setExamEnrollmentDialogVisibility(bool))
}
updateDocumentSentDate = (
financialAidId: number,
sentDate: string
): Promise<*> => {
const { dispatch } = this.props
return dispatch(updateDocumentSentDate(financialAidId, sentDate))
}
addCourseEnrollment = (courseId: string): Promise<*> => {
const { dispatch } = this.props
return dispatch(actions.courseEnrollments.post(courseId)).then(
() => {
dispatch(fetchDashboard(SETTINGS.user.username, true))
dispatch(actions.prices.get(SETTINGS.user.username, true))
dispatch(showEnrollPayLaterSuccessMessage(courseId))
},
() => {
dispatch(
setToastMessage({
message: "Failed to add course enrollment.",
icon: TOAST_FAILURE
})
)
}
)
}
addExamEnrollment = (examCourseId: string): Promise<*> => {
const { dispatch } = this.props
return dispatch(actions.examEnrollment.post(examCourseId)).then(
(result: ExamEnrollmentResponse) => {
if (!result) {
return
}
window.location = result.url
},
() => {
dispatch(
setToastMessage({
message: "Failed to add exam enrollment.",
icon: TOAST_FAILURE
})
)
}
)
}
setDocsInstructionsVisibility = bool => {
const { dispatch } = this.props
dispatch(setDocsInstructionsVisibility(bool))
}
setCouponNotificationVisibility = bool => {
const { dispatch } = this.props
dispatch(setCouponNotificationVisibility(bool))
}
setRecentlyAttachedCoupon = (coupon: Coupon) => {
const { dispatch } = this.props
dispatch(setRecentlyAttachedCoupon(coupon))
}
setEnrollCourseDialogVisibility = bool => {
const { dispatch } = this.props
dispatch(setEnrollCourseDialogVisibility(bool))
}
setEnrollSelectedCourseRun = (run: CourseRun) => {
const { dispatch } = this.props
dispatch(setEnrollSelectedCourseRun(run))
}
setSelectedExamCouponCourse = (courseId: number) => {
const { dispatch } = this.props
dispatch(setSelectedExamCouponCourse(courseId))
}
setCalculatePriceDialogVisibility = bool => {
const { dispatch } = this.props
dispatch(setCalculatePriceDialogVisibility(bool))
}
navigateToProfile = () => {
this.context.router.push("/learner")
}
shouldSkipFinancialAid = (): boolean => {
// If the user has a 100% off coupon for the program, there's no need for financial aid
const program = this.getCurrentlyEnrolledProgram()
return R.compose(
R.any(
coupon =>
program !== undefined &&
isFreeCoupon(coupon) &&
coupon.content_type === COUPON_CONTENT_TYPE_PROGRAM &&
coupon.program_id === program.id
),
R.pathOr([], ["coupons", "coupons"])
)(this.props)
}
setShowGradeDetailDialog = (
open: boolean,
gradeType: GradeType,
courseTitle: string
) => {
const { dispatch } = this.props
if (open) {
dispatch(showDialog(gradeDetailPopupKey(gradeType, courseTitle)))
} else {
dispatch(hideDialog(gradeDetailPopupKey(gradeType, courseTitle)))
}
}
setShowExpandedCourseStatus = (courseId: number) => {
const { dispatch } = this.props
dispatch(setShowExpandedCourseStatus(courseId))
}
renderCouponDialog() {
const { programs, ui, coupons, dashboard } = this.props
const coupon = coupons.recentlyAttachedCoupon
if (!coupon) {
return null
}
const couponProgram = programs.availablePrograms.find(
program => program.id === coupon.program_id
)
let couponCourse = null
if (coupon.content_type === COUPON_CONTENT_TYPE_COURSE) {
const dashboardCouponProgram: Program = (dashboard.programs.find(
program => program.id === coupon.program_id
): any)
couponCourse = dashboardCouponProgram.courses.find(
course => course.id === coupon.object_id
)
}
return (
<CouponNotificationDialog
coupon={coupon}
couponProgram={couponProgram}
couponCourse={couponCourse}
open={ui.couponNotificationVisibility}
setDialogVisibility={this.setCouponNotificationVisibility}
/>
)
}
renderCourseContactPaymentDialog() {
const { ui } = this.props
const program = this.getCurrentlyEnrolledProgram()
const messageTail =
program && program.financial_aid_availability
? "learners who have paid for the course"
: "verified learners"
return (
<Dialog
classes={{ paper: "dialog", root: "course-payment-dialog-wrapper" }}
open={ui.paymentTeaserDialogVisibility}
onClose={this.closePaymentTeaserDialog}
>
<DialogTitle className="dialog-title">
Contact the Course Team
</DialogTitle>
<DialogContent>
<div className="inner-content">
<img
src="/static/images/contact_course_team_icon.png"
alt="Instructor icon"
/>
<p>{`This is a premium feature for ${messageTail}.`}</p>
</div>
</DialogContent>
<DialogActions>
{singleBtnDialogActions(this.closePaymentTeaserDialog)}
</DialogActions>
</Dialog>
)
}
dispatchCheckout = (courseId: string) => {
const { dispatch } = this.props
return dispatch(checkout(courseId)).then(processCheckout)
}
renderPersonalCoursePriceDialog() {
const { ui } = this.props
return (
<PersonalCoursePriceDialog
open={ui.calculatePriceDialogVisibility}
openFinancialAidCalculator={this.openFinancialAidCalculator}
setVisibility={this.setCalculatePriceDialogVisibility}
/>
)
}
renderExamEnrollmentDialog() {
const { ui } = this.props
const program = this.getCurrentlyEnrolledProgram()
if (!program) {
return null
}
let course = null
if (ui.selectedExamCouponCourse) {
course = program.courses.find(
course => course.id === ui.selectedExamCouponCourse
)
}
if (!course) {
return null
}
return (
<ExamEnrollmentDialog
open={ui.examEnrollmentDialogVisibility}
setVisibility={this.setExamEnrollmentDialogVisibility}
addExamEnrollment={this.addExamEnrollment}
course={course}
/>
)
}
renderCourseEnrollmentDialog() {
const { ui } = this.props
const program = this.getCurrentlyEnrolledProgram()
if (!program) {
return null
}
const courseRun = ui.enrollSelectedCourseRun
if (!courseRun) {
return null
}
const course = program.courses.find(course =>
R.contains(courseRun.id, R.pluck("id", course.runs))
)
if (!course) {
return null
}
// technically this is, has user applied or does it not matter if they didn't
const hasUserApplied =
!program.financial_aid_availability ||
this.shouldSkipFinancialAid() ||
program.financial_aid_user_info.has_user_applied
const pendingFinancialAid =
program.financial_aid_availability &&
program.financial_aid_user_info.has_user_applied &&
FA_PENDING_STATUSES.includes(
program.financial_aid_user_info.application_status
)
return (
<CourseEnrollmentDialog
course={course}
courseRun={courseRun}
hasUserApplied={hasUserApplied}
pendingFinancialAid={pendingFinancialAid}
financialAidAvailability={program.financial_aid_availability}
openFinancialAidCalculator={this.openFinancialAidCalculator}
checkout={this.dispatchCheckout}
open={ui.enrollCourseDialogVisibility}
setVisibility={this.setEnrollCourseDialogVisibility}
addCourseEnrollment={this.addCourseEnrollment}
/>
)
}
renderEdxCacheRefreshErrorMessage() {
const { dashboard } = this.props
if (dashboard.isEdxDataFresh) {
return null
}
const email = SETTINGS.support_email
return (
<div className="alert-message alert-message-inline">
<Alert bsStyle="danger">
<p>
Sorry, we're unable to update your dashboard at this time, so some
of the information on this page may not be up to date. <br />
Please refresh the browser, or check back later.
</p>
<p>
If the error persists, contact{" "}
<a href={`mailto:${email}`}>{email}</a> for help.
</p>
</Alert>
</div>
)
}
renderErrorMessage = (): React$Element<*> | null => {
const { dashboard, prices } = this.props
if (dashboard.errorInfo) {
return <ErrorMessage errorInfo={dashboard.errorInfo} />
}
if (prices.error) {
return <ErrorMessage errorInfo={prices.error} />
}
return null
}
renderLearnersInProgramCard(programID: number) {
const { programLearners } = this.props
let learnersInProgramCard
if (
R.pathSatisfies(
count => count > 0,
[programID, "data", "learners_count"],
programLearners
)
) {
learnersInProgramCard = (
<LearnersInProgramCard
programLearners={programLearners[programID].data}
/>
)
}
return learnersInProgramCard
}
addProgramEnrollmentInProgram = (programId: number): Promise<*> => {
const { dispatch } = this.props
return dispatch(addProgramEnrollment(programId))
}
setEnrollDialogError = (error: ?string): void => {
const { dispatch } = this.props
dispatch(setEnrollProgramDialogError(error))
}
setEnrollDialogVisibility = (visibility: boolean): void => {
const { dispatch } = this.props
dispatch(setEnrollProgramDialogVisibility(visibility))
}
setEnrollSelectedProgramById = (programId: ?number): void => {
const { dispatch } = this.props
if (programId) {
dispatch(setEnrollSelectedProgram(programId))
}
}
noProgramSelectedCard = () => {
const {
programs,
ui: {
enrollProgramDialogError,
enrollProgramDialogVisibility,
enrollSelectedProgram
}
} = this.props
return (
<div>
<Card shadow={1} className="no-program-card">
<div>You are not currently enrolled in any programs</div>
<button
className="mm-minor-action enroll-wizard-button"
onClick={() => this.setEnrollDialogVisibility(true)}
>
Enroll in a MicroMasters Program
</button>
<ProgramEnrollmentDialog
enrollInProgram={this.addProgramEnrollmentInProgram}
programs={programs.availablePrograms}
selectedProgram={enrollSelectedProgram}
error={enrollProgramDialogError}
visibility={enrollProgramDialogVisibility}
setError={this.setEnrollDialogError}
setVisibility={this.setEnrollDialogVisibility}
setSelectedProgram={this.setEnrollSelectedProgramById}
fetchAddStatus={programs.postStatus}
/>
</Card>
</div>
)
}
renderPageContent = (): React$Element<*> => {
const {
dashboard,
prices,
profile: { profile },
documents,
ui,
financialAid,
coupons,
discussionsFrontpage
} = this.props
const program = this.getCurrentlyEnrolledProgram()
if (!program) {
return this.noProgramSelectedCard()
}
if (!prices.data) {
throw new Error("no program; should never get here")
}
const couponPrices = calculatePrices(
dashboard.programs,
prices.data,
coupons.coupons
)
let financialAidCard
if (program.financial_aid_availability && !this.shouldSkipFinancialAid()) {
financialAidCard = (
<FinancialAidCard
program={program}
couponPrices={couponPrices}
openFinancialAidCalculator={this.openFinancialAidCalculator}
documents={documents}
setDocumentSentDate={this.setDocumentSentDate}
skipFinancialAid={this.skipFinancialAid}
updateDocumentSentDate={this.updateDocumentSentDate}
setConfirmSkipDialogVisibility={this.setConfirmSkipDialogVisibility}
setDocsInstructionsVisibility={this.setDocsInstructionsVisibility}
ui={ui}
financialAid={financialAid}
/>
)
}
return (
<div>
{this.renderEdxCacheRefreshErrorMessage()}
<h5 className="program-title-dashboard">{program.title}</h5>
<div className="double-column">
<DocsInstructionsDialog
open={ui.docsInstructionsVisibility}
setDialogVisibility={this.setDocsInstructionsVisibility}
/>
{this.renderCouponDialog()}
{this.renderCourseEnrollmentDialog()}
{this.renderPersonalCoursePriceDialog()}
{this.renderExamEnrollmentDialog()}
<div className="first-column">
<DashboardUserCard profile={profile} program={program} />
<FinalExamCard
profile={profile}
program={program}
ui={ui}
navigateToProfile={this.navigateToProfile}
/>
{financialAidCard}
<CourseListCard
program={program}
couponPrices={couponPrices}
key={program.id}
ui={ui}
checkout={this.dispatchCheckout}
openFinancialAidCalculator={this.openFinancialAidCalculator}
addCourseEnrollment={this.addCourseEnrollment}
openCourseContactDialog={this.openCourseContactDialog}
setEnrollSelectedCourseRun={this.setEnrollSelectedCourseRun}
setSelectedExamCouponCourse={this.setSelectedExamCouponCourse}
setExamEnrollmentDialogVisibility={
this.setExamEnrollmentDialogVisibility
}
setEnrollCourseDialogVisibility={
this.setEnrollCourseDialogVisibility
}
setCalculatePriceDialogVisibility={
this.setCalculatePriceDialogVisibility
}
setShowExpandedCourseStatus={this.setShowExpandedCourseStatus}
setShowGradeDetailDialog={this.setShowGradeDetailDialog}
showStaffView={false}
/>
</div>
<div className="second-column">
<ProgressWidget program={program} />
{SETTINGS.FEATURES.DISCUSSIONS_POST_UI &&
SETTINGS.open_discussions_redirect_url ? (
<DiscussionCard
program={program}
frontpage={discussionsFrontpage.data || []}
loaded={discussionsFrontpage.loaded}
/>
) : null}
{this.renderLearnersInProgramCard(program.id)}
</div>
</div>
</div>
)
}
render() {
const { dashboard, prices } = this.props
const loaded = R.all(isFinishedProcessing, [
dashboard.fetchStatus,
prices.getStatus
])
const fetchStarted =
!_.isNil(prices.getStatus) && !_.isNil(dashboard.fetchStatus)
// TODO: we should handle prices.noSpinner too. This currently works because we always dispatch both actions with
// noSpinner: true at the same time
const noSpinner = dashboard.noSpinner
const errorMessage = this.renderErrorMessage()
let pageContent
if ((_.isNil(errorMessage) && loaded && fetchStarted) || noSpinner) {
pageContent = this.renderPageContent()
}
return (
<DocumentTitle title="Learner Dashboard | MITx MicroMasters">
<div className="dashboard">
<Loader loaded={loaded}>
{errorMessage}
{pageContent}
{this.renderCourseContactPaymentDialog()}
</Loader>
</div>
</DocumentTitle>
)
}
}
const mapStateToProps = state => {
let profile = {
profile: {}
}
if (SETTINGS.user && state.profiles[SETTINGS.user.username] !== undefined) {
profile = state.profiles[SETTINGS.user.username]
}
return {
profile: profile,
dashboard: getOwnDashboard(state),
prices: getOwnCoursePrices(state),
programLearners: state.programLearners,
programs: state.programs,
currentProgramEnrollment: state.currentProgramEnrollment,
ui: state.ui,
email: state.email,
documents: state.documents,
orderReceipt: state.orderReceipt,
financialAid: state.financialAid,
coupons: state.coupons,
discussionsFrontpage: state.discussionsFrontpage
}
}
export default R.compose(
connect(mapStateToProps),
withEmailDialog({
[COURSE_EMAIL_TYPE]: COURSE_TEAM_EMAIL_CONFIG
})
)(DashboardPage)
| bsd-3-clause |
mathstuf/rust-keyutils | src/tests/clear.rs | 5674 | // Copyright (c) 2019, Ben Boeckel
// 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 this project nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use crate::keytypes::User;
use crate::Keyring;
use super::utils;
#[test]
fn invalid_keyring() {
let mut keyring = utils::invalid_keyring();
let err = keyring.clear().unwrap_err();
assert_eq!(err, errno::Errno(libc::EINVAL));
}
#[test]
fn clear_non_keyring() {
let mut keyring = utils::new_test_keyring();
let key = keyring
.add_key::<User, _, _>("clear_non_keyring", &b"payload"[..])
.unwrap();
// Try clearing a non-keyring.
let mut not_a_keyring = unsafe { Keyring::new(key.serial()) };
let err = not_a_keyring.clear().unwrap_err();
assert_eq!(err, errno::Errno(libc::ENOTDIR));
keyring.unlink_key(&key).unwrap();
}
#[test]
fn clear_deleted_keyring() {
let mut keyring = utils::new_test_keyring();
let mut sub_keyring = keyring.add_keyring("clear_deleted_keyring").unwrap();
keyring.unlink_keyring(&sub_keyring).unwrap();
// Keys are deleted asynchronously; permissions are revoked until it is actually deleted.
loop {
let err = sub_keyring.clear().unwrap_err();
if err == errno::Errno(libc::EACCES) {
continue;
}
assert_eq!(err, errno::Errno(libc::ENOKEY));
break;
}
}
#[test]
fn clear_empty_keyring() {
let mut keyring = utils::new_test_keyring();
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 0);
assert_eq!(keyrings.len(), 0);
// Clear the keyring.
keyring.clear().unwrap();
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 0);
assert_eq!(keyrings.len(), 0);
}
#[test]
fn clear_keyring_one_key() {
let mut keyring = utils::new_test_keyring();
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 0);
assert_eq!(keyrings.len(), 0);
let key_desc = "clear_keyring:key";
// Create a key.
let payload = &b"payload"[..];
keyring.add_key::<User, _, _>(key_desc, payload).unwrap();
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 1);
assert_eq!(keyrings.len(), 0);
assert_eq!(keys[0].description().unwrap().description, key_desc);
// Clear the keyring.
keyring.clear().unwrap();
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 0);
assert_eq!(keyrings.len(), 0);
}
#[test]
fn clear_keyring_many_keys() {
let mut keyring = utils::new_test_keyring();
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 0);
assert_eq!(keyrings.len(), 0);
let count = 40;
let payload = &b"payload"[..];
let mut descs = Vec::with_capacity(count);
for i in 0..count {
let key_desc = format!("clear_keyring:key{:02}", i);
// Create a key.
keyring
.add_key::<User, _, _>(key_desc.as_ref(), payload)
.unwrap();
descs.push(key_desc);
}
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), count);
assert_eq!(keyrings.len(), 0);
let mut actual_descs = keys
.iter()
.map(|key| key.description().unwrap().description)
.collect::<Vec<_>>();
actual_descs.sort();
assert_eq!(actual_descs, descs);
// Clear the keyring.
keyring.clear().unwrap();
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 0);
assert_eq!(keyrings.len(), 0);
}
#[test]
fn clear_keyring_keyring() {
let mut keyring = utils::new_test_keyring();
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 0);
assert_eq!(keyrings.len(), 0);
let keyring_desc = "clear_keyring:keyring";
// Create a key.
keyring.add_keyring(keyring_desc).unwrap();
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 0);
assert_eq!(keyrings.len(), 1);
assert_eq!(keyrings[0].description().unwrap().description, keyring_desc);
// Clear the keyring.
keyring.clear().unwrap();
let (keys, keyrings) = keyring.read().unwrap();
assert_eq!(keys.len(), 0);
assert_eq!(keyrings.len(), 0);
}
| bsd-3-clause |
ipti/hb | web/scripts/SiteView/Functions.js | 514 | /**
* Post the FORM to add a new Address.
*
* @param {form} $form
*/
function submitCampaignForm($form) {
$('#campaignModal button[type=submit]').html('<i class="fa fa-spinner fa-spin"></i> Criando...');
$('#campaignModal button[type=submit]').click(function(e){
e.preventDefault();
});
$.post(
$form.attr("action"),
$form.serialize()
).done(function(){
window.location.assign("/");
}).fail(function(){
window.location.assign("/");
});
};
| bsd-3-clause |
NCIP/catrip | codebase/projects/catrip-catissuecoreGenerateData/test/edu/duke/catrip/catissuecore/general/SpecimenInsertTest.java | 15862 | /*L
* Copyright Duke Comprehensive Cancer Center
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/catrip/LICENSE.txt for details.
*/
/**
* Created on Aug 31, 2006 by PEEDI002
**/
package edu.duke.catrip.catissuecore.general;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
//import edu.pitt.cabig.cae.domain.breast.BreastCancerTNMFindingTest;
public class SpecimenInsertTest extends TestCase {
//Variable to determining how many recs to create, per table
private static int maxrecs = 500;
//INPUT FILES FOR POPULATING THE TABLES
//Specimen
private static String inFile1 = "data\\SpecimenType.txt";
private static String inFile2 = "data\\SpecimenQuantity.txt";
private static String inFile3 = "data\\SpecimenQuantityAvail.txt";
private static String inFile4 = "data\\SpecimenCmmt.txt";
private static String inFile5 = "data\\SpecimenBarcode2.txt";
private static String inFile6 = "data\\PosDimOne.txt";
private static String inFile7 = "data\\PosDimTwo.txt";
private static String newFile1 = "data\\SpecimenTypeV2.txt";
private static String newFile2 = "data\\SpecimenQuantityV2.txt";
private static String newFile3 = "data\\SpecimenQuantityAvailV2.txt";
private static String newFile4 = "data\\SpecimenCmmtV2.txt";
//Specimen Chars
private static String inFile8 = "data\\TissueSite.txt";
private static String inFile9 = "data\\TissueSide.txt";
private static String inFile10 = "data\\PathStatus.txt";
private static String newFile8 = "data\\TissueSiteV2.txt";
private static String newFile9 = "data\\TissueSideV2.txt";
private static String newFile10 = "data\\PathStatusV2.txt";
//SpecimenCollectionGroup
private static String inFile11 = "data\\ClinicalDiagnosis.txt";
private static String inFile12 = "data\\ClinicalStatus.txt";
private static String newFile11 = "data\\ClinicalDiagnosisV2.txt";
private static String newFile12 = "data\\ClinicalStatusV2.txt";
//CollectionProtocolEvent
private static String inFile13 = "data\\StudyCalEvtPt.txt";
//CollectionProtocol
private static String inFile14 = "data\\SpecDescriptURL.txt";
private static String inFile15 = "data\\dates.txt";
private static String inFile16 = "data\\SpecProtEnrollment.txt";
private static String inFile17 = "data\\IRBs.txt";
private static String inFile18 = "data\\SpecProtSTitle.txt";
private static String inFile19 = "data\\SpecProtTitle.txt";
private static String newFile18 = "data\\SpecProtSTitleV2.txt";
private static String newFile19 = "data\\SpecProtTitlV2.txt";
private static String inFile20 = "data\\mrn.txt";
//Storage Container
private static String inFile24 = "data\\barcodes2.txt";
private static String inFile25 = "data\\StorgeContTemp.txt";
private static String inFile26 = "data\\StorageContNum.txt";
//Storage Container Capacity
private static String inFile27 = "data\\StorageDim.txt";
//Storage Type
private static String inFile32 = "data\\StorageType.txt";
private static String inFile33 = "data\\OneDimLab.txt";
private static String inFile34 = "data\\TwoDimLab.txt";
private static String inFile35 = "data\\DefaultTemp.txt";
private static String newFile32 = "data\\StorageTypeV2.txt";
private static String newFile33 = "data\\OneDimLabV2.txt";
private static String newFile34 = "data\\TwoDimLabV2.txt";
private static String newFile35 = "data\\DefaultTempV2.txt";
//DATA ARRAYS TO MANAGE THE INPUT DATA
//Specimen
public String[] dataarr = new String[500];
public String[] dataarr1 = new String[500];
public String[] dataarr2 = new String[500];
public String[] dataarr3 = new String[500];
public String[] dataarr4 = new String[500];
public String[] dataarr5 = new String[500];
public String[] dataarr6 = new String[500];
public String[] dataarr7 = new String[500];
//SpecimenChars
public String[] dataarr8 = new String[500];
public String[] dataarr9 = new String[500];
public String[] dataarr10 = new String[500];
//SpecimenCollectionGroup
public String[] dataarr11 = new String[500];
public String[] dataarr12 = new String[500];
//CollectionProtocolEvent
public String[] dataarr13 = new String[500];
public String[] dataarr14 = new String[500];
//CollectionProtocol
public String[] dataarr15 = new String[500];
public String[] dataarr16 = new String[500];
public String[] dataarr17 = new String[500];
public String[] dataarr18 = new String[500];
public String[] dataarr19 = new String[500];
public String[] dataarr20 = new String[500];
public String[] dataarr21 = new String[500];
//CollectionProtocolRegistration
public String[] dataarr22 = new String[500];
public String[] dataarr23 = new String[500];
//StorageContainer
public String[] dataarr27 = new String[500];
public String[] dataarr28 = new String[500];
public String[] dataarr29 = new String[500];
public String[] dataarr30 = new String[500];
public String[] dataarr31 = new String[500];
//StorageContainerCapacity
public String[] dataarr32 = new String[500];
public String[] dataarr33 = new String[500];
//StorageType
public String[] dataarr34 = new String[500];
public String[] dataarr35 = new String[500];
public String[] dataarr36 = new String[500];
public String[] dataarr37 = new String[500];
public SpecimenInsertTest(String sTestName) {
super(sTestName);
}
//test reading data files into an array and insert into db
public void testRead_Insert() throws Exception {
final boolean DEBUG = false;
CATissueCoreDataGenerator dg = new CATissueCoreDataGenerator();
if (DEBUG) System.out.println("Inside testReadFile()...");
dg.buildTwoDataFiles(maxrecs,inFile1,newFile1,inFile4,newFile4);
//Specimen
//SPECIMEN TYPE
dataarr1=dg.ReadFile(maxrecs,newFile1);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tSPECIMEN TYPE: " + dataarr1[row]);
}
}
dg.buildTwoDataFiles(maxrecs,inFile2,newFile2,inFile3,newFile3);
//SPECIMEN QUANTITY
dataarr2=dg.ReadFile(maxrecs,newFile2);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tSPECIMEN QUANTITY: " + dataarr2[row]);
}
}
//SPECIMEN QUANTITY AVAIL
dataarr3=dg.ReadFile(maxrecs,newFile3);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tSPECIMEN QUANTITY AVAIL: " + dataarr3[row]);
}
}
//SPECIMEN CMMT
dataarr4=dg.ReadFile(maxrecs,newFile4);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tSPECIMEN CMMT: " + dataarr4[row]);
}
}
//SPECIMEN BARCODE
dataarr5=dg.ReadFile(maxrecs,inFile5);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tSPECIMEN BARCODE: " + dataarr5[row]);
}
}
//PositionDimensionOne
dg.buildDataFile(inFile6, 1, 24);
dataarr6=dg.ReadFile(maxrecs,inFile6);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tPositionDimensionOne: " + dataarr6[row]);
}
}
//PositionDimensionTwo
dg.buildDataFile(inFile7, 1, 24);
dataarr7=dg.ReadFile(maxrecs,inFile7);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tPositionDimensionTwo: " + dataarr7[row]);
}
}
//SpecimenChar
//TISSUE SITE
dg.buildDataFile(maxrecs,inFile8,newFile8);
dataarr8=dg.ReadFile(maxrecs,newFile8);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tTISSUE SITE: " + dataarr8[row]);
}
}
//TISSUE SIDE
dg.buildDataFile(maxrecs,inFile9,newFile9);
dataarr9=dg.ReadFile(maxrecs,newFile9);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tTISSUE SIDE: " + dataarr9[row]);
}
}
//PATH STAT
dg.buildDataFile(maxrecs,inFile10,newFile10);
dataarr10=dg.ReadFile(maxrecs,newFile10);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tPATH STAT: " + dataarr10[row]);
}
}
//SpecimenCollectionGroup
//ClinicalDiag
dg.buildDataFile(maxrecs,inFile11,newFile11);
dataarr11=dg.ReadFile(maxrecs,newFile11);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tPATH STAT: " + dataarr11[row]);
}
}
//ClinicalStatus
dg.buildDataFile(maxrecs,inFile12,newFile12);
dataarr12=dg.ReadFile(maxrecs,newFile12);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tClinicalStatus: " + dataarr12[row]);
}
}
//CollectionProtocolEvent
//Clinical Status
dg.buildDataFile(maxrecs,inFile12,newFile12);
dataarr13=dg.ReadFile(maxrecs,newFile12);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tClinicalStatus: " + dataarr13[row]);
}
}
//StudyCalendarEventPoint
dg.buildDivByFiveFile(1000,10,200,inFile13);
dataarr14=dg.ReadFile(maxrecs,inFile13);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tStudyCalendarEventPoint: " + dataarr13[row]);
}
}
//CollectionProtocol
//DescriptionURL
dataarr15=dg.randomReadFile(maxrecs,inFile14);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tDescriptionURL: " + dataarr15[row]);
}
}
SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yyyy" );
Calendar cal = new GregorianCalendar();
//StartDate
dataarr20=dg.randomReadFile(maxrecs,inFile15);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tStartDate: " + dataarr20[row]);
}
}
//EndDate - match to start date
//So, get the start date and add 365 days
for (int row=0; row<dataarr20.length; row++) {
dataarr[row]=dataarr20[row];
}
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
cal.setTime(sdf.parse(dataarr[row]));
cal.add(GregorianCalendar.DATE,365);
//dataarr16[row]=String.valueOf(cal.getTime());
dataarr16[row] = sdf.format(cal.getTime());
//dataarr16[row]=DateFormat.getInstance().format(cal.getTime());
System.out.println("\t\t\tEndDate2: " + dataarr16[row]);
}
}
//Enrollment
dg.buildDivByFiveFile(1000,100,500,inFile16);
dataarr17=dg.ReadFile(maxrecs,inFile16);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tEnrollment: " + dataarr17[row]);
}
}
//IrbIdentifier
dataarr18=dg.randomReadFile(maxrecs,inFile17);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tIrbIdentifier: " + dataarr18[row]);
}
}
//build title and shorttitle at the same time
dg.buildTwoDataFiles(maxrecs,inFile18,newFile18,inFile19,newFile19);
//ShortTitle
dataarr19=dg.ReadFile(maxrecs,newFile18);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tShortTitle: " + dataarr19[row]);
}
}
//Title
dataarr21=dg.ReadFile(maxrecs,newFile19);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tTitle: " + dataarr21[row]);
}
}
//CollectionProtocolRegistration
//ProtocolParticipantIdentifier
dataarr22=dg.randomReadFile(maxrecs,inFile20);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tProtocolParticipantIdentifier: " + dataarr22[row]);
}
}
//RegistrationDate - match to start date
for (int row=0; row<dataarr20.length; row++) {
dataarr23[row]=dataarr20[row];
}
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tRegistrationDate: " + dataarr23[row]);
}
}
//StorageContainer
//BARCODES
dataarr27=dg.ReadFile(maxrecs,inFile24);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tBARCODES: " + dataarr27[row]);
}
}
//Number
dataarr28=dg.ReadFile(maxrecs,inFile26);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tStorageContainer#: " + dataarr28[row]);
}
}
//PositionDimensionOne
dataarr29=dg.ReadFile(maxrecs,inFile6);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tPositionDimensionOne: " + dataarr29[row]);
}
}
//PositionDimensionTwo
dataarr30=dg.ReadFile(maxrecs,inFile7);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tPositionDimensionTwo: " + dataarr30[row]);
}
}
//TempratureInCentigrade
dataarr31=dg.ReadFile(maxrecs,inFile25);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tTemprature: " + dataarr30[row]);
}
}
//StorageContainerCapacity
dg.buildDivByFiveFile(1000,10,200,inFile27);
//OneDimensionCapacity
dataarr32=dg.ReadFile(maxrecs,inFile27);
//TwoDimensionCapacity
dataarr33=dg.ReadFile(maxrecs,inFile27);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tONE DIMENSION: " + dataarr32[row]);
System.out.println("\t\t\tTWO DIMENSION: " + dataarr33[row]);
}
}
//StorageType
//keep type and temp files in sync
// dg.buildTwoDataFiles(maxrecs,inFile32,newFile32,inFile35,newFile35);
//DefaultTempratureInCentigrade
// dataarr34=dg.ReadFile(maxrecs,newFile35);
dataarr34=dg.ReadFile(maxrecs,inFile35);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tDefaultTempratureInCentigrade: " + dataarr34[row]);
}
}
//keep dimension label files in sync
dg.buildTwoDataFiles(maxrecs,inFile33,newFile33,inFile34,newFile34);
//OneDimensionLabel
dataarr35=dg.ReadFile(maxrecs,newFile33);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tOneDimLab: " + dataarr35[row]);
}
}
//TwoDimensionLabel
dataarr36=dg.ReadFile(maxrecs,newFile34);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tTwoDimLab: " + dataarr36[row]);
}
}
//Type
// dataarr37=dg.ReadFile(maxrecs,newFile32);
dataarr37=dg.ReadFile(maxrecs,inFile32);
if (DEBUG) {
for (int row=0; row<maxrecs; row++) {
System.out.println("\t\t\tStorage Type: " + dataarr37[row]);
}
}
if (DEBUG) System.out.println("\tBack Inside testReadFile()");
//Call the buildSpecimen method to actually insert the data contained in the arrays
dg.buildSpecimen(maxrecs,dataarr1,dataarr2,dataarr3,dataarr4,dataarr5,dataarr6,dataarr7,dataarr8,dataarr9,dataarr10,dataarr11,dataarr12,dataarr13,dataarr14,dataarr15,dataarr16,dataarr17,dataarr18,dataarr19,dataarr20,dataarr21,dataarr22,dataarr23,dataarr27,dataarr28,dataarr29,dataarr30,dataarr31,dataarr32,dataarr33,dataarr34,dataarr35,dataarr36,dataarr37);
if (DEBUG) System.out.println("\tEnd Of testReadFile...");
}
public static void main(String[] args) throws Exception
{
System.out.println("\tInside main...");
TestRunner runner = new TestRunner();
TestResult result = runner.doRun(new TestSuite(SpecimenInsertTest.class));
System.exit(result.errorCount() + result.failureCount());
}
}
| bsd-3-clause |
haoran10/mulan | spring-demo/springdemo-web/src/main/java/wang/conge/springdemo/config/AppCoreConfig.java | 388 | package wang.conge.springdemo.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({
DataSourceConfig.class,
MyBatisConfig.class,
})
@ComponentScan(AppConfigConstant.SERVICE_PACKAGE)
public class AppCoreConfig {
}
| bsd-3-clause |
vidarr/fulisp | doc/doxygen/html/stack_8c.js | 574 | var stack_8c =
[
[ "MODULE_NAME", "stack_8c.html#a14ded244c47bbba850a8a4be6d16c7e3", null ],
[ "stackCreate", "stack_8c.html#a6e31f664f04dbca98b0d06afecc7a4bc", null ],
[ "stackError", "stack_8c.html#a7e90b812609fc9ae4a7d218a646135b5", null ],
[ "stackFree", "stack_8c.html#aa53e7be1cd872c3dbf893442e2f875b0", null ],
[ "stackPop", "stack_8c.html#a57b0740adaba9de2999532644f39e8b6", null ],
[ "stackPush", "stack_8c.html#a9d9caea775cad3f1526829bdb978c91d", null ],
[ "stackResetError", "stack_8c.html#a4bde0e97215d9cfa779c43429143595a", null ]
]; | bsd-3-clause |
govdelivery/govdelivery-tms-ruby | lib/govdelivery/tms/resource/keyword.rb | 1315 | module GovDelivery::TMS #:nodoc:
# A Keyword is a word that TMS will detect in an incoming SMS message. Keywords can have Commands, and
# when an incoming text message has a keyword, TMS will execute the keyword's Commands. Keywords may
# also have a response text field. If the response text is not blank, the system will send an SMS reply to the user
# immediately with the given text.
#
# @attr name [String] The name of the keyword. The system will scan an incoming SMS for this string (in a case-insensitive manner).
# @attr response_text [String] (Optional) The static text with which to reply to an SMS to this keyword.
# This value can be blank, in which case the handset user will not receive a response.
# Note that all keyword commands will be executed, regardless of the value of response_text.
#
# @example
# keyword = client.keywords.build(:name => "HOWDY")
# keyword.post
# keyword.name = "INFO"
# keyword.response_text = "Please call our support staff at 1-555-555-5555"
# keyword.put
# keyword.delete
class Keyword
include InstanceResource
# @!parse attr_accessor :name, :response_text
writeable_attributes :name, :response_text
##
# A CollectionResource of Command objects
collection_attributes :commands
end
end
| bsd-3-clause |
inepex/ineform | ineframe/src/main/java/com/inepex/ineFrame/client/async/FullscreenStatusIndicator.java | 2987 | package com.inepex.ineFrame.client.async;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.InlineHTML;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Widget;
import com.inepex.ineFrame.client.i18n.IneFrameI18n;
public class FullscreenStatusIndicator extends Composite implements AsyncStatusIndicator {
private static FullscreenStatusIndicatorUiBinder uiBinder = GWT
.create(FullscreenStatusIndicatorUiBinder.class);
interface FullscreenStatusIndicatorUiBinder
extends UiBinder<Widget, FullscreenStatusIndicator> {}
@UiField
FlowPanel centerPanel;
private HTML generalLoadingMessage = null;
private int requestInProgressCounter = 0;
private int unconfirmedErrorCount = 0;
public FullscreenStatusIndicator() {
initWidget(uiBinder.createAndBindUi(this));
}
@Override
public void onAsyncRequestStarted(String loadingMessage) {
if (generalLoadingMessage == null) {
generalLoadingMessage = new HTML("<h1>" + IneFrameI18n.loading() + "</h1>");
centerPanel.add(generalLoadingMessage);
generalLoadingMessage.setVisible(false);
}
if (requestInProgressCounter == 0) {
RootPanel.get().add(this);
}
generalLoadingMessage.setVisible(true);
requestInProgressCounter++;
}
@Override
public void onGeneralFailure(String errorMessage) {
requestInProgressCounter--;
unconfirmedErrorCount++;
centerPanel.add(getErrorWidget(errorMessage));
updateVisiblityStates();
}
@Override
public void onSuccess(String successMessage) {
requestInProgressCounter--;
updateVisiblityStates();
}
private Widget getErrorWidget(String errorMsg) {
final FlowPanel fp = new FlowPanel();
Button confirmButton = new Button(IneFrameI18n.OK());
confirmButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
fp.removeFromParent();
unconfirmedErrorCount--;
updateVisiblityStates();
}
});
fp.add(new InlineHTML("<h2>" + errorMsg + "</h2>"));
fp.add(confirmButton);
return fp;
}
private void updateVisiblityStates() {
if (requestInProgressCounter == 0) {
generalLoadingMessage.setVisible(false);
if (unconfirmedErrorCount == 0) {
this.removeFromParent();
}
}
}
}
| bsd-3-clause |
ericmjl/bokeh | bokeh/protocol/__init__.py | 3745 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-----------------------------------------------------------------------------
''' Implement and provide message protocols for communication between Bokeh
Servers and clients.
'''
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
import logging # isort:skip
log = logging.getLogger(__name__)
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# External imports
from tornado.escape import json_decode
# Bokeh imports
from . import messages
from .exceptions import ProtocolError
from .messages.ack import ack
from .messages.error import error
from .messages.ok import ok
from .messages.patch_doc import patch_doc
from .messages.pull_doc_reply import pull_doc_reply
from .messages.pull_doc_req import pull_doc_req
from .messages.push_doc import push_doc
from .messages.server_info_reply import server_info_reply
from .messages.server_info_req import server_info_req
#-----------------------------------------------------------------------------
# Globals and constants
#-----------------------------------------------------------------------------
__all__ = (
'Protocol',
)
SPEC = {
"ACK": ack,
"ERROR": error,
"OK": ok,
'PATCH-DOC': patch_doc,
'PULL-DOC-REPLY': pull_doc_reply,
'PULL-DOC-REQ': pull_doc_req,
'PUSH-DOC': push_doc,
'SERVER-INFO-REPLY': server_info_reply,
'SERVER-INFO-REQ': server_info_req,
}
#-----------------------------------------------------------------------------
# General API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Dev API
#-----------------------------------------------------------------------------
class Protocol(object):
''' Provide a message factory for the Bokeh Server message protocol.
'''
def __init__(self):
self._messages = SPEC
def __repr__(self):
return "Protocol()"
def create(self, msgtype, *args, **kwargs):
''' Create a new Message instance for the given type.
Args:
msgtype (str) :
'''
if msgtype not in self._messages:
raise ProtocolError("Unknown message type %r for Bokeh protocol" % msgtype)
return self._messages[msgtype].create(*args, **kwargs)
def assemble(self, header_json, metadata_json, content_json):
''' Create a Message instance assembled from json fragments.
Args:
header_json (``JSON``) :
metadata_json (``JSON``) :
content_json (``JSON``) :
Returns:
message
'''
header = json_decode(header_json)
if 'msgtype' not in header:
log.error("Bad header with no msgtype was: %r", header)
raise ProtocolError("No 'msgtype' in header")
return self._messages[header['msgtype']].assemble(
header_json, metadata_json, content_json
)
#-----------------------------------------------------------------------------
# Private API
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Code
#-----------------------------------------------------------------------------
| bsd-3-clause |
rubenvb/skia | docs/examples/Surface_MakeFromBackendTextureAsRenderTarget.cpp | 1040 | #if 0 // Disabled until updated to use current API.
// Copyright 2019 Google LLC.
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
#include "fiddle/examples.h"
// HASH=5e87093b9cbe95124ae14cbe77091eb7
REG_FIDDLE(Surface_MakeFromBackendTextureAsRenderTarget, 256, 256, false, 3) {
void draw(SkCanvas* canvas) {
SkPaint paint;
paint.setTextSize(32);
GrContext* context = canvas->getGrContext();
if (!context) {
canvas->drawString("GPU only!", 20, 40, paint);
return;
}
sk_sp<SkSurface> gpuSurface = SkSurface::MakeFromBackendTextureAsRenderTarget(
context, backEndTexture, kTopLeft_GrSurfaceOrigin, 0,
kRGBA_8888_SkColorType, nullptr, nullptr);
auto surfaceCanvas = gpuSurface->getCanvas();
surfaceCanvas->drawString("GPU rocks!", 20, 40, paint);
sk_sp<SkImage> image(gpuSurface->makeImageSnapshot());
canvas->drawImage(image, 0, 0);
}
} // END FIDDLE
#endif // Disabled until updated to use current API.
| bsd-3-clause |
samanalysis/twstools | src/tws_query.cpp | 3055 | /*** tws_query.cpp -- structs for IB/API requests
*
* Copyright (C) 2010-2013 Ruediger Meier
*
* Author: Ruediger Meier <sweet_f_a@gmx.de>
*
* This file is part of twstools.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the author nor the names of any contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 "tws_query.h"
#include <stdio.h>
const IB::Contract& ContractDetailsRequest::ibContract() const
{
return _ibContract;
}
bool ContractDetailsRequest::initialize( const IB::Contract& c )
{
_ibContract = c;
return true;
}
HistRequest::HistRequest()
{
useRTH = 0;
formatDate = 0; // set invalid (IB allows 1 or 2)
}
bool HistRequest::initialize( const IB::Contract& c, const std::string &e,
const std::string &d, const std::string &b,
const std::string &w, int u, int f )
{
ibContract = c;
endDateTime = e;
durationStr = d;
barSizeSetting = b;
whatToShow = w;
useRTH = u;
formatDate = f;
return true;
}
std::string HistRequest::toString() const
{
char buf_c[512];
char buf_a[1024];
snprintf( buf_c, sizeof(buf_c), "%s\t%s\t%s\t%s\t%s\t%g\t%s",
ibContract.symbol.c_str(),
ibContract.secType.c_str(),
ibContract.exchange.c_str(),
ibContract.currency.c_str(),
ibContract.expiry.c_str(),
ibContract.strike,
ibContract.right.c_str() );
snprintf( buf_a, sizeof(buf_a), "%s\t%s\t%s\t%s\t%d\t%d\t%s",
endDateTime.c_str(),
durationStr.c_str(),
barSizeSetting.c_str(),
whatToShow.c_str(),
useRTH,
formatDate,
buf_c );
return std::string(buf_a);
}
AccStatusRequest::AccStatusRequest() :
subscribe(true)
{
}
PlaceOrder::PlaceOrder() :
orderId(0),
time_sent(0)
{
}
MktDataRequest::MktDataRequest() :
snapshot(false)
{
}
| bsd-3-clause |
grani/grpc | src/php/lib/Grpc/AbstractCall.php | 5551 | <?php
/*
*
* Copyright 2015, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
namespace Grpc;
/**
* Class AbstractCall.
* @package Grpc
*/
abstract class AbstractCall
{
/**
* @var Call
*/
protected $call;
protected $deserialize;
protected $metadata;
protected $trailing_metadata;
/**
* Create a new Call wrapper object.
*
* @param Channel $channel The channel to communicate on
* @param string $method The method to call on the
* remote server
* @param callback $deserialize A callback function to deserialize
* the response
* @param array $options Call options (optional)
*/
public function __construct(Channel $channel,
$method,
$deserialize,
array $options = [])
{
if (array_key_exists('timeout', $options) &&
is_numeric($timeout = $options['timeout'])
) {
$now = Timeval::now();
$delta = new Timeval($timeout);
$deadline = $now->add($delta);
} else {
$deadline = Timeval::infFuture();
}
$this->call = new Call($channel, $method, $deadline);
$this->deserialize = $deserialize;
$this->metadata = null;
$this->trailing_metadata = null;
if (array_key_exists('call_credentials_callback', $options) &&
is_callable($call_credentials_callback =
$options['call_credentials_callback'])
) {
$call_credentials = CallCredentials::createFromPlugin(
$call_credentials_callback
);
$this->call->setCredentials($call_credentials);
}
}
/**
* @return mixed The metadata sent by the server
*/
public function getMetadata()
{
return $this->metadata;
}
/**
* @return mixed The trailing metadata sent by the server
*/
public function getTrailingMetadata()
{
return $this->trailing_metadata;
}
/**
* @return string The URI of the endpoint
*/
public function getPeer()
{
return $this->call->getPeer();
}
/**
* Cancels the call.
*/
public function cancel()
{
$this->call->cancel();
}
/**
* Serialize a message to the protobuf binary format.
*
* @param mixed $data The Protobuf message
*
* @return string The protobuf binary format
*/
protected function _serializeMessage($data)
{
// Proto3 implementation
if (method_exists($data, 'encode')) {
return $data->encode();
} else if (method_exists($data, 'serializeToString')) {
return $data->serializeToString();
}
// Protobuf-PHP implementation
return $data->serialize();
}
/**
* Deserialize a response value to an object.
*
* @param string $value The binary value to deserialize
*
* @return mixed The deserialized value
*/
protected function _deserializeResponse($value)
{
if ($value === null) {
return;
}
// Proto3 implementation
if (is_array($this->deserialize)) {
list($className, $deserializeFunc) = $this->deserialize;
$obj = new $className();
if (method_exists($obj, $deserializeFunc)) {
$obj->$deserializeFunc($value);
} else {
$obj->mergeFromString($value);
}
return $obj;
}
// Protobuf-PHP implementation
return call_user_func($this->deserialize, $value);
}
/**
* Set the CallCredentials for the underlying Call.
*
* @param CallCredentials $call_credentials The CallCredentials object
*/
public function setCallCredentials($call_credentials)
{
$this->call->setCredentials($call_credentials);
}
}
| bsd-3-clause |
seanogden/wtf | client/message_hyperdex_del.cc | 2299 | // Copyright (c) 2011-2013, Cornell University
// 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 WTF nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "common/macros.h"
#include "client/message_hyperdex_del.h"
using wtf::message_hyperdex_del;
message_hyperdex_del :: message_hyperdex_del(client* cl,
const char* space,
const char* key)
: message(cl, OPCODE_HYPERDEX_DEL)
, m_space(space)
, m_key(key)
, m_status(HYPERDEX_CLIENT_GARBAGE)
{
TRACE;
}
message_hyperdex_del :: ~message_hyperdex_del() throw()
{
TRACE;
}
int64_t
message_hyperdex_del :: send()
{
TRACE;
hyperdex::Client* hc = &m_cl->m_hyperdex_client;
m_reqid = hc->del(m_space.c_str(), m_key.data(), m_key.size(),
&m_status);
return m_reqid;
}
| bsd-3-clause |
vontrapp/hubroid | src/net/idlesoft/android/apps/github/activities/Search.java | 1605 | /**
* Hubroid - A GitHub app for Android
*
* Copyright (c) 2011 Eddie Ringle.
*
* Licensed under the New BSD License.
*/
package net.idlesoft.android.apps.github.activities;
import net.idlesoft.android.apps.github.R;
import net.idlesoft.android.apps.github.activities.tabs.SearchRepos;
import net.idlesoft.android.apps.github.activities.tabs.SearchUsers;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class Search extends BaseTabActivity {
private static final String TAG_SEARCH_REPOS = "search_repos";
private static final String TAG_SEARCH_USERS = "search_users";
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if (resultCode == 5005) {
Toast.makeText(Search.this, "That user has recently been deleted.", Toast.LENGTH_SHORT)
.show();
}
}
@Override
public void onCreate(final Bundle icicle) {
super.onCreate(icicle, R.layout.search);
setupActionBar(false);
final Intent intent = new Intent(Search.this, SearchRepos.class);
mTabHost.addTab(mTabHost.newTabSpec(TAG_SEARCH_REPOS)
.setIndicator(buildIndicator(R.string.search_repos)).setContent(intent));
intent.setClass(getApplicationContext(), SearchUsers.class);
mTabHost.addTab(mTabHost.newTabSpec(TAG_SEARCH_USERS)
.setIndicator(buildIndicator(R.string.search_users)).setContent(intent));
}
@Override
public void onResume() {
super.onResume();
}
}
| bsd-3-clause |
saem/hairpiece | frontend/src/http/index.js | 953 | import reqwest from 'reqwest';
import Kefir from 'kefir';
const mockApiBody = {
"links": {
"self": "https://www.hairpiece.com/api",
"user": "https://www.hairpiece.com/api/users/243",
"meetings": "https://www.hairpiece.com/api/users/243/meetings",
"settings": "https://www.hairpiece.com/api/users/243/settings",
"logout": "https://www.hairpiece.com/api/logout"
},
"data": {
"type": "api",
"id": "",
"attributes": {
"version": "8bbc4a48fc592bf3e440d6bc8e8fc11d734eb2dd",
"updated": "2015-11-30T11:41:29Z",
"userTrace": "session-id.user-id.service-id1"
}
}
};
export const initApi = () => (Kefir.later(100, mockApiBody));
const prodInitApi = () => (Kefir.stream(emitter => {
const request = reqwest({
url: "https://www.hairpiece.com/api",
success: emitter.emit,
error: emitter.error,
complete: emitter.end
});
return () => { request.abort(); }
}));
| bsd-3-clause |
LindsayBradford/PersonalFinancier | src/main/java/blacksmyth/personalfinancier/control/inflation/command/ChangeInflationValueCommand.java | 2057 | /**
* Copyright (c) 2012, Lindsay Bradford and other Contributors.
* All rights reserved.
*
* This program and the accompanying materials are made available
* under the terms of the BSD 3-Clause licence which accompanies
* this distribution, and is available at
* http://opensource.org/licenses/BSD-3-Clause
*/
package blacksmyth.personalfinancier.control.inflation.command;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import blacksmyth.personalfinancier.model.inflation.InflationModel;
public class ChangeInflationValueCommand extends AbstractInflationCommand {
private InflationModel model;
private int inflationEntryIndex;
private double preCommandValue;
private double postCommandValue;
public static ChangeInflationValueCommand doCmd(InflationModel model, int inflationEntryIndex,
double postCommandValue) {
ChangeInflationValueCommand command = new ChangeInflationValueCommand(
model,
inflationEntryIndex,
model.getInflationList().get(inflationEntryIndex).getCPIValue(),
postCommandValue
);
command.redo();
return command;
}
protected ChangeInflationValueCommand(InflationModel model, int inflationEntryIndex,
double preCommandValue, double postCommandValue) {
this.model = model;
this.inflationEntryIndex = inflationEntryIndex;
this.preCommandValue = preCommandValue;
this.postCommandValue = postCommandValue;
}
@Override
public boolean isSignificant() {
if (this.preCommandValue == this.postCommandValue) {
return false;
}
return true;
}
@Override
public void redo() throws CannotRedoException {
model.setInflationEntryValue(
inflationEntryIndex,
postCommandValue
);
}
@Override
public void undo() throws CannotUndoException {
model.setInflationEntryValue(
inflationEntryIndex,
preCommandValue
);
}
}
| bsd-3-clause |
arrai/mumble-record | src/mumble/AudioOutput.cpp | 32295 | /* Copyright (C) 2005-2010, Thorvald Natvig <thorvald@natvig.com>
Copyright (C) 2009, Stefan Hacker <dd0t@users.sourceforge.net>
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 the Mumble Developers 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 FOUNDATION 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 "AudioOutput.h"
#include "AudioInput.h"
#include "User.h"
#include "Global.h"
#include "Message.h"
#include "Plugins.h"
#include "PacketDataStream.h"
#include "ServerHandler.h"
#include "VoiceRecorder.h"
// Remember that we cannot use static member classes that are not pointers, as the constructor
// for AudioOutputRegistrar() might be called before they are initialized, as the constructor
// is called from global initialization.
// Hence, we allocate upon first call.
QMap<QString, AudioOutputRegistrar *> *AudioOutputRegistrar::qmNew;
QString AudioOutputRegistrar::current = QString();
AudioOutputRegistrar::AudioOutputRegistrar(const QString &n, int p) : name(n), priority(p) {
if (! qmNew)
qmNew = new QMap<QString, AudioOutputRegistrar *>();
qmNew->insert(name,this);
}
AudioOutputRegistrar::~AudioOutputRegistrar() {
qmNew->remove(name);
}
AudioOutputPtr AudioOutputRegistrar::newFromChoice(QString choice) {
if (! qmNew)
return AudioOutputPtr();
if (!choice.isEmpty() && qmNew->contains(choice)) {
g.s.qsAudioOutput = choice;
current = choice;
return AudioOutputPtr(qmNew->value(choice)->create());
}
choice = g.s.qsAudioOutput;
if (qmNew->contains(choice)) {
current = choice;
return AudioOutputPtr(qmNew->value(choice)->create());
}
AudioOutputRegistrar *r = NULL;
foreach(AudioOutputRegistrar *aor, *qmNew)
if (!r || (aor->priority > r->priority))
r = aor;
if (r) {
current = r->name;
return AudioOutputPtr(r->create());
}
return AudioOutputPtr();
}
bool AudioOutputRegistrar::canMuteOthers() const {
return false;
}
bool AudioOutputRegistrar::usesOutputDelay() const {
return true;
}
bool AudioOutputRegistrar::canExclusive() const {
return false;
}
AudioOutputUser::AudioOutputUser(const QString name) : qsName(name) {
iBufferSize = 0;
pfBuffer = NULL;
pfVolume = NULL;
fPos[0]=fPos[1]=fPos[2]=0.0;
}
AudioOutputUser::~AudioOutputUser() {
delete [] pfBuffer;
delete [] pfVolume;
}
void AudioOutputUser::resizeBuffer(unsigned int newsize) {
if (newsize > iBufferSize) {
float *n = new float[newsize];
if (pfBuffer) {
memcpy(n, pfBuffer, sizeof(float) * iBufferSize);
delete [] pfBuffer;
}
pfBuffer = n;
iBufferSize = newsize;
}
}
SoundFile::SoundFile(const QString &fname) {
siInfo.frames = 0 ;
siInfo.channels = 1 ;
siInfo.samplerate = SAMPLE_RATE ;
siInfo.samplerate = 0 ;
siInfo.sections = 0 ;
siInfo.seekable = 0 ;
sfFile = NULL;
qfFile.setFileName(fname);
if (qfFile.open(QIODevice::ReadOnly)) {
static SF_VIRTUAL_IO svi = {&SoundFile::vio_get_filelen, &SoundFile::vio_seek, &SoundFile::vio_read, &SoundFile::vio_write, &SoundFile::vio_tell};
sfFile = sf_open_virtual(&svi, SFM_READ, &siInfo, this) ;
}
}
SoundFile::~SoundFile() {
if (sfFile)
sf_close(sfFile);
}
bool SoundFile::isOpen() const {
return (sfFile != NULL) && qfFile.isOpen();
}
int SoundFile::channels() const {
return siInfo.channels;
}
int SoundFile::samplerate() const {
return siInfo.samplerate;
}
int SoundFile::error() const {
return sf_error(sfFile);
}
QString SoundFile::strError() const {
return QLatin1String(sf_strerror(sfFile));
}
sf_count_t SoundFile::seek(sf_count_t frames, int whence) {
return sf_seek(sfFile, frames, whence);
}
sf_count_t SoundFile::read(float *ptr, sf_count_t items) {
return sf_read_float(sfFile, ptr, items);
}
sf_count_t SoundFile::vio_get_filelen(void *user_data) {
SoundFile *sf = reinterpret_cast<SoundFile *>(user_data);
if (! sf->qfFile.isOpen())
return -1;
return (sf->qfFile.size());
}
sf_count_t SoundFile::vio_seek(sf_count_t offset, int whence, void *user_data) {
SoundFile *sf = reinterpret_cast<SoundFile *>(user_data);
if (! sf->qfFile.isOpen())
return -1;
if (whence == SEEK_SET) {
sf->qfFile.seek(offset);
} else if (whence == SEEK_END) {
sf->qfFile.seek(sf->qfFile.size() - offset);
} else {
sf->qfFile.seek(sf->qfFile.pos() + offset);
}
return sf->qfFile.pos();
}
sf_count_t SoundFile::vio_read(void *ptr, sf_count_t count, void *user_data) {
SoundFile *sf = reinterpret_cast<SoundFile *>(user_data);
if (! sf->qfFile.isOpen())
return -1;
return sf->qfFile.read(reinterpret_cast<char *>(ptr), count);
}
sf_count_t SoundFile::vio_write(const void *ptr, sf_count_t count, void *user_data) {
SoundFile *sf = reinterpret_cast<SoundFile *>(user_data);
if (! sf->qfFile.isOpen())
return -1;
return sf->qfFile.write(reinterpret_cast<const char *>(ptr), count);
}
sf_count_t SoundFile::vio_tell(void *user_data) {
SoundFile *sf = reinterpret_cast<SoundFile *>(user_data);
if (! sf->qfFile.isOpen())
return -1;
return sf->qfFile.pos();
}
AudioOutputSample::AudioOutputSample(const QString &name, SoundFile *psndfile, bool loop, unsigned int freq) : AudioOutputUser(name) {
int err;
sfHandle = psndfile;
iOutSampleRate = freq;
// Check if the file is good
if (sfHandle->channels() <= 0 || sfHandle->channels() > 2) {
sfHandle = NULL;
return;
}
/* qWarning() << "Channels: " << sfHandle->channels();
qWarning() << "Samplerate: " << sfHandle->samplerate();
qWarning() << "Target Sr.: " << freq;
qWarning() << "Format: " << sfHandle->format() << endl; */
// If the frequencies don't match initialize the resampler
if (sfHandle->samplerate() != static_cast<int>(freq)) {
srs = speex_resampler_init(1, sfHandle->samplerate(), iOutSampleRate, 3, &err);
if (err != RESAMPLER_ERR_SUCCESS) {
qWarning() << "Initialize " << sfHandle->samplerate() << " to " << iOutSampleRate << " resampler failed!";
srs = NULL;
sfHandle = NULL;
return;
}
} else {
srs = NULL;
}
iLastConsume = iBufferFilled = 0;
bLoop = loop;
bEof = false;
}
AudioOutputSample::~AudioOutputSample() {
if (srs)
speex_resampler_destroy(srs);
delete sfHandle;
sfHandle = NULL;
}
SoundFile* AudioOutputSample::loadSndfile(const QString &filename) {
SoundFile *sf;
// Create the filehandle and do a quick check if everything is ok
sf = new SoundFile(filename);
if (! sf->isOpen()) {
qWarning() << "File " << filename << " failed to open";
delete sf;
return NULL;
}
if (sf->error() != SF_ERR_NO_ERROR) {
qWarning() << "File " << filename << " couldn't be loaded: " << sf->strError();
delete sf;
return NULL;
}
if (sf->channels() <= 0 || sf->channels() > 2) {
qWarning() << "File " << filename << " contains " << sf->channels() << " Channels, only 1 or 2 are supported.";
delete sf;
return NULL;
}
return sf;
}
QString AudioOutputSample::browseForSndfile() {
SoundFile *sf = NULL;
QString file = QFileDialog::getOpenFileName(NULL, tr("Choose sound file"), QString(), QLatin1String("*.wav *.ogg *.ogv *.oga *.flac"));
if (! file.isEmpty()) {
if ((sf = AudioOutputSample::loadSndfile(file)) == NULL) {
QMessageBox::critical(NULL,
tr("Invalid sound file"),
tr("The file '%1' cannot be used by Mumble. Please select a file with a compatible format and encoding.").arg(file));
return QString();
}
delete sf;
}
return file;
}
bool AudioOutputSample::needSamples(unsigned int snum) {
// Forward the buffer
for (unsigned int i=iLastConsume;i<iBufferFilled;++i)
pfBuffer[i-iLastConsume]=pfBuffer[i];
iBufferFilled -= iLastConsume;
iLastConsume = snum;
// Check if we can satisfy request with current buffer
if (iBufferFilled >= snum)
return true;
// Calculate the required buffersize to hold the results
unsigned int iInputFrames = iroundf(ceilf(static_cast<float>(snum * sfHandle->samplerate()) / static_cast<float>(iOutSampleRate)));
unsigned int iInputSamples = iInputFrames * sfHandle->channels();
float *pOut;
bool mix = sfHandle->channels() > 1;
STACKVAR(float, fOut, iInputSamples);
STACKVAR(float, fMix, iInputFrames);
bool eof = false;
sf_count_t read;
do {
resizeBuffer(iBufferFilled + snum);
// If we need to resample or mix write to the buffer on stack
pOut = (srs || mix) ? fOut : pfBuffer + iBufferFilled;
// Try to read all samples needed to satifsy this request
if ((read = sfHandle->read(pOut, iInputSamples)) < iInputSamples) {
if (sfHandle->error() != SF_ERR_NO_ERROR || !bLoop) {
// We reached the eof or encountered an error, stuff with zeroes
memset(pOut, 0, sizeof(float) * (iInputSamples - read));
read = iInputSamples;
eof = true;
} else {
sfHandle->seek(SEEK_SET, 0);
}
}
if (mix) { // Mix the channels (only two channels)
read /= 2;
// If we need to resample after this write to extra buffer
pOut = srs ? fMix : pfBuffer + iBufferFilled;
for (unsigned int i = 0; i < read; i++)
pOut[i] = (fOut[i*2] + fOut[i*2 + 1]) * 0.5f;
}
spx_uint32_t inlen = static_cast<unsigned int>(read);
spx_uint32_t outlen = snum;
if (srs) // If necessary resample
speex_resampler_process_float(srs, 0, pOut, &inlen, pfBuffer + iBufferFilled, &outlen);
iBufferFilled += outlen;
} while (iBufferFilled < snum);
if (eof && !bEof) {
emit playbackFinished();
bEof = true;
}
return !eof;
}
AudioOutputSpeech::AudioOutputSpeech(ClientUser *user, unsigned int freq, MessageHandler::UDPMessageType type) : AudioOutputUser(user->qsName) {
int err;
p = user;
umtType = type;
unsigned int srate = 0;
cCodec = NULL;
cdDecoder = NULL;
if (umtType != MessageHandler::UDPVoiceSpeex) {
srate = SAMPLE_RATE;
iFrameSize = srate / 100;
dsSpeex = NULL;
} else {
speex_bits_init(&sbBits);
dsSpeex = speex_decoder_init(speex_lib_get_mode(SPEEX_MODEID_UWB));
int iArg=1;
speex_decoder_ctl(dsSpeex, SPEEX_SET_ENH, &iArg);
speex_decoder_ctl(dsSpeex, SPEEX_GET_FRAME_SIZE, &iFrameSize);
speex_decoder_ctl(dsSpeex, SPEEX_GET_SAMPLING_RATE, &srate);
}
if (freq != srate)
srs = speex_resampler_init(1, srate, freq, 3, &err);
else
srs = NULL;
iOutputSize = iroundf(ceilf(static_cast<float>(iFrameSize * freq) / static_cast<float>(srate)));
iBufferOffset = iBufferFilled = iLastConsume = 0;
bLastAlive = true;
iMissCount = 0;
iMissedFrames = 0;
ucFlags = 0xFF;
jbJitter = jitter_buffer_init(iFrameSize);
int margin = g.s.iJitterBufferSize * iFrameSize;
jitter_buffer_ctl(jbJitter, JITTER_BUFFER_SET_MARGIN, &margin);
fFadeIn = new float[iFrameSize];
fFadeOut = new float[iFrameSize];
float mul = static_cast<float>(M_PI / (2.0 * static_cast<double>(iFrameSize)));
for (unsigned int i=0;i<iFrameSize;++i)
fFadeIn[i] = fFadeOut[iFrameSize-i-1] = sinf(static_cast<float>(i) * mul);
}
AudioOutputSpeech::~AudioOutputSpeech() {
if (cdDecoder) {
cCodec->celt_decoder_destroy(cdDecoder);
} else if (dsSpeex) {
speex_bits_destroy(&sbBits);
speex_decoder_destroy(dsSpeex);
}
if (srs)
speex_resampler_destroy(srs);
jitter_buffer_destroy(jbJitter);
delete [] fFadeIn;
delete [] fFadeOut;
}
void AudioOutputSpeech::addFrameToBuffer(const QByteArray &qbaPacket, unsigned int iSeq) {
QMutexLocker lock(&qmJitter);
if (qbaPacket.size() < 2)
return;
PacketDataStream pds(qbaPacket);
pds.next();
int frames = 0;
unsigned int header = 0;
do {
header = static_cast<unsigned char>(pds.next());
frames++;
pds.skip(header & 0x7f);
} while ((header & 0x80) && pds.isValid());
if (pds.isValid()) {
JitterBufferPacket jbp;
jbp.data = const_cast<char *>(qbaPacket.constData());
jbp.len = qbaPacket.size();
jbp.span = iFrameSize * frames;
jbp.timestamp = iFrameSize * iSeq;
if (g.s.bUsage && (umtType != MessageHandler::UDPVoiceSpeex) && p && ! p->qsHash.isEmpty() && (p->qlTiming.count() < 3000)) {
QMutexLocker qml(& p->qmTiming);
ClientUser::JitterRecord jr;
jr.iSequence = iSeq;
jr.iFrames = frames;
jr.uiElapsed = p->tTiming.restart();
if (! p->qlTiming.isEmpty()) {
jr.iFrames -= p->iFrames;
jr.iSequence -= p->iSequence + p->iFrames;
}
p->iFrames = frames;
p->iSequence = iSeq;
p->qlTiming.append(jr);
}
jitter_buffer_put(jbJitter, &jbp);
}
}
bool AudioOutputSpeech::needSamples(unsigned int snum) {
for (unsigned int i=iLastConsume;i<iBufferFilled;++i)
pfBuffer[i-iLastConsume]=pfBuffer[i];
iBufferFilled -= iLastConsume;
iLastConsume = snum;
if (iBufferFilled >= snum)
return bLastAlive;
float *pOut;
STACKVAR(float, fOut, iFrameSize + 4096);
bool nextalive = bLastAlive;
while (iBufferFilled < snum) {
resizeBuffer(iBufferFilled + iOutputSize);
pOut = (srs) ? fOut : (pfBuffer + iBufferFilled);
if (! bLastAlive) {
memset(pOut, 0, iFrameSize * sizeof(float));
} else {
if (p == &LoopUser::lpLoopy) {
LoopUser::lpLoopy.fetchFrames();
}
int avail = 0;
int ts = jitter_buffer_get_pointer_timestamp(jbJitter);
jitter_buffer_ctl(jbJitter, JITTER_BUFFER_GET_AVAILABLE_COUNT, &avail);
if (p && (ts == 0)) {
int want = iroundf(p->fAverageAvailable);
if (avail < want) {
++iMissCount;
if (iMissCount < 20) {
memset(pOut, 0, iFrameSize * sizeof(float));
goto nextframe;
}
}
}
if (qlFrames.isEmpty()) {
QMutexLocker lock(&qmJitter);
char data[4096];
JitterBufferPacket jbp;
jbp.data = data;
jbp.len = 4096;
spx_int32_t startofs = 0;
if (jitter_buffer_get(jbJitter, &jbp, iFrameSize, &startofs) == JITTER_BUFFER_OK) {
PacketDataStream pds(jbp.data, jbp.len);
iMissCount = 0;
ucFlags = static_cast<unsigned char>(pds.next());
bHasTerminator = false;
unsigned int header = 0;
do {
header = static_cast<unsigned int>(pds.next());
if (header)
qlFrames << pds.dataBlock(header & 0x7f);
else
bHasTerminator = true;
} while ((header & 0x80) && pds.isValid());
if (pds.left()) {
pds >> fPos[0];
pds >> fPos[1];
pds >> fPos[2];
} else {
fPos[0] = fPos[1] = fPos[2] = 0.0f;
}
if (p) {
float a = static_cast<float>(avail);
if (avail >= p->fAverageAvailable)
p->fAverageAvailable = a;
else
p->fAverageAvailable *= 0.99f;
}
} else {
jitter_buffer_update_delay(jbJitter, &jbp, NULL);
iMissCount++;
if (iMissCount > 10)
nextalive = false;
}
}
if (! qlFrames.isEmpty()) {
QByteArray qba = qlFrames.takeFirst();
if (umtType != MessageHandler::UDPVoiceSpeex) {
int wantversion = (umtType == MessageHandler::UDPVoiceCELTAlpha) ? g.iCodecAlpha : g.iCodecBeta;
if ((p == &LoopUser::lpLoopy) && (! g.qmCodecs.isEmpty())) {
QMap<int, CELTCodec *>::const_iterator i = g.qmCodecs.constEnd();
--i;
wantversion = i.key();
}
if (cCodec && (cCodec->bitstreamVersion() != wantversion)) {
cCodec->celt_decoder_destroy(cdDecoder);
cdDecoder = NULL;
}
if (! cCodec) {
cCodec = g.qmCodecs.value(wantversion);
if (cCodec) {
cdDecoder = cCodec->decoderCreate();
}
}
if (cdDecoder)
cCodec->decode_float(cdDecoder, qba.isEmpty() ? NULL : reinterpret_cast<const unsigned char *>(qba.constData()), qba.size(), pOut);
else
memset(pOut, 0, sizeof(float) * iFrameSize);
} else {
if (qba.isEmpty()) {
speex_decode(dsSpeex, NULL, pOut);
} else {
speex_bits_read_from(&sbBits, qba.data(), qba.size());
speex_decode(dsSpeex, &sbBits, pOut);
}
for (unsigned int i=0;i<iFrameSize;++i)
pOut[i] *= (1.0f / 32767.f);
}
bool update = true;
if (p) {
float &fPowerMax = p->fPowerMax;
float &fPowerMin = p->fPowerMin;
float pow = 0.0f;
for (unsigned int i=0;i<iFrameSize;++i)
pow += pOut[i] * pOut[i];
pow = sqrtf(pow / static_cast<float>(iFrameSize));
if (pow >= fPowerMax) {
fPowerMax = pow;
} else {
if (pow <= fPowerMin) {
fPowerMin = pow;
} else {
fPowerMax = 0.99f * fPowerMax;
fPowerMin += 0.0001f * pow;
}
}
update = (pow < (fPowerMin + 0.01f * (fPowerMax - fPowerMin)));
}
if (qlFrames.isEmpty() && update)
jitter_buffer_update_delay(jbJitter, NULL, NULL);
if (qlFrames.isEmpty() && bHasTerminator)
nextalive = false;
} else {
if (umtType != MessageHandler::UDPVoiceSpeex) {
if (cdDecoder)
cCodec->decode_float(cdDecoder, NULL, 0, pOut);
else
memset(pOut, 0, sizeof(float) * iFrameSize);
} else {
speex_decode(dsSpeex, NULL, pOut);
for (unsigned int i=0;i<iFrameSize;++i)
pOut[i] *= (1.0f / 32767.f);
}
}
if (! nextalive) {
for (unsigned int i=0;i<iFrameSize;++i)
pOut[i] *= fFadeOut[i];
} else if (ts == 0) {
for (unsigned int i=0;i<iFrameSize;++i)
pOut[i] *= fFadeIn[i];
}
jitter_buffer_tick(jbJitter);
}
nextframe:
spx_uint32_t inlen = iFrameSize;
spx_uint32_t outlen = iOutputSize;
if (srs && bLastAlive)
speex_resampler_process_float(srs, 0, fOut, &inlen, pfBuffer + iBufferFilled, &outlen);
iBufferFilled += outlen;
}
if (p) {
Settings::TalkState ts;
if (! nextalive)
ucFlags = 0xFF;
switch (ucFlags) {
case 0:
ts = Settings::Talking;
break;
case 1:
ts = Settings::Shouting;
break;
case 0xFF:
ts = Settings::Passive;
break;
default:
ts = Settings::Whispering;
break;
}
p->setTalking(ts);
}
bool tmp = bLastAlive;
bLastAlive = nextalive;
return tmp;
}
AudioOutput::AudioOutput() {
iFrameSize = SAMPLE_RATE / 100;
bRunning = true;
iChannels = 0;
fSpeakers = NULL;
fSpeakerVolume = NULL;
bSpeakerPositional = NULL;
iMixerFreq = 0;
eSampleFormat = SampleFloat;
iSampleSize = 0;
}
AudioOutput::~AudioOutput() {
bRunning = false;
wait();
wipe();
delete [] fSpeakers;
delete [] fSpeakerVolume;
delete [] bSpeakerPositional;
}
// Here's the theory.
// We support sound "bloom"ing. That is, if sound comes directly from the left, if it is sufficiently
// close, we'll hear it full intensity from the left side, and "bloom" intensity from the right side.
float AudioOutput::calcGain(float dotproduct, float distance) {
float dotfactor = (dotproduct + 1.0f) / 2.0f;
float att;
// No distance attenuation
if (g.s.fAudioMaxDistVolume > 0.99f) {
att = qMin(1.0f, dotfactor + g.s.fAudioBloom);
} else if (distance < g.s.fAudioMinDistance) {
float bloomfac = g.s.fAudioBloom * (1.0f - distance/g.s.fAudioMinDistance);
att = qMin(1.0f, bloomfac + dotfactor);
} else {
float datt;
if (distance >= g.s.fAudioMaxDistance) {
datt = g.s.fAudioMaxDistVolume;
} else {
float mvol = g.s.fAudioMaxDistVolume;
if (mvol < 0.01f)
mvol = 0.01f;
float drel = (distance-g.s.fAudioMinDistance) / (g.s.fAudioMaxDistance - g.s.fAudioMinDistance);
datt = powf(10.0f, log10f(mvol) * drel);
}
att = datt * dotfactor;
}
return att;
}
void AudioOutput::wipe() {
foreach(AudioOutputUser *aop, qmOutputs)
removeBuffer(aop);
}
const float *AudioOutput::getSpeakerPos(unsigned int &speakers) {
if ((iChannels > 0) && fSpeakers) {
speakers = iChannels;
return fSpeakers;
}
return NULL;
}
AudioOutputSample *AudioOutput::playSample(const QString &filename, bool loop) {
SoundFile *handle;
handle = AudioOutputSample::loadSndfile(filename);
if (handle == NULL)
return NULL;
while ((iMixerFreq == 0) && isAlive()) {
#if QT_VERSION >= 0x040500
QThread::yieldCurrentThread();
#endif
}
if (! iMixerFreq)
return NULL;
qrwlOutputs.lockForWrite();
AudioOutputSample *aos = new AudioOutputSample(filename, handle, loop, iMixerFreq);
qmOutputs.insert(NULL, aos);
qrwlOutputs.unlock();
return aos;
}
void AudioOutput::addFrameToBuffer(ClientUser *user, const QByteArray &qbaPacket, unsigned int iSeq, MessageHandler::UDPMessageType type) {
if (iChannels == 0)
return;
qrwlOutputs.lockForRead();
AudioOutputSpeech *aop = dynamic_cast<AudioOutputSpeech *>(qmOutputs.value(user));
if (! aop || (aop->umtType != type)) {
qrwlOutputs.unlock();
if (aop)
removeBuffer(aop);
while ((iMixerFreq == 0) && isAlive()) {}
if (! iMixerFreq)
return;
qrwlOutputs.lockForWrite();
aop = new AudioOutputSpeech(user, iMixerFreq, type);
qmOutputs.replace(user, aop);
}
aop->addFrameToBuffer(qbaPacket, iSeq);
qrwlOutputs.unlock();
}
void AudioOutput::removeBuffer(const ClientUser *user) {
removeBuffer(qmOutputs.value(user));
}
void AudioOutput::removeBuffer(AudioOutputUser *aop) {
QWriteLocker locker(&qrwlOutputs);
QMultiHash<const ClientUser *, AudioOutputUser *>::iterator i;
for (i=qmOutputs.begin(); i != qmOutputs.end(); ++i) {
if (i.value() == aop) {
qmOutputs.erase(i);
delete aop;
break;
}
}
}
void AudioOutput::initializeMixer(const unsigned int *chanmasks, bool forceheadphone) {
delete fSpeakers;
delete bSpeakerPositional;
delete fSpeakerVolume;
fSpeakers = new float[iChannels * 3];
bSpeakerPositional = new bool[iChannels];
fSpeakerVolume = new float[iChannels];
memset(fSpeakers, 0, sizeof(float) * iChannels * 3);
memset(bSpeakerPositional, 0, sizeof(bool) * iChannels);
for (unsigned int i=0;i<iChannels;++i)
fSpeakerVolume[i] = 1.0f;
if (g.s.bPositionalAudio && (iChannels > 1)) {
for (unsigned int i=0;i<iChannels;i++) {
float *s = &fSpeakers[3*i];
bSpeakerPositional[i] = true;
switch (chanmasks[i]) {
case SPEAKER_FRONT_LEFT:
s[0] = -0.5f;
s[2] = 1.0f;
break;
case SPEAKER_FRONT_RIGHT:
s[0] = 0.5f;
s[2] = 1.0f;
break;
case SPEAKER_FRONT_CENTER:
s[2] = 1.0f;
break;
case SPEAKER_LOW_FREQUENCY:
break;
case SPEAKER_BACK_LEFT:
s[0] = -0.5f;
s[2] = -1.0f;
break;
case SPEAKER_BACK_RIGHT:
s[0] = 0.5f;
s[2] = -1.0f;
break;
case SPEAKER_FRONT_LEFT_OF_CENTER:
s[0] = -0.25;
s[2] = 1.0f;
break;
case SPEAKER_FRONT_RIGHT_OF_CENTER:
s[0] = 0.25;
s[2] = 1.0f;
break;
case SPEAKER_BACK_CENTER:
s[2] = -1.0f;
break;
case SPEAKER_SIDE_LEFT:
s[0] = -1.0f;
break;
case SPEAKER_SIDE_RIGHT:
s[0] = 1.0f;
break;
case SPEAKER_TOP_CENTER:
s[1] = 1.0f;
s[2] = 1.0f;
break;
case SPEAKER_TOP_FRONT_LEFT:
s[0] = -0.5f;
s[1] = 1.0f;
s[2] = 1.0f;
break;
case SPEAKER_TOP_FRONT_CENTER:
s[1] = 1.0f;
s[2] = 1.0f;
break;
case SPEAKER_TOP_FRONT_RIGHT:
s[0] = 0.5f;
s[1] = 1.0f;
s[2] = 1.0f;
break;
case SPEAKER_TOP_BACK_LEFT:
s[0] = -0.5f;
s[1] = 1.0f;
s[2] = -1.0f;
break;
case SPEAKER_TOP_BACK_CENTER:
s[1] = 1.0f;
s[2] = -1.0f;
break;
case SPEAKER_TOP_BACK_RIGHT:
s[0] = 0.5f;
s[1] = 1.0f;
s[2] = -1.0f;
break;
default:
bSpeakerPositional[i] = false;
fSpeakerVolume[i] = 0.0f;
qWarning("AudioOutput: Unknown speaker %d: %08x", i, chanmasks[i]);
break;
}
if (g.s.bPositionalHeadphone || forceheadphone) {
s[1] = 0.0f;
s[2] = 0.0f;
if (s[0] == 0.0f)
fSpeakerVolume[i] = 0.0f;
}
}
for (unsigned int i=0;i<iChannels;i++) {
float d = sqrtf(fSpeakers[3*i+0]*fSpeakers[3*i+0] + fSpeakers[3*i+1]*fSpeakers[3*i+1] + fSpeakers[3*i+2]*fSpeakers[3*i+2]);
if (d > 0.0f) {
fSpeakers[3*i+0] /= d;
fSpeakers[3*i+1] /= d;
fSpeakers[3*i+2] /= d;
}
}
}
iSampleSize = static_cast<int>(iChannels * ((eSampleFormat == SampleFloat) ? sizeof(float) : sizeof(short)));
qWarning("AudioOutput: Initialized %d channel %d hz mixer", iChannels, iMixerFreq);
}
bool AudioOutput::mix(void *outbuff, unsigned int nsamp) {
AudioOutputUser *aop;
QList<AudioOutputUser *> qlMix;
QList<AudioOutputUser *> qlDel;
if (g.s.fVolume < 0.01)
return false;
const float adjustFactor = std::pow(10, -18. / 20);
const float mul = g.s.fVolume;
const unsigned int nchan = iChannels;
VoiceRecorderPtr recorder;
if (g.sh) {
recorder = g.sh->recorder;
}
qrwlOutputs.lockForRead();
bool needAdjustment = false;
QMultiHash<const ClientUser *, AudioOutputUser *>::const_iterator i = qmOutputs.constBegin();
while (i != qmOutputs.constEnd()) {
AudioOutputUser *aop = i.value();
if (! aop->needSamples(nsamp)) {
qlDel.append(aop);
} else {
qlMix.append(aop);
// Set a flag if there is a priority speaker
if (i.key() && i.key()->bPrioritySpeaker)
needAdjustment = true;
}
++i;
}
if (! qlMix.isEmpty()) {
STACKVAR(float, speaker, iChannels*3);
STACKVAR(float, svol, iChannels);
STACKVAR(float, fOutput, iChannels * nsamp);
float *output = (eSampleFormat == SampleFloat) ? reinterpret_cast<float *>(outbuff) : fOutput;
bool validListener = false;
memset(output, 0, sizeof(float) * nsamp * iChannels);
boost::shared_array<float> recbuff;
if (recorder) {
recbuff = boost::shared_array<float>(new float[nsamp]);
memset(recbuff.get(), 0, sizeof(float) * nsamp);
}
for (unsigned int i=0;i<iChannels;++i)
svol[i] = mul * fSpeakerVolume[i];
if (g.s.bPositionalAudio && (iChannels > 1) && g.p->fetch() && (g.bPosTest || g.p->fCameraPosition[0] != 0 || g.p->fCameraPosition[1] != 0 || g.p->fCameraPosition[2] != 0)) {
float front[3] = { g.p->fCameraFront[0], g.p->fCameraFront[1], g.p->fCameraFront[2] };
float top[3] = { g.p->fCameraTop[0], g.p->fCameraTop[1], g.p->fCameraTop[2] };
// Front vector is dominant; if it's zero we presume all is zero.
float flen = sqrtf(front[0]*front[0]+front[1]*front[1]+front[2]*front[2]);
if (flen > 0.0f) {
front[0] *= (1.0f / flen);
front[1] *= (1.0f / flen);
front[2] *= (1.0f / flen);
float tlen = sqrtf(top[0]*top[0]+top[1]*top[1]+top[2]*top[2]);
if (tlen > 0.0f) {
top[0] *= (1.0f / tlen);
top[1] *= (1.0f / tlen);
top[2] *= (1.0f / tlen);
} else {
top[0] = 0.0f;
top[1] = 1.0f;
top[2] = 0.0f;
}
if (fabs(front[0] * top[0] + front[1] * top[1] + front[2] * top[2]) > 0.01f) {
// Not perpendicular. Assume Y up and rotate 90 degrees.
float azimuth = 0.0f;
if ((front[0] != 0.0f) || (front[2] != 0.0f))
azimuth = atan2f(front[2], front[0]);
float inclination = acosf(front[1]) - M_PI / 2;
top[0] = sinf(inclination)*cosf(azimuth);
top[1] = cosf(inclination);
top[2] = sinf(inclination)*sinf(azimuth);
}
} else {
front[0] = 0.0f;
front[1] = 0.0f;
front[2] = 1.0f;
top[0] = 0.0f;
top[1] = 1.0f;
top[2] = 0.0f;
}
// Calculate right vector as front X top
float right[3] = {top[1]*front[2] - top[2]*front[1], top[2]*front[0] - top[0]*front[2], top[0]*front[1] - top[1] * front[0] };
/*
qWarning("Front: %f %f %f", front[0], front[1], front[2]);
qWarning("Top: %f %f %f", top[0], top[1], top[2]);
qWarning("Right: %f %f %f", right[0], right[1], right[2]);
*/
// Rotate speakers to match orientation
for (unsigned int i=0;i<iChannels;++i) {
speaker[3*i+0] = fSpeakers[3*i+0] * right[0] + fSpeakers[3*i+1] * top[0] + fSpeakers[3*i+2] * front[0];
speaker[3*i+1] = fSpeakers[3*i+0] * right[1] + fSpeakers[3*i+1] * top[1] + fSpeakers[3*i+2] * front[1];
speaker[3*i+2] = fSpeakers[3*i+0] * right[2] + fSpeakers[3*i+1] * top[2] + fSpeakers[3*i+2] * front[2];
}
validListener = true;
}
foreach(aop, qlMix) {
const float * RESTRICT pfBuffer = aop->pfBuffer;
float volumeAdjustment = 1;
// We have at least one priority speaker
if (needAdjustment) {
AudioOutputSpeech *aos = qobject_cast<AudioOutputSpeech *>(aop);
// Exclude whispering people
if (aos && (aos->p->tsState == Settings::Talking || aos->p->tsState == Settings::Shouting)) {
// Adjust all non-priority speakers
if (!aos->p->bPrioritySpeaker)
volumeAdjustment = adjustFactor;
}
}
if (recorder) {
AudioOutputSpeech *aos = qobject_cast<AudioOutputSpeech *>(aop);
if (aos) {
for (unsigned int i = 0; i < nsamp; ++i) {
recbuff[i] += pfBuffer[i] * volumeAdjustment;
}
if (!recorder->getMixDown()) {
if (aos) {
recorder->addBuffer(aos->p, recbuff, nsamp);
} else {
// this should be unreachable
Q_ASSERT(false);
}
recbuff = boost::shared_array<float>(new float[nsamp]);
memset(recbuff.get(), 0, sizeof(float) * nsamp);
}
// Don't add the local audio to the real output
if (qobject_cast<RecordUser *>(aos->p)) {
continue;
}
}
}
if (validListener && ((aop->fPos[0] != 0.0f) || (aop->fPos[1] != 0.0f) || (aop->fPos[2] != 0.0f))) {
float dir[3] = { aop->fPos[0] - g.p->fCameraPosition[0], aop->fPos[1] - g.p->fCameraPosition[1], aop->fPos[2] - g.p->fCameraPosition[2] };
float len = sqrtf(dir[0] * dir[0] + dir[1] * dir[1] + dir[2] * dir[2]);
if (len > 0.0f) {
dir[0] /= len;
dir[1] /= len;
dir[2] /= len;
}
/*
qWarning("Voice pos: %f %f %f", aop->fPos[0], aop->fPos[1], aop->fPos[2]);
qWarning("Voice dir: %f %f %f", dir[0], dir[1], dir[2]);
*/
if (! aop->pfVolume) {
aop->pfVolume = new float[nchan];
for (unsigned int s=0;s<nchan;++s)
aop->pfVolume[s] = -1.0;
}
for (unsigned int s=0;s<nchan;++s) {
const float dot = bSpeakerPositional[s] ? dir[0] * speaker[s*3+0] + dir[1] * speaker[s*3+1] + dir[2] * speaker[s*3+2] : 1.0f;
const float str = svol[s] * calcGain(dot, len) * volumeAdjustment;
float * RESTRICT o = output + s;
const float old = (aop->pfVolume[s] >= 0.0) ? aop->pfVolume[s] : str;
const float inc = (str - old) / static_cast<float>(nsamp);
aop->pfVolume[s] = str;
/*
qWarning("%d: Pos %f %f %f : Dot %f Len %f Str %f", s, speaker[s*3+0], speaker[s*3+1], speaker[s*3+2], dot, len, str);
*/
if ((old >= 0.00000001f) || (str >= 0.00000001f))
for (unsigned int i=0;i<nsamp;++i)
o[i*nchan] += pfBuffer[i] * (old + inc*static_cast<float>(i));
}
} else {
for (unsigned int s=0;s<nchan;++s) {
const float str = svol[s] * volumeAdjustment;
float * RESTRICT o = output + s;
for (unsigned int i=0;i<nsamp;++i)
o[i*nchan] += pfBuffer[i] * str;
}
}
}
if (recorder && recorder->getMixDown()) {
recorder->addBuffer(NULL, recbuff, nsamp);
}
// Clip
if (eSampleFormat == SampleFloat)
for (unsigned int i=0;i<nsamp*iChannels;i++)
output[i] = output[i] < -1.0f ? -1.0f : (output[i] > 1.0f ? 1.0f : output[i]);
else
for (unsigned int i=0;i<nsamp*iChannels;i++)
reinterpret_cast<short *>(outbuff)[i] = static_cast<short>(32768.f * (output[i] < -1.0f ? -1.0f : (output[i] > 1.0f ? 1.0f : output[i])));
}
qrwlOutputs.unlock();
foreach(aop, qlDel)
removeBuffer(aop);
return (! qlMix.isEmpty());
}
bool AudioOutput::isAlive() const {
return isRunning();
}
unsigned int AudioOutput::getMixerFreq() const {
return iMixerFreq;
}
| bsd-3-clause |
endlessm/chromium-browser | ash/events/spoken_feedback_event_rewriter_unittest.cc | 13929 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/events/spoken_feedback_event_rewriter.h"
#include <memory>
#include <vector>
#include "ash/accessibility/accessibility_controller_impl.h"
#include "ash/public/cpp/spoken_feedback_event_rewriter_delegate.h"
#include "ash/shell.h"
#include "ash/test/ash_test_base.h"
#include "base/macros.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/chromeos/events/event_rewriter_chromeos.h"
#include "ui/chromeos/events/modifier_key.h"
#include "ui/chromeos/events/pref_names.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/event_rewriter.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/events/test/event_generator.h"
#include "ui/events/test/test_event_rewriter.h"
#include "ui/events/types/event_type.h"
namespace ash {
namespace {
// A test implementation of the spoken feedback delegate interface.
class TestDelegate : public SpokenFeedbackEventRewriterDelegate {
public:
TestDelegate() = default;
~TestDelegate() override = default;
// Count of events sent to the delegate.
size_t recorded_event_count_ = 0;
// Count of captured events sent to the delegate.
size_t captured_event_count_ = 0;
private:
// SpokenFeedbackEventRewriterDelegate:
void DispatchKeyEventToChromeVox(std::unique_ptr<ui::Event> event,
bool capture) override {
recorded_event_count_++;
if (capture)
captured_event_count_++;
}
void DispatchMouseEventToChromeVox(
std::unique_ptr<ui::Event> event) override {
recorded_event_count_++;
}
DISALLOW_COPY_AND_ASSIGN(TestDelegate);
};
class SpokenFeedbackEventRewriterTest
: public ash::AshTestBase,
public ui::EventRewriterChromeOS::Delegate {
public:
SpokenFeedbackEventRewriterTest() {
event_rewriter_chromeos_ =
std::make_unique<ui::EventRewriterChromeOS>(this, nullptr, false);
spoken_feedback_event_rewriter_ =
std::make_unique<SpokenFeedbackEventRewriter>(
event_rewriter_chromeos_.get());
}
void SetUp() override {
ash::AshTestBase::SetUp();
generator_ = AshTestBase::GetEventGenerator();
spoken_feedback_event_rewriter_->set_delegate(&delegate_);
GetContext()->GetHost()->GetEventSource()->AddEventRewriter(
spoken_feedback_event_rewriter_.get());
GetContext()->GetHost()->GetEventSource()->AddEventRewriter(
&event_recorder_);
}
void TearDown() override {
GetContext()->GetHost()->GetEventSource()->RemoveEventRewriter(
&event_recorder_);
GetContext()->GetHost()->GetEventSource()->RemoveEventRewriter(
spoken_feedback_event_rewriter_.get());
spoken_feedback_event_rewriter_->set_delegate(nullptr);
generator_ = nullptr;
ash::AshTestBase::TearDown();
}
size_t delegate_recorded_event_count() {
return delegate_.recorded_event_count_;
}
size_t delegate_captured_event_count() {
return delegate_.captured_event_count_;
}
void SetDelegateCaptureAllKeys(bool value) {
spoken_feedback_event_rewriter_->set_capture_all_keys(value);
}
void ExpectCounts(size_t expected_recorded_count,
size_t expected_delegate_count,
size_t expected_captured_count) {
EXPECT_EQ(expected_recorded_count,
static_cast<size_t>(event_recorder_.events_seen()));
EXPECT_EQ(expected_delegate_count, delegate_recorded_event_count());
EXPECT_EQ(expected_captured_count, delegate_captured_event_count());
}
void SetModifierRemapping(const std::string& pref_name,
ui::chromeos::ModifierKey value) {
modifier_remapping_[pref_name] = static_cast<int>(value);
}
protected:
// A test spoken feedback delegate; simulates ChromeVox.
TestDelegate delegate_;
// Generates ui::Events from simulated user input.
ui::test::EventGenerator* generator_ = nullptr;
// Records events delivered to the next event rewriter after spoken feedback.
ui::test::TestEventRewriter event_recorder_;
std::unique_ptr<SpokenFeedbackEventRewriter> spoken_feedback_event_rewriter_;
std::unique_ptr<ui::EventRewriterChromeOS> event_rewriter_chromeos_;
private:
// ui::EventRewriterChromeOS::Delegate:
bool RewriteModifierKeys() override { return true; }
bool GetKeyboardRemappedPrefValue(const std::string& pref_name,
int* value) const override {
auto it = modifier_remapping_.find(pref_name);
if (it == modifier_remapping_.end())
return false;
*value = it->second;
return true;
}
bool TopRowKeysAreFunctionKeys() const override { return false; }
bool IsExtensionCommandRegistered(ui::KeyboardCode key_code,
int flags) const override {
return false;
}
bool IsSearchKeyAcceleratorReserved() const override { return false; }
std::map<std::string, int> modifier_remapping_;
DISALLOW_COPY_AND_ASSIGN(SpokenFeedbackEventRewriterTest);
};
// The delegate should not intercept events when spoken feedback is disabled.
TEST_F(SpokenFeedbackEventRewriterTest, EventsNotConsumedWhenDisabled) {
AccessibilityControllerImpl* controller =
Shell::Get()->accessibility_controller();
EXPECT_FALSE(controller->spoken_feedback_enabled());
generator_->PressKey(ui::VKEY_A, ui::EF_NONE);
EXPECT_EQ(1, event_recorder_.events_seen());
EXPECT_EQ(0U, delegate_recorded_event_count());
generator_->ReleaseKey(ui::VKEY_A, ui::EF_NONE);
EXPECT_EQ(2, event_recorder_.events_seen());
EXPECT_EQ(0U, delegate_recorded_event_count());
generator_->ClickLeftButton();
EXPECT_EQ(4, event_recorder_.events_seen());
EXPECT_EQ(0U, delegate_recorded_event_count());
generator_->GestureTapAt(gfx::Point());
EXPECT_EQ(6, event_recorder_.events_seen());
EXPECT_EQ(0U, delegate_recorded_event_count());
}
// The delegate should intercept key events when spoken feedback is enabled.
TEST_F(SpokenFeedbackEventRewriterTest, KeyEventsConsumedWhenEnabled) {
AccessibilityControllerImpl* controller =
Shell::Get()->accessibility_controller();
controller->SetSpokenFeedbackEnabled(true, A11Y_NOTIFICATION_NONE);
EXPECT_TRUE(controller->spoken_feedback_enabled());
generator_->PressKey(ui::VKEY_A, ui::EF_NONE);
EXPECT_EQ(1, event_recorder_.events_seen());
EXPECT_EQ(1U, delegate_recorded_event_count());
EXPECT_EQ(0U, delegate_captured_event_count());
generator_->ReleaseKey(ui::VKEY_A, ui::EF_NONE);
EXPECT_EQ(2, event_recorder_.events_seen());
EXPECT_EQ(2U, delegate_recorded_event_count());
EXPECT_EQ(0U, delegate_captured_event_count());
generator_->ClickLeftButton();
EXPECT_EQ(4, event_recorder_.events_seen());
EXPECT_EQ(2U, delegate_recorded_event_count());
EXPECT_EQ(0U, delegate_captured_event_count());
generator_->GestureTapAt(gfx::Point());
EXPECT_EQ(6, event_recorder_.events_seen());
EXPECT_EQ(2U, delegate_recorded_event_count());
EXPECT_EQ(0U, delegate_captured_event_count());
}
// Asynchronously unhandled events should be sent to subsequent rewriters.
TEST_F(SpokenFeedbackEventRewriterTest, UnhandledEventsSentToOtherRewriters) {
// Before it can forward unhandled events, SpokenFeedbackEventRewriter
// must have seen at least one event in the first place.
generator_->PressKey(ui::VKEY_A, ui::EF_NONE);
EXPECT_EQ(1, event_recorder_.events_seen());
generator_->ReleaseKey(ui::VKEY_A, ui::EF_NONE);
EXPECT_EQ(2, event_recorder_.events_seen());
spoken_feedback_event_rewriter_->OnUnhandledSpokenFeedbackEvent(
std::make_unique<ui::KeyEvent>(ui::ET_KEY_PRESSED, ui::VKEY_A,
ui::EF_NONE));
EXPECT_EQ(3, event_recorder_.events_seen());
spoken_feedback_event_rewriter_->OnUnhandledSpokenFeedbackEvent(
std::make_unique<ui::KeyEvent>(ui::ET_KEY_RELEASED, ui::VKEY_A,
ui::EF_NONE));
EXPECT_EQ(4, event_recorder_.events_seen());
}
TEST_F(SpokenFeedbackEventRewriterTest, KeysNotEatenWithChromeVoxDisabled) {
AccessibilityControllerImpl* controller =
Shell::Get()->accessibility_controller();
EXPECT_FALSE(controller->spoken_feedback_enabled());
// Send Search+Shift+Right.
generator_->PressKey(ui::VKEY_LWIN, ui::EF_COMMAND_DOWN);
EXPECT_EQ(1, event_recorder_.events_seen());
generator_->PressKey(ui::VKEY_SHIFT, ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN);
EXPECT_EQ(2, event_recorder_.events_seen());
// Mock successful commands lookup and dispatch; shouldn't matter either way.
generator_->PressKey(ui::VKEY_RIGHT, ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN);
EXPECT_EQ(3, event_recorder_.events_seen());
// Released keys shouldn't get eaten.
generator_->ReleaseKey(ui::VKEY_RIGHT,
ui::EF_COMMAND_DOWN | ui::EF_SHIFT_DOWN);
generator_->ReleaseKey(ui::VKEY_SHIFT, ui::EF_COMMAND_DOWN);
generator_->ReleaseKey(ui::VKEY_LWIN, 0);
EXPECT_EQ(6, event_recorder_.events_seen());
// Try releasing more keys.
generator_->ReleaseKey(ui::VKEY_RIGHT, 0);
generator_->ReleaseKey(ui::VKEY_SHIFT, 0);
generator_->ReleaseKey(ui::VKEY_LWIN, 0);
EXPECT_EQ(9, event_recorder_.events_seen());
EXPECT_EQ(0U, delegate_recorded_event_count());
}
TEST_F(SpokenFeedbackEventRewriterTest, KeyEventsCaptured) {
AccessibilityControllerImpl* controller =
Shell::Get()->accessibility_controller();
controller->SetSpokenFeedbackEnabled(true, A11Y_NOTIFICATION_NONE);
EXPECT_TRUE(controller->spoken_feedback_enabled());
// Initialize expected counts as variables for easier maintaiblity.
size_t recorded_count = 0;
size_t delegate_count = 0;
size_t captured_count = 0;
// Anything with Search gets captured.
generator_->PressKey(ui::VKEY_LWIN, ui::EF_COMMAND_DOWN);
ExpectCounts(recorded_count, ++delegate_count, ++captured_count);
generator_->ReleaseKey(ui::VKEY_LWIN, ui::EF_COMMAND_DOWN);
ExpectCounts(recorded_count, ++delegate_count, ++captured_count);
// Tab never gets captured.
generator_->PressKey(ui::VKEY_TAB, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
generator_->ReleaseKey(ui::VKEY_TAB, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
// A client requested capture of all keys.
SetDelegateCaptureAllKeys(true);
generator_->PressKey(ui::VKEY_A, ui::EF_NONE);
ExpectCounts(recorded_count, ++delegate_count, ++captured_count);
generator_->ReleaseKey(ui::VKEY_A, ui::EF_NONE);
ExpectCounts(recorded_count, ++delegate_count, ++captured_count);
// Tab never gets captured even with explicit client request for all keys.
generator_->PressKey(ui::VKEY_TAB, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
generator_->ReleaseKey(ui::VKEY_TAB, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
// A client requested to not capture all keys.
SetDelegateCaptureAllKeys(false);
generator_->PressKey(ui::VKEY_A, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
generator_->ReleaseKey(ui::VKEY_A, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
}
TEST_F(SpokenFeedbackEventRewriterTest,
KeyEventsCapturedWithModifierRemapping) {
AccessibilityControllerImpl* controller =
Shell::Get()->accessibility_controller();
controller->SetSpokenFeedbackEnabled(true, A11Y_NOTIFICATION_NONE);
EXPECT_TRUE(controller->spoken_feedback_enabled());
// Initialize expected counts as variables for easier maintaiblity.
size_t recorded_count = 0;
size_t delegate_count = 0;
size_t captured_count = 0;
// Map Control key to Search.
SetModifierRemapping(prefs::kLanguageRemapControlKeyTo,
ui::chromeos::ModifierKey::kSearchKey);
// Anything with Search gets captured.
generator_->PressKey(ui::VKEY_CONTROL, ui::EF_CONTROL_DOWN);
ExpectCounts(recorded_count, ++delegate_count, ++captured_count);
// EventRewriterChromeOS actually omits the modifier flag.
generator_->ReleaseKey(ui::VKEY_CONTROL, 0);
ExpectCounts(recorded_count, ++delegate_count, ++captured_count);
// Search itself should also work.
generator_->PressKey(ui::VKEY_LWIN, ui::EF_COMMAND_DOWN);
ExpectCounts(recorded_count, ++delegate_count, ++captured_count);
generator_->ReleaseKey(ui::VKEY_LWIN, 0);
ExpectCounts(recorded_count, ++delegate_count, ++captured_count);
// Remapping should have no effect on all other expectations.
// Tab never gets captured.
generator_->PressKey(ui::VKEY_TAB, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
generator_->ReleaseKey(ui::VKEY_TAB, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
// A client requested capture of all keys.
SetDelegateCaptureAllKeys(true);
generator_->PressKey(ui::VKEY_A, ui::EF_NONE);
ExpectCounts(recorded_count, ++delegate_count, ++captured_count);
generator_->ReleaseKey(ui::VKEY_A, ui::EF_NONE);
ExpectCounts(recorded_count, ++delegate_count, ++captured_count);
// Tab never gets captured even with explicit client request for all keys.
generator_->PressKey(ui::VKEY_TAB, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
generator_->ReleaseKey(ui::VKEY_TAB, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
// A client requested to not capture all keys.
SetDelegateCaptureAllKeys(false);
generator_->PressKey(ui::VKEY_A, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
generator_->ReleaseKey(ui::VKEY_A, ui::EF_NONE);
ExpectCounts(++recorded_count, ++delegate_count, captured_count);
}
} // namespace
} // namespace ash
| bsd-3-clause |
irvs/ros_tms | tms_sa/tms_sa_bas/tms_sa_bas_person/include/tms_sa_bas_person/HumanModel.cpp | 15379 | //------------------------------------------------------------------------------
// @file : HumanModel.cpp
// @brief : keep human's behavior, position and another parameters
// @author : Masahide Tanaka
// @version: Ver0.1 (since 2012.11.13)
// @date : 2012.11.13
//------------------------------------------------------------------------------
#include "HumanModel.h"
#define SIGMA 2.1 // σ
void HumanModel::calcBaseStepCycle(tms_msg_ss::fss_person_trajectory_data humanTrajectory)
{
//------------------------------------------------------------------------------
// copy sample stepCycle to stepCycleData
for (unsigned int i = 0; i < humanTrajectory.trajectory.size(); i++)
{
std::vector< SampleData > tempStepCycleData;
for (unsigned int j = 0; j < humanTrajectory.trajectory[i].fCenterX.size(); j++)
{
unsigned int k = j + 1;
if (k < humanTrajectory.trajectory[i].fCenterX.size())
{
// calculate stepCycle
double tempStepCycle;
uint64_t this_sTime, next_sTime;
SampleData tempData;
this_sTime = humanTrajectory.trajectory[i].tStartTime[j].toNSec();
next_sTime = humanTrajectory.trajectory[i].tStartTime[k].toNSec();
tempStepCycle = (double)(next_sTime - this_sTime) / 1.0e9;
tempData.value = tempStepCycle;
tempData.isValid = true;
tempStepCycleData.push_back(tempData);
}
else
break;
}
stepCycleData.push_back(tempStepCycleData);
}
// printf("------------------------------------------------\n");
// printf("calcStepCycle:\n");
// printf("------------------------------------------------\n");
//------------------------------------------------------------------------------
// calculate average and var in nσ
double n = SIGMA;
for (unsigned int i = 0; i < stepCycleData.size(); i++)
{
// printf("humanTrajectory[%d]: data_num: %d\n", i, stepCycleData[i].size());
int count;
double sigma;
double stepCycle, stepCycleVar, sumStepCycle, sumStepCycleVar;
while (1)
{
count = 0;
stepCycle = stepCycleVar = sumStepCycle = sumStepCycleVar = 0.0;
if (stepCycleData[i].size() > 0)
{
for (unsigned int j = 0; j < stepCycleData[i].size(); j++)
{
if (stepCycleData[i][j].isValid)
{
sumStepCycle += stepCycleData[i][j].value;
sumStepCycleVar += stepCycleData[i][j].value * stepCycleData[i][j].value;
;
count++;
}
}
stepCycle = sumStepCycle / (double)count;
stepCycleVar = (sumStepCycleVar / (double)count) - stepCycle * stepCycle;
sigma = sqrt(stepCycleVar);
// printf("stepCycle: %lf, stepCycleVar: %lf, sigma: %lf\n", stepCycle, stepCycleVar, sigma);
// eliminate sample data which is out of nσ
bool isFinished = true;
for (unsigned int j = 0; j < stepCycleData[i].size(); j++)
{
if (stepCycleData[i][j].isValid)
{
if (stepCycleData[i][j].value <= stepCycle - n * sigma ||
stepCycle + n * sigma <= stepCycleData[i][j].value)
{
stepCycleData[i][j].isValid = false;
isFinished = false;
}
}
}
if (isFinished)
{
baseStepCycle.push_back(stepCycle);
baseStepCycleVar.push_back(stepCycleVar);
break;
}
}
else
{
// printf("【Error】 No data.\n");
// printf("stepCycle: %lf, stepCycleVar: %lf, sigma: %lf\n", stepCycle, stepCycleVar, sigma);
baseStepCycle.push_back(stepCycle);
baseStepCycleVar.push_back(stepCycleVar);
break;
}
}
//------------------------------------------------------------------------------
// display stepCycle
// if(stepCycleData[i].size() > 0){
// for(unsigned int j=0 ; j<stepCycleData[i].size() ; j++){
// printf("[%d]-[%d]: %lf", j+1, j+2, stepCycleData[i][j].value);
// if(!stepCycleData[i][j].isValid)
// printf(" -- false");
// printf("\n");
// }
// }
//
// printf("--\n");
// printf("stepCycle: %lf\n", stepCycle);
// printf("stepCycleVar: %lf\n", stepCycleVar);
// printf("------------------------------------------------\n");
}
}
void HumanModel::calcBaseGaitCycle(tms_msg_ss::fss_person_trajectory_data humanTrajectory)
{
//------------------------------------------------------------------------------
// copy sample gaitCycle to gaitCycleData
for (unsigned int i = 0; i < humanTrajectory.trajectory.size(); i++)
{
std::vector< SampleData > tempGaitCycleData;
for (unsigned int j = 0; j < humanTrajectory.trajectory[i].fCenterX.size(); j++)
{
unsigned int k = j + 2;
if (k < humanTrajectory.trajectory[i].fCenterX.size())
{
// calculate gaitCycle
double tempGaitCycle;
uint64_t this_sTime, next_sTime;
SampleData tempData;
this_sTime = humanTrajectory.trajectory[i].tStartTime[j].toNSec();
next_sTime = humanTrajectory.trajectory[i].tStartTime[k].toNSec();
tempGaitCycle = (double)(next_sTime - this_sTime) / 1.0e9;
tempData.value = tempGaitCycle;
tempData.isValid = true;
tempGaitCycleData.push_back(tempData);
}
else
break;
}
gaitCycleData.push_back(tempGaitCycleData);
}
// printf("------------------------------------------------\n");
// printf("calcGaitCycle:\n");
// printf("------------------------------------------------\n");
//------------------------------------------------------------------------------
// calculate average and var in nσ
double n = SIGMA;
for (unsigned int i = 0; i < gaitCycleData.size(); i++)
{
// printf("humanTrajectory[%d]: data_num: %d\n", i, gaitCycleData[i].size());
int count;
double sigma;
double gaitCycle, gaitCycleVar, sumGaitCycle, sumGaitCycleVar;
while (1)
{
count = 0;
gaitCycle = gaitCycleVar = sumGaitCycle = sumGaitCycleVar = 0.0;
if (gaitCycleData[i].size() > 0)
{
for (unsigned int j = 0; j < gaitCycleData[i].size(); j++)
{
if (gaitCycleData[i][j].isValid)
{
sumGaitCycle += gaitCycleData[i][j].value;
sumGaitCycleVar += gaitCycleData[i][j].value * gaitCycleData[i][j].value;
;
count++;
}
}
gaitCycle = sumGaitCycle / (double)count;
gaitCycleVar = (sumGaitCycleVar / (double)count) - gaitCycle * gaitCycle;
sigma = sqrt(gaitCycleVar);
// printf("gaitCycle: %lf, gaitCycleVar: %lf, sigma: %lf\n", gaitCycle, gaitCycleVar, sigma);
// eliminate sample data which is out of nσ
bool isFinished = true;
for (unsigned int j = 0; j < gaitCycleData[i].size(); j++)
{
if (gaitCycleData[i][j].isValid)
{
if (gaitCycleData[i][j].value <= gaitCycle - n * sigma ||
gaitCycle + n * sigma <= gaitCycleData[i][j].value)
{
gaitCycleData[i][j].isValid = false;
isFinished = false;
}
}
}
if (isFinished)
{
baseGaitCycle.push_back(gaitCycle);
baseGaitCycleVar.push_back(gaitCycleVar);
break;
}
}
else
{
// printf("【Error】 No data.\n");
// printf("gaitCycle: %lf, gaitCycleVar: %lf, sigma: %lf\n", gaitCycle, gaitCycleVar, sigma);
baseGaitCycle.push_back(gaitCycle);
baseGaitCycleVar.push_back(gaitCycleVar);
break;
}
}
//------------------------------------------------------------------------------
// display gaitCycle
// if(gaitCycleData[i].size() > 0){
// for(unsigned int j=0 ; j<gaitCycleData[i].size() ; j++){
// printf("[%d]-[%d]: %lf", j+1, j+3, gaitCycleData[i][j].value);
// if(!gaitCycleData[i][j].isValid)
// printf(" -- false");
// printf("\n");
// }
// }
//
// printf("--\n");
// printf("gaitCycle: %lf\n", gaitCycle);
// printf("gaitCycleVar: %lf\n", gaitCycleVar);
// printf("------------------------------------------------\n");
}
}
void HumanModel::calcBaseStepCycleByAll()
{
//------------------------------------------------------------------------------
// copy each stepCycleData to stepCycleDataByAll
for (unsigned int i = 0; i < stepCycleData.size(); i++)
{
for (unsigned int j = 0; j < stepCycleData[i].size(); j++)
{
SampleData tempStepCycleDataByAll;
tempStepCycleDataByAll.value = stepCycleData[i][j].value;
tempStepCycleDataByAll.isValid = true;
stepCycleDataByAll.push_back(tempStepCycleDataByAll);
}
}
// printf("------------------------------------------------\n");
// printf("calcStepCycleByAll:\n");
// printf("------------------------------------------------\n");
// printf("humanTrajectory all data: data_num: %d\n",stepCycleDataByAll.size());
//------------------------------------------------------------------------------
// calculate average and var in nσ
double n = SIGMA;
int count;
double sigma;
double stepCycle, stepCycleVar, sumStepCycle, sumStepCycleVar;
while (1)
{
count = 0;
stepCycle = stepCycleVar = sumStepCycle = sumStepCycleVar = 0.0;
if (stepCycleDataByAll.size() > 0)
{
for (unsigned int i = 0; i < stepCycleDataByAll.size(); i++)
{
if (stepCycleDataByAll[i].isValid)
{
sumStepCycle += stepCycleDataByAll[i].value;
sumStepCycleVar += stepCycleDataByAll[i].value * stepCycleDataByAll[i].value;
;
count++;
}
}
stepCycle = sumStepCycle / (double)count;
stepCycleVar = (sumStepCycleVar / (double)count) - stepCycle * stepCycle;
sigma = sqrt(stepCycleVar);
// printf("stepCycle: %lf, stepCycleVar: %lf, sigma: %lf\n", stepCycle, stepCycleVar, sigma);
// eliminate sample data which is out of nσ
bool isFinished = true;
for (unsigned int i = 0; i < stepCycleDataByAll.size(); i++)
{
if (stepCycleDataByAll[i].isValid)
{
if (stepCycleDataByAll[i].value <= stepCycle - n * sigma ||
stepCycle + n * sigma <= stepCycleDataByAll[i].value)
{
stepCycleDataByAll[i].isValid = false;
isFinished = false;
}
}
}
if (isFinished)
{
baseStepCycleByAll = stepCycle;
baseStepCycleVarByAll = stepCycleVar;
break;
}
}
else
{
// printf("【Error】 No data.\n");
// printf("stepCycle: %lf, stepCycleVar: %lf, sigma: %lf\n", stepCycle, stepCycleVar, sigma);
baseStepCycleByAll = stepCycle;
baseStepCycleVarByAll = stepCycleVar;
break;
}
}
//------------------------------------------------------------------------------
// display stepCycle
// if(stepCycleDataByAll.size() > 0){
// for(unsigned int i=0 ; i<stepCycleDataByAll.size() ; i++){
// printf("[%d]-[%d]: %lf", i+1, i+2, stepCycleDataByAll[i].value);
// if(!stepCycleDataByAll[i].isValid)
// printf(" -- false");
// printf("\n");
// }
// }
//
// printf("--\n");
// printf("stepCycle: %lf\n", stepCycle);
// printf("stepCycleVar: %lf\n", stepCycleVar);
// printf("------------------------------------------------\n");
}
void HumanModel::calcBaseGaitCycleByAll()
{
//------------------------------------------------------------------------------
// copy each gaitCycleData to gaitCycleDataByAll
for (unsigned int i = 0; i < gaitCycleData.size(); i++)
{
for (unsigned int j = 0; j < gaitCycleData[i].size(); j++)
{
SampleData tempGaitCycleDataByAll;
tempGaitCycleDataByAll.value = gaitCycleData[i][j].value;
tempGaitCycleDataByAll.isValid = true;
gaitCycleDataByAll.push_back(tempGaitCycleDataByAll);
}
}
// printf("------------------------------------------------\n");
// printf("calcGaitCycleByAll:\n");
// printf("------------------------------------------------\n");
// printf("humanTrajectory all data: data_num: %d\n",gaitCycleDataByAll.size());
//------------------------------------------------------------------------------
// calculate average and var in nσ
double n = SIGMA;
int count;
double sigma;
double gaitCycle, gaitCycleVar, sumGaitCycle, sumGaitCycleVar;
while (1)
{
count = 0;
gaitCycle = gaitCycleVar = sumGaitCycle = sumGaitCycleVar = 0.0;
if (gaitCycleDataByAll.size() > 0)
{
for (unsigned int i = 0; i < gaitCycleDataByAll.size(); i++)
{
if (gaitCycleDataByAll[i].isValid)
{
sumGaitCycle += gaitCycleDataByAll[i].value;
sumGaitCycleVar += gaitCycleDataByAll[i].value * gaitCycleDataByAll[i].value;
;
count++;
}
}
gaitCycle = sumGaitCycle / (double)count;
gaitCycleVar = (sumGaitCycleVar / (double)count) - gaitCycle * gaitCycle;
sigma = sqrt(gaitCycleVar);
// printf("gaitCycle: %lf, gaitCycleVar: %lf, sigma: %lf\n", gaitCycle, gaitCycleVar, sigma);
// eliminate sample data which is out of nσ
bool isFinished = true;
for (unsigned int i = 0; i < gaitCycleDataByAll.size(); i++)
{
if (gaitCycleDataByAll[i].isValid)
{
if (gaitCycleDataByAll[i].value <= gaitCycle - n * sigma ||
gaitCycle + n * sigma <= gaitCycleDataByAll[i].value)
{
gaitCycleDataByAll[i].isValid = false;
isFinished = false;
}
}
}
if (isFinished)
{
baseGaitCycleByAll = gaitCycle;
baseGaitCycleVarByAll = gaitCycleVar;
break;
}
}
else
{
// printf("【Error】 No data.\n");
// printf("gaitCycle: %lf, gaitCycleVar: %lf, sigma: %lf\n", gaitCycle, gaitCycleVar, sigma);
baseGaitCycleByAll = gaitCycle;
baseGaitCycleVarByAll = gaitCycleVar;
break;
}
}
//------------------------------------------------------------------------------
// display gaitCycle
// if(gaitCycleDataByAll.size() > 0){
// for(unsigned int i=0 ; i<gaitCycleDataByAll.size() ; i++){
// printf("[%d]-[%d]: %lf", i+1, i+2, gaitCycleDataByAll[i].value);
// if(!gaitCycleDataByAll[i].isValid)
// printf(" -- false");
// printf("\n");
// }
// }
//
// printf("--\n");
// printf("gaitCycle: %lf\n", gaitCycle);
// printf("gaitCycleVar: %lf\n", gaitCycleVar);
// printf("------------------------------------------------\n");
}
void HumanModel::clearAllParameter()
{
behaviorWalking = 0;
behaviorSitting = 0;
behaviorSleeping = 0;
stepCycle = 0;
fPosFoot1X = 0;
fPosFoot1Y = 0;
fPosFoot2X = 0;
fPosFoot2Y = 0;
fAccFoot1X = 0;
fAccFoot1Y = 0;
fAccFoot2X = 0;
fAccFoot2Y = 0;
baseStepCycleByAll = 0;
baseStepCycleVarByAll = 0;
baseGaitCycleByAll = 0;
baseGaitCycleVarByAll = 0;
baseStepCycle.clear();
baseStepCycleVar.clear();
baseGaitCycle.clear();
baseGaitCycleVar.clear();
stepCycleData.clear();
gaitCycleData.clear();
stepCycleDataByAll.clear();
gaitCycleDataByAll.clear();
}
| bsd-3-clause |
robertzml/Rhea | Rhea.Data/Properties/AssemblyInfo.cs | 1306 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("Rhea.Data")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Rhea.Data")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("dd5e393b-27b5-4f63-97a7-3bd79027ded5")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| bsd-3-clause |
hiraq/qiscus-model | src/Utility/InMemory.php | 1877 | <?php
namespace Qiscus\Utility;
/**
* Simulate storage in memory
*/
class InMemory
{
/**
* key value based
*/
private $map = [];
/**
* sequences values
*/
private $list = [];
/**
* save key and their values
* on map
*
* @return void
*/
public function onMap($key, $value)
{
$this->map[$key] = $value;
}
/**
* check if given $key was saved in map
*
* @return boolean
*/
public function inMap($key)
{
return array_key_exists($key, $this->map);
}
/**
* return value based on given $key
* parameter
*/
public function fromMap($key)
{
if ($this->inMap($key)) {
return $this->map[$key];
} else {
return null;
}
}
/**
* remove data from map collection
*
* @return void
*/
public function removeFromMap($key)
{
unset($this->map[$key]);
}
/**
* save $value into a collection of values
*
* @return void
*/
public function onList($value)
{
$this->list[] = $value;
}
/**
* check if given $value
* was existed inside list collectoins
*
* @return boolean
*/
public function inList($value)
{
return in_array($value, $this->list);
}
/**
* remove data from list collection
*
* @return void
*/
public function removeFromList($value)
{
/*
* filtering each value inside list collection
* compare with given $value parameter
* only return a value that doesn't same
* with $value
*/
$filter = function($list) use($value) {
return $list != $value;
};
$this->list = array_filter($this->list, $filter);
}
}
| bsd-3-clause |
jdef/dns | msg.go | 55111 | // DNS packet assembly, see RFC 1035. Converting from - Unpack() -
// and to - Pack() - wire format.
// All the packers and unpackers take a (msg []byte, off int)
// and return (off1 int, ok bool). If they return ok==false, they
// also return off1==len(msg), so that the next unpacker will
// also fail. This lets us avoid checks of ok until the end of a
// packing sequence.
package dns
import (
"encoding/base32"
"encoding/base64"
"encoding/hex"
"math/big"
"math/rand"
"net"
"reflect"
"strconv"
"time"
)
const maxCompressionOffset = 2 << 13 // We have 14 bits for the compression pointer
var (
// ErrAlg indicates an error with the (DNSSEC) algorithm.
ErrAlg error = &Error{err: "bad algorithm"}
// ErrAuth indicates an error in the TSIG authentication.
ErrAuth error = &Error{err: "bad authentication"}
// ErrBuf indicates that the buffer used it too small for the message.
ErrBuf error = &Error{err: "buffer size too small"}
// ErrConn indicates that a connection has both a TCP and UDP socket.
ErrConn error = &Error{err: "conn holds both UDP and TCP connection"}
// ErrConnEmpty indicates a connection is being uses before it is initialized.
ErrConnEmpty error = &Error{err: "conn has no connection"}
// ErrExtendedRcode ...
ErrExtendedRcode error = &Error{err: "bad extended rcode"}
// ErrFqdn indicates that a domain name does not have a closing dot.
ErrFqdn error = &Error{err: "domain must be fully qualified"}
// ErrId indicates there is a mismatch with the message's ID.
ErrId error = &Error{err: "id mismatch"}
ErrKeyAlg error = &Error{err: "bad key algorithm"}
ErrKey error = &Error{err: "bad key"}
ErrKeySize error = &Error{err: "bad key size"}
ErrNoSig error = &Error{err: "no signature found"}
ErrPrivKey error = &Error{err: "bad private key"}
ErrRcode error = &Error{err: "bad rcode"}
ErrRdata error = &Error{err: "bad rdata"}
ErrRRset error = &Error{err: "bad rrset"}
ErrSecret error = &Error{err: "no secrets defined"}
ErrShortRead error = &Error{err: "short read"}
// ErrSig indicates that a signature can not be cryptographically validated.
ErrSig error = &Error{err: "bad signature"}
// ErrSigGen indicates a faulure to generate a signature.
ErrSigGen error = &Error{err: "bad signature generation"}
// ErrSOA indicates that no SOA RR was seen when doing zone transfers.
ErrSoa error = &Error{err: "no SOA"}
// ErrTime indicates a timing error in TSIG authentication.
ErrTime error = &Error{err: "bad time"}
)
// Id, by default, returns a 16 bits random number to be used as a
// message id. The random provided should be good enough. This being a
// variable the function can be reassigned to a custom function.
// For instance, to make it return a static value:
//
// dns.Id = func() uint16 { return 3 }
var Id func() uint16 = id
// MsgHdr is a a manually-unpacked version of (id, bits).
type MsgHdr struct {
Id uint16
Response bool
Opcode int
Authoritative bool
Truncated bool
RecursionDesired bool
RecursionAvailable bool
Zero bool
AuthenticatedData bool
CheckingDisabled bool
Rcode int
}
// Msg contains the layout of a DNS message.
type Msg struct {
MsgHdr
Compress bool `json:"-"` // If true, the message will be compressed when converted to wire format. This not part of the official DNS packet format.
Question []Question // Holds the RR(s) of the question section.
Answer []RR // Holds the RR(s) of the answer section.
Ns []RR // Holds the RR(s) of the authority section.
Extra []RR // Holds the RR(s) of the additional section.
}
// TypeToString is a map of strings for each RR wire type.
var TypeToString = map[uint16]string{
TypeA: "A",
TypeAAAA: "AAAA",
TypeAFSDB: "AFSDB",
TypeANY: "ANY", // Meta RR
TypeATMA: "ATMA",
TypeAXFR: "AXFR", // Meta RR
TypeCAA: "CAA",
TypeCDNSKEY: "CDNSKEY",
TypeCDS: "CDS",
TypeCERT: "CERT",
TypeCNAME: "CNAME",
TypeDHCID: "DHCID",
TypeDLV: "DLV",
TypeDNAME: "DNAME",
TypeDNSKEY: "DNSKEY",
TypeDS: "DS",
TypeEID: "EID",
TypeEUI48: "EUI48",
TypeEUI64: "EUI64",
TypeGID: "GID",
TypeGPOS: "GPOS",
TypeHINFO: "HINFO",
TypeHIP: "HIP",
TypeIPSECKEY: "IPSECKEY",
TypeISDN: "ISDN",
TypeIXFR: "IXFR", // Meta RR
TypeKEY: "KEY",
TypeKX: "KX",
TypeL32: "L32",
TypeL64: "L64",
TypeLOC: "LOC",
TypeLP: "LP",
TypeMB: "MB",
TypeMD: "MD",
TypeMF: "MF",
TypeMG: "MG",
TypeMINFO: "MINFO",
TypeMR: "MR",
TypeMX: "MX",
TypeNAPTR: "NAPTR",
TypeNID: "NID",
TypeNINFO: "NINFO",
TypeNIMLOC: "NIMLOC",
TypeNS: "NS",
TypeNSAP: "NSAP",
TypeNSAPPTR: "NSAP-PTR",
TypeNSEC3: "NSEC3",
TypeNSEC3PARAM: "NSEC3PARAM",
TypeNSEC: "NSEC",
TypeNULL: "NULL",
TypeOPT: "OPT",
TypeOPENPGPKEY: "OPENPGPKEY",
TypePTR: "PTR",
TypeRKEY: "RKEY",
TypeRP: "RP",
TypeRRSIG: "RRSIG",
TypeRT: "RT",
TypeSIG: "SIG",
TypeSOA: "SOA",
TypeSPF: "SPF",
TypeSRV: "SRV",
TypeSSHFP: "SSHFP",
TypeTA: "TA",
TypeTALINK: "TALINK",
TypeTKEY: "TKEY", // Meta RR
TypeTLSA: "TLSA",
TypeTSIG: "TSIG", // Meta RR
TypeTXT: "TXT",
TypePX: "PX",
TypeUID: "UID",
TypeUINFO: "UINFO",
TypeUNSPEC: "UNSPEC",
TypeURI: "URI",
TypeWKS: "WKS",
TypeX25: "X25",
}
// StringToType is the reverse of TypeToString, needed for string parsing.
var StringToType = reverseInt16(TypeToString)
// StringToClass is the reverse of ClassToString, needed for string parsing.
var StringToClass = reverseInt16(ClassToString)
// Map of opcodes strings.
var StringToOpcode = reverseInt(OpcodeToString)
// Map of rcodes strings.
var StringToRcode = reverseInt(RcodeToString)
// ClassToString is a maps Classes to strings for each CLASS wire type.
var ClassToString = map[uint16]string{
ClassINET: "IN",
ClassCSNET: "CS",
ClassCHAOS: "CH",
ClassHESIOD: "HS",
ClassNONE: "NONE",
ClassANY: "ANY",
}
// OpcodeToString maps Opcodes to strings.
var OpcodeToString = map[int]string{
OpcodeQuery: "QUERY",
OpcodeIQuery: "IQUERY",
OpcodeStatus: "STATUS",
OpcodeNotify: "NOTIFY",
OpcodeUpdate: "UPDATE",
}
// RcodeToString maps Rcodes to strings.
var RcodeToString = map[int]string{
RcodeSuccess: "NOERROR",
RcodeFormatError: "FORMERR",
RcodeServerFailure: "SERVFAIL",
RcodeNameError: "NXDOMAIN",
RcodeNotImplemented: "NOTIMPL",
RcodeRefused: "REFUSED",
RcodeYXDomain: "YXDOMAIN", // From RFC 2136
RcodeYXRrset: "YXRRSET",
RcodeNXRrset: "NXRRSET",
RcodeNotAuth: "NOTAUTH",
RcodeNotZone: "NOTZONE",
RcodeBadSig: "BADSIG", // Also known as RcodeBadVers, see RFC 6891
// RcodeBadVers: "BADVERS",
RcodeBadKey: "BADKEY",
RcodeBadTime: "BADTIME",
RcodeBadMode: "BADMODE",
RcodeBadName: "BADNAME",
RcodeBadAlg: "BADALG",
RcodeBadTrunc: "BADTRUNC",
}
// Rather than write the usual handful of routines to pack and
// unpack every message that can appear on the wire, we use
// reflection to write a generic pack/unpack for structs and then
// use it. Thus, if in the future we need to define new message
// structs, no new pack/unpack/printing code needs to be written.
// Domain names are a sequence of counted strings
// split at the dots. They end with a zero-length string.
// PackDomainName packs a domain name s into msg[off:].
// If compression is wanted compress must be true and the compression
// map needs to hold a mapping between domain names and offsets
// pointing into msg[].
func PackDomainName(s string, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
off1, _, err = packDomainName(s, msg, off, compression, compress)
return
}
func packDomainName(s string, msg []byte, off int, compression map[string]int, compress bool) (off1 int, labels int, err error) {
// special case if msg == nil
lenmsg := 256
if msg != nil {
lenmsg = len(msg)
}
ls := len(s)
if ls == 0 { // Ok, for instance when dealing with update RR without any rdata.
return off, 0, nil
}
// If not fully qualified, error out, but only if msg == nil #ugly
switch {
case msg == nil:
if s[ls-1] != '.' {
s += "."
ls++
}
case msg != nil:
if s[ls-1] != '.' {
return lenmsg, 0, ErrFqdn
}
}
// Each dot ends a segment of the name.
// We trade each dot byte for a length byte.
// Except for escaped dots (\.), which are normal dots.
// There is also a trailing zero.
// Compression
nameoffset := -1
pointer := -1
// Emit sequence of counted strings, chopping at dots.
begin := 0
bs := []byte(s)
roBs, bsFresh, escapedDot := s, true, false
for i := 0; i < ls; i++ {
if bs[i] == '\\' {
for j := i; j < ls-1; j++ {
bs[j] = bs[j+1]
}
ls--
if off+1 > lenmsg {
return lenmsg, labels, ErrBuf
}
// check for \DDD
if i+2 < ls && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
bs[i] = dddToByte(bs[i:])
for j := i + 1; j < ls-2; j++ {
bs[j] = bs[j+2]
}
ls -= 2
} else if bs[i] == 't' {
bs[i] = '\t'
} else if bs[i] == 'r' {
bs[i] = '\r'
} else if bs[i] == 'n' {
bs[i] = '\n'
}
escapedDot = bs[i] == '.'
bsFresh = false
continue
}
if bs[i] == '.' {
if i > 0 && bs[i-1] == '.' && !escapedDot {
// two dots back to back is not legal
return lenmsg, labels, ErrRdata
}
if i-begin >= 1<<6 { // top two bits of length must be clear
return lenmsg, labels, ErrRdata
}
// off can already (we're in a loop) be bigger than len(msg)
// this happens when a name isn't fully qualified
if off+1 > lenmsg {
return lenmsg, labels, ErrBuf
}
if msg != nil {
msg[off] = byte(i - begin)
}
offset := off
off++
for j := begin; j < i; j++ {
if off+1 > lenmsg {
return lenmsg, labels, ErrBuf
}
if msg != nil {
msg[off] = bs[j]
}
off++
}
if compress && !bsFresh {
roBs = string(bs)
bsFresh = true
}
// Dont try to compress '.'
if compress && roBs[begin:] != "." {
if p, ok := compression[roBs[begin:]]; !ok {
// Only offsets smaller than this can be used.
if offset < maxCompressionOffset {
compression[roBs[begin:]] = offset
}
} else {
// The first hit is the longest matching dname
// keep the pointer offset we get back and store
// the offset of the current name, because that's
// where we need to insert the pointer later
// If compress is true, we're allowed to compress this dname
if pointer == -1 && compress {
pointer = p // Where to point to
nameoffset = offset // Where to point from
break
}
}
}
labels++
begin = i + 1
}
escapedDot = false
}
// Root label is special
if len(bs) == 1 && bs[0] == '.' {
return off, labels, nil
}
// If we did compression and we find something add the pointer here
if pointer != -1 {
// We have two bytes (14 bits) to put the pointer in
// if msg == nil, we will never do compression
msg[nameoffset], msg[nameoffset+1] = packUint16(uint16(pointer ^ 0xC000))
off = nameoffset + 1
goto End
}
if msg != nil {
msg[off] = 0
}
End:
off++
return off, labels, nil
}
// Unpack a domain name.
// In addition to the simple sequences of counted strings above,
// domain names are allowed to refer to strings elsewhere in the
// packet, to avoid repeating common suffixes when returning
// many entries in a single domain. The pointers are marked
// by a length byte with the top two bits set. Ignoring those
// two bits, that byte and the next give a 14 bit offset from msg[0]
// where we should pick up the trail.
// Note that if we jump elsewhere in the packet,
// we return off1 == the offset after the first pointer we found,
// which is where the next record will start.
// In theory, the pointers are only allowed to jump backward.
// We let them jump anywhere and stop jumping after a while.
// UnpackDomainName unpacks a domain name into a string.
func UnpackDomainName(msg []byte, off int) (string, int, error) {
s := make([]byte, 0, 64)
off1 := 0
lenmsg := len(msg)
ptr := 0 // number of pointers followed
Loop:
for {
if off >= lenmsg {
return "", lenmsg, ErrBuf
}
c := int(msg[off])
off++
switch c & 0xC0 {
case 0x00:
if c == 0x00 {
// end of name
if len(s) == 0 {
if ptr == 0 {
off1 = off
}
return ".", off1, nil
}
break Loop
}
// literal string
if off+c > lenmsg {
return "", lenmsg, ErrBuf
}
for j := off; j < off+c; j++ {
switch b := msg[j]; b {
case '.', '(', ')', ';', ' ', '@':
fallthrough
case '"', '\\':
s = append(s, '\\', b)
case '\t':
s = append(s, '\\', 't')
case '\r':
s = append(s, '\\', 'r')
default:
if b < 32 || b >= 127 { // unprintable use \DDD
var buf [3]byte
bufs := strconv.AppendInt(buf[:0], int64(b), 10)
s = append(s, '\\')
for i := 0; i < 3-len(bufs); i++ {
s = append(s, '0')
}
for _, r := range bufs {
s = append(s, r)
}
} else {
s = append(s, b)
}
}
}
s = append(s, '.')
off += c
case 0xC0:
// pointer to somewhere else in msg.
// remember location after first ptr,
// since that's how many bytes we consumed.
// also, don't follow too many pointers --
// maybe there's a loop.
if off >= lenmsg {
return "", lenmsg, ErrBuf
}
c1 := msg[off]
off++
if ptr == 0 {
off1 = off
}
if ptr++; ptr > 10 {
return "", lenmsg, &Error{err: "too many compression pointers"}
}
off = (c^0xC0)<<8 | int(c1)
default:
// 0x80 and 0x40 are reserved
return "", lenmsg, ErrRdata
}
}
if ptr == 0 {
off1 = off
}
return string(s), off1, nil
}
func packTxt(txt []string, msg []byte, offset int, tmp []byte) (int, error) {
var err error
if len(txt) == 0 {
if offset >= len(msg) {
return offset, ErrBuf
}
msg[offset] = 0
return offset, nil
}
for i := range txt {
if len(txt[i]) > len(tmp) {
return offset, ErrBuf
}
offset, err = packTxtString(txt[i], msg, offset, tmp)
if err != nil {
return offset, err
}
}
return offset, err
}
func packTxtString(s string, msg []byte, offset int, tmp []byte) (int, error) {
lenByteOffset := offset
if offset >= len(msg) {
return offset, ErrBuf
}
offset++
bs := tmp[:len(s)]
copy(bs, s)
for i := 0; i < len(bs); i++ {
if len(msg) <= offset {
return offset, ErrBuf
}
if bs[i] == '\\' {
i++
if i == len(bs) {
break
}
// check for \DDD
if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
msg[offset] = dddToByte(bs[i:])
i += 2
} else if bs[i] == 't' {
msg[offset] = '\t'
} else if bs[i] == 'r' {
msg[offset] = '\r'
} else if bs[i] == 'n' {
msg[offset] = '\n'
} else {
msg[offset] = bs[i]
}
} else {
msg[offset] = bs[i]
}
offset++
}
l := offset - lenByteOffset - 1
if l > 255 {
return offset, &Error{err: "string exceeded 255 bytes in txt"}
}
msg[lenByteOffset] = byte(l)
return offset, nil
}
func packOctetString(s string, msg []byte, offset int, tmp []byte) (int, error) {
if offset >= len(msg) {
return offset, ErrBuf
}
bs := tmp[:len(s)]
copy(bs, s)
for i := 0; i < len(bs); i++ {
if len(msg) <= offset {
return offset, ErrBuf
}
if bs[i] == '\\' {
i++
if i == len(bs) {
break
}
// check for \DDD
if i+2 < len(bs) && isDigit(bs[i]) && isDigit(bs[i+1]) && isDigit(bs[i+2]) {
msg[offset] = dddToByte(bs[i:])
i += 2
} else {
msg[offset] = bs[i]
}
} else {
msg[offset] = bs[i]
}
offset++
}
return offset, nil
}
func unpackTxt(msg []byte, offset, rdend int) ([]string, int, error) {
var err error
var ss []string
var s string
for offset < rdend && err == nil {
s, offset, err = unpackTxtString(msg, offset)
if err == nil {
ss = append(ss, s)
}
}
return ss, offset, err
}
func unpackTxtString(msg []byte, offset int) (string, int, error) {
if offset+1 > len(msg) {
return "", offset, &Error{err: "overflow unpacking txt"}
}
l := int(msg[offset])
if offset+l+1 > len(msg) {
return "", offset, &Error{err: "overflow unpacking txt"}
}
s := make([]byte, 0, l)
for _, b := range msg[offset+1 : offset+1+l] {
switch b {
case '"', '\\':
s = append(s, '\\', b)
case '\t':
s = append(s, `\t`...)
case '\r':
s = append(s, `\r`...)
case '\n':
s = append(s, `\n`...)
default:
if b < 32 || b > 127 { // unprintable
var buf [3]byte
bufs := strconv.AppendInt(buf[:0], int64(b), 10)
s = append(s, '\\')
for i := 0; i < 3-len(bufs); i++ {
s = append(s, '0')
}
for _, r := range bufs {
s = append(s, r)
}
} else {
s = append(s, b)
}
}
}
offset += 1 + l
return string(s), offset, nil
}
// Pack a reflect.StructValue into msg. Struct members can only be uint8, uint16, uint32, string,
// slices and other (often anonymous) structs.
func packStructValue(val reflect.Value, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
var txtTmp []byte
lenmsg := len(msg)
numfield := val.NumField()
for i := 0; i < numfield; i++ {
typefield := val.Type().Field(i)
if typefield.Tag == `dns:"-"` {
continue
}
switch fv := val.Field(i); fv.Kind() {
default:
return lenmsg, &Error{err: "bad kind packing"}
case reflect.Interface:
// PrivateRR is the only RR implementation that has interface field.
// therefore it's expected that this interface would be PrivateRdata
switch data := fv.Interface().(type) {
case PrivateRdata:
n, err := data.Pack(msg[off:])
if err != nil {
return lenmsg, err
}
off += n
default:
return lenmsg, &Error{err: "bad kind interface packing"}
}
case reflect.Slice:
switch typefield.Tag {
default:
return lenmsg, &Error{"bad tag packing slice: " + typefield.Tag.Get("dns")}
case `dns:"domain-name"`:
for j := 0; j < val.Field(i).Len(); j++ {
element := val.Field(i).Index(j).String()
off, err = PackDomainName(element, msg, off, compression, false && compress)
if err != nil {
return lenmsg, err
}
}
case `dns:"txt"`:
if txtTmp == nil {
txtTmp = make([]byte, 256*4+1)
}
off, err = packTxt(fv.Interface().([]string), msg, off, txtTmp)
if err != nil {
return lenmsg, err
}
case `dns:"opt"`: // edns
for j := 0; j < val.Field(i).Len(); j++ {
element := val.Field(i).Index(j).Interface()
b, e := element.(EDNS0).pack()
if e != nil {
return lenmsg, &Error{err: "overflow packing opt"}
}
// Option code
msg[off], msg[off+1] = packUint16(element.(EDNS0).Option())
// Length
msg[off+2], msg[off+3] = packUint16(uint16(len(b)))
off += 4
if off+len(b) > lenmsg {
copy(msg[off:], b)
off = lenmsg
continue
}
// Actual data
copy(msg[off:off+len(b)], b)
off += len(b)
}
case `dns:"a"`:
if val.Type().String() == "dns.IPSECKEY" {
// Field(2) is GatewayType, must be 1
if val.Field(2).Uint() != 1 {
continue
}
}
// It must be a slice of 4, even if it is 16, we encode
// only the first 4
if off+net.IPv4len > lenmsg {
return lenmsg, &Error{err: "overflow packing a"}
}
switch fv.Len() {
case net.IPv6len:
msg[off] = byte(fv.Index(12).Uint())
msg[off+1] = byte(fv.Index(13).Uint())
msg[off+2] = byte(fv.Index(14).Uint())
msg[off+3] = byte(fv.Index(15).Uint())
off += net.IPv4len
case net.IPv4len:
msg[off] = byte(fv.Index(0).Uint())
msg[off+1] = byte(fv.Index(1).Uint())
msg[off+2] = byte(fv.Index(2).Uint())
msg[off+3] = byte(fv.Index(3).Uint())
off += net.IPv4len
case 0:
// Allowed, for dynamic updates
default:
return lenmsg, &Error{err: "overflow packing a"}
}
case `dns:"aaaa"`:
if val.Type().String() == "dns.IPSECKEY" {
// Field(2) is GatewayType, must be 2
if val.Field(2).Uint() != 2 {
continue
}
}
if fv.Len() == 0 {
break
}
if fv.Len() > net.IPv6len || off+fv.Len() > lenmsg {
return lenmsg, &Error{err: "overflow packing aaaa"}
}
for j := 0; j < net.IPv6len; j++ {
msg[off] = byte(fv.Index(j).Uint())
off++
}
case `dns:"wks"`:
// TODO(miek): this is wrong should be lenrd
if off == lenmsg {
break // dyn. updates
}
if val.Field(i).Len() == 0 {
break
}
var bitmapbyte uint16
for j := 0; j < val.Field(i).Len(); j++ {
serv := uint16((fv.Index(j).Uint()))
bitmapbyte = uint16(serv / 8)
if int(bitmapbyte) > lenmsg {
return lenmsg, &Error{err: "overflow packing wks"}
}
bit := uint16(serv) - bitmapbyte*8
msg[bitmapbyte] = byte(1 << (7 - bit))
}
off += int(bitmapbyte)
case `dns:"nsec"`: // NSEC/NSEC3
// This is the uint16 type bitmap
if val.Field(i).Len() == 0 {
// Do absolutely nothing
break
}
lastwindow := uint16(0)
length := uint16(0)
if off+2 > lenmsg {
return lenmsg, &Error{err: "overflow packing nsecx"}
}
for j := 0; j < val.Field(i).Len(); j++ {
t := uint16((fv.Index(j).Uint()))
window := uint16(t / 256)
if lastwindow != window {
// New window, jump to the new offset
off += int(length) + 3
if off > lenmsg {
return lenmsg, &Error{err: "overflow packing nsecx bitmap"}
}
}
length = (t - window*256) / 8
bit := t - (window * 256) - (length * 8)
if off+2+int(length) > lenmsg {
return lenmsg, &Error{err: "overflow packing nsecx bitmap"}
}
// Setting the window #
msg[off] = byte(window)
// Setting the octets length
msg[off+1] = byte(length + 1)
// Setting the bit value for the type in the right octet
msg[off+2+int(length)] |= byte(1 << (7 - bit))
lastwindow = window
}
off += 2 + int(length)
off++
if off > lenmsg {
return lenmsg, &Error{err: "overflow packing nsecx bitmap"}
}
}
case reflect.Struct:
off, err = packStructValue(fv, msg, off, compression, compress)
if err != nil {
return lenmsg, err
}
case reflect.Uint8:
if off+1 > lenmsg {
return lenmsg, &Error{err: "overflow packing uint8"}
}
msg[off] = byte(fv.Uint())
off++
case reflect.Uint16:
if off+2 > lenmsg {
return lenmsg, &Error{err: "overflow packing uint16"}
}
i := fv.Uint()
msg[off] = byte(i >> 8)
msg[off+1] = byte(i)
off += 2
case reflect.Uint32:
if off+4 > lenmsg {
return lenmsg, &Error{err: "overflow packing uint32"}
}
i := fv.Uint()
msg[off] = byte(i >> 24)
msg[off+1] = byte(i >> 16)
msg[off+2] = byte(i >> 8)
msg[off+3] = byte(i)
off += 4
case reflect.Uint64:
switch typefield.Tag {
default:
if off+8 > lenmsg {
return lenmsg, &Error{err: "overflow packing uint64"}
}
i := fv.Uint()
msg[off] = byte(i >> 56)
msg[off+1] = byte(i >> 48)
msg[off+2] = byte(i >> 40)
msg[off+3] = byte(i >> 32)
msg[off+4] = byte(i >> 24)
msg[off+5] = byte(i >> 16)
msg[off+6] = byte(i >> 8)
msg[off+7] = byte(i)
off += 8
case `dns:"uint48"`:
// Used in TSIG, where it stops at 48 bits, so we discard the upper 16
if off+6 > lenmsg {
return lenmsg, &Error{err: "overflow packing uint64 as uint48"}
}
i := fv.Uint()
msg[off] = byte(i >> 40)
msg[off+1] = byte(i >> 32)
msg[off+2] = byte(i >> 24)
msg[off+3] = byte(i >> 16)
msg[off+4] = byte(i >> 8)
msg[off+5] = byte(i)
off += 6
}
case reflect.String:
// There are multiple string encodings.
// The tag distinguishes ordinary strings from domain names.
s := fv.String()
switch typefield.Tag {
default:
return lenmsg, &Error{"bad tag packing string: " + typefield.Tag.Get("dns")}
case `dns:"base64"`:
b64, e := fromBase64([]byte(s))
if e != nil {
return lenmsg, e
}
copy(msg[off:off+len(b64)], b64)
off += len(b64)
case `dns:"domain-name"`:
if val.Type().String() == "dns.IPSECKEY" {
// Field(2) is GatewayType, 1 and 2 or used for addresses
x := val.Field(2).Uint()
if x == 1 || x == 2 {
continue
}
}
if off, err = PackDomainName(s, msg, off, compression, false && compress); err != nil {
return lenmsg, err
}
case `dns:"cdomain-name"`:
if off, err = PackDomainName(s, msg, off, compression, true && compress); err != nil {
return lenmsg, err
}
case `dns:"size-base32"`:
// This is purely for NSEC3 atm, the previous byte must
// holds the length of the encoded string. As NSEC3
// is only defined to SHA1, the hashlength is 20 (160 bits)
msg[off-1] = 20
fallthrough
case `dns:"base32"`:
b32, e := fromBase32([]byte(s))
if e != nil {
return lenmsg, e
}
copy(msg[off:off+len(b32)], b32)
off += len(b32)
case `dns:"size-hex"`:
fallthrough
case `dns:"hex"`:
// There is no length encoded here
h, e := hex.DecodeString(s)
if e != nil {
return lenmsg, e
}
if off+hex.DecodedLen(len(s)) > lenmsg {
return lenmsg, &Error{err: "overflow packing hex"}
}
copy(msg[off:off+hex.DecodedLen(len(s))], h)
off += hex.DecodedLen(len(s))
case `dns:"size"`:
// the size is already encoded in the RR, we can safely use the
// length of string. String is RAW (not encoded in hex, nor base64)
copy(msg[off:off+len(s)], s)
off += len(s)
case `dns:"octet"`:
bytesTmp := make([]byte, 256)
off, err = packOctetString(fv.String(), msg, off, bytesTmp)
if err != nil {
return lenmsg, err
}
case `dns:"txt"`:
fallthrough
case "":
if txtTmp == nil {
txtTmp = make([]byte, 256*4+1)
}
off, err = packTxtString(fv.String(), msg, off, txtTmp)
if err != nil {
return lenmsg, err
}
}
}
}
return off, nil
}
func structValue(any interface{}) reflect.Value {
return reflect.ValueOf(any).Elem()
}
// PackStruct packs any structure to wire format.
func PackStruct(any interface{}, msg []byte, off int) (off1 int, err error) {
off, err = packStructValue(structValue(any), msg, off, nil, false)
return off, err
}
func packStructCompress(any interface{}, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
off, err = packStructValue(structValue(any), msg, off, compression, compress)
return off, err
}
// TODO(miek): Fix use of rdlength here
// Unpack a reflect.StructValue from msg.
// Same restrictions as packStructValue.
func unpackStructValue(val reflect.Value, msg []byte, off int) (off1 int, err error) {
var lenrd int
lenmsg := len(msg)
for i := 0; i < val.NumField(); i++ {
if lenrd != 0 && lenrd == off {
break
}
if off > lenmsg {
return lenmsg, &Error{"bad offset unpacking"}
}
switch fv := val.Field(i); fv.Kind() {
default:
return lenmsg, &Error{err: "bad kind unpacking"}
case reflect.Interface:
// PrivateRR is the only RR implementation that has interface field.
// therefore it's expected that this interface would be PrivateRdata
switch data := fv.Interface().(type) {
case PrivateRdata:
n, err := data.Unpack(msg[off:lenrd])
if err != nil {
return lenmsg, err
}
off += n
default:
return lenmsg, &Error{err: "bad kind interface unpacking"}
}
case reflect.Slice:
switch val.Type().Field(i).Tag {
default:
return lenmsg, &Error{"bad tag unpacking slice: " + val.Type().Field(i).Tag.Get("dns")}
case `dns:"domain-name"`:
// HIP record slice of name (or none)
var servers []string
var s string
for off < lenrd {
s, off, err = UnpackDomainName(msg, off)
if err != nil {
return lenmsg, err
}
servers = append(servers, s)
}
fv.Set(reflect.ValueOf(servers))
case `dns:"txt"`:
if off == lenmsg || lenrd == off {
break
}
var txt []string
txt, off, err = unpackTxt(msg, off, lenrd)
if err != nil {
return lenmsg, err
}
fv.Set(reflect.ValueOf(txt))
case `dns:"opt"`: // edns0
if off == lenrd {
// This is an EDNS0 (OPT Record) with no rdata
// We can safely return here.
break
}
var edns []EDNS0
Option:
code := uint16(0)
if off+2 > lenmsg {
return lenmsg, &Error{err: "overflow unpacking opt"}
}
code, off = unpackUint16(msg, off)
optlen, off1 := unpackUint16(msg, off)
if off1+int(optlen) > lenrd {
return lenmsg, &Error{err: "overflow unpacking opt"}
}
switch code {
case EDNS0NSID:
e := new(EDNS0_NSID)
if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
return lenmsg, err
}
edns = append(edns, e)
off = off1 + int(optlen)
case EDNS0SUBNET, EDNS0SUBNETDRAFT:
e := new(EDNS0_SUBNET)
if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
return lenmsg, err
}
edns = append(edns, e)
off = off1 + int(optlen)
if code == EDNS0SUBNETDRAFT {
e.DraftOption = true
}
case EDNS0UL:
e := new(EDNS0_UL)
if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
return lenmsg, err
}
edns = append(edns, e)
off = off1 + int(optlen)
case EDNS0LLQ:
e := new(EDNS0_LLQ)
if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
return lenmsg, err
}
edns = append(edns, e)
off = off1 + int(optlen)
case EDNS0DAU:
e := new(EDNS0_DAU)
if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
return lenmsg, err
}
edns = append(edns, e)
off = off1 + int(optlen)
case EDNS0DHU:
e := new(EDNS0_DHU)
if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
return lenmsg, err
}
edns = append(edns, e)
off = off1 + int(optlen)
case EDNS0N3U:
e := new(EDNS0_N3U)
if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
return lenmsg, err
}
edns = append(edns, e)
off = off1 + int(optlen)
default:
e := new(EDNS0_LOCAL)
e.Code = code
if err := e.unpack(msg[off1 : off1+int(optlen)]); err != nil {
return lenmsg, err
}
edns = append(edns, e)
off = off1 + int(optlen)
}
if off < lenrd {
goto Option
}
fv.Set(reflect.ValueOf(edns))
case `dns:"a"`:
if val.Type().String() == "dns.IPSECKEY" {
// Field(2) is GatewayType, must be 1
if val.Field(2).Uint() != 1 {
continue
}
}
if off == lenrd {
break // dyn. update
}
if off+net.IPv4len > lenrd || off+net.IPv4len > lenmsg {
return lenmsg, &Error{err: "overflow unpacking a"}
}
fv.Set(reflect.ValueOf(net.IPv4(msg[off], msg[off+1], msg[off+2], msg[off+3])))
off += net.IPv4len
case `dns:"aaaa"`:
if val.Type().String() == "dns.IPSECKEY" {
// Field(2) is GatewayType, must be 2
if val.Field(2).Uint() != 2 {
continue
}
}
if off == lenrd {
break
}
if off+net.IPv6len > lenrd || off+net.IPv6len > lenmsg {
return lenmsg, &Error{err: "overflow unpacking aaaa"}
}
fv.Set(reflect.ValueOf(net.IP{msg[off], msg[off+1], msg[off+2], msg[off+3], msg[off+4],
msg[off+5], msg[off+6], msg[off+7], msg[off+8], msg[off+9], msg[off+10],
msg[off+11], msg[off+12], msg[off+13], msg[off+14], msg[off+15]}))
off += net.IPv6len
case `dns:"wks"`:
// Rest of the record is the bitmap
var serv []uint16
j := 0
for off < lenrd {
if off+1 > lenmsg {
return lenmsg, &Error{err: "overflow unpacking wks"}
}
b := msg[off]
// Check the bits one by one, and set the type
if b&0x80 == 0x80 {
serv = append(serv, uint16(j*8+0))
}
if b&0x40 == 0x40 {
serv = append(serv, uint16(j*8+1))
}
if b&0x20 == 0x20 {
serv = append(serv, uint16(j*8+2))
}
if b&0x10 == 0x10 {
serv = append(serv, uint16(j*8+3))
}
if b&0x8 == 0x8 {
serv = append(serv, uint16(j*8+4))
}
if b&0x4 == 0x4 {
serv = append(serv, uint16(j*8+5))
}
if b&0x2 == 0x2 {
serv = append(serv, uint16(j*8+6))
}
if b&0x1 == 0x1 {
serv = append(serv, uint16(j*8+7))
}
j++
off++
}
fv.Set(reflect.ValueOf(serv))
case `dns:"nsec"`: // NSEC/NSEC3
if off == lenrd {
break
}
// Rest of the record is the type bitmap
if off+2 > lenrd || off+2 > lenmsg {
return lenmsg, &Error{err: "overflow unpacking nsecx"}
}
var nsec []uint16
length := 0
window := 0
for off+2 < lenrd {
if off+2 > lenmsg {
return lenmsg, &Error{err: "overflow unpacking nsecx"}
}
window = int(msg[off])
length = int(msg[off+1])
//println("off, windows, length, end", off, window, length, endrr)
if length == 0 {
// A length window of zero is strange. If there
// the window should not have been specified. Bail out
// println("dns: length == 0 when unpacking NSEC")
return lenmsg, &Error{err: "overflow unpacking nsecx"}
}
if length > 32 {
return lenmsg, &Error{err: "overflow unpacking nsecx"}
}
// Walk the bytes in the window - and check the bit settings...
off += 2
for j := 0; j < length; j++ {
if off+j+1 > lenmsg {
return lenmsg, &Error{err: "overflow unpacking nsecx"}
}
b := msg[off+j]
// Check the bits one by one, and set the type
if b&0x80 == 0x80 {
nsec = append(nsec, uint16(window*256+j*8+0))
}
if b&0x40 == 0x40 {
nsec = append(nsec, uint16(window*256+j*8+1))
}
if b&0x20 == 0x20 {
nsec = append(nsec, uint16(window*256+j*8+2))
}
if b&0x10 == 0x10 {
nsec = append(nsec, uint16(window*256+j*8+3))
}
if b&0x8 == 0x8 {
nsec = append(nsec, uint16(window*256+j*8+4))
}
if b&0x4 == 0x4 {
nsec = append(nsec, uint16(window*256+j*8+5))
}
if b&0x2 == 0x2 {
nsec = append(nsec, uint16(window*256+j*8+6))
}
if b&0x1 == 0x1 {
nsec = append(nsec, uint16(window*256+j*8+7))
}
}
off += length
}
fv.Set(reflect.ValueOf(nsec))
}
case reflect.Struct:
off, err = unpackStructValue(fv, msg, off)
if err != nil {
return lenmsg, err
}
if val.Type().Field(i).Name == "Hdr" {
lenrd = off + int(val.FieldByName("Hdr").FieldByName("Rdlength").Uint())
}
case reflect.Uint8:
if off == lenmsg {
break
}
if off+1 > lenmsg {
return lenmsg, &Error{err: "overflow unpacking uint8"}
}
fv.SetUint(uint64(uint8(msg[off])))
off++
case reflect.Uint16:
if off == lenmsg {
break
}
var i uint16
if off+2 > lenmsg {
return lenmsg, &Error{err: "overflow unpacking uint16"}
}
i, off = unpackUint16(msg, off)
fv.SetUint(uint64(i))
case reflect.Uint32:
if off == lenmsg {
break
}
if off+4 > lenmsg {
return lenmsg, &Error{err: "overflow unpacking uint32"}
}
fv.SetUint(uint64(uint32(msg[off])<<24 | uint32(msg[off+1])<<16 | uint32(msg[off+2])<<8 | uint32(msg[off+3])))
off += 4
case reflect.Uint64:
switch val.Type().Field(i).Tag {
default:
if off+8 > lenmsg {
return lenmsg, &Error{err: "overflow unpacking uint64"}
}
fv.SetUint(uint64(uint64(msg[off])<<56 | uint64(msg[off+1])<<48 | uint64(msg[off+2])<<40 |
uint64(msg[off+3])<<32 | uint64(msg[off+4])<<24 | uint64(msg[off+5])<<16 | uint64(msg[off+6])<<8 | uint64(msg[off+7])))
off += 8
case `dns:"uint48"`:
// Used in TSIG where the last 48 bits are occupied, so for now, assume a uint48 (6 bytes)
if off+6 > lenmsg {
return lenmsg, &Error{err: "overflow unpacking uint64 as uint48"}
}
fv.SetUint(uint64(uint64(msg[off])<<40 | uint64(msg[off+1])<<32 | uint64(msg[off+2])<<24 | uint64(msg[off+3])<<16 |
uint64(msg[off+4])<<8 | uint64(msg[off+5])))
off += 6
}
case reflect.String:
var s string
if off == lenmsg {
break
}
switch val.Type().Field(i).Tag {
default:
return lenmsg, &Error{"bad tag unpacking string: " + val.Type().Field(i).Tag.Get("dns")}
case `dns:"octet"`:
strend := lenrd
if strend > lenmsg {
return lenmsg, &Error{err: "overflow unpacking octet"}
}
s = string(msg[off:strend])
off = strend
case `dns:"hex"`:
hexend := lenrd
if val.FieldByName("Hdr").FieldByName("Rrtype").Uint() == uint64(TypeHIP) {
hexend = off + int(val.FieldByName("HitLength").Uint())
}
if hexend > lenrd || hexend > lenmsg {
return lenmsg, &Error{err: "overflow unpacking hex"}
}
s = hex.EncodeToString(msg[off:hexend])
off = hexend
case `dns:"base64"`:
// Rest of the RR is base64 encoded value
b64end := lenrd
if val.FieldByName("Hdr").FieldByName("Rrtype").Uint() == uint64(TypeHIP) {
b64end = off + int(val.FieldByName("PublicKeyLength").Uint())
}
if b64end > lenrd || b64end > lenmsg {
return lenmsg, &Error{err: "overflow unpacking base64"}
}
s = toBase64(msg[off:b64end])
off = b64end
case `dns:"cdomain-name"`:
fallthrough
case `dns:"domain-name"`:
if val.Type().String() == "dns.IPSECKEY" {
// Field(2) is GatewayType, 1 and 2 or used for addresses
x := val.Field(2).Uint()
if x == 1 || x == 2 {
continue
}
}
if off == lenmsg {
// zero rdata foo, OK for dyn. updates
break
}
s, off, err = UnpackDomainName(msg, off)
if err != nil {
return lenmsg, err
}
case `dns:"size-base32"`:
var size int
switch val.Type().Name() {
case "NSEC3":
switch val.Type().Field(i).Name {
case "NextDomain":
name := val.FieldByName("HashLength")
size = int(name.Uint())
}
}
if off+size > lenmsg {
return lenmsg, &Error{err: "overflow unpacking base32"}
}
s = toBase32(msg[off : off+size])
off += size
case `dns:"size-hex"`:
// a "size" string, but it must be encoded in hex in the string
var size int
switch val.Type().Name() {
case "NSEC3":
switch val.Type().Field(i).Name {
case "Salt":
name := val.FieldByName("SaltLength")
size = int(name.Uint())
case "NextDomain":
name := val.FieldByName("HashLength")
size = int(name.Uint())
}
case "TSIG":
switch val.Type().Field(i).Name {
case "MAC":
name := val.FieldByName("MACSize")
size = int(name.Uint())
case "OtherData":
name := val.FieldByName("OtherLen")
size = int(name.Uint())
}
}
if off+size > lenmsg {
return lenmsg, &Error{err: "overflow unpacking hex"}
}
s = hex.EncodeToString(msg[off : off+size])
off += size
case `dns:"txt"`:
fallthrough
case "":
s, off, err = unpackTxtString(msg, off)
}
fv.SetString(s)
}
}
return off, nil
}
// Helpers for dealing with escaped bytes
func isDigit(b byte) bool { return b >= '0' && b <= '9' }
func dddToByte(s []byte) byte {
return byte((s[0]-'0')*100 + (s[1]-'0')*10 + (s[2] - '0'))
}
// UnpackStruct unpacks a binary message from offset off to the interface
// value given.
func UnpackStruct(any interface{}, msg []byte, off int) (int, error) {
return unpackStructValue(structValue(any), msg, off)
}
// Helper function for packing and unpacking
func intToBytes(i *big.Int, length int) []byte {
buf := i.Bytes()
if len(buf) < length {
b := make([]byte, length)
copy(b[length-len(buf):], buf)
return b
}
return buf
}
func unpackUint16(msg []byte, off int) (uint16, int) {
return uint16(msg[off])<<8 | uint16(msg[off+1]), off + 2
}
func packUint16(i uint16) (byte, byte) {
return byte(i >> 8), byte(i)
}
func toBase32(b []byte) string {
return base32.HexEncoding.EncodeToString(b)
}
func fromBase32(s []byte) (buf []byte, err error) {
buflen := base32.HexEncoding.DecodedLen(len(s))
buf = make([]byte, buflen)
n, err := base32.HexEncoding.Decode(buf, s)
buf = buf[:n]
return
}
func toBase64(b []byte) string {
return base64.StdEncoding.EncodeToString(b)
}
func fromBase64(s []byte) (buf []byte, err error) {
buflen := base64.StdEncoding.DecodedLen(len(s))
buf = make([]byte, buflen)
n, err := base64.StdEncoding.Decode(buf, s)
buf = buf[:n]
return
}
// PackRR packs a resource record rr into msg[off:].
// See PackDomainName for documentation about the compression.
func PackRR(rr RR, msg []byte, off int, compression map[string]int, compress bool) (off1 int, err error) {
if rr == nil {
return len(msg), &Error{err: "nil rr"}
}
off1, err = packStructCompress(rr, msg, off, compression, compress)
if err != nil {
return len(msg), err
}
if rawSetRdlength(msg, off, off1) {
return off1, nil
}
return off, ErrRdata
}
// UnpackRR unpacks msg[off:] into an RR.
func UnpackRR(msg []byte, off int) (rr RR, off1 int, err error) {
// unpack just the header, to find the rr type and length
var h RR_Header
off0 := off
if off, err = UnpackStruct(&h, msg, off); err != nil {
return nil, len(msg), err
}
end := off + int(h.Rdlength)
// make an rr of that type and re-unpack.
mk, known := typeToRR[h.Rrtype]
if !known {
rr = new(RFC3597)
} else {
rr = mk()
}
off, err = UnpackStruct(rr, msg, off0)
if off != end {
return &h, end, &Error{err: "bad rdlength"}
}
return rr, off, err
}
// Reverse a map
func reverseInt8(m map[uint8]string) map[string]uint8 {
n := make(map[string]uint8)
for u, s := range m {
n[s] = u
}
return n
}
func reverseInt16(m map[uint16]string) map[string]uint16 {
n := make(map[string]uint16)
for u, s := range m {
n[s] = u
}
return n
}
func reverseInt(m map[int]string) map[string]int {
n := make(map[string]int)
for u, s := range m {
n[s] = u
}
return n
}
// Convert a MsgHdr to a string, with dig-like headers:
//
//;; opcode: QUERY, status: NOERROR, id: 48404
//
//;; flags: qr aa rd ra;
func (h *MsgHdr) String() string {
if h == nil {
return "<nil> MsgHdr"
}
s := ";; opcode: " + OpcodeToString[h.Opcode]
s += ", status: " + RcodeToString[h.Rcode]
s += ", id: " + strconv.Itoa(int(h.Id)) + "\n"
s += ";; flags:"
if h.Response {
s += " qr"
}
if h.Authoritative {
s += " aa"
}
if h.Truncated {
s += " tc"
}
if h.RecursionDesired {
s += " rd"
}
if h.RecursionAvailable {
s += " ra"
}
if h.Zero { // Hmm
s += " z"
}
if h.AuthenticatedData {
s += " ad"
}
if h.CheckingDisabled {
s += " cd"
}
s += ";"
return s
}
// Pack packs a Msg: it is converted to to wire format.
// If the dns.Compress is true the message will be in compressed wire format.
func (dns *Msg) Pack() (msg []byte, err error) {
return dns.PackBuffer(nil)
}
// PackBuffer packs a Msg, using the given buffer buf. If buf is too small
// a new buffer is allocated.
func (dns *Msg) PackBuffer(buf []byte) (msg []byte, err error) {
var dh Header
var compression map[string]int
if dns.Compress {
compression = make(map[string]int) // Compression pointer mappings
}
if dns.Rcode < 0 || dns.Rcode > 0xFFF {
return nil, ErrRcode
}
if dns.Rcode > 0xF {
// Regular RCODE field is 4 bits
opt := dns.IsEdns0()
if opt == nil {
return nil, ErrExtendedRcode
}
opt.SetExtendedRcode(uint8(dns.Rcode >> 4))
dns.Rcode &= 0xF
}
// Convert convenient Msg into wire-like Header.
dh.Id = dns.Id
dh.Bits = uint16(dns.Opcode)<<11 | uint16(dns.Rcode)
if dns.Response {
dh.Bits |= _QR
}
if dns.Authoritative {
dh.Bits |= _AA
}
if dns.Truncated {
dh.Bits |= _TC
}
if dns.RecursionDesired {
dh.Bits |= _RD
}
if dns.RecursionAvailable {
dh.Bits |= _RA
}
if dns.Zero {
dh.Bits |= _Z
}
if dns.AuthenticatedData {
dh.Bits |= _AD
}
if dns.CheckingDisabled {
dh.Bits |= _CD
}
// Prepare variable sized arrays.
question := dns.Question
answer := dns.Answer
ns := dns.Ns
extra := dns.Extra
dh.Qdcount = uint16(len(question))
dh.Ancount = uint16(len(answer))
dh.Nscount = uint16(len(ns))
dh.Arcount = uint16(len(extra))
// We need the uncompressed length here, because we first pack it and then compress it.
msg = buf
compress := dns.Compress
dns.Compress = false
if packLen := dns.Len() + 1; len(msg) < packLen {
msg = make([]byte, packLen)
}
dns.Compress = compress
// Pack it in: header and then the pieces.
off := 0
off, err = packStructCompress(&dh, msg, off, compression, dns.Compress)
if err != nil {
return nil, err
}
for i := 0; i < len(question); i++ {
off, err = packStructCompress(&question[i], msg, off, compression, dns.Compress)
if err != nil {
return nil, err
}
}
for i := 0; i < len(answer); i++ {
off, err = PackRR(answer[i], msg, off, compression, dns.Compress)
if err != nil {
return nil, err
}
}
for i := 0; i < len(ns); i++ {
off, err = PackRR(ns[i], msg, off, compression, dns.Compress)
if err != nil {
return nil, err
}
}
for i := 0; i < len(extra); i++ {
off, err = PackRR(extra[i], msg, off, compression, dns.Compress)
if err != nil {
return nil, err
}
}
return msg[:off], nil
}
// Unpack unpacks a binary message to a Msg structure.
func (dns *Msg) Unpack(msg []byte) (err error) {
// Header.
var dh Header
off := 0
if off, err = UnpackStruct(&dh, msg, off); err != nil {
return err
}
dns.Id = dh.Id
dns.Response = (dh.Bits & _QR) != 0
dns.Opcode = int(dh.Bits>>11) & 0xF
dns.Authoritative = (dh.Bits & _AA) != 0
dns.Truncated = (dh.Bits & _TC) != 0
dns.RecursionDesired = (dh.Bits & _RD) != 0
dns.RecursionAvailable = (dh.Bits & _RA) != 0
dns.Zero = (dh.Bits & _Z) != 0
dns.AuthenticatedData = (dh.Bits & _AD) != 0
dns.CheckingDisabled = (dh.Bits & _CD) != 0
dns.Rcode = int(dh.Bits & 0xF)
// Don't pre-alloc these arrays, the incoming lengths are from the network.
dns.Question = make([]Question, 0, 1)
dns.Answer = make([]RR, 0, 10)
dns.Ns = make([]RR, 0, 10)
dns.Extra = make([]RR, 0, 10)
var q Question
for i := 0; i < int(dh.Qdcount); i++ {
off1 := off
off, err = UnpackStruct(&q, msg, off)
if err != nil {
return err
}
if off1 == off { // Offset does not increase anymore, dh.Qdcount is a lie!
dh.Qdcount = uint16(i)
break
}
dns.Question = append(dns.Question, q)
}
// If we see a TC bit being set we return here, without
// an error, because technically it isn't an error. So return
// without parsing the potentially corrupt packet and hitting an error.
// TODO(miek): this isn't the best strategy!
if dns.Truncated {
dns.Answer = nil
dns.Ns = nil
dns.Extra = nil
return nil
}
var r RR
for i := 0; i < int(dh.Ancount); i++ {
off1 := off
r, off, err = UnpackRR(msg, off)
if err != nil {
return err
}
if off1 == off { // Offset does not increase anymore, dh.Ancount is a lie!
dh.Ancount = uint16(i)
break
}
dns.Answer = append(dns.Answer, r)
}
for i := 0; i < int(dh.Nscount); i++ {
off1 := off
r, off, err = UnpackRR(msg, off)
if err != nil {
return err
}
if off1 == off { // Offset does not increase anymore, dh.Nscount is a lie!
dh.Nscount = uint16(i)
break
}
dns.Ns = append(dns.Ns, r)
}
for i := 0; i < int(dh.Arcount); i++ {
off1 := off
r, off, err = UnpackRR(msg, off)
if err != nil {
return err
}
if off1 == off { // Offset does not increase anymore, dh.Arcount is a lie!
dh.Arcount = uint16(i)
break
}
dns.Extra = append(dns.Extra, r)
}
if off != len(msg) {
// TODO(miek) make this an error?
// use PackOpt to let people tell how detailed the error reporting should be?
// println("dns: extra bytes in dns packet", off, "<", len(msg))
}
return nil
}
// Convert a complete message to a string with dig-like output.
func (dns *Msg) String() string {
if dns == nil {
return "<nil> MsgHdr"
}
s := dns.MsgHdr.String() + " "
s += "QUERY: " + strconv.Itoa(len(dns.Question)) + ", "
s += "ANSWER: " + strconv.Itoa(len(dns.Answer)) + ", "
s += "AUTHORITY: " + strconv.Itoa(len(dns.Ns)) + ", "
s += "ADDITIONAL: " + strconv.Itoa(len(dns.Extra)) + "\n"
if len(dns.Question) > 0 {
s += "\n;; QUESTION SECTION:\n"
for i := 0; i < len(dns.Question); i++ {
s += dns.Question[i].String() + "\n"
}
}
if len(dns.Answer) > 0 {
s += "\n;; ANSWER SECTION:\n"
for i := 0; i < len(dns.Answer); i++ {
if dns.Answer[i] != nil {
s += dns.Answer[i].String() + "\n"
}
}
}
if len(dns.Ns) > 0 {
s += "\n;; AUTHORITY SECTION:\n"
for i := 0; i < len(dns.Ns); i++ {
if dns.Ns[i] != nil {
s += dns.Ns[i].String() + "\n"
}
}
}
if len(dns.Extra) > 0 {
s += "\n;; ADDITIONAL SECTION:\n"
for i := 0; i < len(dns.Extra); i++ {
if dns.Extra[i] != nil {
s += dns.Extra[i].String() + "\n"
}
}
}
return s
}
// Len returns the message length when in (un)compressed wire format.
// If dns.Compress is true compression it is taken into account. Len()
// is provided to be a faster way to get the size of the resulting packet,
// than packing it, measuring the size and discarding the buffer.
func (dns *Msg) Len() int {
// We always return one more than needed.
l := 12 // Message header is always 12 bytes
var compression map[string]int
if dns.Compress {
compression = make(map[string]int)
}
for i := 0; i < len(dns.Question); i++ {
l += dns.Question[i].len()
if dns.Compress {
compressionLenHelper(compression, dns.Question[i].Name)
}
}
for i := 0; i < len(dns.Answer); i++ {
l += dns.Answer[i].len()
if dns.Compress {
k, ok := compressionLenSearch(compression, dns.Answer[i].Header().Name)
if ok {
l += 1 - k
}
compressionLenHelper(compression, dns.Answer[i].Header().Name)
k, ok = compressionLenSearchType(compression, dns.Answer[i])
if ok {
l += 1 - k
}
compressionLenHelperType(compression, dns.Answer[i])
}
}
for i := 0; i < len(dns.Ns); i++ {
l += dns.Ns[i].len()
if dns.Compress {
k, ok := compressionLenSearch(compression, dns.Ns[i].Header().Name)
if ok {
l += 1 - k
}
compressionLenHelper(compression, dns.Ns[i].Header().Name)
k, ok = compressionLenSearchType(compression, dns.Ns[i])
if ok {
l += 1 - k
}
compressionLenHelperType(compression, dns.Ns[i])
}
}
for i := 0; i < len(dns.Extra); i++ {
l += dns.Extra[i].len()
if dns.Compress {
k, ok := compressionLenSearch(compression, dns.Extra[i].Header().Name)
if ok {
l += 1 - k
}
compressionLenHelper(compression, dns.Extra[i].Header().Name)
k, ok = compressionLenSearchType(compression, dns.Extra[i])
if ok {
l += 1 - k
}
compressionLenHelperType(compression, dns.Extra[i])
}
}
return l
}
// Put the parts of the name in the compression map.
func compressionLenHelper(c map[string]int, s string) {
pref := ""
lbs := Split(s)
for j := len(lbs) - 1; j >= 0; j-- {
pref = s[lbs[j]:]
if _, ok := c[pref]; !ok {
c[pref] = len(pref)
}
}
}
// Look for each part in the compression map and returns its length,
// keep on searching so we get the longest match.
func compressionLenSearch(c map[string]int, s string) (int, bool) {
off := 0
end := false
if s == "" { // don't bork on bogus data
return 0, false
}
for {
if _, ok := c[s[off:]]; ok {
return len(s[off:]), true
}
if end {
break
}
off, end = NextLabel(s, off)
}
return 0, false
}
// TODO(miek): should add all types, because the all can be *used* for compression.
func compressionLenHelperType(c map[string]int, r RR) {
switch x := r.(type) {
case *NS:
compressionLenHelper(c, x.Ns)
case *MX:
compressionLenHelper(c, x.Mx)
case *CNAME:
compressionLenHelper(c, x.Target)
case *PTR:
compressionLenHelper(c, x.Ptr)
case *SOA:
compressionLenHelper(c, x.Ns)
compressionLenHelper(c, x.Mbox)
case *MB:
compressionLenHelper(c, x.Mb)
case *MG:
compressionLenHelper(c, x.Mg)
case *MR:
compressionLenHelper(c, x.Mr)
case *MF:
compressionLenHelper(c, x.Mf)
case *MD:
compressionLenHelper(c, x.Md)
case *RT:
compressionLenHelper(c, x.Host)
case *MINFO:
compressionLenHelper(c, x.Rmail)
compressionLenHelper(c, x.Email)
case *AFSDB:
compressionLenHelper(c, x.Hostname)
}
}
// Only search on compressing these types.
func compressionLenSearchType(c map[string]int, r RR) (int, bool) {
switch x := r.(type) {
case *NS:
return compressionLenSearch(c, x.Ns)
case *MX:
return compressionLenSearch(c, x.Mx)
case *CNAME:
return compressionLenSearch(c, x.Target)
case *PTR:
return compressionLenSearch(c, x.Ptr)
case *SOA:
k, ok := compressionLenSearch(c, x.Ns)
k1, ok1 := compressionLenSearch(c, x.Mbox)
if !ok && !ok1 {
return 0, false
}
return k + k1, true
case *MB:
return compressionLenSearch(c, x.Mb)
case *MG:
return compressionLenSearch(c, x.Mg)
case *MR:
return compressionLenSearch(c, x.Mr)
case *MF:
return compressionLenSearch(c, x.Mf)
case *MD:
return compressionLenSearch(c, x.Md)
case *RT:
return compressionLenSearch(c, x.Host)
case *MINFO:
k, ok := compressionLenSearch(c, x.Rmail)
k1, ok1 := compressionLenSearch(c, x.Email)
if !ok && !ok1 {
return 0, false
}
return k + k1, true
case *AFSDB:
return compressionLenSearch(c, x.Hostname)
}
return 0, false
}
// id returns a 16 bits random number to be used as a
// message id. The random provided should be good enough.
func id() uint16 {
return uint16(rand.Int()) ^ uint16(time.Now().Nanosecond())
}
// Copy returns a new RR which is a deep-copy of r.
func Copy(r RR) RR {
r1 := r.copy()
return r1
}
// Copy returns a new *Msg which is a deep-copy of dns.
func (dns *Msg) Copy() *Msg {
return dns.CopyTo(new(Msg))
}
// CopyTo copies the contents to the provided message using a deep-copy and returns the copy.
func (dns *Msg) CopyTo(r1 *Msg) *Msg {
r1.MsgHdr = dns.MsgHdr
r1.Compress = dns.Compress
if len(dns.Question) > 0 {
r1.Question = make([]Question, len(dns.Question))
copy(r1.Question, dns.Question) // TODO(miek): Question is an immutable value, ok to do a shallow-copy
}
rrArr := make([]RR, len(dns.Answer)+len(dns.Ns)+len(dns.Extra))
var rri int
if len(dns.Answer) > 0 {
rrbegin := rri
for i := 0; i < len(dns.Answer); i++ {
rrArr[rri] = dns.Answer[i].copy()
rri++
}
r1.Answer = rrArr[rrbegin:rri:rri]
}
if len(dns.Ns) > 0 {
rrbegin := rri
for i := 0; i < len(dns.Ns); i++ {
rrArr[rri] = dns.Ns[i].copy()
rri++
}
r1.Ns = rrArr[rrbegin:rri:rri]
}
if len(dns.Extra) > 0 {
rrbegin := rri
for i := 0; i < len(dns.Extra); i++ {
rrArr[rri] = dns.Extra[i].copy()
rri++
}
r1.Extra = rrArr[rrbegin:rri:rri]
}
return r1
}
| bsd-3-clause |