code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from .local import Local # noqa
from .production import Production # noqa
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
|
Java
|
// Copyright 2014 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.
#ifndef ASH_SYSTEM_AUDIO_TRAY_AUDIO_H_
#define ASH_SYSTEM_AUDIO_TRAY_AUDIO_H_
#include "ash/system/audio/audio_observer.h"
#include "ash/system/tray/tray_image_item.h"
#include "base/memory/scoped_ptr.h"
namespace ash {
namespace system {
class TrayAudioDelegate;
}
namespace internal {
namespace tray {
class VolumeView;
}
class TrayAudio : public TrayImageItem,
public AudioObserver {
public:
TrayAudio(SystemTray* system_tray,
scoped_ptr<system::TrayAudioDelegate> audio_delegate);
virtual ~TrayAudio();
protected:
virtual void Update();
scoped_ptr<system::TrayAudioDelegate> audio_delegate_;
tray::VolumeView* volume_view_;
// True if VolumeView should be created for accelerator pop up;
// Otherwise, it should be created for detailed view in ash tray bubble.
bool pop_up_volume_view_;
private:
// Overridden from TrayImageItem.
virtual bool GetInitialVisibility() OVERRIDE;
// Overridden from SystemTrayItem.
virtual views::View* CreateDefaultView(user::LoginStatus status) OVERRIDE;
virtual views::View* CreateDetailedView(user::LoginStatus status) OVERRIDE;
virtual void DestroyDefaultView() OVERRIDE;
virtual void DestroyDetailedView() OVERRIDE;
virtual bool ShouldHideArrow() const OVERRIDE;
virtual bool ShouldShowShelf() const OVERRIDE;
// Overridden from AudioObserver.
virtual void OnOutputVolumeChanged() OVERRIDE;
virtual void OnOutputMuteChanged() OVERRIDE;
virtual void OnAudioNodesChanged() OVERRIDE;
virtual void OnActiveOutputNodeChanged() OVERRIDE;
virtual void OnActiveInputNodeChanged() OVERRIDE;
DISALLOW_COPY_AND_ASSIGN(TrayAudio);
};
} // namespace internal
} // namespace ash
#endif // ASH_SYSTEM_AUDIO_TRAY_AUDIO_H_
|
Java
|
module Text.OpenGL.Xml.ReadRegistry (
readRegistry,
parseRegistry,
PreProcess
) where
import Prelude hiding ((.), id)
import Control.Category
import Text.OpenGL.Types
import Text.OpenGL.Xml.Pickle()
import Text.OpenGL.Xml.PreProcess
import Text.XML.HXT.Core
type PreProcess = Bool
-- TODO RelaxNG validation
readRegistry :: FilePath -> PreProcess -> IO (Either String Registry)
readRegistry fp pp = do
results <- runX (
readDocument readOpts fp >>> preProcess pp >>> parseRegistryArrow
) -- TODO: error handling
return $ handleResults results
where
readOpts :: [SysConfig]
readOpts = [withValidate no, withPreserveComment no]
preProcess :: (ArrowChoice a, ArrowXml a) => PreProcess -> a XmlTree XmlTree
preProcess pp = if pp then preProcessRegistry else id
-- | TODO: make it work (doesn't work with the <?xml ?> header.
parseRegistry :: String -> PreProcess -> Either String Registry
parseRegistry str pp = handleResults $ runLA (
xread >>> preProcess pp >>> parseRegistryArrow
) str
handleResults :: [Either String Registry] -> Either String Registry
handleResults rs = case rs of
[] -> Left "No parse"
(_:_:_) -> Left "Multiple parse"
[rc] -> rc
parseRegistryArrow :: ArrowXml a => a XmlTree (Either String Registry)
parseRegistryArrow =
removeAllWhiteSpace >>> -- This processing is needed for the non IO case.
removeAllComment >>>
arr (unpickleDoc' xpickle)
|
Java
|
//
// CEDestinySDK.h
// CEDestinySDK
//
// Created by Caleb Eades on 11/12/15.
// Copyright (c) 2015 Caleb Eades. All rights reserved.
//
#import <UIKit/UIKit.h>
//! Project version number for CEDestinySDK.
FOUNDATION_EXPORT double CEDestinySDKVersionNumber;
//! Project version string for CEDestinySDK.
FOUNDATION_EXPORT const unsigned char CEDestinySDKVersionString[];
// In this header, you should import all the public headers of your framework using statements like #import <CEDestinySDK/PublicHeader.h>
#import "CEDestinySDK.h"
|
Java
|
/**
* History.js Core
* @author Benjamin Arthur Lupton <contact@balupton.com>
* @copyright 2010-2011 Benjamin Arthur Lupton <contact@balupton.com>
* @license New BSD License <http://creativecommons.org/licenses/BSD/>
*/
(function(window,undefined){
"use strict";
// ========================================================================
// Initialise
// Localise Globals
var
console = window.console||undefined, // Prevent a JSLint complain
document = window.document, // Make sure we are using the correct document
navigator = window.navigator, // Make sure we are using the correct navigator
sessionStorage = false, // sessionStorage
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
setInterval = window.setInterval,
clearInterval = window.clearInterval,
JSON = window.JSON,
alert = window.alert,
History = window.History = window.History||{}, // Public History Object
history = window.history; // Old History Object
// MooTools Compatibility
JSON.stringify = JSON.stringify||JSON.encode;
JSON.parse = JSON.parse||JSON.decode;
try {
sessionStorage = window.sessionStorage; // This will throw an exception in some browsers when cookies/localStorage are explicitly disabled (i.e. Chrome)
sessionStorage.setItem('TEST', '1');
sessionStorage.removeItem('TEST');
} catch(e) {
sessionStorage = false;
}
// Check Existence
if ( typeof History.init !== 'undefined' ) {
throw new Error('History.js Core has already been loaded...');
}
// Initialise History
History.init = function(){
// Check Load Status of Adapter
if ( typeof History.Adapter === 'undefined' ) {
return false;
}
// Check Load Status of Core
if ( typeof History.initCore !== 'undefined' ) {
History.initCore();
}
// Check Load Status of HTML4 Support
if ( typeof History.initHtml4 !== 'undefined' ) {
History.initHtml4();
}
// Return true
return true;
};
// ========================================================================
// Initialise Core
// Initialise Core
History.initCore = function(){
// Initialise
if ( typeof History.initCore.initialized !== 'undefined' ) {
// Already Loaded
return false;
}
else {
History.initCore.initialized = true;
}
// ====================================================================
// Options
/**
* History.options
* Configurable options
*/
History.options = History.options||{};
/**
* History.options.hashChangeInterval
* How long should the interval be before hashchange checks
*/
History.options.hashChangeInterval = History.options.hashChangeInterval || 100;
/**
* History.options.safariPollInterval
* How long should the interval be before safari poll checks
*/
History.options.safariPollInterval = History.options.safariPollInterval || 500;
/**
* History.options.doubleCheckInterval
* How long should the interval be before we perform a double check
*/
History.options.doubleCheckInterval = History.options.doubleCheckInterval || 500;
/**
* History.options.storeInterval
* How long should we wait between store calls
*/
History.options.storeInterval = History.options.storeInterval || 5000;
/**
* History.options.busyDelay
* How long should we wait between busy events
*/
History.options.busyDelay = History.options.busyDelay || 250;
/**
* History.options.debug
* If true will enable debug messages to be logged
*/
History.options.debug = History.options.debug || false;
/**
* History.options.initialTitle
* What is the title of the initial state
*/
History.options.initialTitle = History.options.initialTitle || document.title;
// ====================================================================
// Interval record
/**
* History.intervalList
* List of intervals set, to be cleared when document is unloaded.
*/
History.intervalList = [];
/**
* History.clearAllIntervals
* Clears all setInterval instances.
*/
History.clearAllIntervals = function(){
var i, il = History.intervalList;
if (typeof il !== "undefined" && il !== null) {
for (i = 0; i < il.length; i++) {
clearInterval(il[i]);
}
History.intervalList = null;
}
};
// ====================================================================
// Debug
/**
* History.debug(message,...)
* Logs the passed arguments if debug enabled
*/
History.debug = function(){
if ( (History.options.debug||false) ) {
History.log.apply(History,arguments);
}
};
/**
* History.log(message,...)
* Logs the passed arguments
*/
History.log = function(){
// Prepare
var
consoleExists = !(typeof console === 'undefined' || typeof console.log === 'undefined' || typeof console.log.apply === 'undefined'),
textarea = document.getElementById('log'),
message,
i,n,
args,arg
;
// Write to Console
if ( consoleExists ) {
args = Array.prototype.slice.call(arguments);
message = args.shift();
if ( typeof console.debug !== 'undefined' ) {
console.debug.apply(console,[message,args]);
}
else {
console.log.apply(console,[message,args]);
}
}
else {
message = ("\n"+arguments[0]+"\n");
}
// Write to log
for ( i=1,n=arguments.length; i<n; ++i ) {
arg = arguments[i];
if ( typeof arg === 'object' && typeof JSON !== 'undefined' ) {
try {
arg = JSON.stringify(arg);
}
catch ( Exception ) {
// Recursive Object
}
}
message += "\n"+arg+"\n";
}
// Textarea
if ( textarea ) {
textarea.value += message+"\n-----\n";
textarea.scrollTop = textarea.scrollHeight - textarea.clientHeight;
}
// No Textarea, No Console
else if ( !consoleExists ) {
alert(message);
}
// Return true
return true;
};
// ====================================================================
// Emulated Status
/**
* History.getInternetExplorerMajorVersion()
* Get's the major version of Internet Explorer
* @return {integer}
* @license Public Domain
* @author Benjamin Arthur Lupton <contact@balupton.com>
* @author James Padolsey <https://gist.github.com/527683>
*/
History.getInternetExplorerMajorVersion = function(){
var result = History.getInternetExplorerMajorVersion.cached =
(typeof History.getInternetExplorerMajorVersion.cached !== 'undefined')
? History.getInternetExplorerMajorVersion.cached
: (function(){
var v = 3,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while ( (div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->') && all[0] ) {}
return (v > 4) ? v : false;
})()
;
return result;
};
/**
* History.isInternetExplorer()
* Are we using Internet Explorer?
* @return {boolean}
* @license Public Domain
* @author Benjamin Arthur Lupton <contact@balupton.com>
*/
History.isInternetExplorer = function(){
var result =
History.isInternetExplorer.cached =
(typeof History.isInternetExplorer.cached !== 'undefined')
? History.isInternetExplorer.cached
: Boolean(History.getInternetExplorerMajorVersion())
;
return result;
};
/**
* History.emulated
* Which features require emulating?
*/
History.emulated = {
pushState: !Boolean(
window.history && window.history.pushState && window.history.replaceState
&& !(
(/ Mobile\/([1-7][a-z]|(8([abcde]|f(1[0-8]))))/i).test(navigator.userAgent) /* disable for versions of iOS before version 4.3 (8F190) */
|| (/AppleWebKit\/5([0-2]|3[0-2])/i).test(navigator.userAgent) /* disable for the mercury iOS browser, or at least older versions of the webkit engine */
)
),
hashChange: Boolean(
!(('onhashchange' in window) || ('onhashchange' in document))
||
(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8)
)
};
/**
* History.enabled
* Is History enabled?
*/
History.enabled = !History.emulated.pushState;
/**
* History.bugs
* Which bugs are present
*/
History.bugs = {
/**
* Safari 5 and Safari iOS 4 fail to return to the correct state once a hash is replaced by a `replaceState` call
* https://bugs.webkit.org/show_bug.cgi?id=56249
*/
setHash: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
/**
* Safari 5 and Safari iOS 4 sometimes fail to apply the state change under busy conditions
* https://bugs.webkit.org/show_bug.cgi?id=42940
*/
safariPoll: Boolean(!History.emulated.pushState && navigator.vendor === 'Apple Computer, Inc.' && /AppleWebKit\/5([0-2]|3[0-3])/.test(navigator.userAgent)),
/**
* MSIE 6 and 7 sometimes do not apply a hash even it was told to (requiring a second call to the apply function)
*/
ieDoubleCheck: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 8),
/**
* MSIE 6 requires the entire hash to be encoded for the hashes to trigger the onHashChange event
*/
hashEscape: Boolean(History.isInternetExplorer() && History.getInternetExplorerMajorVersion() < 7)
};
/**
* History.isEmptyObject(obj)
* Checks to see if the Object is Empty
* @param {Object} obj
* @return {boolean}
*/
History.isEmptyObject = function(obj) {
for ( var name in obj ) {
return false;
}
return true;
};
/**
* History.cloneObject(obj)
* Clones a object and eliminate all references to the original contexts
* @param {Object} obj
* @return {Object}
*/
History.cloneObject = function(obj) {
var hash,newObj;
if ( obj ) {
hash = JSON.stringify(obj);
newObj = JSON.parse(hash);
}
else {
newObj = {};
}
return newObj;
};
History.extendObject = function(obj, extension) {
for (var key in extension)
{
if (extension.hasOwnProperty(key))
{
obj[key] = extension[key];
}
}
};
History.setSessionStorageItem = function(key, value)
{
try
{
sessionStorage.setItem(key, value);
}
catch(e)
{
try
{
// hack: Workaround for a bug seen on iPads. Sometimes the quota exceeded error comes up and simply
// removing/resetting the storage can work.
sessionStorage.removeItem(key);
sessionStorage.setItem(key, value);
}
catch(e)
{
try
{
// no permissions or quota exceed
if (e.name === 'QuotaExceededError' ||
e.name === 'NS_ERROR_DOM_QUOTA_REACHED')
{
History.Adapter.trigger(window, 'storageQuotaExceed');
sessionStorage.setItem(key, value);
}
}
catch(e)
{
}
}
}
}
// ====================================================================
// URL Helpers
/**
* History.getRootUrl()
* Turns "http://mysite.com/dir/page.html?asd" into "http://mysite.com"
* @return {String} rootUrl
*/
History.getRootUrl = function(){
// Create
var rootUrl = document.location.protocol+'//'+(document.location.hostname||document.location.host);
if ( document.location.port||false ) {
rootUrl += ':'+document.location.port;
}
rootUrl += '/';
// Return
return rootUrl;
};
/**
* History.getBaseHref()
* Fetches the `href` attribute of the `<base href="...">` element if it exists
* @return {String} baseHref
*/
History.getBaseHref = function(){
// Create
var
baseElements = document.getElementsByTagName('base'),
baseElement = null,
baseHref = '';
// Test for Base Element
if ( baseElements.length === 1 ) {
// Prepare for Base Element
baseElement = baseElements[0];
baseHref = baseElement.href.replace(/[^\/]+$/,'');
}
// Adjust trailing slash
baseHref = baseHref.replace(/\/+$/,'');
if ( baseHref ) baseHref += '/';
// Return
return baseHref;
};
/**
* History.getBaseUrl()
* Fetches the baseHref or basePageUrl or rootUrl (whichever one exists first)
* @return {String} baseUrl
*/
History.getBaseUrl = function(){
// Create
var baseUrl = History.getBaseHref()||History.getBasePageUrl()||History.getRootUrl();
// Return
return baseUrl;
};
/**
* History.getPageUrl()
* Fetches the URL of the current page
* @return {String} pageUrl
*/
History.getPageUrl = function(){
// Fetch
var
State = History.getState(false,false),
stateUrl = (State||{}).url||document.location.href,
pageUrl;
// Create
pageUrl = stateUrl.replace(/\/+$/,'').replace(/[^\/]+$/,function(part,index,string){
return (/\./).test(part) ? part : part+'/';
});
// Return
return pageUrl;
};
/**
* History.getBasePageUrl()
* Fetches the Url of the directory of the current page
* @return {String} basePageUrl
*/
History.getBasePageUrl = function(){
// Create
var basePageUrl = document.location.href.replace(/[#\?].*/,'').replace(/[^\/]+$/,function(part,index,string){
return (/[^\/]$/).test(part) ? '' : part;
}).replace(/\/+$/,'')+'/';
// Return
return basePageUrl;
};
/**
* History.getFullUrl(url)
* Ensures that we have an absolute URL and not a relative URL
* @param {string} url
* @param {Boolean} allowBaseHref
* @return {string} fullUrl
*/
History.getFullUrl = function(url,allowBaseHref){
// Prepare
var fullUrl = url, firstChar = url.substring(0,1);
allowBaseHref = (typeof allowBaseHref === 'undefined') ? true : allowBaseHref;
// Check
if ( /[a-z]+\:\/\//.test(url) ) {
// Full URL
}
else if ( firstChar === '/' ) {
// Root URL
fullUrl = History.getRootUrl()+url.replace(/^\/+/,'');
}
else if ( firstChar === '#' ) {
// Anchor URL
fullUrl = History.getPageUrl().replace(/#.*/,'')+url;
}
else if ( firstChar === '?' ) {
// Query URL
fullUrl = History.getPageUrl().replace(/[\?#].*/,'')+url;
}
else {
// Relative URL
if ( allowBaseHref ) {
fullUrl = History.getBaseUrl()+url.replace(/^(\.\/)+/,'');
} else {
fullUrl = History.getBasePageUrl()+url.replace(/^(\.\/)+/,'');
}
// We have an if condition above as we do not want hashes
// which are relative to the baseHref in our URLs
// as if the baseHref changes, then all our bookmarks
// would now point to different locations
// whereas the basePageUrl will always stay the same
}
// Return
return fullUrl.replace(/\#$/,'');
};
/**
* History.getShortUrl(url)
* Ensures that we have a relative URL and not a absolute URL
* @param {string} url
* @return {string} url
*/
History.getShortUrl = function(url){
// Prepare
var shortUrl = url, baseUrl = History.getBaseUrl(), rootUrl = History.getRootUrl();
// Trim baseUrl
if ( History.emulated.pushState ) {
// We are in a if statement as when pushState is not emulated
// The actual url these short urls are relative to can change
// So within the same session, we the url may end up somewhere different
shortUrl = shortUrl.replace(baseUrl,'');
}
// Trim rootUrl
shortUrl = shortUrl.replace(rootUrl,'/');
// Ensure we can still detect it as a state
if ( History.isTraditionalAnchor(shortUrl) ) {
shortUrl = './'+shortUrl;
}
// Clean It
shortUrl = shortUrl.replace(/^(\.\/)+/g,'./').replace(/\#$/,'');
// Return
return shortUrl;
};
// ====================================================================
// State Storage
/**
* History.store
* The store for all session specific data
*/
History.store = {};
/**
* History.idToState
* 1-1: State ID to State Object
*/
History.idToState = History.idToState||{};
/**
* History.stateToId
* 1-1: State String to State ID
*/
History.stateToId = History.stateToId||{};
/**
* History.urlToId
* 1-1: State URL to State ID
*/
History.urlToId = History.urlToId||{};
/**
* History.storedStates
* Store the states in an array
*/
History.storedStates = History.storedStates||[];
/**
* History.savedStates
* Saved the states in an array
*/
History.savedStates = History.savedStates||[];
/**
* History.noramlizeStore()
* Noramlize the store by adding necessary values
*/
History.normalizeStore = function(){
History.store.idToState = History.store.idToState||{};
History.store.urlToId = History.store.urlToId||{};
History.store.stateToId = History.store.stateToId||{};
};
/**
* History.getState()
* Get an object containing the data, title and url of the current state
* @param {Boolean} friendly
* @param {Boolean} create
* @return {Object} State
*/
History.getState = function(friendly,create){
// Prepare
if ( typeof friendly === 'undefined' ) { friendly = true; }
if ( typeof create === 'undefined' ) { create = true; }
// Fetch
var State = History.getLastSavedState();
// Create
if ( !State && create ) {
State = History.createStateObject();
}
// Adjust
if ( friendly ) {
State = History.cloneObject(State);
State.url = State.cleanUrl||State.url;
}
// Return
return State;
};
/**
* History.getIdByState(State)
* Gets a ID for a State
* @param {State} newState
* @return {String} id
*/
History.getIdByState = function(newState){
// Fetch ID
var id = History.extractId(newState.url),
lastSavedState,
str;
if ( !id ) {
// Find ID via State String
str = History.getStateString(newState);
if ( typeof History.stateToId[str] !== 'undefined' ) {
id = History.stateToId[str];
}
else if ( typeof History.store.stateToId[str] !== 'undefined' ) {
id = History.store.stateToId[str];
}
else {
id = sessionStorage ? sessionStorage.getItem('uniqId') : new Date().getTime();
if (id == undefined){
id = 0;
}
lastSavedState = History.getLastSavedState();
if (lastSavedState)
{
id = lastSavedState.id + 1;
if (sessionStorage)
{
History.setSessionStorageItem('uniqId', id);
}
}
else
{
// Generate a new ID
while (true)
{
++id;
if (typeof History.idToState[id] === 'undefined' && typeof History.store.idToState[id] === 'undefined')
{
if (sessionStorage)
{
History.setSessionStorageItem('uniqId', id);
}
break;
}
}
}
// Apply the new State to the ID
History.stateToId[str] = id;
History.idToState[id] = newState;
}
}
// Return ID
return id;
};
/**
* History.normalizeState(State)
* Expands a State Object
* @param {object} State
* @return {object}
*/
History.normalizeState = function(oldState){
// Variables
var newState, dataNotEmpty;
// Prepare
if ( !oldState || (typeof oldState !== 'object') ) {
oldState = {};
}
// Check
if ( typeof oldState.normalized !== 'undefined' ) {
return oldState;
}
// Adjust
if ( !oldState.data || (typeof oldState.data !== 'object') ) {
oldState.data = {};
}
// ----------------------------------------------------------------
// Create
newState = {};
newState.normalized = true;
newState.title = oldState.title||'';
newState.url = History.getFullUrl(History.unescapeString(oldState.url||document.location.href));
newState.hash = History.getShortUrl(newState.url);
newState.data = History.cloneObject(oldState.data);
// Fetch ID
newState.id = History.getIdByState(newState);
// ----------------------------------------------------------------
// Clean the URL
newState.cleanUrl = newState.url.replace(/\??\&_suid.*/,'');
newState.url = newState.cleanUrl;
// Check to see if we have more than just a url
dataNotEmpty = !History.isEmptyObject(newState.data);
// Apply
if ( newState.title || dataNotEmpty ) {
// Add ID to Hash
newState.hash = History.getShortUrl(newState.url).replace(/\??\&_suid.*/,'');
if ( !/\?/.test(newState.hash) ) {
newState.hash += '?';
}
newState.hash += '&_suid='+newState.id;
}
// Create the Hashed URL
newState.hashedUrl = History.getFullUrl(newState.hash);
// ----------------------------------------------------------------
// Update the URL if we have a duplicate
if ( (History.emulated.pushState || History.bugs.safariPoll) && History.hasUrlDuplicate(newState) ) {
newState.url = newState.hashedUrl;
}
// ----------------------------------------------------------------
// Return
return newState;
};
/**
* History.createStateObject(data,title,url)
* Creates a object based on the data, title and url state params
* @param {object} data
* @param {string} title
* @param {string} url
* @return {object}
*/
History.createStateObject = function(data,title,url){
// Hashify
var State = {
'data': data,
'title': title,
'url': url
};
// Expand the State
State = History.normalizeState(State);
// Return object
return State;
};
/**
* History.getStateById(id)
* Get a state by it's UID
* @param {String} id
*/
History.getStateById = function(id){
// Prepare
id = String(id);
// Retrieve
var State = History.idToState[id] || History.store.idToState[id] || undefined;
// Return State
return State;
};
/**
* Get a State's String
* @param {State} passedState
*/
History.getStateString = function(passedState){
// Prepare
var State, cleanedState, str;
// Fetch
State = History.normalizeState(passedState);
// Clean
cleanedState = {
data: State.data,
title: passedState.title,
url: passedState.url
};
// Fetch
str = JSON.stringify(cleanedState);
// Return
return str;
};
/**
* Get a State's ID
* @param {State} passedState
* @return {String} id
*/
History.getStateId = function(passedState){
// Prepare
var State, id;
// Fetch
State = History.normalizeState(passedState);
// Fetch
id = State.id;
// Return
return id;
};
/**
* History.getHashByState(State)
* Creates a Hash for the State Object
* @param {State} passedState
* @return {String} hash
*/
History.getHashByState = function(passedState){
// Prepare
var State, hash;
// Fetch
State = History.normalizeState(passedState);
// Hash
hash = State.hash;
// Return
return hash;
};
/**
* History.extractId(url_or_hash)
* Get a State ID by it's URL or Hash
* @param {string} url_or_hash
* @return {string} id
*/
History.extractId = function ( url_or_hash ) {
// Prepare
var id,parts,url;
// Extract
parts = /(.*)\&_suid=([0-9]+)$/.exec(url_or_hash);
url = parts ? (parts[1]||url_or_hash) : url_or_hash;
id = parts ? String(parts[2]||'') : '';
// Return
return id||false;
};
/**
* History.isTraditionalAnchor
* Checks to see if the url is a traditional anchor or not
* @param {String} url_or_hash
* @return {Boolean}
*/
History.isTraditionalAnchor = function(url_or_hash){
// Check
var isTraditional = !(/[\/\?\.]/.test(url_or_hash));
// Return
return isTraditional;
};
/**
* History.extractState
* Get a State by it's URL or Hash
* @param {String} url_or_hash
* @return {State|null}
*/
History.extractState = function(url_or_hash,create){
// Prepare
var State = null, id, url;
create = create||false;
// Fetch SUID
id = History.extractId(url_or_hash);
if ( id ) {
State = History.getStateById(id);
}
// Fetch SUID returned no State
if ( !State ) {
// Fetch URL
url = History.getFullUrl(url_or_hash);
// Check URL
id = History.getIdByUrl(url)||false;
if ( id ) {
State = History.getStateById(id);
}
// Create State
if ( !State && create && !History.isTraditionalAnchor(url_or_hash) ) {
State = History.createStateObject(null,null,url);
}
}
// Return
return State;
};
/**
* History.getIdByUrl()
* Get a State ID by a State URL
*/
History.getIdByUrl = function(url){
// Fetch
var id = History.urlToId[url] || History.store.urlToId[url] || undefined;
// Return
return id;
};
/**
* History.getLastSavedState()
* Get an object containing the data, title and url of the current state
* @return {Object} State
*/
History.getLastSavedState = function(){
return History.savedStates[History.savedStates.length-1]||undefined;
};
/**
* History.getLastStoredState()
* Get an object containing the data, title and url of the current state
* @return {Object} State
*/
History.getLastStoredState = function(){
return History.storedStates[History.storedStates.length-1]||undefined;
};
/**
* History.hasUrlDuplicate
* Checks if a Url will have a url conflict
* @param {Object} newState
* @return {Boolean} hasDuplicate
*/
History.hasUrlDuplicate = function(newState) {
// Prepare
var hasDuplicate = false,
oldState;
// Fetch
oldState = History.extractState(newState.url);
// Check
hasDuplicate = oldState && oldState.id !== newState.id;
// Return
return hasDuplicate;
};
/**
* History.storeState
* Store a State
* @param {Object} newState
* @return {Object} newState
*/
History.storeState = function(newState){
// Store the State
History.urlToId[newState.url] = newState.id;
// Push the State
History.storedStates.push(History.cloneObject(newState));
// Return newState
return newState;
};
/**
* History.isLastSavedState(newState)
* Tests to see if the state is the last state
* @param {Object} newState
* @return {boolean} isLast
*/
History.isLastSavedState = function(newState){
// Prepare
var isLast = false,
newId, oldState, oldId;
// Check
if ( History.savedStates.length ) {
newId = newState.id;
oldState = History.getLastSavedState();
oldId = oldState.id;
// Check
isLast = (newId === oldId);
}
// Return
return isLast;
};
/**
* History.saveState
* Push a State
* @param {Object} newState
* @return {boolean} changed
*/
History.saveState = function(newState){
// Check Hash
if ( History.isLastSavedState(newState) ) {
return false;
}
// Push the State
History.savedStates.push(History.cloneObject(newState));
// Return true
return true;
};
/**
* History.getStateByIndex()
* Gets a state by the index
* @param {integer} index
* @return {Object}
*/
History.getStateByIndex = function(index){
// Prepare
var State = null;
// Handle
if ( typeof index === 'undefined' ) {
// Get the last inserted
State = History.savedStates[History.savedStates.length-1];
}
else if ( index < 0 ) {
// Get from the end
State = History.savedStates[History.savedStates.length+index];
}
else {
// Get from the beginning
State = History.savedStates[index];
}
// Return State
return State;
};
// ====================================================================
// Hash Helpers
/**
* History.getHash()
* Gets the current document hash
* @return {string}
*/
History.getHash = function(){
var hash = History.unescapeHash(document.location.hash);
return hash;
};
/**
* History.unescapeString()
* Unescape a string
* @param {String} str
* @return {string}
*/
History.unescapeString = function(str){
// Prepare
var result = str,
tmp;
// Unescape hash
while ( true ) {
tmp = window.unescape(result);
if ( tmp === result ) {
break;
}
result = tmp;
}
// Return result
return result;
};
/**
* History.unescapeHash()
* normalize and Unescape a Hash
* @param {String} hash
* @return {string}
*/
History.unescapeHash = function(hash){
// Prepare
var result = History.normalizeHash(hash);
// Unescape hash
result = History.unescapeString(result);
// Return result
return result;
};
/**
* History.normalizeHash()
* normalize a hash across browsers
* @return {string}
*/
History.normalizeHash = function(hash){
// Prepare
var result = hash.replace(/[^#]*#/,'').replace(/#.*/, '');
// Return result
return result;
};
/**
* History.setHash(hash)
* Sets the document hash
* @param {string} hash
* @return {History}
*/
History.setHash = function(hash,queue){
// Prepare
var adjustedHash, State, pageUrl;
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.setHash: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.setHash,
args: arguments,
queue: queue
});
return false;
}
// Log
//History.debug('History.setHash: called',hash);
// Prepare
adjustedHash = History.escapeHash(hash);
// Make Busy + Continue
History.busy(true);
// Check if hash is a state
State = History.extractState(hash,true);
if ( State && !History.emulated.pushState ) {
// Hash is a state so skip the setHash
//History.debug('History.setHash: Hash is a state so skipping the hash set with a direct pushState call',arguments);
// PushState
History.pushState(State.data,State.title,State.url,false);
}
else if ( document.location.hash !== adjustedHash ) {
// Hash is a proper hash, so apply it
// Handle browser bugs
if ( History.bugs.setHash ) {
// Fix Safari Bug https://bugs.webkit.org/show_bug.cgi?id=56249
// Fetch the base page
pageUrl = History.getPageUrl();
// Safari hash apply
History.pushState(null,null,pageUrl+'#'+adjustedHash,false);
}
else {
// Normal hash apply
document.location.hash = adjustedHash;
}
}
// Chain
return History;
};
/**
* History.escape()
* normalize and Escape a Hash
* @return {string}
*/
History.escapeHash = function(hash){
// Prepare
var result = History.normalizeHash(hash);
// Escape hash
result = window.escape(result);
// IE6 Escape Bug
if ( !History.bugs.hashEscape ) {
// Restore common parts
result = result
.replace(/\%21/g,'!')
.replace(/\%26/g,'&')
.replace(/\%3D/g,'=')
.replace(/\%3F/g,'?');
}
// Return result
return result;
};
/**
* History.getHashByUrl(url)
* Extracts the Hash from a URL
* @param {string} url
* @return {string} url
*/
History.getHashByUrl = function(url){
// Extract the hash
var hash = String(url)
.replace(/([^#]*)#?([^#]*)#?(.*)/, '$2')
;
// Unescape hash
hash = History.unescapeHash(hash);
// Return hash
return hash;
};
/**
* History.setTitle(title)
* Applies the title to the document
* @param {State} newState
* @return {Boolean}
*/
History.setTitle = function(newState){
// Prepare
var title = newState.title,
firstState;
// Initial
if ( !title ) {
firstState = History.getStateByIndex(0);
if ( firstState && firstState.url === newState.url ) {
title = firstState.title||History.options.initialTitle;
}
}
// Apply
try {
document.getElementsByTagName('title')[0].innerHTML = title.replace('<','<').replace('>','>').replace(' & ',' & ');
}
catch ( Exception ) { }
document.title = title;
// Chain
return History;
};
// ====================================================================
// Queueing
/**
* History.queues
* The list of queues to use
* First In, First Out
*/
History.queues = [];
/**
* History.busy(value)
* @param {boolean} value [optional]
* @return {boolean} busy
*/
History.busy = function(value){
// Apply
if ( typeof value !== 'undefined' ) {
//History.debug('History.busy: changing ['+(History.busy.flag||false)+'] to ['+(value||false)+']', History.queues.length);
History.busy.flag = value;
}
// Default
else if ( typeof History.busy.flag === 'undefined' ) {
History.busy.flag = false;
}
// Queue
if ( !History.busy.flag ) {
// Execute the next item in the queue
clearTimeout(History.busy.timeout);
var fireNext = function(){
var i, queue, item;
if ( History.busy.flag ) return;
for ( i=History.queues.length-1; i >= 0; --i ) {
queue = History.queues[i];
if ( queue.length === 0 ) continue;
item = queue.shift();
History.fireQueueItem(item);
History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
}
};
History.busy.timeout = setTimeout(fireNext,History.options.busyDelay);
}
// Return
return History.busy.flag;
};
/**
* History.busy.flag
*/
History.busy.flag = false;
/**
* History.fireQueueItem(item)
* Fire a Queue Item
* @param {Object} item
* @return {Mixed} result
*/
History.fireQueueItem = function(item){
return item.callback.apply(item.scope||History,item.args||[]);
};
/**
* History.pushQueue(callback,args)
* Add an item to the queue
* @param {Object} item [scope,callback,args,queue]
*/
History.pushQueue = function(item){
// Prepare the queue
History.queues[item.queue||0] = History.queues[item.queue||0]||[];
// Add to the queue
History.queues[item.queue||0].push(item);
// Chain
return History;
};
/**
* History.queue (item,queue), (func,queue), (func), (item)
* Either firs the item now if not busy, or adds it to the queue
*/
History.queue = function(item,queue){
// Prepare
if ( typeof item === 'function' ) {
item = {
callback: item
};
}
if ( typeof queue !== 'undefined' ) {
item.queue = queue;
}
// Handle
if ( History.busy() ) {
History.pushQueue(item);
} else {
History.fireQueueItem(item);
}
// Chain
return History;
};
/**
* History.clearQueue()
* Clears the Queue
*/
History.clearQueue = function(){
History.busy.flag = false;
History.queues = [];
return History;
};
// ====================================================================
// IE Bug Fix
/**
* History.stateChanged
* States whether or not the state has changed since the last double check was initialised
*/
History.stateChanged = false;
/**
* History.doubleChecker
* Contains the timeout used for the double checks
*/
History.doubleChecker = false;
/**
* History.doubleCheckComplete()
* Complete a double check
* @return {History}
*/
History.doubleCheckComplete = function(){
// Update
History.stateChanged = true;
// Clear
History.doubleCheckClear();
// Chain
return History;
};
/**
* History.doubleCheckClear()
* Clear a double check
* @return {History}
*/
History.doubleCheckClear = function(){
// Clear
if ( History.doubleChecker ) {
clearTimeout(History.doubleChecker);
History.doubleChecker = false;
}
// Chain
return History;
};
/**
* History.doubleCheck()
* Create a double check
* @return {History}
*/
History.doubleCheck = function(tryAgain){
// Reset
History.stateChanged = false;
History.doubleCheckClear();
// Fix IE6,IE7 bug where calling history.back or history.forward does not actually change the hash (whereas doing it manually does)
// Fix Safari 5 bug where sometimes the state does not change: https://bugs.webkit.org/show_bug.cgi?id=42940
if ( History.bugs.ieDoubleCheck ) {
// Apply Check
History.doubleChecker = setTimeout(
function(){
History.doubleCheckClear();
if ( !History.stateChanged ) {
//History.debug('History.doubleCheck: State has not yet changed, trying again', arguments);
// Re-Attempt
tryAgain();
}
return true;
},
History.options.doubleCheckInterval
);
}
// Chain
return History;
};
// ====================================================================
// Safari Bug Fix
/**
* History.safariStatePoll()
* Poll the current state
* @return {History}
*/
History.safariStatePoll = function(){
// Poll the URL
// Get the Last State which has the new URL
var
urlState = History.extractState(document.location.href),
newState;
// Check for a difference
if ( !History.isLastSavedState(urlState) ) {
newState = urlState;
}
else {
return;
}
// Check if we have a state with that url
// If not create it
if ( !newState ) {
//History.debug('History.safariStatePoll: new');
newState = History.createStateObject();
}
// Apply the New State
//History.debug('History.safariStatePoll: trigger');
History.Adapter.trigger(window,'popstate');
// Chain
return History;
};
// ====================================================================
// State Aliases
/**
* History.back(queue)
* Send the browser history back one item
* @param {Integer} queue [optional]
*/
History.back = function(queue){
//History.debug('History.back: called', arguments);
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.back: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.back,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Fix certain browser bugs that prevent the state from changing
History.doubleCheck(function(){
History.back(false);
});
// Go back
history.go(-1);
// End back closure
return true;
};
/**
* History.forward(queue)
* Send the browser history forward one item
* @param {Integer} queue [optional]
*/
History.forward = function(queue){
//History.debug('History.forward: called', arguments);
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.forward: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.forward,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Fix certain browser bugs that prevent the state from changing
History.doubleCheck(function(){
History.forward(false);
});
// Go forward
history.go(1);
// End forward closure
return true;
};
/**
* History.go(index,queue)
* Send the browser history back or forward index times
* @param {Integer} queue [optional]
*/
History.go = function(index,queue){
//History.debug('History.go: called', arguments);
// Prepare
var i;
// Handle
if ( index > 0 ) {
// Forward
for ( i=1; i<=index; ++i ) {
History.forward(queue);
}
}
else if ( index < 0 ) {
// Backward
for ( i=-1; i>=index; --i ) {
History.back(queue);
}
}
else {
throw new Error('History.go: History.go requires a positive or negative integer passed.');
}
// Chain
return History;
};
// ====================================================================
// HTML5 State Support
// Non-Native pushState Implementation
if ( History.emulated.pushState ) {
/*
* Provide Skeleton for HTML4 Browsers
*/
// Prepare
var emptyFunction = function(){};
History.pushState = History.pushState||emptyFunction;
History.replaceState = History.replaceState||emptyFunction;
} // History.emulated.pushState
// Native pushState Implementation
else {
/*
* Use native HTML5 History API Implementation
*/
/**
* History.onPopState(event,extra)
* Refresh the Current State
*/
History.onPopState = function(event,extra){
// Prepare
var stateId = false, newState = false, currentHash, currentState;
// Reset the double check
History.doubleCheckComplete();
// Check for a Hash, and handle apporiatly
currentHash = History.getHash();
if ( currentHash ) {
// Expand Hash
currentState = History.extractState(currentHash||document.location.href,true);
if ( currentState ) {
// We were able to parse it, it must be a State!
// Let's forward to replaceState
//History.debug('History.onPopState: state anchor', currentHash, currentState);
History.replaceState(currentState.data, currentState.title, currentState.url, false);
}
else {
// Traditional Anchor
//History.debug('History.onPopState: traditional anchor', currentHash);
History.Adapter.trigger(window,'anchorchange');
History.busy(false);
}
// We don't care for hashes
History.expectedStateId = false;
return false;
}
// Ensure
stateId = History.Adapter.extractEventData('state',event,extra) || false;
// Fetch State
if ( stateId ) {
// Vanilla: Back/forward button was used
newState = History.getStateById(stateId);
}
else if ( History.expectedStateId ) {
// Vanilla: A new state was pushed, and popstate was called manually
newState = History.getStateById(History.expectedStateId);
}
else {
// Initial State
newState = History.extractState(document.location.href);
}
// The State did not exist in our store
if ( !newState ) {
// Regenerate the State
newState = History.createStateObject(null,null,document.location.href);
}
// Clean
History.expectedStateId = false;
// Check if we are the same state
if ( History.isLastSavedState(newState) ) {
// There has been no change (just the page's hash has finally propagated)
//History.debug('History.onPopState: no change', newState, History.savedStates);
History.busy(false);
return false;
}
// Store the State
History.storeState(newState);
History.saveState(newState);
// Force update of the title
History.setTitle(newState);
// Fire Our Event
History.Adapter.trigger(window,'statechange');
History.busy(false);
// Return true
return true;
};
History.Adapter.bind(window,'popstate',History.onPopState);
/**
* History.pushState(data,title,url)
* Add a new State to the history object, become it, and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @return {true}
*/
History.pushState = function(data,title,url,queue){
//History.debug('History.pushState: called', arguments);
// Check the State
if ( History.getHashByUrl(url) && History.emulated.pushState ) {
throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.pushState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.pushState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Create the newState
var newState = History.createStateObject(data,title,url);
// Check it
if ( History.isLastSavedState(newState) ) {
// Won't be a change
History.busy(false);
}
else {
//remove previously stored state, because it can be and can be non empty
History.Adapter.trigger(window, 'stateremove', { stateId: newState.id });
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Push the newState
history.pushState(newState.id,newState.title,newState.url);
// Fire HTML5 Event
History.Adapter.trigger(window,'popstate');
}
// End pushState closure
return true;
};
/**
* History.replaceState(data,title,url)
* Replace the State and trigger onpopstate
* We have to trigger for HTML4 compatibility
* @param {object} data
* @param {string} title
* @param {string} url
* @param {object} queue
* @param {boolean} createNewState
* @return {true}
*/
History.replaceState = function(data,title,url,queue,createNewState){
//History.debug('History.replaceState: called', arguments);
// Check the State
if ( History.getHashByUrl(url) && History.emulated.pushState ) {
throw new Error('History.js does not support states with fragement-identifiers (hashes/anchors).');
}
// Handle Queueing
if ( queue !== false && History.busy() ) {
// Wait + Push to Queue
//History.debug('History.replaceState: we must wait', arguments);
History.pushQueue({
scope: History,
callback: History.replaceState,
args: arguments,
queue: queue
});
return false;
}
// Make Busy + Continue
History.busy(true);
// Create the newState
var newState;
if (createNewState)
{
data.rnd = new Date().getTime();
newState = History.createStateObject(data, title, url);
}
else
{
newState = History.getState();
newState.data = data;
History.idToState[newState.id] = newState;
History.extendObject(History.getLastSavedState(), newState);
}
// Check it
if ( History.isLastSavedState(newState) ) {
// Won't be a change
History.busy(false);
}
else {
// Store the newState
History.storeState(newState);
History.expectedStateId = newState.id;
// Push the newState
history.replaceState(newState.id,newState.title,newState.url);
// Fire HTML5 Event
History.Adapter.trigger(window,'popstate');
}
// End replaceState closure
return true;
};
} // !History.emulated.pushState
// ====================================================================
// Initialise
/**
* Load the Store
*/
if ( sessionStorage ) {
// Fetch
try {
History.store = JSON.parse(/*LZString.decompress*/(sessionStorage.getItem('History.store')))||{};
}
catch ( err ) {
History.store = {};
}
// Normalize
History.normalizeStore();
}
else {
// Default Load
History.store = {};
History.normalizeStore();
}
/**
* Clear Intervals on exit to prevent memory leaks
*/
History.Adapter.bind(window,"beforeunload",History.clearAllIntervals);
History.Adapter.bind(window,"unload",History.clearAllIntervals);
/**
* Create the initial State
*/
History.saveState(History.storeState(History.extractState(document.location.href,true)));
/**
* Bind for Saving Store
*/
if ( sessionStorage ) {
// When the page is closed
History.onUnload = function(){
// Prepare
var currentStore, item;
// Fetch
try {
currentStore = JSON.parse(/*LZString.decompress*/(sessionStorage.getItem('History.store')))||{};
}
catch ( err ) {
currentStore = {};
}
// Ensure
currentStore.idToState = currentStore.idToState || {};
currentStore.urlToId = currentStore.urlToId || {};
currentStore.stateToId = currentStore.stateToId || {};
// Sync
for ( item in History.idToState ) {
if ( !History.idToState.hasOwnProperty(item) ) {
continue;
}
currentStore.idToState[item] = History.idToState[item];
}
for ( item in History.urlToId ) {
if ( !History.urlToId.hasOwnProperty(item) ) {
continue;
}
currentStore.urlToId[item] = History.urlToId[item];
}
for ( item in History.stateToId ) {
if ( !History.stateToId.hasOwnProperty(item) ) {
continue;
}
currentStore.stateToId[item] = History.stateToId[item];
}
var historyEntries = [];
var maxHistoryEntriesCount = 10;
//slice overweight entries
for ( item in currentStore.idToState ) {
if ( !currentStore.idToState.hasOwnProperty(item) ) {
continue;
}
currentStore.idToState[item].entryId = item;
historyEntries.push(currentStore.idToState[item]);
}
if (historyEntries.length > maxHistoryEntriesCount)
{
historyEntries.sort(function(e1, e2)
{
return e1.entryId - e2.entryId;
});
var excludedEntries = historyEntries.slice(0, historyEntries.length - maxHistoryEntriesCount);
for (var entryIndex = 0; entryIndex < excludedEntries.length; entryIndex++)
{
var entry = excludedEntries[entryIndex];
delete currentStore.idToState[entry.entryId];
for (var url in currentStore.urlToId )
{
if (currentStore.urlToId.hasOwnProperty(url) &&
currentStore.urlToId[url] == entry.entryId)
{
delete currentStore.urlToId[url];
}
}
for (var state in currentStore.stateToId )
{
if (currentStore.stateToId.hasOwnProperty(state) &&
currentStore.stateToId[state] == entry.entryId)
{
delete currentStore.stateToId[state];
}
}
History.Adapter.trigger(window, 'stateremove', { stateId: entry.entryId });
}
}
// Update
History.store = currentStore;
History.normalizeStore();
// Store
History.setSessionStorageItem('History.store', /*LZString.compress*/(JSON.stringify(currentStore)));
};
// For Internet Explorer
History.intervalList.push(setInterval(History.onUnload,History.options.storeInterval));
// For Other Browsers
History.Adapter.bind(window,'beforeunload',History.onUnload);
History.Adapter.bind(window,'unload',History.onUnload);
// Both are enabled for consistency
}
// Non-Native pushState Implementation
if ( !History.emulated.pushState ) {
// Be aware, the following is only for native pushState implementations
// If you are wanting to include something for all browsers
// Then include it above this if block
/**
* Setup Safari Fix
*/
if ( History.bugs.safariPoll ) {
History.intervalList.push(setInterval(History.safariStatePoll, History.options.safariPollInterval));
}
/**
* Ensure Cross Browser Compatibility
*/
if ( navigator.vendor === 'Apple Computer, Inc.' || (navigator.appCodeName||'') === 'Mozilla' ) {
/**
* Fix Safari HashChange Issue
*/
// Setup Alias
History.Adapter.bind(window,'hashchange',function(){
History.Adapter.trigger(window,'popstate');
});
// Initialise Alias
if ( History.getHash() ) {
History.Adapter.onDomLoad(function(){
History.Adapter.trigger(window,'hashchange');
});
}
}
} // !History.emulated.pushState
}; // History.initCore
// Try and Initialise History
History.init();
})(window);
|
Java
|
require 'spree_auto_invoice'
require 'rails'
module SpreeAutoInvoice
class Railtie < Rails::Railtie
rake_tasks do
require '../tasks/spree_auto_invoice.rake'
end
end
end
|
Java
|
<?php
use librarys\helpers\utils\String;
?>
<!-- 文章正文 下面部分 -->
<div class="a_info neinf">
<div>
<div class="a_rea a_hop">
<h2>
<span><a href="http://jb.9939.com/article_list.shtml">更多文章>></a></span>
与“<font style="color:#F00"><?php echo String::cutString($title, 8, 1)?></font>”相似的文章
</h2>
<ul class="a_prev">
<?php
if (isset($relArticles['list']) && !empty($relArticles['list'])) {
$leftRelArticles = array_splice($relArticles['list'], 0, 12);
foreach ($leftRelArticles as $relArticle){
?>
<li>
<a href="<?php echo '/article/'.date("Y/md", $relArticle["inputtime"]).'/'.$relArticle['id'].'.shtml' ; ?>" title="<?php echo $relArticle['title']; ?>"><?php echo $relArticle['title']; ?></a>
</li>
<?php
}
}
?>
</ul>
</div>
</div>
<div>
<div class="a_rea a_hop inpc">
<h2>
<span>
<a href="http://ask.9939.com/asking/" class="inqu">我要提问</a>
<a href="http://ask.9939.com/">更多问答>></a>
</span>
<img src="/images/pi_02.png">
</h2>
<ul class="a_mon">
<?php
if (isset($asks['list']) && !empty($asks['list'])) {
foreach ($asks['list'] as $outerKey => $outerAsk){
?>
<li>
<h3>
<a href="<?php echo \yii\helpers\Url::to('@ask/id/' . $outerAsk['ask']['id']); ?>" title="<?php echo $outerAsk['ask']['title']; ?>">
<?php echo $outerAsk['ask']['title']; ?>
</a>
</h3>
<p>
<?php
if (isset($outerAsk['answer']) && !empty($outerAsk['answer'])) {
?>
<?php echo \librarys\helpers\utils\String::cutString($outerAsk['answer']['content'], 54); ?>
<?php
}
?>
<a href="<?php echo \yii\helpers\Url::to('@ask/id/' . $outerAsk['ask']['id']); ?>">详细</a>
</p>
</li>
<?php
}
}
?>
</ul>
</div>
</div>
<?php
if (isset($disease) && !empty($disease)) {
?>
<!--热门疾病-->
<div class="a_rea a_hop inpc" style="background: none;">
<h2>
<span>
<?php
if (isset($isSymptom) && $isSymptom == 1) {
?>
<a href="/zhengzhuang/<?php echo $disease['pinyin_initial']; ?>/jiancha/">更多>></a>
<?php
}else {
?>
<a href="/<?php echo $disease['pinyin_initial']; ?>/lcjc/">更多>></a>
<?php } ?>
</span>
<img src="/images/reche.gif">
</h2>
<div class="nipat">
<?php
if (isset($isSymptom) && $isSymptom == 1){
?>
<h3><?php echo $disease['name']; ?><span>症状</span></h3>
<p><?php echo String::cutString($disease['examine'], 100); ?>
<a href="/zhengzhuang/<?php echo $disease['pinyin_initial']; ?>/jiancha/">详细</a>
</p>
<?php
}else {
?>
<h3><?php echo $disease['name']; ?><span>疾病</span></h3>
<p><?php echo String::cutString($disease['inspect'], 100); ?>
<a href="/<?php echo $disease['pinyin_initial']; ?>/lcjc/">详细</a>
</p>
<?php
}
?>
</div>
</div>
<?php } ?>
<div class="a_rea a_hop inpc" style="background: none;">
<h2>
<img src="/images/everb.gif">
</h2>
<?php
if (isset($disease) && !empty($disease)) {
?>
<ul class="finin clearfix">
<?php
if (isset($stillFind) && !empty($stillFind)) {
foreach ($stillFind as $find){
?>
<li>
<a href="http://jb.9939.com/so/<?php echo $find['pinyin']; ?>/" title="<?php echo $find['keywords']; ?>">
<?php echo $find['keywords']; ?>
</a>
</li>
<?php
}
}
?>
</ul>
<?php
}
?>
</div>
<!-- 图谱部分 Start -->
<?php echo $this->render('detail_below_pic'); ?>
<!-- 图谱部分 End -->
</div>
|
Java
|
// 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 "components/optimization_guide/hints_processing_util.h"
#include "components/optimization_guide/proto/hint_cache.pb.h"
#include "components/optimization_guide/proto/hints.pb.h"
#include "components/optimization_guide/store_update_data.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
namespace optimization_guide {
TEST(HintsProcessingUtilTest, FindPageHintForSubstringPagePattern) {
proto::Hint hint1;
// Page hint for "/one/"
proto::PageHint* page_hint1 = hint1.add_page_hints();
page_hint1->set_page_pattern("foo.org/*/one/");
// Page hint for "two"
proto::PageHint* page_hint2 = hint1.add_page_hints();
page_hint2->set_page_pattern("two");
// Page hint for "three.jpg"
proto::PageHint* page_hint3 = hint1.add_page_hints();
page_hint3->set_page_pattern("three.jpg");
EXPECT_EQ(nullptr, FindPageHintForURL(GURL(""), &hint1));
EXPECT_EQ(nullptr, FindPageHintForURL(GURL("https://www.foo.org/"), &hint1));
EXPECT_EQ(nullptr,
FindPageHintForURL(GURL("https://www.foo.org/one"), &hint1));
EXPECT_EQ(nullptr,
FindPageHintForURL(GURL("https://www.foo.org/one/"), &hint1));
EXPECT_EQ(page_hint1,
FindPageHintForURL(GURL("https://www.foo.org/pages/one/"), &hint1));
EXPECT_EQ(page_hint1,
FindPageHintForURL(GURL("https://www.foo.org/pages/subpages/one/"),
&hint1));
EXPECT_EQ(page_hint1, FindPageHintForURL(
GURL("https://www.foo.org/pages/one/two"), &hint1));
EXPECT_EQ(page_hint1,
FindPageHintForURL(
GURL("https://www.foo.org/pages/one/two/three.jpg"), &hint1));
EXPECT_EQ(page_hint2,
FindPageHintForURL(
GURL("https://www.foo.org/pages/onetwo/three.jpg"), &hint1));
EXPECT_EQ(page_hint2,
FindPageHintForURL(GURL("https://www.foo.org/one/two/three.jpg"),
&hint1));
EXPECT_EQ(page_hint2,
FindPageHintForURL(GURL("https://one.two.org"), &hint1));
EXPECT_EQ(page_hint3, FindPageHintForURL(
GURL("https://www.foo.org/bar/three.jpg"), &hint1));
}
TEST(HintsProcessingUtilTest, ConvertProtoEffectiveConnectionType) {
EXPECT_EQ(
ConvertProtoEffectiveConnectionType(
proto::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_UNKNOWN),
net::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_UNKNOWN);
EXPECT_EQ(
ConvertProtoEffectiveConnectionType(
proto::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_OFFLINE),
net::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_OFFLINE);
EXPECT_EQ(
ConvertProtoEffectiveConnectionType(
proto::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_SLOW_2G),
net::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_SLOW_2G);
EXPECT_EQ(ConvertProtoEffectiveConnectionType(
proto::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_2G),
net::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_2G);
EXPECT_EQ(ConvertProtoEffectiveConnectionType(
proto::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_3G),
net::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_3G);
EXPECT_EQ(ConvertProtoEffectiveConnectionType(
proto::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_4G),
net::EffectiveConnectionType::EFFECTIVE_CONNECTION_TYPE_4G);
}
TEST(HintsProcessingUtilTest, IsValidURLForURLKeyedHints) {
EXPECT_TRUE(IsValidURLForURLKeyedHint(GURL("https://blerg.com")));
EXPECT_TRUE(IsValidURLForURLKeyedHint(GURL("http://blerg.com")));
EXPECT_FALSE(IsValidURLForURLKeyedHint(GURL("file://blerg")));
EXPECT_FALSE(IsValidURLForURLKeyedHint(GURL("chrome://blerg")));
EXPECT_FALSE(IsValidURLForURLKeyedHint(
GURL("https://username:password@www.example.com/")));
EXPECT_FALSE(IsValidURLForURLKeyedHint(GURL("https://localhost:5000")));
EXPECT_FALSE(IsValidURLForURLKeyedHint(GURL("https://192.168.1.1")));
}
} // namespace optimization_guide
|
Java
|
// Copyright (c) 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/extensions/settings_api_bubble_helpers.h"
#include <utility>
#include "build/build_config.h"
#include "chrome/browser/extensions/ntp_overridden_bubble_delegate.h"
#include "chrome/browser/extensions/settings_api_bubble_delegate.h"
#include "chrome/browser/extensions/settings_api_helpers.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/extensions/extension_message_bubble_bridge.h"
#include "chrome/browser/ui/extensions/extension_settings_overridden_dialog.h"
#include "chrome/browser/ui/extensions/settings_overridden_params_providers.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/toolbar/toolbar_actions_bar.h"
#include "chrome/browser/ui/ui_features.h"
#include "chrome/common/extensions/manifest_handlers/settings_overrides_handler.h"
#include "chrome/common/url_constants.h"
#include "content/public/browser/browser_url_handler.h"
#include "content/public/browser/navigation_entry.h"
#include "extensions/common/constants.h"
namespace extensions {
namespace {
// Whether the NTP post-install UI is enabled. By default, this is limited to
// Windows, Mac, and ChromeOS, but can be overridden for testing.
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_CHROMEOS)
bool g_ntp_post_install_ui_enabled = true;
#else
bool g_ntp_post_install_ui_enabled = false;
#endif
#if defined(OS_WIN) || defined(OS_MACOSX)
void ShowSettingsApiBubble(SettingsApiOverrideType type,
Browser* browser) {
ToolbarActionsModel* model = ToolbarActionsModel::Get(browser->profile());
if (model->has_active_bubble())
return;
std::unique_ptr<ExtensionMessageBubbleController> settings_api_bubble(
new ExtensionMessageBubbleController(
new SettingsApiBubbleDelegate(browser->profile(), type), browser));
if (!settings_api_bubble->ShouldShow())
return;
settings_api_bubble->SetIsActiveBubble();
std::unique_ptr<ToolbarActionsBarBubbleDelegate> bridge(
new ExtensionMessageBubbleBridge(std::move(settings_api_bubble)));
browser->window()->GetExtensionsContainer()->ShowToolbarActionBubbleAsync(
std::move(bridge));
}
#endif
} // namespace
void SetNtpPostInstallUiEnabledForTesting(bool enabled) {
g_ntp_post_install_ui_enabled = enabled;
}
void MaybeShowExtensionControlledHomeNotification(Browser* browser) {
#if defined(OS_WIN) || defined(OS_MACOSX)
ShowSettingsApiBubble(BUBBLE_TYPE_HOME_PAGE, browser);
#endif
}
void MaybeShowExtensionControlledSearchNotification(
content::WebContents* web_contents,
AutocompleteMatch::Type match_type) {
#if defined(OS_WIN) || defined(OS_MACOSX)
if (!AutocompleteMatch::IsSearchType(match_type) ||
match_type == AutocompleteMatchType::SEARCH_OTHER_ENGINE) {
return;
}
Browser* browser = chrome::FindBrowserWithWebContents(web_contents);
if (!browser)
return;
if (base::FeatureList::IsEnabled(
features::kExtensionSettingsOverriddenDialogs)) {
base::Optional<ExtensionSettingsOverriddenDialog::Params> params =
settings_overridden_params::GetSearchOverriddenParams(
browser->profile());
if (!params)
return;
auto dialog = std::make_unique<ExtensionSettingsOverriddenDialog>(
std::move(*params), browser->profile());
if (!dialog->ShouldShow())
return;
chrome::ShowExtensionSettingsOverriddenDialog(std::move(dialog), browser);
} else {
ShowSettingsApiBubble(BUBBLE_TYPE_SEARCH_ENGINE, browser);
}
#endif
}
void MaybeShowExtensionControlledNewTabPage(
Browser* browser, content::WebContents* web_contents) {
if (!g_ntp_post_install_ui_enabled)
return;
// Acknowledge existing extensions if necessary.
NtpOverriddenBubbleDelegate::MaybeAcknowledgeExistingNtpExtensions(
browser->profile());
// Jump through a series of hoops to see if the web contents is pointing to
// an extension-controlled NTP.
// TODO(devlin): Some of this is redundant with the checks in the bubble/
// dialog. We should consolidate, but that'll be simpler once we only have
// one UI option. In the meantime, extra checks don't hurt.
content::NavigationEntry* entry =
web_contents->GetController().GetVisibleEntry();
if (!entry)
return;
GURL active_url = entry->GetURL();
if (!active_url.SchemeIs(extensions::kExtensionScheme))
return; // Not a URL that we care about.
// See if the current active URL matches a transformed NewTab URL.
GURL ntp_url(chrome::kChromeUINewTabURL);
content::BrowserURLHandler::GetInstance()->RewriteURLIfNecessary(
&ntp_url, web_contents->GetBrowserContext());
if (ntp_url != active_url)
return; // Not being overridden by an extension.
Profile* const profile = browser->profile();
ToolbarActionsModel* model = ToolbarActionsModel::Get(profile);
if (model->has_active_bubble())
return;
if (base::FeatureList::IsEnabled(
features::kExtensionSettingsOverriddenDialogs)) {
base::Optional<ExtensionSettingsOverriddenDialog::Params> params =
settings_overridden_params::GetNtpOverriddenParams(profile);
if (!params)
return;
auto dialog = std::make_unique<ExtensionSettingsOverriddenDialog>(
std::move(*params), profile);
if (!dialog->ShouldShow())
return;
chrome::ShowExtensionSettingsOverriddenDialog(std::move(dialog), browser);
return;
}
std::unique_ptr<ExtensionMessageBubbleController> ntp_overridden_bubble(
new ExtensionMessageBubbleController(
new NtpOverriddenBubbleDelegate(profile), browser));
if (!ntp_overridden_bubble->ShouldShow())
return;
ntp_overridden_bubble->SetIsActiveBubble();
std::unique_ptr<ToolbarActionsBarBubbleDelegate> bridge(
new ExtensionMessageBubbleBridge(std::move(ntp_overridden_bubble)));
browser->window()->GetExtensionsContainer()->ShowToolbarActionBubbleAsync(
std::move(bridge));
}
} // namespace extensions
|
Java
|
package org.broadinstitute.hellbender.engine;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.hellbender.cmdline.TestProgramGroup;
/**
* A Dummy / Placeholder class that can be used where a {@link GATKTool} is required.
* DO NOT USE THIS FOR ANYTHING OTHER THAN TESTING.
* THIS MUST BE IN THE ENGINE PACKAGE DUE TO SCOPE ON `features`!
* Created by jonn on 9/19/18.
*/
@CommandLineProgramProperties(
summary = "A dummy GATKTool to help test Funcotator.",
oneLineSummary = "Dummy dumb dumb tool for testing.",
programGroup = TestProgramGroup.class
)
public final class DummyPlaceholderGatkTool extends GATKTool {
public DummyPlaceholderGatkTool() {
parseArgs(new String[]{});
onStartup();
}
@Override
public void traverse() {
}
@Override
void initializeFeatures(){
features = new FeatureManager(this, FeatureDataSource.DEFAULT_QUERY_LOOKAHEAD_BASES, cloudPrefetchBuffer, cloudIndexPrefetchBuffer,
referenceArguments.getReferencePath());
}
}
|
Java
|
// Standard system includes
#include <assert.h>
#include <errno.h> // -EINVAL, -ENODEV
#include <netdb.h> // gethostbyname
#include <sys/poll.h>
#include <sys/types.h> // connect
#include <sys/socket.h> // connect
#include <trace.h>
#define MY_TRACE_PREFIX "EthernetServer"
extern "C" {
#include "string.h"
}
#include "Ethernet.h"
#include "EthernetClient.h"
#include "EthernetServer.h"
EthernetServer::EthernetServer(uint16_t port)
{
_port = port;
_sock = -1;
_init_ok = false;
pclients = new EthernetClient[MAX_SOCK_NUM];
_pcli_inactivity_counter = new int[MAX_SOCK_NUM];
_scansock = 0;
if (pclients == NULL){
trace_error("%s OOM condition", __func__);
return;
}
for(int sock = 0; sock < MAX_SOCK_NUM; sock++){
_pcli_inactivity_counter[sock] = 0;
pclients[sock].id = sock;
}
}
EthernetServer::~EthernetServer()
{
if (pclients != NULL){
delete [] pclients;
pclients = NULL;
}
if(_pcli_inactivity_counter != NULL){
delete [] _pcli_inactivity_counter;
_pcli_inactivity_counter = NULL;
}
}
void EthernetServer::begin()
{
int ret;
extern int errno;
_sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (_sock < 0){
trace_error("unable to open a TCP socket!");
return;
}
_sin.sin_addr.s_addr = INADDR_ANY;
_sin.sin_family = AF_INET;
_sin.sin_port = htons(_port);
ret = bind(_sock, (struct sockaddr*)&_sin, sizeof(_sin));
if ( ret < 0){
trace_error("%s unable to bind port %d", __func__, _port);
return;
}
//socket(sock, SnMR::TCP, _port, 0);
ret = listen(_sock, MAX_SOCK_NUM);
if ( ret < 0){
trace_error("%s unable to listen on port %d", __func__, _port);
return;
}
for(int sock = 0; sock < MAX_SOCK_NUM; sock++)
EthernetClass::_server_port[sock] = _port;
// mark as available
_init_ok = true;
}
static int _accept(int sock, struct sockaddr * psin, socklen_t * psize)
{
return accept(sock, psin, psize);
}
void EthernetServer::accept()
{
struct pollfd ufds;
int ret = 0, size_val, success = 0;
extern int errno;
if (_sock == -1)
return;
ufds.fd = _sock;
ufds.events = POLLIN;
ufds.revents = 0;
ret = poll(&ufds, 1, 0);
if ( ret < 0 ){
trace_error("%s error on poll errno %d", __func__, errno);
_sock = -1;
close(_sock);
return;
}
if(ufds.revents&POLLIN){
//trace_debug("%s in activity on socket %d - calling accept()", __func__, _sock);
size_val = sizeof(_cli_sin);
ret = _accept(_sock, (struct sockaddr*)&_cli_sin, (socklen_t*)&size_val);
if ( ret < 0){
close(_sock);
_sock = -1;
trace_error("%s Fail to accept() sock %d port %d", __func__, _sock, _port);
return;
}
for(int sock = 0; sock < MAX_SOCK_NUM && success == 0; sock++){
if (pclients[sock]._sock == -1){
pclients[sock]._sock = ret;
pclients[sock]._pCloseServer = this;
pclients[sock].connect_true = true;
pclients[sock]._inactive_counter = &_pcli_inactivity_counter[sock];
success = 1;
}
}
if ( success == 0 ){
trace_error("%s detect connect event - unable to allocate socket slot !", __func__);
}
}
}
EthernetClient EthernetServer::available()
{
accept();
// Scan for next connection - meaning don't return the same one each time
for(int sock = 0; sock < MAX_SOCK_NUM; sock++){
if (pclients[sock]._sock != -1 && sock != _scansock){
//trace_debug("Returning socket entity %d socket %d", sock, pclients[sock]._sock);
_scansock = sock;
return pclients[sock];
}
}
// scan for any connection
for(int sock = 0; sock < MAX_SOCK_NUM; sock++){
if (pclients[sock]._sock != -1){
//trace_debug("Returning socket entity %d socket %d", sock, pclients[sock]._sock);
_scansock = sock;
return pclients[sock];
}
}
//trace_debug("%s no client to return", __func__);
_scansock = 0;
return pclients[0];
}
size_t EthernetServer::write(uint8_t b)
{
return write(&b, 1);
}
size_t EthernetServer::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
//accept();
// This routine writes the given data to all current clients
for(int sock = 0; sock < MAX_SOCK_NUM; sock++){
if (pclients[sock]._sock != -1){
n += pclients[sock].write(buffer, size);
}
}
return n;
}
void EthernetServer::closeNotify(int idx)
{
if (idx < MAX_SOCK_NUM)
pclients[idx]._sock = -1;
}
|
Java
|
'use strict';
module.exports = function (Logger, $rootScope) {
return {
restrict: 'A',
scope: {
hasRank: '='
},
link: function ($scope, elem, attrs) {
$rootScope.$watch('currentUser', function () {
Logger.info('Checking for rank: ' + $scope.hasRank);
if ($rootScope.currentUser && $rootScope.currentUser.rank >= $scope.hasRank) {
elem.show();
} else {
elem.hide();
}
});
}
};
};
|
Java
|
/*
* Created on 02/04/2005
*
* JRandTest package
*
* Copyright (c) 2005, Zur Aougav, aougav@hotmail.com
* 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 JRandTest nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.fasteasytrade.jrandtest.algo;
import java.math.BigInteger;
import java.util.Random;
/**
* QuadraidResidue1 Prng algorithm from NIST test package
* <p>
* Fix random p, prime, length 512 bits.
* <p>
* Fix random g, prime, length 512 bits. g < p.
* <p>
* Each prng iteration calculate g = g**2 mod p.<br>
* The lowest 64 bits of g are the prng result.
*
* @author Zur Aougav
*/
public class QuadraticResidue1Prng extends Cipher {
/**
* n's length/num of bits
*/
public final int bit_length = 512;
/**
* prime (with probability < 2 ** -100).
* <p>
* Length of p is bit_length = 512 bits = 64 bytes.
*/
BigInteger p;
/**
* Initial g is a random prime (with probability < 2 ** -100)
* <p>
* Length of g is bit_length = 512 bits = 64 bytes.
* <p>
* g is the "state" of the prng.
* <p>
* g = take 64 lowr bits of ( g**2 mod n ).
*/
BigInteger g;
/**
* g0 is the "initial state" of the prng.
* <p>
* reset method set g to g0.
*/
BigInteger g0;
QuadraticResidue1Prng() {
setup(bit_length);
}
QuadraticResidue1Prng(int x) {
if (x < bit_length) {
setup(bit_length);
} else {
setup(x);
}
}
QuadraticResidue1Prng(BigInteger p, BigInteger g) {
this.p = p;
this.g = g;
g0 = g;
}
QuadraticResidue1Prng(BigInteger p, BigInteger g, BigInteger g0) {
this.p = p;
this.g = g;
this.g0 = g0;
}
/**
* Generate the key and seed for Quadratic Residue Prng.
* <p>
* Select random primes - p, g. g < p.
*
* @param len
* length of p and g, num of bits.
*/
void setup(int len) {
Random rand = new Random();
p = BigInteger.probablePrime(len, rand);
g = BigInteger.probablePrime(len, rand);
/**
* if g >= p swap(g, p).
*/
if (g.compareTo(p) > -1) {
BigInteger temp = g;
g = p;
p = temp;
}
/**
* here for sure g < p
*/
g0 = g;
}
/**
* calculate g**2 mod p and returns lowest 64 bits, long.
*
*/
public long nextLong() {
g = g.multiply(g).mod(p);
/**
* set g to 2 if g <= 1.
*/
if (g.compareTo(BigInteger.ONE) < 1) {
g = BigInteger.valueOf(2);
}
return g.longValue();
}
/**
* Public key.
*
* @return p prime (with probability < 2 ** -100)
*/
public BigInteger getP() {
return p;
}
/**
* Secret key
*
* @return g prime (with probability < 2 ** -100)
*/
public BigInteger getG() {
return g;
}
/**
* Reset "state" of prng by setting g to g0 (initial g).
*
*/
public void reset() {
g = g0;
}
}
|
Java
|
/*
* Copyright (c) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "core/inspector/MainThreadDebugger.h"
#include "bindings/core/v8/BindingSecurity.h"
#include "bindings/core/v8/DOMWrapperWorld.h"
#include "bindings/core/v8/ScriptController.h"
#include "bindings/core/v8/SourceLocation.h"
#include "bindings/core/v8/V8ErrorHandler.h"
#include "bindings/core/v8/V8Node.h"
#include "bindings/core/v8/V8Window.h"
#include "bindings/core/v8/WorkerOrWorkletScriptController.h"
#include "core/dom/ContainerNode.h"
#include "core/dom/Document.h"
#include "core/dom/Element.h"
#include "core/dom/ExecutionContext.h"
#include "core/dom/StaticNodeList.h"
#include "core/events/ErrorEvent.h"
#include "core/frame/Deprecation.h"
#include "core/frame/FrameConsole.h"
#include "core/frame/FrameHost.h"
#include "core/frame/LocalDOMWindow.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Settings.h"
#include "core/frame/UseCounter.h"
#include "core/inspector/ConsoleMessage.h"
#include "core/inspector/ConsoleMessageStorage.h"
#include "core/inspector/IdentifiersFactory.h"
#include "core/inspector/InspectedFrames.h"
#include "core/inspector/InspectorTaskRunner.h"
#include "core/timing/MemoryInfo.h"
#include "core/workers/MainThreadWorkletGlobalScope.h"
#include "core/xml/XPathEvaluator.h"
#include "core/xml/XPathResult.h"
#include "platform/UserGestureIndicator.h"
#include "platform/inspector_protocol/Values.h"
#include "platform/v8_inspector/public/V8Inspector.h"
#include "wtf/PtrUtil.h"
#include "wtf/ThreadingPrimitives.h"
#include <memory>
namespace blink {
namespace {
int frameId(LocalFrame* frame)
{
ASSERT(frame);
return WeakIdentifierMap<LocalFrame>::identifier(frame);
}
Mutex& creationMutex()
{
DEFINE_THREAD_SAFE_STATIC_LOCAL(Mutex, mutex, (new Mutex));
return mutex;
}
LocalFrame* toFrame(ExecutionContext* context)
{
if (!context)
return nullptr;
if (context->isDocument())
return toDocument(context)->frame();
if (context->isMainThreadWorkletGlobalScope())
return toMainThreadWorkletGlobalScope(context)->frame();
return nullptr;
}
}
MainThreadDebugger* MainThreadDebugger::s_instance = nullptr;
MainThreadDebugger::MainThreadDebugger(v8::Isolate* isolate)
: ThreadDebugger(isolate)
, m_taskRunner(wrapUnique(new InspectorTaskRunner()))
, m_paused(false)
{
MutexLocker locker(creationMutex());
ASSERT(!s_instance);
s_instance = this;
}
MainThreadDebugger::~MainThreadDebugger()
{
MutexLocker locker(creationMutex());
ASSERT(s_instance == this);
s_instance = nullptr;
}
void MainThreadDebugger::reportConsoleMessage(ExecutionContext* context, MessageSource source, MessageLevel level, const String& message, SourceLocation* location)
{
if (LocalFrame* frame = toFrame(context))
frame->console().reportMessageToClient(source, level, message, location);
}
int MainThreadDebugger::contextGroupId(ExecutionContext* context)
{
LocalFrame* frame = toFrame(context);
return frame ? contextGroupId(frame) : 0;
}
void MainThreadDebugger::setClientMessageLoop(std::unique_ptr<ClientMessageLoop> clientMessageLoop)
{
ASSERT(!m_clientMessageLoop);
ASSERT(clientMessageLoop);
m_clientMessageLoop = std::move(clientMessageLoop);
}
void MainThreadDebugger::didClearContextsForFrame(LocalFrame* frame)
{
DCHECK(isMainThread());
if (frame->localFrameRoot() == frame)
v8Inspector()->resetContextGroup(contextGroupId(frame));
}
void MainThreadDebugger::contextCreated(ScriptState* scriptState, LocalFrame* frame, SecurityOrigin* origin)
{
ASSERT(isMainThread());
v8::HandleScope handles(scriptState->isolate());
DOMWrapperWorld& world = scriptState->world();
std::unique_ptr<protocol::DictionaryValue> auxData = protocol::DictionaryValue::create();
auxData->setBoolean("isDefault", world.isMainWorld());
auxData->setString("frameId", IdentifiersFactory::frameId(frame));
V8ContextInfo contextInfo(scriptState->context(), contextGroupId(frame), world.isIsolatedWorld() ? world.isolatedWorldHumanReadableName() : "");
if (origin)
contextInfo.origin = origin->toRawString();
contextInfo.auxData = auxData->toJSONString();
contextInfo.hasMemoryOnConsole = scriptState->getExecutionContext()->isDocument();
v8Inspector()->contextCreated(contextInfo);
}
void MainThreadDebugger::contextWillBeDestroyed(ScriptState* scriptState)
{
v8::HandleScope handles(scriptState->isolate());
v8Inspector()->contextDestroyed(scriptState->context());
}
void MainThreadDebugger::exceptionThrown(ExecutionContext* context, ErrorEvent* event)
{
LocalFrame* frame = nullptr;
ScriptState* scriptState = nullptr;
if (context->isDocument()) {
frame = toDocument(context)->frame();
if (!frame)
return;
scriptState = event->world() ? ScriptState::forWorld(frame, *event->world()) : nullptr;
} else if (context->isMainThreadWorkletGlobalScope()) {
frame = toMainThreadWorkletGlobalScope(context)->frame();
if (!frame)
return;
scriptState = toMainThreadWorkletGlobalScope(context)->scriptController()->getScriptState();
} else {
NOTREACHED();
}
frame->console().reportMessageToClient(JSMessageSource, ErrorMessageLevel, event->messageForConsole(), event->location());
const String16 defaultMessage = "Uncaught";
if (scriptState && scriptState->contextIsValid()) {
ScriptState::Scope scope(scriptState);
v8::Local<v8::Value> exception = V8ErrorHandler::loadExceptionFromErrorEventWrapper(scriptState, event, scriptState->context()->Global());
SourceLocation* location = event->location();
v8Inspector()->exceptionThrown(scriptState->context(), defaultMessage, exception, event->messageForConsole(), location->url(), location->lineNumber(), location->columnNumber(), location->takeStackTrace(), location->scriptId());
}
}
int MainThreadDebugger::contextGroupId(LocalFrame* frame)
{
LocalFrame* localFrameRoot = frame->localFrameRoot();
return frameId(localFrameRoot);
}
MainThreadDebugger* MainThreadDebugger::instance()
{
ASSERT(isMainThread());
V8PerIsolateData* data = V8PerIsolateData::from(V8PerIsolateData::mainThreadIsolate());
ASSERT(data->threadDebugger() && !data->threadDebugger()->isWorker());
return static_cast<MainThreadDebugger*>(data->threadDebugger());
}
void MainThreadDebugger::interruptMainThreadAndRun(std::unique_ptr<InspectorTaskRunner::Task> task)
{
MutexLocker locker(creationMutex());
if (s_instance) {
s_instance->m_taskRunner->appendTask(std::move(task));
s_instance->m_taskRunner->interruptAndRunAllTasksDontWait(s_instance->m_isolate);
}
}
void MainThreadDebugger::runMessageLoopOnPause(int contextGroupId)
{
LocalFrame* pausedFrame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
// Do not pause in Context of detached frame.
if (!pausedFrame)
return;
ASSERT(pausedFrame == pausedFrame->localFrameRoot());
m_paused = true;
if (UserGestureToken* token = UserGestureIndicator::currentToken())
token->setPauseInDebugger();
// Wait for continue or step command.
if (m_clientMessageLoop)
m_clientMessageLoop->run(pausedFrame);
}
void MainThreadDebugger::quitMessageLoopOnPause()
{
m_paused = false;
if (m_clientMessageLoop)
m_clientMessageLoop->quitNow();
}
void MainThreadDebugger::muteMetrics(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
if (frame && frame->host()) {
frame->host()->useCounter().muteForInspector();
frame->host()->deprecation().muteForInspector();
}
}
void MainThreadDebugger::unmuteMetrics(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
if (frame && frame->host()) {
frame->host()->useCounter().unmuteForInspector();
frame->host()->deprecation().unmuteForInspector();
}
}
v8::Local<v8::Context> MainThreadDebugger::ensureDefaultContextInGroup(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
ScriptState* scriptState = frame ? ScriptState::forMainWorld(frame) : nullptr;
return scriptState ? scriptState->context() : v8::Local<v8::Context>();
}
void MainThreadDebugger::beginEnsureAllContextsInGroup(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
frame->settings()->setForceMainWorldInitialization(true);
}
void MainThreadDebugger::endEnsureAllContextsInGroup(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
frame->settings()->setForceMainWorldInitialization(false);
}
bool MainThreadDebugger::canExecuteScripts(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
return frame->script().canExecuteScripts(NotAboutToExecuteScript);
}
void MainThreadDebugger::resumeStartup(int contextGroupId)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
if (m_clientMessageLoop)
m_clientMessageLoop->resumeStartup(frame);
}
void MainThreadDebugger::consoleAPIMessage(int contextGroupId, V8ConsoleAPIType type, const String16& message, const String16& url, unsigned lineNumber, unsigned columnNumber, V8StackTrace* stackTrace)
{
LocalFrame* frame = WeakIdentifierMap<LocalFrame>::lookup(contextGroupId);
if (!frame)
return;
if (type == V8ConsoleAPIType::kClear && frame->host())
frame->host()->consoleMessageStorage().clear();
std::unique_ptr<SourceLocation> location = SourceLocation::create(url, lineNumber, columnNumber, stackTrace ? stackTrace->clone() : nullptr, 0);
frame->console().reportMessageToClient(ConsoleAPIMessageSource, consoleAPITypeToMessageLevel(type), message, location.get());
}
v8::MaybeLocal<v8::Value> MainThreadDebugger::memoryInfo(v8::Isolate* isolate, v8::Local<v8::Context> context)
{
ExecutionContext* executionContext = toExecutionContext(context);
ASSERT_UNUSED(executionContext, executionContext);
ASSERT(executionContext->isDocument());
return toV8(MemoryInfo::create(), context->Global(), isolate);
}
void MainThreadDebugger::installAdditionalCommandLineAPI(v8::Local<v8::Context> context, v8::Local<v8::Object> object)
{
ThreadDebugger::installAdditionalCommandLineAPI(context, object);
createFunctionProperty(context, object, "$", MainThreadDebugger::querySelectorCallback, "function $(selector, [startNode]) { [Command Line API] }");
createFunctionProperty(context, object, "$$", MainThreadDebugger::querySelectorAllCallback, "function $$(selector, [startNode]) { [Command Line API] }");
createFunctionProperty(context, object, "$x", MainThreadDebugger::xpathSelectorCallback, "function $x(xpath, [startNode]) { [Command Line API] }");
}
static Node* secondArgumentAsNode(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() > 1) {
if (Node* node = V8Node::toImplWithTypeCheck(info.GetIsolate(), info[1]))
return node;
}
ExecutionContext* executionContext = toExecutionContext(info.GetIsolate()->GetCurrentContext());
if (executionContext->isDocument())
return toDocument(executionContext);
return nullptr;
}
void MainThreadDebugger::querySelectorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() < 1)
return;
String selector = toCoreStringWithUndefinedOrNullCheck(info[0]);
if (selector.isEmpty())
return;
Node* node = secondArgumentAsNode(info);
if (!node || !node->isContainerNode())
return;
ExceptionState exceptionState(ExceptionState::ExecutionContext, "$", "CommandLineAPI", info.Holder(), info.GetIsolate());
Element* element = toContainerNode(node)->querySelector(AtomicString(selector), exceptionState);
if (exceptionState.throwIfNeeded())
return;
if (element)
info.GetReturnValue().Set(toV8(element, info.Holder(), info.GetIsolate()));
else
info.GetReturnValue().Set(v8::Null(info.GetIsolate()));
}
void MainThreadDebugger::querySelectorAllCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() < 1)
return;
String selector = toCoreStringWithUndefinedOrNullCheck(info[0]);
if (selector.isEmpty())
return;
Node* node = secondArgumentAsNode(info);
if (!node || !node->isContainerNode())
return;
ExceptionState exceptionState(ExceptionState::ExecutionContext, "$$", "CommandLineAPI", info.Holder(), info.GetIsolate());
// toV8(elementList) doesn't work here, since we need a proper Array instance, not NodeList.
StaticElementList* elementList = toContainerNode(node)->querySelectorAll(AtomicString(selector), exceptionState);
if (exceptionState.throwIfNeeded() || !elementList)
return;
v8::Isolate* isolate = info.GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Array> nodes = v8::Array::New(isolate, elementList->length());
for (size_t i = 0; i < elementList->length(); ++i) {
Element* element = elementList->item(i);
if (!nodes->Set(context, i, toV8(element, info.Holder(), info.GetIsolate())).FromMaybe(false))
return;
}
info.GetReturnValue().Set(nodes);
}
void MainThreadDebugger::xpathSelectorCallback(const v8::FunctionCallbackInfo<v8::Value>& info)
{
if (info.Length() < 1)
return;
String selector = toCoreStringWithUndefinedOrNullCheck(info[0]);
if (selector.isEmpty())
return;
Node* node = secondArgumentAsNode(info);
if (!node || !node->isContainerNode())
return;
ExceptionState exceptionState(ExceptionState::ExecutionContext, "$x", "CommandLineAPI", info.Holder(), info.GetIsolate());
XPathResult* result = XPathEvaluator::create()->evaluate(selector, node, nullptr, XPathResult::kAnyType, ScriptValue(), exceptionState);
if (exceptionState.throwIfNeeded() || !result)
return;
if (result->resultType() == XPathResult::kNumberType) {
info.GetReturnValue().Set(toV8(result->numberValue(exceptionState), info.Holder(), info.GetIsolate()));
} else if (result->resultType() == XPathResult::kStringType) {
info.GetReturnValue().Set(toV8(result->stringValue(exceptionState), info.Holder(), info.GetIsolate()));
} else if (result->resultType() == XPathResult::kBooleanType) {
info.GetReturnValue().Set(toV8(result->booleanValue(exceptionState), info.Holder(), info.GetIsolate()));
} else {
v8::Isolate* isolate = info.GetIsolate();
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Array> nodes = v8::Array::New(isolate);
size_t index = 0;
while (Node* node = result->iterateNext(exceptionState)) {
if (exceptionState.throwIfNeeded())
return;
if (!nodes->Set(context, index++, toV8(node, info.Holder(), info.GetIsolate())).FromMaybe(false))
return;
}
info.GetReturnValue().Set(nodes);
}
exceptionState.throwIfNeeded();
}
} // namespace blink
|
Java
|
Spree.user_class.class_eval do
belongs_to :supplier, class_name: 'Spree::Supplier', optional: true
has_many :variants, through: :supplier
def supplier?
supplier.present?
end
def supplier_admin?
spree_roles.map(&:name).include?("supplier_admin")
end
def market_maker?
has_admin_role?
end
def has_admin_role?
spree_roles.map(&:name).include?("admin")
end
end
|
Java
|
# Possible discounts:
# - Node (administer inline with nodes)
# - Bulk amounts on nodes
# - User
# - Group of users
# - Order (this is more-or-less a voucher)
# - Shipping costs
# Possible amounts:
# - Percentage
# - Fixed amount
# Flag indicating if a discount can be combined with other discounts.
# Boolean "offer" to include in list of offers. Default to true if discount is at node level.
# Save all applied discounts when ordering in a ManyToMany relationship with Order.
|
Java
|
// Copyright © 2017 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Threading.Tasks;
namespace CefSharp.Test
{
public static class WebBrowserTestExtensions
{
public static Task<LoadUrlAsyncResponse> LoadRequestAsync(this IWebBrowser browser, IRequest request)
{
if(request == null)
{
throw new ArgumentNullException("request");
}
//If using .Net 4.6 then use TaskCreationOptions.RunContinuationsAsynchronously
//and switch to tcs.TrySetResult below - no need for the custom extension method
var tcs = new TaskCompletionSource<LoadUrlAsyncResponse>(TaskCreationOptions.RunContinuationsAsynchronously);
EventHandler<LoadErrorEventArgs> loadErrorHandler = null;
EventHandler<LoadingStateChangedEventArgs> loadingStateChangeHandler = null;
loadErrorHandler = (sender, args) =>
{
//Ignore Aborted
//Currently invalid SSL certificates which aren't explicitly allowed
//end up with CefErrorCode.Aborted, I've created the following PR
//in the hopes of getting this fixed.
//https://bitbucket.org/chromiumembedded/cef/pull-requests/373
if (args.ErrorCode == CefErrorCode.Aborted)
{
return;
}
//If LoadError was called then we'll remove both our handlers
//as we won't need to capture LoadingStateChanged, we know there
//was an error
browser.LoadError -= loadErrorHandler;
browser.LoadingStateChanged -= loadingStateChangeHandler;
tcs.TrySetResult(new LoadUrlAsyncResponse(args.ErrorCode, -1));
};
loadingStateChangeHandler = (sender, args) =>
{
//Wait for while page to finish loading not just the first frame
if (!args.IsLoading)
{
var host = args.Browser.GetHost();
var navEntry = host?.GetVisibleNavigationEntry();
int statusCode = navEntry?.HttpStatusCode ?? -1;
//By default 0 is some sort of error, we map that to -1
//so that it's clearer that something failed.
if (statusCode == 0)
{
statusCode = -1;
}
browser.LoadingStateChanged -= loadingStateChangeHandler;
//This is required when using a standard TaskCompletionSource
//Extension method found in the CefSharp.Internals namespace
tcs.TrySetResult(new LoadUrlAsyncResponse(CefErrorCode.None, statusCode));
}
};
browser.LoadingStateChanged += loadingStateChangeHandler;
browser.GetMainFrame().LoadRequest(request);
return tcs.Task;
}
public static Task<bool> WaitForQUnitTestExeuctionToComplete(this IWebBrowser browser)
{
//If using .Net 4.6 then use TaskCreationOptions.RunContinuationsAsynchronously
//and switch to tcs.TrySetResult below - no need for the custom extension method
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
EventHandler<JavascriptMessageReceivedEventArgs> handler = null;
handler = (sender, args) =>
{
browser.JavascriptMessageReceived -= handler;
dynamic msg = args.Message;
//Wait for while page to finish loading not just the first frame
if (msg.Type == "QUnitExecutionComplete")
{
var details = msg.Details;
var total = (int)details.total;
var passed = (int)details.passed;
tcs.TrySetResult(total == passed);
}
else
{
tcs.TrySetException(new Exception("WaitForQUnitTestExeuctionToComplete - Incorrect Message Type"));
}
};
browser.JavascriptMessageReceived += handler;
return tcs.Task;
}
}
}
|
Java
|
<?php
use yii\db\Migration;
class m160407_113339_vraagenAndAwnserFixjes extends Migration
{
public function safeUp()
{
$this->alterColumn('vraag', 'text', 'blob');
$this->alterColumn('antwoord', 'text', 'blob');
}
public function safeDown()
{
$this->alterColumn('vraag', 'text', 'string(128)');
$this->alterColumn('antwoord', 'text', 'string(128)');
}
}
|
Java
|
#ifndef CTRL_PARTITION_H
#define CTRL_PARTITION_H
#include <wx/panel.h>
//#include <wx/sizer.h>
enum CTRL_STATE
{
S_IDLE,
S_LEFT_SLIDER,
S_RIGHT_SLIDER,
S_MOVE
};
class wxPartition : public wxPanel
{
static const int slider_width = 10;
int slider_left_pos;
int slider_right_pos;
CTRL_STATE state;
unsigned n_steps;
wxMouseEvent mouse_old_pos;
bool enabled;
public:
wxPartition(wxWindow *parent,
wxWindowID winid = wxID_ANY,
const wxPoint& pos = wxDefaultPosition,
const wxSize& size = wxDefaultSize,
long style = 0,
const wxString &name = wxPanelNameStr);
void SetNumberOfSteps(unsigned n_steps){this->n_steps=n_steps;}
unsigned GetNumberOfSteps(){return n_steps;}
bool SetLeftSliderPos(unsigned pos);
bool SetRightSliderPos(unsigned pos);
unsigned GetLeftSliderPos();
unsigned GetRightSliderPos();
bool Enable(bool enable=true);
void paintEvent(wxPaintEvent & evt);
void paintNow();
void render(wxDC& dc);
void mouseMoved(wxMouseEvent& event);
void mouseDown(wxMouseEvent& event);
void mouseReleased(wxMouseEvent& event);
void mouseLeftWindow(wxMouseEvent& event);
void mouseLeftDoubleClick(wxMouseEvent& event);
DECLARE_EVENT_TABLE()
};
#endif
|
Java
|
Title: Music API Server说明文档
Date: 2014-06-24 12:56
Update: 2014-07-02 20:36
Tags: 音乐服务, API
音乐服务的api通用接口,目前已支持的音乐服务:
* 虾米
* 专辑
* 歌曲列表
* 精选集
* 网易云音乐
* 专辑
* 歌曲列表
* 歌单
仓库地址: [mawenbao/music-api-server](https://github.com/mawenbao/music-api-server)
## 安装(debian/ubuntu)
首先检查`GOPATH`变量是否正确设置,如果未设置,参考[这里](http://blog.atime.me/note/golang-summary.html#3867e350ebb33a487c4ac5f7787e1c29)进行设置。
# install redis-server
sudo apt-get install redis-server
# install redis driver for golang
go get github.com/garyburd/redigo/redis
# install music api server
go get github.com/mawenbao/music-api-server
# install init script
sudo cp $GOPATH/src/github.com/mawenbao/music-api-server/tools/init-script /etc/init.d/music-api-server
# set your GOPATH in init script
sudo sed -i "s|/SET/YOUR/GOPATH/HERE|`echo $GOPATH`|" /etc/init.d/music-api-server
sudo chmod +x /etc/init.d/music-api-server
# start music api server
sudo service music-api-server start
# (optional) let music api server start on boot
sudo update-rc.d music-api-server defaults
# (optional) install logrotate config
sudo cp $GOPATH/src/github.com/mawenbao/music-api-server/tools/logrotate-config /etc/logrotate.d/music-api-server
## 更新(debian/ubuntu)
# update and restart music-api-server
go get -u github.com/mawenbao/music-api-server
sudo service music-api-server restart
# flush redis cache
redis-cli
> flushall
## API
### Demo
[http://app.atime.me/music-api-server/?p=xiami&t=songlist&i=20526,1772292423&c=abc123](http://app.atime.me/music-api-server/?p=xiami&t=songlist&i=20526,1772292423&c=abc123)
### 请求
GET http://localhost:9099/?p=xiami&t=songlist&i=20526,1772292423&c=abc123
* `localhost:9099`: 默认监听地址
* `p=xiami`: 音乐API提供商,目前支持:
* 虾米(xiami)
* 网易云音乐(netease)
* `t=songlist`: 音乐类型
* songlist(xiami + netease): 歌曲列表,对应的id是半角逗号分隔的多个歌曲id
* album(xiami + netease): 音乐专辑,对应的id为专辑id
* collect(xiami): 虾米的精选集,对应的id为精选集id
* playlist(netease): 网易云音乐的歌单,对应的id为歌单(playlist)id
* `i=20526,1772292423`: 歌曲/专辑/精选集/歌单的id,歌曲列表类型可用半角逗号分割多个歌曲id
* `c=abc123`: 使用jsonp方式返回数据,实际返回为`abc123({songs: ...});`
### 返回
{
"status": "返回状态,ok为正常,failed表示出错并设置msg",
"msg": "如果status为failed,这里会保存错误信息,否则不返回该字段",
"songs": [
{
"name": "歌曲名称",
"url": "歌曲播放地址",
"artists": "演唱者",
"provider": "音乐提供商"
"lrc_url": "歌词文件地址(可能没有)",
}
]
}
如果有`c=abc123`请求参数,则实际以[jsonp](http://en.wikipedia.org/wiki/JSONP)方式返回数据。
## TODO
1. 更好的缓存策略
## Thanks
* [Wordpress Hermit Player](http://mufeng.me/hermit-for-wordpress.html)
* [网易云音乐API分析](https://github.com/yanunon/NeteaseCloudMusic/wiki/%E7%BD%91%E6%98%93%E4%BA%91%E9%9F%B3%E4%B9%90API%E5%88%86%E6%9E%90)
|
Java
|
<?php
use SerializerKit\XmlSerializer;
class XmlSerializerTest extends PHPUnit_Framework_TestCase
{
function test()
{
$xmls = new XmlSerializer;
$string = $xmls->encode(array(
'title' => 'War and Peace',
'isbn' => 123123123,
'authors' => array(
array( 'name' => 'First', 'email' => 'Email-1' ),
array( 'name' => 'Second', 'email' => 'Email-2' ),
),
));
ok( $string );
$data = $xmls->decode( $string );
ok( $data['title'] );
ok( $data['isbn'] );
ok( is_array($data['authors']) );
ok( $data['authors'][0] );
ok( $data['authors'][1] );
}
}
|
Java
|
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# User-friendly check for sphinx-build
ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
endif
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
clean:
rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Blinky.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Blinky.qhc"
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/Blinky"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Blinky"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
|
Java
|
#![allow(missing_docs)]
use downcast_rs::Downcast;
use na::{DVector, RealField};
use ncollide::query::ContactId;
use crate::detection::ColliderContactManifold;
use crate::material::MaterialsCoefficientsTable;
use crate::object::{BodyHandle, BodySet, ColliderHandle};
use crate::solver::{ConstraintSet, IntegrationParameters};
/// The modeling of a contact.
pub trait ContactModel<N: RealField, Handle: BodyHandle, CollHandle: ColliderHandle>:
Downcast + Send + Sync
{
/// Maximum number of velocity constraint to be generated for each contact.
fn num_velocity_constraints(
&self,
manifold: &ColliderContactManifold<N, Handle, CollHandle>,
) -> usize;
/// Generate all constraints for the given contact manifolds.
fn constraints(
&mut self,
parameters: &IntegrationParameters<N>,
material_coefficients: &MaterialsCoefficientsTable<N>,
bodies: &dyn BodySet<N, Handle = Handle>,
ext_vels: &DVector<N>,
manifolds: &[ColliderContactManifold<N, Handle, CollHandle>],
ground_j_id: &mut usize,
j_id: &mut usize,
jacobians: &mut [N],
constraints: &mut ConstraintSet<N, Handle, CollHandle, ContactId>,
);
/// Stores all the impulses found by the solver into a cache for warmstarting.
fn cache_impulses(&mut self, constraints: &ConstraintSet<N, Handle, CollHandle, ContactId>);
}
impl_downcast!(ContactModel<N, Handle, CollHandle> where N: RealField, Handle: BodyHandle, CollHandle: ColliderHandle);
|
Java
|
/**
* @file
* Money is a value object representing a monetary value. It does not use
* floating point numbers, so it avoids rounding errors.
* The only operation that may cause stray cents is split, it assures that no
* cents vanish by distributing as evenly as possible among the parts it splits into.
*
* Money has no notion of currency, so working in a single currency -- no matter
* which one -- is appropriate usage.
*
* In lack of better terminology, Money uses "dollars" and "cents".
*
* One dollar is assumed to be 100 cents.
*
* The cent number is guaranteed to be below 100.
*/
Module("Cactus.Data", function (m) {
/**
* @param natural dollars
* @param natural cents
* if > 100 then dollars are added until cents < 100.
*/
var Money = Class("Money", {
has : {
/**
* @type int
*/
amount : null
},
methods : {
BUILD : function (dollars, cents) {
var dollars = parseInt(dollars, 10);
var cents = parseInt(cents, 10);
if (dollars !== 0 && cents < 0) {
throw new Error("Money: cents < 0");
}
if (isNaN(dollars)) {
throw new Error("Money: dollars is NaN");
}
if (isNaN(cents)) {
throw new Error("Money: cents is NaN");
}
return {
amount : dollars * 100 + (dollars < 0 ? -1 * cents : cents)
};
},
/**
* @return int
*/
_getAmount : function () {
return this.amount;
},
/**
* @return natural
*/
getDollars : function () {
if (this.amount < 0) {
return Math.ceil(this.amount / 100);
} else {
return Math.floor(this.amount / 100);
}
},
/**
* @return natural
*/
getCents : function () {
if (this.amount < 0 && this.getDollars() === 0) {
return this.amount % 100;
} else {
return Math.abs(this.amount % 100);
}
},
/**
* The value with zero padded cents if < 100, and . used as the decimal
* separator.
*
* @return string
*/
toString : function () {
if (this.isNegative()) {
if (this.gt(new Money(-1, 0))) {
var cents = (-this.getCents()) < 10
? "0" + (-this.getCents()) : (-this.getCents());
return "-0." + cents;
}
}
var cents = this.getCents() < 10
? "0" + this.getCents() : this.getCents();
return this.getDollars() + "." + cents;
},
/**
* @param Money money
* @return Money
*/
add : function (money) {
return Money._fromAmount(this._getAmount() + money._getAmount());
},
/**
* @param Money money
* @return Money
*/
sub : function (money) {
return Money._fromAmount(this._getAmount() - money._getAmount());
},
/**
* @param number multiplier
* @return Money
*/
mult : function (multiplier) {
return Money._fromAmount(this._getAmount() * multiplier);
},
/**
* @return Boolean
*/
isPositive : function () {
return this._getAmount() > 0;
},
/**
* @return Boolean
*/
isNegative : function () {
return this._getAmount() < 0;
},
/**
* @return Boolean
*/
isZero : function () {
return this._getAmount() === 0;
},
/**
* @param Money money
* @return Boolean
*/
equals : function (money) {
return this._getAmount() === money._getAmount();
},
/**
* @param Money money
* @return Boolean
*/
gt : function (money) {
return this._getAmount() > money._getAmount();
},
/**
* @param Money money
* @return Boolean
*/
lt : function (money) {
return money.gt(this);
},
/**
* @param Money money
* @return Money
*/
negate : function () {
return Money._fromAmount(-this._getAmount());
},
/**
* Splits the object into parts, the remaining cents are distributed from
* the first element of the result and onward.
*
* @param int divisor
* @return Array<Money>
*/
split : function (divisor) {
var dividend = this._getAmount();
var quotient = Math.floor(dividend / divisor);
var remainder = dividend - quotient * divisor;
var res = [];
var moneyA = Money._fromAmount(quotient + 1);
var moneyB = Money._fromAmount(quotient);
for (var i = 0; i < remainder; i++) {
res.push(moneyA);
}
for (i = 0; i < divisor - remainder; i++) {
res.push(moneyB);
}
return res;
},
/**
* @return Hash{
* dollars : int,
* cents : int
* }
*/
serialize : function () {
return {
dollars : this.getDollars(),
cents : this.getCents()
};
}
}
});
/**
* @param String s
* @return Money
*/
Money.fromString = function (s) {
if (s === null) {
throw new Error("Money.fromString: String was null.");
}
if (s === "") {
throw new Error("Money.fromString: String was empty.");
}
if (!/^-?\d+(?:\.\d{2})?$/.test(s)) {
throw new Error("Money.fromString: Invalid format, got: " + s);
}
var a = s.split(".");
if (a.length === 1) {
return new Money(parseInt(a[0], 10), 0);
} else if (a.length === 2) {
return new Money(parseInt(a[0], 10), parseInt(a[1], 10));
} else {
throw new Error("Money:fromString: BUG: RegExp should have prevent this from happening.");
}
};
/**
* @param int amount
* @return Money
*/
Money._fromAmount = function (amount) {
if (amount > 0) {
return new Money(Math.floor(amount / 100), amount % 100);
} else {
return new Money(Math.ceil(amount / 100), Math.abs(amount) < 100 ? (amount % 100) : -(amount % 100));
}
};
/**
* @param Array<Money> ms
* @return Money
*/
Money.sum = function (ms) {
var sum = new Money(0, 0);
for (var i = 0; i < ms.length; i++) {
sum = sum.add(ms[i]);
}
return sum;
};
m.Money = Money;
});
|
Java
|
#include "Shape.h"
#include "DynBase.h"
//#include <iostream>
using std::cout;
using std::endl;
Shape::~Shape()
{
cout << "~Shape ..." << endl;
}
void Circle::Draw()
{
cout << "Circle::Draw() ..." << endl;
}
Circle::~Circle()
{
cout << "~Circle ..." << endl;
}
void Square::Draw()
{
cout << "Square::Draw() ..." << endl;
}
Square::~Square()
{
cout << "~Square ..." << endl;
}
void Rectangle::Draw()
{
cout << "Rectangle::Draw() ..." << endl;
}
Rectangle::~Rectangle()
{
cout << "~Rectangle ..." << endl;
}
REGISTER_CLASS(Circle);
REGISTER_CLASS(Square);
REGISTER_CLASS(Rectangle);
/*class CircleRegister
{
public:
static void* NewInstance()
{
return new Rectangle;
}
private:
static Register reg_;
};
Register CircleRegister::reg_("Circle", CircleRegister::NewInstance);*/
|
Java
|
// Copyright (c) Jupyter Development Team.
// Distributed under the terms of the Modified BSD License.
'use strict';
import {
IContentsModel
} from 'jupyter-js-services';
import {
Message
} from 'phosphor-messaging';
import {
PanelLayout
} from 'phosphor-panel';
import {
Widget
} from 'phosphor-widget';
import {
FileButtons
} from './buttons';
import {
BreadCrumbs
} from './crumbs';
import {
DirListing
} from './listing';
import {
FileBrowserModel
} from './model';
import {
FILE_BROWSER_CLASS, showErrorMessage
} from './utils';
/**
* The class name added to the filebrowser crumbs node.
*/
const CRUMBS_CLASS = 'jp-FileBrowser-crumbs';
/**
* The class name added to the filebrowser buttons node.
*/
const BUTTON_CLASS = 'jp-FileBrowser-buttons';
/**
* The class name added to the filebrowser listing node.
*/
const LISTING_CLASS = 'jp-FileBrowser-listing';
/**
* The duration of auto-refresh in ms.
*/
const REFRESH_DURATION = 30000;
/**
* A widget which hosts a file browser.
*
* The widget uses the Jupyter Contents API to retreive contents,
* and presents itself as a flat list of files and directories with
* breadcrumbs.
*/
export
class FileBrowserWidget extends Widget {
/**
* Construct a new file browser.
*
* @param model - The file browser view model.
*/
constructor(model: FileBrowserModel) {
super();
this.addClass(FILE_BROWSER_CLASS);
this._model = model;
this._model.refreshed.connect(this._handleRefresh, this)
this._crumbs = new BreadCrumbs(model);
this._buttons = new FileButtons(model);
this._listing = new DirListing(model);
this._crumbs.addClass(CRUMBS_CLASS);
this._buttons.addClass(BUTTON_CLASS);
this._listing.addClass(LISTING_CLASS);
let layout = new PanelLayout();
layout.addChild(this._crumbs);
layout.addChild(this._buttons);
layout.addChild(this._listing);
this.layout = layout;
}
/**
* Dispose of the resources held by the file browser.
*/
dispose() {
this._model = null;
this._crumbs = null;
this._buttons = null;
this._listing = null;
super.dispose();
}
/**
* Get the model used by the file browser.
*
* #### Notes
* This is a read-only property.
*/
get model(): FileBrowserModel {
return this._model;
}
/**
* Get the widget factory for the widget.
*/
get widgetFactory(): (model: IContentsModel) => Widget {
return this._listing.widgetFactory;
}
/**
* Set the widget factory for the widget.
*/
set widgetFactory(factory: (model: IContentsModel) => Widget) {
this._listing.widgetFactory = factory;
}
/**
* Change directory.
*/
cd(path: string): Promise<void> {
return this._model.cd(path);
}
/**
* Open the currently selected item(s).
*
* Changes to the first directory encountered.
* Emits [[openRequested]] signals for files.
*/
open(): void {
let foundDir = false;
let items = this._model.sortedItems;
for (let item of items) {
if (!this._model.isSelected(item.name)) {
continue;
}
if (item.type === 'directory' && !foundDir) {
foundDir = true;
this._model.open(item.name).catch(error =>
showErrorMessage(this, 'Open directory', error)
);
} else {
this.model.open(item.name);
}
}
}
/**
* Create a new untitled file or directory in the current directory.
*/
newUntitled(type: string, ext?: string): Promise<IContentsModel> {
return this.model.newUntitled(type, ext);
}
/**
* Rename the first currently selected item.
*/
rename(): Promise<string> {
return this._listing.rename();
}
/**
* Cut the selected items.
*/
cut(): void {
this._listing.cut();
}
/**
* Copy the selected items.
*/
copy(): void {
this._listing.copy();
}
/**
* Paste the items from the clipboard.
*/
paste(): Promise<void> {
return this._listing.paste();
}
/**
* Delete the currently selected item(s).
*/
delete(): Promise<void> {
return this._listing.delete();
}
/**
* Duplicate the currently selected item(s).
*/
duplicate(): Promise<void> {
return this._listing.duplicate();
}
/**
* Download the currently selected item(s).
*/
download(): Promise<void> {
return this._listing.download();
}
/**
* Shut down kernels on the applicable currently selected items.
*/
shutdownKernels(): Promise<void> {
return this._listing.shutdownKernels();
}
/**
* Refresh the current directory.
*/
refresh(): Promise<void> {
return this._model.refresh().catch(
error => showErrorMessage(this, 'Refresh Error', error)
);
}
/**
* Select next item.
*/
selectNext(): void {
this._listing.selectNext();
}
/**
* Select previous item.
*/
selectPrevious(): void {
this._listing.selectPrevious();
}
/**
* A message handler invoked on an `'after-attach'` message.
*/
protected onAfterAttach(msg: Message): void {
super.onAfterAttach(msg);
this.refresh();
}
/**
* A message handler invoked on an `'after-show'` message.
*/
protected onAfterShow(msg: Message): void {
super.onAfterShow(msg);
this.refresh();
}
/**
* Handle a model refresh.
*/
private _handleRefresh(): void {
clearTimeout(this._timeoutId);
this._timeoutId = setTimeout(() => this.refresh(), REFRESH_DURATION);
}
private _model: FileBrowserModel = null;
private _crumbs: BreadCrumbs = null;
private _buttons: FileButtons = null;
private _listing: DirListing = null;
private _timeoutId = -1;
}
|
Java
|
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace ZendTest\Mvc\Controller\Plugin\TestAsset;
use Zend\Authentication\Adapter\AdapterInterface;
use Zend\Authentication\Result;
class AuthenticationAdapter implements AdapterInterface
{
protected $identity;
public function setIdentity($identity)
{
$this->identity = $identity;
}
public function authenticate()
{
return new Result(Result::SUCCESS, $this->identity);
}
}
|
Java
|
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "solicitud_prestamo".
*
* @property integer $SPRE_ID
* @property string $PE_RUT
* @property string $SPRE_DESCRIPCION
* @property string $SPRE_FECHA
* @property string $SPRE_ESTADO
* @property string $SPRE_TEXTO
*
* @property Persona $pERUT
* @property SpreHeSolicita[] $spreHeSolicitas
*/
class SolicitudPrestamo extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'solicitud_prestamo';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['PE_RUT'], 'required'],
[['SPRE_FECHA'], 'safe'],
[['SPRE_DESCRIPCION'], 'string'],
[['PE_RUT'], 'string', 'max' => 12],
[['SPRE_TITULO'], 'string', 'max' => 50],
[['SPRE_ESTADO'], 'string', 'max' => 20]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'SPRE_ID' => 'ID',
'PE_RUT' => 'Persona',
'SPRE_TITULO' => 'Título',
'SPRE_FECHA' => 'Fecha',
'SPRE_ESTADO' => 'Estado',
'SPRE_DESCRIPCION' => 'Descripción',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getPERUT()
{
return $this->hasOne(Persona::className(), ['PE_RUT' => 'PE_RUT']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getSpreHeSolicitas()
{
return $this->hasMany(SpreHeSolicita::className(), ['SPRE_ID' => 'SPRE_ID']);
}
}
|
Java
|
% File: api.pl
% Purpose: prolog api for elf application
% Author: Roger Evans
% Version: 1.0
% Date: 21/12/2013
%
% (c) Copyright 2013, University of Brighton
% application api from prolog
nimrodel(Model, Title, String) :-
nimrodel(['-model', Model, '-title', Title, String]).
nimrodel(Model, String) :-
nimrodel(['-model', Model, String]).
nimrodel(X) :- atom(X), !,
nimrodel([X]).
nimrodel(X) :-
datr_query('nimrodel.MAIN', [arglist | X], _V).
nimrodel_query(Index, Path) :-
datr_theorem('nimrodel.STRING-QUERY', [Index | Path]).
|
Java
|
@(message: String,books : List[models.Book], conditions : List[models.Condition],
requests : List[models.CurrentRequest], bookSelected : Long , price : String ,conditionSelected : Long )
@implicitFieldConstructor = @{ helper.FieldConstructor(twitterBootstrapInput.render) }
@main("My Requests") {
<div class="container">
<div class="row main-features">
<br>
<div class="span7">
<div class="well">
<h3>Create a Book Request</h3>
@helper.form(action = routes.CurrentRequest.newRequest()) {
<div class="span2">
<span class="label label-inverse">Book </span>
</div>
<div class="span4">
<select name="bookKey" name="bookKey" >
@for(book <- books) {
<option value=@book.getPrimaryKey()
@if(bookSelected == book.getPrimaryKey()){selected}>@book.getTitle()</option>
}
</select>
</div>
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>
<span class="label label-info">Version </span>
</th>
<th>
<span class="label label-info">ISBN </span>
</th>
<th>
<span class="label label-info">Bookstore Price </span>
</th>
<th>
<span class="label label-info">Cover </span>
</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
@for(book <- books) {
@if(bookSelected == book.getPrimaryKey()){
<td>
<label>
<b>@book.getEdition()</b>
</label>
</td>
<td>
<label>
<b>@book.getIsbn()</b>
</label>
</td>
<td>
<label>
<b>@book.getBookStorePrice()</b>
</label>
</td>
<td>
<img src="http://covers.openlibrary.org/b/isbn/@book.getIsbn()-S.jpg">
</td>
}}
</tr>
</tbody>
</table>
<div class="span2">
<span class="label label-inverse">Condition</span>
</div>
<div class="span4">
<select name="conditionKey">
@for(condition <- conditions) {
<option @if(conditionSelected == condition.getPrimaryKey()){ selected }
value=@condition.getPrimaryKey()>@condition.getName()</option>
}
</select>
</div>
<div class="span2">
<span class="label label-inverse">Price</span>
</div>
<div class="span3">
<input name="price" type="text" value="@price" class="input-medium"> <br>
<br>
</div>
<br>
<br>
<div class="span5">
<input type="submit" class="btn btn-primary btn-large btn-block" id="newRequest" value="Create New Request" />
</div>
}
<br>
<br>
<br>
<br>
<br>
<br>
<br>
</div>
</div>
<div class="span7">
<p>
@message
</p>
</div>
<div class="span7">
<table class="table table-condensed table-striped">
<thead>
<tr>
<th>
<span class="label label-info">Book </span>
</th>
<th>
<span class="label label-info">Condition </span>
</th>
<th>
<span class="label label-info">Request Price </span>
</th>
<th></th>
</tr>
</thead>
<tbody>
@for(request <- requests) {
<tr>
<td>
@request.getBook().getTitle()
</td>
<td>
@request.getCondition().getName()
</td>
<td>
<input type="text" value=@request.getPrice() class="input-medium">
</td>
<td>
<div class="btn-group">
<a class="btn btn-small btn-primary">Update</a>
</div>
</td>
</tr>
}
</tbody>
</table>
@if(requests.size() ==0){ No Current Requests}
</div>
</div>
</div>
}
|
Java
|
---
title: "8차 천일 결사 1차 백일 기도 정진 56일째"
date: 2014-05-18 08:01:52
tags:
- 8000th
- 8-100th
- 56th
---
#수행일지
남에 마음에 노력하기 위한 저 자신을 봅니다. 어릴때 부모님 특히 엄마를 볼 수 있는 시간이 부족해서 전 사랑고파병이 있습니다. 그래서 누구든지 그 사람의 마음에 들기 위해서 무의식적으로 노력하고 있는 저를 봅니다. 이것을 알아차리니 이제 남의 마음에 들지 않기 위해서 노력하고 있는 저를 봅니다. 저는 양 극단을 헤메이고 있습니다. 부처님이 말씀하신 마음에 들기 위해서 노력할것도 마음에 들지 않기 위해서 노력하지도 않는 중도의 길을 가는것이 바른길임을 알고 바른 방향으로 수행 정진해 나가야 하겠습니다. 오늘도 모든 만물에 평화와 안녕이 깃들기를 기원합니다. 감사합니다.
|
Java
|
<?php
namespace app\models;
use app\models\query\ActionQuery;
use app\models\query\CommentQuery;
use Yii;
use yii\db\ActiveRecord;
/**
* This is the model class for table "comment".
*
* @property integer $id
* @property integer $action_id
* @property string $content
*
* @property Action $action
*/
class Comment extends ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'comment';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['action_id', 'content'], 'required'],
[['action_id'], 'integer'],
[['content'], 'string', 'max' => 255],
[['action_id'], 'exist', 'skipOnError' => true, 'targetClass' => Action::className(), 'targetAttribute' => ['action_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => Yii::t('app', 'ID'),
'action_id' => Yii::t('app', 'Action ID'),
'content' => Yii::t('app', 'Content'),
];
}
/**
* @return ActionQuery
*/
public function getAction()
{
return $this->hasOne(Action::className(), ['id' => 'action_id'])->inverseOf('comments');
}
/**
* @inheritdoc
* @return CommentQuery the active query used by this AR class.
*/
public static function find()
{
return new CommentQuery(get_called_class());
}
}
|
Java
|
<!DOCTYPE html>
<html lang='en'>
<head>
<title>Ligs and Pseudo Test</title>
<link href="b.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<p data-a="hello ">Hello world how are you today?</p>
<p>This is a test of the use of ligatures to encode icons in a fun and cool way. Now you can insert graphics just through very simple text edditing, kind of like having emoticons!</p>
<p>Sadly ligs aren't supported in IE before version 10!</p>
<p>We will also test the <span aria-hidden="true" data-icon="heroku"> </span> for the CSS :before and :after pseudo elements</p>
</body>
</html>
|
Java
|
// 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/net/sdch_dictionary_fetcher.h"
#include "base/bind.h"
#include "base/compiler_specific.h"
#include "base/message_loop.h"
#include "chrome/browser/profiles/profile.h"
#include "content/public/common/url_fetcher.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"
SdchDictionaryFetcher::SdchDictionaryFetcher(
net::URLRequestContextGetter* context)
: ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)),
task_is_pending_(false),
context_(context) {
DCHECK(CalledOnValidThread());
}
SdchDictionaryFetcher::~SdchDictionaryFetcher() {
DCHECK(CalledOnValidThread());
}
// static
void SdchDictionaryFetcher::Shutdown() {
net::SdchManager::Shutdown();
}
void SdchDictionaryFetcher::Schedule(const GURL& dictionary_url) {
DCHECK(CalledOnValidThread());
// Avoid pushing duplicate copy onto queue. We may fetch this url again later
// and get a different dictionary, but there is no reason to have it in the
// queue twice at one time.
if (!fetch_queue_.empty() && fetch_queue_.back() == dictionary_url) {
net::SdchManager::SdchErrorRecovery(
net::SdchManager::DICTIONARY_ALREADY_SCHEDULED_TO_DOWNLOAD);
return;
}
if (attempted_load_.find(dictionary_url) != attempted_load_.end()) {
net::SdchManager::SdchErrorRecovery(
net::SdchManager::DICTIONARY_ALREADY_TRIED_TO_DOWNLOAD);
return;
}
attempted_load_.insert(dictionary_url);
fetch_queue_.push(dictionary_url);
ScheduleDelayedRun();
}
void SdchDictionaryFetcher::ScheduleDelayedRun() {
if (fetch_queue_.empty() || current_fetch_.get() || task_is_pending_)
return;
MessageLoop::current()->PostDelayedTask(FROM_HERE,
base::Bind(&SdchDictionaryFetcher::StartFetching,
weak_factory_.GetWeakPtr()),
base::TimeDelta::FromMilliseconds(kMsDelayFromRequestTillDownload));
task_is_pending_ = true;
}
void SdchDictionaryFetcher::StartFetching() {
DCHECK(task_is_pending_);
task_is_pending_ = false;
DCHECK(context_.get());
current_fetch_.reset(content::URLFetcher::Create(
fetch_queue_.front(), content::URLFetcher::GET, this));
fetch_queue_.pop();
current_fetch_->SetRequestContext(context_.get());
current_fetch_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
net::LOAD_DO_NOT_SAVE_COOKIES);
current_fetch_->Start();
}
void SdchDictionaryFetcher::OnURLFetchComplete(
const net::URLFetcher* source) {
if ((200 == source->GetResponseCode()) &&
(source->GetStatus().status() == net::URLRequestStatus::SUCCESS)) {
std::string data;
source->GetResponseAsString(&data);
net::SdchManager::Global()->AddSdchDictionary(data, source->GetURL());
}
current_fetch_.reset(NULL);
ScheduleDelayedRun();
}
|
Java
|
<?php
use yii\helpers\Html;
use mdm\admin\models\Assignment;
use backend\models\UserBackend;
use yii\base\Object;
$user = new UserBackend();
$list = UserBackend::find()->where([])->asArray()->all();
//print_r($list);
//echo "<br>";
$euserId = "";
for($i=0;$i<count($list);$i++){
$tmpId = $list[$i]["id"];
$assign = new Assignment($tmpId);
$test = $assign->getItems();
//print_r($test);
//echo "<br>";
if(array_key_exists("企业管理员",$test["assigned"])){
$euserId = $tmpId;
break;
}
}
//echo "userId=".$euserId;
/* @var $this \yii\web\View */
/* @var $content string */
if (Yii::$app->controller->action->id === 'login') {
/**
* Do not use this code in your template. Remove it.
* Instead, use the code $this->layout = '//main-login'; in your controller.
*/
echo $this->render(
'main-login',
['content' => $content]
);
} else {
if (class_exists('backend\assets\AppAsset')) {
backend\assets\AppAsset::register($this);
} else {
app\assets\AppAsset::register($this);
}
dmstr\web\AdminLteAsset::register($this);
$directoryAsset = Yii::$app->assetManager->getPublishedUrl('@vendor/almasaeed2010/adminlte/dist');
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<?= Html::csrfMetaTags() ?>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body class="hold-transition <?= \dmstr\helpers\AdminLteHelper::skinClass() ?> sidebar-mini">
<?php $this->beginBody() ?>
<div class="wrapper">
<?= $this->render(
'header.php',
['directoryAsset' => $directoryAsset,'euserId'=>$euserId]
) ?>
<?= $this->render(
'left.php',
['directoryAsset' => $directoryAsset,'euserId'=>$euserId]
)
?>
<?= $this->render(
'content.php',
['content' => $content, 'directoryAsset' => $directoryAsset]
) ?>
</div>
<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
<?php } ?>
|
Java
|
C Copyright (c) 2007-2017 National Technology & Engineering Solutions of
C Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with
C NTESS, the U.S. Government retains certain rights in this software.
C
C Redistribution and use in source and binary forms, with or without
C modification, are permitted provided that the following conditions are
C met:
C
C * Redistributions of source code must retain the above copyright
C notice, this list of conditions and the following disclaimer.
C
C * Redistributions in binary form must reproduce the above
C copyright notice, this list of conditions and the following
C disclaimer in the documentation and/or other materials provided
C with the distribution.
C
C * Neither the name of NTESS nor the names of its
C contributors may be used to endorse or promote products derived
C from this software without specific prior written permission.
C
C THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
C "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
C LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
C A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
C OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
C SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
C LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
C DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
C THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
C (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
C OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
C
C========================================================================
*DECK, SETON0
SUBROUTINE SETON0(ICONA,NELTN,SOLEA,SOLENA,IDBLK,XA,YA,ZA,ISTP,
& ITT,iblk)
C
C *********************************************************************
C
C Subroutine SETON0 extracts nodal values of shell element variables by
C looping over each element and summing the value of the variable
C in that element to each node in the connectivity list for that
C element. Then the nodal summation of element variables is divided
C by the number of elements that contributed to that node (resulting
C in a nodal average of the element value.) This is done for the old
C mesh elements and nodes to facilitate interpolation.
C
C Each element block must be processed independently in order to
C avoid averaging element variables across material boundaries.
C Note: the last set of DO loops acts over all nodes; to make sense
C one element block must be completely processed before another
C element block is sent into this subroutine.
C
C Calls subroutine VOL
C
c Called by MAPVAR
C
C *********************************************************************
C
C ICONA mesh-A connectivity (1:nelnda,1:numeba)
C NELTN number of elements tied to each node (1:nodesa)
C SOLEA element variables (1:numeba,1:nvarel)
C SOLENA element variables at nodes (1:nodesa,1:nvarel)
C IDBLK current element block I.D.
C XA,YA,ZA coordinates
C XX,YY,ZZ vector of coordinates of nodes for an element
C ISTP current time step
C ITT truth table
C iblk element block being processed (not ID)
C
C *********************************************************************
C
include 'aexds1.blk'
include 'aexds2.blk'
include 'amesh.blk'
include 'ebbyeb.blk'
include 'ex2tp.blk'
include 'tapes.blk'
C
DIMENSION ICONA(NELNDA,*), NELTN(*)
DIMENSION SOLEA(NUMEBA,*), SOLENA(NODESA,NVAREL), ITT(NVAREL,*)
DIMENSION XA(*), YA(*), ZA(*), XX(27), YY(27), ZZ(27)
C
C *********************************************************************
C
NNODES = 4
DO 10 I = 1, NODESA
NELTN(I) = 0
DO 10 J = 1, NVAREL
SOLENA(I,J) = 0.
10 CONTINUE
C
DO 20 NEL = 1, NUMEBA
DO 30 I = 1, NNODES
C
C number of elements associated with each node - used for
C computing an average later on
C
NELTN(ICONA(I,NEL)) = NELTN(ICONA(I,NEL)) + 1
30 CONTINUE
20 CONTINUE
C
DO 40 IVAR = 1, NVAREL
IF (ITT(IVAR,iblk) .EQ. 0)GO TO 40
CALL EXGEV(NTP2EX,ISTP,IVAR,IDBLK,NUMEBA,SOLEA(1,IVAR),IERR)
C
IF (NAMVAR(nvargp+IVAR)(1:6) .EQ. 'ELMASS') THEN
C
C replace element mass with nodal density for interpolation
C
DO 50 IEL = 1, NUMEBA
DO 60 I = 1, NNODES
XX(I) = XA(ICONA(I,IEL))
YY(I) = YA(ICONA(I,IEL))
ZZ(I) = ZA(ICONA(I,IEL))
60 CONTINUE
CALL VOL(ITYPE,XX,YY,ZZ,VOLUME)
SOLEA(IEL,IVAR) = SOLEA(IEL,IVAR) / VOLUME
50 CONTINUE
END IF
C
C accumulate element variables to nodes
C
DO 70 NEL = 1, NUMEBA
DO 80 I = 1, NNODES
SOLENA(ICONA(I,NEL),IVAR) =
& SOLENA(ICONA(I,NEL),IVAR) + SOLEA(NEL,IVAR)
80 CONTINUE
70 CONTINUE
C
C divide by number of elements contributing to each node (average)
C
DO 90 I = 1, NODESA
IF(NELTN(I) .NE. 0)THEN
SOLENA(I,IVAR) = SOLENA(I,IVAR) / float(NELTN(I))
END IF
90 CONTINUE
40 CONTINUE
RETURN
END
|
Java
|
<!--
Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file
for details. All rights reserved. Use of this source code is governed by a
BSD-style license that can be found in the LICENSE file.
-->
<div *ngIf="pending"
class="btn spinner">
<material-spinner></material-spinner>
</div>
<material-button #yesButton
*ngIf="!pending && yesDisplayed"
class="btn btn-yes"
[autoFocus]="yesAutoFocus"
[raised]="yesRaised || raised"
[class.highlighted]="yesHighlighted"
[disabled]="yesDisabled || disabled"
[attr.aria-label]="yesAriaLabel"
[attr.aria-describedby]="yesAriaDescribedBy"
(trigger)="onYes($event)">
{{yesText}}
</material-button>
<material-button #noButton
*ngIf="!pending && noDisplayed"
class="btn btn-no"
[autoFocus]="noAutoFocus"
[raised]="raised"
[disabled]="noDisabled || disabled"
[attr.aria-label]="noAriaLabel"
[attr.aria-describedby]="noAriaDescribedBy"
(trigger)="onNo($event)">
{{noText}}
</material-button>
|
Java
|
package de.uni.freiburg.iig.telematik.wolfgang.properties.check;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import de.invation.code.toval.graphic.component.DisplayFrame;
import de.invation.code.toval.graphic.util.SpringUtilities;
import de.uni.freiburg.iig.telematik.sepia.petrinet.cpn.properties.cwn.CWNProperties;
import de.uni.freiburg.iig.telematik.sepia.petrinet.properties.PropertyCheckingResult;
import javax.swing.SpringLayout;
public class CWNPropertyCheckView extends AbstractPropertyCheckView<CWNProperties> {
private static final long serialVersionUID = -950169446391727139L;
private PropertyCheckResultLabel lblStructure;
private PropertyCheckResultLabel lblInOutPlaces;
private PropertyCheckResultLabel lblConnectedness;
private PropertyCheckResultLabel lblValidMarking;
private PropertyCheckResultLabel lblCFDependency;
private PropertyCheckResultLabel lblNoDeadTransitions;
private PropertyCheckResultLabel lblCompletion;
private PropertyCheckResultLabel lblOptionComplete;
private PropertyCheckResultLabel lblBounded;
@Override
protected String getHeadline() {
return "Colored WF Net Check";
}
@Override
protected void addSpecificFields(JPanel pnl) {
lblStructure = new PropertyCheckResultLabel("\u2022 CWN Structure", PropertyCheckingResult.UNKNOWN);
pnl.add(lblStructure);
JPanel pnlStructureSub = new JPanel(new SpringLayout());
pnl.add(pnlStructureSub);
lblInOutPlaces = new PropertyCheckResultLabel("\u2022 Valid InOut Places", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblInOutPlaces);
lblConnectedness = new PropertyCheckResultLabel("\u2022 Strong Connectedness", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblConnectedness);
lblValidMarking = new PropertyCheckResultLabel("\u2022 Valid Initial Marking", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblValidMarking);
lblCFDependency = new PropertyCheckResultLabel("\u2022 Control Flow Dependency", PropertyCheckingResult.UNKNOWN);
pnlStructureSub.add(lblCFDependency);
SpringUtilities.makeCompactGrid(pnlStructureSub, pnlStructureSub.getComponentCount(), 1, 15, 0, 0, 0);
pnl.add(new JPopupMenu.Separator());
lblBounded = new PropertyCheckResultLabel("\u2022 Is Bounded", PropertyCheckingResult.UNKNOWN);
pnl.add(lblBounded);
pnl.add(new JPopupMenu.Separator());
lblOptionComplete = new PropertyCheckResultLabel("\u2022 Option To Complete", PropertyCheckingResult.UNKNOWN);
pnl.add(lblOptionComplete);
pnl.add(new JPopupMenu.Separator());
lblCompletion = new PropertyCheckResultLabel("\u2022 Proper Completion", PropertyCheckingResult.UNKNOWN);
pnl.add(lblCompletion);
pnl.add(new JPopupMenu.Separator());
lblNoDeadTransitions = new PropertyCheckResultLabel("\u2022 No Dead Transitions", PropertyCheckingResult.UNKNOWN);
pnl.add(lblNoDeadTransitions);
}
@Override
public void resetFieldContent() {
super.updateFieldContent(null, null);
lblStructure.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblInOutPlaces.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblConnectedness.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblValidMarking.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblCFDependency.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblBounded.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblOptionComplete.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblCompletion.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
lblNoDeadTransitions.updatePropertyCheckingResult(PropertyCheckingResult.UNKNOWN);
}
@Override
public void updateFieldContent(CWNProperties checkResult, Exception exception) {
super.updateFieldContent(checkResult, exception);
lblStructure.updatePropertyCheckingResult(checkResult.hasCWNStructure);
lblInOutPlaces.updatePropertyCheckingResult(checkResult.validInOutPlaces);
lblConnectedness.updatePropertyCheckingResult(checkResult.strongConnectedness);
lblValidMarking.updatePropertyCheckingResult(checkResult.validInitialMarking);
lblCFDependency.updatePropertyCheckingResult(checkResult.controlFlowDependency);
lblBounded.updatePropertyCheckingResult(checkResult.isBounded);
lblOptionComplete.updatePropertyCheckingResult(checkResult.optionToCompleteAndProperCompletion);
lblCompletion.updatePropertyCheckingResult(checkResult.optionToCompleteAndProperCompletion);
lblNoDeadTransitions.updatePropertyCheckingResult(checkResult.noDeadTransitions);
}
public static void main(String[] args) {
CWNPropertyCheckView view = new CWNPropertyCheckView();
view.setUpGui();
view.updateFieldContent(new CWNProperties(), null);
new DisplayFrame(view, true);
}
}
|
Java
|
/*
* Zorbage: an algebraic data hierarchy for use in numeric processing.
*
* Copyright (c) 2016-2021 Barry DeZonia 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 <copyright holder> 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 <COPYRIGHT HOLDER> 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 nom.bdezonia.zorbage.algorithm;
import java.math.BigDecimal;
import java.math.MathContext;
import nom.bdezonia.zorbage.algebra.Addition;
import nom.bdezonia.zorbage.algebra.Algebra;
import nom.bdezonia.zorbage.algebra.Conjugate;
import nom.bdezonia.zorbage.algebra.Invertible;
import nom.bdezonia.zorbage.algebra.Multiplication;
import nom.bdezonia.zorbage.algebra.RealConstants;
import nom.bdezonia.zorbage.algebra.SetComplex;
import nom.bdezonia.zorbage.algebra.Trigonometric;
import nom.bdezonia.zorbage.algebra.Unity;
import nom.bdezonia.zorbage.datasource.IndexedDataSource;
/**
*
* @author Barry DeZonia
*
*/
public class InvFFT {
// do not instantiate
private InvFFT() {}
/**
*
* @param <T>
* @param <U>
* @param <V>
* @param <W>
* @param cmplxAlg
* @param realAlg
* @param a
* @param b
*/
public static
<T extends Algebra<T,U> & Addition<U> & Multiplication<U> & Conjugate<U>,
U extends SetComplex<W>,
V extends Algebra<V,W> & Trigonometric<W> & RealConstants<W> & Unity<W> &
Multiplication<W> & Addition<W> & Invertible<W>,
W>
void compute(T cmplxAlg, V realAlg, IndexedDataSource<U> a,IndexedDataSource<U> b)
{
long aSize = a.size();
long bSize = b.size();
if (aSize != FFT.enclosingPowerOf2(aSize))
throw new IllegalArgumentException("input size is not a power of 2");
if (aSize != bSize)
throw new IllegalArgumentException("output size does not match input size");
U one_over_n = cmplxAlg.construct((BigDecimal.ONE.divide(BigDecimal.valueOf(aSize), new MathContext(100))).toString());
nom.bdezonia.zorbage.algorithm.Conjugate.compute(cmplxAlg, a, b);
FFT.compute(cmplxAlg, realAlg, b, b);
nom.bdezonia.zorbage.algorithm.Conjugate.compute(cmplxAlg, b, b);
Scale.compute(cmplxAlg, one_over_n, b, b);
}
}
|
Java
|
import matplotlib.pyplot as plt
import numpy as np
import scalpplot
from scalpplot import plot_scalp
from positions import POS_10_5
from scipy import signal
def plot_timeseries(frames, time=None, offset=None, color='k', linestyle='-'):
frames = np.asarray(frames)
if offset == None:
offset = np.max(np.std(frames, axis=0)) * 3
if time == None:
time = np.arange(frames.shape[0])
plt.plot(time, frames - np.mean(frames, axis=0) +
np.arange(frames.shape[1]) * offset, color=color, ls=linestyle)
def plot_scalpgrid(scalps, sensors, locs=POS_10_5, width=None,
clim=None, cmap=None, titles=None):
'''
Plots a grid with scalpplots. Scalps contains the different scalps in the
rows, sensors contains the names for the columns of scalps, locs is a dict
that maps the sensor-names to locations.
Width determines the width of the grid that contains the plots. Cmap selects
a colormap, for example plt.cm.RdBu_r is very useful for AUC-ROC plots.
Clim is a list containing the minimim and maximum value mapped to a color.
Titles is an optional list with titles for each subplot.
Returns a list with subplots for further manipulation.
'''
scalps = np.asarray(scalps)
assert scalps.ndim == 2
nscalps = scalps.shape[0]
subplots = []
if not width:
width = int(min(8, np.ceil(np.sqrt(nscalps))))
height = int(np.ceil(nscalps/float(width)))
if not clim:
clim = [np.min(scalps), np.max(scalps)]
plt.clf()
for i in range(nscalps):
subplots.append(plt.subplot(height, width, i + 1))
plot_scalp(scalps[i], sensors, locs, clim=clim, cmap=cmap)
if titles:
plt.title(titles[i])
# plot colorbar next to last scalp
bb = plt.gca().get_position()
plt.colorbar(cax=plt.axes([bb.xmax + bb.width/10, bb.ymin, bb.width/10,
bb.height]), ticks=np.linspace(clim[0], clim[1], 5).round(2))
return subplots
|
Java
|
package main
import (
"encoding/json"
"fmt"
"log"
"time"
"github.com/boltdb/bolt"
)
type Entry struct {
Id string `json:"id"`
Url string `json:"url"`
Subreddit string `json:"subreddit"`
}
//InitDB initializes the BoltDB instance and loads in the database file.
func InitDB() {
var err error
db, err = bolt.Open("data.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
CheckErr(err, "InitDB() - Open Database", true)
err = db.Update(func(tx *bolt.Tx) error {
var err error
_, err = tx.CreateBucketIfNotExists([]byte("to_handle"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
_, err = tx.CreateBucketIfNotExists([]byte("handled"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
_, err = tx.CreateBucketIfNotExists([]byte("credentials"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
return nil
})
CheckErr(err, "InitDB() - Create Buckets", true)
}
//CloseDB closes the BoltDB database safely during the shutdown cleanup.
func CloseDB() {
fmt.Print("Closing database...")
db.Close()
fmt.Println("Done!")
fmt.Println("Goodbye! <3")
}
//ReadCreds reads the credential bucket from BotlDB.
func ReadCreds() {
var user, pass []byte
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("credentials"))
u := b.Get([]byte("user"))
p := b.Get([]byte("pass"))
if u != nil && p != nil {
user = make([]byte, len(u))
pass = make([]byte, len(p))
copy(user, u)
copy(pass, p)
}
return nil
})
CheckErr(err, "ReadCreds() - Read Database", true)
username = string(user)
password = string(pass)
if username == "" || password == "" {
log.Fatalln("Fatal Error: One or more stored credentials are missing, cannot continue without credentials!")
}
}
//UpdateCreds takes the current credentials and inserts them into
//the BoltDB database.
func UpdateCreds(user, pass string) {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("credentials"))
err := b.Put([]byte("user"), []byte(user))
if err != nil {
return err
}
err = b.Put([]byte("pass"), []byte(pass))
return err
})
CheckErr(err, "UpdateCreds() - Write Database", true)
}
//ClearCreds removes the stores credentials from the database.
func ClearCreds() {
err := db.Update(func(tx *bolt.Tx) error {
err := tx.DeleteBucket([]byte("credentials"))
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists([]byte("credentials"))
return err
})
CheckErr(err, "ClearCreds() - Delete Bucket", true)
}
//ClearDB removes all entires from the BotlDB database.
func ClearDB() {
ClearCreds()
err := db.Update(func(tx *bolt.Tx) error {
err := tx.DeleteBucket([]byte("to_handle"))
if err != nil {
return err
}
err = tx.DeleteBucket([]byte("handled"))
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists([]byte("to_handle"))
if err != nil {
return err
}
_, err = tx.CreateBucketIfNotExists([]byte("handled"))
return err
})
CheckErr(err, "ClearDB() - Delete Bucket", true)
}
//KeyExists checks if a given key exists within the given BoltDB bucket.
func KeyExists(id, bucket string) bool {
exists := false
err := db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
v := b.Get([]byte(id))
exists = v != nil
return nil
})
CheckErr(err, "KeyExists() - Read Database", true)
return exists
}
//HandleLater takes the id (reddit thing_id) of a submission that the
//bot has determined to be offending, and adds it to the bucket of
//posts to be handled in the future.
func HandleLater(entry Entry) {
bytes, err := json.Marshal(entry)
if !CheckErr(err, "HandleLater() - Marshal JSON", false) {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("to_handle"))
err := b.Put([]byte(entry.Id), bytes)
return err
})
CheckErr(err, "HandleLater() - Add ID", true)
}
}
//AddToHandled adds the id (reddit thing_id) to the BoltDB handled bucket.
func AddToHandled(id string) {
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("handled"))
err := b.Put([]byte(id), []byte(""))
return err
})
CheckErr(err, "AddToHandled() - Add 'handled' ID", true)
err = db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("to_handle"))
err := b.Delete([]byte(id))
return err
})
CheckErr(err, "AddToHandled() - Delete 'to_handle' ID", true)
}
func FetchFromQueue() *Entry {
var val []byte
needhandle := false
err := db.Update(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("to_handle"))
c := b.Cursor()
k, v := c.First()
if k != nil {
needhandle = true
val = make([]byte, len(v))
copy(val, v)
}
return nil
})
CheckErr(err, "FetchFromQueue() - Read Database", true)
if needhandle {
log.Printf("Handling one post: %s\n", val)
entry := &Entry{}
json.Unmarshal(val, entry)
return entry
}
return nil
}
//PrintList reads all of the data from the specified BoltDB bucket
//and lists it out to the console.
func PrintList(bucket string) {
db.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte(bucket))
c := b.Cursor()
for k, v := c.First(); k != nil; k, v = c.Next() {
fmt.Printf("key=%s, value=%s\n", k, v)
}
return nil
})
}
|
Java
|
@import url(http://fonts.useso.com/css?family=Raleway:200,500,700,800);
@font-face {
font-family: 'icomoon';
src:url('../fonts/icomoon.eot?yrquyl');
src:url('../fonts/icomoon.eot?#iefixyrquyl') format('embedded-opentype'),
url('../fonts/icomoon.woff?yrquyl') format('woff'),
url('../fonts/icomoon.ttf?yrquyl') format('truetype'),
url('../fonts/icomoon.svg?yrquyl#icomoon') format('svg');
font-weight: normal;
font-style: normal;
}
[class^="icon-"], [class*=" icon-"] {
font-family: 'icomoon';
speak: none;
font-style: normal;
font-weight: normal;
font-variant: normal;
text-transform: none;
line-height: 1;
/* Better Font Rendering =========== */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body, html { font-size: 100%; padding: 0; margin: 0;}
/* Reset */
*,
*:after,
*:before {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
/* Clearfix hack by Nicolas Gallagher: http://nicolasgallagher.com/micro-clearfix-hack/ */
.clearfix:before,
.clearfix:after {
content: " ";
display: table;
}
.clearfix:after {
clear: both;
}
body{
background: #f9f7f6;
color: #404d5b;
font-weight: 500;
font-size: 1.05em;
font-family: "Segoe UI", "Lucida Grande", Helvetica, Arial, "Microsoft YaHei", FreeSans, Arimo, "Droid Sans", "wenquanyi micro hei", "Hiragino Sans GB", "Hiragino Sans GB W3", "FontAwesome", sans-serif;
}
a{color: #2fa0ec;text-decoration: none;outline: none;}
a:hover,a:focus{color:#74777b;};
.htmleaf-container{
margin: 0 auto;
text-align: center;
overflow: hidden;
}
.htmleaf-content {
font-size: 150%;
padding: 3em 0;
}
.htmleaf-content h2 {
margin: 0 0 2em;
opacity: 0.1;
}
.htmleaf-content p {
margin: 1em 0;
padding: 5em 0 0 0;
font-size: 0.65em;
}
.bgcolor-1 { background: #f0efee; }
.bgcolor-2 { background: #f9f9f9; }
.bgcolor-3 { background: #e8e8e8; }/*light grey*/
.bgcolor-4 { background: #2f3238; color: #fff; }/*Dark grey*/
.bgcolor-5 { background: #df6659; color: #521e18; }/*pink1*/
.bgcolor-6 { background: #2fa8ec; }/*sky blue*/
.bgcolor-7 { background: #d0d6d6; }/*White tea*/
.bgcolor-8 { background: #3d4444; color: #fff; }/*Dark grey2*/
.bgcolor-9 { background: #ef3f52; color: #fff;}/*pink2*/
.bgcolor-10{ background: #64448f; color: #fff;}/*Violet*/
.bgcolor-11{ background: #3755ad; color: #fff;}/*dark blue*/
.bgcolor-12{ background: #3498DB; color: #fff;}/*light blue*/
/* Header */
.htmleaf-header{
padding: 3em 190px 4em;
letter-spacing: -1px;
text-align: center;
}
.htmleaf-header h1 {
font-weight: 600;
font-size: 2em;
line-height: 1;
margin-bottom: 0;
/*text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);*/
}
.htmleaf-header h1 span {
font-family: "Segoe UI", "Lucida Grande", Helvetica, Arial, "Microsoft YaHei", FreeSans, Arimo, "Droid Sans", "wenquanyi micro hei", "Hiragino Sans GB", "Hiragino Sans GB W3", "FontAwesome", sans-serif;
display: block;
font-size: 60%;
font-weight: 400;
padding: 0.8em 0 0.5em 0;
color: #c3c8cd;
}
/*nav*/
.htmleaf-demo a{color: #1d7db1;text-decoration: none;}
.htmleaf-demo{width: 100%;padding-bottom: 1.2em;}
.htmleaf-demo a{display: inline-block;margin: 0.5em;padding: 0.6em 1em;border: 3px solid #1d7db1;font-weight: 700;}
.htmleaf-demo a:hover{opacity: 0.6;}
.htmleaf-demo a.current{background:#1d7db1;color: #fff; }
/* Top Navigation Style */
.htmleaf-links {
position: relative;
display: inline-block;
white-space: nowrap;
font-size: 1.5em;
text-align: center;
}
.htmleaf-links::after {
position: absolute;
top: 0;
left: 50%;
margin-left: -1px;
width: 2px;
height: 100%;
background: #dbdbdb;
content: '';
-webkit-transform: rotate3d(0,0,1,22.5deg);
transform: rotate3d(0,0,1,22.5deg);
}
.htmleaf-icon {
display: inline-block;
margin: 0.5em;
padding: 0em 0;
width: 1.5em;
text-decoration: none;
}
.htmleaf-icon span {
display: none;
}
.htmleaf-icon:before {
margin: 0 5px;
text-transform: none;
font-weight: normal;
font-style: normal;
font-variant: normal;
font-family: 'icomoon';
line-height: 1;
speak: none;
-webkit-font-smoothing: antialiased;
}
/* footer */
.htmleaf-footer{width: 100%;padding-top: 10px;}
.htmleaf-small{font-size: 0.8em;}
.center{text-align: center;}
/* icomoon */
.icon-home:before {
content: "\e600";
}
.icon-pacman:before {
content: "\e623";
}
.icon-users2:before {
content: "\e678";
}
.icon-bug:before {
content: "\e699";
}
.icon-eye:before {
content: "\e610";
}
.icon-eye-blocked:before {
content: "\e611";
}
.icon-eye2:before {
content: "\e612";
}
.icon-arrow-up-left3:before {
content: "\e72f";
}
.icon-arrow-up3:before {
content: "\e730";
}
.icon-arrow-up-right3:before {
content: "\e731";
}
.icon-arrow-right3:before {
content: "\e732";
}
.icon-arrow-down-right3:before {
content: "\e733";
}
.icon-arrow-down3:before {
content: "\e734";
}
.icon-arrow-down-left3:before {
content: "\e735";
}
.icon-arrow-left3:before {
content: "\e736";
}
@media screen and (max-width: 50em) {
.htmleaf-header {
padding: 3em 10% 4em;
}
.htmleaf-header h1 {
font-size:2em;
}
}
@media screen and (max-width: 40em) {
.htmleaf-header h1 {
font-size: 1.5em;
}
}
@media screen and (max-width: 30em) {
.htmleaf-header h1 {
font-size:1.2em;
}
}
|
Java
|
package eu.monnetproject.sim.entity;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import eu.monnetproject.util.Logger;
import eu.monnetproject.label.LabelExtractor;
import eu.monnetproject.label.LabelExtractorFactory;
import eu.monnetproject.lang.Language;
import eu.monnetproject.ontology.Entity;
import eu.monnetproject.sim.EntitySimilarityMeasure;
import eu.monnetproject.sim.StringSimilarityMeasure;
import eu.monnetproject.sim.string.Levenshtein;
import eu.monnetproject.sim.token.TokenBagOfWordsCosine;
import eu.monnetproject.sim.util.Functions;
import eu.monnetproject.sim.util.SimilarityUtils;
import eu.monnetproject.tokenizer.FairlyGoodTokenizer;
import eu.monnetproject.translatorimpl.Translator;
import eu.monnetproject.util.Logging;
/**
* Levenshtein similarity.
* Intralingual aggregation: average
* Interlingual aggregation: maximum
*
* @author Dennis Spohr
*
*/
public class MaximumAverageLevenshtein implements EntitySimilarityMeasure {
private Logger log = Logging.getLogger(this);
private final String name = this.getClass().getName();
private LabelExtractorFactory lef;
private LabelExtractor lex = null;
private Collection<Language> languages = Collections.emptySet();
private StringSimilarityMeasure measure;
private boolean includePuns = false;
private Translator translator;
public MaximumAverageLevenshtein(LabelExtractorFactory lef) {
this.lef = lef;
this.measure = new Levenshtein();
this.translator = new Translator();
}
public void configure(Properties properties) {
this.languages = SimilarityUtils.getLanguages(properties.getProperty("languages", ""));
for (Language lang : this.languages) {
log.info("Requested language: "+lang);
}
this.includePuns = SimilarityUtils.getIncludePuns(properties.getProperty("include_puns", "false"));
}
@Override
public double getScore(Entity srcEntity, Entity tgtEntity) {
if (this.lex == null) {
this.lex = this.lef.getExtractor(SimilarityUtils.determineLabelProperties(srcEntity, tgtEntity), true, false);
}
if (this.languages.size() < 1) {
log.warning("No languages specified in config file.");
this.languages = SimilarityUtils.determineLanguages(srcEntity, tgtEntity);
String langs = "";
for (Language lang : languages) {
langs += lang.getName()+", ";
}
try {
log.warning("Using "+langs.substring(0, langs.lastIndexOf(","))+".");
} catch (Exception e) {
log.severe("No languages in source and target ontology.");
}
}
Map<Language, Collection<String>> srcMap = null;
Map<Language, Collection<String>> tgtMap = null;
if (includePuns) {
srcMap = SimilarityUtils.getLabelsIncludingPuns(srcEntity,lex);
tgtMap = SimilarityUtils.getLabelsIncludingPuns(tgtEntity,lex);
} else {
srcMap = SimilarityUtils.getLabelsExcludingPuns(srcEntity,lex);
tgtMap = SimilarityUtils.getLabelsExcludingPuns(tgtEntity,lex);
}
List<Double> intralingualScores = new ArrayList<Double>();
for (Language language : this.languages) {
Collection<String> srcLabels = srcMap.get(language);
Collection<String> tgtLabels = tgtMap.get(language);
if (srcLabels == null) {
if (translator == null) {
log.warning("Can't match in "+language+" because "+srcEntity.getURI()+" has no labels in "+language+" and no translator is available.");
continue;
}
srcLabels = SimilarityUtils.getTranslatedLabels(srcEntity,language,translator,lex);
}
if (tgtLabels == null) {
if (translator == null) {
log.warning("Can't match in "+language+" because "+tgtEntity.getURI()+" has no labels in "+language+" and no translator is available.");
continue;
}
tgtLabels = SimilarityUtils.getTranslatedLabels(tgtEntity,language,translator,lex);
}
double[] scores = new double[srcLabels.size()*tgtLabels.size()];
int index = 0;
for (String srcLabel : srcLabels) {
for (String tgtLabel : tgtLabels) {
scores[index++] = measure.getScore(srcLabel, tgtLabel);
}
}
intralingualScores.add(Functions.mean(scores));
}
if (intralingualScores.size() < 1)
return 0.;
double[] intralingualScoresArray = new double[intralingualScores.size()];
for (int i = 0; i < intralingualScores.size(); i++) {
intralingualScoresArray[i] = intralingualScores.get(i);
}
return Functions.max(intralingualScoresArray);
}
@Override
public String getName() {
return this.name;
}
}
|
Java
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="robots" content="all,follow">
<meta name="googlebot" content="index,follow,snippet,archive">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Universal - All In 1 Template</title>
<meta name="keywords" content="">
<link href='http://fonts.googleapis.com/css?family=Roboto:400,100,100italic,300,300italic,500,700,800' rel='stylesheet' type='text/css'>
<!-- Bootstrap and Font Awesome css -->
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<!-- Css animations -->
<link href="css/animate.css" rel="stylesheet">
<!-- Theme stylesheet, if possible do not edit this stylesheet -->
<link href="css/style.default.css" rel="stylesheet" id="theme-stylesheet">
<!-- Custom stylesheet - for your changes -->
<link href="css/custom.css" rel="stylesheet">
<!-- Responsivity for older IE -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<!-- Favicon and apple touch icons-->
<link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon" />
<link rel="apple-touch-icon" href="img/apple-touch-icon.png" />
<link rel="apple-touch-icon" sizes="57x57" href="img/apple-touch-icon-57x57.png" />
<link rel="apple-touch-icon" sizes="72x72" href="img/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon" sizes="76x76" href="img/apple-touch-icon-76x76.png" />
<link rel="apple-touch-icon" sizes="114x114" href="img/apple-touch-icon-114x114.png" />
<link rel="apple-touch-icon" sizes="120x120" href="img/apple-touch-icon-120x120.png" />
<link rel="apple-touch-icon" sizes="144x144" href="img/apple-touch-icon-144x144.png" />
<link rel="apple-touch-icon" sizes="152x152" href="img/apple-touch-icon-152x152.png" />
<!-- owl carousel css -->
<link href="css/owl.carousel.css" rel="stylesheet">
<link href="css/owl.theme.css" rel="stylesheet">
</head>
<body>
<div id="all">
<header>
<!-- *** TOP ***
_________________________________________________________ -->
<div id="top">
<div class="container">
<div class="row">
<div class="col-xs-5 contact">
<p class="hidden-sm hidden-xs">Contact us on +420 777 555 333 or hello@universal.com.</p>
<p class="hidden-md hidden-lg"><a href="#" data-animate-hover="pulse"><i class="fa fa-phone"></i></a> <a href="#" data-animate-hover="pulse"><i class="fa fa-envelope"></i></a>
</p>
</div>
<div class="col-xs-7">
<div class="social">
<a href="#" class="external facebook" data-animate-hover="pulse"><i class="fa fa-facebook"></i></a>
<a href="#" class="external gplus" data-animate-hover="pulse"><i class="fa fa-google-plus"></i></a>
<a href="#" class="external twitter" data-animate-hover="pulse"><i class="fa fa-twitter"></i></a>
<a href="#" class="email" data-animate-hover="pulse"><i class="fa fa-envelope"></i></a>
</div>
<div class="login">
<a href="#" data-toggle="modal" data-target="#login-modal"><i class="fa fa-sign-in"></i> <span class="hidden-xs text-uppercase">Sign in</span></a>
<a href="customer-register.html"><i class="fa fa-user"></i> <span class="hidden-xs text-uppercase">Sign up</span></a>
</div>
</div>
</div>
</div>
</div>
<!-- *** TOP END *** -->
<!-- *** NAVBAR ***
_________________________________________________________ -->
<div class="navbar-affixed-top" data-spy="affix" data-offset-top="200">
<div class="navbar navbar-default yamm" role="navigation" id="navbar">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand home" href="index.html">
<img src="img/logo.png" alt="Universal logo" class="hidden-xs hidden-sm">
<img src="img/logo-small.png" alt="Universal logo" class="visible-xs visible-sm"><span class="sr-only">Universal - go to homepage</span>
</a>
<div class="navbar-buttons">
<button type="button" class="navbar-toggle btn-template-main" data-toggle="collapse" data-target="#navigation">
<span class="sr-only">Toggle navigation</span>
<i class="fa fa-align-justify"></i>
</button>
</div>
</div>
<!--/.navbar-header -->
<div class="navbar-collapse collapse" id="navigation">
<ul class="nav navbar-nav navbar-right">
<li class="dropdown active">
<a href="javascript: void(0)" class="dropdown-toggle" data-toggle="dropdown">Home <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="index.html">Option 1: Default Page</a>
</li>
<li><a href="index2.html">Option 2: Application</a>
</li>
<li><a href="index3.html">Option 3: Startup</a>
</li>
<li><a href="index4.html">Option 4: Agency</a>
</li>
<li><a href="index5.html">Option 5: Portfolio</a>
</li>
</ul>
</li>
<li class="dropdown use-yamm yamm-fw">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Features<b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<div class="yamm-content">
<div class="row">
<div class="col-sm-6">
<img src="img/template-easy-customize.png" class="img-responsive hidden-xs" alt="">
</div>
<div class="col-sm-3">
<h5>Shortcodes</h5>
<ul>
<li><a href="template-accordions.html">Accordions</a>
</li>
<li><a href="template-alerts.html">Alerts</a>
</li>
<li><a href="template-buttons.html">Buttons</a>
</li>
<li><a href="template-content-boxes.html">Content boxes</a>
</li>
<li><a href="template-blocks.html">Horizontal blocks</a>
</li>
<li><a href="template-pagination.html">Pagination</a>
</li>
<li><a href="template-tabs.html">Tabs</a>
</li>
<li><a href="template-typography.html">Typography</a>
</li>
</ul>
</div>
<div class="col-sm-3">
<h5>Header variations</h5>
<ul>
<li><a href="template-header-default.html">Default sticky header</a>
</li>
<li><a href="template-header-nosticky.html">No sticky header</a>
</li>
<li><a href="template-header-light.html">Light header</a>
</li>
</ul>
</div>
</div>
</div>
</li>
</ul>
</li>
<li class="dropdown use-yamm yamm-fw">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Portfolio <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<div class="yamm-content">
<div class="row">
<div class="col-sm-6">
<img src="img/template-homepage.png" class="img-responsive hidden-xs" alt="">
</div>
<div class="col-sm-3">
<h5>Portfolio</h5>
<ul>
<li><a href="portfolio-2.html">2 columns</a>
</li>
<li><a href="portfolio-no-space-2.html">2 columns with negative space</a>
</li>
<li><a href="portfolio-3.html">3 columns</a>
</li>
<li><a href="portfolio-no-space-3.html">3 columns with negative space</a>
</li>
<li><a href="portfolio-4.html">4 columns</a>
</li>
<li><a href="portfolio-no-space-4.html">4 columns with negative space</a>
</li>
<li><a href="portfolio-detail.html">Portfolio - detail</a>
</li>
<li><a href="portfolio-detail-2.html">Portfolio - detail 2</a>
</li>
</ul>
</div>
<div class="col-sm-3">
<h5>About</h5>
<ul>
<li><a href="about.html">About us</a>
</li>
<li><a href="team.html">Our team</a>
</li>
<li><a href="team-member.html">Team member</a>
</li>
<li><a href="services.html">Services</a>
</li>
</ul>
<h5>Marketing</h5>
<ul>
<li><a href="packages.html">Packages</a>
</li>
</ul>
</div>
</div>
</div>
</li>
</ul>
</li>
<!-- ========== FULL WIDTH MEGAMENU ================== -->
<li class="dropdown use-yamm yamm-fw">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" data-hover="dropdown" data-delay="200">All Pages <b class="caret"></b></a>
<ul class="dropdown-menu">
<li>
<div class="yamm-content">
<div class="row">
<div class="col-sm-3">
<h5>Home</h5>
<ul>
<li><a href="index.html">Option 1: Default Page</a>
</li>
<li><a href="index2.html">Option 2: Application</a>
</li>
<li><a href="index3.html">Option 3: Startup</a>
</li>
<li><a href="index4.html">Option 4: Agency</a>
</li>
<li><a href="index5.html">Option 5: Portfolio</a>
</li>
</ul>
<h5>About</h5>
<ul>
<li><a href="about.html">About us</a>
</li>
<li><a href="team.html">Our team</a>
</li>
<li><a href="team-member.html">Team member</a>
</li>
<li><a href="services.html">Services</a>
</li>
</ul>
<h5>Marketing</h5>
<ul>
<li><a href="packages.html">Packages</a>
</li>
</ul>
</div>
<div class="col-sm-3">
<h5>Portfolio</h5>
<ul>
<li><a href="portfolio-2.html">2 columns</a>
</li>
<li><a href="portfolio-no-space-2.html">2 columns with negative space</a>
</li>
<li><a href="portfolio-3.html">3 columns</a>
</li>
<li><a href="portfolio-no-space-3.html">3 columns with negative space</a>
</li>
<li><a href="portfolio-4.html">4 columns</a>
</li>
<li><a href="portfolio-no-space-4.html">4 columns with negative space</a>
</li>
<li><a href="portfolio-detail.html">Portfolio - detail</a>
</li>
<li><a href="portfolio-detail-2.html">Portfolio - detail 2</a>
</li>
</ul>
<h5>User pages</h5>
<ul>
<li><a href="customer-register.html">Register / login</a>
</li>
<li><a href="customer-orders.html">Orders history</a>
</li>
<li><a href="customer-order.html">Order history detail</a>
</li>
<li><a href="customer-wishlist.html">Wishlist</a>
</li>
<li><a href="customer-account.html">Customer account / change password</a>
</li>
</ul>
</div>
<div class="col-sm-3">
<h5>Shop</h5>
<ul>
<li><a href="shop-category.html">Category - sidebar right</a>
</li>
<li><a href="shop-category-left.html">Category - sidebar left</a>
</li>
<li><a href="shop-category-full.html">Category - full width</a>
</li>
<li><a href="shop-detail.html">Product detail</a>
</li>
</ul>
<h5>Shop - order process</h5>
<ul>
<li><a href="shop-basket.html">Shopping cart</a>
</li>
<li><a href="shop-checkout1.html">Checkout - step 1</a>
</li>
<li><a href="shop-checkout2.html">Checkout - step 2</a>
</li>
<li><a href="shop-checkout3.html">Checkout - step 3</a>
</li>
<li><a href="shop-checkout4.html">Checkout - step 4</a>
</li>
</ul>
</div>
<div class="col-sm-3">
<h5>Contact</h5>
<ul>
<li><a href="contact.html">Contact</a>
</li>
<li><a href="contact2.html">Contact - version 2</a>
</li>
<li><a href="contact3.html">Contact - version 3</a>
</li>
</ul>
<h5>Pages</h5>
<ul>
<li><a href="text.html">Text page</a>
</li>
<li><a href="text-left.html">Text page - left sidebar</a>
</li>
<li><a href="text-full.html">Text page - full width</a>
</li>
<li><a href="faq.html">FAQ</a>
</li>
<li><a href="404.html">404 page</a>
</li>
</ul>
<h5>Blog</h5>
<ul>
<li><a href="blog.html">Blog listing big</a>
</li>
<li><a href="blog-medium.html">Blog listing medium</a>
</li>
<li><a href="blog-small.html">Blog listing small</a>
</li>
<li><a href="blog-post.html">Blog Post</a>
</li>
</ul>
</div>
</div>
</div>
<!-- /.yamm-content -->
</li>
</ul>
</li>
<!-- ========== FULL WIDTH MEGAMENU END ================== -->
<li class="dropdown">
<a href="javascript: void(0)" class="dropdown-toggle" data-toggle="dropdown">Contact <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="contact.html">Contact option 1</a>
</li>
<li><a href="contact2.html">Contact option 2</a>
</li>
<li><a href="contact3.html">Contact option 3</a>
</li>
</ul>
</li>
</ul>
</div>
<!--/.nav-collapse -->
<div class="collapse clearfix" id="search">
<form class="navbar-form" role="search">
<div class="input-group">
<input type="text" class="form-control" placeholder="Search">
<span class="input-group-btn">
<button type="submit" class="btn btn-template-main"><i class="fa fa-search"></i></button>
</span>
</div>
</form>
</div>
<!--/.nav-collapse -->
</div>
</div>
<!-- /#navbar -->
</div>
<!-- *** NAVBAR END *** -->
</header>
<!-- *** LOGIN MODAL ***
_________________________________________________________ -->
<div class="modal fade" id="login-modal" tabindex="-1" role="dialog" aria-labelledby="Login" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="Login">Customer login</h4>
</div>
<div class="modal-body">
<form action="customer-orders.html" method="post">
<div class="form-group">
<input type="text" class="form-control" id="email_modal" placeholder="email">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password_modal" placeholder="password">
</div>
<p class="text-center">
<button class="btn btn-template-main"><i class="fa fa-sign-in"></i> Log in</button>
</p>
</form>
<p class="text-center text-muted">Not registered yet?</p>
<p class="text-center text-muted"><a href="customer-register.html"><strong>Register now</strong></a>! It is easy and done in 1 minute and gives you access to special discounts and much more!</p>
</div>
</div>
</div>
</div>
<!-- *** LOGIN MODAL END *** -->
<div id="heading-breadcrumbs">
<div class="container">
<div class="row">
<div class="col-md-7">
<h1>Portfolio item detail</h1>
</div>
<div class="col-md-5">
<ul class="breadcrumb">
<li><a href="index.html">Home</a>
</li>
<li><a href="portfolio-2.html">Portfolio</a>
</li>
<li>Portfolio item detail</li>
</ul>
</div>
</div>
</div>
</div>
<div id="content">
<div class="container">
<section class="no-mb">
<div class="row">
<div class="col-md-12">
<p class="lead">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean
ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>
</div>
</section>
<section>
<div class="project owl-carousel">
<div class="item">
<img src="img/main-slider1.jpg" alt="" class="img-responsive">
</div>
<div class="item">
<img class="img-responsive" src="img/main-slider2.jpg" alt="">
</div>
<div class="item">
<img class="img-responsive" src="img/main-slider3.jpg" alt="">
</div>
<div class="item">
<img class="img-responsive" src="img/main-slider4.jpg" alt="">
</div>
</div>
<!-- /.project owl-slider -->
</section>
<section>
<div class="row portfolio-project">
<div class="col-md-8">
<div class="heading">
<h3>Project description</h3>
</div>
<p>Bringing unlocked me an striking ye perceive. Mr by wound hours oh happy. Me in resolution pianoforte continuing we. Most my no spot felt by no. He he in forfeited furniture sweetness he arranging. Me tedious so to behaved
written account ferrars moments. Too objection for elsewhere her preferred allowance her. Marianne shutters mr steepest to me. Up mr ignorant produced distance although is sociable blessing. Ham whom call all lain like.</p>
<p>To sorry world an at do spoil along. Incommode he depending do frankness remainder to. Edward day almost active him friend thirty piqued. People as period twenty my extent as. Set was better abroad ham plenty secure had horses.
Admiration has sir decisively excellence say everything inhabiting acceptance. Sooner settle add put you sudden him.</p>
</div>
<div class="col-md-4 project-more">
<div class="heading">
<h3>More</h3>
</div>
<h4>Client</h4>
<p>Pietro Filippi</p>
<h4>Services</h4>
<p>Consulting, Webdesign, Print</p>
<h4>Technologies</h4>
<p>PHP, HipHop, Break-dance</p>
<h4>Dates</h4>
<p>10/2013 - 06/2014</p>
</div>
</div>
</section>
<section>
<div class="row portfolio">
<div class="col-md-12">
<div class="heading">
<h3>Related projects</h3>
</div>
</div>
<div class="col-sm-6 col-md-3">
<div class="box-image">
<div class="image">
<img src="img/portfolio-1.jpg" alt="" class="img-responsive">
</div>
<div class="bg"></div>
<div class="name">
<h3><a href="portfolio-detail.html">Portfolio box-image</a></h3>
</div>
<div class="text">
<p class="buttons">
<a href="portfolio-detail.html" class="btn btn-template-transparent-primary">View</a>
<a href="#" class="btn btn-template-transparent-primary">Website</a>
</p>
</div>
</div>
<!-- /.box-image -->
</div>
<div class="col-sm-6 col-md-3">
<div class="box-image">
<div class="image">
<img src="img/portfolio-2.jpg" alt="" class="img-responsive">
</div>
<div class="bg"></div>
<div class="name">
<h3><a href="portfolio-detail.html">Portfolio box-image</a></h3>
</div>
<div class="text">
<p class="buttons">
<a href="portfolio-detail.html" class="btn btn-template-transparent-primary">View</a>
<a href="#" class="btn btn-template-transparent-primary">Website</a>
</p>
</div>
</div>
<!-- /.box-image -->
</div>
<div class="col-sm-6 col-md-3">
<div class="box-image">
<div class="image">
<img src="img/portfolio-3.jpg" alt="" class="img-responsive">
</div>
<div class="bg"></div>
<div class="name">
<h3><a href="portfolio-detail.html">Portfolio box-image</a></h3>
</div>
<div class="text">
<p class="buttons">
<a href="portfolio-detail.html" class="btn btn-template-transparent-primary">View</a>
<a href="#" class="btn btn-template-transparent-primary">Website</a>
</p>
</div>
</div>
<!-- /.box-image -->
</div>
<div class="col-sm-6 col-md-3">
<div class="box-image">
<div class="image">
<img src="img/portfolio-4.jpg" alt="" class="img-responsive">
</div>
<div class="bg"></div>
<div class="name">
<h3><a href="portfolio-detail.html">Portfolio box-image</a></h3>
</div>
<div class="text">
<p class="buttons">
<a href="portfolio-detail.html" class="btn btn-template-transparent-primary">View</a>
<a href="#" class="btn btn-template-transparent-primary">Website</a>
</p>
</div>
</div>
<!-- /.box-image -->
</div>
</div>
</section>
</div>
<!-- /.container -->
</div>
<!-- /#content -->
<!-- *** GET IT ***
_________________________________________________________ -->
<div id="get-it">
<div class="container">
<div class="col-md-8 col-sm-12">
<h3>Do you want cool website like this one?</h3>
</div>
<div class="col-md-4 col-sm-12">
<a href="#" class="btn btn-template-transparent-primary">Buy this template now</a>
</div>
</div>
</div>
<!-- *** GET IT END *** -->
<!-- *** FOOTER ***
_________________________________________________________ -->
<footer id="footer">
<div class="container">
<div class="col-md-3 col-sm-6">
<h4>About us</h4>
<p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
<hr>
<h4>Join our monthly newsletter</h4>
<form>
<div class="input-group">
<input type="text" class="form-control">
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-send"></i></button>
</span>
</div>
<!-- /input-group -->
</form>
<hr class="hidden-md hidden-lg hidden-sm">
</div>
<!-- /.col-md-3 -->
<div class="col-md-3 col-sm-6">
<h4>Blog</h4>
<div class="blog-entries">
<div class="item same-height-row clearfix">
<div class="image same-height-always">
<a href="#">
<img class="img-responsive" src="img/detailsquare.jpg" alt="">
</a>
</div>
<div class="name same-height-always">
<h5><a href="#">Blog post name</a></h5>
</div>
</div>
<div class="item same-height-row clearfix">
<div class="image same-height-always">
<a href="#">
<img class="img-responsive" src="img/detailsquare.jpg" alt="">
</a>
</div>
<div class="name same-height-always">
<h5><a href="#">Blog post name</a></h5>
</div>
</div>
<div class="item same-height-row clearfix">
<div class="image same-height-always">
<a href="#">
<img class="img-responsive" src="img/detailsquare.jpg" alt="">
</a>
</div>
<div class="name same-height-always">
<h5><a href="#">Very very long blog post name</a></h5>
</div>
</div>
</div>
<hr class="hidden-md hidden-lg">
</div>
<!-- /.col-md-3 -->
<div class="col-md-3 col-sm-6">
<h4>Contact</h4>
<p><strong>Universal Ltd.</strong>
<br>13/25 New Avenue
<br>Newtown upon River
<br>45Y 73J
<br>England
<br>
<strong>Great Britain</strong>
</p>
<a href="contact.html" class="btn btn-small btn-template-main">Go to contact page</a>
<hr class="hidden-md hidden-lg hidden-sm">
</div>
<!-- /.col-md-3 -->
<div class="col-md-3 col-sm-6">
<h4>Photostream</h4>
<div class="photostream">
<div>
<a href="#">
<img src="img/detailsquare.jpg" class="img-responsive" alt="#">
</a>
</div>
<div>
<a href="#">
<img src="img/detailsquare2.jpg" class="img-responsive" alt="#">
</a>
</div>
<div>
<a href="#">
<img src="img/detailsquare3.jpg" class="img-responsive" alt="#">
</a>
</div>
<div>
<a href="#">
<img src="img/detailsquare3.jpg" class="img-responsive" alt="#">
</a>
</div>
<div>
<a href="#">
<img src="img/detailsquare2.jpg" class="img-responsive" alt="#">
</a>
</div>
<div>
<a href="#">
<img src="img/detailsquare.jpg" class="img-responsive" alt="#">
</a>
</div>
</div>
</div>
<!-- /.col-md-3 -->
</div>
<!-- /.container -->
</footer>
<!-- /#footer -->
<!-- *** FOOTER END *** -->
<!-- *** COPYRIGHT ***
_________________________________________________________ -->
<div id="copyright">
<div class="container">
<div class="col-md-12">
<p class="pull-left">© 2015. Your company / name goes here</p>
<p class="pull-right">Template by <a href="http://www.bootstrapious.com">Bootstrap Templates</a> with support from <a href="http://kakusei.cz">Věci do vašeho domova</a>
<!-- Not removing these links is part of the licence conditions of the template. Thanks for understanding :) -->
</p>
</div>
</div>
</div>
<!-- /#copyright -->
<!-- *** COPYRIGHT END *** -->
</div>
<!-- /#all -->
<!-- #### JAVASCRIPT FILES ### -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery-1.11.0.min.js"><\/script>')
</script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script src="js/waypoints.min.js"></script>
<script src="js/jquery.counterup.min.js"></script>
<script src="js/jquery.parallax-1.1.3.js"></script>
<script src="js/front.js"></script>
<!-- owl carousel -->
<script src="js/owl.carousel.min.js"></script>
</body>
</html>
|
Java
|
/*
-- MAGMA (version 1.5.0-beta3) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date July 2014
@generated from zgels_gpu.cpp normal z -> d, Fri Jul 18 17:34:16 2014
*/
#include "common_magma.h"
/**
Purpose
-------
Solves the overdetermined, least squares problem
min || A*X - C ||
using the QR factorization A.
The underdetermined problem (m < n) is not currently handled.
Arguments
---------
@param[in]
trans magma_trans_t
- = MagmaNoTrans: the linear system involves A.
Only TRANS=MagmaNoTrans is currently handled.
@param[in]
m INTEGER
The number of rows of the matrix A. M >= 0.
@param[in]
n INTEGER
The number of columns of the matrix A. M >= N >= 0.
@param[in]
nrhs INTEGER
The number of columns of the matrix C. NRHS >= 0.
@param[in,out]
dA DOUBLE_PRECISION array on the GPU, dimension (LDA,N)
On entry, the M-by-N matrix A.
On exit, A is overwritten by details of its QR
factorization as returned by DGEQRF.
@param[in]
ldda INTEGER
The leading dimension of the array A, LDDA >= M.
@param[in,out]
dB DOUBLE_PRECISION array on the GPU, dimension (LDDB,NRHS)
On entry, the M-by-NRHS matrix C.
On exit, the N-by-NRHS solution matrix X.
@param[in]
lddb INTEGER
The leading dimension of the array dB. LDDB >= M.
@param[out]
hwork (workspace) DOUBLE_PRECISION array, dimension MAX(1,LWORK).
On exit, if INFO = 0, HWORK(1) returns the optimal LWORK.
@param[in]
lwork INTEGER
The dimension of the array HWORK,
LWORK >= (M - N + NB)*(NRHS + NB) + NRHS*NB,
where NB is the blocksize given by magma_get_dgeqrf_nb( M ).
\n
If LWORK = -1, then a workspace query is assumed; the routine
only calculates the optimal size of the HWORK array, returns
this value as the first entry of the HWORK array.
@param[out]
info INTEGER
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value
@ingroup magma_dgels_driver
********************************************************************/
extern "C" magma_int_t
magma_dgels_gpu( magma_trans_t trans, magma_int_t m, magma_int_t n, magma_int_t nrhs,
double *dA, magma_int_t ldda,
double *dB, magma_int_t lddb,
double *hwork, magma_int_t lwork,
magma_int_t *info)
{
double *dT;
double *tau;
magma_int_t k;
magma_int_t nb = magma_get_dgeqrf_nb(m);
magma_int_t lwkopt = (m - n + nb)*(nrhs + nb) + nrhs*nb;
int lquery = (lwork == -1);
hwork[0] = MAGMA_D_MAKE( (double)lwkopt, 0. );
*info = 0;
/* For now, N is the only case working */
if ( trans != MagmaNoTrans )
*info = -1;
else if (m < 0)
*info = -2;
else if (n < 0 || m < n) /* LQ is not handle for now*/
*info = -3;
else if (nrhs < 0)
*info = -4;
else if (ldda < max(1,m))
*info = -6;
else if (lddb < max(1,m))
*info = -8;
else if (lwork < lwkopt && ! lquery)
*info = -10;
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return *info;
}
else if (lquery)
return *info;
k = min(m,n);
if (k == 0) {
hwork[0] = MAGMA_D_ONE;
return *info;
}
/*
* Allocate temporary buffers
*/
int ldtwork = ( 2*k + ((n+31)/32)*32 )*nb;
if (nb < nrhs)
ldtwork = ( 2*k + ((n+31)/32)*32 )*nrhs;
if (MAGMA_SUCCESS != magma_dmalloc( &dT, ldtwork )) {
*info = MAGMA_ERR_DEVICE_ALLOC;
return *info;
}
magma_dmalloc_cpu( &tau, k );
if ( tau == NULL ) {
magma_free( dT );
*info = MAGMA_ERR_HOST_ALLOC;
return *info;
}
magma_dgeqrf_gpu( m, n, dA, ldda, tau, dT, info );
if ( *info == 0 ) {
magma_dgeqrs_gpu( m, n, nrhs,
dA, ldda, tau, dT,
dB, lddb, hwork, lwork, info );
}
magma_free( dT );
magma_free_cpu(tau);
return *info;
}
|
Java
|
<?php
use AudioDidact\GlobalFunctions;
/**
* Returns Pug rendered HTML for the User page, either view or edit
*
* @param $webID string webID of the user's page to be rendered
* @param $edit boolean true if the user is logged in and viewing their own page
* @param null|string $verifyEmail null or string if the user is trying to verify their email address
* @return string HTML of User's page from Pug
*/
function makeUserPage($webID, $edit, $verifyEmail = null){
$dal = GlobalFunctions::getDAL();
$user = $dal->getUserByWebID($webID);
if($user == null){
echo "<script type=\"text/javascript\">alert(\"Invalid User!\");window.location = \"/" . SUBDIR . "\";</script>";
exit();
}
if($edit){
$title = "User Page | $webID | Edit";
}
else{
$title = "User Page | $webID";
}
$emailVerify = 0;
if($verifyEmail != null && !$user->isEmailVerified()){
$result = $user->verifyEmailVerificationCode($verifyEmail);
// If the email verification code is correct, update the user information
if($result){
$user->setEmailVerified(1);
$user->setEmailVerificationCodes([]);
$dal->updateUser($user);
$emailVerify = 1;
}
else{
$emailVerify = 2;
}
}
$userData = ["privateFeed" => $user->isPrivateFeed(), "fName" => $user->getFname(), "lName" => $user->getLname(),
"gender" => $user->getGender(), "webID" => $user->getWebID(), "username" => $user->getUsername(),
"email" => $user->getEmail(), "feedLength" => $user->getFeedLength(), "feedDetails" => $user->getFeedDetails()
];
$episodeData = [];
if($edit || $userData["privateFeed"] == 0){
$items = $dal->getFeed($user);
for($x = 0; $x < $user->getFeedLength() && isset($items[$x]); $x++){
/** @var \AudioDidact\Video $i */
$i = $items[$x];
$descr = $i->getDesc();
// Limit description to 3 lines initially
$words = explode("\n", $descr, 4);
if(count($words) > 3){
$words[3] = "<p id='" . $i->getId() . "' style='display:none;'>" . trim($words[3]) . " </p></p>";
$words[4] = "<a onclick='$(\"#" . $i->getId() . "\").show();'>Continue Reading...</a>";
}
$descr = implode("\n", $words);
$descr = mb_ereg_replace('(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.%-=#~\@!]*(\?\S+)?)?)?)', '<a href="\\1" target="_blank">\\1</a>', $descr);
$descr = nl2br($descr);
$thumb = LOCAL_URL . DOWNLOAD_PATH . '/' . $i->getThumbnailFilename();
$episodeFile = LOCAL_URL . DOWNLOAD_PATH . '/' . $i->getFilename() . $i->getFileExtension();
$episodeData[] = ["title" => $i->getTitle(), "author" => $i->getAuthor(), "id" => $i->getId(),
"description" => $descr, "thumbnail" => $thumb, "episodeFile" => $episodeFile, "isVideo" => $i->isIsVideo()];
}
}
$options = ["edit" => $edit, "episodes" => $episodeData, "emailverify" => $emailVerify, "pageUser" => $userData,
"stats" => generateStatistics($user)];
return GlobalFunctions::generatePug("views/userPage.pug", $title, $options);
}
/**
* Returns Array with informative statistics about all videos in the feed
*
* @param \AudioDidact\User $user
* @return array
*/
function generateStatistics(\AudioDidact\User $user){
$dal = GlobalFunctions::getDAL();
$stats = [];
$feed = $dal->getFullFeedHistory($user);
$stats["numVids"] = count($feed);
$time = 0;
foreach($feed as $v){
/** @var \AudioDidact\Video $v */
$time += $v->getDuration();
}
$timeConversion = GlobalFunctions::secondsToTime($time);
$timeList = [];
foreach($timeConversion as $unit => $value){
if($value > 0){
$timeList[] = $value . " " . GlobalFunctions::pluralize($unit, $value);
}
}
$stats["totalTime"] = GlobalFunctions::arrayToCommaSeparatedString($timeList);
return $stats;
}
|
Java
|
{% for reply in replies %}
<div class="cell reply from_{{ reply.member_num }}">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td width="48" valign="top">
<a href="/member/{{ reply.created_by }}">{{ reply.member|avatar:"normal"|safe }}</a>
</td>
<td width="10"></td>
<td width="auto" valign="top">
<div class="fr" id="reply_{{ reply.num }}_buttons">
<strong>
<small class="snow">#{{ forloop.counter }} - {{ reply.created|timesince }} ago
<img src="/static/img/reply.png" align="absmiddle" border="0" alt="回复 {{ reply.member.username }}" onclick="replyOne('{{ reply.member.username }}')" class="clickable" />
<span class="ops"></span>
</small>
</strong>
</div>
<div class="sep3"></div>
<strong>
<a href="/member/{{ reply.created_by }}" class="dark">{{ reply.created_by }}</a>
</strong>
{% if reply.source %}
<span class="snow"> via {{ reply.source }}</span>
{% endif %}
<div class="sep5"></div>
{% autoescape off %}
<div class="content reply_content">{{ reply.content|imgly|mentions|gist|linebreaksbr|bleachify }}</div>
{% endautoescape %}
</td>
</table>
<script>
replies_keys[({{ forloop.counter }} - 1)] = '{{ reply.key }}';
replies_ids[({{ forloop.counter }} - 1)] = '{{ reply.num }}';
{% if reply.parent %}
replies_parents[({{ forloop.counter }} - 1)] = 1;
{% else %}
replies_parents[({{ forloop.counter }} - 1)] = 0;
{% endif %}
</script>
</div>
{% endfor %}
|
Java
|
/*!
* \file dcxtab.cpp
* \brief blah
*
* blah
*
* \author David Legault ( clickhere at scriptsdb dot org )
* \version 1.0
*
* \b Revisions
*
* © ScriptsDB.org - 2006
*/
#include "defines.h"
#include "Classes/dcxtab.h"
#include "Classes/dcxdialog.h"
/*!
* \brief Constructor
*
* \param ID Control ID
* \param p_Dialog Parent DcxDialog Object
* \param mParentHwnd Parent Window Handle
* \param rc Window Rectangle
* \param styles Window Style Tokenized List
*/
DcxTab::DcxTab( UINT ID, DcxDialog * p_Dialog, HWND mParentHwnd, RECT * rc, TString & styles )
: DcxControl(ID, p_Dialog)
, m_bClosable(false)
, m_bGradient(false)
{
LONG Styles = 0, ExStyles = 0;
BOOL bNoTheme = FALSE;
this->parseControlStyles( styles, &Styles, &ExStyles, &bNoTheme );
this->m_Hwnd = CreateWindowEx(
ExStyles | WS_EX_CONTROLPARENT,
DCX_TABCTRLCLASS,
NULL,
WS_CHILD | Styles,
rc->left, rc->top, rc->right - rc->left, rc->bottom - rc->top,
mParentHwnd,
(HMENU) ID,
GetModuleHandle(NULL),
NULL);
if (!IsWindow(this->m_Hwnd))
throw "Unable To Create Window";
if ( bNoTheme )
Dcx::UXModule.dcxSetWindowTheme( this->m_Hwnd , L" ", L" " );
/*
HWND hHwndTip = TabCtrl_GetToolTips( this->m_Hwnd );
if ( IsWindow( hHwndTip ) ) {
TOOLINFO ti;
ZeroMemory( &ti, sizeof( TOOLINFO ) );
ti.cbSize = sizeof( TOOLINFO );
ti.uFlags = TTF_SUBCLASS | TTF_IDISHWND;
ti.hwnd = mParentHwnd;
ti.uId = (UINT) this->m_Hwnd;
ti.lpszText = LPSTR_TEXTCALLBACK;
SendMessage( hHwndTip, TTM_ADDTOOL, (WPARAM) 0, (LPARAM) &ti );
}
*/
//if (p_Dialog->getToolTip() != NULL) {
// if (styles.istok("tooltips")) {
// this->m_ToolTipHWND = p_Dialog->getToolTip();
// TabCtrl_SetToolTips(this->m_Hwnd,this->m_ToolTipHWND);
// //AddToolTipToolInfo(this->m_ToolTipHWND, this->m_Hwnd);
// }
//}
this->setControlFont( GetStockFont( DEFAULT_GUI_FONT ), FALSE );
this->registreDefaultWindowProc( );
SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this );
}
/*!
* \brief blah
*
* blah
*/
DcxTab::~DcxTab( ) {
ImageList_Destroy( this->getImageList( ) );
int n = 0, nItems = TabCtrl_GetItemCount( this->m_Hwnd );
while ( n < nItems ) {
this->deleteLParamInfo( n );
++n;
}
this->unregistreDefaultWindowProc( );
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::parseControlStyles( TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme ) {
unsigned int i = 1, numtok = styles.numtok( );
//*ExStyles = WS_EX_CONTROLPARENT;
while ( i <= numtok ) {
if ( styles.gettok( i ) == "vertical" )
*Styles |= TCS_VERTICAL;
else if ( styles.gettok( i ) == "bottom" )
*Styles |= TCS_BOTTOM;
else if ( styles.gettok( i ) == "right" )
*Styles |= TCS_RIGHT;
else if ( styles.gettok( i ) == "fixedwidth" )
*Styles |= TCS_FIXEDWIDTH;
else if ( styles.gettok( i ) == "buttons" )
*Styles |= TCS_BUTTONS;
else if ( styles.gettok( i ) == "flat" )
*Styles |= TCS_FLATBUTTONS;
else if ( styles.gettok( i ) == "hot" )
*Styles |= TCS_HOTTRACK;
else if ( styles.gettok( i ) == "multiline" )
*Styles |= TCS_MULTILINE;
else if ( styles.gettok( i ) == "rightjustify" )
*Styles |= TCS_RIGHTJUSTIFY;
else if ( styles.gettok( i ) == "scrollopposite" )
*Styles |= TCS_SCROLLOPPOSITE;
//else if ( styles.gettok( i ) == "tooltips" )
// *Styles |= TCS_TOOLTIPS;
else if ( styles.gettok( i ) == "flatseps" )
*ExStyles |= TCS_EX_FLATSEPARATORS;
else if (styles.gettok(i) == "closable") {
this->m_bClosable = true;
*Styles |= TCS_OWNERDRAWFIXED;
}
else if ( styles.gettok( i ) == "gradient" )
this->m_bGradient = true;
i++;
}
this->parseGeneralControlStyles( styles, Styles, ExStyles, bNoTheme );
}
/*!
* \brief $xdid Parsing Function
*
* \param input [NAME] [ID] [PROP] (OPTIONS)
* \param szReturnValue mIRC Data Container
*
* \return > void
*/
void DcxTab::parseInfoRequest( TString & input, char * szReturnValue ) {
int numtok = input.numtok( );
TString prop(input.gettok( 3 ));
if ( prop == "text" && numtok > 3 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_TEXT;
tci.pszText = szReturnValue;
tci.cchTextMax = MIRC_BUFFER_SIZE_CCH;
TabCtrl_GetItem( this->m_Hwnd, nItem, &tci );
return;
}
}
else if ( prop == "num" ) {
wnsprintf( szReturnValue, MIRC_BUFFER_SIZE_CCH, "%d", TabCtrl_GetItemCount( this->m_Hwnd ) );
return;
}
// [NAME] [ID] [PROP] [N]
else if ( prop == "icon" && numtok > 3 ) {
int iTab = input.gettok( 4 ).to_int( ) - 1;
if ( iTab > -1 && iTab < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_IMAGE;
TabCtrl_GetItem( this->m_Hwnd, iTab, &tci );
wnsprintf( szReturnValue, MIRC_BUFFER_SIZE_CCH, "%d", tci.iImage + 1 );
return;
}
}
else if ( prop == "sel" ) {
int nItem = TabCtrl_GetCurSel( this->m_Hwnd );
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
wnsprintf( szReturnValue, MIRC_BUFFER_SIZE_CCH, "%d", nItem + 1 );
return;
}
}
else if ( prop == "seltext" ) {
int nItem = TabCtrl_GetCurSel( this->m_Hwnd );
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_TEXT;
tci.pszText = szReturnValue;
tci.cchTextMax = MIRC_BUFFER_SIZE_CCH;
TabCtrl_GetItem( this->m_Hwnd, nItem, &tci );
return;
}
}
else if ( prop == "childid" && numtok > 3 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_PARAM;
TabCtrl_GetItem( this->m_Hwnd, nItem, &tci );
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
DcxControl * c = this->m_pParentDialog->getControlByHWND( lpdtci->mChildHwnd );
if ( c != NULL )
wnsprintf( szReturnValue, MIRC_BUFFER_SIZE_CCH, "%d", c->getUserID( ) );
return;
}
}
// [NAME] [ID] [PROP]
else if (prop == "mouseitem") {
TCHITTESTINFO tchi;
tchi.flags = TCHT_ONITEM;
GetCursorPos(&tchi.pt);
MapWindowPoints(NULL, this->m_Hwnd, &tchi.pt, 1);
int tab = TabCtrl_HitTest(this->m_Hwnd, &tchi);
wnsprintf(szReturnValue, MIRC_BUFFER_SIZE_CCH, "%d", tab +1);
return;
}
else if ( this->parseGlobalInfoRequest( input, szReturnValue ) )
return;
szReturnValue[0] = 0;
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::parseCommandRequest( TString & input ) {
XSwitchFlags flags(input.gettok(3));
int numtok = input.numtok( );
// xdid -r [NAME] [ID] [SWITCH]
if (flags['r']) {
int n = 0;
TCITEM tci;
int nItems = TabCtrl_GetItemCount(this->m_Hwnd);
while (n < nItems) {
ZeroMemory(&tci, sizeof(TCITEM));
tci.mask = TCIF_PARAM;
if (TabCtrl_GetItem(this->m_Hwnd, n, &tci)) {
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
if (lpdtci != NULL && lpdtci->mChildHwnd != NULL && IsWindow(lpdtci->mChildHwnd)) {
DestroyWindow(lpdtci->mChildHwnd);
delete lpdtci;
}
}
++n;
}
TabCtrl_DeleteAllItems(this->m_Hwnd);
}
// xdid -a [NAME] [ID] [SWITCH] [N] [ICON] [TEXT][TAB][ID] [CONTROL] [X] [Y] [W] [H] (OPTIONS)[TAB](TOOLTIP)
if ( flags['a'] && numtok > 4 ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_IMAGE | TCIF_PARAM;
TString data(input.gettok( 1, TSTAB ).trim());
TString control_data;
if ( input.numtok( TSTAB ) > 1 )
control_data = input.gettok( 2, TSTAB ).trim();
TString tooltip;
if ( input.numtok( TSTAB ) > 2 )
tooltip = input.gettok( 3, -1, TSTAB ).trim();
int nIndex = data.gettok( 4 ).to_int( ) - 1;
if ( nIndex == -1 )
nIndex += TabCtrl_GetItemCount( this->m_Hwnd ) + 1;
tci.iImage = data.gettok( 5 ).to_int( ) - 1;
// Extra params
LPDCXTCITEM lpdtci = new DCXTCITEM;
if (lpdtci == NULL) {
this->showError(NULL, "-a", "Unable To Create Control, Unable to Allocate Memory");
return;
}
lpdtci->tsTipText = tooltip;
tci.lParam = (LPARAM) lpdtci;
// Itemtext
TString itemtext;
if ( data.numtok( ) > 5 ) {
itemtext = data.gettok( 6, -1 );
tci.mask |= TCIF_TEXT;
if (this->m_bClosable)
itemtext += " ";
tci.pszText = itemtext.to_chr( );
}
if ( control_data.numtok( ) > 5 ) {
UINT ID = mIRC_ID_OFFSET + (UINT)control_data.gettok( 1 ).to_int( );
if ( ID > mIRC_ID_OFFSET - 1 &&
!IsWindow( GetDlgItem( this->m_pParentDialog->getHwnd( ), ID ) ) &&
this->m_pParentDialog->getControlByID( ID ) == NULL )
{
try {
DcxControl * p_Control = DcxControl::controlFactory(this->m_pParentDialog,ID,control_data,2,
CTLF_ALLOW_TREEVIEW |
CTLF_ALLOW_LISTVIEW |
CTLF_ALLOW_RICHEDIT |
CTLF_ALLOW_DIVIDER |
CTLF_ALLOW_PANEL |
CTLF_ALLOW_TAB |
CTLF_ALLOW_REBAR |
CTLF_ALLOW_WEBCTRL |
CTLF_ALLOW_EDIT |
CTLF_ALLOW_IMAGE |
CTLF_ALLOW_LIST
,this->m_Hwnd);
if ( p_Control != NULL ) {
lpdtci->mChildHwnd = p_Control->getHwnd( );
this->m_pParentDialog->addControl( p_Control );
}
}
catch ( char *err ) {
this->showErrorEx(NULL, "-a", "Unable To Create Control %d (%s)", ID - mIRC_ID_OFFSET, err);
}
}
else
this->showErrorEx(NULL, "-a", "Control with ID \"%d\" already exists", ID - mIRC_ID_OFFSET );
}
TabCtrl_InsertItem( this->m_Hwnd, nIndex, &tci );
this->activateSelectedTab( );
}
// xdid -c [NAME] [ID] [SWITCH] [N]
else if ( flags['c'] && numtok > 3 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TabCtrl_SetCurSel( this->m_Hwnd, nItem );
this->activateSelectedTab( );
}
}
// xdid -d [NAME] [ID] [SWITCH] [N]
else if ( flags['d'] && numtok > 3 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
// if a valid item to delete
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
int curSel = TabCtrl_GetCurSel(this->m_Hwnd);
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_PARAM;
if (TabCtrl_GetItem(this->m_Hwnd, nItem, &tci)) {
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
if ( lpdtci != NULL && lpdtci->mChildHwnd != NULL && IsWindow( lpdtci->mChildHwnd ) ) {
DestroyWindow( lpdtci->mChildHwnd );
delete lpdtci;
}
}
TabCtrl_DeleteItem( this->m_Hwnd, nItem );
// select the next tab item if its the current one
if (curSel == nItem) {
if (nItem < TabCtrl_GetItemCount(this->m_Hwnd))
TabCtrl_SetCurSel(this->m_Hwnd, nItem);
else
TabCtrl_SetCurSel(this->m_Hwnd, nItem -1);
this->activateSelectedTab( );
}
}
}
// xdid -l [NAME] [ID] [SWITCH] [N] [ICON]
else if ( flags['l'] && numtok > 4 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
int nIcon = input.gettok( 5 ).to_int( ) - 1;
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_IMAGE;
tci.iImage = nIcon;
TabCtrl_SetItem( this->m_Hwnd, nItem, &tci );
}
}
// xdid -m [NAME] [ID] [SWITCH] [X] [Y]
else if ( flags['m'] && numtok > 4 ) {
int X = input.gettok( 4 ).to_int( );
int Y = input.gettok( 5 ).to_int( );
TabCtrl_SetItemSize( this->m_Hwnd, X, Y );
}
// This it to avoid an invalid flag message.
// xdid -r [NAME] [ID] [SWITCH]
else if ( flags['r'] ) {
}
// xdid -t [NAME] [ID] [SWITCH] [N] (text)
else if ( flags['t'] && numtok > 3 ) {
int nItem = input.gettok( 4 ).to_int( ) - 1;
if ( nItem > -1 && nItem < TabCtrl_GetItemCount( this->m_Hwnd ) ) {
TString itemtext;
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_TEXT;
if ( numtok > 4 )
itemtext = input.gettok( 5, -1 ).trim();
tci.pszText = itemtext.to_chr( );
TabCtrl_SetItem( this->m_Hwnd, nItem, &tci );
}
}
// xdid -v [DNAME] [ID] [SWITCH] [N] [POS]
else if (flags['v'] && numtok > 4) {
int nItem = input.gettok(4).to_int();
int pos = input.gettok(5).to_int();
BOOL adjustDelete = FALSE;
if (nItem == pos)
return;
else if ((nItem < 1) || (nItem > TabCtrl_GetItemCount(this->m_Hwnd)))
return;
else if ((pos < 1) || (pos > TabCtrl_GetItemCount(this->m_Hwnd)))
return;
// does the nItem index get shifted after we insert
if (nItem > pos)
adjustDelete = TRUE;
// decrement coz of 0-index
nItem--;
// get the item we're moving
char* text = new char[MIRC_BUFFER_SIZE_CCH];
TCITEM tci;
ZeroMemory(&tci, sizeof(TCITEM));
tci.pszText = text;
tci.cchTextMax = MIRC_BUFFER_SIZE_CCH;
tci.mask = TCIF_IMAGE | TCIF_PARAM | TCIF_TEXT | TCIF_STATE;
TabCtrl_GetItem(this->m_Hwnd, nItem, &tci);
// insert it into the new position
TabCtrl_InsertItem(this->m_Hwnd, pos, &tci);
// remove the old tab item
TabCtrl_DeleteItem(this->m_Hwnd, (adjustDelete ? nItem +1 : nItem));
delete [] text;
}
// xdid -w [NAME] [ID] [SWITCH] [FLAGS] [INDEX] [FILENAME]
else if (flags['w'] && numtok > 5) {
HIMAGELIST himl;
HICON icon;
TString flag(input.gettok( 4 ));
int index = input.gettok( 5 ).to_int();
TString filename(input.gettok(6, -1));
if ((himl = this->getImageList()) == NULL) {
himl = this->createImageList();
if (himl)
this->setImageList(himl);
}
icon = dcxLoadIcon(index, filename, false, flag);
ImageList_AddIcon(himl, icon);
DestroyIcon(icon);
}
// xdid -y [NAME] [ID] [SWITCH] [+FLAGS]
else if ( flags['y'] ) {
ImageList_Destroy( this->getImageList( ) );
}
else
this->parseGlobalCommandRequest( input, flags );
}
/*!
* \brief blah
*
* blah
*/
HIMAGELIST DcxTab::getImageList( ) {
return TabCtrl_GetImageList( this->m_Hwnd );
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::setImageList( HIMAGELIST himl ) {
TabCtrl_SetImageList( this->m_Hwnd, himl );
}
/*!
* \brief blah
*
* blah
*/
HIMAGELIST DcxTab::createImageList( ) {
return ImageList_Create( 16, 16, ILC_COLOR32|ILC_MASK, 1, 0 );
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::deleteLParamInfo( const int nItem ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_PARAM;
if ( TabCtrl_GetItem( this->m_Hwnd, nItem, &tci ) ) {
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
if ( lpdtci != NULL )
delete lpdtci;
}
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::activateSelectedTab( ) {
int nTab = TabCtrl_GetItemCount( this->m_Hwnd );
int nSel = TabCtrl_GetCurSel( this->m_Hwnd );
if ( nTab > 0 ) {
RECT tabrect, rc;
GetWindowRect( this->m_Hwnd, &tabrect );
TabCtrl_AdjustRect( this->m_Hwnd, FALSE, &tabrect );
GetWindowRect( this->m_Hwnd, &rc );
OffsetRect( &tabrect, -rc.left, -rc.top );
/*
char data[500];
wnsprintf( data, 500, "WRECT %d %d %d %d - ARECT %d %d %d %d",
rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top,
tabrect.left, tabrect.top, tabrect.right-tabrect.left, tabrect.bottom-tabrect.top );
mIRCError( data );
*/
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_PARAM;
HDWP hdwp = BeginDeferWindowPos( 0 );
while ( nTab-- ) {
TabCtrl_GetItem( this->m_Hwnd, nTab, &tci );
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
if ( lpdtci->mChildHwnd != NULL && IsWindow( lpdtci->mChildHwnd ) ) {
if ( nTab == nSel ) {
hdwp = DeferWindowPos( hdwp, lpdtci->mChildHwnd, NULL,
tabrect.left, tabrect.top, tabrect.right-tabrect.left, tabrect.bottom-tabrect.top,
SWP_SHOWWINDOW | SWP_NOZORDER | SWP_NOOWNERZORDER );
}
else {
hdwp = DeferWindowPos( hdwp, lpdtci->mChildHwnd, NULL, 0, 0, 0, 0,
SWP_HIDEWINDOW | SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOREDRAW | SWP_NOACTIVATE | SWP_NOOWNERZORDER );
}
}
}
EndDeferWindowPos( hdwp );
}
}
void DcxTab::getTab(int index, LPTCITEM tcItem) {
TabCtrl_GetItem(this->m_Hwnd, index, tcItem);
}
int DcxTab::getTabCount() {
return TabCtrl_GetItemCount(this->m_Hwnd);
}
void DcxTab::GetCloseButtonRect(const RECT& rcItem, RECT& rcCloseButton)
{
// ----------
//rcCloseButton.top = rcItem.top + 2;
//rcCloseButton.bottom = rcCloseButton.top + (m_iiCloseButton.rcImage.bottom - m_iiCloseButton.rcImage.top);
//rcCloseButton.right = rcItem.right - 2;
//rcCloseButton.left = rcCloseButton.right - (m_iiCloseButton.rcImage.right - m_iiCloseButton.rcImage.left);
// ----------
rcCloseButton.top = rcItem.top + 2;
rcCloseButton.bottom = rcCloseButton.top + (16);
rcCloseButton.right = rcItem.right - 2;
rcCloseButton.left = rcCloseButton.right - (16);
// ----------
}
TString DcxTab::getStyles(void) {
TString styles(__super::getStyles());
DWORD ExStyles, Styles;
Styles = GetWindowStyle(this->m_Hwnd);
ExStyles = GetWindowExStyle(this->m_Hwnd);
if (Styles & TCS_VERTICAL)
styles.addtok("vertical", " ");
if (Styles & TCS_BOTTOM)
styles.addtok("bottom", " ");
if (Styles & TCS_RIGHT)
styles.addtok("right", " ");
if (Styles & TCS_FIXEDWIDTH)
styles.addtok("fixedwidth", " ");
if (Styles & TCS_RIGHT)
styles.addtok("buttons", " ");
if (Styles & TCS_BUTTONS)
styles.addtok("flat", " ");
if (Styles & TCS_FLATBUTTONS)
styles.addtok("flat", " ");
if (Styles & TCS_HOTTRACK)
styles.addtok("hot", " ");
if (Styles & TCS_MULTILINE)
styles.addtok("multiline", " ");
if (Styles & TCS_RIGHTJUSTIFY)
styles.addtok("rightjustify", " ");
if (Styles & TCS_SCROLLOPPOSITE)
styles.addtok("scrollopposite", " ");
if (ExStyles & TCS_EX_FLATSEPARATORS)
styles.addtok("flatseps", " ");
if (this->m_bClosable)
styles.addtok("closable", " ");
if (this->m_bGradient)
styles.addtok("gradient", " ");
return styles;
}
void DcxTab::toXml(TiXmlElement * xml) {
if (xml == NULL)
return;
__super::toXml(xml);
int count = this->getTabCount();
char buf[MIRC_BUFFER_SIZE_CCH];
TCITEM tci;
for (int i = 0; i < count; i++) {
tci.cchTextMax = MIRC_BUFFER_SIZE_CCH -1;
tci.pszText = buf;
tci.mask |= TCIF_TEXT;
if(TabCtrl_GetItem(this->m_Hwnd, i, &tci)) {
LPDCXTCITEM lpdtci = (LPDCXTCITEM) tci.lParam;
if (lpdtci != NULL) {
DcxControl * ctrl = this->m_pParentDialog->getControlByHWND(lpdtci->mChildHwnd);
if (ctrl != NULL) {
TiXmlElement * ctrlxml = ctrl->toXml();
// we need to remove hidden style here
TString styles(ctrlxml->Attribute("styles"));
if (styles.len() > 0) {
styles.remtok("hidden", 1);
if (styles.len() > 0)
ctrlxml->SetAttribute("styles", styles.to_chr());
else
ctrlxml->RemoveAttribute("styles");
}
if (tci.mask & TCIF_TEXT)
ctrlxml->SetAttribute("caption", tci.pszText);
xml->LinkEndChild(ctrlxml);
}
}
}
}
}
/*!
* \brief blah
*
* blah
*/
LRESULT DcxTab::ParentMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL &bParsed)
{
switch (uMsg) {
case WM_NOTIFY :
{
LPNMHDR hdr = (LPNMHDR) lParam;
if (!hdr)
break;
switch (hdr->code) {
case NM_RCLICK:
{
if (this->m_pParentDialog->getEventMask() & DCX_EVENT_CLICK) {
TCHITTESTINFO tchi;
tchi.flags = TCHT_ONITEM;
GetCursorPos(&tchi.pt);
MapWindowPoints(NULL, this->m_Hwnd, &tchi.pt, 1);
int tab = TabCtrl_HitTest(this->m_Hwnd, &tchi);
TabCtrl_GetCurSel(this->m_Hwnd);
if (tab != -1)
this->execAliasEx("%s,%d,%d", "rclick", this->getUserID(), tab +1);
}
bParsed = TRUE;
break;
}
case NM_CLICK:
{
if (this->m_pParentDialog->getEventMask() & DCX_EVENT_CLICK) {
int tab = TabCtrl_GetCurFocus(this->m_Hwnd);
//int tab = TabCtrl_GetCurSel(this->m_Hwnd);
if (tab != -1) {
if (this->m_bClosable) {
RECT rcCloseButton, rc;
POINT pt;
GetCursorPos(&pt);
MapWindowPoints(NULL,this->m_Hwnd, &pt, 1);
TabCtrl_GetItemRect(this->m_Hwnd, tab, &rc);
GetCloseButtonRect(rc, rcCloseButton);
if (PtInRect(&rcCloseButton, pt)) {
this->execAliasEx("%s,%d,%d", "closetab", this->getUserID(), tab +1);
break;
}
}
this->execAliasEx("%s,%d,%d", "sclick", this->getUserID(), tab +1);
}
}
}
// fall through.
case TCN_SELCHANGE:
{
this->activateSelectedTab();
bParsed = TRUE;
}
break;
}
break;
}
// Original source based on code from eMule 0.47 source code available at http://www.emule-project.net
case WM_DRAWITEM:
{
if (!m_bClosable)
break;
DRAWITEMSTRUCT *idata = (DRAWITEMSTRUCT *)lParam;
if ((idata == NULL) || (!IsWindow(idata->hwndItem)))
break;
//DcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem, "dcx_cthis");
//if (c_this == NULL)
// break;
RECT rect;
int nTabIndex = idata->itemID;
if (nTabIndex < 0)
break;
CopyRect(&rect, &idata->rcItem);
// if themes are active use them.
// call default WndProc(), DrawThemeParentBackgroundUx() is only temporary
DcxControl::DrawCtrlBackground(idata->hDC, this, &rect);
//DrawThemeParentBackgroundUx(this->m_Hwnd, idata->hDC, &rect);
//CopyRect(&rect, &idata->rcItem);
if (this->m_bGradient) {
if (this->m_clrBackText == -1)
// Gives a nice silver/gray gradient
XPopupMenuItem::DrawGradient(idata->hDC, &rect, GetSysColor(COLOR_BTNHIGHLIGHT), GetSysColor(COLOR_BTNFACE), TRUE);
else
XPopupMenuItem::DrawGradient(idata->hDC, &rect, GetSysColor(COLOR_BTNHIGHLIGHT), this->m_clrBackText, TRUE);
}
rect.left += 1+ GetSystemMetrics(SM_CXEDGE); // move in past border.
// TODO: (twig) Ook can u take a look at this plz? string stuff isnt my forte
TString label((UINT)MIRC_BUFFER_SIZE_CCH);
TC_ITEM tci;
tci.mask = TCIF_TEXT | TCIF_IMAGE | TCIF_STATE;
tci.pszText = label.to_chr();
tci.cchTextMax = MIRC_BUFFER_SIZE_CCH;
tci.dwStateMask = TCIS_HIGHLIGHTED;
if (!TabCtrl_GetItem(this->getHwnd(), nTabIndex, &tci)) {
this->showError(NULL, "DcxTab Fatal Error", "Invalid item");
break;
}
// fill the rect so it appears to "merge" with the tab page content
//if (!dcxIsThemeActive())
//FillRect(idata->hDC, &rect, GetSysColorBrush(COLOR_BTNFACE));
// set transparent so text background isnt annoying
int iOldBkMode = SetBkMode(idata->hDC, TRANSPARENT);
// Draw icon on left side if the item has an icon
if (tci.iImage != -1) {
ImageList_DrawEx( this->getImageList(), tci.iImage, idata->hDC, rect.left, rect.top, 0, 0, CLR_NONE, CLR_NONE, ILD_TRANSPARENT );
IMAGEINFO ii;
ImageList_GetImageInfo( this->getImageList(), tci.iImage, &ii);
rect.left += (ii.rcImage.right - ii.rcImage.left);
}
// Draw 'Close button' at right side
if (m_bClosable) {
RECT rcCloseButton;
GetCloseButtonRect(rect, rcCloseButton);
// Draw systems close button ? or do you want a custom close button?
DrawFrameControl(idata->hDC, &rcCloseButton, DFC_CAPTION, DFCS_CAPTIONCLOSE | DFCS_FLAT | DFCS_TRANSPARENT);
//MoveToEx( idata->hDC, rcCloseButton.left, rcCloseButton.top, NULL );
//LineTo( idata->hDC, rcCloseButton.right, rcCloseButton.bottom );
//MoveToEx( idata->hDC, rcCloseButton.right, rcCloseButton.top, NULL );
//LineTo( idata->hDC, rcCloseButton.left, rcCloseButton.bottom );
rect.right = rcCloseButton.left - 2;
}
COLORREF crOldColor = 0;
if (tci.dwState & TCIS_HIGHLIGHTED)
crOldColor = SetTextColor(idata->hDC, GetSysColor(COLOR_HIGHLIGHTTEXT));
rect.top += 1+ GetSystemMetrics(SM_CYEDGE); //4;
//DrawText(idata->hDC, label.to_chr(), label.len(), &rect, DT_SINGLELINE | DT_TOP | DT_NOPREFIX);
// allow mirc formatted text.
//mIRC_DrawText(idata->hDC, label, &rect, DT_SINGLELINE | DT_TOP | DT_NOPREFIX, false, this->m_bUseUTF8);
//if (!this->m_bCtrlCodeText) {
// if (this->m_bShadowText)
// dcxDrawShadowText(idata->hDC, label.to_wchr(this->m_bUseUTF8), label.wlen(),&rect, DT_WORD_ELLIPSIS | DT_LEFT | DT_TOP | DT_SINGLELINE, GetTextColor(idata->hDC), 0, 5, 5);
// else
// DrawTextW( idata->hDC, label.to_wchr(this->m_bUseUTF8), label.wlen( ), &rect, DT_WORD_ELLIPSIS | DT_LEFT | DT_TOP | DT_SINGLELINE );
//}
//else
// mIRC_DrawText( idata->hDC, label, &rect, DT_WORD_ELLIPSIS | DT_LEFT | DT_TOP | DT_SINGLELINE, this->m_bShadowText, this->m_bUseUTF8);
this->ctrlDrawText(idata->hDC, label, &rect, DT_WORD_ELLIPSIS | DT_LEFT | DT_TOP | DT_SINGLELINE);
if (tci.dwState & TCIS_HIGHLIGHTED)
SetTextColor(idata->hDC, crOldColor);
SetBkMode(idata->hDC, iOldBkMode);
break;
}
}
return 0L;
}
LRESULT DcxTab::PostMessage( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL & bParsed )
{
LRESULT lRes = 0L;
switch( uMsg ) {
case WM_CONTEXTMENU:
case WM_LBUTTONUP:
break;
case WM_NOTIFY :
{
LPNMHDR hdr = (LPNMHDR) lParam;
if (!hdr)
break;
//if (hdr->hwndFrom == this->m_ToolTipHWND) {
// switch(hdr->code) {
// case TTN_GETDISPINFO:
// {
// LPNMTTDISPINFO di = (LPNMTTDISPINFO)lParam;
// di->lpszText = this->m_tsToolTip.to_chr();
// di->hinst = NULL;
// bParsed = TRUE;
// }
// break;
// case TTN_LINKCLICK:
// {
// bParsed = TRUE;
// this->execAliasEx("%s,%d", "tooltiplink", this->getUserID());
// }
// break;
// default:
// break;
// }
//}
if (IsWindow(hdr->hwndFrom)) {
DcxControl *c_this = (DcxControl *) GetProp(hdr->hwndFrom,"dcx_cthis");
if (c_this != NULL)
lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
}
}
break;
case WM_HSCROLL:
case WM_VSCROLL:
case WM_COMMAND:
{
if (IsWindow((HWND) lParam)) {
DcxControl *c_this = (DcxControl *) GetProp((HWND) lParam,"dcx_cthis");
if (c_this != NULL)
lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
}
}
break;
case WM_DELETEITEM:
{
DELETEITEMSTRUCT *idata = (DELETEITEMSTRUCT *)lParam;
if ((idata != NULL) && (IsWindow(idata->hwndItem))) {
DcxControl *c_this = (DcxControl *) GetProp(idata->hwndItem,"dcx_cthis");
if (c_this != NULL)
lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
}
}
break;
case WM_MEASUREITEM:
{
HWND cHwnd = GetDlgItem(this->m_Hwnd, wParam);
if (IsWindow(cHwnd)) {
DcxControl *c_this = (DcxControl *) GetProp(cHwnd,"dcx_cthis");
if (c_this != NULL)
lRes = c_this->ParentMessage(uMsg, wParam, lParam, bParsed);
}
}
break;
case WM_SIZE:
{
this->activateSelectedTab( );
if (this->m_pParentDialog->getEventMask() & DCX_EVENT_SIZE)
this->execAliasEx("%s,%d", "sizing", this->getUserID( ) );
}
break;
case WM_ERASEBKGND:
{
if (this->isExStyle(WS_EX_TRANSPARENT))
this->DrawParentsBackground((HDC)wParam);
else
DcxControl::DrawCtrlBackground((HDC) wParam,this);
bParsed = TRUE;
return TRUE;
}
break;
case WM_PAINT:
{
if (!this->m_bAlphaBlend)
break;
PAINTSTRUCT ps;
HDC hdc;
hdc = BeginPaint( this->m_Hwnd, &ps );
bParsed = TRUE;
// Setup alpha blend if any.
LPALPHAINFO ai = this->SetupAlphaBlend(&hdc);
lRes = CallWindowProc( this->m_DefaultWindowProc, this->m_Hwnd, uMsg, (WPARAM) hdc, lParam );
this->FinishAlphaBlend(ai);
EndPaint( this->m_Hwnd, &ps );
}
break;
//case WM_CLOSE:
// {
// if (GetKeyState(VK_ESCAPE) != 0) // don't allow the window to close if escape is pressed. Needs looking into for a better method.
// bParsed = TRUE;
// }
// break;
case WM_DESTROY:
{
delete this;
bParsed = TRUE;
}
break;
default:
lRes = this->CommonMessage( uMsg, wParam, lParam, bParsed);
break;
}
return lRes;
}
|
Java
|
package uk.ac.soton.ecs.comp3204.l3;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.io.IOException;
import javax.swing.JPanel;
import org.openimaj.content.slideshow.Slide;
import org.openimaj.content.slideshow.SlideshowApplication;
import org.openimaj.data.dataset.VFSGroupDataset;
import org.openimaj.image.DisplayUtilities.ImageComponent;
import org.openimaj.image.FImage;
import org.openimaj.image.ImageUtilities;
import uk.ac.soton.ecs.comp3204.l3.FaceDatasetDemo.FaceDatasetProvider;
import uk.ac.soton.ecs.comp3204.utils.Utils;
import uk.ac.soton.ecs.comp3204.utils.annotations.Demonstration;
/**
* Visualise mean-centered face images
*
* @author Jonathon Hare (jsh2@ecs.soton.ac.uk)
*
*/
@Demonstration(title = "Mean-centred faces demo")
public class MeanCenteredFacesDemo implements Slide {
@Override
public Component getComponent(int width, int height) throws IOException {
final VFSGroupDataset<FImage> dataset = FaceDatasetProvider.getDataset();
final FImage mean = dataset.getRandomInstance().fill(0f);
for (final FImage i : dataset) {
mean.addInplace(i);
}
mean.divideInplace(dataset.numInstances());
final JPanel outer = new JPanel();
outer.setOpaque(false);
outer.setPreferredSize(new Dimension(width, height));
outer.setLayout(new GridBagLayout());
final JPanel base = new JPanel();
base.setOpaque(false);
base.setPreferredSize(new Dimension(width, height - 50));
base.setLayout(new FlowLayout());
for (int i = 0; i < 60; i++) {
final FImage img = dataset.getRandomInstance().subtract(mean).normalise();
final ImageComponent ic = new ImageComponent(true, false);
ic.setAllowPanning(false);
ic.setAllowZoom(false);
ic.setShowPixelColours(false);
ic.setShowXYPosition(false);
ic.setImage(ImageUtilities.createBufferedImageForDisplay(img));
base.add(ic);
}
outer.add(base);
return outer;
}
@Override
public void close() {
// do nothing
}
public static void main(String[] args) throws IOException {
new SlideshowApplication(new MeanCenteredFacesDemo(), 1024, 768, Utils.BACKGROUND_IMAGE);
}
}
|
Java
|
package com.salesforce.dva.argus.service.mq.kafka;
import com.fasterxml.jackson.databind.JavaType;
import java.io.Serializable;
import java.util.List;
public interface Consumer {
<T extends Serializable> List<T> dequeueFromBuffer(String topic, Class<T> type, int timeout, int limit);
<T extends Serializable> List<T> dequeueFromBuffer(String topic, JavaType type, int timeout, int limit);
void shutdown();
}
|
Java
|
# -*- encoding: binary -*-
require "./test/exec"
require "tmpdir"
require "fileutils"
require "net/http"
module TestFreshSetup
include TestExec
def setup
setup_mogilefs
end
def setup_mogilefs(plugins = nil)
@test_host = "127.0.0.1"
setup_mogstored
@tracker = TCPServer.new(@test_host, 0)
@tracker_port = @tracker.addr[1]
@dbname = Tempfile.new(["mogfresh", ".sqlite3"])
@mogilefsd_conf = Tempfile.new(["mogilefsd", "conf"])
@mogilefsd_pid = Tempfile.new(["mogilefsd", "pid"])
cmd = %w(mogdbsetup --yes --type=SQLite --dbname) << @dbname.path
x!(*cmd)
@mogilefsd_conf.puts "db_dsn DBI:SQLite:#{@dbname.path}"
@mogilefsd_conf.write <<EOF
conf_port #@tracker_port
listen #@test_host
pidfile #{@mogilefsd_pid.path}
replicate_jobs 1
fsck_jobs 1
query_jobs 1
mogstored_stream_port #{@mogstored_mgmt_port}
node_timeout 10
EOF
@mogilefsd_conf.flush
@trackers = @hosts = [ "#@test_host:#@tracker_port" ]
@tracker.close
x!("mogilefsd", "--daemon", "--config=#{@mogilefsd_conf.path}")
wait_for_port @tracker_port
@admin = MogileFS::Admin.new(:hosts => @hosts)
50.times do
break if File.size(@mogstored_pid.path) > 0
sleep 0.1
end
end
def wait_for_port(port)
tries = 50
begin
TCPSocket.new(@test_host, port).close
return
rescue
sleep 0.1
end while (tries -= 1) > 0
raise "#@test_host:#{port} never became ready"
end
def test_admin_setup_new_host_and_devices
assert_equal [], @admin.get_hosts
args = { :ip => @test_host, :port => @mogstored_http_port }
@admin.create_host("me", args)
yield_for_monitor_update { @admin.get_hosts.empty? or break }
hosts = @admin.get_hosts
assert_equal 1, hosts.size
host = @admin.get_hosts[0]
assert_equal "me", host["hostname"]
assert_equal @mogstored_http_port, host["http_port"]
assert_nil host["http_get_port"]
assert_equal @test_host, host["hostip"]
assert_kind_of Integer, host["hostid"]
assert_equal hosts, @admin.get_hosts(host["hostid"])
assert_equal [], @admin.get_devices
end
def test_replicate_now
assert_equal({"count" => 0}, @admin.replicate_now)
end
def test_clear_cache
assert_nil @admin.clear_cache
end
def test_create_update_delete_class
domain = "rbmogtest#{Time.now.strftime('%Y%m%d%H%M%S')}.#{uuid}"
@admin.create_domain(domain)
yield_for_monitor_update { @admin.get_domains.include?(domain) and break }
assert_nothing_raised do
@admin.create_class(domain, "klassy", 1)
end
assert_raises(MogileFS::Backend::ClassExistsError) do
@admin.create_class(domain, "klassy", 1)
end
assert_nothing_raised do
@admin.update_class(domain, "klassy",
:mindevcount => 1, :replpolicy => "MultipleHosts(1)")
end
tmp = nil
yield_for_monitor_update do
tmp = @admin.get_domains[domain]["klassy"]
break if tmp && tmp["replpolicy"] == "MultipleHosts(1)"
end
assert tmp, "domain did not show up"
assert_equal 1, tmp["mindevcount"]
assert_equal "MultipleHosts(1)", tmp["replpolicy"]
assert_nothing_raised { @admin.update_class(domain, "klassy", 2) }
ensure
@admin.delete_class(domain, "klassy") rescue nil
end
def add_host_device_domain
assert_equal [], @admin.get_hosts
args = { :ip => @test_host, :port => @mogstored_http_port }
args[:status] = "alive"
@admin.create_host("me", args)
assert File.directory?("#@docroot/dev1")
assert File.directory?("#@docroot/dev2")
yield_for_monitor_update { @admin.get_hosts.empty? or break }
me = @admin.get_hosts.find { |x| x["hostname"] == "me" }
assert_instance_of Hash, me, me.inspect
assert_kind_of Integer, me["hostid"], me
assert_equal true, @admin.create_device(me["hostid"], 1)
yield_for_monitor_update { @admin.get_devices.empty? or break }
wait_for_usage_file "dev1"
assert_equal true, @admin.create_device("me", 2)
wait_for_usage_file "dev2"
# MogileFS::Server 2.60+ shows reject_bad_md5 monitor status
dev = @admin.get_devices[0]
if dev.include?("reject_bad_md5")
assert [true, false].include?(dev["reject_bad_md5"])
end
out = err = nil
tries = 0
begin
out.close! if out
err.close! if err
status, out, err = mogadm("check")
assert status.success?, status.inspect
if (tries += 1) > 100
warn err.read
puts out.read
raise "mogadm failed"
end
sleep 0.1
end until out.read =~ /write?able/
domain = "rbmogtest.#$$"
@admin.create_domain(domain)
yield_for_monitor_update { @admin.get_domains.include?(domain) and break }
@domain = domain
end
def test_device_file_add
add_host_device_domain
client = MogileFS::MogileFS.new :hosts => @hosts, :domain => @domain
r, w = IO.pipe
thr = Thread.new do
(0..9).each do |i|
sleep 0.05
w.write("#{i}\n")
end
w.close
:ok
end
assert_equal 20, client.store_file("pipe", nil, r)
assert_equal :ok, thr.value
r.close
assert_equal "0\n1\n2\n3\n4\n5\n6\n7\n8\n9\n", client.get_file_data("pipe")
end
def teardown_mogilefs
if @mogstored_pid
pid = File.read(@mogstored_pid.path).to_i
Process.kill(:TERM, pid) if pid > 0
end
if @mogilefsd_pid
s = TCPSocket.new(@test_host, @tracker_port)
s.write "!shutdown\r\n"
s.close
end
FileUtils.rmtree(@docroot)
end
def wait_for_usage_file(device)
uri = URI("http://#@test_host:#@mogstored_http_port/#{device}/usage")
res = nil
100.times do
res = Net::HTTP.get_response(uri)
if Net::HTTPOK === res
puts res.body if $DEBUG
return
end
puts res.inspect if $DEBUG
sleep 0.1
end
raise "#{uri} failed to appear: #{res.inspect}"
end
def setup_mogstored
@docroot = Dir.mktmpdir(["mogfresh", "docroot"])
Dir.mkdir("#@docroot/dev1")
Dir.mkdir("#@docroot/dev2")
@mogstored_mgmt = TCPServer.new(@test_host, 0)
@mogstored_http = TCPServer.new(@test_host, 0)
@mogstored_mgmt_port = @mogstored_mgmt.addr[1]
@mogstored_http_port = @mogstored_http.addr[1]
@mogstored_conf = Tempfile.new(["mogstored", "conf"])
@mogstored_pid = Tempfile.new(["mogstored", "pid"])
@mogstored_conf.write <<EOF
pidfile = #{@mogstored_pid.path}
maxconns = 1000
httplisten = #@test_host:#{@mogstored_http_port}
mgmtlisten = #@test_host:#{@mogstored_mgmt_port}
docroot = #@docroot
EOF
@mogstored_conf.flush
@mogstored_mgmt.close
@mogstored_http.close
x!("mogstored", "--daemon", "--config=#{@mogstored_conf.path}")
wait_for_port @mogstored_mgmt_port
wait_for_port @mogstored_http_port
end
end
|
Java
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('setlist', '0012_remove_show_leg'),
]
operations = [
migrations.CreateModel(
name='Show2',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('venue', models.ForeignKey(to='setlist.Venue', to_field='id')),
('tour', models.ForeignKey(to='setlist.Tour', to_field='id')),
('date', models.DateField(db_index=True)),
('setlist', models.TextField(default=b'', blank=True)),
('notes', models.TextField(default=b'', blank=True)),
('source', models.TextField(default=b'', blank=True)),
],
options={
},
bases=(models.Model,),
),
]
|
Java
|
{-# Language OverloadedStrings #-}
module XMonad.Actions.XHints.Render where
import XMonad hiding (drawString)
import Data.Text (Text)
import qualified Data.Text as T
import Foreign.C
import Graphics.X11.Xlib.Types
import qualified Data.Text.Foreign as TF
import qualified Data.ByteString as BS
import Codec.Binary.UTF8.String
mkUnmanagedWindow :: Display -> Screen -> Window -> Position
-> Position -> Dimension -> Dimension -> IO Window
mkUnmanagedWindow d s rw x y w h = do
let visual = defaultVisualOfScreen s
attrmask = cWOverrideRedirect
allocaSetWindowAttributes $
\attributes -> do
set_override_redirect attributes True
createWindow d rw x y w h 0 (defaultDepthOfScreen s)
inputOutput visual attrmask attributes
newHintWindow :: Display -> IO (Window,GC)
newHintWindow dpy = do
let win = defaultRootWindow dpy
blk = blackPixel dpy $ defaultScreen dpy
wht = whitePixel dpy $ defaultScreen dpy
scn = defaultScreenOfDisplay dpy
(_,_,_,_,_,x,y,_) <- queryPointer dpy win
nw <- createSimpleWindow dpy win (fromIntegral x) (fromIntegral y) 2 2 1 blk wht
mapWindow dpy nw
gc <- createGC dpy nw
return (nw,gc)
|
Java
|
// An object that encapsulates everything we need to run a 'find'
// operation, encoded in the REST API format.
var Parse = require('parse/node').Parse;
import { default as FilesController } from './Controllers/FilesController';
// restOptions can include:
// skip
// limit
// order
// count
// include
// keys
// redirectClassNameForKey
function RestQuery(config, auth, className, restWhere = {}, restOptions = {}) {
this.config = config;
this.auth = auth;
this.className = className;
this.restWhere = restWhere;
this.response = null;
this.findOptions = {};
if (!this.auth.isMaster) {
this.findOptions.acl = this.auth.user ? [this.auth.user.id] : null;
if (this.className == '_Session') {
if (!this.findOptions.acl) {
throw new Parse.Error(Parse.Error.INVALID_SESSION_TOKEN,
'This session token is invalid.');
}
this.restWhere = {
'$and': [this.restWhere, {
'user': {
__type: 'Pointer',
className: '_User',
objectId: this.auth.user.id
}
}]
};
}
}
this.doCount = false;
// The format for this.include is not the same as the format for the
// include option - it's the paths we should include, in order,
// stored as arrays, taking into account that we need to include foo
// before including foo.bar. Also it should dedupe.
// For example, passing an arg of include=foo.bar,foo.baz could lead to
// this.include = [['foo'], ['foo', 'baz'], ['foo', 'bar']]
this.include = [];
for (var option in restOptions) {
switch(option) {
case 'keys':
this.keys = new Set(restOptions.keys.split(','));
this.keys.add('objectId');
this.keys.add('createdAt');
this.keys.add('updatedAt');
break;
case 'count':
this.doCount = true;
break;
case 'skip':
case 'limit':
this.findOptions[option] = restOptions[option];
break;
case 'order':
var fields = restOptions.order.split(',');
var sortMap = {};
for (var field of fields) {
if (field[0] == '-') {
sortMap[field.slice(1)] = -1;
} else {
sortMap[field] = 1;
}
}
this.findOptions.sort = sortMap;
break;
case 'include':
var paths = restOptions.include.split(',');
var pathSet = {};
for (var path of paths) {
// Add all prefixes with a .-split to pathSet
var parts = path.split('.');
for (var len = 1; len <= parts.length; len++) {
pathSet[parts.slice(0, len).join('.')] = true;
}
}
this.include = Object.keys(pathSet).sort((a, b) => {
return a.length - b.length;
}).map((s) => {
return s.split('.');
});
break;
case 'redirectClassNameForKey':
this.redirectKey = restOptions.redirectClassNameForKey;
this.redirectClassName = null;
break;
default:
throw new Parse.Error(Parse.Error.INVALID_JSON,
'bad option: ' + option);
}
}
}
// A convenient method to perform all the steps of processing a query
// in order.
// Returns a promise for the response - an object with optional keys
// 'results' and 'count'.
// TODO: consolidate the replaceX functions
RestQuery.prototype.execute = function() {
return Promise.resolve().then(() => {
return this.buildRestWhere();
}).then(() => {
return this.runFind();
}).then(() => {
return this.runCount();
}).then(() => {
return this.handleInclude();
}).then(() => {
return this.response;
});
};
RestQuery.prototype.buildRestWhere = function() {
return Promise.resolve().then(() => {
return this.getUserAndRoleACL();
}).then(() => {
return this.redirectClassNameForKey();
}).then(() => {
return this.validateClientClassCreation();
}).then(() => {
return this.replaceSelect();
}).then(() => {
return this.replaceDontSelect();
}).then(() => {
return this.replaceInQuery();
}).then(() => {
return this.replaceNotInQuery();
});
}
// Uses the Auth object to get the list of roles, adds the user id
RestQuery.prototype.getUserAndRoleACL = function() {
if (this.auth.isMaster || !this.auth.user) {
return Promise.resolve();
}
return this.auth.getUserRoles().then((roles) => {
roles.push(this.auth.user.id);
this.findOptions.acl = roles;
return Promise.resolve();
});
};
// Changes the className if redirectClassNameForKey is set.
// Returns a promise.
RestQuery.prototype.redirectClassNameForKey = function() {
if (!this.redirectKey) {
return Promise.resolve();
}
// We need to change the class name based on the schema
return this.config.database.redirectClassNameForKey(
this.className, this.redirectKey).then((newClassName) => {
this.className = newClassName;
this.redirectClassName = newClassName;
});
};
// Validates this operation against the allowClientClassCreation config.
RestQuery.prototype.validateClientClassCreation = function() {
let sysClass = ['_User', '_Installation', '_Role', '_Session', '_Product'];
if (this.config.allowClientClassCreation === false && !this.auth.isMaster
&& sysClass.indexOf(this.className) === -1) {
return this.config.database.collectionExists(this.className).then((hasClass) => {
if (hasClass === true) {
return Promise.resolve();
}
throw new Parse.Error(Parse.Error.OPERATION_FORBIDDEN,
'This user is not allowed to access ' +
'non-existent class: ' + this.className);
});
} else {
return Promise.resolve();
}
};
// Replaces a $inQuery clause by running the subquery, if there is an
// $inQuery clause.
// The $inQuery clause turns into an $in with values that are just
// pointers to the objects returned in the subquery.
RestQuery.prototype.replaceInQuery = function() {
var inQueryObject = findObjectWithKey(this.restWhere, '$inQuery');
if (!inQueryObject) {
return;
}
// The inQuery value must have precisely two keys - where and className
var inQueryValue = inQueryObject['$inQuery'];
if (!inQueryValue.where || !inQueryValue.className) {
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'improper usage of $inQuery');
}
var subquery = new RestQuery(
this.config, this.auth, inQueryValue.className,
inQueryValue.where);
return subquery.execute().then((response) => {
var values = [];
for (var result of response.results) {
values.push({
__type: 'Pointer',
className: inQueryValue.className,
objectId: result.objectId
});
}
delete inQueryObject['$inQuery'];
if (Array.isArray(inQueryObject['$in'])) {
inQueryObject['$in'] = inQueryObject['$in'].concat(values);
} else {
inQueryObject['$in'] = values;
}
// Recurse to repeat
return this.replaceInQuery();
});
};
// Replaces a $notInQuery clause by running the subquery, if there is an
// $notInQuery clause.
// The $notInQuery clause turns into a $nin with values that are just
// pointers to the objects returned in the subquery.
RestQuery.prototype.replaceNotInQuery = function() {
var notInQueryObject = findObjectWithKey(this.restWhere, '$notInQuery');
if (!notInQueryObject) {
return;
}
// The notInQuery value must have precisely two keys - where and className
var notInQueryValue = notInQueryObject['$notInQuery'];
if (!notInQueryValue.where || !notInQueryValue.className) {
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'improper usage of $notInQuery');
}
var subquery = new RestQuery(
this.config, this.auth, notInQueryValue.className,
notInQueryValue.where);
return subquery.execute().then((response) => {
var values = [];
for (var result of response.results) {
values.push({
__type: 'Pointer',
className: notInQueryValue.className,
objectId: result.objectId
});
}
delete notInQueryObject['$notInQuery'];
if (Array.isArray(notInQueryObject['$nin'])) {
notInQueryObject['$nin'] = notInQueryObject['$nin'].concat(values);
} else {
notInQueryObject['$nin'] = values;
}
// Recurse to repeat
return this.replaceNotInQuery();
});
};
// Replaces a $select clause by running the subquery, if there is a
// $select clause.
// The $select clause turns into an $in with values selected out of
// the subquery.
// Returns a possible-promise.
RestQuery.prototype.replaceSelect = function() {
var selectObject = findObjectWithKey(this.restWhere, '$select');
if (!selectObject) {
return;
}
// The select value must have precisely two keys - query and key
var selectValue = selectObject['$select'];
// iOS SDK don't send where if not set, let it pass
if (!selectValue.query ||
!selectValue.key ||
typeof selectValue.query !== 'object' ||
!selectValue.query.className ||
Object.keys(selectValue).length !== 2) {
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'improper usage of $select');
}
var subquery = new RestQuery(
this.config, this.auth, selectValue.query.className,
selectValue.query.where);
return subquery.execute().then((response) => {
var values = [];
for (var result of response.results) {
values.push(result[selectValue.key]);
}
delete selectObject['$select'];
if (Array.isArray(selectObject['$in'])) {
selectObject['$in'] = selectObject['$in'].concat(values);
} else {
selectObject['$in'] = values;
}
// Keep replacing $select clauses
return this.replaceSelect();
})
};
// Replaces a $dontSelect clause by running the subquery, if there is a
// $dontSelect clause.
// The $dontSelect clause turns into an $nin with values selected out of
// the subquery.
// Returns a possible-promise.
RestQuery.prototype.replaceDontSelect = function() {
var dontSelectObject = findObjectWithKey(this.restWhere, '$dontSelect');
if (!dontSelectObject) {
return;
}
// The dontSelect value must have precisely two keys - query and key
var dontSelectValue = dontSelectObject['$dontSelect'];
if (!dontSelectValue.query ||
!dontSelectValue.key ||
typeof dontSelectValue.query !== 'object' ||
!dontSelectValue.query.className ||
Object.keys(dontSelectValue).length !== 2) {
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'improper usage of $dontSelect');
}
var subquery = new RestQuery(
this.config, this.auth, dontSelectValue.query.className,
dontSelectValue.query.where);
return subquery.execute().then((response) => {
var values = [];
for (var result of response.results) {
values.push(result[dontSelectValue.key]);
}
delete dontSelectObject['$dontSelect'];
if (Array.isArray(dontSelectObject['$nin'])) {
dontSelectObject['$nin'] = dontSelectObject['$nin'].concat(values);
} else {
dontSelectObject['$nin'] = values;
}
// Keep replacing $dontSelect clauses
return this.replaceDontSelect();
})
};
// Returns a promise for whether it was successful.
// Populates this.response with an object that only has 'results'.
RestQuery.prototype.runFind = function() {
return this.config.database.find(
this.className, this.restWhere, this.findOptions).then((results) => {
if (this.className == '_User') {
for (var result of results) {
delete result.password;
}
}
this.config.filesController.expandFilesInObject(this.config, results);
if (this.keys) {
var keySet = this.keys;
results = results.map((object) => {
var newObject = {};
for (var key in object) {
if (keySet.has(key)) {
newObject[key] = object[key];
}
}
return newObject;
});
}
if (this.redirectClassName) {
for (var r of results) {
r.className = this.redirectClassName;
}
}
this.response = {results: results};
});
};
// Returns a promise for whether it was successful.
// Populates this.response.count with the count
RestQuery.prototype.runCount = function() {
if (!this.doCount) {
return;
}
this.findOptions.count = true;
delete this.findOptions.skip;
delete this.findOptions.limit;
return this.config.database.find(
this.className, this.restWhere, this.findOptions).then((c) => {
this.response.count = c;
});
};
// Augments this.response with data at the paths provided in this.include.
RestQuery.prototype.handleInclude = function() {
if (this.include.length == 0) {
return;
}
var pathResponse = includePath(this.config, this.auth,
this.response, this.include[0]);
if (pathResponse.then) {
return pathResponse.then((newResponse) => {
this.response = newResponse;
this.include = this.include.slice(1);
return this.handleInclude();
});
} else if (this.include.length > 0) {
this.include = this.include.slice(1);
return this.handleInclude();
}
return pathResponse;
};
// Adds included values to the response.
// Path is a list of field names.
// Returns a promise for an augmented response.
function includePath(config, auth, response, path) {
var pointers = findPointers(response.results, path);
if (pointers.length == 0) {
return response;
}
var className = null;
var objectIds = {};
for (var pointer of pointers) {
if (className === null) {
className = pointer.className;
} else {
if (className != pointer.className) {
throw new Parse.Error(Parse.Error.INVALID_JSON,
'inconsistent type data for include');
}
}
objectIds[pointer.objectId] = true;
}
if (!className) {
throw new Parse.Error(Parse.Error.INVALID_JSON,
'bad pointers');
}
// Get the objects for all these object ids
var where = {'objectId': {'$in': Object.keys(objectIds)}};
var query = new RestQuery(config, auth, className, where);
return query.execute().then((includeResponse) => {
var replace = {};
for (var obj of includeResponse.results) {
obj.__type = 'Object';
obj.className = className;
if(className == "_User"){
delete obj.sessionToken;
}
replace[obj.objectId] = obj;
}
var resp = {
results: replacePointers(response.results, path, replace)
};
if (response.count) {
resp.count = response.count;
}
return resp;
});
}
// Object may be a list of REST-format object to find pointers in, or
// it may be a single object.
// If the path yields things that aren't pointers, this throws an error.
// Path is a list of fields to search into.
// Returns a list of pointers in REST format.
function findPointers(object, path) {
if (object instanceof Array) {
var answer = [];
for (var x of object) {
answer = answer.concat(findPointers(x, path));
}
return answer;
}
if (typeof object !== 'object') {
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'can only include pointer fields');
}
if (path.length == 0) {
if (object.__type == 'Pointer') {
return [object];
}
throw new Parse.Error(Parse.Error.INVALID_QUERY,
'can only include pointer fields');
}
var subobject = object[path[0]];
if (!subobject) {
return [];
}
return findPointers(subobject, path.slice(1));
}
// Object may be a list of REST-format objects to replace pointers
// in, or it may be a single object.
// Path is a list of fields to search into.
// replace is a map from object id -> object.
// Returns something analogous to object, but with the appropriate
// pointers inflated.
function replacePointers(object, path, replace) {
if (object instanceof Array) {
return object.map((obj) => replacePointers(obj, path, replace));
}
if (typeof object !== 'object') {
return object;
}
if (path.length == 0) {
if (object.__type == 'Pointer') {
return replace[object.objectId];
}
return object;
}
var subobject = object[path[0]];
if (!subobject) {
return object;
}
var newsub = replacePointers(subobject, path.slice(1), replace);
var answer = {};
for (var key in object) {
if (key == path[0]) {
answer[key] = newsub;
} else {
answer[key] = object[key];
}
}
return answer;
}
// Finds a subobject that has the given key, if there is one.
// Returns undefined otherwise.
function findObjectWithKey(root, key) {
if (typeof root !== 'object') {
return;
}
if (root instanceof Array) {
for (var item of root) {
var answer = findObjectWithKey(item, key);
if (answer) {
return answer;
}
}
}
if (root && root[key]) {
return root;
}
for (var subkey in root) {
var answer = findObjectWithKey(root[subkey], key);
if (answer) {
return answer;
}
}
}
module.exports = RestQuery;
|
Java
|
<?php
use yii\bootstrap\Html;
/**
* @var $this \yii\web\View
* @var $content string
*/
?>
<?php $this->beginContent('@app/views/layouts/base.php') ?>
<div class="wrap">
<?= $this->render('//shared/admin_panel') ?>
<?= $this->render('//shared/header') ?>
<a class="logo" href="/">
<?php echo Html::img("@web/files/img/logo.png") ?>
</a>
<?= $this->render('//shared/menu') ?>
<?php
if (isset($this->blocks['topBanner'])) {
echo $this->blocks['topBanner'];
}
?>
<div class="container"><?= $content ?></div>
</div>
<footer class="footer">
<div class="container">
<p class="pull-left">© Vetoni <?= date('Y') ?></p>
<p class="pull-right"><?= Yii::powered() ?></p>
</div>
</footer>
<?php $this->endContent() ?>
|
Java
|
<h1 id="title_header"></h1>
<div id="calendar" class="{{ css_classes }}">
</div>
|
Java
|
package com.github.paulp.optional
import scala.collection._
import mutable.HashSet
case class Options(
options: Map[String, String],
args: List[String],
rawArgs: List[String]
)
case class ArgInfo(short: Char, long: String, isSwitch: Boolean, help: String)
object Options
{
private val ShortOption = """-(\w)""".r
private val ShortSquashedOption = """-([^-\s]\w+)""".r
private val LongOption = """--([-\w]+)""".r
private val OptionTerminator = "--"
private val True = "true";
/**
* Take a list of string arguments and parse them into options.
* Currently the dumbest option parser in the entire world, but
* oh well.
*/
def parse(mainArgs: scala.collection.immutable.Map [String, MainArg], argInfos: HashSet[ArgInfo], args: String*): Options = {
import mutable._;
val optionsStack = new ArrayStack[String];
val options = new OpenHashMap[String, String];
val arguments = new ArrayBuffer[String];
def addSwitch(c: Char) =
options(c.toString) = True
def isSwitch(c: Char) =
argInfos exists {
case ArgInfo(`c`, _, true, _) => true
case _ => false
}
def addOption(name: String) = {
if (mainArgs.isDefinedAt(name) && mainArgs(name).isBoolean) {
options(name) = True;
}
else if (optionsStack.isEmpty) {
options(name) = True;
}
else {
val next = optionsStack.pop;
next match {
case ShortOption(_) | ShortSquashedOption(_) | LongOption(_) | OptionTerminator =>
optionsStack.push(next);
options(name) = True;
case x => options(name) = x;
}
}
}
optionsStack ++= args.reverse;
while(!optionsStack.isEmpty){
optionsStack.pop match {
case ShortSquashedOption(xs) =>
xs foreach addSwitch
case ShortOption(name) =>
val c = name(0)
if (isSwitch(c)) addSwitch(c)
else addOption(name)
// Treat hyphens as if they were underscores, so we can have --switches-like-this as well as --switches_like_this
case LongOption(name) => addOption (name.replaceAll ("-", "_"));
case OptionTerminator => optionsStack.drain(arguments += _);
case x => arguments += x;
}
}
Options(options, arguments.toList, args.toList)
}
}
|
Java
|
/*-
* Copyright (c) 2001-2008, by Cisco Systems, Inc. All rights reserved.
* Copyright (c) 2008-2012, by Randall Stewart. All rights reserved.
* Copyright (c) 2008-2012, by Michael Tuexen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* a) Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* b) 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.
*
* c) Neither the name of Cisco Systems, 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 <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#ifndef _NETINET_SCTP_CONSTANTS_H_
#define _NETINET_SCTP_CONSTANTS_H_
/* IANA assigned port number for SCTP over UDP encapsulation */
#define SCTP_OVER_UDP_TUNNELING_PORT 9899
/* Number of packets to get before sack sent by default */
#define SCTP_DEFAULT_SACK_FREQ 2
/* Address limit - This variable is calculated
* based on an 65535 byte max ip packet. We take out 100 bytes
* for the cookie, 40 bytes for a v6 header and 32
* bytes for the init structure. A second init structure
* for the init-ack and then finally a third one for the
* imbedded init. This yeilds 100+40+(3 * 32) = 236 bytes.
* This leaves 65299 bytes for addresses. We throw out the 299 bytes.
* Now whatever we send in the INIT() we need to allow to get back in the
* INIT-ACK plus all the values from INIT and INIT-ACK
* listed in the cookie. Plus we need some overhead for
* maybe copied parameters in the COOKIE. If we
* allow 1080 addresses, and each side has 1080 V6 addresses
* that will be 21600 bytes. In the INIT-ACK we will
* see the INIT-ACK 21600 + 43200 in the cookie. This leaves
* about 500 bytes slack for misc things in the cookie.
*/
#define SCTP_ADDRESS_LIMIT 1080
/* We need at least 2k of space for us, inits
* larger than that lets abort.
*/
#define SCTP_LARGEST_INIT_ACCEPTED (65535 - 2048)
/* Number of addresses where we just skip the counting */
#define SCTP_COUNT_LIMIT 40
#define SCTP_ZERO_COPY_TICK_DELAY (((100 * hz) + 999) / 1000)
#define SCTP_ZERO_COPY_SENDQ_TICK_DELAY (((100 * hz) + 999) / 1000)
/* Number of ticks to delay before running
* iterator on an address change.
*/
#define SCTP_ADDRESS_TICK_DELAY 2
#define SCTP_VERSION_STRING "KAME-BSD 1.1"
/* #define SCTP_AUDITING_ENABLED 1 used for debug/auditing */
#define SCTP_AUDIT_SIZE 256
#define SCTP_KTRHEAD_NAME "sctp_iterator"
#define SCTP_KTHREAD_PAGES 0
#define SCTP_MCORE_NAME "sctp_core_worker"
/* If you support Multi-VRF how big to
* make the initial array of VRF's to.
*/
#define SCTP_DEFAULT_VRF_SIZE 4
/* constants for rto calc */
#define sctp_align_safe_nocopy 0
#define sctp_align_unsafe_makecopy 1
/* JRS - Values defined for the HTCP algorithm */
#define ALPHA_BASE (1<<7) /* 1.0 with shift << 7 */
#define BETA_MIN (1<<6) /* 0.5 with shift << 7 */
#define BETA_MAX 102 /* 0.8 with shift << 7 */
/* Places that CWND log can happen from */
#define SCTP_CWND_LOG_FROM_FR 1
#define SCTP_CWND_LOG_FROM_RTX 2
#define SCTP_CWND_LOG_FROM_BRST 3
#define SCTP_CWND_LOG_FROM_SS 4
#define SCTP_CWND_LOG_FROM_CA 5
#define SCTP_CWND_LOG_FROM_SAT 6
#define SCTP_BLOCK_LOG_INTO_BLK 7
#define SCTP_BLOCK_LOG_OUTOF_BLK 8
#define SCTP_BLOCK_LOG_CHECK 9
#define SCTP_STR_LOG_FROM_INTO_STRD 10
#define SCTP_STR_LOG_FROM_IMMED_DEL 11
#define SCTP_STR_LOG_FROM_INSERT_HD 12
#define SCTP_STR_LOG_FROM_INSERT_MD 13
#define SCTP_STR_LOG_FROM_INSERT_TL 14
#define SCTP_STR_LOG_FROM_MARK_TSN 15
#define SCTP_STR_LOG_FROM_EXPRS_DEL 16
#define SCTP_FR_LOG_BIGGEST_TSNS 17
#define SCTP_FR_LOG_STRIKE_TEST 18
#define SCTP_FR_LOG_STRIKE_CHUNK 19
#define SCTP_FR_T3_TIMEOUT 20
#define SCTP_MAP_PREPARE_SLIDE 21
#define SCTP_MAP_SLIDE_FROM 22
#define SCTP_MAP_SLIDE_RESULT 23
#define SCTP_MAP_SLIDE_CLEARED 24
#define SCTP_MAP_SLIDE_NONE 25
#define SCTP_FR_T3_MARK_TIME 26
#define SCTP_FR_T3_MARKED 27
#define SCTP_FR_T3_STOPPED 28
#define SCTP_FR_MARKED 30
#define SCTP_CWND_LOG_NOADV_SS 31
#define SCTP_CWND_LOG_NOADV_CA 32
#define SCTP_MAX_BURST_APPLIED 33
#define SCTP_MAX_IFP_APPLIED 34
#define SCTP_MAX_BURST_ERROR_STOP 35
#define SCTP_INCREASE_PEER_RWND 36
#define SCTP_DECREASE_PEER_RWND 37
#define SCTP_SET_PEER_RWND_VIA_SACK 38
#define SCTP_LOG_MBCNT_INCREASE 39
#define SCTP_LOG_MBCNT_DECREASE 40
#define SCTP_LOG_MBCNT_CHKSET 41
#define SCTP_LOG_NEW_SACK 42
#define SCTP_LOG_TSN_ACKED 43
#define SCTP_LOG_TSN_REVOKED 44
#define SCTP_LOG_LOCK_TCB 45
#define SCTP_LOG_LOCK_INP 46
#define SCTP_LOG_LOCK_SOCK 47
#define SCTP_LOG_LOCK_SOCKBUF_R 48
#define SCTP_LOG_LOCK_SOCKBUF_S 49
#define SCTP_LOG_LOCK_CREATE 50
#define SCTP_LOG_INITIAL_RTT 51
#define SCTP_LOG_RTTVAR 52
#define SCTP_LOG_SBALLOC 53
#define SCTP_LOG_SBFREE 54
#define SCTP_LOG_SBRESULT 55
#define SCTP_FR_DUPED 56
#define SCTP_FR_MARKED_EARLY 57
#define SCTP_FR_CWND_REPORT 58
#define SCTP_FR_CWND_REPORT_START 59
#define SCTP_FR_CWND_REPORT_STOP 60
#define SCTP_CWND_LOG_FROM_SEND 61
#define SCTP_CWND_INITIALIZATION 62
#define SCTP_CWND_LOG_FROM_T3 63
#define SCTP_CWND_LOG_FROM_SACK 64
#define SCTP_CWND_LOG_NO_CUMACK 65
#define SCTP_CWND_LOG_FROM_RESEND 66
#define SCTP_FR_LOG_CHECK_STRIKE 67
#define SCTP_SEND_NOW_COMPLETES 68
#define SCTP_CWND_LOG_FILL_OUTQ_CALLED 69
#define SCTP_CWND_LOG_FILL_OUTQ_FILLS 70
#define SCTP_LOG_FREE_SENT 71
#define SCTP_NAGLE_APPLIED 72
#define SCTP_NAGLE_SKIPPED 73
#define SCTP_WAKESND_FROM_SACK 74
#define SCTP_WAKESND_FROM_FWDTSN 75
#define SCTP_NOWAKE_FROM_SACK 76
#define SCTP_CWNDLOG_PRESEND 77
#define SCTP_CWNDLOG_ENDSEND 78
#define SCTP_AT_END_OF_SACK 79
#define SCTP_REASON_FOR_SC 80
#define SCTP_BLOCK_LOG_INTO_BLKA 81
#define SCTP_ENTER_USER_RECV 82
#define SCTP_USER_RECV_SACKS 83
#define SCTP_SORECV_BLOCKSA 84
#define SCTP_SORECV_BLOCKSB 85
#define SCTP_SORECV_DONE 86
#define SCTP_SACK_RWND_UPDATE 87
#define SCTP_SORECV_ENTER 88
#define SCTP_SORECV_ENTERPL 89
#define SCTP_MBUF_INPUT 90
#define SCTP_MBUF_IALLOC 91
#define SCTP_MBUF_IFREE 92
#define SCTP_MBUF_ICOPY 93
#define SCTP_MBUF_SPLIT 94
#define SCTP_SORCV_FREECTL 95
#define SCTP_SORCV_DOESCPY 96
#define SCTP_SORCV_DOESLCK 97
#define SCTP_SORCV_DOESADJ 98
#define SCTP_SORCV_BOTWHILE 99
#define SCTP_SORCV_PASSBF 100
#define SCTP_SORCV_ADJD 101
#define SCTP_UNKNOWN_MAX 102
#define SCTP_RANDY_STUFF 103
#define SCTP_RANDY_STUFF1 104
#define SCTP_STRMOUT_LOG_ASSIGN 105
#define SCTP_STRMOUT_LOG_SEND 106
#define SCTP_FLIGHT_LOG_DOWN_CA 107
#define SCTP_FLIGHT_LOG_UP 108
#define SCTP_FLIGHT_LOG_DOWN_GAP 109
#define SCTP_FLIGHT_LOG_DOWN_RSND 110
#define SCTP_FLIGHT_LOG_UP_RSND 111
#define SCTP_FLIGHT_LOG_DOWN_RSND_TO 112
#define SCTP_FLIGHT_LOG_DOWN_WP 113
#define SCTP_FLIGHT_LOG_UP_REVOKE 114
#define SCTP_FLIGHT_LOG_DOWN_PDRP 115
#define SCTP_FLIGHT_LOG_DOWN_PMTU 116
#define SCTP_SACK_LOG_NORMAL 117
#define SCTP_SACK_LOG_EXPRESS 118
#define SCTP_MAP_TSN_ENTERS 119
#define SCTP_THRESHOLD_CLEAR 120
#define SCTP_THRESHOLD_INCR 121
#define SCTP_FLIGHT_LOG_DWN_WP_FWD 122
#define SCTP_FWD_TSN_CHECK 123
#define SCTP_LOG_MAX_TYPES 124
/*
* To turn on various logging, you must first enable 'options KTR' and
* you might want to bump the entires 'options KTR_ENTRIES=80000'.
* To get something to log you define one of the logging defines.
* (see LINT).
*
* This gets the compile in place, but you still need to turn the
* logging flag on too in the sysctl (see in sctp.h).
*/
#define SCTP_LOG_EVENT_UNKNOWN 0
#define SCTP_LOG_EVENT_CWND 1
#define SCTP_LOG_EVENT_BLOCK 2
#define SCTP_LOG_EVENT_STRM 3
#define SCTP_LOG_EVENT_FR 4
#define SCTP_LOG_EVENT_MAP 5
#define SCTP_LOG_EVENT_MAXBURST 6
#define SCTP_LOG_EVENT_RWND 7
#define SCTP_LOG_EVENT_MBCNT 8
#define SCTP_LOG_EVENT_SACK 9
#define SCTP_LOG_LOCK_EVENT 10
#define SCTP_LOG_EVENT_RTT 11
#define SCTP_LOG_EVENT_SB 12
#define SCTP_LOG_EVENT_NAGLE 13
#define SCTP_LOG_EVENT_WAKE 14
#define SCTP_LOG_MISC_EVENT 15
#define SCTP_LOG_EVENT_CLOSE 16
#define SCTP_LOG_EVENT_MBUF 17
#define SCTP_LOG_CHUNK_PROC 18
#define SCTP_LOG_ERROR_RET 19
#define SCTP_LOG_MAX_EVENT 20
#define SCTP_LOCK_UNKNOWN 2
/* number of associations by default for zone allocation */
#define SCTP_MAX_NUM_OF_ASOC 40000
/* how many addresses per assoc remote and local */
#define SCTP_SCALE_FOR_ADDR 2
/* default MULTIPLE_ASCONF mode enable(1)/disable(0) value (sysctl) */
#define SCTP_DEFAULT_MULTIPLE_ASCONFS 0
/*
* Theshold for rwnd updates, we have to read (sb_hiwat >>
* SCTP_RWND_HIWAT_SHIFT) before we will look to see if we need to send a
* window update sack. When we look, we compare the last rwnd we sent vs the
* current rwnd. It too must be greater than this value. Using 3 divdes the
* hiwat by 8, so for 200k rwnd we need to read 24k. For a 64k rwnd we need
* to read 8k. This seems about right.. I hope :-D.. we do set a
* min of a MTU on it so if the rwnd is real small we will insist
* on a full MTU of 1500 bytes.
*/
#define SCTP_RWND_HIWAT_SHIFT 3
/* How much of the rwnd must the
* message be taking up to start partial delivery.
* We calculate this by shifing the hi_water (recv_win)
* left the following .. set to 1, when a message holds
* 1/2 the rwnd. If we set it to 2 when a message holds
* 1/4 the rwnd...etc..
*/
#define SCTP_PARTIAL_DELIVERY_SHIFT 1
/*
* default HMAC for cookies, etc... use one of the AUTH HMAC id's
* SCTP_HMAC is the HMAC_ID to use
* SCTP_SIGNATURE_SIZE is the digest length
*/
#define SCTP_HMAC SCTP_AUTH_HMAC_ID_SHA1
#define SCTP_SIGNATURE_SIZE SCTP_AUTH_DIGEST_LEN_SHA1
#define SCTP_SIGNATURE_ALOC_SIZE SCTP_SIGNATURE_SIZE
/*
* the SCTP protocol signature this includes the version number encoded in
* the last 4 bits of the signature.
*/
#define PROTO_SIGNATURE_A 0x30000000
#define SCTP_VERSION_NUMBER 0x3
#define MAX_TSN 0xffffffff
/* how many executions every N tick's */
#define SCTP_ITERATOR_MAX_AT_ONCE 20
/* number of clock ticks between iterator executions */
#define SCTP_ITERATOR_TICKS 1
/*
* option: If you comment out the following you will receive the old behavior
* of obeying cwnd for the fast retransmit algorithm. With this defined a FR
* happens right away with-out waiting for the flightsize to drop below the
* cwnd value (which is reduced by the FR to 1/2 the inflight packets).
*/
#define SCTP_IGNORE_CWND_ON_FR 1
/*
* Adds implementors guide behavior to only use newest highest update in SACK
* gap ack's to figure out if you need to stroke a chunk for FR.
*/
#define SCTP_NO_FR_UNLESS_SEGMENT_SMALLER 1
/* default max I can burst out after a fast retransmit, 0 disables it */
#define SCTP_DEF_MAX_BURST 4
#define SCTP_DEF_HBMAX_BURST 4
#define SCTP_DEF_FRMAX_BURST 4
/* RTO calculation flag to say if it
* is safe to determine local lan or not.
*/
#define SCTP_RTT_FROM_NON_DATA 0
#define SCTP_RTT_FROM_DATA 1
/* IP hdr (20/40) + 12+2+2 (enet) + sctp common 12 */
#define SCTP_FIRST_MBUF_RESV 68
/* Packet transmit states in the sent field */
#define SCTP_DATAGRAM_UNSENT 0
#define SCTP_DATAGRAM_SENT 1
#define SCTP_DATAGRAM_RESEND1 2 /* not used (in code, but may
* hit this value) */
#define SCTP_DATAGRAM_RESEND2 3 /* not used (in code, but may
* hit this value) */
#define SCTP_DATAGRAM_RESEND 4
#define SCTP_DATAGRAM_ACKED 10010
#define SCTP_DATAGRAM_MARKED 20010
#define SCTP_FORWARD_TSN_SKIP 30010
#define SCTP_DATAGRAM_NR_ACKED 40010
/* chunk output send from locations */
#define SCTP_OUTPUT_FROM_USR_SEND 0
#define SCTP_OUTPUT_FROM_T3 1
#define SCTP_OUTPUT_FROM_INPUT_ERROR 2
#define SCTP_OUTPUT_FROM_CONTROL_PROC 3
#define SCTP_OUTPUT_FROM_SACK_TMR 4
#define SCTP_OUTPUT_FROM_SHUT_TMR 5
#define SCTP_OUTPUT_FROM_HB_TMR 6
#define SCTP_OUTPUT_FROM_SHUT_ACK_TMR 7
#define SCTP_OUTPUT_FROM_ASCONF_TMR 8
#define SCTP_OUTPUT_FROM_STRRST_TMR 9
#define SCTP_OUTPUT_FROM_AUTOCLOSE_TMR 10
#define SCTP_OUTPUT_FROM_EARLY_FR_TMR 11
#define SCTP_OUTPUT_FROM_STRRST_REQ 12
#define SCTP_OUTPUT_FROM_USR_RCVD 13
#define SCTP_OUTPUT_FROM_COOKIE_ACK 14
#define SCTP_OUTPUT_FROM_DRAIN 15
#define SCTP_OUTPUT_FROM_CLOSING 16
#define SCTP_OUTPUT_FROM_SOCKOPT 17
/* SCTP chunk types are moved sctp.h for application (NAT, FW) use */
/* align to 32-bit sizes */
#define SCTP_SIZE32(x) ((((x) + 3) >> 2) << 2)
#define IS_SCTP_CONTROL(a) ((a)->chunk_type != SCTP_DATA)
#define IS_SCTP_DATA(a) ((a)->chunk_type == SCTP_DATA)
/* SCTP parameter types */
/*************0x0000 series*************/
#define SCTP_HEARTBEAT_INFO 0x0001
#define SCTP_IPV4_ADDRESS 0x0005
#define SCTP_IPV6_ADDRESS 0x0006
#define SCTP_STATE_COOKIE 0x0007
#define SCTP_UNRECOG_PARAM 0x0008
#define SCTP_COOKIE_PRESERVE 0x0009
#define SCTP_HOSTNAME_ADDRESS 0x000b
#define SCTP_SUPPORTED_ADDRTYPE 0x000c
/* draft-ietf-stewart-tsvwg-strreset-xxx */
#define SCTP_STR_RESET_OUT_REQUEST 0x000d
#define SCTP_STR_RESET_IN_REQUEST 0x000e
#define SCTP_STR_RESET_TSN_REQUEST 0x000f
#define SCTP_STR_RESET_RESPONSE 0x0010
#define SCTP_STR_RESET_ADD_OUT_STREAMS 0x0011
#define SCTP_STR_RESET_ADD_IN_STREAMS 0x0012
#define SCTP_MAX_RESET_PARAMS 2
#define SCTP_STREAM_RESET_TSN_DELTA 0x1000
/*************0x4000 series*************/
/*************0x8000 series*************/
#define SCTP_ECN_CAPABLE 0x8000
/* draft-ietf-tsvwg-auth-xxx */
#define SCTP_RANDOM 0x8002
#define SCTP_CHUNK_LIST 0x8003
#define SCTP_HMAC_LIST 0x8004
/*
* draft-ietf-tsvwg-addip-sctp-xx param=0x8008 len=0xNNNN Byte | Byte | Byte
* | Byte Byte | Byte ...
*
* Where each byte is a chunk type extension supported. For example, to support
* all chunks one would have (in hex):
*
* 80 01 00 09 C0 C1 80 81 82 00 00 00
*
* Has the parameter. C0 = PR-SCTP (RFC3758) C1, 80 = ASCONF (addip draft) 81
* = Packet Drop 82 = Stream Reset 83 = Authentication
*/
#define SCTP_SUPPORTED_CHUNK_EXT 0x8008
/*************0xC000 series*************/
#define SCTP_PRSCTP_SUPPORTED 0xc000
/* draft-ietf-tsvwg-addip-sctp */
#define SCTP_ADD_IP_ADDRESS 0xc001
#define SCTP_DEL_IP_ADDRESS 0xc002
#define SCTP_ERROR_CAUSE_IND 0xc003
#define SCTP_SET_PRIM_ADDR 0xc004
#define SCTP_SUCCESS_REPORT 0xc005
#define SCTP_ULP_ADAPTATION 0xc006
/* behave-nat-draft */
#define SCTP_HAS_NAT_SUPPORT 0xc007
#define SCTP_NAT_VTAGS 0xc008
/* bits for TOS field */
#define SCTP_ECT0_BIT 0x02
#define SCTP_ECT1_BIT 0x01
#define SCTP_CE_BITS 0x03
/* below turns off above */
#define SCTP_FLEXIBLE_ADDRESS 0x20
#define SCTP_NO_HEARTBEAT 0x40
/* mask to get sticky */
#define SCTP_STICKY_OPTIONS_MASK 0x0c
/*
* SCTP states for internal state machine XXX (should match "user" values)
*/
#define SCTP_STATE_EMPTY 0x0000
#define SCTP_STATE_INUSE 0x0001
#define SCTP_STATE_COOKIE_WAIT 0x0002
#define SCTP_STATE_COOKIE_ECHOED 0x0004
#define SCTP_STATE_OPEN 0x0008
#define SCTP_STATE_SHUTDOWN_SENT 0x0010
#define SCTP_STATE_SHUTDOWN_RECEIVED 0x0020
#define SCTP_STATE_SHUTDOWN_ACK_SENT 0x0040
#define SCTP_STATE_SHUTDOWN_PENDING 0x0080
#define SCTP_STATE_CLOSED_SOCKET 0x0100
#define SCTP_STATE_ABOUT_TO_BE_FREED 0x0200
#define SCTP_STATE_PARTIAL_MSG_LEFT 0x0400
#define SCTP_STATE_WAS_ABORTED 0x0800
#define SCTP_STATE_IN_ACCEPT_QUEUE 0x1000
#define SCTP_STATE_MASK 0x007f
#define SCTP_GET_STATE(asoc) ((asoc)->state & SCTP_STATE_MASK)
#define SCTP_SET_STATE(asoc, newstate) ((asoc)->state = ((asoc)->state & ~SCTP_STATE_MASK) | newstate)
#define SCTP_CLEAR_SUBSTATE(asoc, substate) ((asoc)->state &= ~substate)
#define SCTP_ADD_SUBSTATE(asoc, substate) ((asoc)->state |= substate)
/* SCTP reachability state for each address */
#define SCTP_ADDR_REACHABLE 0x001
#define SCTP_ADDR_NO_PMTUD 0x002
#define SCTP_ADDR_NOHB 0x004
#define SCTP_ADDR_BEING_DELETED 0x008
#define SCTP_ADDR_NOT_IN_ASSOC 0x010
#define SCTP_ADDR_OUT_OF_SCOPE 0x080
#define SCTP_ADDR_UNCONFIRMED 0x200
#define SCTP_ADDR_REQ_PRIMARY 0x400
/* JRS 5/13/07 - Added potentially failed state for CMT PF */
#define SCTP_ADDR_PF 0x800
/* bound address types (e.g. valid address types to allow) */
#define SCTP_BOUND_V6 0x01
#define SCTP_BOUND_V4 0x02
/*
* what is the default number of mbufs in a chain I allow before switching to
* a cluster
*/
#define SCTP_DEFAULT_MBUFS_IN_CHAIN 5
/* How long a cookie lives in milli-seconds */
#define SCTP_DEFAULT_COOKIE_LIFE 60000
/* Maximum the mapping array will grow to (TSN mapping array) */
#define SCTP_MAPPING_ARRAY 512
/* size of the inital malloc on the mapping array */
#define SCTP_INITIAL_MAPPING_ARRAY 16
/* how much we grow the mapping array each call */
#define SCTP_MAPPING_ARRAY_INCR 32
/*
* Here we define the timer types used by the implementation as arguments in
* the set/get timer type calls.
*/
#define SCTP_TIMER_INIT 0
#define SCTP_TIMER_RECV 1
#define SCTP_TIMER_SEND 2
#define SCTP_TIMER_HEARTBEAT 3
#define SCTP_TIMER_PMTU 4
#define SCTP_TIMER_MAXSHUTDOWN 5
#define SCTP_TIMER_SIGNATURE 6
/*
* number of timer types in the base SCTP structure used in the set/get and
* has the base default.
*/
#define SCTP_NUM_TMRS 7
/* timer types */
#define SCTP_TIMER_TYPE_NONE 0
#define SCTP_TIMER_TYPE_SEND 1
#define SCTP_TIMER_TYPE_INIT 2
#define SCTP_TIMER_TYPE_RECV 3
#define SCTP_TIMER_TYPE_SHUTDOWN 4
#define SCTP_TIMER_TYPE_HEARTBEAT 5
#define SCTP_TIMER_TYPE_COOKIE 6
#define SCTP_TIMER_TYPE_NEWCOOKIE 7
#define SCTP_TIMER_TYPE_PATHMTURAISE 8
#define SCTP_TIMER_TYPE_SHUTDOWNACK 9
#define SCTP_TIMER_TYPE_ASCONF 10
#define SCTP_TIMER_TYPE_SHUTDOWNGUARD 11
#define SCTP_TIMER_TYPE_AUTOCLOSE 12
#define SCTP_TIMER_TYPE_EVENTWAKE 13
#define SCTP_TIMER_TYPE_STRRESET 14
#define SCTP_TIMER_TYPE_INPKILL 15
#define SCTP_TIMER_TYPE_ASOCKILL 16
#define SCTP_TIMER_TYPE_ADDR_WQ 17
#define SCTP_TIMER_TYPE_ZERO_COPY 18
#define SCTP_TIMER_TYPE_ZCOPY_SENDQ 19
#define SCTP_TIMER_TYPE_PRIM_DELETED 20
/* add new timers here - and increment LAST */
#define SCTP_TIMER_TYPE_LAST 21
#define SCTP_IS_TIMER_TYPE_VALID(t) (((t) > SCTP_TIMER_TYPE_NONE) && \
((t) < SCTP_TIMER_TYPE_LAST))
/* max number of TSN's dup'd that I will hold */
#define SCTP_MAX_DUP_TSNS 20
/*
* Here we define the types used when setting the retry amounts.
*/
/* How many drop re-attempts we make on INIT/COOKIE-ECHO */
#define SCTP_RETRY_DROPPED_THRESH 4
/*
* Maxmium number of chunks a single association can have on it. Note that
* this is a squishy number since the count can run over this if the user
* sends a large message down .. the fragmented chunks don't count until
* AFTER the message is on queue.. it would be the next send that blocks
* things. This number will get tuned up at boot in the sctp_init and use the
* number of clusters as a base. This way high bandwidth environments will
* not get impacted by the lower bandwidth sending a bunch of 1 byte chunks
*/
#define SCTP_ASOC_MAX_CHUNKS_ON_QUEUE 512
/* The conversion from time to ticks and vice versa is done by rounding
* upwards. This way we can test in the code the time to be positive and
* know that this corresponds to a positive number of ticks.
*/
#define MSEC_TO_TICKS(x) ((hz == 1000) ? x : ((((x) * hz) + 999) / 1000))
#define TICKS_TO_MSEC(x) ((hz == 1000) ? x : ((((x) * 1000) + (hz - 1)) / hz))
#define SEC_TO_TICKS(x) ((x) * hz)
#define TICKS_TO_SEC(x) (((x) + (hz - 1)) / hz)
/*
* Basically the minimum amount of time before I do a early FR. Making this
* value to low will cause duplicate retransmissions.
*/
#define SCTP_MINFR_MSEC_TIMER 250
/* The floor this value is allowed to fall to when starting a timer. */
#define SCTP_MINFR_MSEC_FLOOR 20
/* init timer def = 1 sec */
#define SCTP_INIT_SEC 1
/* send timer def = 1 seconds */
#define SCTP_SEND_SEC 1
/* recv timer def = 200ms */
#define SCTP_RECV_MSEC 200
/* 30 seconds + RTO (in ms) */
#define SCTP_HB_DEFAULT_MSEC 30000
/* Max time I will wait for Shutdown to complete */
#define SCTP_DEF_MAX_SHUTDOWN_SEC 180
/*
* This is how long a secret lives, NOT how long a cookie lives how many
* ticks the current secret will live.
*/
#define SCTP_DEFAULT_SECRET_LIFE_SEC 3600
#define SCTP_RTO_UPPER_BOUND (60000) /* 60 sec in ms */
#define SCTP_RTO_LOWER_BOUND (1000) /* 1 sec is ms */
#define SCTP_RTO_INITIAL (3000) /* 3 sec in ms */
#define SCTP_INP_KILL_TIMEOUT 20/* number of ms to retry kill of inpcb */
#define SCTP_ASOC_KILL_TIMEOUT 10 /* number of ms to retry kill of inpcb */
#define SCTP_DEF_MAX_INIT 8
#define SCTP_DEF_MAX_SEND 10
#define SCTP_DEF_MAX_PATH_RTX 5
#define SCTP_DEF_PATH_PF_THRESHOLD SCTP_DEF_MAX_PATH_RTX
#define SCTP_DEF_PMTU_RAISE_SEC 600 /* 10 min between raise attempts */
/* How many streams I request initally by default */
#define SCTP_OSTREAM_INITIAL 10
#define SCTP_ISTREAM_INITIAL 2048
/*
* How many smallest_mtu's need to increase before a window update sack is
* sent (should be a power of 2).
*/
/* Send window update (incr * this > hiwat). Should be a power of 2 */
#define SCTP_MINIMAL_RWND (4096) /* minimal rwnd */
#define SCTP_ADDRMAX 16
/* SCTP DEBUG Switch parameters */
#define SCTP_DEBUG_TIMER1 0x00000001
#define SCTP_DEBUG_TIMER2 0x00000002 /* unused */
#define SCTP_DEBUG_TIMER3 0x00000004 /* unused */
#define SCTP_DEBUG_TIMER4 0x00000008
#define SCTP_DEBUG_OUTPUT1 0x00000010
#define SCTP_DEBUG_OUTPUT2 0x00000020
#define SCTP_DEBUG_OUTPUT3 0x00000040
#define SCTP_DEBUG_OUTPUT4 0x00000080
#define SCTP_DEBUG_UTIL1 0x00000100
#define SCTP_DEBUG_UTIL2 0x00000200 /* unused */
#define SCTP_DEBUG_AUTH1 0x00000400
#define SCTP_DEBUG_AUTH2 0x00000800 /* unused */
#define SCTP_DEBUG_INPUT1 0x00001000
#define SCTP_DEBUG_INPUT2 0x00002000
#define SCTP_DEBUG_INPUT3 0x00004000
#define SCTP_DEBUG_INPUT4 0x00008000 /* unused */
#define SCTP_DEBUG_ASCONF1 0x00010000
#define SCTP_DEBUG_ASCONF2 0x00020000
#define SCTP_DEBUG_OUTPUT5 0x00040000 /* unused */
#define SCTP_DEBUG_XXX 0x00080000 /* unused */
#define SCTP_DEBUG_PCB1 0x00100000
#define SCTP_DEBUG_PCB2 0x00200000 /* unused */
#define SCTP_DEBUG_PCB3 0x00400000
#define SCTP_DEBUG_PCB4 0x00800000
#define SCTP_DEBUG_INDATA1 0x01000000
#define SCTP_DEBUG_INDATA2 0x02000000 /* unused */
#define SCTP_DEBUG_INDATA3 0x04000000 /* unused */
#define SCTP_DEBUG_CRCOFFLOAD 0x08000000 /* unused */
#define SCTP_DEBUG_USRREQ1 0x10000000 /* unused */
#define SCTP_DEBUG_USRREQ2 0x20000000 /* unused */
#define SCTP_DEBUG_PEEL1 0x40000000
#define SCTP_DEBUG_XXXXX 0x80000000 /* unused */
#define SCTP_DEBUG_ALL 0x7ff3ffff
#define SCTP_DEBUG_NOISY 0x00040000
/* What sender needs to see to avoid SWS or we consider peers rwnd 0 */
#define SCTP_SWS_SENDER_DEF 1420
/*
* SWS is scaled to the sb_hiwat of the socket. A value of 2 is hiwat/4, 1
* would be hiwat/2 etc.
*/
/* What receiver needs to see in sockbuf or we tell peer its 1 */
#define SCTP_SWS_RECEIVER_DEF 3000
#define SCTP_INITIAL_CWND 4380
#define SCTP_DEFAULT_MTU 1500 /* emergency default MTU */
/* amount peer is obligated to have in rwnd or I will abort */
#define SCTP_MIN_RWND 1500
#define SCTP_DEFAULT_MAXSEGMENT 65535
#define SCTP_CHUNK_BUFFER_SIZE 512
#define SCTP_PARAM_BUFFER_SIZE 512
/* small chunk store for looking at chunk_list in auth */
#define SCTP_SMALL_CHUNK_STORE 260
#define SCTP_HOW_MANY_SECRETS 2 /* how many secrets I keep */
#define SCTP_NUMBER_OF_SECRETS 8 /* or 8 * 4 = 32 octets */
#define SCTP_SECRET_SIZE 32 /* number of octets in a 256 bits */
/*
* SCTP upper layer notifications
*/
#define SCTP_NOTIFY_ASSOC_UP 1
#define SCTP_NOTIFY_ASSOC_DOWN 2
#define SCTP_NOTIFY_INTERFACE_DOWN 3
#define SCTP_NOTIFY_INTERFACE_UP 4
#define SCTP_NOTIFY_SENT_DG_FAIL 5
#define SCTP_NOTIFY_UNSENT_DG_FAIL 6
#define SCTP_NOTIFY_SPECIAL_SP_FAIL 7
#define SCTP_NOTIFY_ASSOC_LOC_ABORTED 8
#define SCTP_NOTIFY_ASSOC_REM_ABORTED 9
#define SCTP_NOTIFY_ASSOC_RESTART 10
#define SCTP_NOTIFY_PEER_SHUTDOWN 11
#define SCTP_NOTIFY_ASCONF_ADD_IP 12
#define SCTP_NOTIFY_ASCONF_DELETE_IP 13
#define SCTP_NOTIFY_ASCONF_SET_PRIMARY 14
#define SCTP_NOTIFY_PARTIAL_DELVIERY_INDICATION 15
#define SCTP_NOTIFY_INTERFACE_CONFIRMED 16
#define SCTP_NOTIFY_STR_RESET_RECV 17
#define SCTP_NOTIFY_STR_RESET_SEND 18
#define SCTP_NOTIFY_STR_RESET_FAILED_OUT 19
#define SCTP_NOTIFY_STR_RESET_FAILED_IN 20
#define SCTP_NOTIFY_STR_RESET_DENIED_OUT 21
#define SCTP_NOTIFY_STR_RESET_DENIED_IN 22
#define SCTP_NOTIFY_AUTH_NEW_KEY 23
#define SCTP_NOTIFY_AUTH_FREE_KEY 24
#define SCTP_NOTIFY_NO_PEER_AUTH 25
#define SCTP_NOTIFY_SENDER_DRY 26
#define SCTP_NOTIFY_REMOTE_ERROR 27
/* This is the value for messages that are NOT completely
* copied down where we will start to split the message.
* So, with our default, we split only if the piece we
* want to take will fill up a full MTU (assuming
* a 1500 byte MTU).
*/
#define SCTP_DEFAULT_SPLIT_POINT_MIN 2904
/* Maximum length of diagnostic information in error causes */
#define SCTP_DIAG_INFO_LEN 64
/* ABORT CODES and other tell-tale location
* codes are generated by adding the below
* to the instance id.
*/
/* File defines */
#define SCTP_FROM_SCTP_INPUT 0x10000000
#define SCTP_FROM_SCTP_PCB 0x20000000
#define SCTP_FROM_SCTP_INDATA 0x30000000
#define SCTP_FROM_SCTP_TIMER 0x40000000
#define SCTP_FROM_SCTP_USRREQ 0x50000000
#define SCTP_FROM_SCTPUTIL 0x60000000
#define SCTP_FROM_SCTP6_USRREQ 0x70000000
#define SCTP_FROM_SCTP_ASCONF 0x80000000
#define SCTP_FROM_SCTP_OUTPUT 0x90000000
#define SCTP_FROM_SCTP_PEELOFF 0xa0000000
#define SCTP_FROM_SCTP_PANDA 0xb0000000
#define SCTP_FROM_SCTP_SYSCTL 0xc0000000
#define SCTP_FROM_SCTP_CC_FUNCTIONS 0xd0000000
/* Location ID's */
#define SCTP_LOC_1 0x00000001
#define SCTP_LOC_2 0x00000002
#define SCTP_LOC_3 0x00000003
#define SCTP_LOC_4 0x00000004
#define SCTP_LOC_5 0x00000005
#define SCTP_LOC_6 0x00000006
#define SCTP_LOC_7 0x00000007
#define SCTP_LOC_8 0x00000008
#define SCTP_LOC_9 0x00000009
#define SCTP_LOC_10 0x0000000a
#define SCTP_LOC_11 0x0000000b
#define SCTP_LOC_12 0x0000000c
#define SCTP_LOC_13 0x0000000d
#define SCTP_LOC_14 0x0000000e
#define SCTP_LOC_15 0x0000000f
#define SCTP_LOC_16 0x00000010
#define SCTP_LOC_17 0x00000011
#define SCTP_LOC_18 0x00000012
#define SCTP_LOC_19 0x00000013
#define SCTP_LOC_20 0x00000014
#define SCTP_LOC_21 0x00000015
#define SCTP_LOC_22 0x00000016
#define SCTP_LOC_23 0x00000017
#define SCTP_LOC_24 0x00000018
#define SCTP_LOC_25 0x00000019
#define SCTP_LOC_26 0x0000001a
#define SCTP_LOC_27 0x0000001b
#define SCTP_LOC_28 0x0000001c
#define SCTP_LOC_29 0x0000001d
#define SCTP_LOC_30 0x0000001e
#define SCTP_LOC_31 0x0000001f
#define SCTP_LOC_32 0x00000020
#define SCTP_LOC_33 0x00000021
#define SCTP_LOC_34 0x00000022
#define SCTP_LOC_35 0x00000023
/* Free assoc codes */
#define SCTP_NORMAL_PROC 0
#define SCTP_PCBFREE_NOFORCE 1
#define SCTP_PCBFREE_FORCE 2
/* From codes for adding addresses */
#define SCTP_ADDR_IS_CONFIRMED 8
#define SCTP_ADDR_DYNAMIC_ADDED 6
#define SCTP_IN_COOKIE_PROC 100
#define SCTP_ALLOC_ASOC 1
#define SCTP_LOAD_ADDR_2 2
#define SCTP_LOAD_ADDR_3 3
#define SCTP_LOAD_ADDR_4 4
#define SCTP_LOAD_ADDR_5 5
#define SCTP_DONOT_SETSCOPE 0
#define SCTP_DO_SETSCOPE 1
/* This value determines the default for when
* we try to add more on the send queue., if
* there is room. This prevents us from cycling
* into the copy_resume routine to often if
* we have not got enough space to add a decent
* enough size message. Note that if we have enough
* space to complete the message copy we will always
* add to the message, no matter what the size. Its
* only when we reach the point that we have some left
* to add, there is only room for part of it that we
* will use this threshold. Its also a sysctl.
*/
#define SCTP_DEFAULT_ADD_MORE 1452
#ifndef SCTP_PCBHASHSIZE
/* default number of association hash buckets in each endpoint */
#define SCTP_PCBHASHSIZE 256
#endif
#ifndef SCTP_TCBHASHSIZE
#define SCTP_TCBHASHSIZE 1024
#endif
#ifndef SCTP_CHUNKQUEUE_SCALE
#define SCTP_CHUNKQUEUE_SCALE 10
#endif
/* clock variance is 1 ms */
#define SCTP_CLOCK_GRANULARITY 1
#define IP_HDR_SIZE 40 /* we use the size of a IP6 header here this
* detracts a small amount for ipv4 but it
* simplifies the ipv6 addition */
/* Argument magic number for sctp_inpcb_free() */
/* third argument */
#define SCTP_CALLED_DIRECTLY_NOCMPSET 0
#define SCTP_CALLED_AFTER_CMPSET_OFCLOSE 1
#define SCTP_CALLED_FROM_INPKILL_TIMER 2
/* second argument */
#define SCTP_FREE_SHOULD_USE_ABORT 1
#define SCTP_FREE_SHOULD_USE_GRACEFUL_CLOSE 0
#ifndef IPPROTO_SCTP
#define IPPROTO_SCTP 132 /* the Official IANA number :-) */
#endif /* !IPPROTO_SCTP */
#define SCTP_MAX_DATA_BUNDLING 256
/* modular comparison */
/* See RFC 1982 for details. */
#define SCTP_SSN_GT(a, b) (((a < b) && ((uint16_t)(b - a) > (1U<<15))) || \
((a > b) && ((uint16_t)(a - b) < (1U<<15))))
#define SCTP_SSN_GE(a, b) (SCTP_SSN_GT(a, b) || (a == b))
#define SCTP_TSN_GT(a, b) (((a < b) && ((uint32_t)(b - a) > (1U<<31))) || \
((a > b) && ((uint32_t)(a - b) < (1U<<31))))
#define SCTP_TSN_GE(a, b) (SCTP_TSN_GT(a, b) || (a == b))
/* Mapping array manipulation routines */
#define SCTP_IS_TSN_PRESENT(arry, gap) ((arry[(gap >> 3)] >> (gap & 0x07)) & 0x01)
#define SCTP_SET_TSN_PRESENT(arry, gap) (arry[(gap >> 3)] |= (0x01 << ((gap & 0x07))))
#define SCTP_UNSET_TSN_PRESENT(arry, gap) (arry[(gap >> 3)] &= ((~(0x01 << ((gap & 0x07)))) & 0xff))
#define SCTP_CALC_TSN_TO_GAP(gap, tsn, mapping_tsn) do { \
if (tsn >= mapping_tsn) { \
gap = tsn - mapping_tsn; \
} else { \
gap = (MAX_TSN - mapping_tsn) + tsn + 1; \
} \
} while (0)
#define SCTP_RETRAN_DONE -1
#define SCTP_RETRAN_EXIT -2
/*
* This value defines the number of vtag block time wait entry's per list
* element. Each entry will take 2 4 byte ints (and of course the overhead
* of the next pointer as well). Using 15 as an example will yield * ((8 *
* 15) + 8) or 128 bytes of overhead for each timewait block that gets
* initialized. Increasing it to 31 would yeild 256 bytes per block.
*/
#define SCTP_NUMBER_IN_VTAG_BLOCK 15
/*
* If we use the STACK option, we have an array of this size head pointers.
* This array is mod'd the with the size to find which bucket and then all
* entries must be searched to see if the tag is in timed wait. If so we
* reject it.
*/
#define SCTP_STACK_VTAG_HASH_SIZE 32
/*
* Number of seconds of time wait for a vtag.
*/
#define SCTP_TIME_WAIT 60
/* How many micro seconds is the cutoff from
* local lan type rtt's
*/
/*
* We allow 900us for the rtt.
*/
#define SCTP_LOCAL_LAN_RTT 900
#define SCTP_LAN_UNKNOWN 0
#define SCTP_LAN_LOCAL 1
#define SCTP_LAN_INTERNET 2
#define SCTP_SEND_BUFFER_SPLITTING 0x00000001
#define SCTP_RECV_BUFFER_SPLITTING 0x00000002
/* The system retains a cache of free chunks such to
* cut down on calls the memory allocation system. There
* is a per association limit of free items and a overall
* system limit. If either one gets hit then the resource
* stops being cached.
*/
#define SCTP_DEF_ASOC_RESC_LIMIT 10
#define SCTP_DEF_SYSTEM_RESC_LIMIT 1000
/*-
* defines for socket lock states.
* Used by __APPLE__ and SCTP_SO_LOCK_TESTING
*/
#define SCTP_SO_LOCKED 1
#define SCTP_SO_NOT_LOCKED 0
#define SCTP_HOLDS_LOCK 1
#define SCTP_NOT_LOCKED 0
/*-
* For address locks, do we hold the lock?
*/
#define SCTP_ADDR_LOCKED 1
#define SCTP_ADDR_NOT_LOCKED 0
#define IN4_ISPRIVATE_ADDRESS(a) \
((((uint8_t *)&(a)->s_addr)[0] == 10) || \
((((uint8_t *)&(a)->s_addr)[0] == 172) && \
(((uint8_t *)&(a)->s_addr)[1] >= 16) && \
(((uint8_t *)&(a)->s_addr)[1] <= 32)) || \
((((uint8_t *)&(a)->s_addr)[0] == 192) && \
(((uint8_t *)&(a)->s_addr)[1] == 168)))
#define IN4_ISLOOPBACK_ADDRESS(a) \
((((uint8_t *)&(a)->s_addr)[0] == 127) && \
(((uint8_t *)&(a)->s_addr)[1] == 0) && \
(((uint8_t *)&(a)->s_addr)[2] == 0) && \
(((uint8_t *)&(a)->s_addr)[3] == 1))
#define IN4_ISLINKLOCAL_ADDRESS(a) \
((((uint8_t *)&(a)->s_addr)[0] == 169) && \
(((uint8_t *)&(a)->s_addr)[1] == 254))
#if defined(_KERNEL)
#define SCTP_GETTIME_TIMEVAL(x) (getmicrouptime(x))
#define SCTP_GETPTIME_TIMEVAL(x) (microuptime(x))
#endif
#if defined(_KERNEL) || defined(__Userspace__)
#define sctp_sowwakeup(inp, so) \
do { \
if (inp->sctp_flags & SCTP_PCB_FLAGS_DONT_WAKE) { \
inp->sctp_flags |= SCTP_PCB_FLAGS_WAKEOUTPUT; \
} else { \
sowwakeup(so); \
} \
} while (0)
#define sctp_sowwakeup_locked(inp, so) \
do { \
if (inp->sctp_flags & SCTP_PCB_FLAGS_DONT_WAKE) { \
SOCKBUF_UNLOCK(&((so)->so_snd)); \
inp->sctp_flags |= SCTP_PCB_FLAGS_WAKEOUTPUT; \
} else { \
sowwakeup_locked(so); \
} \
} while (0)
#define sctp_sorwakeup(inp, so) \
do { \
if (inp->sctp_flags & SCTP_PCB_FLAGS_DONT_WAKE) { \
inp->sctp_flags |= SCTP_PCB_FLAGS_WAKEINPUT; \
} else { \
sorwakeup(so); \
} \
} while (0)
#define sctp_sorwakeup_locked(inp, so) \
do { \
if (inp->sctp_flags & SCTP_PCB_FLAGS_DONT_WAKE) { \
inp->sctp_flags |= SCTP_PCB_FLAGS_WAKEINPUT; \
SOCKBUF_UNLOCK(&((so)->so_rcv)); \
} else { \
sorwakeup_locked(so); \
} \
} while (0)
#endif /* _KERNEL || __Userspace__ */
#endif
|
Java
|
{% load applicationcontent_tags i18n %}
{% include "base/widget/_base_begin.html" %}
<div id="{{ widget.fe_identifier }}" class="{{ widget.render_base_classes }}" {% if widget.enter_effect_style != 'disabled' %}data-aos="{{ widget.enter_effect_style }}"{% endif %}{% if widget.enter_effect_duration %}data-aos-duration="{{ widget.enter_effect_duration }}"{% endif %} {% if widget.enter_effect_delay %}data-aos-delay="{{ widget.enter_effect_delay }}"{% endif %} {% if widget.enter_effect_offset %}data-aos-offset="{{ widget.enter_effect_offset }}"{% endif %} data-aos-once="{% if widget.enter_effect_iteration == 0 %}false{% elif widget.enter_effect_iteration == 1 %}true{% endif %}">
<div class="jumbotron {{ widget.render_content_classes }}">
{% if request.frontend_editing %}
<div class="widget-tools">
{% include "base/widget/_edit.html" %}
</div>
{% endif %}
{% block title %}
{% if widget.label %}
<a id="{{ widget.label|slugify }}"></a>
<h2 class="widget-title"><span>{{ widget.label }}</span></h2>
{% endif %}
{% endblock %}
{% block content %}{% endblock %}
</div>
</div>
{% include "base/widget/_base_end.html" %}
|
Java
|
<?php
/*=========================================================================
MIDAS Server
Copyright (c) Kitware SAS. 20 rue de la Villette. All rights reserved.
69328 Lyon, FRANCE.
See Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
/** Assetstore Model Base*/
abstract class AssetstoreModelBase extends AppModel
{
/** Constructor*/
public function __construct()
{
parent::__construct();
$this->_name = 'assetstore';
$this->_key = 'assetstore_id';
$this->_mainData = array(
'assetstore_id' => array('type' => MIDAS_DATA),
'name' => array('type' => MIDAS_DATA),
'itemrevision_id' => array('type' => MIDAS_DATA),
'path' => array('type' => MIDAS_DATA),
'type' => array('type' => MIDAS_DATA),
'bitstreams' => array('type' => MIDAS_ONE_TO_MANY, 'model' => 'Bitstream', 'parent_column' => 'assetstore_id', 'child_column' => 'assetstore_id'),
);
$this->initialize(); // required
} // end __construct()
/** Abstract functions */
abstract function getAll();
/** save an assetsore*/
public function save($dao)
{
parent::save($dao);
}
/** delete an assetstore (and all the items in it)*/
public function delete($dao)
{
if(!$dao instanceof AssetstoreDao)
{
throw new Zend_Exception("Error param.");
}
$bitreams = $dao->getBitstreams();
$items = array();
foreach($bitreams as $key => $bitstream)
{
$revision = $bitstream->getItemrevision();
if(empty($revision))
{
continue;
}
$item = $revision->getItem();
if(empty($item))
{
continue;
}
$items[$item->getKey()] = $item;
}
$modelLoader = new MIDAS_ModelLoader();
$item_model = $modelLoader->loadModel('Item');
foreach($items as $item)
{
$item_model->delete($item);
}
parent::delete($dao);
}// delete
} // end class AssetstoreModelBase
|
Java
|
package eu.monnetproject.util;
import java.util.*;
/**
* Utility function to syntactically sugar properties for OSGi.
* This allows you to create a property map as follows
* <code>Props.prop("key1","value1")</code><br/>
* <code> .prop("key2","value2")</code>
*/
public final class Props {
public static PropsMap prop(String key, Object value) {
PropsMap pm = new PropsMap();
pm.put(key,value);
return pm;
}
public static class PropsMap extends Hashtable<String,Object> {
public PropsMap prop(String key, Object value) {
put(key,value);
return this;
}
}
}
|
Java
|
#!/usr/bin/env python
import sys
from os.path import *
import os
from pyflann import *
from copy import copy
from numpy import *
from numpy.random import *
import unittest
class Test_PyFLANN_nn(unittest.TestCase):
def setUp(self):
self.nn = FLANN(log_level="warning")
################################################################################
# The typical
def test_nn_2d_10pt(self):
self.__nd_random_test_autotune(2, 2)
def test_nn_autotune_2d_1000pt(self):
self.__nd_random_test_autotune(2, 1000)
def test_nn_autotune_100d_1000pt(self):
self.__nd_random_test_autotune(100, 1000)
def test_nn_autotune_500d_100pt(self):
self.__nd_random_test_autotune(500, 100)
#
# ##########################################################################################
# # Stress it should handle
#
def test_nn_stress_1d_1pt_kmeans_autotune(self):
self.__nd_random_test_autotune(1, 1)
def __ensure_list(self,arg):
if type(arg)!=list:
return [arg]
else:
return arg
def __nd_random_test_autotune(self, dim, N, num_neighbors = 1, **kwargs):
"""
Make a set of random points, then pass the same ones to the
query points. Each point should be closest to itself.
"""
seed(0)
x = rand(N, dim)
xq = rand(N, dim)
perm = permutation(N)
# compute ground truth nearest neighbors
gt_idx, gt_dist = self.nn.nn(x,xq,
algorithm='linear',
num_neighbors=num_neighbors)
for tp in [0.70, 0.80, 0.90]:
nidx,ndist = self.nn.nn(x, xq,
algorithm='autotuned',
sample_fraction=1.0,
num_neighbors = num_neighbors,
target_precision = tp, checks=-2, **kwargs)
correctness = 0.0
for i in xrange(N):
l1 = self.__ensure_list(nidx[i])
l2 = self.__ensure_list(gt_idx[i])
correctness += float(len(set(l1).intersection(l2)))/num_neighbors
correctness /= N
self.assert_(correctness >= tp*0.9,
'failed #1: targ_prec=%f, N=%d,correctness=%f' % (tp, N, correctness))
if __name__ == '__main__':
unittest.main()
|
Java
|
# -*- coding: utf-8 -*-
from collections import OrderedDict
import locale
from optparse import make_option
from verify.management.commands import VerifyBaseCommand
from verify.models import *
from verify.politici_models import *
from django.db.models import Q, Count
__author__ = 'guglielmo'
class Command(VerifyBaseCommand):
"""
Report delle statistiche di genere complessive, a livello nazionale,
per tutti gli organi di tutte le istituzioni.
Può limitarsi a una o più istituzioni, se si passa un elenco di institution_id
"""
args = '<institution_id institution_id ...>'
help = "Check that all locations have only male components (list locations with female components)."
option_list = VerifyBaseCommand.option_list
def execute_verification(self, *args, **options):
self.csv_headers = ["ISTITUZIONE", "INCARICO", "N_DONNE", "N_UOMINI", "N_TOTALI", "PERC_DONNE", "PERC_UOMINI"]
institutions = OpInstitution.objects.using('politici').all()
if args:
institutions = institutions.filter(id__in=args)
self.logger.info(
"Verification {0} launched with institutions limited to {1}".format(
self.__class__.__module__, ",".join(institutions.values_list('id', flat=True))
)
)
else:
self.logger.info(
"Verification {0} launched for all institutions".format(
self.__class__.__module__
)
)
self.ok_locs = []
self.ko_locs = []
for institution in institutions:
charge_types_ids = OpInstitutionCharge.objects.using('politici').\
filter(date_end__isnull=True,
content__deleted_at__isnull=True).\
filter(institution=institution).\
values_list('charge_type', flat=True).\
distinct()
charge_types = OpChargeType.objects.using('politici').\
filter(id__in=charge_types_ids)
for charge_type in charge_types:
self.logger.info(
"Counting {0} in {1}".format(
charge_type.name, institution.name
)
)
qs = OpInstitutionCharge.objects.using('politici').\
filter(date_end__isnull=True,
content__deleted_at__isnull=True).\
filter(institution=institution,
charge_type=charge_type)
n_tot = qs.count()
n_fem = qs.filter(politician__sex__iexact='f').count()
n_mal = n_tot - n_fem
merged = [institution.name, charge_type.name, n_fem, n_mal, n_tot,]
merged.append(locale.format("%.2f",100. * n_fem / float(n_tot) ))
merged.append(locale.format("%.2f",100. * n_mal / float(n_tot) ))
self.ko_locs.append(merged)
outcome = Verification.OUTCOME.failed
self.logger.info(
"Report for {0} institutions generated.".format(
len(self.ko_locs)
)
)
return outcome
|
Java
|
#ifndef __KIDS_CONFIG_H_
#define __KIDS_CONFIG_H_
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#define NLIMIT_NORMAL 0
#define NLIMIT_NETWORKSTORE 1
#define NLIMIT_PUBSUB 2
struct LimitConfig {
int hard_limit_bytes;
int soft_limit_bytes;
int soft_limit_seconds;
};
struct StoreConfig {
~StoreConfig() {
for (std::vector<StoreConfig*>::iterator it = stores.begin(); it != stores.end(); ++it) {
delete *it;
}
}
std::string type;
std::string buffer_type;
std::string socket;
std::string host;
std::string port;
std::string path;
std::string name;
std::string rotate;
std::string success;
std::string topic;
std::vector<StoreConfig*> stores;
};
struct KidsConfig {
KidsConfig() : store(NULL) { memset(nlimit, 0, sizeof(nlimit)); }
~KidsConfig() { delete store; }
std::string listen_socket;
std::string listen_host;
std::string listen_port;
std::string log_level;
std::string log_file;
std::string max_clients;
std::string worker_threads;
std::string ignore_case;
LimitConfig nlimit[3];
StoreConfig *store;
};
struct Token {
Token() {}
Token(int tid, char *s, char *e) {
id = tid;
while (s < e) {
value.push_back(*s);
s++;
}
}
int id;
std::string value;
};
struct KeyValue {
KeyValue(std::string k, std::vector<std::string>* v)
:key(k), value(*v) {}
std::string key;
std::vector<std::string> value;
};
struct ParseContext {
ParseContext() : line(0), success(true), conf(NULL) {}
~ParseContext() { delete conf; }
int line;
bool success;
char error[1025];
KidsConfig *conf;
};
ParseContext *ParseConfigFile(const std::string& filename);
ParseContext *ParseConfig(std::string str);
#endif // __KIDS_CONFIG_H_
|
Java
|
/*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2008-2016. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
package edu.wpi.first.wpilibj;
import edu.wpi.first.wpilibj.hal.FRCNetComm.tResourceType;
import edu.wpi.first.wpilibj.hal.HAL;
import edu.wpi.first.wpilibj.hal.HAL;
/**
* Handle input from standard Joysticks connected to the Driver Station. This class handles standard
* input that comes from the Driver Station. Each time a value is requested the most recent value is
* returned. There is a single class instance for each joystick and the mapping of ports to hardware
* buttons depends on the code in the driver station.
*/
public class Joystick extends GenericHID {
static final byte kDefaultXAxis = 0;
static final byte kDefaultYAxis = 1;
static final byte kDefaultZAxis = 2;
static final byte kDefaultTwistAxis = 2;
static final byte kDefaultThrottleAxis = 3;
static final int kDefaultTriggerButton = 1;
static final int kDefaultTopButton = 2;
/**
* Represents an analog axis on a joystick.
*/
public enum AxisType {
kX(0), kY(1), kZ(2), kTwist(3), kThrottle(4), kNumAxis(5);
@SuppressWarnings("MemberName")
public final int value;
private AxisType(int value) {
this.value = value;
}
}
/**
* Represents a digital button on the JoyStick.
*/
public enum ButtonType {
kTrigger(0), kTop(1), kNumButton(2);
@SuppressWarnings("MemberName")
public final int value;
private ButtonType(int value) {
this.value = value;
}
}
/**
* Represents a rumble output on the JoyStick.
*/
public enum RumbleType {
kLeftRumble, kRightRumble
}
private final DriverStation m_ds;
private final int m_port;
private final byte[] m_axes;
private final byte[] m_buttons;
private int m_outputs;
private short m_leftRumble;
private short m_rightRumble;
/**
* Construct an instance of a joystick. The joystick index is the usb port on the drivers
* station.
*
* @param port The port on the driver station that the joystick is plugged into.
*/
public Joystick(final int port) {
this(port, AxisType.kNumAxis.value, ButtonType.kNumButton.value);
m_axes[AxisType.kX.value] = kDefaultXAxis;
m_axes[AxisType.kY.value] = kDefaultYAxis;
m_axes[AxisType.kZ.value] = kDefaultZAxis;
m_axes[AxisType.kTwist.value] = kDefaultTwistAxis;
m_axes[AxisType.kThrottle.value] = kDefaultThrottleAxis;
m_buttons[ButtonType.kTrigger.value] = kDefaultTriggerButton;
m_buttons[ButtonType.kTop.value] = kDefaultTopButton;
HAL.report(tResourceType.kResourceType_Joystick, port);
}
/**
* Protected version of the constructor to be called by sub-classes.
*
* <p>This constructor allows the subclass to configure the number of constants for axes and
* buttons.
*
* @param port The port on the driver station that the joystick is plugged into.
* @param numAxisTypes The number of axis types in the enum.
* @param numButtonTypes The number of button types in the enum.
*/
protected Joystick(int port, int numAxisTypes, int numButtonTypes) {
m_ds = DriverStation.getInstance();
m_axes = new byte[numAxisTypes];
m_buttons = new byte[numButtonTypes];
m_port = port;
}
/**
* Get the X value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The X value of the joystick.
*/
public double getX(Hand hand) {
return getRawAxis(m_axes[AxisType.kX.value]);
}
/**
* Get the Y value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The Y value of the joystick.
*/
public double getY(Hand hand) {
return getRawAxis(m_axes[AxisType.kY.value]);
}
/**
* Get the Z value of the joystick. This depends on the mapping of the joystick connected to the
* current port.
*
* @param hand Unused
* @return The Z value of the joystick.
*/
public double getZ(Hand hand) {
return getRawAxis(m_axes[AxisType.kZ.value]);
}
/**
* Get the twist value of the current joystick. This depends on the mapping of the joystick
* connected to the current port.
*
* @return The Twist value of the joystick.
*/
public double getTwist() {
return getRawAxis(m_axes[AxisType.kTwist.value]);
}
/**
* Get the throttle value of the current joystick. This depends on the mapping of the joystick
* connected to the current port.
*
* @return The Throttle value of the joystick.
*/
public double getThrottle() {
return getRawAxis(m_axes[AxisType.kThrottle.value]);
}
/**
* Get the value of the axis.
*
* @param axis The axis to read, starting at 0.
* @return The value of the axis.
*/
public double getRawAxis(final int axis) {
return m_ds.getStickAxis(m_port, axis);
}
/**
* For the current joystick, return the axis determined by the argument.
*
* <p>This is for cases where the joystick axis is returned programatically, otherwise one of the
* previous functions would be preferable (for example getX()).
*
* @param axis The axis to read.
* @return The value of the axis.
*/
public double getAxis(final AxisType axis) {
switch (axis) {
case kX:
return getX();
case kY:
return getY();
case kZ:
return getZ();
case kTwist:
return getTwist();
case kThrottle:
return getThrottle();
default:
return 0.0;
}
}
/**
* For the current joystick, return the number of axis.
*/
public int getAxisCount() {
return m_ds.getStickAxisCount(m_port);
}
/**
* Read the state of the trigger on the joystick.
*
* <p>Look up which button has been assigned to the trigger and read its state.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the trigger.
*/
public boolean getTrigger(Hand hand) {
return getRawButton(m_buttons[ButtonType.kTrigger.value]);
}
/**
* Read the state of the top button on the joystick.
*
* <p>Look up which button has been assigned to the top and read its state.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the top button.
*/
public boolean getTop(Hand hand) {
return getRawButton(m_buttons[ButtonType.kTop.value]);
}
/**
* This is not supported for the Joystick. This method is only here to complete the GenericHID
* interface.
*
* @param hand This parameter is ignored for the Joystick class and is only here to complete the
* GenericHID interface.
* @return The state of the bumper (always false)
*/
public boolean getBumper(Hand hand) {
return false;
}
/**
* Get the button value (starting at button 1).
*
* <p>The appropriate button is returned as a boolean value.
*
* @param button The button number to be read (starting at 1).
* @return The state of the button.
*/
public boolean getRawButton(final int button) {
return m_ds.getStickButton(m_port, (byte) button);
}
/**
* For the current joystick, return the number of buttons.
*/
public int getButtonCount() {
return m_ds.getStickButtonCount(m_port);
}
/**
* Get the angle in degrees of a POV on the joystick.
*
* <p>The POV angles start at 0 in the up direction, and increase clockwise (eg right is 90,
* upper-left is 315).
*
* @param pov The index of the POV to read (starting at 0)
* @return the angle of the POV in degrees, or -1 if the POV is not pressed.
*/
public int getPOV(int pov) {
return m_ds.getStickPOV(m_port, pov);
}
/**
* For the current joystick, return the number of POVs.
*/
public int getPOVCount() {
return m_ds.getStickPOVCount(m_port);
}
/**
* Get buttons based on an enumerated type.
*
* <p>The button type will be looked up in the list of buttons and then read.
*
* @param button The type of button to read.
* @return The state of the button.
*/
public boolean getButton(ButtonType button) {
switch (button) {
case kTrigger:
return getTrigger();
case kTop:
return getTop();
default:
return false;
}
}
/**
* Get the magnitude of the direction vector formed by the joystick's current position relative to
* its origin.
*
* @return The magnitude of the direction vector
*/
public double getMagnitude() {
return Math.sqrt(Math.pow(getX(), 2) + Math.pow(getY(), 2));
}
/**
* Get the direction of the vector formed by the joystick and its origin in radians.
*
* @return The direction of the vector in radians
*/
public double getDirectionRadians() {
return Math.atan2(getX(), -getY());
}
/**
* Get the direction of the vector formed by the joystick and its origin in degrees.
*
* <p>Uses acos(-1) to represent Pi due to absence of readily accessable Pi constant in C++
*
* @return The direction of the vector in degrees
*/
public double getDirectionDegrees() {
return Math.toDegrees(getDirectionRadians());
}
/**
* Get the channel currently associated with the specified axis.
*
* @param axis The axis to look up the channel for.
* @return The channel fr the axis.
*/
public int getAxisChannel(AxisType axis) {
return m_axes[axis.value];
}
/**
* Set the channel associated with a specified axis.
*
* @param axis The axis to set the channel for.
* @param channel The channel to set the axis to.
*/
public void setAxisChannel(AxisType axis, int channel) {
m_axes[axis.value] = (byte) channel;
}
/**
* Get the value of isXbox for the current joystick.
*
* @return A boolean that is true if the controller is an xbox controller.
*/
public boolean getIsXbox() {
return m_ds.getJoystickIsXbox(m_port);
}
/**
* Get the HID type of the current joystick.
*
* @return The HID type value of the current joystick.
*/
public int getType() {
return m_ds.getJoystickType(m_port);
}
/**
* Get the name of the current joystick.
*
* @return The name of the current joystick.
*/
public String getName() {
return m_ds.getJoystickName(m_port);
}
/**
* Get the port number of the joystick.
*
* @return The port number of the joystick.
*/
public int getPort() {
return m_port;
}
/**
* Get the axis type of a joystick axis.
*
* @return the axis type of a joystick axis.
*/
public int getAxisType(int axis) {
return m_ds.getJoystickAxisType(m_port, axis);
}
/**
* Set the rumble output for the joystick. The DS currently supports 2 rumble values, left rumble
* and right rumble.
*
* @param type Which rumble value to set
* @param value The normalized value (0 to 1) to set the rumble to
*/
public void setRumble(RumbleType type, float value) {
if (value < 0) {
value = 0;
} else if (value > 1) {
value = 1;
}
if (type == RumbleType.kLeftRumble) {
m_leftRumble = (short) (value * 65535);
} else {
m_rightRumble = (short) (value * 65535);
}
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
/**
* Set a single HID output value for the joystick.
*
* @param outputNumber The index of the output to set (1-32)
* @param value The value to set the output to
*/
public void setOutput(int outputNumber, boolean value) {
m_outputs = (m_outputs & ~(1 << (outputNumber - 1))) | ((value ? 1 : 0) << (outputNumber - 1));
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
/**
* Set all HID output values for the joystick.
*
* @param value The 32 bit output value (1 bit for each output)
*/
public void setOutputs(int value) {
m_outputs = value;
HAL.setJoystickOutputs((byte) m_port, m_outputs, m_leftRumble, m_rightRumble);
}
}
|
Java
|
package sdp
func (s Session) appendAttributes(attrs Attributes) Session {
for _, v := range attrs {
if v.Value == blank {
s = s.AddFlag(v.Key)
} else {
s = s.AddAttribute(v.Key, v.Value)
}
}
return s
}
// Append encodes message to Session and returns result.
//
// See RFC 4566 Section 5.
func (m *Message) Append(s Session) Session {
s = s.AddVersion(m.Version)
s = s.AddOrigin(m.Origin)
s = s.AddSessionName(m.Name)
if len(m.Info) > 0 {
s = s.AddSessionInfo(m.Info)
}
if len(m.URI) > 0 {
s = s.AddURI(m.URI)
}
if len(m.Email) > 0 {
s = s.AddEmail(m.Email)
}
if len(m.Phone) > 0 {
s = s.AddPhone(m.Phone)
}
if !m.Connection.Blank() {
s = s.AddConnectionData(m.Connection)
}
for t, v := range m.Bandwidths {
s = s.AddBandwidth(t, v)
}
// One or more time descriptions ("t=" and "r=" lines)
for _, t := range m.Timing {
s = s.AddTiming(t.Start, t.End)
if len(t.Offsets) > 0 {
s = s.AddRepeatTimesCompact(t.Repeat, t.Active, t.Offsets...)
}
}
if len(m.TZAdjustments) > 0 {
s = s.AddTimeZones(m.TZAdjustments...)
}
if !m.Encryption.Blank() {
s = s.AddEncryption(m.Encryption)
}
s = s.appendAttributes(m.Attributes)
for i := range m.Medias {
s = s.AddMediaDescription(m.Medias[i].Description)
if len(m.Medias[i].Title) > 0 {
s = s.AddSessionInfo(m.Medias[i].Title)
}
if !m.Medias[i].Connection.Blank() {
s = s.AddConnectionData(m.Medias[i].Connection)
}
for t, v := range m.Medias[i].Bandwidths {
s = s.AddBandwidth(t, v)
}
if !m.Medias[i].Encryption.Blank() {
s = s.AddEncryption(m.Medias[i].Encryption)
}
s = s.appendAttributes(m.Medias[i].Attributes)
}
return s
}
|
Java
|
<?php
if(!class_exists('AbstractQueuedJob')) return;
/**
* A Job for running a external link check for published pages
*
*/
class CheckLinksJob extends AbstractQueuedJob implements QueuedJob {
public function getTitle() {
return _t('CheckLinksJob.TITLE', 'Checking for broken links');
}
public function getJobType() {
return QueuedJob::QUEUED;
}
public function getSignature() {
return md5(get_class($this));
}
/**
* Check an individual page
*/
public function process() {
$task = CheckLinksTask::create();
$track = $task->runLinksCheck(1);
$this->currentStep = $track->CompletedPages;
$this->totalSteps = $track->TotalPages;
$this->isComplete = $track->Status === 'Completed';
}
}
|
Java
|
// Copyright 2010-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef MOZC_WIN32_BASE_OMAHA_UTIL_H_
#define MOZC_WIN32_BASE_OMAHA_UTIL_H_
// Omaha is the code name of Google Update, which is not used in
// OSS version of Mozc.
#if !defined(GOOGLE_JAPANESE_INPUT_BUILD)
#error OmahaUtil must be used with Google Japanese Input, not OSS Mozc
#endif // !GOOGLE_JAPANESE_INPUT_BUILD
#include <windows.h>
#include <string>
#include "base/port.h"
namespace mozc {
namespace win32 {
// TODO(yukawa): Add unit test for this class.
class OmahaUtil {
public:
// Writes the channel name specified by |value| for Omaha.
// Returns true if the operation completed successfully.
static bool WriteChannel(const wstring &value);
// Reads the channel name for Omaha.
// Returns an empty string if there is no entry or fails to retrieve the
// channel name.
static wstring ReadChannel();
// Clears the registry entry to specify error message for Omaha.
// Returns true if the operation completed successfully.
static bool ClearOmahaError();
// Writes the registry entry for Omaha to show some error messages.
// Returns true if the operation completed successfully.
static bool WriteOmahaError(const wstring &ui_message, const wstring &header);
// Clears the registry entry for the channel name.
// Returns true if the operation completed successfully.
static bool ClearChannel();
private:
DISALLOW_COPY_AND_ASSIGN(OmahaUtil);
};
} // namespace win32
} // namespace mozc
#endif // MOZC_WIN32_BASE_OMAHA_UTIL_H_
|
Java
|
#!/usr/bin/env python
from distutils.core import setup
setup(name='django-modeltranslation',
version='0.4.0-alpha1',
description='Translates Django models using a registration approach.',
long_description='The modeltranslation application can be used to '
'translate dynamic content of existing models to an '
'arbitrary number of languages without having to '
'change the original model classes. It uses a '
'registration approach (comparable to Django\'s admin '
'app) to be able to add translations to existing or '
'new projects and is fully integrated into the Django '
'admin backend.',
author='Peter Eschler',
author_email='p.eschler@nmy.de',
maintainer='Dirk Eschler',
maintainer_email='d.eschler@nmy.de',
url='http://code.google.com/p/django-modeltranslation/',
packages=['modeltranslation', 'modeltranslation.management',
'modeltranslation.management.commands'],
package_data={'modeltranslation': ['static/modeltranslation/css/*.css',
'static/modeltranslation/js/*.js']},
include_package_data = True,
requires=['django(>=1.0)'],
download_url='http://django-modeltranslation.googlecode.com/files/django-modeltranslation-0.4.0-alpha1.tar.gz',
classifiers=['Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License'],
license='New BSD')
|
Java
|
<div class="row">
<div class="col-xs-12">
<div class="box">
<?= \yii\grid\GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
'idadvert',
[
'label' => 'title',
'value' => 'title',
],
'user.email',
'price',
'created_at:datetime',
[
'class' => 'yii\grid\ActionColumn',
'template' => '{view} {delete}',
'buttons' => [
'view' => function ($url, $model, $key) {
return \yii\helpers\Html::a("<span class=\"glyphicon glyphicon-eye-open\"></span>", Yii::$app->params['baseUrl']. "/view-advert/".$key, ['target' => '_blank']);
}
],
]
],
]) ?>
</div>
</div>
</div>
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>DHAIR2: PatientAssociate Class Reference</title>
<link href="../../doxygen.css" rel="stylesheet" type="text/css">
<link href="../../tabs.css" rel="stylesheet" type="text/css">
</head><body>
<!-- Generated by Doxygen 1.5.6 -->
<div class="navigation" id="top">
<div class="tabs">
<ul>
<li><a href="../../index.html"><span>Main Page</span></a></li>
<li><a href="../../namespaces.html"><span>Namespaces</span></a></li>
<li class="current"><a href="../../annotated.html"><span>Classes</span></a></li>
<li>
<form action="../../search.php" method="get">
<table cellspacing="0" cellpadding="0" border="0">
<tr>
<td><label> <u>S</u>earch for </label></td>
<td><input type="text" name="query" value="" size="20" accesskey="s"/></td>
</tr>
</table>
</form>
</li>
</ul>
</div>
<div class="tabs">
<ul>
<li><a href="../../annotated.html"><span>Class List</span></a></li>
<li><a href="../../hierarchy.html"><span>Class Hierarchy</span></a></li>
<li><a href="../../functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div class="contents">
<h1>PatientAssociate Class Reference</h1><!-- doxytag: class="PatientAssociate" --><!-- doxytag: inherits="AppModel" --><div class="dynheader">
Inheritance diagram for PatientAssociate:</div>
<div class="dynsection">
<p><center><img src="../../de/d63/classPatientAssociate.png" usemap="#PatientAssociate_map" border="0" alt=""></center>
<map name="PatientAssociate_map">
</map>
</div>
<p>
<a href="../../d5/d8a/classPatientAssociate-members.html">List of all members.</a><table border="0" cellpadding="0" cellspacing="0">
<tr><td></td></tr>
<tr><td colspan="2"><br><h2>Public Member Functions</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="3163fd014a399c0dccb94d3d7cae6932"></a><!-- doxytag: member="PatientAssociate::countForPatientJournal" ref="3163fd014a399c0dccb94d3d7cae6932" args="($patient_id)" -->
</td><td class="memItemRight" valign="bottom"><b>countForPatientJournal</b> ($patient_id)</td></tr>
<tr><td colspan="2"><br><h2>Public Attributes</h2></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="821f8762aba39015c29fed74ff3e7a7f"></a><!-- doxytag: member="PatientAssociate::$name" ref="821f8762aba39015c29fed74ff3e7a7f" args="" -->
</td><td class="memItemRight" valign="bottom"><b>$name</b> = "PatientAssociate"</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="1b477ef9589643785b5f6a7c7f3f394d"></a><!-- doxytag: member="PatientAssociate::$useTable" ref="1b477ef9589643785b5f6a7c7f3f394d" args="" -->
</td><td class="memItemRight" valign="bottom"><b>$useTable</b> = "patients_associates"</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="78b87fcff6874c80559dce177d1bb35d"></a><!-- doxytag: member="PatientAssociate::$primaryKey" ref="78b87fcff6874c80559dce177d1bb35d" args="" -->
</td><td class="memItemRight" valign="bottom"><b>$primaryKey</b> = "id"</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="6a54b69164de94dc59049ad7460aacca"></a><!-- doxytag: member="PatientAssociate::$belongsTo" ref="6a54b69164de94dc59049ad7460aacca" args="" -->
</td><td class="memItemRight" valign="bottom"><b>$belongsTo</b> = array("Patient", "<a class="el" href="../../d1/d41/classAssociate.html">Associate</a>")</td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"> </td><td class="memItemRight" valign="bottom"><b>$hasAndBelongsToMany</b></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="66a8e0acf7290babaf0a38825346adea"></a><!-- doxytag: member="PatientAssociate::$validate" ref="66a8e0acf7290babaf0a38825346adea" args="" -->
</td><td class="memItemRight" valign="bottom"><b>$validate</b></td></tr>
<tr><td class="memItemLeft" nowrap align="right" valign="top"><a class="anchor" name="0ca548fc0bc60b7022c1d70038ccc9d0"></a><!-- doxytag: member="PatientAssociate::$count" ref="0ca548fc0bc60b7022c1d70038ccc9d0" args="" -->
return </td><td class="memItemRight" valign="bottom"><b>$count</b></td></tr>
</table>
<hr><a name="_details"></a><h2>Detailed Description</h2>
Copyright 2013 University of Washington, School of Nursing. <a href="http://opensource.org/licenses/BSD-3-Clause">http://opensource.org/licenses/BSD-3-Clause</a> <hr><h2>Member Data Documentation</h2>
<a class="anchor" name="b323350ddab8b46be3e6d56e4b8df364"></a><!-- doxytag: member="PatientAssociate::$hasAndBelongsToMany" ref="b323350ddab8b46be3e6d56e4b8df364" args="" -->
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">PatientAssociate::$hasAndBelongsToMany </td>
</tr>
</table>
</div>
<div class="memdoc">
<p>
<b>Initial value:</b><div class="fragment"><pre class="fragment"> array(<span class="stringliteral">"Subscale"</span> =>
array(<span class="stringliteral">'className'</span> => <span class="stringliteral">"Subscale"</span>,
<span class="stringliteral">'joinTable'</span> => <span class="stringliteral">"patients_associates_subscales"</span>,
<span class="stringliteral">'foreignKey'</span> => <span class="stringliteral">"patient_associate_id"</span>,
<span class="stringliteral">"dependent"</span> => <span class="keyword">true</span>,
<span class="stringliteral">'associationForeignKey'</span> => <span class="stringliteral">'subscale_id'</span>
))
</pre></div>
</div>
</div><p>
<hr>The documentation for this class was generated from the following file:<ul>
<li>/var/lib/jenkins/jobs/CPRO doc auto-generation - GitHub Repo/workspace/app/Model/PatientAssociate.php</ul>
</div>
<hr size="1"><address style="text-align: right;"><small>Generated on Mon Dec 23 10:49:47 2013 for DHAIR2 by
<a href="http://www.doxygen.org/index.html">
<img src="../../doxygen.png" alt="doxygen" align="middle" border="0"></a> 1.5.6 </small></address>
</body>
</html>
|
Java
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Border Properties</title>
<style type="text/css">
<!--
.style1 {
font-family: Arial;
font-size: 10pt;
}
-->
</style>
</head>
<BODY>
<P class=style1><IMG height=270 src="screenshots/Border Properties Dialog.jpg" width=363></P>
<P class=style1>Border properties dialog defines borders of the balloons (both
static and dynamic). This doesn't apply to other items. </P>
</BODY>
</html>
|
Java
|
#include "stdfx.h"
//#include "tfxparam.h"
#include "trop.h"
//===================================================================
class PremultiplyFx : public TStandardRasterFx {
FX_PLUGIN_DECLARATION(PremultiplyFx)
TRasterFxPort m_input;
public:
PremultiplyFx() { addInputPort("Source", m_input); }
~PremultiplyFx(){};
bool doGetBBox(double frame, TRectD &bBox, const TRenderSettings &info) {
if (m_input.isConnected())
return m_input->doGetBBox(frame, bBox, info);
else {
bBox = TRectD();
return false;
}
}
void doCompute(TTile &tile, double frame, const TRenderSettings &ri);
bool canHandle(const TRenderSettings &info, double frame) { return true; }
};
//------------------------------------------------------------------------------
void PremultiplyFx::doCompute(TTile &tile, double frame,
const TRenderSettings &ri) {
if (!m_input.isConnected()) return;
m_input->compute(tile, frame, ri);
TRop::premultiply(tile.getRaster());
}
FX_PLUGIN_IDENTIFIER(PremultiplyFx, "premultiplyFx");
|
Java
|
/* $NetBSD: proc.h,v 1.8 1996/11/25 22:09:11 gwr Exp $ */
/*
* Copyright (c) 1991, 1993
* The Regents of the University of California. 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, 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 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.
*
* from: proc.h 8.1 (Berkeley) 6/10/93
*/
/*
* Machine-dependent part of the proc structure for sun3.
*/
struct mdproc {
int *md_regs; /* registers on current frame */
int md_flags; /* machine-dependent flags */
};
/* md_flags */
#define MDP_FPUSED 0x0001 /* floating point coprocessor used */
#define MDP_STACKADJ 0x0002 /* frame SP adjusted, might have to
undo when system call returns
ERESTART. */
#define MDP_HPUXTRACE 0x0004 /* being traced by HP-UX process */
|
Java
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/components/phonehub/multidevice_setup_state_updater.h"
#include "ash/components/phonehub/pref_names.h"
#include "ash/components/phonehub/util/histogram_util.h"
#include "base/callback_helpers.h"
#include "chromeos/components/multidevice/logging/logging.h"
#include "chromeos/services/multidevice_setup/public/cpp/prefs.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
namespace chromeos {
namespace phonehub {
namespace {
using multidevice_setup::mojom::Feature;
using multidevice_setup::mojom::FeatureState;
using multidevice_setup::mojom::HostStatus;
} // namespace
// static
void MultideviceSetupStateUpdater::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterBooleanPref(prefs::kIsAwaitingVerifiedHost, false);
}
MultideviceSetupStateUpdater::MultideviceSetupStateUpdater(
PrefService* pref_service,
multidevice_setup::MultiDeviceSetupClient* multidevice_setup_client,
NotificationAccessManager* notification_access_manager)
: pref_service_(pref_service),
multidevice_setup_client_(multidevice_setup_client),
notification_access_manager_(notification_access_manager) {
multidevice_setup_client_->AddObserver(this);
notification_access_manager_->AddObserver(this);
}
MultideviceSetupStateUpdater::~MultideviceSetupStateUpdater() {
multidevice_setup_client_->RemoveObserver(this);
notification_access_manager_->RemoveObserver(this);
}
void MultideviceSetupStateUpdater::OnNotificationAccessChanged() {
switch (notification_access_manager_->GetAccessStatus()) {
case NotificationAccessManager::AccessStatus::kAccessGranted:
if (IsWaitingForAccessToInitiallyEnableNotifications()) {
PA_LOG(INFO) << "Enabling PhoneHubNotifications for the first time now "
<< "that access has been granted by the phone.";
multidevice_setup_client_->SetFeatureEnabledState(
Feature::kPhoneHubNotifications, /*enabled=*/true,
/*auth_token=*/absl::nullopt, base::DoNothing());
}
break;
case NotificationAccessManager::AccessStatus::kAvailableButNotGranted:
FALLTHROUGH;
case NotificationAccessManager::AccessStatus::kProhibited:
// Disable kPhoneHubNotifications if notification access has been revoked
// by the phone.
PA_LOG(INFO) << "Disabling PhoneHubNotifications feature.";
multidevice_setup_client_->SetFeatureEnabledState(
Feature::kPhoneHubNotifications, /*enabled=*/false,
/*auth_token=*/absl::nullopt, base::DoNothing());
break;
}
}
void MultideviceSetupStateUpdater::OnHostStatusChanged(
const multidevice_setup::MultiDeviceSetupClient::HostStatusWithDevice&
host_device_with_status) {
EnablePhoneHubIfAwaitingVerifiedHost();
}
void MultideviceSetupStateUpdater::OnFeatureStatesChanged(
const multidevice_setup::MultiDeviceSetupClient::FeatureStatesMap&
feature_state_map) {
EnablePhoneHubIfAwaitingVerifiedHost();
}
bool MultideviceSetupStateUpdater::
IsWaitingForAccessToInitiallyEnableNotifications() const {
// If the Phone Hub notifications feature has never been explicitly set, we
// should enable it after
// 1. the top-level Phone Hub feature is enabled, and
// 2. the phone has granted access.
// We do *not* want disrupt the feature state if it was already explicitly set
// by the user.
return multidevice_setup::IsDefaultFeatureEnabledValue(
Feature::kPhoneHubNotifications, pref_service_) &&
multidevice_setup_client_->GetFeatureState(Feature::kPhoneHub) ==
FeatureState::kEnabledByUser;
}
void MultideviceSetupStateUpdater::EnablePhoneHubIfAwaitingVerifiedHost() {
bool is_awaiting_verified_host =
pref_service_->GetBoolean(prefs::kIsAwaitingVerifiedHost);
const HostStatus host_status =
multidevice_setup_client_->GetHostStatus().first;
const FeatureState feature_state =
multidevice_setup_client_->GetFeatureState(Feature::kPhoneHub);
// Enable the PhoneHub feature if the phone is verified and there was an
// intent to enable the feature. We also ensure that the feature is currently
// disabled and not in state like kNotSupportedByPhone or kProhibitedByPolicy.
if (is_awaiting_verified_host && host_status == HostStatus::kHostVerified &&
feature_state == FeatureState::kDisabledByUser) {
multidevice_setup_client_->SetFeatureEnabledState(
Feature::kPhoneHub, /*enabled=*/true, /*auth_token=*/absl::nullopt,
base::DoNothing());
util::LogFeatureOptInEntryPoint(util::OptInEntryPoint::kSetupFlow);
}
UpdateIsAwaitingVerifiedHost();
}
void MultideviceSetupStateUpdater::UpdateIsAwaitingVerifiedHost() {
// Wait to enable Phone Hub until after host phone is verified. The intent to
// enable Phone Hub must be persisted in the event that this class is
// destroyed before the phone is verified.
const HostStatus host_status =
multidevice_setup_client_->GetHostStatus().first;
if (host_status ==
HostStatus::kHostSetLocallyButWaitingForBackendConfirmation) {
pref_service_->SetBoolean(prefs::kIsAwaitingVerifiedHost, true);
return;
}
// The intent to enable Phone Hub after host verification was fulfilled.
// Note: We don't want to reset the pref if, say, the host status is
// kNoEligibleHosts; that might just be a transient state seen during
// start-up, for instance. It is true that we don't want to enable Phone Hub
// if the user explicitly disabled it in settings, however, that can only
// occur after the host becomes verified and we first enable Phone Hub.
const bool is_awaiting_verified_host =
pref_service_->GetBoolean(prefs::kIsAwaitingVerifiedHost);
const FeatureState feature_state =
multidevice_setup_client_->GetFeatureState(Feature::kPhoneHub);
if (is_awaiting_verified_host && host_status == HostStatus::kHostVerified &&
feature_state == FeatureState::kEnabledByUser) {
pref_service_->SetBoolean(prefs::kIsAwaitingVerifiedHost, false);
return;
}
}
} // namespace phonehub
} // namespace chromeos
|
Java
|
/*
* jQuery File Upload Plugin JS Example 8.9.1
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/* global $, window */
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: root_url + '/media/upload'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
if (window.location.hostname === 'blueimp.github.io') {
// Demo settings:
$('#fileupload').fileupload('option', {
url: '//jquery-file-upload.appspot.com/',
// Enable image resizing, except for Android and Opera,
// which actually support image resizing, but fail to
// send Blob objects via XHR requests:
disableImageResize: /Android(?!.*Chrome)|Opera/
.test(window.navigator.userAgent),
maxFileSize: 5000000,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
});
// Upload server status check for browsers with CORS support:
if ($.support.cors) {
$.ajax({
url: '//jquery-file-upload.appspot.com/',
type: 'HEAD'
}).fail(function () {
$('<div class="alert alert-danger"/>')
.text('Upload server currently unavailable - ' +
new Date())
.appendTo('#fileupload');
});
}
} else {
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
///////////////////////////////////////////////
});
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" type="image/ico" href="http://www.datatables.net/media/images/favicon.ico" />
<title>DataTables example</title>
<style type="text/css" title="currentStyle">
@import "../../media/css/demo_page.css";
@import "../../media/css/demo_table.css";
</style>
<script type="text/javascript" language="javascript" src="../../media/js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="../../media/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$('#example').dataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "scripts/post.php",
"type": "POST"
}
} );
} );
</script>
</head>
<body id="dt_example">
<div id="container">
<div class="full_width big">
DataTables server-side processing with POST example
</div>
<h1>Preamble</h1>
<p>The default HTTP method that DataTables uses to get data from the server-side if GET, however, there are times when you may wish to use POST. This is very easy using the sServerMethod initialisation parameter, which is simply set to the HTTP method that you want to use - the default is 'GET' and this example shows 'POST' being used.</p>
<h1>Live example</h1>
<div id="dynamic">
<table cellpadding="0" cellspacing="0" border="0" class="display" id="example">
<thead>
<tr>
<th width="20%">Rendering engine</th>
<th width="25%">Browser</th>
<th width="25%">Platform(s)</th>
<th width="15%">Engine version</th>
<th width="15%">CSS grade</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="5" class="dataTables_empty">Loading data from server</td>
</tr>
</tbody>
<tfoot>
<tr>
<th>Rendering engine</th>
<th>Browser</th>
<th>Platform(s)</th>
<th>Engine version</th>
<th>CSS grade</th>
</tr>
</tfoot>
</table>
</div>
<div class="spacer"></div>
<h1>Initialisation code</h1>
<pre class="brush: js;">$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"bServerSide": true,
"sAjaxSource": "scripts/post.php",
"sServerMethod": "POST"
} );
} );</pre>
<style type="text/css">
@import "../examples_support/syntax/css/shCore.css";
</style>
<script type="text/javascript" language="javascript" src="../examples_support/syntax/js/shCore.js"></script>
<h1>Server response</h1>
<p>The code below shows the latest JSON data that has been returned from the server in response to the Ajax request made by DataTables. This will update as further requests are made.</p>
<pre id="latest_xhr" class="brush: js;"></pre>
<h1>Other examples</h1>
<div class="demo_links">
<h2>Basic initialisation</h2>
<ul>
<li><a href="../basic_init/zero_config.html">Zero configuration</a></li>
<li><a href="../basic_init/filter_only.html">Feature enablement</a></li>
<li><a href="../basic_init/table_sorting.html">Sorting data</a></li>
<li><a href="../basic_init/multi_col_sort.html">Multi-column sorting</a></li>
<li><a href="../basic_init/multiple_tables.html">Multiple tables</a></li>
<li><a href="../basic_init/hidden_columns.html">Hidden columns</a></li>
<li><a href="../basic_init/complex_header.html">Complex headers - grouping with colspan</a></li>
<li><a href="../basic_init/dom.html">DOM positioning</a></li>
<li><a href="../basic_init/flexible_width.html">Flexible table width</a></li>
<li><a href="../basic_init/state_save.html">State saving</a></li>
<li><a href="../basic_init/alt_pagination.html">Alternative pagination styles</a></li>
<li>Scrolling: <br>
<a href="../basic_init/scroll_x.html">Horizontal</a> /
<a href="../basic_init/scroll_y.html">Vertical</a> /
<a href="../basic_init/scroll_xy.html">Both</a> /
<a href="../basic_init/scroll_y_theme.html">Themed</a> /
<a href="../basic_init/scroll_y_infinite.html">Infinite</a>
</li>
<li><a href="../basic_init/language.html">Change language information (internationalisation)</a></li>
<li><a href="../basic_init/themes.html">ThemeRoller themes (Smoothness)</a></li>
</ul>
<h2>Advanced initialisation</h2>
<ul>
<li>Events: <br>
<a href="../advanced_init/events_live.html">Live events</a> /
<a href="../advanced_init/events_pre_init.html">Pre-init</a> /
<a href="../advanced_init/events_post_init.html">Post-init</a>
</li>
<li><a href="../advanced_init/column_render.html">Column rendering</a></li>
<li><a href="../advanced_init/html_sort.html">Sorting without HTML tags</a></li>
<li><a href="../advanced_init/dom_multiple_elements.html">Multiple table controls (sDom)</a></li>
<li><a href="../advanced_init/length_menu.html">Defining length menu options</a></li>
<li><a href="../advanced_init/complex_header.html">Complex headers and hidden columns</a></li>
<li><a href="../advanced_init/dom_toolbar.html">Custom toolbar (element) around table</a></li>
<li><a href="../advanced_init/highlight.html">Row highlighting with CSS</a></li>
<li><a href="../advanced_init/row_grouping.html">Row grouping</a></li>
<li><a href="../advanced_init/row_callback.html">Row callback</a></li>
<li><a href="../advanced_init/footer_callback.html">Footer callback</a></li>
<li><a href="../advanced_init/sorting_control.html">Control sorting direction of columns</a></li>
<li><a href="../advanced_init/language_file.html">Change language information from a file (internationalisation)</a></li>
<li><a href="../advanced_init/defaults.html">Setting defaults</a></li>
<li><a href="../advanced_init/localstorage.html">State saving with localStorage</a></li>
<li><a href="../advanced_init/dt_events.html">Custom events</a></li>
</ul>
<h2>API</h2>
<ul>
<li><a href="../api/add_row.html">Dynamically add a new row</a></li>
<li><a href="../api/multi_filter.html">Individual column filtering (using "input" elements)</a></li>
<li><a href="../api/multi_filter_select.html">Individual column filtering (using "select" elements)</a></li>
<li><a href="../api/highlight.html">Highlight rows and columns</a></li>
<li><a href="../api/row_details.html">Show and hide details about a particular record</a></li>
<li><a href="../api/select_row.html">User selectable rows (multiple rows)</a></li>
<li><a href="../api/select_single_row.html">User selectable rows (single row) and delete rows</a></li>
<li><a href="../api/editable.html">Editable rows (with jEditable)</a></li>
<li><a href="../api/form.html">Submit form with elements in table</a></li>
<li><a href="../api/counter_column.html">Index column (static number column)</a></li>
<li><a href="../api/show_hide.html">Show and hide columns dynamically</a></li>
<li><a href="../api/api_in_init.html">API function use in initialisation object (callback)</a></li>
<li><a href="../api/tabs_and_scrolling.html">DataTables scrolling and tabs</a></li>
<li><a href="../api/regex.html">Regular expression filtering</a></li>
</ul>
</div>
<div class="demo_links">
<h2>Data sources</h2>
<ul>
<li><a href="../data_sources/dom.html">DOM</a></li>
<li><a href="../data_sources/js_array.html">Javascript array</a></li>
<li><a href="../data_sources/ajax.html">Ajax source</a></li>
<li><a href="../data_sources/server_side.html">Server side processing</a></li>
</ul>
<h2>Server-side processing</h2>
<ul>
<li><a href="../server_side/server_side.html">Obtain server-side data</a></li>
<li><a href="../server_side/custom_vars.html">Add extra HTTP variables</a></li>
<li><a href="../server_side/post.html">Use HTTP POST</a></li>
<li><a href="../server_side/ids.html">Automatic addition of IDs and classes to rows</a></li>
<li><a href="../server_side/object_data.html">Reading table data from objects</a></li>
<li><a href="../server_side/row_details.html">Show and hide details about a particular record</a></li>
<li><a href="../server_side/select_rows.html">User selectable rows (multiple rows)</a></li>
<li><a href="../server_side/jsonp.html">JSONP for a cross domain data source</a></li>
<li><a href="../server_side/editable.html">jEditable integration with DataTables</a></li>
<li><a href="../server_side/defer_loading.html">Deferred loading of Ajax data</a></li>
<li><a href="../server_side/pipeline.html">Pipelining data (reduce Ajax calls for paging)</a></li>
</ul>
<h2>Ajax data source</h2>
<ul>
<li><a href="../ajax/ajax.html">Ajax sourced data (array of arrays)</a></li>
<li><a href="../ajax/objects.html">Ajax sourced data (array of objects)</a></li>
<li><a href="../ajax/defer_render.html">Deferred DOM creation for extra speed</a></li>
<li><a href="../ajax/null_data_source.html">Empty data source columns</a></li>
<li><a href="../ajax/custom_data_property.html">Use a data source other than aaData (the default)</a></li>
<li><a href="../ajax/objects_subarrays.html">Read column data from sub-arrays</a></li>
<li><a href="../ajax/deep.html">Read column data from deeply nested properties</a></li>
</ul>
<h2>Plug-ins</h2>
<ul>
<li><a href="../plug-ins/plugin_api.html">Add custom API functions</a></li>
<li><a href="../plug-ins/sorting_plugin.html">Sorting and automatic type detection</a></li>
<li><a href="../plug-ins/sorting_sType.html">Sorting without automatic type detection</a></li>
<li><a href="../plug-ins/paging_plugin.html">Custom pagination controls</a></li>
<li><a href="../plug-ins/range_filtering.html">Range filtering / custom filtering</a></li>
<li><a href="../plug-ins/dom_sort.html">Live DOM sorting</a></li>
<li><a href="../plug-ins/html_sort.html">Automatic HTML type detection</a></li>
</ul>
</div>
<div id="footer" class="clear" style="text-align:center;">
<p>
Please refer to the <a href="http://www.datatables.net/usage">DataTables documentation</a> for full information about its API properties and methods.<br>
Additionally, there are a wide range of <a href="http://www.datatables.net/extras">extras</a> and <a href="http://www.datatables.net/plug-ins">plug-ins</a> which extend the capabilities of DataTables.
</p>
<span style="font-size:10px;">
DataTables designed and created by <a href="http://www.sprymedia.co.uk">Allan Jardine</a> © 2007-2011<br>
DataTables is dual licensed under the <a href="http://www.datatables.net/license_gpl2">GPL v2 license</a> or a <a href="http://www.datatables.net/license_bsd">BSD (3-point) license</a>.
</span>
</div>
</div>
</body>
</html>
|
Java
|
module Spree
module Admin
class AuthorsController < ResourceController
def index
params[:q] ||= {}
params[:q][:deleted_at_null] ||= "1"
@search = @authors.ransack(params[:q])
@authors = @search.result.page(params[:page]).per(Spree::Config[:admin_products_per_page])
@authors = @authors.includes(:user_detail)
end
def update
author_info = Spree::UserDetail.find_or_create_by(user_id: params[:id])
result = author_info.update_attributes(author_params[:user_detail])
if result
flash[:success] = flash_message_for(@author, :successfully_updated)
respond_with(@author) do |format|
format.html { redirect_to admin_authors_path }
format.json { render layout: false, status: :updated }
end
else
invoke_callbacks(:update, :fails)
respond_with(@author)
end
end
protected
def collection
page = params[:page].to_i > 0 ? params[:page].to_i : 1
per_page = params[:per_page].to_i > 0 ? params[:per_page].to_i : 20
Spree::User.authors.page(page).per(per_page)
end
private
def author_params
params.require(:author).permit(:id, { user_detail: [:nickname, :website_url, :bio_info] })
end
end
end
end
|
Java
|
/*
* Copyright (c) 2006, 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* ceil(x)
* Return x rounded toward -inf to integral value
* Method:
* Bit twiddling.
* Exception:
* Inexact flag raised if x not equal to ceil(x).
*/
#include "fdlibm.h"
#ifdef __STDC__
static const double huge = 1.0e300;
#else
static double huge = 1.0e300;
#endif
#ifdef __STDC__
double ceil(double x)
#else
double ceil(x)
double x;
#endif
{
int i0,i1,j0;
unsigned i,j;
i0 = __HI(x);
i1 = __LO(x);
j0 = ((i0>>20)&0x7ff)-0x3ff;
if(j0<20) {
if(j0<0) { /* raise inexact if x != 0 */
if(huge+x>0.0) {/* return 0*sign(x) if |x|<1 */
if(i0<0) {i0=0x80000000;i1=0;}
else if((i0|i1)!=0) { i0=0x3ff00000;i1=0;}
}
} else {
i = (0x000fffff)>>j0;
if(((i0&i)|i1)==0) return x; /* x is integral */
if(huge+x>0.0) { /* raise inexact flag */
if(i0>0) i0 += (0x00100000)>>j0;
i0 &= (~i); i1=0;
}
}
} else if (j0>51) {
if(j0==0x400) return x+x; /* inf or NaN */
else return x; /* x is integral */
} else {
i = ((unsigned)(0xffffffff))>>(j0-20);
if((i1&i)==0) return x; /* x is integral */
if(huge+x>0.0) { /* raise inexact flag */
if(i0>0) {
if(j0==20) i0+=1;
else {
j = i1 + (1<<(52-j0));
if(j<i1) i0+=1; /* got a carry */
i1 = j;
}
}
i1 &= (~i);
}
}
__HI(x) = i0;
__LO(x) = i1;
return x;
}
|
Java
|
.aui-base {
}
|
Java
|
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
* Portions Copyright (c) 2008-2009 Stacey Son <sson@FreeBSD.org>
*
* $FreeBSD$
*
*/
/*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include "opt_kdtrace.h"
#include <sys/cdefs.h>
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/conf.h>
#include <sys/kernel.h>
#include <sys/limits.h>
#include <sys/lock.h>
#include <sys/linker.h>
#include <sys/module.h>
#include <sys/mutex.h>
#include <sys/dtrace.h>
#include <sys/lockstat.h>
#if defined(__i386__) || defined(__amd64__) || \
defined(__mips__) || defined(__powerpc__)
#define LOCKSTAT_AFRAMES 1
#else
#error "architecture not supported"
#endif
static d_open_t lockstat_open;
static void lockstat_provide(void *, dtrace_probedesc_t *);
static void lockstat_destroy(void *, dtrace_id_t, void *);
static void lockstat_enable(void *, dtrace_id_t, void *);
static void lockstat_disable(void *, dtrace_id_t, void *);
static void lockstat_load(void *);
static int lockstat_unload(void);
typedef struct lockstat_probe {
char *lsp_func;
char *lsp_name;
int lsp_probe;
dtrace_id_t lsp_id;
#ifdef __FreeBSD__
int lsp_frame;
#endif
} lockstat_probe_t;
#ifdef __FreeBSD__
lockstat_probe_t lockstat_probes[] =
{
/* Spin Locks */
{ LS_MTX_SPIN_LOCK, LSS_ACQUIRE, LS_MTX_SPIN_LOCK_ACQUIRE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_MTX_SPIN_LOCK, LSS_SPIN, LS_MTX_SPIN_LOCK_SPIN,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_MTX_SPIN_UNLOCK, LSS_RELEASE, LS_MTX_SPIN_UNLOCK_RELEASE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
/* Adaptive Locks */
{ LS_MTX_LOCK, LSA_ACQUIRE, LS_MTX_LOCK_ACQUIRE,
DTRACE_IDNONE, (LOCKSTAT_AFRAMES + 1) },
{ LS_MTX_LOCK, LSA_BLOCK, LS_MTX_LOCK_BLOCK,
DTRACE_IDNONE, (LOCKSTAT_AFRAMES + 1) },
{ LS_MTX_LOCK, LSA_SPIN, LS_MTX_LOCK_SPIN,
DTRACE_IDNONE, (LOCKSTAT_AFRAMES + 1) },
{ LS_MTX_UNLOCK, LSA_RELEASE, LS_MTX_UNLOCK_RELEASE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_MTX_TRYLOCK, LSA_ACQUIRE, LS_MTX_TRYLOCK_ACQUIRE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
/* Reader/Writer Locks */
{ LS_RW_RLOCK, LSR_ACQUIRE, LS_RW_RLOCK_ACQUIRE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_RW_RLOCK, LSR_BLOCK, LS_RW_RLOCK_BLOCK,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_RW_RLOCK, LSR_SPIN, LS_RW_RLOCK_SPIN,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_RW_RUNLOCK, LSR_RELEASE, LS_RW_RUNLOCK_RELEASE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_RW_WLOCK, LSR_ACQUIRE, LS_RW_WLOCK_ACQUIRE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_RW_WLOCK, LSR_BLOCK, LS_RW_WLOCK_BLOCK,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_RW_WLOCK, LSR_SPIN, LS_RW_WLOCK_SPIN,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_RW_WUNLOCK, LSR_RELEASE, LS_RW_WUNLOCK_RELEASE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_RW_TRYUPGRADE, LSR_UPGRADE, LS_RW_TRYUPGRADE_UPGRADE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_RW_DOWNGRADE, LSR_DOWNGRADE, LS_RW_DOWNGRADE_DOWNGRADE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
/* Shared/Exclusive Locks */
{ LS_SX_SLOCK, LSX_ACQUIRE, LS_SX_SLOCK_ACQUIRE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_SX_SLOCK, LSX_BLOCK, LS_SX_SLOCK_BLOCK,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_SX_SLOCK, LSX_SPIN, LS_SX_SLOCK_SPIN,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_SX_SUNLOCK, LSX_RELEASE, LS_SX_SUNLOCK_RELEASE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_SX_XLOCK, LSX_ACQUIRE, LS_SX_XLOCK_ACQUIRE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_SX_XLOCK, LSX_BLOCK, LS_SX_XLOCK_BLOCK,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_SX_XLOCK, LSX_SPIN, LS_SX_XLOCK_SPIN,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_SX_XUNLOCK, LSX_RELEASE, LS_SX_XUNLOCK_RELEASE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_SX_TRYUPGRADE, LSX_UPGRADE, LS_SX_TRYUPGRADE_UPGRADE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ LS_SX_DOWNGRADE, LSX_DOWNGRADE, LS_SX_DOWNGRADE_DOWNGRADE,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
/* Thread Locks */
{ LS_THREAD_LOCK, LST_SPIN, LS_THREAD_LOCK_SPIN,
DTRACE_IDNONE, LOCKSTAT_AFRAMES },
{ NULL }
};
#else
#error "OS not supported"
#endif
static struct cdevsw lockstat_cdevsw = {
.d_version = D_VERSION,
.d_open = lockstat_open,
.d_name = "lockstat",
};
static struct cdev *lockstat_cdev;
static dtrace_provider_id_t lockstat_id;
/*ARGSUSED*/
static void
lockstat_enable(void *arg, dtrace_id_t id, void *parg)
{
lockstat_probe_t *probe = parg;
ASSERT(!lockstat_probemap[probe->lsp_probe]);
lockstat_enabled++;
lockstat_probemap[probe->lsp_probe] = id;
#ifdef DOODAD
membar_producer();
#endif
lockstat_probe_func = dtrace_probe;
#ifdef DOODAD
membar_producer();
lockstat_hot_patch();
membar_producer();
#endif
}
/*ARGSUSED*/
static void
lockstat_disable(void *arg, dtrace_id_t id, void *parg)
{
lockstat_probe_t *probe = parg;
int i;
ASSERT(lockstat_probemap[probe->lsp_probe]);
lockstat_enabled--;
lockstat_probemap[probe->lsp_probe] = 0;
#ifdef DOODAD
lockstat_hot_patch();
membar_producer();
#endif
/*
* See if we have any probes left enabled.
*/
for (i = 0; i < LS_NPROBES; i++) {
if (lockstat_probemap[i]) {
/*
* This probe is still enabled. We don't need to deal
* with waiting for all threads to be out of the
* lockstat critical sections; just return.
*/
return;
}
}
}
/*ARGSUSED*/
static int
lockstat_open(struct cdev *dev __unused, int oflags __unused,
int devtype __unused, struct thread *td __unused)
{
return (0);
}
/*ARGSUSED*/
static void
lockstat_provide(void *arg, dtrace_probedesc_t *desc)
{
int i = 0;
for (i = 0; lockstat_probes[i].lsp_func != NULL; i++) {
lockstat_probe_t *probe = &lockstat_probes[i];
if (dtrace_probe_lookup(lockstat_id, "kernel",
probe->lsp_func, probe->lsp_name) != 0)
continue;
ASSERT(!probe->lsp_id);
#ifdef __FreeBSD__
probe->lsp_id = dtrace_probe_create(lockstat_id,
"kernel", probe->lsp_func, probe->lsp_name,
probe->lsp_frame, probe);
#else
probe->lsp_id = dtrace_probe_create(lockstat_id,
"kernel", probe->lsp_func, probe->lsp_name,
LOCKSTAT_AFRAMES, probe);
#endif
}
}
/*ARGSUSED*/
static void
lockstat_destroy(void *arg, dtrace_id_t id, void *parg)
{
lockstat_probe_t *probe = parg;
ASSERT(!lockstat_probemap[probe->lsp_probe]);
probe->lsp_id = 0;
}
static dtrace_pattr_t lockstat_attr = {
{ DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_COMMON },
{ DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
{ DTRACE_STABILITY_PRIVATE, DTRACE_STABILITY_PRIVATE, DTRACE_CLASS_UNKNOWN },
{ DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_COMMON },
{ DTRACE_STABILITY_EVOLVING, DTRACE_STABILITY_EVOLVING, DTRACE_CLASS_COMMON },
};
static dtrace_pops_t lockstat_pops = {
lockstat_provide,
NULL,
lockstat_enable,
lockstat_disable,
NULL,
NULL,
NULL,
NULL,
NULL,
lockstat_destroy
};
static void
lockstat_load(void *dummy)
{
/* Create the /dev/dtrace/lockstat entry. */
lockstat_cdev = make_dev(&lockstat_cdevsw, 0, UID_ROOT, GID_WHEEL, 0600,
"dtrace/lockstat");
if (dtrace_register("lockstat", &lockstat_attr, DTRACE_PRIV_USER,
NULL, &lockstat_pops, NULL, &lockstat_id) != 0)
return;
}
static int
lockstat_unload()
{
int error = 0;
if ((error = dtrace_unregister(lockstat_id)) != 0)
return (error);
destroy_dev(lockstat_cdev);
return (error);
}
/* ARGSUSED */
static int
lockstat_modevent(module_t mod __unused, int type, void *data __unused)
{
int error = 0;
switch (type) {
case MOD_LOAD:
break;
case MOD_UNLOAD:
break;
case MOD_SHUTDOWN:
break;
default:
error = EOPNOTSUPP;
break;
}
return (error);
}
SYSINIT(lockstat_load, SI_SUB_DTRACE_PROVIDER, SI_ORDER_ANY, lockstat_load, NULL);
SYSUNINIT(lockstat_unload, SI_SUB_DTRACE_PROVIDER, SI_ORDER_ANY, lockstat_unload, NULL);
DEV_MODULE(lockstat, lockstat_modevent, NULL);
MODULE_VERSION(lockstat, 1);
MODULE_DEPEND(lockstat, dtrace, 1, 1, 1);
MODULE_DEPEND(lockstat, opensolaris, 1, 1, 1);
|
Java
|
<?php namespace xp\runtime;
/**
* Wrap code passed in from the command line.
*
* @see https://wiki.php.net/rfc/group_use_declarations
* @test xp://net.xp_framework.unittest.runtime.CodeTest
*/
class Code {
private $fragment, $imports;
/**
* Creates a new code instance
*
* @param string $input
*/
public function __construct($input) {
// Shebang
if (0 === strncmp($input, '#!', 2)) {
$input= substr($input, strcspn($input, "\n") + 1);
}
// PHP open tags
if (0 === strncmp($input, '<?', 2)) {
$input= substr($input, strcspn($input, "\r\n\t =") + 1);
}
$this->fragment= trim($input, "\r\n\t ;").';';
$this->imports= [];
while (0 === strncmp($this->fragment, 'use ', 4)) {
$delim= strpos($this->fragment, ';');
foreach ($this->importsIn(substr($this->fragment, 4, $delim - 4)) as $import) {
$this->imports[]= $import;
}
$this->fragment= ltrim(substr($this->fragment, $delim + 1), ' ');
}
}
/** @return string */
public function fragment() { return $this->fragment; }
/** @return string */
public function expression() {
return strstr($this->fragment, 'return ') || strstr($this->fragment, 'return;')
? $this->fragment
: 'return '.$this->fragment
;
}
/** @return string[] */
public function imports() { return $this->imports; }
/** @return string */
public function head() {
return empty($this->imports) ? '' : 'use '.implode(', ', $this->imports).';';
}
/**
* Returns types used inside a `use ...` directive.
*
* @param string $use
* @return string[]
*/
private function importsIn($use) {
$name= strrpos($use, '\\') + 1;
$used= [];
if ('{' === $use{$name}) {
$namespace= substr($use, 0, $name);
foreach (explode(',', substr($use, $name + 1, -1)) as $type) {
$used[]= $namespace.trim($type);
}
} else {
foreach (explode(',', $use) as $type) {
$used[]= trim($type);
}
}
return $used;
}
}
|
Java
|
#!/usr/bin/python
# Copyright (c) 2009, Purdue 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 the Purdue University 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.
"""Test for Credential cache library."""
__copyright__ = 'Copyright (C) 2009, Purdue University'
__license__ = 'BSD'
__version__ = '#TRUNK#'
import unittest
import os
import roster_core
from roster_server import credentials
CONFIG_FILE = 'test_data/roster.conf' # Example in test_data
SCHEMA_FILE = '../roster-core/data/database_schema.sql'
DATA_FILE = 'test_data/test_data.sql'
class TestCredentialsLibrary(unittest.TestCase):
def setUp(self):
self.config_instance = roster_core.Config(file_name=CONFIG_FILE)
self.cred_instance = credentials.CredCache(self.config_instance,
u'sharrell')
db_instance = self.config_instance.GetDb()
db_instance.CreateRosterDatabase()
data = open(DATA_FILE, 'r').read()
db_instance.StartTransaction()
db_instance.cursor.execute(data)
db_instance.EndTransaction()
db_instance.close()
self.core_instance = roster_core.Core(u'sharrell', self.config_instance)
def is_valid_uuid (self, uuid):
"""
TAKEN FROM THE BLUEZ MODULE
is_valid_uuid (uuid) -> bool
returns True if uuid is a valid 128-bit UUID.
valid UUIDs are always strings taking one of the following forms:
XXXX
XXXXXXXX
XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
where each X is a hexadecimal digit (case insensitive)
"""
try:
if len (uuid) == 4:
if int (uuid, 16) < 0: return False
elif len (uuid) == 8:
if int (uuid, 16) < 0: return False
elif len (uuid) == 36:
pieces = uuid.split ("-")
if len (pieces) != 5 or \
len (pieces[0]) != 8 or \
len (pieces[1]) != 4 or \
len (pieces[2]) != 4 or \
len (pieces[3]) != 4 or \
len (pieces[4]) != 12:
return False
[ int (p, 16) for p in pieces ]
else:
return False
except ValueError:
return False
except TypeError:
return False
return True
def testCredentials(self):
self.assertTrue(self.cred_instance.Authenticate(u'sharrell', 'test'))
cred_string = self.cred_instance.GetCredentials(u'sharrell', 'test',
self.core_instance)
self.assertEqual(self.cred_instance.CheckCredential(cred_string,
u'sharrell',
self.core_instance),
u'')
self.assertEqual(self.cred_instance.CheckCredential(u'test', u'sharrell',
self.core_instance),
None)
if( __name__ == '__main__' ):
unittest.main()
|
Java
|
#!/usr/bin/env python
import sys
import hyperdex.client
from hyperdex.client import LessEqual, GreaterEqual, Range, Regex, LengthEquals, LengthLessEqual, LengthGreaterEqual
c = hyperdex.client.Client(sys.argv[1], int(sys.argv[2]))
def to_objectset(xs):
return set([frozenset(x.items()) for x in xs])
assert c.put('kv', 'k', {}) == True
assert c.get('kv', 'k') == {'v': {}}
assert c.put('kv', 'k', {'v': {1: 3.14, 2: 0.25, 3: 1.0}}) == True
assert c.get('kv', 'k') == {'v': {1: 3.14, 2: 0.25, 3: 1.0}}
assert c.put('kv', 'k', {'v': {}}) == True
assert c.get('kv', 'k') == {'v': {}}
|
Java
|
<?php
namespace yiicms\components\core;
# Websun template parser, version 0.1.80
# http://webew.ru/articles/3609.webew
/*
0.1.80 - allowed_extensions option implemented
0.1.71 - replaced too new array declaration [] with array() - keeping PHP 5.3 compatibility
0.1.70 - added :^N and :^i
0.1.60 - __construct() accepts an array as of now
(wrapping function accepts distinct variables still)
- "no_global_variables" setting implemented
0.1.55 - fixed misbehavior of functions' args parsing
when dealing with comma inside of double quotes
like @function(*var*, "string,string")
По поводу массивов в JSON-нотации в качестве скалярных величин:
// 1. Как *var* вытащить из json_decode?
// Сначала *var* => json_encode(*var*, 1)
// (это будет голый массив данных; не-data-свойства потеряются)
// 2. Как указывать кодировку (json_decode только в UTF-8),
// $WEBSUN_CHARSET?
// 2а) Как вообще избавиться от %u0441 вместо кириллицы?
// возможно только для UTF-8 или избирательно 1251,
// т.к. нужно ловить буквы и делать им кодирование в %uXXXX
// Всё это будет очень долго, особенно если это проводить
// для каждой переменной
// (хотя там можно поставить костыль на [ и { -
// если не встретили в начале, то обрабатываем как обычно)
0.1.54 - $WEBSUN_ALLOWED_CALLBACKS instead of $WEBSUN_VISIBLES
0.1.53 - list of visible functions as a global variable for all versions
(for a while - see v. 0.1.51)
0.1.53(beta) - added trim() at the beginning get_var_or_string()
0.1.52(beta) - using is_numeric() when parsing ifs (opposite to v.0.1.17)
0.1.51(beta) - list of visible functions added (draft)
prior to PHP 5.6 - as a global array variable
PHP 5.6 and higher - as a namespace
0.1.50 - fixed default paths handling (see __construct() )
0.1.49 - added preg_quote() in parse_cycle() for searching array's name
0.1.48 - $ can be used in templates_root direcory path
(^ makes no sense, because it means templates_root path itself)
0.1.47 - called back the possibility of spaces before variables,
because it makes parsing of cycles harder:
instead of [*|&..]array: we must catch [*|&..]\s*array,
which (according to one of the tests) works ~10% slower;
simple (non-cycle) variables and constants
(literally how it is described in comment to previous version)
can still work - this unofficial possibility will be left
0.1.46 - spaces can be like {?* a = b *}, {?* a > b *}
(especially convenient when using constants: {?*a = =CONST*})
0.1.45 - now spaces can be around &, | and variable names in ifs
0.1.44 - loosen parse_cycle() regexp
to accept arrays with non-alphanumeric keys
(for example, it may occur handy to use
some non-latin string as a key),
now {%* anything here *} is accepted.
Note: except of dots in "anything", which are
still interpreted as key separators.
0.1.43 - some fixes in profiling:
parse_template's time is not added to total
instead of this, total time is calculated
as a time of highest level parse_template run
Note: profiling by itself may increase
total run time up to 60%
0.1.42 - loosen regexp at check_if_condition_part()
from [$=]?[\w.\^]*+ to [^*=<>]*+
now any variable name can be used in ifs,
not just alphanumeric;
such loose behaviour looks more flexible
and parallels var_value() algorithm
(which can interpret any variable name
except of with dots)
0.1.41 - fixed find_and_parse_cycle():
"array_name:" prefixed with & is also catched
(required for ifs like {?*array:key1&array:key2*})
0.1.40 - fixed error in check_if_condition_part()
(pattern)
0.1.39 - fixed error in check_if_condition_part()
(forgotten vars like array^COUNT>1 etc.)
0.1.38 - fixed error in if alternatives (see 0.1.37)
introduced check_if_condition_part() method
added possibility of "AND", not just "OR" in if alternatives:
{?*var_1="one"|var_2="two"*} it is OR {*var_1="one"|var_2="two"*?}
{?*var_1="one"&var_2="two"*} it is AND {*var_1="one"&var_2="two"*?}
Fixed profiling!
Now any profiling information is passed to the higher level -
otherwise (as it previously was) each object instance (i.e. each
call of nested template or module) produced it's own and private
timesheet.
0.1.37 - fixes in var_value():
parsing of | (if alternatives) now goes before
parsing of strings ("..")
so things like {?*var_1="one"|var_2="two"*} ... {*var_1="one"|var_2="two"*?}
are possible
(but things like {?*var="one|two"*} are not)
0.1.36 - correct string literals parsing - var_value() fix
(important when passed to module)
0.1.35 - two literals comparison is accepted in if's now
(previously only variable was allowed at the left)
Needed to do so because of :^KEY parsing - those
are converted to literals BEFORE ifs are processed
Substituted ("[^"*][\w.:$|\^]*+) subpattern
with the ("[^"*]+"|[\w.:$|\^]*+) one
0.1.34 - fixed surpassing variables to child templates
(now {* + *var1|var2* | *tpl1|tpl2* *} works)
0.1.33 - fixed parse_if (now {?*var1|var2*}..{*var1|var2*?} works)
0.1.32 - fixed getting template name from variable
(now variable can be like {*var1|var2|"string"*}
as everywhere else)
0.1.31 - fixed /r/n deletion from the end of the pattern
0.1.30 - fixed parse_cycle() function:
regexp now catches {* *%array:subarray* | ... *}
(previously missed it)
0.1.29 - fixed a misprint
0.1.28 - A bunch of little fixes.
Added profiling mode (experimental
for a while so not recommended to use
hardly).
Regexp for ifs speeded up by substituting
loose [^<>=]* with strict [\w.:$\^]*+
(boosted the usecase about 100 times)
In parse_cycle - also
([\w$.]*) instead of ([-\w$.]*)
(don't remember, what "-" was for).
Constants are now handled in var_value
(with all other stuff like ^COUNT etc.)
instead of in get_var_or_string().
0.1.27 - "alt" version is main now
added {* + *some* | >{*var*} *} -
templates right inside of the var
0.1.26 - fixed some things with $matches dealing in parsee_if
0.1.25 - version suffix changed "beta" (b) to "alternative" (alt)
0.1.25 - fixed replacement of array:foo -
Now it is more strict and occurs if only
symbols *=<>| precede array:foo
( =<> - for {*array:foo_1>array:foo_2*}, |
- for {*array:foo_1|array:foo_2*},
* - for just {*array:foo*} )
0.1.24 - (beta) rewriting regexps with no named subpatterns
for compatibility with old PHP versions
(PCRE documentation is unclear and issues like
new PHP and no support of named subpatterns occur)
EXCEPT pattern for addvars method
0.1.23 - fixed ^KEY parsing a little (removed preg_quote and fixed regexp)
0.1.22 - now not only *array:foo* (and *array:^KEY*) is caught,
but array:foo and array:^KEY as well
Needed it because otherwise if clauses like {*array:a|array:b*}
are not parsed. This required substitution of str_replace with
with preg_replace which had no visible affect on perfomance.
0.1.21 - fixed some in var_value() (substr sometimes returns FALSE not empty string)
everything is mb* now
0.1.20 - fixed trimming \r\n at the end
of the template
0.1.19 - websun_parse_template_path() fixed
to set current templates directory
to the one of template specified
0.1.18 - KEY added
0.1.17 - fixed some in var_value()
теперь по умолчанию корневой каталог шаблона -
тот, в котором выполняется вызвавший функцию скрипт
добавлены ^COUNT (0.1.13)
добавлены if'ы: {*var_1|var_2|"строка"|1234(число)*}
в if'ах добавлено сравнение с переменными:
{?*a>b*}..{*a>b?*}
{?*a>"строка"*}..{*a>"строка"*?}
{?*a>3*}..{*a>3*?}
*/
class websun
{
public $vars;
public $templates_root_dir; // templates_root_dir указывать без закрывающего слэша!
public $templates_current_dir;
public $TIMES;
public $no_global_vars;
private $profiling;
private $predecessor; // объект шаблонизатора верхнего уровня, из которого делался вызов текущего
function __construct($options)
{
// $options - ассоциативный массив с ключами:
// - data - данные
// - templates_root - корневой каталог шаблонизатора
// - predecessor - объект-родитель (из которого вызывается дочерний)
// - allowed_extensions - список разрешенных расширений шаблонов (по умолчанию: *.tpl, *.html, *.css, *.js)
// - no_global_vars - разрешать ли использовать в шаблонах переменные глобальной области видимости
// - profiling - включать ли измерения скорости (пока не до конца отлажено)
$this->vars = $options['data'];
if (isset($options['templates_root']) AND $options['templates_root']) // корневой каталог шаблонов
{
$this->templates_root_dir = $this->template_real_path($options['templates_root']);
} else { // если не указан, то принимается каталог файла, в котором вызван websun
// С 0.50 - НЕ getcwd()! Т.к. текущий каталог - тот, откуда он запускается,
// $this->templates_root_dir = getcwd();
foreach (debug_backtrace() as $trace) {
if (preg_match('/^websun_parse_template/', $trace['function'])) {
$this->templates_root_dir = dirname($trace['file']);
break;
}
}
if (!$this->templates_root_dir) {
foreach (debug_backtrace() as $trace) {
if ($trace['class'] == 'websun') {
$this->templates_root_dir = dirname($trace['file']);
break;
}
}
}
}
$this->templates_current_dir = $this->templates_root_dir . '/';
$this->predecessor = (isset($options['predecessor']) ? $options['predecessor'] : false);
$this->allowed_extensions = (isset($options['allowed_extensions']))
? $options['allowed_extensions']
: ['tpl', 'html', 'css', 'js'];
$this->no_global_vars = (isset($options['no_global_vars']) ? $options['no_global_vars'] : false);
$this->profiling = (isset($options['profiling']) ? $options['profiling'] : false);
}
function parse_template($template)
{
if ($this->profiling) {
$start = microtime(1);
}
$template = preg_replace('/ \\/\* (.*?) \*\\/ /sx', '', $template);
/**ПЕРЕПИСАТЬ ПО JEFFREY FRIEDL'У !!!**/
$template = str_replace('\\\\', "\x01", $template); // убираем двойные слэши
$template = str_replace('\*', "\x02", $template); // и экранированные звездочки
// С 0.1.51 отключили
// $template = preg_replace_callback( // дописывающие модули
// '/
// {\*
// &(\w+)
// (?P<args>\([^*]*\))?
// \*}
// /x',
// array($this, 'addvars'),
// $template
// );
$template = $this->find_and_parse_cycle($template);
$template = $this->find_and_parse_if($template);
$template = preg_replace_callback( // переменные, шаблоны и модули
'/
{\*
(.*?)
\*}
/x',
/* подумать о том, чтобы вместо (.*?)
использовать жадное, но более строгое
(
(?:
[^*]*+
|
\*(?!})
)+
)
*/
[$this, 'parse_vars_templates_functions'],
$template
);
$template = str_replace("\x01", '\\\\', $template); // возвращаем двойные слэши обратно
$template = str_replace("\x02", '*', $template); // а звездочки - уже без экранирования
if ($this->profiling AND !$this->predecessor) {
$this->TIMES['_TOTAL'] = round(microtime(1) - $start, 4) . " s";
// ksort($this->TIMES);
echo '<pre>' . print_r($this->TIMES, 1) . '</pre>';
}
return $template;
}
// // дописывание массива переменных из шаблона
// // (хак для Бурцева)
// 0.1.51 - убрали; все равно Бурцев не пользуется
// function addvars($matches) {
// // if ($this->profiling)
// // // $start = microtime(1);
// //
// // $module_name = 'module_'.$matches[1];
// // # ДОБАВИТЬ КЛАССЫ ПОТОМ
// // $args = (isset($matches['args']))
// // // ? explode(',', mb_substr($matches['args'], 1, -1) ) // убираем скобки
// // // : array();
// // $this->vars = array_merge(
// // // $this->vars,
// // // call_user_func_array($module_name, $args)
// // // ); // call_user_func_array быстрее, чем call_user_func
// //
// // if ($this->profiling)
// // // $this->write_time(__FUNCTION__, $start, microtime(1));
// //
// // return TRUE;
// }
function var_value($string)
{
if ($this->profiling) {
$start = microtime(1);
}
if (mb_substr($string, 0, 1) == '=') { # константа
$C = mb_substr($string, 1);
$out = (defined($C)) ? constant($C) : '';
}
// можно делать if'ы:
// {*var_1|var_2|"строка"|134*}
// сработает первая часть, которая TRUE
elseif (mb_strpos($string, '|') !== false) {
$f = __FUNCTION__;
foreach (explode('|', $string) as $str) {
// останавливаемся при первом же TRUE
if ($val = $this->$f($str)) {
break;
}
}
$out = $val;
} elseif ( # скалярная величина
mb_substr($string, 0, 1) == '"'
AND
mb_substr($string, -1) == '"'
) {
$out = mb_substr($string, 1, -1);
} elseif (is_numeric($string)) {
$out = $string;
} else {
if (mb_substr($string, 0, 1) == '$') {
// глобальная переменная
if (!$this->no_global_vars) {
$string = mb_substr($string, 1);
$value = $GLOBALS;
} else {
$value = '';
}
} else {
$value = $this->vars;
}
// допустимы выражения типа {*var^COUNT*}
// (вернет count($var)) )
if (mb_substr($string, -6) == '^COUNT') {
$string = mb_substr($string, 0, -6);
$return_mode = 'count';
} else {
$return_mode = false;
} // default
$rawkeys = explode('.', $string);
$keys = [];
foreach ($rawkeys as $v) {
if ($v !== '') {
$keys[] = $v;
}
}
// array_filter() использовать не получается,
// т.к. числовой индекс 0 она тоже считает за FALSE и убирает
// поэтому нужно сравнение с учетом типа
// пустая строка указывает на корневой массив
foreach ($keys as $k) {
if (is_array($value) AND isset($value[$k])) {
$value = $value[$k];
} elseif (is_object($value)) {
try {
$value = $value->$k;
} catch (\Exception $e) {
$value = null;
break;
}
} else {
$value = null;
break;
}
}
// в зависимости от $return_mode действуем по-разному:
$out = (!$return_mode)
// возвращаем значение переменной (обычный случай)
? $value
// возвращаем число элементов в массиве
: (is_array($value) ? count($value) : false);
}
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function find_and_parse_cycle($template)
{
if ($this->profiling) {
$start = microtime(1);
}
// пришлось делать специальную функцию, чтобы реализовать рекурсию
$out = preg_replace_callback(
'/
{%\* ([^*]*) \*}
(.*?)
{\* \1 \*%}
/sx',
[$this, 'parse_cycle'],
$template
);
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function parse_cycle($matches)
{
if ($this->profiling) {
$start = microtime(1);
}
$array_name = $matches[1];
$array = $this->var_value($array_name);
$array_name_quoted = preg_quote($array_name);
if (!is_array($array)) {
return false;
}
$parsed = '';
$dot = ($array_name != '' AND $array_name != '$')
? '.'
: '';
$i = 0;
$n = 1;
foreach ($array as $key => $value) {
$parsed .= preg_replace(
[// массив поиска
"/(?<=[*=<>|&%])\s*$array_name_quoted\:\^KEY\b/",
"/(?<=[*=<>|&%])\s*$array_name_quoted\:\^i\b/",
"/(?<=[*=<>|&%])\s*$array_name_quoted\:\^N\b/",
"/(?<=[*=<>|&%])\s*$array_name_quoted\:/"
],
[// массив замены
'"' . $key . '"', // preg_quote для ключей нельзя,
'"' . $i . '"',
'"' . $n . '"',
$array_name . $dot . $key . '.' // т.к. в них бывает удобно
], // хранить некоторые данные,
$matches[2] // а preg_quote слишком многое экранирует
);
$i++;
$n++;
}
$parsed = $this->find_and_parse_cycle($parsed);
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $parsed;
}
function find_and_parse_if($template)
{
if ($this->profiling) {
$start = microtime(1);
}
$out = preg_replace_callback(
'/
{ (\?\!?) \*([^*]*)\* } # открывающее условие
(.*?) # тело if
{\*\2\* \1} # закрывающее условие
/sx',
[$this, 'parse_if'],
$template
);
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function parse_if($matches)
{
// 1 - ? или ?!
// 2 - тело условия
// 3 - тело if
if ($this->profiling) {
$start = microtime(1);
}
$final_check = false;
$separator = (strpos($matches[2], '&'))
? '&' // "AND"
: '|'; // "OR"
$parts = explode($separator, $matches[2]);
$parts = array_map('trim', $parts); // убираем пробелы по краям
$checks = [];
foreach ($parts as $p) {
$checks[] = $this->check_if_condition_part($p);
}
if ($separator == '|') // режим "OR"
{
$final_check = in_array(true, $checks);
} else // режим "AND"
{
$final_check = !in_array(false, $checks);
}
$result = ($matches[1] == '?')
? $final_check
: !$final_check;
$parsed_if = ($result)
? $this->find_and_parse_if($matches[3])
: '';
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $parsed_if;
}
function check_if_condition_part($str)
{
if ($this->profiling) {
$start = microtime(1);
}
preg_match(
'/^
(
"[^"*]+" # строковый литерал
| # или
[^*<>=]*+ # имя переменной
)
(?: # если есть сравнение с чем-то:
([=<>]) # знак сравнения
\s*
(.*) # то, с чем сравнивают
)?
$
/x',
$str,
$matches
);
$left = $this->var_value(trim($matches[1]));
if (!isset($matches[2])) {
$check = ($left == true);
} else {
$right = (isset($matches[3]))
? $this->var_value($matches[3])
: false;
switch ($matches[2]) {
case '=':
$check = ($left == $right);
break;
case '>':
$check = ($left > $right);
break;
case '<':
$check = ($left < $right);
break;
default:
$check = ($left == true);
}
}
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $check;
}
function parse_vars_templates_functions($matches)
{
if ($this->profiling) {
$start = microtime(1);
}
// тут обрабатываем сразу всё - и переменные, и шаблоны, и модули
$work = $matches[1];
$work = trim($work); // убираем пробелы по краям
if (mb_substr($work, 0, 1) == '@') { // модуль {* @name(arg1,arg2) | template *}
$p = '/
^
([^(|]++) # 1 - имя модуля
(?: \( ([^)]*+) \) \s* )? # 2 - аргументы
(?: \| \s* (.*+) )? # 3 - это уже до конца
$ # (именно .*+, а не .++)
/x';
if (preg_match($p, mb_substr($work, 1), $m)) {
$function_name = $this->get_var_or_string($m[1]);
// С версии 0.1.51 - проверяем по специальному списку
// if (PHP_VERSION_ID / 100 > 506) { // это включим позже, получим PHP 5.6
// $list = - тут ссылка на константу из namespace
// else
global $WEBSUN_ALLOWED_CALLBACKS;
$list = $WEBSUN_ALLOWED_CALLBACKS;
// }
if ($list and in_array($function_name, $list)) {
$allowed = true;
} else {
$allowed = false;
trigger_error("<b>$function_name()</b> is not in the list of allowed callbacks.", E_USER_WARNING);
}
if ($allowed) {
$args = [];
if (isset($m[2])) {
preg_match_all('/[^",]+|"[^"]*"/', $m[2], $tmp);
if ($tmp) {
// от промежутков между аргументами и запятыми останутся пробелы; их надо убрать
$tmp = array_filter(array_map('trim', $tmp[0]));
$args = array_map([$this, 'get_var_or_string'], $tmp);
}
unset($tmp);
}
$subvars = call_user_func_array($function_name, $args);
// print_r(array_map( array($this, 'get_var_or_string'), explode(',', $m[2]) )); exit;
if (isset($m[3])) // передали указание на шаблон
{
$html = $this->call_template($m[3], $subvars);
} else {
$html = $subvars;
} // шаблон не указан => модуль возвращает строку
} else {
$html = '';
}
} else {
$html = '';
} // вызов модуля сделан некорректно
} elseif (mb_substr($work, 0, 1) == '+') {
// шаблон - {* +*vars_var*|*tpl_var* *}
// переменная как шаблон - {* +*var* | >*template_inside* *}
$html = '';
$parts = preg_split(
'/(?<=[\*\s])\|(?=[\*\s])/', // вертикальная черта
mb_substr($work, 1) // должна ловиться только как разделитель
// между переменной и шаблоном, но не должна ловиться
// как разделитель внутри нотации переменой или шаблона
// (например, {* + *var1|$GLOBAL* | *tpl1|tpl2* *}
);
$parts = array_map('trim', $parts); // убираем пробелы по краям
if (!isset($parts[1])) { // если нет разделителя (|) - значит,
// передали только имя шаблона +template
$html = $this->call_template($parts[0], $this->vars);
} else {
$varname_string = mb_substr($parts[0], 1, -1); // убираем звездочки
// {* +*vars* | шаблон *} - простая передача переменной шаблону
// {* +*?vars* | шаблон *} - подключение шаблона только в случае, если vars == TRUE
// {* +*%vars* | шаблон *} - подключение шаблона не для самого vars, а для каждого его дочернего элемента
$indicator = mb_substr($varname_string, 0, 1);
if ($indicator == '?') {
if ($subvars = $this->var_value(mb_substr($varname_string, 1))) // 0.1.27 $html = $this->parse_child_template($tplname, $subvars);
{
$html = $this->call_template($parts[1], $subvars);
}
} elseif ($indicator == '%') {
if ($subvars = $this->var_value(mb_substr($varname_string, 1))) {
foreach ($subvars as $row) {
// 0.1.27 $html .= $this->parse_child_template($tplname, $row);
$html .= $this->call_template($parts[1], $row);
}
}
} else {
$subvars = $this->var_value($varname_string);
// 0.1.27 $html = $this->parse_child_template($tplname, $subvars);
$html = $this->call_template($parts[1], $subvars);
}
}
} else {
$html = $this->var_value($work);
} // переменная (+ константы - тут же)
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $html;
}
function call_template($template_notation, $vars)
{
if ($this->profiling) {
$start = microtime(1);
}
// $template_notation - либо путь к шаблону,
// либо переменная, содержащая путь к шаблону,
// либо шаблон прямо в переменной - если >*var*
$c = __CLASS__; // нужен объект этого же класса - делаем
$subobject = new $c([
'data' => $vars,
'templates_root' => $this->templates_root_dir,
'predecessor' => $this,
'no_global_vars' => $this->no_global_vars,
'profiling' => $this->profiling,
]);
$template_notation = trim($template_notation);
if (mb_substr($template_notation, 0, 1) == '>') {
// шаблон прямо в переменной
$v = mb_substr($template_notation, 1);
$subtemplate = $this->get_var_or_string($v);
$subobject->templates_current_dir = $this->templates_current_dir;
} else {
$path = $this->get_var_or_string($template_notation);
$subobject->templates_current_dir = pathinfo($this->template_real_path($path), PATHINFO_DIRNAME) . '/';
$subtemplate = $this->get_template($path);
}
$result = $subobject->parse_template($subtemplate);
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $result;
}
function get_var_or_string($str)
{
// используется, в основном,
// для получения имён шаблонов и модулей
$str = trim($str);
if ($this->profiling) {
$start = microtime(1);
}
if (mb_substr($str, 0, 1) == '*' AND mb_substr($str, -1) == '*') {
$out = $this->var_value(mb_substr($str, 1, -1));
} // если вокруг есть звездочки - значит, перменная
else // нет звездочек - значит, обычная строка-литерал
{
$out = (mb_substr($str, 0, 1) == '"' AND mb_substr($str, -1) == '"') // строка
? mb_substr($str, 1, -1)
: $str;
}
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function get_template($tpl)
{
if ($this->profiling) {
$start = microtime(1);
}
if (!$tpl) {
return false;
}
$tpl_real_path = $this->template_real_path($tpl);
$ext = pathinfo($tpl_real_path, PATHINFO_EXTENSION);
if (!in_array($ext, $this->allowed_extensions)) {
trigger_error(
"Template's <b>$tpl_real_path</b> extension is not in the allowed list ("
. implode(", ", $this->allowed_extensions) . ").
Check <b>allowed_extensions</b> option.",
E_USER_WARNING
);
return '';
}
// return rtrim(file_get_contents($tpl_real_path), "\r\n");
// (убираем перенос строки, присутствующий в конце любого файла)
$out = preg_replace(
'/\r?\n$/',
'',
file_get_contents($tpl_real_path)
);
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function template_real_path($tpl)
{
// функция определяет реальный путь к шаблону в файловой системе
// первый символ пути к шаблону определяет тип пути
// если в начале адреса есть / - интерпретируем как абсолютный путь ФС
// если второй символ пути - двоеточие (путь вида C:/ - Windows) -
// также интепретируем как абсолютный путь ФС
// если есть ^ - отталкиваемся от $templates_root_dir
// если $ - от $_SERVER[DOCUMENT_ROOT]
// во всех остальных случаях отталкиваемся от каталога текущего шаблона - templates_current_dir
if ($this->profiling) {
$start = microtime(1);
}
$dir_indicator = mb_substr($tpl, 0, 1);
$adjust_tpl_path = true;
if ($dir_indicator == '^') {
$dir = $this->templates_root_dir;
} elseif ($dir_indicator == '$') {
$dir = $_SERVER['DOCUMENT_ROOT'];
} elseif ($dir_indicator == '/') {
$dir = '';
$adjust_tpl_path = false;
} // абсолютный путь для ФС
else {
if (mb_substr($tpl, 1, 1) == ':') // Windows - указан абсолютный путь - вида С:/...
{
$dir = '';
} else {
$dir = $this->templates_current_dir;
}
$adjust_tpl_path = false; // в обоих случаях строку к пути менять не надо
}
if ($adjust_tpl_path) {
$tpl = mb_substr($tpl, 1);
}
$tpl_real_path = $dir . $tpl;
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $tpl_real_path;
}
function write_time($method, $start, $end)
{
//echo ($this->predecessor) . '<br>';
if (!$this->predecessor) {
$time = &$this->TIMES;
} else {
$time = &$this->predecessor->TIMES;
}
if (!isset($time[$method])) {
$time[$method] = [
'n' => 0,
'last' => 0,
'total' => 0,
'avg' => 0
];
}
$time[$method]['n'] += 1;
$time[$method]['last'] = round($end - $start, 4);
$time[$method]['total'] += $time[$method]['last'];
$time[$method]['avg'] = round($time[$method]['total'] / $time[$method]['n'], 4);
}
}
function websun_parse_template_path(
$data,
$template_path,
$templates_root_dir = false,
$no_global_vars = false
// $profiling = FALSE - пока убрали
)
{
// функция-обёртка для быстрого вызова класса
// принимает шаблон в виде пути к нему
$W = new websun([
'data' => $data,
'templates_root' => $templates_root_dir,
'no_global_vars' => $no_global_vars
]);
$tpl = $W->get_template($template_path);
$W->templates_current_dir = pathinfo($W->template_real_path($template_path), PATHINFO_DIRNAME) . '/';
$string = $W->parse_template($tpl);
return $string;
}
function websun_parse_template(
$data,
$template_code,
$templates_root_dir = false,
$no_global_vars = false
// profiling пока убрали
)
{
// функция-обёртка для быстрого вызова класса
// принимает шаблон непосредственно в виде кода
$W = new websun([
'data' => $data,
'templates_root' => $templates_root_dir,
'no_global_vars' => $no_global_vars
]);
$string = $W->parse_template($template_code);
return $string;
}
?>
|
Java
|
/* Since the td elements are the ones that actually get colored, don't bother
with the row itself. */
.HighlightMe td {
background-color: hsl(36, 100%, 75%) !important;
}
/* Turn the transparent boxes white */
.HighlightMe .notstarted {
background-color: white;
}
|
Java
|
/*!
* speedt
* Copyright(c) 2015 speedt <13837186852@qq.com>
* BSD 3 Licensed
*/
'use strict';
var utils = require('speedt-utils');
var Service = function(app){
var self = this;
// TODO
self.serverId = app.getServerId();
self.connCount = 0;
self.loginedCount = 0;
self.logined = {};
};
module.exports = Service;
var proto = Service.prototype;
proto.increaseConnectionCount = function(){
return ++this.connCount;
};
proto.decreaseConnectionCount = function(uid){
var self = this;
// TODO
var result = [--self.connCount];
// TODO
if(uid) result.push(removeLoginedUser.call(self, uid));
return result;
};
proto.replaceLoginedUser = function(uid, info){
var self = this;
// TODO
var user = self.logined[uid];
if(user) return updateUserInfo.call(self, user, info);
// TODO
self.loginedCount++;
// TODO
info.uid = uid;
self.logined[uid] = info;
};
var updateUserInfo = function(user, info){
var self = this;
// TODO
for(var p in info){
if(info.hasOwnProperty(p) && typeof 'function' !== info[p]){
self.logined[user.uid][p] = info[p];
} // END
} // END
};
var removeLoginedUser = function(uid){
var self = this;
// TODO
if(!self.logined[uid]) return;
// TODO
delete self.logined[uid];
// TODO
return --self.loginedCount;
};
proto.getStatisticsInfo = function(){
var self = this;
return {
serverId: self.serverId,
connCount: self.connCount,
loginedCount: self.loginedCount,
logined: self.logined
};
};
|
Java
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// GCC 5 does not evaluate static assertions dependent on a template parameter.
// UNSUPPORTED: gcc-5
// UNSUPPORTED: c++98, c++03
// <string>
// Test that hash specializations for <string> require "char_traits<_CharT>" not just any "_Trait".
#include <string>
template <class _CharT>
struct trait // copied from <__string>
{
typedef _CharT char_type;
typedef int int_type;
typedef std::streamoff off_type;
typedef std::streampos pos_type;
typedef std::mbstate_t state_type;
static inline void assign(char_type& __c1, const char_type& __c2) {
__c1 = __c2;
}
static inline bool eq(char_type __c1, char_type __c2) { return __c1 == __c2; }
static inline bool lt(char_type __c1, char_type __c2) { return __c1 < __c2; }
static int compare(const char_type* __s1, const char_type* __s2, size_t __n);
static size_t length(const char_type* __s);
static const char_type* find(const char_type* __s, size_t __n,
const char_type& __a);
static char_type* move(char_type* __s1, const char_type* __s2, size_t __n);
static char_type* copy(char_type* __s1, const char_type* __s2, size_t __n);
static char_type* assign(char_type* __s, size_t __n, char_type __a);
static inline int_type not_eof(int_type __c) {
return eq_int_type(__c, eof()) ? ~eof() : __c;
}
static inline char_type to_char_type(int_type __c) { return char_type(__c); }
static inline int_type to_int_type(char_type __c) { return int_type(__c); }
static inline bool eq_int_type(int_type __c1, int_type __c2) {
return __c1 == __c2;
}
static inline int_type eof() { return int_type(EOF); }
};
template <class CharT>
void test() {
typedef std::basic_string<CharT, trait<CharT> > str_t;
std::hash<str_t>
h; // expected-error-re 4 {{{{call to implicitly-deleted default constructor of 'std::hash<str_t>'|implicit instantiation of undefined template}} {{.+}}}}}}
(void)h;
}
int main(int, char**) {
test<char>();
test<wchar_t>();
test<char16_t>();
test<char32_t>();
return 0;
}
|
Java
|
/*=========================================================================
Program: Advanced Normalization Tools
Module: $RCSfile: itkANTSImageRegistrationOptimizer.h,v $
Language: C++
Date: $Date: 2009/04/22 01:00:17 $
Version: $Revision: 1.44 $
Copyright (c) ConsortiumOfANTS. All rights reserved.
See accompanying COPYING.txt or
http://sourceforge.net/projects/advants/files/ANTS/ANTSCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef __itkANTSImageRegistrationOptimizer_h
#define __itkANTSImageRegistrationOptimizer_h
#include "itkObject.h"
#include "itkObjectFactory.h"
#include "itkVectorGaussianInterpolateImageFunction.h"
#include "antsCommandLineParser.h"
#include "itkShiftScaleImageFilter.h"
#include "itkMinimumMaximumImageFilter.h"
#include "itkImage.h"
#include "itkMacro.h"
#include "ReadWriteImage.h"
#include "itkCenteredEuler3DTransform.h"
#include "itkQuaternionRigidTransform.h"
#include "itkANTSAffine3DTransform.h"
#include "itkANTSCenteredAffine2DTransform.h"
#include "itkCenteredTransformInitializer.h"
#include "itkTransformFileReader.h"
#include "itkTransformFileWriter.h"
#include "itkFiniteDifferenceFunction.h"
#include "itkFixedArray.h"
#include "itkANTSSimilarityMetric.h"
#include "itkVectorExpandImageFilter.h"
//#include "itkNeighbohoodAlgorithm.h"
#include "itkPDEDeformableRegistrationFilter.h"
#include "itkWarpImageFilter.h"
#include "itkWarpImageMultiTransformFilter.h"
#include "itkDeformationFieldFromMultiTransformFilter.h"
#include "itkWarpImageWAffineFilter.h"
#include "itkPointSet.h"
#include "itkVector.h"
#include "itkBSplineScatteredDataPointSetToImageFilter.h"
#include "itkGeneralToBSplineDeformationFieldFilter.h"
#include "ANTS_affine_registration2.h"
#include "itkVectorFieldGradientImageFunction.h"
#include "itkBSplineInterpolateImageFunction.h"
namespace itk {
template<unsigned int TDimension = 3, class TReal = float>
class ITK_EXPORT ANTSImageRegistrationOptimizer
: public Object
{
public:
/** Standard class typedefs. */
typedef ANTSImageRegistrationOptimizer Self;
typedef Object Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro( Self );
/** Run-time type information (and related methods). */
itkTypeMacro( ANTSImageRegistrationOptimizer, Object );
itkStaticConstMacro( Dimension, unsigned int, TDimension );
itkStaticConstMacro( ImageDimension, unsigned int, TDimension );
typedef TReal RealType;
typedef Image<RealType,
itkGetStaticConstMacro( Dimension )> ImageType;
typedef typename ImageType::Pointer ImagePointer;
typedef itk::MatrixOffsetTransformBase< double, ImageDimension, ImageDimension > TransformType;
/** Point Types for landmarks and labeled point-sets */
typedef itk::ANTSLabeledPointSet<Dimension> LabeledPointSetType;
typedef typename LabeledPointSetType::Pointer LabeledPointSetPointer;
typedef typename LabeledPointSetType::PointSetType PointSetType;
typedef typename PointSetType::Pointer PointSetPointer;
typedef typename PointSetType::PointType PointType;
typedef typename PointSetType::PixelType PointDataType;
typedef typename ImageType::PointType ImagePointType;
typedef itk::MatrixOffsetTransformBase<double, TDimension, TDimension> AffineTransformType;
typedef typename AffineTransformType::Pointer AffineTransformPointer;
typedef OptAffine<AffineTransformPointer, ImagePointer> OptAffineType;
typedef itk::Vector<float,ImageDimension> VectorType;
typedef itk::Image<VectorType,ImageDimension> DeformationFieldType;
typedef typename DeformationFieldType::Pointer DeformationFieldPointer;
typedef itk::Image<VectorType,ImageDimension+1> TimeVaryingVelocityFieldType;
typedef typename TimeVaryingVelocityFieldType::Pointer TimeVaryingVelocityFieldPointer;
typedef itk::VectorLinearInterpolateImageFunction<TimeVaryingVelocityFieldType,float> VelocityFieldInterpolatorType;
typedef itk::VectorGaussianInterpolateImageFunction<TimeVaryingVelocityFieldType,float> VelocityFieldInterpolatorType2;
typedef typename DeformationFieldType::IndexType IndexType;
typedef ants::CommandLineParser ParserType;
typedef typename ParserType::OptionType OptionType;
typedef GeneralToBSplineDeformationFieldFilter<DeformationFieldType> BSplineFilterType;
typedef FixedArray<RealType,
itkGetStaticConstMacro( ImageDimension )> ArrayType;
/** Typedefs for similarity metrics */
typedef ANTSSimilarityMetric <itkGetStaticConstMacro( Dimension ), float> SimilarityMetricType;
typedef typename SimilarityMetricType::Pointer SimilarityMetricPointer;
typedef std::vector<SimilarityMetricPointer> SimilarityMetricListType;
/** FiniteDifferenceFunction type. */
typedef FiniteDifferenceFunction<DeformationFieldType> FiniteDifferenceFunctionType;
typedef typename FiniteDifferenceFunctionType::TimeStepType TimeStepType;
typedef typename
FiniteDifferenceFunctionType::Pointer FiniteDifferenceFunctionPointer;
typedef AvantsPDEDeformableRegistrationFunction<ImageType,ImageType,
DeformationFieldType> MetricBaseType;
typedef typename MetricBaseType::Pointer MetricBaseTypePointer;
/* Jacobian and other calculations */
typedef itk::VectorFieldGradientImageFunction<DeformationFieldType> JacobianFunctionType;
/** Set functions */
void SetAffineTransform(AffineTransformPointer A) {this->m_AffineTransform=A;}
void SetDeformationField(DeformationFieldPointer A) {this->m_DeformationField=A;}
void SetInverseDeformationField(DeformationFieldPointer A) {this->m_InverseDeformationField=A;}
void SetMaskImage( ImagePointer m) { this->m_MaskImage=m; }
void SetFixedImageAffineTransform(AffineTransformPointer A) {this->m_FixedImageAffineTransform=A;}
AffineTransformPointer GetFixedImageAffineTransform() {return this->m_FixedImageAffineTransform;}
/** Get functions */
AffineTransformPointer GetAffineTransform() {return this->m_AffineTransform;}
DeformationFieldPointer GetDeformationField( ) {return this->m_DeformationField;}
DeformationFieldPointer GetInverseDeformationField() {return this->m_InverseDeformationField;}
/** Initialize all parameters */
void SetNumberOfLevels(unsigned int i) {this->m_NumberOfLevels=i;}
void SetParser( typename ParserType::Pointer P ) {this->m_Parser=P;}
/** Basic operations */
DeformationFieldPointer CopyDeformationField( DeformationFieldPointer input );
std::string localANTSGetFilePrefix(const char *str){
std::string filename = str;
std::string::size_type pos = filename.rfind( "." );
std::string filepre = std::string( filename, 0, pos );
if ( pos != std::string::npos ){
std::string extension = std::string( filename, pos, filename.length()-1);
if (extension==std::string(".gz")){
pos = filepre.rfind( "." );
extension = std::string( filepre, pos, filepre.length()-1 );
}
// if (extension==".txt") return AFFINE_FILE;
// else return DEFORMATION_FILE;
}
// else{
// return INVALID_FILE;
//}
return filepre;
}
void SmoothDeformationField(DeformationFieldPointer field, bool TrueEqualsGradElseTotal )
{
typename ParserType::OptionType::Pointer regularizationOption
= this->m_Parser->GetOption( "regularization" );
if ( ( regularizationOption->GetValue() ).find( "DMFFD" )
!= std::string::npos )
{
if( ( !TrueEqualsGradElseTotal && this->m_TotalSmoothingparam == 0.0 ) ||
( TrueEqualsGradElseTotal && this->m_GradSmoothingparam == 0.0 ) )
{
return;
}
ArrayType meshSize;
unsigned int splineOrder = this->m_BSplineFieldOrder;
float bsplineKernelVariance = static_cast<float>( splineOrder + 1 ) / 12.0;
unsigned int numberOfLevels = 1;
if( TrueEqualsGradElseTotal )
{
if( this->m_GradSmoothingparam < 0.0 )
{
meshSize = this->m_GradSmoothingMeshSize;
for( unsigned int d = 0; d < ImageDimension; d++ )
{
meshSize[d] *= static_cast<unsigned int>(
vcl_pow( 2.0, static_cast<int>( this->m_CurrentLevel ) ) );
}
}
else
{
float spanLength = vcl_sqrt( this->m_GradSmoothingparam /
bsplineKernelVariance );
for( unsigned int d = 0; d < ImageDimension; d++ )
{
meshSize[d] = static_cast<unsigned int>(
field->GetLargestPossibleRegion().GetSize()[d] /
spanLength + 0.5 );
}
}
this->SmoothDeformationFieldBSpline( field, meshSize, splineOrder,
numberOfLevels );
}
else
{
if( this->m_TotalSmoothingparam < 0.0 )
{
meshSize = this->m_TotalSmoothingMeshSize;
for( unsigned int d = 0; d < ImageDimension; d++ )
{
meshSize[d] *= static_cast<unsigned int>(
vcl_pow( 2.0, static_cast<int>( this->m_CurrentLevel ) ) );
}
}
else
{
float spanLength = vcl_sqrt( this->m_TotalSmoothingparam /
bsplineKernelVariance );
for( unsigned int d = 0; d < ImageDimension; d++ )
{
meshSize[d] = static_cast<unsigned int>(
field->GetLargestPossibleRegion().GetSize()[d] /
spanLength + 0.5 );
}
}
RealType maxMagnitude = 0.0;
ImageRegionIterator<DeformationFieldType> It( field,
field->GetLargestPossibleRegion() );
for( It.GoToBegin(); !It.IsAtEnd(); ++It )
{
RealType magnitude = ( It.Get() ).GetNorm();
if( magnitude > maxMagnitude )
{
maxMagnitude = magnitude;
}
}
this->SmoothDeformationFieldBSpline( field, meshSize, splineOrder,
numberOfLevels );
if( maxMagnitude > 0.0 )
{
for( It.GoToBegin(); !It.IsAtEnd(); ++It )
{
It.Set( It.Get() / maxMagnitude );
}
}
}
}
else // Gaussian
{
float sig=0;
if (TrueEqualsGradElseTotal) sig=this->m_GradSmoothingparam;
else sig=this->m_TotalSmoothingparam;
this->SmoothDeformationFieldGauss(field,sig);
}
}
void SmoothDeformationFieldGauss(DeformationFieldPointer field = NULL,
float sig=0.0, bool useparamimage=false, unsigned int lodim=ImageDimension);
// float = smoothingparam, int = maxdim to smooth
void SmoothVelocityGauss(TimeVaryingVelocityFieldPointer field,float,unsigned int);
void SmoothDeformationFieldBSpline(DeformationFieldPointer field, ArrayType meshSize,
unsigned int splineorder, unsigned int numberoflevels );
DeformationFieldPointer ComputeUpdateFieldAlternatingMin(DeformationFieldPointer fixedwarp, DeformationFieldPointer movingwarp, PointSetPointer fpoints=NULL, PointSetPointer wpoints=NULL,DeformationFieldPointer updateFieldInv=NULL, bool updateenergy=true);
DeformationFieldPointer ComputeUpdateField(DeformationFieldPointer fixedwarp, DeformationFieldPointer movingwarp, PointSetPointer fpoints=NULL, PointSetPointer wpoints=NULL,DeformationFieldPointer updateFieldInv=NULL, bool updateenergy=true);
TimeVaryingVelocityFieldPointer ExpandVelocity( ) {
float expandFactors[ImageDimension+1];
expandFactors[ImageDimension]=1;
m_Debug=false;
for( int idim = 0; idim < ImageDimension; idim++ )
{
expandFactors[idim] = (float)this->m_CurrentDomainSize[idim]/(float) this->m_TimeVaryingVelocity->GetLargestPossibleRegion().GetSize()[idim];
if( expandFactors[idim] < 1 ) expandFactors[idim] = 1;
if (this->m_Debug) std::cout << " ExpFac " << expandFactors[idim] << " curdsz " << this->m_CurrentDomainSize[idim] << std::endl;
}
VectorType pad; pad.Fill(0);
typedef VectorExpandImageFilter<TimeVaryingVelocityFieldType, TimeVaryingVelocityFieldType> ExpanderType;
typename ExpanderType::Pointer m_FieldExpander = ExpanderType::New();
m_FieldExpander->SetInput(this->m_TimeVaryingVelocity);
m_FieldExpander->SetExpandFactors( expandFactors );
m_FieldExpander->SetEdgePaddingValue( pad );
m_FieldExpander->UpdateLargestPossibleRegion();
return m_FieldExpander->GetOutput();
}
DeformationFieldPointer ExpandField(DeformationFieldPointer field, typename ImageType::SpacingType targetSpacing)
{
// this->m_Debug=true;
float expandFactors[ImageDimension];
for( int idim = 0; idim < ImageDimension; idim++ )
{
expandFactors[idim] = (float)this->m_CurrentDomainSize[idim]/(float)field->GetLargestPossibleRegion().GetSize()[idim];
if( expandFactors[idim] < 1 ) expandFactors[idim] = 1;
// if (this->m_Debug) std::cout << " ExpFac " << expandFactors[idim] << " curdsz " << this->m_CurrentDomainSize[idim] << std::endl;
}
VectorType pad;
pad.Fill(0);
typedef VectorExpandImageFilter<DeformationFieldType, DeformationFieldType> ExpanderType;
typename ExpanderType::Pointer m_FieldExpander = ExpanderType::New();
m_FieldExpander->SetInput(field);
m_FieldExpander->SetExpandFactors( expandFactors );
// use default
m_FieldExpander->SetEdgePaddingValue( pad );
m_FieldExpander->UpdateLargestPossibleRegion();
typename DeformationFieldType::Pointer fieldout=m_FieldExpander->GetOutput();
fieldout->SetSpacing(targetSpacing);
fieldout->SetOrigin(field->GetOrigin());
if (this->m_Debug) std::cout << " Field size " << fieldout->GetLargestPossibleRegion().GetSize() << std::endl;
//this->m_Debug=false;
return fieldout;
}
ImagePointer GetVectorComponent(DeformationFieldPointer field, unsigned int index)
{
// Initialize the Moving to the displacement field
typedef DeformationFieldType FieldType;
typename ImageType::Pointer sfield=ImageType::New();
sfield->SetSpacing( field->GetSpacing() );
sfield->SetOrigin( field->GetOrigin() );
sfield->SetDirection( field->GetDirection() );
sfield->SetLargestPossibleRegion(field->GetLargestPossibleRegion() );
sfield->SetRequestedRegion(field->GetRequestedRegion() );
sfield->SetBufferedRegion( field->GetBufferedRegion() );
sfield->Allocate();
typedef itk::ImageRegionIteratorWithIndex<FieldType> Iterator;
Iterator vfIter( field, field->GetLargestPossibleRegion() );
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter)
{
VectorType v1=vfIter.Get();
sfield->SetPixel(vfIter.GetIndex(),v1[index]);
}
return sfield;
}
ImagePointer SubsampleImage( ImagePointer, RealType , typename ImageType::PointType outputOrigin, typename ImageType::DirectionType outputDirection, AffineTransformPointer aff = NULL);
DeformationFieldPointer SubsampleField( DeformationFieldPointer field, typename ImageType::SizeType
targetSize, typename ImageType::SpacingType targetSpacing )
{
std::cout << "FIXME -- NOT DONE CORRECTLY " << std::endl;
std::cout << "FIXME -- NOT DONE CORRECTLY " << std::endl;
std::cout << "FIXME -- NOT DONE CORRECTLY " << std::endl;
std::cout << "FIXME -- NOT DONE CORRECTLY " << std::endl;
std::cout << " SUBSAM FIELD SUBSAM FIELD SUBSAM FIELD " << std::endl;
typename DeformationFieldType::Pointer sfield=DeformationFieldType::New();
for (unsigned int i=0; i < ImageDimension; i++)
{
typename ImageType::Pointer precomp=this->GetVectorComponent(field,i);
typename ImageType::Pointer comp=this->SubsampleImage(precomp,targetSize,targetSpacing);
if ( i==0 )
{
sfield->SetSpacing( comp->GetSpacing() );
sfield->SetOrigin( comp->GetOrigin() );
sfield->SetDirection( comp->GetDirection() );
sfield->SetLargestPossibleRegion(comp->GetLargestPossibleRegion() );
sfield->SetRequestedRegion(comp->GetRequestedRegion() );
sfield->SetBufferedRegion( comp->GetBufferedRegion() );
sfield->Allocate();
}
typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
typedef typename DeformationFieldType::PixelType VectorType;
VectorType v1;
VectorType zero;
zero.Fill(0.0);
Iterator vfIter( sfield, sfield->GetLargestPossibleRegion() );
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter)
{
v1=vfIter.Get();
v1[i]=comp->GetPixel(vfIter.GetIndex());
vfIter.Set(v1);
}
}
return sfield;
}
PointSetPointer WarpMultiTransform(ImagePointer referenceimage, ImagePointer movingImage, PointSetPointer movingpoints, AffineTransformPointer aff , DeformationFieldPointer totalField, bool doinverse , AffineTransformPointer fixedaff )
{
if (!movingpoints) { std::cout << " NULL POINTS " << std::endl; return NULL; }
AffineTransformPointer affinverse=NULL;
if (aff)
{
affinverse=AffineTransformType::New();
aff->GetInverse(affinverse);
}
AffineTransformPointer fixedaffinverse=NULL;
if (fixedaff)
{
fixedaffinverse=AffineTransformType::New();
fixedaff->GetInverse(fixedaffinverse);
}
typedef itk::WarpImageMultiTransformFilter<ImageType,ImageType, DeformationFieldType, TransformType> WarperType;
typename WarperType::Pointer warper = WarperType::New();
warper->SetInput(movingImage);
warper->SetEdgePaddingValue( 0);
warper->SetSmoothScale(1);
if (!doinverse)
{
if (totalField) warper->PushBackDeformationFieldTransform(totalField);
if (fixedaff) warper->PushBackAffineTransform(fixedaff);
else if (aff) warper->PushBackAffineTransform(aff);
}
else
{
if (aff) warper->PushBackAffineTransform( affinverse );
else if (fixedaff) warper->PushBackAffineTransform(fixedaffinverse);
if (totalField) warper->PushBackDeformationFieldTransform(totalField);
}
warper->SetOutputOrigin(referenceimage->GetOrigin());
typename ImageType::SizeType size=referenceimage->GetLargestPossibleRegion().GetSize();
if (totalField) size=totalField->GetLargestPossibleRegion().GetSize();
warper->SetOutputSize(size);
typename ImageType::SpacingType spacing=referenceimage->GetSpacing();
if (totalField) spacing=totalField->GetSpacing();
warper->SetOutputSpacing(spacing);
warper->SetOutputDirection(referenceimage->GetDirection());
totalField->SetOrigin(referenceimage->GetOrigin() );
totalField->SetDirection(referenceimage->GetDirection() );
// warper->Update();
// std::cout << " updated in point warp " << std::endl;
PointSetPointer outputMesh = PointSetType::New();
unsigned long count = 0;
unsigned long sz1 = movingpoints->GetNumberOfPoints();
if (this->m_Debug) std::cout << " BEFORE # points " << sz1 << std::endl;
for (unsigned long ii=0; ii<sz1; ii++)
{
PointType point,wpoint;
PointDataType label=0;
movingpoints->GetPoint(ii,&point);
movingpoints->GetPointData(ii,&label);
// convert pointtype to imagepointtype
ImagePointType pt,wpt;
for (unsigned int jj=0; jj<ImageDimension; jj++) pt[jj]=point[jj];
bool bisinside = warper->MultiTransformSinglePoint(pt,wpt);
if (bisinside)
{
for (unsigned int jj=0; jj<ImageDimension; jj++) wpoint[jj]=wpt[jj];
outputMesh->SetPointData( count, label );
outputMesh->SetPoint( count, wpoint );
// if (ii % 100 == 0) std::cout << " pt " << pt << " wpt " << wpt << std::endl;
count++;
}
}
if (this->m_Debug) std::cout << " AFTER # points " << count << std::endl;
// if (count != sz1 ) std::cout << " WARNING: POINTS ARE MAPPING OUT OF IMAGE DOMAIN " << 1.0 - (float) count/(float)(sz1+1) << std::endl;
return outputMesh;
}
ImagePointer WarpMultiTransform( ImagePointer referenceimage, ImagePointer movingImage, AffineTransformPointer aff , DeformationFieldPointer totalField, bool doinverse , AffineTransformPointer fixedaff )
{
typedef typename ImageType::DirectionType DirectionType;
DirectionType rdirection=referenceimage->GetDirection();
DirectionType mdirection=movingImage->GetDirection();
AffineTransformPointer affinverse=NULL;
if (aff)
{
affinverse=AffineTransformType::New();
aff->GetInverse(affinverse);
}
AffineTransformPointer fixedaffinverse=NULL;
if (fixedaff)
{
fixedaffinverse=AffineTransformType::New();
fixedaff->GetInverse(fixedaffinverse);
}
DirectionType iddir;
iddir.Fill(0);
for (unsigned int i=0;i<ImageDimension;i++) iddir[i][i]=1;
typedef itk::LinearInterpolateImageFunction<ImageType,double> InterpolatorType1;
typedef itk::NearestNeighborInterpolateImageFunction<ImageType,double> InterpolatorType2;
typedef itk::BSplineInterpolateImageFunction<ImageType,double> InterpolatorType3;
typename InterpolatorType1::Pointer interp1 = InterpolatorType1::New();
typename InterpolatorType2::Pointer interpnn = InterpolatorType2::New();
typename InterpolatorType3::Pointer interpcu = InterpolatorType3::New();
this->m_UseMulti=true;
if (!this->m_UseMulti){
ImagePointer wmimage = this->SubsampleImage(movingImage , this->m_ScaleFactor , movingImage->GetOrigin() , movingImage->GetDirection() , aff );
typedef itk::WarpImageFilter<ImageType,ImageType, DeformationFieldType> WarperType;
typename WarperType::Pointer warper;
warper = WarperType::New();
warper->SetInput( wmimage);
warper->SetDeformationField(totalField);
warper->SetOutputSpacing(totalField->GetSpacing());
warper->SetOutputOrigin(totalField->GetOrigin());
warper->SetInterpolator(interp1);
if (this->m_UseNN) warper->SetInterpolator(interpnn);
if (this->m_UseBSplineInterpolation) warper->SetInterpolator(interpcu);
// warper->SetOutputSize(this->m_CurrentDomainSize);
// warper->SetEdgePaddingValue( 0 );
warper->Update();
return warper->GetOutput();
}
typedef itk::WarpImageMultiTransformFilter<ImageType,ImageType, DeformationFieldType, TransformType> WarperType;
typename WarperType::Pointer warper = WarperType::New();
warper->SetInput(movingImage);
warper->SetEdgePaddingValue( 0);
warper->SetSmoothScale(1);
warper->SetInterpolator(interp1);
if (this->m_UseNN) warper->SetInterpolator(interpnn);
if (!doinverse)
{
if (totalField) warper->PushBackDeformationFieldTransform(totalField);
if (fixedaff) warper->PushBackAffineTransform(fixedaff);
else if (aff) warper->PushBackAffineTransform(aff);
}
else
{
if (aff) warper->PushBackAffineTransform( affinverse );
else if (fixedaff) warper->PushBackAffineTransform(fixedaffinverse);
if (totalField) warper->PushBackDeformationFieldTransform(totalField);
}
warper->SetOutputOrigin(referenceimage->GetOrigin());
typename ImageType::SizeType size=referenceimage->GetLargestPossibleRegion().GetSize();
if (totalField) size=totalField->GetLargestPossibleRegion().GetSize();
warper->SetOutputSize(size);
typename ImageType::SpacingType spacing=referenceimage->GetSpacing();
if (totalField) spacing=totalField->GetSpacing();
warper->SetOutputSpacing(spacing);
warper->SetOutputDirection(referenceimage->GetDirection());
totalField->SetOrigin(referenceimage->GetOrigin() );
totalField->SetDirection(referenceimage->GetDirection() );
warper->Update();
if (this->m_Debug){
std::cout << " updated ok -- warped image output size " << warper->GetOutput()->GetLargestPossibleRegion().GetSize() << " requested size " << totalField->GetLargestPossibleRegion().GetSize() << std::endl;
}
typename ImageType::Pointer outimg=warper->GetOutput();
return outimg;
}
ImagePointer SmoothImageToScale(ImagePointer image , float scalingFactor )
{
typename ImageType::SpacingType inputSpacing = image->GetSpacing();
typename ImageType::RegionType::SizeType inputSize = image->GetRequestedRegion().GetSize();
typename ImageType::SpacingType outputSpacing;
typename ImageType::RegionType::SizeType outputSize;
RealType minimumSpacing = inputSpacing.GetVnlVector().min_value();
// RealType maximumSpacing = inputSpacing.GetVnlVector().max_value();
for ( unsigned int d = 0; d < Dimension; d++ )
{
RealType scaling = vnl_math_min( scalingFactor * minimumSpacing / inputSpacing[d],
static_cast<RealType>( inputSize[d] ) / 32.0 );
outputSpacing[d] = inputSpacing[d] * scaling;
outputSize[d] = static_cast<unsigned long>( inputSpacing[d] *
static_cast<RealType>( inputSize[d] ) / outputSpacing[d] + 0.5 );
typedef RecursiveGaussianImageFilter<ImageType, ImageType> GaussianFilterType;
typename GaussianFilterType::Pointer smoother = GaussianFilterType::New();
smoother->SetInputImage( image );
smoother->SetDirection( d );
smoother->SetNormalizeAcrossScale( false );
float sig = (outputSpacing[d]/inputSpacing[d]-1.0)*0.2;///(float)ImageDimension;
smoother->SetSigma(sig );
if ( smoother->GetSigma() > 0.0 )
{
smoother->Update();
image = smoother->GetOutput();
}
}
image=this->NormalizeImage(image);
return image;
}
typename ANTSImageRegistrationOptimizer<TDimension, TReal>::DeformationFieldPointer
IntegrateConstantVelocity(DeformationFieldPointer totalField, unsigned int ntimesteps, float timeweight);
/** Base optimization functions */
// AffineTransformPointer AffineOptimization(AffineTransformPointer &aff_init, OptAffine &affine_opt); // {return NULL;}
AffineTransformPointer AffineOptimization(OptAffineType &affine_opt); // {return NULL;}
std::string GetTransformationModel( ) { return this->m_TransformationModel; }
void SetTransformationModel( std::string s) {
this->m_TransformationModel=s;
std::cout << " Requested Transformation Model: " << this->m_TransformationModel << " : Using " << std::endl;
if ( this->m_TransformationModel == std::string("Elast") )
{
std::cout << "Elastic model for transformation. " << std::endl;
}
else if ( this->m_TransformationModel == std::string("SyN") )
{
std::cout << "SyN diffeomorphic model for transformation. " << std::endl;
}
else if ( this->m_TransformationModel == std::string("GreedyExp") )
{
std::cout << "Greedy Exp Diff model for transformation. Similar to Diffeomorphic Demons. Params same as Exp model. " << std::endl;
this->m_TransformationModel=std::string("GreedyExp");
}
else
{
std::cout << "Exp Diff model for transformation. " << std::endl;
this->m_TransformationModel=std::string("Exp");
}
}
void SetUpParameters()
{
/** Univariate Deformable Mapping */
// set up parameters for deformation restriction
std::string temp=this->m_Parser->GetOption( "Restrict-Deformation" )->GetValue();
this->m_RestrictDeformation = this->m_Parser->template ConvertVector<float>(temp);
if ( this->m_RestrictDeformation.size() != ImageDimension ) {
std::cout <<" You input a vector of size : " << this->m_RestrictDeformation.size() << " for --Restrict-Deformation. The vector length does not match the image dimension. Ignoring. " << std::endl;
for (unsigned int jj=0; jj<this->m_RestrictDeformation.size(); jj++ )
this->m_RestrictDeformation[jj]=0;
}
// set up max iterations per level
temp=this->m_Parser->GetOption( "number-of-iterations" )->GetValue();
this->m_Iterations = this->m_Parser->template ConvertVector<unsigned int>(temp);
this->SetNumberOfLevels(this->m_Iterations.size());
this->m_UseROI=false;
if ( typename OptionType::Pointer option = this->m_Parser->GetOption( "roi" ) )
{
temp=this->m_Parser->GetOption( "roi" )->GetValue();
this->m_RoiNumbers = this->m_Parser->template ConvertVector<float>(temp);
if ( temp.length() > 3 ) this->m_UseROI=true;
}
typename ParserType::OptionType::Pointer oOption
= this->m_Parser->GetOption( "output-naming" );
this->m_OutputNamingConvention=oOption->GetValue();
typename ParserType::OptionType::Pointer thicknessOption
= this->m_Parser->GetOption( "geodesic" );
if( thicknessOption->GetValue() == "true" || thicknessOption->GetValue() == "1" ) { this->m_ComputeThickness=1; this->m_SyNFullTime=2; }// asymm forces
else if( thicknessOption->GetValue() == "2" ) { this->m_ComputeThickness=1; this->m_SyNFullTime=1; } // symmetric forces
else this->m_ComputeThickness=0; // not full time varying stuff
/**
* Get transformation model and associated parameters
*/
typename ParserType::OptionType::Pointer transformOption
= this->m_Parser->GetOption( "transformation-model" );
this->SetTransformationModel( transformOption->GetValue() );
if ( transformOption->GetNumberOfParameters() >= 1 )
{
std::string parameter = transformOption->GetParameter( 0, 0 );
float temp=this->m_Parser->template Convert<float>( parameter );
this->m_Gradstep = temp;
this->m_GradstepAltered = temp;
}
else { this->m_Gradstep=0.5; this->m_GradstepAltered=0.5; }
if ( transformOption->GetNumberOfParameters() >= 2 )
{
std::string parameter = transformOption->GetParameter( 0, 1 );
this->m_NTimeSteps = this->m_Parser->template Convert<unsigned int>( parameter );
}
else this->m_NTimeSteps=1;
if ( transformOption->GetNumberOfParameters() >= 3 )
{
std::string parameter = transformOption->GetParameter( 0, 2 );
this->m_DeltaTime
= this->m_Parser->template Convert<float>( parameter );
if (this->m_DeltaTime > 1) this->m_DeltaTime=1;
if (this->m_DeltaTime <= 0) this->m_DeltaTime=0.001;
std::cout <<" set DT " << this->m_DeltaTime << std::endl;
this->m_SyNType=1;
}
else this->m_DeltaTime=0.1;
// if ( transformOption->GetNumberOfParameters() >= 3 )
// {
// std::string parameter = transformOption->GetParameter( 0, 2 );
// this->m_SymmetryType
// = this->m_Parser->template Convert<unsigned int>( parameter );
// }
/**
* Get regularization and associated parameters
*/
this->m_GradSmoothingparam = -1;
this->m_TotalSmoothingparam = -1;
this->m_GradSmoothingMeshSize.Fill( 0 );
this->m_TotalSmoothingMeshSize.Fill( 0 );
typename ParserType::OptionType::Pointer regularizationOption
= this->m_Parser->GetOption( "regularization" );
if( regularizationOption->GetValue() == "Gauss" )
{
if ( regularizationOption->GetNumberOfParameters() >= 1 )
{
std::string parameter = regularizationOption->GetParameter( 0, 0 );
this->m_GradSmoothingparam = this->m_Parser->template Convert<float>( parameter );
}
else this->m_GradSmoothingparam=3;
if ( regularizationOption->GetNumberOfParameters() >= 2 )
{
std::string parameter = regularizationOption->GetParameter( 0, 1 );
this->m_TotalSmoothingparam = this->m_Parser->template Convert<float>( parameter );
}
else this->m_TotalSmoothingparam=0.5;
if ( regularizationOption->GetNumberOfParameters() >= 3 )
{
std::string parameter = regularizationOption->GetParameter( 0, 2 );
this->m_GaussianTruncation = this->m_Parser->template Convert<float>( parameter );
}
else this->m_GaussianTruncation = 256;
std::cout <<" Grad Step " << this->m_Gradstep << " total-smoothing " << this->m_TotalSmoothingparam << " gradient-smoothing " << this->m_GradSmoothingparam << std::endl;
}
else if( ( regularizationOption->GetValue() ).find( "DMFFD" )
!= std::string::npos )
{
if ( regularizationOption->GetNumberOfParameters() >= 1 )
{
std::string parameter = regularizationOption->GetParameter( 0, 0 );
if( parameter.find( "x" ) != std::string::npos )
{
std::vector<unsigned int> gradMeshSize
= this->m_Parser->template ConvertVector<unsigned int>( parameter );
for( unsigned int d = 0; d < ImageDimension; d++ )
{
this->m_GradSmoothingMeshSize[d] = gradMeshSize[d];
}
}
else
{
this->m_GradSmoothingparam
= this->m_Parser->template Convert<float>( parameter );
}
}
else
{
this->m_GradSmoothingparam = 3.0;
}
if ( regularizationOption->GetNumberOfParameters() >= 2 )
{
std::string parameter = regularizationOption->GetParameter( 0, 1 );
if( parameter.find( "x" ) != std::string::npos )
{
std::vector<unsigned int> totalMeshSize
= this->m_Parser->template ConvertVector<unsigned int>( parameter );
for( unsigned int d = 0; d < ImageDimension; d++ )
{
this->m_TotalSmoothingMeshSize[d] = totalMeshSize[d];
}
}
else
{
this->m_TotalSmoothingparam
= this->m_Parser->template Convert<float>( parameter );
}
}
else
{
this->m_TotalSmoothingparam=0.5;
}
if ( regularizationOption->GetNumberOfParameters() >= 3 )
{
std::string parameter = regularizationOption->GetParameter( 0, 2 );
this->m_BSplineFieldOrder
= this->m_Parser->template Convert<unsigned int>( parameter );
}
else this->m_BSplineFieldOrder = 3;
std::cout <<" Grad Step " << this->m_Gradstep
<< " total-smoothing " << this->m_TotalSmoothingparam
<< " gradient-smoothing " << this->m_GradSmoothingparam
<< " bspline-field-order " << this->m_BSplineFieldOrder
<< std::endl;
}
else
{
this->m_GradSmoothingparam=3;
this->m_TotalSmoothingparam=0.5;
std::cout <<" Default Regularization is Gaussian smoothing with : " << this->m_GradSmoothingparam << " & " << this->m_TotalSmoothingparam << std::endl;
// itkExceptionMacro( "Invalid regularization: " << regularizationOption->GetValue() );
}
}
void ComputeMultiResolutionParameters(ImagePointer fixedImage )
{
VectorType zero;
zero.Fill(0);
/** Compute scale factors */
this->m_FullDomainSpacing = fixedImage->GetSpacing();
this->m_FullDomainSize = fixedImage->GetRequestedRegion().GetSize();
this->m_CurrentDomainSpacing = fixedImage->GetSpacing();
this->m_CurrentDomainSize = fixedImage->GetRequestedRegion().GetSize();
this->m_CurrentDomainDirection=fixedImage->GetDirection();
this->m_FullDomainOrigin.Fill(0);
this->m_CurrentDomainOrigin.Fill(0);
/** alter the input size based on information gained from the ROI information - if available */
if (this->m_UseROI)
{
for (unsigned int ii=0; ii<ImageDimension; ii++)
{
this->m_FullDomainSize[ii]= (typename ImageType::SizeType::SizeValueType) this->m_RoiNumbers[ii+ImageDimension];
this->m_FullDomainOrigin[ii]=this->m_RoiNumbers[ii];
}
std::cout << " ROI #s : size " << this->m_FullDomainSize << " orig " << this->m_FullDomainOrigin << std::endl;
}
RealType minimumSpacing = this->m_FullDomainSpacing.GetVnlVector().min_value();
// RealType maximumSpacing = this->m_FullDomainSpacing.GetVnlVector().max_value();
for ( unsigned int d = 0; d < Dimension; d++ )
{
RealType scaling = vnl_math_min( this->m_ScaleFactor * minimumSpacing / this->m_FullDomainSpacing[d], static_cast<RealType>( this->m_FullDomainSize[d] ) / 32.0 );
if (scaling < 1) scaling=1;
this->m_CurrentDomainSpacing[d] = this->m_FullDomainSpacing[d] * scaling;
this->m_CurrentDomainSize[d] = static_cast<unsigned long>( this->m_FullDomainSpacing[d] *static_cast<RealType>( this->m_FullDomainSize[d] ) / this->m_CurrentDomainSpacing[d] + 0.5 );
this->m_CurrentDomainOrigin[d] = static_cast<unsigned long>( this->m_FullDomainSpacing[d] *static_cast<RealType>( this->m_FullDomainOrigin[d] ) / this->m_CurrentDomainSpacing[d] + 0.5 );
}
// this->m_Debug=true;
if (this->m_Debug) std::cout << " outsize " << this->m_CurrentDomainSize << " curspc " << this->m_CurrentDomainSpacing << " fullspc " << this->m_FullDomainSpacing << " fullsz " << this->m_FullDomainSize << std::endl;
// this->m_Debug=false;
if (!this->m_DeformationField)
{/*FIXME -- need initial deformation strategy */
this->m_DeformationField=DeformationFieldType::New();
this->m_DeformationField->SetSpacing( this->m_CurrentDomainSpacing);
this->m_DeformationField->SetOrigin( fixedImage->GetOrigin() );
this->m_DeformationField->SetDirection( fixedImage->GetDirection() );
typename ImageType::RegionType region;
region.SetSize( this->m_CurrentDomainSize);
this->m_DeformationField->SetLargestPossibleRegion(region);
this->m_DeformationField->SetRequestedRegion(region);
this->m_DeformationField->SetBufferedRegion(region);
this->m_DeformationField->Allocate();
this->m_DeformationField->FillBuffer(zero);
std::cout << " allocated def field " << this->m_DeformationField->GetDirection() << std::endl;
//exit(0);
}
else
{
this->m_DeformationField=this->ExpandField(this->m_DeformationField,this->m_CurrentDomainSpacing);
if ( this->m_TimeVaryingVelocity ) this->ExpandVelocity();
}
}
ImagePointer NormalizeImage( ImagePointer image) {
typedef itk::MinimumMaximumImageFilter<ImageType> MinMaxFilterType;
typename MinMaxFilterType::Pointer minMaxFilter = MinMaxFilterType::New();
minMaxFilter->SetInput( image );
minMaxFilter->Update();
double min = minMaxFilter->GetMinimum();
double shift = -1.0 * static_cast<double>( min );
double scale = static_cast<double>( minMaxFilter->GetMaximum() );
scale += shift;
scale = 1.0 / scale;
typedef itk::ShiftScaleImageFilter<ImageType,ImageType> FilterType;
typename FilterType::Pointer filter = FilterType::New();
filter->SetInput( image );
filter->SetShift( shift );
filter->SetScale( scale );
filter->Update();
return filter->GetOutput();
}
void DeformableOptimization()
{
DeformationFieldPointer updateField = NULL;
this->SetUpParameters();
typename ImageType::SpacingType spacing;
VectorType zero;
zero.Fill(0);
std::cout << " setting N-TimeSteps = "
<< this->m_NTimeSteps << " trunc " << this->m_GaussianTruncation << std::endl;
unsigned int maxits=0;
for ( unsigned int currentLevel = 0; currentLevel < this->m_NumberOfLevels; currentLevel++ )
if ( this->m_Iterations[currentLevel] > maxits) maxits=this->m_Iterations[currentLevel];
if (maxits == 0)
{
this->m_DeformationField=NULL;
this->m_InverseDeformationField=NULL;
// this->ComputeMultiResolutionParameters(this->m_SimilarityMetrics[0]->GetFixedImage());
return;
}
/* this is a hack to force univariate mappings in the future,
we will re-cast this framework s.t. multivariate images can be used */
unsigned int numberOfMetrics=this->m_SimilarityMetrics.size();
for ( unsigned int metricCount = 1; metricCount < numberOfMetrics; metricCount++)
{
this->m_SimilarityMetrics[metricCount]->GetFixedImage( )->SetOrigin( this->m_SimilarityMetrics[0]->GetFixedImage()->GetOrigin());
this->m_SimilarityMetrics[metricCount]->GetFixedImage( )->SetDirection( this->m_SimilarityMetrics[0]->GetFixedImage()->GetDirection());
this->m_SimilarityMetrics[metricCount]->GetMovingImage( )->SetOrigin( this->m_SimilarityMetrics[0]->GetMovingImage()->GetOrigin());
this->m_SimilarityMetrics[metricCount]->GetMovingImage( )->SetDirection( this->m_SimilarityMetrics[0]->GetMovingImage()->GetDirection());
}
/* here, we assign all point set pointers to any single
non-null point-set pointer */
for (unsigned int metricCount=0; metricCount < numberOfMetrics; metricCount++)
{
for (unsigned int metricCount2=0; metricCount2 < numberOfMetrics; metricCount2++)
{
if (this->m_SimilarityMetrics[metricCount]->GetFixedPointSet())
this->m_SimilarityMetrics[metricCount2]->SetFixedPointSet(this->m_SimilarityMetrics[metricCount]->GetFixedPointSet());
if (this->m_SimilarityMetrics[metricCount]->GetMovingPointSet())
this->m_SimilarityMetrics[metricCount2]->SetMovingPointSet(this->m_SimilarityMetrics[metricCount]->GetMovingPointSet());
}
}
this->m_SmoothFixedImages.resize(numberOfMetrics,NULL);
this->m_SmoothMovingImages.resize(numberOfMetrics,NULL);
for ( unsigned int currentLevel = 0; currentLevel < this->m_NumberOfLevels; currentLevel++ )
{
this->m_CurrentLevel = currentLevel;
typedef Vector<float,1> ProfilePointDataType;
typedef Image<ProfilePointDataType, 1> CurveType;
typedef PointSet<ProfilePointDataType, 1> EnergyProfileType;
typedef typename EnergyProfileType::PointType ProfilePointType;
std::vector<EnergyProfileType::Pointer> energyProfiles;
energyProfiles.resize( numberOfMetrics );
for( unsigned int qq = 0; qq < numberOfMetrics; qq++ )
{
energyProfiles[qq] = EnergyProfileType::New();
energyProfiles[qq]->Initialize();
}
ImagePointer fixedImage;
ImagePointer movingImage;
this->m_GradstepAltered=this->m_Gradstep;
this->m_ScaleFactor = pow( 2.0, (int)static_cast<RealType>( this->m_NumberOfLevels-currentLevel-1 ) );
std::cout << " this->m_ScaleFactor " << this->m_ScaleFactor
<< " nlev " << this->m_NumberOfLevels << " curl " << currentLevel << std::endl;
/** FIXME -- here we assume the metrics all have the same image */
fixedImage = this->m_SimilarityMetrics[0]->GetFixedImage();
movingImage = this->m_SimilarityMetrics[0]->GetMovingImage();
spacing=fixedImage->GetSpacing();
this->ComputeMultiResolutionParameters(fixedImage);
std::cout << " Its at this level " << this->m_Iterations[currentLevel] << std::endl;
/* generate smoothed images for all metrics */
for ( unsigned int metricCount=0; metricCount < numberOfMetrics; metricCount++)
{
this->m_SmoothFixedImages[metricCount] = this->SmoothImageToScale(this->m_SimilarityMetrics[metricCount]->GetFixedImage(), this->m_ScaleFactor);
this->m_SmoothMovingImages[metricCount] = this->SmoothImageToScale(this->m_SimilarityMetrics[metricCount]->GetMovingImage(), this->m_ScaleFactor);
}
fixedImage=this->m_SmoothFixedImages[0];
movingImage=this->m_SmoothMovingImages[0];
unsigned int nmet=this->m_SimilarityMetrics.size();
this->m_LastEnergy.resize(nmet,1.e12);
this->m_Energy.resize(nmet,1.e9);
this->m_EnergyBad.resize(nmet,0);
bool converged=false;
this->m_CurrentIteration=0;
if (this->GetTransformationModel() != std::string("SyN")) this->m_FixedImageAffineTransform=NULL;
while (!converged)
{
for (unsigned int metricCount=0; metricCount < numberOfMetrics; metricCount++)
this->m_SimilarityMetrics[metricCount]->GetMetric()->SetIterations(this->m_CurrentIteration);
if ( this->GetTransformationModel() == std::string("Elast"))
{
if (this->m_Iterations[currentLevel] > 0)
this->ElasticRegistrationUpdate(fixedImage, movingImage);
}
else if (this->GetTransformationModel() == std::string("SyN"))
{
if ( currentLevel > 0 )
{
this->m_SyNF=this->ExpandField(this->m_SyNF,this->m_CurrentDomainSpacing);
this->m_SyNFInv=this->ExpandField(this->m_SyNFInv,this->m_CurrentDomainSpacing);
this->m_SyNM=this->ExpandField(this->m_SyNM,this->m_CurrentDomainSpacing);
this->m_SyNMInv=this->ExpandField(this->m_SyNMInv,this->m_CurrentDomainSpacing);
}
if(this->m_Iterations[currentLevel] > 0)
{
if (this->m_SyNType && this->m_ComputeThickness )
this->DiReCTUpdate(fixedImage, movingImage, this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() );
else if (this->m_SyNType)
this->SyNTVRegistrationUpdate(fixedImage, movingImage, this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() );
else
this->SyNRegistrationUpdate(fixedImage, movingImage, this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() );
}
else if (this->m_SyNType)
this->UpdateTimeVaryingVelocityFieldWithSyNFandSyNM( );
// this->CopyOrAddToVelocityField( this->m_SyNF, 0 , false);
}
else if (this->GetTransformationModel() == std::string("Exp"))
{
if(this->m_Iterations[currentLevel] > 0)
{
this->DiffeomorphicExpRegistrationUpdate(fixedImage, movingImage,this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() );
}
}
else if (this->GetTransformationModel() == std::string("GreedyExp"))
{
if(this->m_Iterations[currentLevel] > 0)
{
this->GreedyExpRegistrationUpdate(fixedImage, movingImage,this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() );
}
}
this->m_CurrentIteration++;
/**
* This is where we track the energy profile to check for convergence.
*/
for( unsigned int qq = 0; qq < numberOfMetrics; qq++ )
{
ProfilePointType point;
point[0] = this->m_CurrentIteration-1;
ProfilePointDataType energy;
energy[0] = this->m_Energy[qq];
energyProfiles[qq]->SetPoint( this->m_CurrentIteration-1, point );
energyProfiles[qq]->SetPointData( this->m_CurrentIteration-1, energy );
}
/**
* If there are a sufficent number of iterations, fit a quadratic
* single B-spline span to the number of energy profile points
* in the first metric. To test convergence, evaluate the derivative
* at the end of the profile to determine if >= 0. To change to a
* window of the energy profile, simply change the origin (assuming that
* the desired window will start at the user-specified origin and
* end at the current iteration).
*/
unsigned int domtar=12;
if( this->m_CurrentIteration > domtar )
{
typedef BSplineScatteredDataPointSetToImageFilter
<EnergyProfileType, CurveType> BSplinerType;
typename BSplinerType::Pointer bspliner
= BSplinerType::New();
typename CurveType::PointType origin;
unsigned int domainorigin=0;
unsigned int domainsize=this->m_CurrentIteration - domainorigin;
if ( this->m_CurrentIteration > domtar ) { domainsize=domtar; domainorigin=this->m_CurrentIteration-domainsize; }
origin.Fill( domainorigin );
typename CurveType::SizeType size;
size.Fill( domainsize );
typename CurveType::SpacingType spacing;
spacing.Fill( 1 );
typename EnergyProfileType::Pointer energyProfileWindow = EnergyProfileType::New();
energyProfileWindow->Initialize();
unsigned int windowBegin = static_cast<unsigned int>( origin[0] );
float totale=0;
for( unsigned int qq = windowBegin; qq < this->m_CurrentIteration; qq++ )
{
ProfilePointType point;
point[0] = qq;
ProfilePointDataType energy;
energy.Fill( 0 );
energyProfiles[0]->GetPointData( qq, &energy );
totale+=energy[0];
energyProfileWindow->SetPoint( qq-windowBegin, point );
energyProfileWindow->SetPointData( qq-windowBegin, energy );
}
// std::cout <<" totale " << totale << std::endl;
if (totale > 0) totale*=(-1.0);
for( unsigned int qq = windowBegin; qq < this->m_CurrentIteration; qq++ )
{
ProfilePointDataType energy; energy.Fill(0);
energyProfiles[0]->GetPointData( qq, &energy );
energyProfileWindow->SetPointData( qq-windowBegin, energy/totale);
}
bspliner->SetInput( energyProfileWindow );
bspliner->SetOrigin( origin );
bspliner->SetSpacing( spacing );
bspliner->SetSize( size );
bspliner->SetNumberOfLevels( 1 );
unsigned int order=1;
bspliner->SetSplineOrder( order );
typename BSplinerType::ArrayType ncps;
ncps.Fill( order+1); // single span, order = 2
bspliner->SetNumberOfControlPoints( ncps );
bspliner->Update();
ProfilePointType endPoint;
endPoint[0] = static_cast<float>( this->m_CurrentIteration-domainsize*0.5 );
typename BSplinerType::GradientType gradient;
gradient.Fill(0);
bspliner->EvaluateGradientAtPoint( endPoint, gradient );
this->m_ESlope=gradient[0][0] ;
if ( this->m_ESlope < 0.0001 && this->m_CurrentIteration > domtar) converged=true;
std::cout << " E-Slope " << this->m_ESlope;//<< std::endl;
}
for ( unsigned int qq=0; qq < this->m_Energy.size(); qq++ )
{
if ( qq==0 )
std::cout << " iteration " << this->m_CurrentIteration;
std::cout << " energy " << qq << " : " << this->m_Energy[qq];// << " Last " << this->m_LastEnergy[qq];
if (this->m_LastEnergy[qq] < this->m_Energy[qq])
{
this->m_EnergyBad[qq]++;
}
}
unsigned int numbade=0;
for (unsigned int qq=0; qq<this->m_Energy.size(); qq++)
if (this->m_CurrentIteration <= 1)
this->m_EnergyBad[qq] = 0;
else if ( this->m_EnergyBad[qq] > 1 )
numbade += this->m_EnergyBad[qq];
//if ( this->m_EnergyBad[0] > 2)
// {
// this->m_GradstepAltered*=0.8;
// std::cout <<" reducing gradstep " << this->m_GradstepAltered;
// this->m_EnergyBad[this->m_Energy.size()-1]=0;
// }
std::cout << std::endl;
if (this->m_CurrentIteration >= this->m_Iterations[currentLevel] )converged = true;
// || this->m_EnergyBad[0] >= 6 )
//
if ( converged && this->m_CurrentIteration >= this->m_Iterations[currentLevel] )
std::cout <<" tired convergence: reached max iterations " << std::endl;
else if (converged)
{
std::cout << " Converged due to oscillation in optimization ";
for (unsigned int qq=0; qq<this->m_Energy.size(); qq++)
std::cout<< " metric " << qq << " bad " << this->m_EnergyBad[qq] << " " ;
std::cout <<std::endl;
}
}
}
if ( this->GetTransformationModel() == std::string("SyN"))
{
// float timestep=1.0/(float)this->m_NTimeSteps;
// unsigned int nts=this->m_NTimeSteps;
if (this->m_SyNType)
{
// this->m_SyNFInv = this->IntegrateConstantVelocity(this->m_SyNF, nts, timestep*(-1.));
// this->m_SyNMInv = this->IntegrateConstantVelocity(this->m_SyNM, nts, timestep*(-1.));
// this->m_SyNF= this->IntegrateConstantVelocity(this->m_SyNF, nts, timestep);
// this->m_SyNM= this->IntegrateConstantVelocity(this->m_SyNM,
// nts, timestep);
// DeformationFieldPointer fdiffmap = this->IntegrateVelocity(0,0.5);
// this->m_SyNFInv = this->IntegrateVelocity(0.5,0);
// DeformationFieldPointer mdiffmap = this->IntegrateVelocity(0.5,1);
// this->m_SyNMInv = this->IntegrateVelocity(1,0.5);
// this->m_SyNM=this->CopyDeformationField(mdiffmap);
// this->m_SyNF=this->CopyDeformationField(fdiffmap);
this->m_DeformationField = this->IntegrateVelocity(0,1);
// ImagePointer wmimage= this->WarpMultiTransform( this->m_SmoothFixedImages[0],this->m_SmoothMovingImages[0], this->m_AffineTransform, this->m_DeformationField, false , this->m_ScaleFactor );
this->m_InverseDeformationField=this->IntegrateVelocity(1,0);
}
else
{
this->m_InverseDeformationField=this->CopyDeformationField( this->m_SyNM);
this->ComposeDiffs(this->m_SyNF,this->m_SyNMInv,this->m_DeformationField,1);
this->ComposeDiffs(this->m_SyNM,this->m_SyNFInv,this->m_InverseDeformationField,1);
}
}
else if (this->GetTransformationModel() == std::string("Exp"))
{
DeformationFieldPointer diffmap = this->IntegrateConstantVelocity( this->m_DeformationField, (unsigned int)this->m_NTimeSteps , 1 ); // 1.0/ (float)this->m_NTimeSteps);
DeformationFieldPointer invdiffmap = this->IntegrateConstantVelocity(this->m_DeformationField,(unsigned int) this->m_NTimeSteps, -1 ); // -1.0/(float)this->m_NTimeSteps);
this->m_InverseDeformationField=invdiffmap;
this->m_DeformationField=diffmap;
AffineTransformPointer invaff =NULL;
if (this->m_AffineTransform)
{
invaff=AffineTransformType::New();
this->m_AffineTransform->GetInverse(invaff);
if (this->m_Debug) std::cout << " ??????invaff " << this->m_AffineTransform << std::endl << std::endl;
if (this->m_Debug) std::cout << " invaff?????? " << invaff << std::endl << std::endl;
}
}
else if (this->GetTransformationModel() == std::string("GreedyExp"))
{
DeformationFieldPointer diffmap = this->m_DeformationField;
this->m_InverseDeformationField=NULL;
this->m_DeformationField=diffmap;
AffineTransformPointer invaff =NULL;
if (this->m_AffineTransform)
{
invaff=AffineTransformType::New();
this->m_AffineTransform->GetInverse(invaff);
if (this->m_Debug) std::cout << " ??????invaff " << this->m_AffineTransform << std::endl << std::endl;
if (this->m_Debug) std::cout << " invaff?????? " << invaff << std::endl << std::endl;
}
}
this->m_DeformationField->SetOrigin( this->m_SimilarityMetrics[0]->GetFixedImage()->GetOrigin() );
this->m_DeformationField->SetDirection( this->m_SimilarityMetrics[0]->GetFixedImage()->GetDirection() );
if (this->m_InverseDeformationField)
{
this->m_InverseDeformationField->SetOrigin( this->m_SimilarityMetrics[0]->GetFixedImage()->GetOrigin() );
this->m_InverseDeformationField->SetDirection( this->m_SimilarityMetrics[0]->GetFixedImage()->GetDirection() );
}
if ( this->m_TimeVaryingVelocity ) {
std::string outname=localANTSGetFilePrefix(this->m_OutputNamingConvention.c_str())+std::string("velocity.mhd");
typename itk::ImageFileWriter<TimeVaryingVelocityFieldType>::Pointer writer = itk::ImageFileWriter<TimeVaryingVelocityFieldType>::New();
writer->SetFileName(outname.c_str());
writer->SetInput( this->m_TimeVaryingVelocity);
writer->UpdateLargestPossibleRegion();
// writer->Write();
std::cout << " write tv field " << outname << std::endl;
// WriteImage<TimeVaryingVelocityFieldType>( this->m_TimeVaryingVelocity , outname.c_str());
}
}
void DiffeomorphicExpRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage,PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL);
void GreedyExpRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage,PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL);
void SyNRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL);
void SyNExpRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL);
void SyNTVRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL);
void DiReCTUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL);
/** allows one to copy or add a field to a time index within the velocity
* field
*/
void UpdateTimeVaryingVelocityFieldWithSyNFandSyNM( );
void CopyOrAddToVelocityField( TimeVaryingVelocityFieldPointer velocity, DeformationFieldPointer update1, DeformationFieldPointer update2 , float timept);
//void CopyOrAddToVelocityField( DeformationFieldPointer update, unsigned int timeindex, bool CopyIsTrueOtherwiseAdd);
void ElasticRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage)
{
typename ImageType::SpacingType spacing;
VectorType zero;
zero.Fill(0);
DeformationFieldPointer updateField;
updateField=this->ComputeUpdateField(this->m_DeformationField,NULL,NULL,NULL,NULL);
typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
Iterator dIter(this->m_DeformationField,this->m_DeformationField->GetLargestPossibleRegion() );
for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )
{
typename ImageType::IndexType index=dIter.GetIndex();
VectorType vec=updateField->GetPixel(index);
dIter.Set(dIter.Get()+vec*this->m_Gradstep);
}
if (this->m_Debug)
{
std::cout << " updated elast " << " up-sz " << updateField->GetLargestPossibleRegion() << std::endl;
std::cout << " t-sz " << this->m_DeformationField->GetLargestPossibleRegion() << std::endl;
}
this->SmoothDeformationField(this->m_DeformationField, false);
return;
}
ImagePointer WarpImageBackward( ImagePointer image, DeformationFieldPointer field )
{
typedef WarpImageFilter<ImageType,ImageType, DeformationFieldType> WarperType;
typename WarperType::Pointer warper = WarperType::New();
typedef NearestNeighborInterpolateImageFunction<ImageType,double>
InterpolatorType;
warper->SetInput(image);
warper->SetDeformationField( field );
warper->SetEdgePaddingValue( 0);
warper->SetOutputSpacing(field->GetSpacing() );
warper->SetOutputOrigin( field->GetOrigin() );
warper->Update();
return warper->GetOutput();
}
void ComposeDiffs(DeformationFieldPointer fieldtowarpby, DeformationFieldPointer field, DeformationFieldPointer fieldout, float sign);
void SetSimilarityMetrics( SimilarityMetricListType S ) {this->m_SimilarityMetrics=S;}
void SetFixedPointSet( PointSetPointer p ) { this->m_FixedPointSet=p; }
void SetMovingPointSet( PointSetPointer p ) { this->m_MovingPointSet=p; }
void SetDeltaTime( float t) {this->m_DeltaTime=t; }
float InvertField(DeformationFieldPointer field,
DeformationFieldPointer inverseField, float weight=1.0,
float toler=0.1, int maxiter=20, bool print = false)
{
float mytoler=toler;
unsigned int mymaxiter=maxiter;
typename ParserType::OptionType::Pointer thicknessOption
= this->m_Parser->GetOption( "go-faster" );
if( thicknessOption->GetValue() == "true" || thicknessOption->GetValue() == "1" )
{ mytoler=0.5; maxiter=12; }
VectorType zero; zero.Fill(0);
// if (this->GetElapsedIterations() < 2 ) maxiter=10;
ImagePointer floatImage = ImageType::New();
floatImage->SetLargestPossibleRegion( field->GetLargestPossibleRegion() );
floatImage->SetBufferedRegion( field->GetLargestPossibleRegion().GetSize() );
floatImage->SetSpacing(field->GetSpacing());
floatImage->SetOrigin(field->GetOrigin());
floatImage->SetDirection(field->GetDirection());
floatImage->Allocate();
typedef typename DeformationFieldType::PixelType VectorType;
typedef typename DeformationFieldType::IndexType IndexType;
typedef typename VectorType::ValueType ScalarType;
typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
DeformationFieldPointer lagrangianInitCond=DeformationFieldType::New();
lagrangianInitCond->SetSpacing( field->GetSpacing() );
lagrangianInitCond->SetOrigin( field->GetOrigin() );
lagrangianInitCond->SetDirection( field->GetDirection() );
lagrangianInitCond->SetLargestPossibleRegion( field->GetLargestPossibleRegion() );
lagrangianInitCond->SetRequestedRegion(field->GetRequestedRegion() );
lagrangianInitCond->SetBufferedRegion( field->GetLargestPossibleRegion() );
lagrangianInitCond->Allocate();
DeformationFieldPointer eulerianInitCond=DeformationFieldType::New();
eulerianInitCond->SetSpacing( field->GetSpacing() );
eulerianInitCond->SetOrigin( field->GetOrigin() );
eulerianInitCond->SetDirection( field->GetDirection() );
eulerianInitCond->SetLargestPossibleRegion( field->GetLargestPossibleRegion() );
eulerianInitCond->SetRequestedRegion(field->GetRequestedRegion() );
eulerianInitCond->SetBufferedRegion( field->GetLargestPossibleRegion() );
eulerianInitCond->Allocate();
typedef typename DeformationFieldType::SizeType SizeType;
SizeType size=field->GetLargestPossibleRegion().GetSize();
typename ImageType::SpacingType spacing = field->GetSpacing();
float subpix=0.0;
unsigned long npix=1;
for (int j=0; j<ImageDimension; j++) // only use in-plane spacing
{
npix*=field->GetLargestPossibleRegion().GetSize()[j];
}
subpix=pow((float)ImageDimension,(float)ImageDimension)*0.5;
float max=0;
Iterator iter( field, field->GetLargestPossibleRegion() );
for( iter.GoToBegin(); !iter.IsAtEnd(); ++iter )
{
IndexType index=iter.GetIndex();
VectorType vec1=iter.Get();
VectorType newvec=vec1*weight;
lagrangianInitCond->SetPixel(index,newvec);
float mag=0;
for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=newvec[jj]*newvec[jj];
mag=sqrt(mag);
if (mag > max) max=mag;
}
eulerianInitCond->FillBuffer(zero);
float scale=(1.)/max;
if (scale > 1.) scale=1.0;
// float initscale=scale;
Iterator vfIter( inverseField, inverseField->GetLargestPossibleRegion() );
// int num=10;
// for (int its=0; its<num; its++)
float difmag=10.0;
unsigned int ct=0;
float denergy=10;
float denergy2=10;
float laste=1.e9;
float meandif=1.e8;
// int badct=0;
// while (difmag > subpix && meandif > subpix*0.1 && badct < 2 )//&& ct < 20 && denergy > 0)
// float length=0.0;
float stepl=2.;
float lastdifmag=0;
float epsilon = (float)size[0]/256;
if (epsilon > 1) epsilon = 1;
while ( difmag > mytoler && ct < mymaxiter && meandif > 0.001)
{
denergy=laste-difmag;//meandif;
denergy2=laste-meandif;
laste=difmag;//meandif;
meandif=0.0;
//this field says what position the eulerian field should contain in the E domain
this->ComposeDiffs(inverseField,lagrangianInitCond, eulerianInitCond, 1);
difmag=0.0;
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
IndexType index=vfIter.GetIndex();
VectorType update=eulerianInitCond->GetPixel(index);
float mag=0;
for (int j=0; j<ImageDimension;j++)
{
update[j]*=(-1.0);
mag+=(update[j]/spacing[j])*(update[j]/spacing[j]);
}
mag=sqrt(mag);
meandif+=mag;
if (mag > difmag) {difmag=mag; }
// if (mag < 1.e-2) update.Fill(0);
eulerianInitCond->SetPixel(index,update);
floatImage->SetPixel(index,mag);
}
meandif/=(float)npix;
if (ct == 0) epsilon = 0.75;
else epsilon=0.5;
stepl=difmag*epsilon;
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
float val = floatImage->GetPixel(vfIter.GetIndex());
VectorType update=eulerianInitCond->GetPixel(vfIter.GetIndex());
if (val > stepl) update = update * (stepl/val);
VectorType upd=vfIter.Get()+update * (epsilon);
vfIter.Set(upd);
}
ct++;
lastdifmag=difmag;
}
// std::cout <<" difmag " << difmag << ": its " << ct << std::endl;
return difmag;
}
void SetUseNearestNeighborInterpolation( bool useNN) { this->m_UseNN=useNN; }
void SetUseBSplineInterpolation( bool useNN) { this->m_UseBSplineInterpolation=useNN; }
protected:
DeformationFieldPointer IntegrateVelocity(float,float);
DeformationFieldPointer IntegrateLandmarkSetVelocity(float,float, PointSetPointer movingpoints, ImagePointer referenceimage );
VectorType IntegratePointVelocity(float starttimein, float finishtimein , IndexType startPoint);
ImagePointer MakeSubImage( ImagePointer bigimage)
{
typedef itk::ImageRegionIteratorWithIndex<ImageType> Iterator;
ImagePointer varimage=ImageType::New();
typename ImageType::RegionType region;
typename ImageType::SizeType size=bigimage->GetLargestPossibleRegion().GetSize();
region.SetSize( this->m_CurrentDomainSize);
typename ImageType::IndexType index; index.Fill(0);
region.SetIndex(index);
varimage->SetRegions( region );
varimage->SetSpacing(this->m_CurrentDomainSpacing);
varimage->SetOrigin(bigimage->GetOrigin());
varimage->SetDirection(bigimage->GetDirection());
varimage->Allocate();
varimage->FillBuffer(0);
typename ImageType::IndexType cornerind;
cornerind.Fill(0);
for (unsigned int ii=0; ii<ImageDimension; ii++)
{
float diff =(float)this->m_CurrentDomainOrigin[ii]-(float)this->m_CurrentDomainSize[ii]/2;
if (diff < 0) diff=0;
cornerind[ii]=(unsigned long) diff;
}
// std::cout << " corner index " << cornerind << std::endl;
Iterator vfIter2( bigimage, bigimage->GetLargestPossibleRegion() );
for( vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
{
typename ImageType::IndexType origindex=vfIter2.GetIndex();
typename ImageType::IndexType index=vfIter2.GetIndex();
bool oktosample=true;
for (unsigned int ii=0; ii<ImageDimension; ii++)
{
float centerbasedcoord = (origindex[ii]-this->m_CurrentDomainOrigin[ii]);
// float diff =
// index[ii]=origindex[ii]-cornerind[ii];
if ( fabs(centerbasedcoord) > (this->m_CurrentDomainSize[ii]/2-1)) oktosample=false;
}
if (oktosample) {
// std::cout << " index " << index << " origindex " << origindex << " ok? " << oktosample << std::endl;
varimage->SetPixel(index,bigimage->GetPixel(origindex)); }
}
//std::cout << " sizes " << varimage->GetLargestPossibleRegion().GetSize() << " bigimage " << bigimage->GetLargestPossibleRegion().GetSize() << std::endl;
return varimage;
}
float MeasureDeformation(DeformationFieldPointer field, int option=0)
{
typedef typename DeformationFieldType::PixelType VectorType;
typedef typename DeformationFieldType::IndexType IndexType;
typedef typename DeformationFieldType::SizeType SizeType;
typedef typename VectorType::ValueType ScalarType;
typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
// all we have to do here is add the local field to the global field.
Iterator vfIter( field, field->GetLargestPossibleRegion() );
SizeType size=field->GetLargestPossibleRegion().GetSize();
unsigned long ct=1;
double totalmag=0;
float maxstep=0;
// this->m_EuclideanNorm=0;
typename ImageType::SpacingType myspacing = field->GetSpacing();
for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )
{
IndexType index=vfIter.GetIndex();
IndexType rindex=vfIter.GetIndex();
IndexType lindex=vfIter.GetIndex();
VectorType update=vfIter.Get();
float mag=0.0;
float stepl=0.0;
for (int i=0;i<ImageDimension;i++)
{
rindex=index;
lindex=index;
if ((int)index[i]< (int)(size[i]-2)) rindex[i]=rindex[i]+1;
if (index[i]>2) lindex[i]=lindex[i]-1;
VectorType rupdate=field->GetPixel(rindex);
VectorType lupdate=field->GetPixel(lindex);
VectorType dif=rupdate-lupdate;
for (int tt=0; tt<ImageDimension; tt++)
{
stepl+=update[tt]*update[tt]/(myspacing[tt]*myspacing[tt]);
mag+=dif[tt]*dif[tt]/(myspacing[tt]*myspacing[tt]);
}
}
stepl=sqrt(stepl);
mag=sqrt(mag);
if (stepl > maxstep) maxstep=stepl;
ct++;
totalmag+=mag;
// this->m_EuclideanNorm+=stepl;
}
//this->m_EuclideanNorm/=ct;
//this->m_ElasticPathLength = totalmag/ct;
//this->m_LinftyNorm = maxstep;
// std::cout << " Elast path length " << this->m_ElasticPathLength << " L inf norm " << this->m_LinftyNorm << std::endl;
//if (this->m_ElasticPathLength >= this->m_ArcLengthGoal)
// if (maxstep >= this->m_ArcLengthGoal)
{
// this->StopRegistration();
// scale the field to the right length
// float scale=this->m_ArcLengthGoal/this->m_ElasticPathLength;
// for( vfIter.GoToBegin(); !vfIter.IsAtEnd(); ++vfIter )vfIter.Set(vfIter.Get()*scale);
}
//if (this->m_LinftyNorm <= 0) this->m_LinftyNorm=1;
//if (this->m_ElasticPathLength <= 0) this->m_ElasticPathLength=0;
//if (this->m_EuclideanNorm <= 0) this->m_EuclideanNorm=0;
//if (option==0) return this->m_ElasticPathLength;
//else if (option==2) return this->m_EuclideanNorm;
// else
return maxstep;
}
ANTSImageRegistrationOptimizer();
virtual ~ANTSImageRegistrationOptimizer() {}
void PrintSelf( std::ostream& os, Indent indent ) const;
private:
ANTSImageRegistrationOptimizer( const Self& ); //purposely not implemented
void operator=( const Self& ); //purposely not implemented
typename VelocityFieldInterpolatorType::Pointer m_VelocityFieldInterpolator;
typename ImageType::SizeType m_CurrentDomainSize;
typename ImageType::PointType m_CurrentDomainOrigin;
typename ImageType::SpacingType m_CurrentDomainSpacing;
typename ImageType::DirectionType m_CurrentDomainDirection;
typename ImageType::SizeType m_FullDomainSize;
typename ImageType::PointType m_FullDomainOrigin;
typename ImageType::SpacingType m_FullDomainSpacing;
AffineTransformPointer m_AffineTransform;
AffineTransformPointer m_FixedImageAffineTransform;
DeformationFieldPointer m_DeformationField;
DeformationFieldPointer m_InverseDeformationField;
std::vector<float> m_GradientDescentParameters;
std::vector<float> m_MetricScalarWeights;
std::vector<ImagePointer> m_SmoothFixedImages;
std::vector<ImagePointer> m_SmoothMovingImages;
bool m_Debug;
unsigned int m_NumberOfLevels;
typename ParserType::Pointer m_Parser;
SimilarityMetricListType m_SimilarityMetrics;
ImagePointer m_MaskImage;
float m_ScaleFactor;
bool m_UseMulti;
bool m_UseROI;
bool m_UseNN;
bool m_UseBSplineInterpolation;
unsigned int m_CurrentIteration;
unsigned int m_CurrentLevel;
std::string m_TransformationModel;
std::string m_OutputNamingConvention;
PointSetPointer m_FixedPointSet;
PointSetPointer m_MovingPointSet;
std::vector<unsigned int> m_Iterations;
std::vector<float> m_RestrictDeformation;
std::vector<float> m_RoiNumbers;
float m_GradSmoothingparam;
float m_TotalSmoothingparam;
float m_Gradstep;
float m_GradstepAltered;
float m_NTimeSteps;
float m_GaussianTruncation;
float m_DeltaTime;
float m_ESlope;
/** energy stuff */
std::vector<float> m_Energy;
std::vector<float> m_LastEnergy;
std::vector<unsigned int> m_EnergyBad;
/** for SyN only */
DeformationFieldPointer m_SyNF;
DeformationFieldPointer m_SyNFInv;
DeformationFieldPointer m_SyNM;
DeformationFieldPointer m_SyNMInv;
TimeVaryingVelocityFieldPointer m_TimeVaryingVelocity;
TimeVaryingVelocityFieldPointer m_LastTimeVaryingVelocity;
TimeVaryingVelocityFieldPointer m_LastTimeVaryingUpdate;
unsigned int m_SyNType;
/** for BSpline stuff */
unsigned int m_BSplineFieldOrder;
ArrayType m_GradSmoothingMeshSize;
ArrayType m_TotalSmoothingMeshSize;
/** For thickness calculation */
ImagePointer m_HitImage;
ImagePointer m_ThickImage;
unsigned int m_ComputeThickness;
unsigned int m_SyNFullTime;
};
}
// end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkANTSImageRegistrationOptimizer.cxx"
#endif
#endif
|
Java
|
#!/bin/bash
# AUTHOR: Léo Perrin <leoperrin@picarresursix.fr>
# Time-stamp: <2013-04-16 22:35:22 leo>
# Append a pdf to the end of another.
if (( $# < 1 ))
then
echo "Usage:"
echo " concat-pdf.sh 1.pdf 2.pdf"
echo "Creates a pdf called 1-2.pdf made of the concatenation of the"\
"content of 1.pdf and 2.pdf"
echo ""
echo " concat-pdf.sh pdf-to-append.pdf"
echo "Prompts for a pdf file and appends pdf-to-append.pdf at the end"\
"of it. The result is stored in a new file."
elif (( $# < 2 ))
then
main_pdf=$(zenity --text="The file "$1" will appended to:" \
--file-selection --file-filter="*.pdf" --filename=$(pwd)/)
out=$(sed "s/\.[^\.]*//" <<< $main_pdf)-$(sed "s/\.[^\.]*//" <<< $1).pdf
pdftk $main_pdf $1 cat output $out
else
out=$(sed "s/\.[^\.]*//" <<< $1)-$(sed "s/\.[^\.]*//" <<< $2).pdf
pdftk $1 $2 cat output $out
fi
|
Java
|
# intelengine
## Introduction
intelengine aims to be an information gathering and exploitation architecture,
it is based on the use of transforms, that convert one data type into
another. For instance, a simple transform would be obtaining a list of
domains from an IP address or a location history from a twitter nickname.
## Main goals
The main goals of intelengine can be summarized in:
* Simplicity
* Modularity
* Scalability
* RESTful
* Programming language agnostic
## Architecture
intelengine consists in a client-server architecture.
**intelsrv**, the server component, is an HTTP server that exposes a REST API,
that allows the communication between server and clients. The mission of
intelsrv is handling execution flows and distribute tasks between the different
intelworker present in the architecture. Besides that, it also taskes care of
error handling, concurrency and caching
**intelworker**, the worker component is responsible for executing the commands
issued by clients and transmit their results back to intelsrv. intelworker is
designed to be programming language agnostic, so commands can be coded using
any language that can read from STDIN and write to STDOUT.
Finally, the **client** can be any program able to interact with the intelsrv's
REST API.
It is important to note that the communication between the different instances
of intelserver and intelworker is carried out via a message broker using the
amqp protocol.
```
+--------+ http +------------+ amqp +--------+ amqp +---------------+
| client |----+---->| intelsrv_1 |----+---->| BROKER |----+---->| intelworker_1 |
+--------+ | +------------+ | +--------+ | +---------------+
| +------------+ | | +---------------+
+---->| intelsrv_2 |----+ +---->| intelworker_2 |
| +------------+ | | +---------------+
| +------------+ | | +---------------+
+---->| intelsrv_n |----+ +---->| intelworker_m |
+------------+ +---------------+
```
## Commands
Commands live with intelworker and are splitted in two parts:
* **Definition file** (cmd file)
* **Implementation** (standalone executable)
The command **definition file** is a JSON file that defines how the command is
called. It must include the following information:
* **Description**: Description of the command functionality
* **Path**: Path of the executable that will be called when the command is executed
* **Args**: Arguments passed to the executable when it is called
* **Input**: Type of the input data
* **Output**: Type of the output data
* **Parameters**: Structure describing the type of the accepted parameters
* **Group**: Command category
The following snippet shows a dummy cmd file:
```json
{
"Description": "echo request's body",
"Cmd": "cat",
"Args": [],
"Input": "",
"Output": "",
"Parameters": "",
"Group": "debug"
}
```
Also, the definition files must have the extension ".cmd", being the name of the
command the name of the file without this extension.
The command's **implementation** is an standalone executable that implements the
command's functionality. By convention, it must wait for JSON input via STDIN
and write its output in JSON format to STDOUT. Also, it must exit with the
return value 0 when the execution finished correctly, or any other value on
error.
The input of the command is the body of the POST request sent to the intelsrv's
path "/cmd/exec/\<cmdname\>". When the users makes this request, an unique ID
will be generated and returned in the response. This way it is possible to
retrieve the result of the command sending a GET request to
"/cmd/result/\<uuid\>", being the output of the command returned to the client
in the response body. If the command exited with error, this error will be
returned in the "Error" field within the JSON response.
Commands must take care of the input and output types specified in their
definition file. Also, input and output must be treated as arrays of those
types. For instance, if the input type is "IP", the command should expect an
array of IPs as input.
Due to these design principles, commands can be implemented in any programming
language that can read from STDIN and write to STDOUT.
## Transforms vs Commands
The word **command** was chosen rather than **transform**, because a transform
can be considered as a particular class of command. It's important to take into
account that intelengine is not only aimed at being used for data gathering
but also for exploitation, crawlering, etc.
## intelsrv's routes
The following routes are configured by default:
* **GET /cmd/list**: List supported commands
* **POST /cmd/exec/\<cmdname\>**: Execute the command \<cmdname\>
* **GET /cmd/result/\<uuid\>**: Retrieve the result of the command linked
to the UUID \<uuid\>
|
Java
|
module Watir
module RowContainer
# Returns a row in the table
# * index - the index of the row
def [](index)
assert_exists
TableRow.new(self, :ole_object, @o.rows.item(index))
end
def strings
assert_exists
rows_memo = []
@o.rows.each do |row|
cells_memo = []
row.cells.each do |cell|
cells_memo << TableCell.new(self, :ole_object, cell).text
end
rows_memo << cells_memo
end
rows_memo
end
end
# This class is used for dealing with tables.
# Normally a user would not need to create this object as it is returned by the Watir::Container#table method
#
# many of the methods available to this object are inherited from the Element class
#
class Table < NonControlElement
include RowContainer
# override the highlight method, as if the tables rows are set to have a background color,
# this will override the table background color, and the normal flash method won't work
def highlight(set_or_clear)
if set_or_clear == :set
begin
@original_border = @o.border.to_i
if @o.border.to_i==1
@o.border = 2
else
@o.border = 1
end
rescue
@original_border = nil
end
else
begin
@o.border= @original_border unless @original_border == nil
@original_border = nil
rescue
# we could be here for a number of reasons...
ensure
@original_border = nil
end
end
super
end
# this method is used to populate the properties in the to_s method
def table_string_creator
n = []
n << "rows:".ljust(TO_S_SIZE) + self.row_count.to_s
n << "cols:".ljust(TO_S_SIZE) + self.column_count.to_s
return n
end
private :table_string_creator
# returns the properties of the object in a string
# raises an ObjectNotFound exception if the object cannot be found
def to_s
assert_exists
r = string_creator
r += table_string_creator
return r.join("\n")
end
# iterates through the rows in the table. Yields a TableRow object
def each
assert_exists
@o.rows.each do |row|
yield TableRow.new(self, :ole_object, row)
end
end
# Returns the number of rows inside the table, including rows in nested tables.
def row_count
assert_exists
rows.length
end
# This method returns the number of columns in a row of the table.
# Raises an UnknownObjectException if the table doesn't exist.
# * index - the index of the row
def column_count(index=0)
assert_exists
row[index].cells.length
end
# Returns an array containing all the text values in the specified column
# Raises an UnknownCellException if the specified column does not exist in every
# Raises an UnknownObjectException if the table doesn't exist.
# row of the table
# * columnnumber - column index to extract values from
def column_values(columnnumber)
return (0..row_count - 1).collect {|i| self[i][columnnumber].text}
end
# Returns an array containing all the text values in the specified row
# Raises an UnknownObjectException if the table doesn't exist.
# * rownumber - row index to extract values from
def row_values(rownumber)
return (0..column_count(rownumber) - 1).collect {|i| self[rownumber][i].text}
end
def hashes
assert_exists
headers = []
@o.rows.item(0).cells.each do |cell|
headers << TableCell.new(self, :ole_object, cell).text
end
rows_memo = []
i = 0
@o.rows.each do |row|
next if row.uniqueID == @o.rows.item(0).uniqueID
cells_memo = {}
cells = row.cells
raise "row at index #{i} has #{cells.length} cells, expected #{headers.length}" if cells.length < headers.length
j = 0
cells.each do |cell|
cells_memo[headers[j]] = TableCell.new(self, :ole_object, cell).text
j += 1
end
rows_memo << cells_memo
i += 1
end
rows_memo
end
end
class TableSection < NonControlElement
include RowContainer
Watir::Container.module_eval do
def tbody(how={}, what=nil)
how = {how => what} if what
TableSection.new(self, how.merge(:tag_name => "tbody"), nil)
end
def tbodys(how={}, what=nil)
how = {how => what} if what
TableSectionCollection.new(self, how.merge(:tag_name => "tbody"), nil)
end
def thead(how={}, what=nil)
how = {how => what} if what
TableSection.new(self, how.merge(:tag_name => "thead"), nil)
end
def theads(how={}, what=nil)
how = {how => what} if what
TableSectionCollection.new(self, how.merge(:tag_name => "thead"), nil)
end
def tfoot(how={}, what=nil)
how = {how => what} if what
TableSection.new(self, how.merge(:tag_name => "tfoot"), nil)
end
def tfoots(how={}, what=nil)
how = {how => what} if what
TableSectionCollection.new(self, how.merge(:tag_name => "tfoot"), nil)
end
end
end
class TableRow < NonControlElement
TAG = "TR"
# this method iterates through each of the cells in the row. Yields a TableCell object
def each
locate
cells.each {|cell| yield cell}
end
# Returns an element from the row as a TableCell object
def [](index)
assert_exists
if cells.length <= index
raise UnknownCellException, "Unable to locate a cell at index #{index}"
end
return cells[index]
end
# defaults all missing methods to the array of elements, to be able to
# use the row as an array
# def method_missing(aSymbol, *args)
# return @o.send(aSymbol, *args)
# end
def column_count
locate
cells.length
end
Watir::Container.module_eval do
def row(how={}, what=nil)
TableRow.new(self, how, what)
end
alias_method :tr, :row
def rows(how={}, what=nil)
TableRows.new(self, how, what)
end
alias_method :trs, :rows
end
end
# this class is a table cell - when called via the Table object
class TableCell < NonControlElement
TAGS = ["TH", "TD"]
alias to_s text
def colspan
locate
@o.colSpan
end
Watir::Container.module_eval do
def cell(how={}, what=nil)
TableCell.new(self, how, what)
end
alias_method :td, :cell
def cells(how={}, what=nil)
TableCells.new(self, how, what)
end
alias_method :tds, :cells
end
end
end
|
Java
|
<?php
namespace PragmaRX\Health\Checkers;
use GuzzleHttp\Client as Guzzle;
use Illuminate\Support\Str;
use PragmaRX\Health\Support\LocallyProtected;
use PragmaRX\Health\Support\Result;
class ServerVars extends Base
{
protected $response;
protected $errors;
/**
* Check resource.
*
* @return Result
*/
public function check()
{
$this->requestServerVars();
collect($this->target->config['vars'])->each(function ($var) {
$this->checkVar($var);
});
return blank($this->errors)
? $this->makeHealthyResult()
: $this->makeResult(false, sprintf($this->target->resource->errorMessage, implode('; ', $this->errors)));
}
public function requestServerVars()
{
$url = $this->makeUrl();
$bearer = (new LocallyProtected())->protect($this->target->config['cache_timeout'] ?? 60);
$guzze = new Guzzle($this->getAuthorization());
$response = $guzze->request('GET', $url, [
'headers' => ['API-Token' => $bearer],
]);
if (($code = $response->getStatusCode()) !== 200) {
throw new \Exception("Request to {$url} returned a status code {$code}");
}
$this->response = json_decode((string) $response->getBody(), true);
}
public function checkVar($var)
{
if (blank($this->response[$var['name']] ?? null)) {
if ($var['mandatory']) {
$this->errors[] = "{$var['name']} is empty";
}
return;
}
$got = $this->response[$var['name']];
$expected = $var['value'];
if (! $this->compare($var, $expected, $got)) {
$this->errors[] = "{$var['name']}: expected '{$expected}' but got '{$got}'";
}
}
public function compare($var, $expected, $got)
{
$operator = $var['operator'] ?? 'equals';
$strict = $var['strict'] ?? true;
if ($operator === 'equals') {
return $strict ? $expected === $got : $expected == $got;
}
if ($operator === 'contains') {
return Str::contains($got, $expected);
}
throw new \Exception("Operator '$operator' is not supported.");
}
public function makeUrl()
{
$url = route($this->target->config['route']);
if ($queryString = $this->target->config['query_string']) {
$url .= "?$queryString";
}
return $url;
}
public function getAuthorization()
{
if (blank($auth = $this->target->config['auth'] ?? null)) {
return [];
}
return ['auth' => [$auth['username'], $auth['password']]];
}
}
|
Java
|
<aside class="main-sidebar">
<section class="sidebar">
<?= dmstr\widgets\Menu::widget(
[
'options' => ['class' => 'sidebar-menu'],
'items' => [
['label' => 'Menu', 'options' => ['class' => 'header']],
['label' => 'Home', 'icon' => 'fa fa-area-chart', 'url' => ['/site/index']],
['label' => 'Login', 'url' => ['site/login'], 'visible' => Yii::$app->user->isGuest],
[
'label' => 'Lesson',
'icon' => 'fa fa-book',
'url' => '#',
'items' => [
['label' => 'Index', 'icon' => 'fa fa-th-list', 'url' => ['/lesson/index'],],
['label' => 'Create', 'icon' => 'fa fa-edit', 'url' => ['/lesson/create'],],
],
],
[
'label' => 'App User',
'icon' => 'fa fa-group',
'url' => '#',
'items' => [
['label' => 'Points', 'icon' => 'fa fa-dollar', 'url' => ['/user-earned-point/index'],],
['label' => 'Score', 'icon' => 'fa fa-graduation-cap', 'url' => ['/user-score/index'],],
],
],
],
]
) ?>
</section>
</aside>
|
Java
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/optimization_guide/optimization_guide_web_contents_observer.h"
#include "chrome/browser/optimization_guide/chrome_hints_manager.h"
#include "chrome/browser/optimization_guide/optimization_guide_keyed_service.h"
#include "chrome/browser/optimization_guide/optimization_guide_keyed_service_factory.h"
#include "chrome/browser/prefetch/no_state_prefetch/no_state_prefetch_manager_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "components/no_state_prefetch/browser/no_state_prefetch_manager.h"
#include "components/optimization_guide/core/hints_fetcher.h"
#include "components/optimization_guide/core/hints_processing_util.h"
#include "components/optimization_guide/core/optimization_guide_enums.h"
#include "components/optimization_guide/core/optimization_guide_features.h"
#include "components/optimization_guide/proto/hints.pb.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
namespace {
bool IsValidOptimizationGuideNavigation(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle->IsInPrimaryMainFrame())
return false;
if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS())
return false;
// Now check if this is a NSP navigation. NSP is not a valid navigation.
prerender::NoStatePrefetchManager* no_state_prefetch_manager =
prerender::NoStatePrefetchManagerFactory::GetForBrowserContext(
navigation_handle->GetWebContents()->GetBrowserContext());
if (!no_state_prefetch_manager) {
// Not a NSP navigation if there is no NSP manager.
return true;
}
return !(no_state_prefetch_manager->IsWebContentsPrerendering(
navigation_handle->GetWebContents()));
}
} // namespace
OptimizationGuideWebContentsObserver::OptimizationGuideWebContentsObserver(
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
optimization_guide_keyed_service_ =
OptimizationGuideKeyedServiceFactory::GetForProfile(
Profile::FromBrowserContext(web_contents->GetBrowserContext()));
}
OptimizationGuideWebContentsObserver::~OptimizationGuideWebContentsObserver() =
default;
OptimizationGuideNavigationData* OptimizationGuideWebContentsObserver::
GetOrCreateOptimizationGuideNavigationData(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK_EQ(web_contents(), navigation_handle->GetWebContents());
NavigationHandleData* navigation_handle_data =
NavigationHandleData::GetOrCreateForNavigationHandle(*navigation_handle);
OptimizationGuideNavigationData* navigation_data =
navigation_handle_data->GetOptimizationGuideNavigationData();
if (!navigation_data) {
// We do not have one already - create one.
navigation_handle_data->SetOptimizationGuideNavigationData(
std::make_unique<OptimizationGuideNavigationData>(
navigation_handle->GetNavigationId(),
navigation_handle->NavigationStart()));
navigation_data =
navigation_handle_data->GetOptimizationGuideNavigationData();
}
DCHECK(navigation_data);
return navigation_data;
}
void OptimizationGuideWebContentsObserver::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!IsValidOptimizationGuideNavigation(navigation_handle))
return;
if (!optimization_guide_keyed_service_)
return;
OptimizationGuideNavigationData* navigation_data =
GetOrCreateOptimizationGuideNavigationData(navigation_handle);
navigation_data->set_navigation_url(navigation_handle->GetURL());
optimization_guide_keyed_service_->OnNavigationStartOrRedirect(
navigation_data);
}
void OptimizationGuideWebContentsObserver::DidRedirectNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!IsValidOptimizationGuideNavigation(navigation_handle))
return;
if (!optimization_guide_keyed_service_)
return;
OptimizationGuideNavigationData* navigation_data =
GetOrCreateOptimizationGuideNavigationData(navigation_handle);
navigation_data->set_navigation_url(navigation_handle->GetURL());
optimization_guide_keyed_service_->OnNavigationStartOrRedirect(
navigation_data);
}
void OptimizationGuideWebContentsObserver::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!IsValidOptimizationGuideNavigation(navigation_handle))
return;
// Note that a lot of Navigations (same document, non-committed, etc.) might
// not have navigation data associated with them, but we reduce likelihood of
// future leaks by always trying to remove the data.
NavigationHandleData* navigation_handle_data =
NavigationHandleData::GetForNavigationHandle(*navigation_handle);
if (!navigation_handle_data)
return;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&OptimizationGuideWebContentsObserver::NotifyNavigationFinish,
weak_factory_.GetWeakPtr(),
navigation_handle_data->TakeOptimizationGuideNavigationData(),
navigation_handle->GetRedirectChain()));
}
void OptimizationGuideWebContentsObserver::PostFetchHintsUsingManager(
content::RenderFrameHost* render_frame_host) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!render_frame_host->GetLastCommittedURL().SchemeIsHTTPOrHTTPS())
return;
if (!optimization_guide_keyed_service_)
return;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&OptimizationGuideWebContentsObserver::FetchHintsUsingManager,
weak_factory_.GetWeakPtr(),
optimization_guide_keyed_service_->GetHintsManager(),
web_contents()->GetPrimaryPage().GetWeakPtr()));
}
void OptimizationGuideWebContentsObserver::FetchHintsUsingManager(
optimization_guide::ChromeHintsManager* hints_manager,
base::WeakPtr<content::Page> page) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK(hints_manager);
if (!page)
return;
PageData& page_data = GetPageData(*page);
page_data.set_sent_batched_hints_request();
hints_manager->FetchHintsForURLs(
page_data.GetHintsTargetUrls(),
optimization_guide::proto::CONTEXT_BATCH_UPDATE_GOOGLE_SRP);
}
void OptimizationGuideWebContentsObserver::NotifyNavigationFinish(
std::unique_ptr<OptimizationGuideNavigationData> navigation_data,
const std::vector<GURL>& navigation_redirect_chain) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (optimization_guide_keyed_service_) {
optimization_guide_keyed_service_->OnNavigationFinish(
navigation_redirect_chain);
}
// We keep the navigation data in the PageData around to keep track of events
// happening for the navigation that can happen after commit, such as a fetch
// for the navigation successfully completing (which is not guaranteed to come
// back before commit, if at all).
PageData& page_data = GetPageData(web_contents()->GetPrimaryPage());
page_data.SetNavigationData(std::move(navigation_data));
}
void OptimizationGuideWebContentsObserver::FlushLastNavigationData() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
PageData& page_data = GetPageData(web_contents()->GetPrimaryPage());
page_data.SetNavigationData(nullptr);
}
void OptimizationGuideWebContentsObserver::AddURLsToBatchFetchBasedOnPrediction(
std::vector<GURL> urls,
content::WebContents* web_contents) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!this->web_contents())
return;
DCHECK_EQ(this->web_contents(), web_contents);
PageData& page_data = GetPageData(web_contents->GetPrimaryPage());
if (page_data.is_sent_batched_hints_request())
return;
page_data.InsertHintTargetUrls(urls);
PostFetchHintsUsingManager(web_contents->GetMainFrame());
}
OptimizationGuideWebContentsObserver::PageData&
OptimizationGuideWebContentsObserver::GetPageData(content::Page& page) {
return *PageData::GetOrCreateForPage(page);
}
OptimizationGuideWebContentsObserver::PageData::PageData(content::Page& page)
: PageUserData(page) {}
OptimizationGuideWebContentsObserver::PageData::~PageData() = default;
void OptimizationGuideWebContentsObserver::PageData::InsertHintTargetUrls(
const std::vector<GURL>& urls) {
DCHECK(!sent_batched_hints_request_);
for (const GURL& url : urls)
hints_target_urls_.insert(url);
}
std::vector<GURL>
OptimizationGuideWebContentsObserver::PageData::GetHintsTargetUrls() {
std::vector<GURL> target_urls = std::move(hints_target_urls_.vector());
hints_target_urls_.clear();
return target_urls;
}
OptimizationGuideWebContentsObserver::NavigationHandleData::
NavigationHandleData(content::NavigationHandle&) {}
OptimizationGuideWebContentsObserver::NavigationHandleData::
~NavigationHandleData() = default;
PAGE_USER_DATA_KEY_IMPL(OptimizationGuideWebContentsObserver::PageData);
NAVIGATION_HANDLE_USER_DATA_KEY_IMPL(
OptimizationGuideWebContentsObserver::NavigationHandleData);
WEB_CONTENTS_USER_DATA_KEY_IMPL(OptimizationGuideWebContentsObserver);
|
Java
|
// GLFW Engine.
// -----------------------------------------------------------------------------
// Copyright (C) 2011, ZEUS project (See authors)
//
// This program is open source and distributed under the New BSD License. See
// license for more detail.
// -----------------------------------------------------------------------------
#include <Core/GLFWEngine.h>
#include <Devices/GLFWKeyboard.h>
#include <Devices/GLFWMouse.h>
#include <Display/Camera.h>
#include <Display/GLFWWindow.h>
#include <Math/Vector.h>
#include <GL/glfw.h>
#include <stdlib.h>
using namespace ZEUS::Display;
using namespace ZEUS::Devices;
using namespace ZEUS::Math;
namespace ZEUS {
namespace Core {
GLFWEngine::GLFWEngine()
: IEngine() {
if (!glfwInit()) exit(EXIT_FAILURE);
Vector<2, unsigned int> res(800, 600);
window = new Display::GLFWWindow(res);
IKeyboard::Add<GLFWKeyboard>();
IMouse::Add<GLFWMouse>();
}
GLFWEngine::~GLFWEngine(){
glfwTerminate();
}
GLFWEngine* GLFWEngine::CreateEngine(){
GLFWEngine* tmp = new GLFWEngine();
engine = tmp;
return tmp;
}
void GLFWEngine::Initialize(){
glfwSetTime(0.0);
}
double GLFWEngine::GetImplTime(){
return glfwGetTime();
}
}
}
|
Java
|
/*
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <folly/Conv.h>
#include <folly/Foreach.h>
#include <folly/wangle/acceptor/ConnectionManager.h>
#include <folly/io/Cursor.h>
#include <folly/io/async/EventBase.h>
#include <folly/io/async/EventBaseManager.h>
#include <folly/io/async/TimeoutManager.h>
#include <gtest/gtest.h>
#include <proxygen/lib/http/codec/test/MockHTTPCodec.h>
#include <proxygen/lib/http/codec/test/TestUtils.h>
#include <proxygen/lib/http/session/HTTPDirectResponseHandler.h>
#include <proxygen/lib/http/session/HTTPDownstreamSession.h>
#include <proxygen/lib/http/session/HTTPSession.h>
#include <proxygen/lib/http/session/test/HTTPSessionMocks.h>
#include <proxygen/lib/http/session/test/HTTPSessionTest.h>
#include <proxygen/lib/http/session/test/MockByteEventTracker.h>
#include <proxygen/lib/http/session/test/TestUtils.h>
#include <proxygen/lib/test/TestAsyncTransport.h>
#include <string>
#include <strstream>
#include <folly/io/async/test/MockAsyncTransport.h>
#include <vector>
using namespace folly::wangle;
using namespace folly;
using namespace proxygen;
using namespace std;
using namespace testing;
struct HTTP1xCodecPair {
typedef HTTP1xCodec Codec;
static const int version = 1;
};
struct HTTP2CodecPair {
typedef HTTP2Codec Codec;
static const int version = 2;
};
struct SPDY2CodecPair {
typedef SPDYCodec Codec;
static const SPDYVersion version = SPDYVersion::SPDY2;
};
struct SPDY3CodecPair {
typedef SPDYCodec Codec;
static const SPDYVersion version = SPDYVersion::SPDY3;
};
struct SPDY3_1CodecPair {
typedef SPDYCodec Codec;
static const SPDYVersion version = SPDYVersion::SPDY3_1;
};
template <typename C>
class HTTPDownstreamTest : public testing::Test {
public:
explicit HTTPDownstreamTest(uint32_t sessionWindowSize = spdy::kInitialWindow)
: eventBase_(),
transport_(new TestAsyncTransport(&eventBase_)),
transactionTimeouts_(makeTimeoutSet(&eventBase_)) {
EXPECT_CALL(mockController_, attachSession(_));
httpSession_ = new HTTPDownstreamSession(
transactionTimeouts_.get(),
std::move(AsyncTransportWrapper::UniquePtr(transport_)),
localAddr, peerAddr,
&mockController_,
std::move(makeServerCodec<typename C::Codec>(
C::version)),
mockTransportInfo /* no stats for now */);
httpSession_->setFlowControl(spdy::kInitialWindow, spdy::kInitialWindow,
sessionWindowSize);
httpSession_->startNow();
}
void SetUp() {
folly::EventBaseManager::get()->clearEventBase();
HTTPSession::setPendingWriteMax(65536);
}
void addSingleByteReads(const char* data,
std::chrono::milliseconds delay={}) {
for (const char* p = data; *p != '\0'; ++p) {
transport_->addReadEvent(p, 1, delay);
}
}
void testPriorities(HTTPCodec& clientCodec, uint32_t numPriorities);
void testChunks(bool trailers);
void parseOutput(HTTPCodec& clientCodec) {
IOBufQueue stream(IOBufQueue::cacheChainLength());
auto writeEvents = transport_->getWriteEvents();
for (auto event: *writeEvents) {
auto vec = event->getIoVec();
for (size_t i = 0; i < event->getCount(); i++) {
unique_ptr<IOBuf> buf(
std::move(IOBuf::wrapBuffer(vec[i].iov_base, vec[i].iov_len)));
stream.append(std::move(buf));
uint32_t consumed = clientCodec.onIngress(*stream.front());
stream.split(consumed);
}
}
EXPECT_EQ(stream.chainLength(), 0);
}
protected:
EventBase eventBase_;
TestAsyncTransport* transport_; // invalid once httpSession_ is destroyed
AsyncTimeoutSet::UniquePtr transactionTimeouts_;
StrictMock<MockController> mockController_;
HTTPDownstreamSession* httpSession_;
};
// Uses TestAsyncTransport
typedef HTTPDownstreamTest<HTTP1xCodecPair> HTTPDownstreamSessionTest;
typedef HTTPDownstreamTest<SPDY2CodecPair> SPDY2DownstreamSessionTest;
typedef HTTPDownstreamTest<SPDY3CodecPair> SPDY3DownstreamSessionTest;
TEST_F(HTTPDownstreamSessionTest, immediate_eof) {
// Send EOF without any request data
EXPECT_CALL(mockController_, getRequestHandler(_, _)).Times(0);
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, http_1_0_no_headers) {
MockHTTPHandler* handler = new MockHTTPHandler();
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(handler));
EXPECT_CALL(*handler, setTransaction(_))
.WillOnce(SaveArg<0>(&handler->txn_));
EXPECT_CALL(*handler, onHeadersComplete(_))
.WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) {
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("/", msg->getURL());
EXPECT_EQ("/", msg->getPath());
EXPECT_EQ("", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(0, msg->getHTTPVersion().second);
}));
EXPECT_CALL(*handler, onEOM())
.WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate));
EXPECT_CALL(*handler, detachTransaction())
.WillOnce(InvokeWithoutArgs([&] { delete handler; }));
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent("GET / HTTP/1.0\r\n\r\n",
std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, http_1_0_no_headers_eof) {
MockHTTPHandler* handler = new MockHTTPHandler();
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(handler));
EXPECT_CALL(*handler, setTransaction(_))
.WillOnce(SaveArg<0>(&handler->txn_));
EXPECT_CALL(*handler, onHeadersComplete(_))
.WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) {
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("http://example.com/foo?bar", msg->getURL());
EXPECT_EQ("/foo", msg->getPath());
EXPECT_EQ("bar", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(0, msg->getHTTPVersion().second);
}));
EXPECT_CALL(*handler, onEOM())
.WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate));
EXPECT_CALL(*handler, detachTransaction())
.WillOnce(InvokeWithoutArgs([&] { delete handler; }));
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent("GET http://example.com/foo?bar HTTP/1.0\r\n\r\n",
std::chrono::milliseconds(0));
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, single_bytes) {
MockHTTPHandler* handler = new MockHTTPHandler();
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(handler));
EXPECT_CALL(*handler, setTransaction(_))
.WillOnce(SaveArg<0>(&handler->txn_));
EXPECT_CALL(*handler, onHeadersComplete(_))
.WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(2, hdrs.size());
EXPECT_TRUE(hdrs.exists("host"));
EXPECT_TRUE(hdrs.exists("connection"));
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("/somepath.php?param=foo", msg->getURL());
EXPECT_EQ("/somepath.php", msg->getPath());
EXPECT_EQ("param=foo", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(1, msg->getHTTPVersion().second);
}));
EXPECT_CALL(*handler, onEOM())
.WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate));
EXPECT_CALL(*handler, detachTransaction())
.WillOnce(InvokeWithoutArgs([&] { delete handler; }));
EXPECT_CALL(mockController_, detachSession(_));
addSingleByteReads("GET /somepath.php?param=foo HTTP/1.1\r\n"
"Host: example.com\r\n"
"Connection: close\r\n"
"\r\n");
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, single_bytes_with_body) {
MockHTTPHandler* handler = new MockHTTPHandler();
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(handler));
EXPECT_CALL(*handler, setTransaction(_))
.WillOnce(SaveArg<0>(&handler->txn_));
EXPECT_CALL(*handler, onHeadersComplete(_))
.WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(3, hdrs.size());
EXPECT_TRUE(hdrs.exists("host"));
EXPECT_TRUE(hdrs.exists("content-length"));
EXPECT_TRUE(hdrs.exists("myheader"));
EXPECT_FALSE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("/somepath.php?param=foo", msg->getURL());
EXPECT_EQ("/somepath.php", msg->getPath());
EXPECT_EQ("param=foo", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(1, msg->getHTTPVersion().second);
}));
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("1"))
.WillOnce(ExpectString("2"))
.WillOnce(ExpectString("3"))
.WillOnce(ExpectString("4"))
.WillOnce(ExpectString("5"));
EXPECT_CALL(*handler, onEOM())
.WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate));
EXPECT_CALL(*handler, detachTransaction())
.WillOnce(InvokeWithoutArgs([&] { delete handler; }));
EXPECT_CALL(mockController_, detachSession(_));
addSingleByteReads("POST /somepath.php?param=foo HTTP/1.1\r\n"
"Host: example.com\r\n"
"MyHeader: FooBar\r\n"
"Content-Length: 5\r\n"
"\r\n"
"12345");
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, split_body) {
MockHTTPHandler* handler = new MockHTTPHandler();
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(handler));
EXPECT_CALL(*handler, setTransaction(_))
.WillOnce(SaveArg<0>(&handler->txn_));
EXPECT_CALL(*handler, onHeadersComplete(_))
.WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(2, hdrs.size());
}));
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("12345"))
.WillOnce(ExpectString("abcde"));
EXPECT_CALL(*handler, onEOM())
.WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate));
EXPECT_CALL(*handler, detachTransaction())
.WillOnce(InvokeWithoutArgs([&] { delete handler; }));
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent("POST / HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Length: 10\r\n"
"\r\n"
"12345", std::chrono::milliseconds(0));
transport_->addReadEvent("abcde", std::chrono::milliseconds(5));
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, post_chunked) {
MockHTTPHandler* handler = new MockHTTPHandler();
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(handler));
EXPECT_CALL(*handler, setTransaction(_))
.WillOnce(SaveArg<0>(&handler->txn_));
EXPECT_CALL(*handler, onHeadersComplete(_))
.WillOnce(Invoke([&] (std::shared_ptr<HTTPMessage> msg) {
const HTTPHeaders& hdrs = msg->getHeaders();
EXPECT_EQ(3, hdrs.size());
EXPECT_TRUE(hdrs.exists("host"));
EXPECT_TRUE(hdrs.exists("content-type"));
EXPECT_TRUE(hdrs.exists("transfer-encoding"));
EXPECT_TRUE(msg->getIsChunked());
EXPECT_FALSE(msg->getIsUpgraded());
EXPECT_EQ("http://example.com/cgi-bin/foo.aspx?abc&def",
msg->getURL());
EXPECT_EQ("/cgi-bin/foo.aspx", msg->getPath());
EXPECT_EQ("abc&def", msg->getQueryString());
EXPECT_EQ(1, msg->getHTTPVersion().first);
EXPECT_EQ(1, msg->getHTTPVersion().second);
}));
EXPECT_CALL(*handler, onChunkHeader(3));
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("bar"));
EXPECT_CALL(*handler, onChunkComplete());
EXPECT_CALL(*handler, onChunkHeader(0x22));
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("0123456789abcdef\nfedcba9876543210\n"));
EXPECT_CALL(*handler, onChunkComplete());
EXPECT_CALL(*handler, onChunkHeader(3));
EXPECT_CALL(*handler, onBody(_))
.WillOnce(ExpectString("foo"));
EXPECT_CALL(*handler, onChunkComplete());
EXPECT_CALL(*handler, onEOM())
.WillOnce(InvokeWithoutArgs(handler, &MockHTTPHandler::terminate));
EXPECT_CALL(*handler, detachTransaction())
.WillOnce(InvokeWithoutArgs([&] { delete handler; }));
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent("POST http://example.com/cgi-bin/foo.aspx?abc&def "
"HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Type: text/pla", std::chrono::milliseconds(0));
transport_->addReadEvent("in; charset=utf-8\r\n"
"Transfer-encoding: chunked\r\n"
"\r", std::chrono::milliseconds(2));
transport_->addReadEvent("\n"
"3\r\n"
"bar\r\n"
"22\r\n"
"0123456789abcdef\n"
"fedcba9876543210\n"
"\r\n"
"3\r", std::chrono::milliseconds(3));
transport_->addReadEvent("\n"
"foo\r\n"
"0\r\n\r\n", std::chrono::milliseconds(1));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, multi_message) {
MockHTTPHandler* handler1 = new MockHTTPHandler();
MockHTTPHandler* handler2 = new MockHTTPHandler();
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(handler1))
.WillOnce(Return(handler2));
InSequence dummy;
EXPECT_CALL(*handler1, setTransaction(_))
.WillOnce(SaveArg<0>(&handler1->txn_));
EXPECT_CALL(*handler1, onHeadersComplete(_));
EXPECT_CALL(*handler1, onBody(_))
.WillOnce(ExpectString("foo"))
.WillOnce(ExpectString("bar9876"));
EXPECT_CALL(*handler1, onEOM())
.WillOnce(InvokeWithoutArgs(handler1, &MockHTTPHandler::sendReply));
EXPECT_CALL(*handler1, detachTransaction())
.WillOnce(InvokeWithoutArgs([&] { delete handler1; }));
EXPECT_CALL(*handler2, setTransaction(_))
.WillOnce(SaveArg<0>(&handler2->txn_));
EXPECT_CALL(*handler2, onHeadersComplete(_));
EXPECT_CALL(*handler2, onChunkHeader(0xa));
EXPECT_CALL(*handler2, onBody(_))
.WillOnce(ExpectString("some "))
.WillOnce(ExpectString("data\n"));
EXPECT_CALL(*handler2, onChunkComplete());
EXPECT_CALL(*handler2, onEOM())
.WillOnce(InvokeWithoutArgs(handler2, &MockHTTPHandler::terminate));
EXPECT_CALL(*handler2, detachTransaction())
.WillOnce(InvokeWithoutArgs([&] { delete handler2; }));
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent("POST / HTTP/1.1\r\n"
"Host: example.com\r\n"
"Content-Length: 10\r\n"
"\r\n"
"foo", std::chrono::milliseconds(0));
transport_->addReadEvent("bar9876"
"POST /foo HTTP/1.1\r\n"
"Host: exa", std::chrono::milliseconds(2));
transport_->addReadEvent("mple.com\r\n"
"Connection: close\r\n"
"Trans", std::chrono::milliseconds(0));
transport_->addReadEvent("fer-encoding: chunked\r\n"
"\r\n", std::chrono::milliseconds(2));
transport_->addReadEvent("a\r\nsome ", std::chrono::milliseconds(0));
transport_->addReadEvent("data\n\r\n0\r\n\r\n", std::chrono::milliseconds(2));
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, connect) {
StrictMock<MockHTTPHandler> handler;
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler));
EXPECT_CALL(handler, setTransaction(_))
.WillOnce(SaveArg<0>(&handler.txn_));
// Send HTTP 200 OK to accept the CONNECT request
EXPECT_CALL(handler, onHeadersComplete(_))
.WillOnce(Invoke([&handler] (std::shared_ptr<HTTPMessage> msg) {
handler.sendHeaders(200, 100);
}));
EXPECT_CALL(handler, onUpgrade(_));
// Data should be received using onBody
EXPECT_CALL(handler, onBody(_))
.WillOnce(ExpectString("12345"))
.WillOnce(ExpectString("abcde"));
EXPECT_CALL(handler, onEOM())
.WillOnce(InvokeWithoutArgs(&handler, &MockHTTPHandler::terminate));
EXPECT_CALL(handler, detachTransaction());
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent("CONNECT test HTTP/1.1\r\n"
"\r\n"
"12345", std::chrono::milliseconds(0));
transport_->addReadEvent("abcde", std::chrono::milliseconds(5));
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, connect_rejected) {
StrictMock<MockHTTPHandler> handler;
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler));
EXPECT_CALL(handler, setTransaction(_))
.WillOnce(SaveArg<0>(&handler.txn_));
// Send HTTP 400 to reject the CONNECT request
EXPECT_CALL(handler, onHeadersComplete(_))
.WillOnce(Invoke([&handler] (std::shared_ptr<HTTPMessage> msg) {
handler.sendReplyCode(400);
}));
EXPECT_CALL(handler, onEOM())
.WillOnce(InvokeWithoutArgs(&handler, &MockHTTPHandler::terminate));
EXPECT_CALL(handler, detachTransaction());
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent("CONNECT test HTTP/1.1\r\n"
"\r\n"
"12345", std::chrono::milliseconds(0));
transport_->addReadEvent("abcde", std::chrono::milliseconds(5));
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, http_upgrade) {
StrictMock<MockHTTPHandler> handler;
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler));
EXPECT_CALL(handler, setTransaction(_))
.WillOnce(SaveArg<0>(&handler.txn_));
// Send HTTP 101 Switching Protocls to accept the upgrade request
EXPECT_CALL(handler, onHeadersComplete(_))
.WillOnce(Invoke([&handler] (std::shared_ptr<HTTPMessage> msg) {
handler.sendHeaders(101, 100);
}));
// Send the response in the new protocol after upgrade
EXPECT_CALL(handler, onUpgrade(_))
.WillOnce(Invoke([&handler] (UpgradeProtocol protocol) {
handler.sendReplyCode(100);
}));
EXPECT_CALL(handler, onEOM())
.WillOnce(InvokeWithoutArgs(&handler, &MockHTTPHandler::terminate));
EXPECT_CALL(handler, detachTransaction());
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent("GET /upgrade HTTP/1.1\r\n"
"Upgrade: TEST/1.0\r\n"
"Connection: upgrade\r\n"
"\r\n", std::chrono::milliseconds(0));
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST(HTTPDownstreamTest, parse_error_no_txn) {
// 1) Get a parse error on SYN_STREAM for streamID == 1
// 2) Expect that the codec should be asked to generate an abort on
// streamID==1
EventBase evb;
// Setup the controller and its expecations.
NiceMock<MockController> mockController;
// Setup the codec, its callbacks, and its expectations.
auto codec = makeDownstreamParallelCodec();
HTTPCodec::Callback* codecCallback = nullptr;
EXPECT_CALL(*codec, setCallback(_))
.WillRepeatedly(SaveArg<0>(&codecCallback));
// Expect egress abort for streamID == 1
EXPECT_CALL(*codec, generateRstStream(_, 1, _));
// Setup transport
bool transportGood = true;
auto transport = newMockTransport(&evb);
EXPECT_CALL(*transport, good())
.WillRepeatedly(ReturnPointee(&transportGood));
EXPECT_CALL(*transport, closeNow())
.WillRepeatedly(Assign(&transportGood, false));
EXPECT_CALL(*transport, writeChain(_, _, _))
.WillRepeatedly(Invoke([&] (folly::AsyncTransportWrapper::WriteCallback* callback,
const shared_ptr<IOBuf> iob,
WriteFlags flags) {
callback->writeSuccess();
}));
// Create the downstream session, thus initializing codecCallback
auto transactionTimeouts = makeInternalTimeoutSet(&evb);
auto session = new HTTPDownstreamSession(
transactionTimeouts.get(),
AsyncTransportWrapper::UniquePtr(transport),
localAddr, peerAddr,
&mockController, std::move(codec),
mockTransportInfo);
session->startNow();
HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS, "foo");
ex.setProxygenError(kErrorParseHeader);
ex.setCodecStatusCode(ErrorCode::REFUSED_STREAM);
codecCallback->onError(HTTPCodec::StreamID(1), ex, true);
// cleanup
session->shutdownTransportWithReset(kErrorConnectionReset);
evb.loop();
}
TEST(HTTPDownstreamTest, byte_events_drained) {
// Test that byte events are drained before socket is closed
EventBase evb;
NiceMock<MockController> mockController;
auto codec = makeDownstreamParallelCodec();
auto byteEventTracker = new MockByteEventTracker(nullptr);
auto transport = newMockTransport(&evb);
auto transactionTimeouts = makeInternalTimeoutSet(&evb);
// Create the downstream session
auto session = new HTTPDownstreamSession(
transactionTimeouts.get(),
AsyncTransportWrapper::UniquePtr(transport),
localAddr, peerAddr,
&mockController, std::move(codec),
mockTransportInfo);
session->setByteEventTracker(
std::unique_ptr<ByteEventTracker>(byteEventTracker));
InSequence dummy;
session->startNow();
// Byte events should be drained first
EXPECT_CALL(*byteEventTracker, drainByteEvents())
.Times(1);
EXPECT_CALL(*transport, closeWithReset())
.Times(AtLeast(1));
// Close the socket
session->shutdownTransportWithReset(kErrorConnectionReset);
evb.loop();
}
TEST_F(HTTPDownstreamSessionTest, trailers) {
testChunks(true);
}
TEST_F(HTTPDownstreamSessionTest, explicit_chunks) {
testChunks(false);
}
template <class C>
void HTTPDownstreamTest<C>::testChunks(bool trailers) {
StrictMock<MockHTTPHandler> handler;
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler));
EXPECT_CALL(handler, setTransaction(_))
.WillOnce(SaveArg<0>(&handler.txn_));
EXPECT_CALL(handler, onHeadersComplete(_));
EXPECT_CALL(handler, onEOM())
.WillOnce(InvokeWithoutArgs([&handler, trailers] () {
handler.sendChunkedReplyWithBody(200, 100, 17, trailers);
}));
EXPECT_CALL(handler, detachTransaction());
transport_->addReadEvent("GET / HTTP/1.1\r\n"
"\r\n", std::chrono::milliseconds(0));
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
HTTP1xCodec clientCodec(TransportDirection::UPSTREAM);
NiceMock<MockHTTPCodecCallback> callbacks;
EXPECT_CALL(callbacks, onMessageBegin(1, _))
.Times(1);
EXPECT_CALL(callbacks, onHeadersComplete(1, _))
.Times(1);
for (int i = 0; i < 6; i++) {
EXPECT_CALL(callbacks, onChunkHeader(1, _));
EXPECT_CALL(callbacks, onBody(1, _));
EXPECT_CALL(callbacks, onChunkComplete(1));
}
if (trailers) {
EXPECT_CALL(callbacks, onTrailersComplete(1, _));
}
EXPECT_CALL(callbacks, onMessageComplete(1, _));
clientCodec.setCallback(&callbacks);
parseOutput(clientCodec);
EXPECT_CALL(mockController_, detachSession(_));
}
TEST_F(HTTPDownstreamSessionTest, http_drain) {
StrictMock<MockHTTPHandler> handler1;
StrictMock<MockHTTPHandler> handler2;
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler1));
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(SaveArg<0>(&handler1.txn_));
EXPECT_CALL(handler1, onHeadersComplete(_))
.WillOnce(Invoke([this, &handler1] (std::shared_ptr<HTTPMessage> msg) {
handler1.sendHeaders(200, 100);
httpSession_->notifyPendingShutdown();
}));
EXPECT_CALL(handler1, onEOM())
.WillOnce(InvokeWithoutArgs([&handler1] {
handler1.sendBody(100);
handler1.txn_->sendEOM();
}));
EXPECT_CALL(handler1, detachTransaction());
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler2));
EXPECT_CALL(handler2, setTransaction(_))
.WillOnce(SaveArg<0>(&handler2.txn_));
EXPECT_CALL(handler2, onHeadersComplete(_))
.WillOnce(Invoke([this, &handler2] (std::shared_ptr<HTTPMessage> msg) {
handler2.sendHeaders(200, 100);
}));
EXPECT_CALL(handler2, onEOM())
.WillOnce(InvokeWithoutArgs([&handler2] {
handler2.sendBody(100);
handler2.txn_->sendEOM();
}));
EXPECT_CALL(handler2, detachTransaction());
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent("GET / HTTP/1.1\r\n"
"\r\n", std::chrono::milliseconds(0));
transport_->addReadEvent("GET / HTTP/1.1\r\n"
"\r\n", std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
// 1) receive full request
// 2) notify pending shutdown
// 3) wait for session read timeout -> should be ignored
// 4) response completed
TEST_F(HTTPDownstreamSessionTest, http_drain_long_running) {
StrictMock<MockHTTPHandler> handler;
InSequence enforceSequence;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler));
// txn1, as soon as headers go out, mark set code shouldShutdown=true
EXPECT_CALL(handler, setTransaction(_))
.WillOnce(SaveArg<0>(&handler.txn_));
EXPECT_CALL(handler, onHeadersComplete(_))
.WillOnce(Invoke([this, &handler] (std::shared_ptr<HTTPMessage> msg) {
httpSession_->notifyPendingShutdown();
eventBase_.tryRunAfterDelay([this] {
// simulate read timeout
httpSession_->timeoutExpired();
}, 100);
eventBase_.tryRunAfterDelay([&handler] {
handler.sendReplyWithBody(200, 100);
}, 200);
}));
EXPECT_CALL(handler, onEOM());
EXPECT_CALL(handler, detachTransaction());
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent("GET / HTTP/1.1\r\n"
"\r\n", std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, early_abort) {
MockHTTPHandler* handler = new MockHTTPHandler();
InSequence dummy;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(handler));
EXPECT_CALL(*handler, setTransaction(_))
.WillOnce(Invoke([&] (HTTPTransaction* txn) {
handler->txn_ = txn;
handler->txn_->sendAbort();
}));
EXPECT_CALL(*handler, onHeadersComplete(_))
.Times(0);
EXPECT_CALL(*handler, detachTransaction())
.WillOnce(InvokeWithoutArgs([&] { delete handler; }));
EXPECT_CALL(mockController_, detachSession(_));
addSingleByteReads("GET /somepath.php?param=foo HTTP/1.1\r\n"
"Host: example.com\r\n"
"Connection: close\r\n"
"\r\n");
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(SPDY3DownstreamSessionTest, http_paused_buffered) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
IOBufQueue rst{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
MockHTTPHandler handler1;
MockHTTPHandler handler2;
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY3);
auto streamID = HTTPCodec::StreamID(1);
clientCodec.generateConnectionPreface(requests);
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
clientCodec.generateRstStream(rst, streamID, ErrorCode::CANCEL);
streamID += 2;
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler1))
.WillOnce(Return(&handler2));
EXPECT_CALL(mockController_, detachSession(_));
InSequence handlerSequence;
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
handler1.txn_ = txn; }));
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM())
.WillOnce(InvokeWithoutArgs([&handler1, this] {
transport_->pauseWrites();
handler1.sendHeaders(200, 65536 * 2);
handler1.sendBody(65536 * 2);
}));
EXPECT_CALL(handler1, onEgressPaused());
EXPECT_CALL(handler2, setTransaction(_))
.WillOnce(Invoke([&handler2] (HTTPTransaction* txn) {
handler2.txn_ = txn; }));
EXPECT_CALL(handler2, onEgressPaused());
EXPECT_CALL(handler2, onHeadersComplete(_));
EXPECT_CALL(handler2, onEOM());
EXPECT_CALL(handler1, onError(_))
.WillOnce(Invoke([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorStreamAbort);
eventBase_.runInLoop([this] {
transport_->resumeWrites();
});
}));
EXPECT_CALL(handler1, detachTransaction());
EXPECT_CALL(handler2, onEgressResumed())
.WillOnce(Invoke([&] () {
handler2.sendReplyWithBody(200, 32768);
}));
EXPECT_CALL(handler2, detachTransaction());
transport_->addReadEvent(requests, std::chrono::milliseconds(10));
transport_->addReadEvent(rst, std::chrono::milliseconds(10));
transport_->addReadEOF(std::chrono::milliseconds(50));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, http_writes_draining_timeout) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
MockHTTPHandler handler1;
HTTP1xCodec clientCodec(TransportDirection::UPSTREAM);
auto streamID = HTTPCodec::StreamID(0);
clientCodec.generateConnectionPreface(requests);
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
clientCodec.generateHeader(requests, streamID, req);
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler1));
EXPECT_CALL(mockController_, detachSession(_));
InSequence handlerSequence;
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
handler1.txn_ = txn; }));
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM())
.WillOnce(InvokeWithoutArgs([&handler1, this] {
transport_->pauseWrites();
handler1.sendHeaders(200, 1000);
}));
EXPECT_CALL(handler1, onError(_))
.WillOnce(Invoke([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(
folly::to<std::string>("WriteTimeout on transaction id: ",
handler1.txn_->getID()),
std::string(ex.what()));
handler1.txn_->sendAbort();
}));
EXPECT_CALL(handler1, detachTransaction());
transport_->addReadEvent(requests, std::chrono::milliseconds(10));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, http_rate_limit_normal) {
// The rate-limiting code grabs the event base from the EventBaseManager,
// so we need to set it.
folly::EventBaseManager::get()->setEventBase(&eventBase_, false);
// Create a request
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
MockHTTPHandler handler1;
HTTP1xCodec clientCodec(TransportDirection::UPSTREAM);
auto streamID = HTTPCodec::StreamID(0);
clientCodec.generateConnectionPreface(requests);
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
// The controller should return the handler when asked
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillRepeatedly(Return(&handler1));
// Set a low rate-limit on the transaction
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
uint32_t rateLimit_kbps = 640;
txn->setEgressRateLimit(rateLimit_kbps * 1024);
handler1.txn_ = txn;
}));
// Send a somewhat big response that we know will get rate-limited
InSequence handlerSequence;
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM())
.WillOnce(InvokeWithoutArgs([&handler1, this] {
// At 640kbps, this should take slightly over 800ms
uint32_t rspLengthBytes = 100000;
handler1.sendHeaders(200, rspLengthBytes);
handler1.sendBody(rspLengthBytes);
handler1.txn_->sendEOM();
}));
EXPECT_CALL(handler1, detachTransaction());
transport_->addReadEvent(requests, std::chrono::milliseconds(10));
transport_->startReadEvents();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
proxygen::TimePoint timeFirstWrite =
transport_->getWriteEvents()->front()->getTime();
proxygen::TimePoint timeLastWrite =
transport_->getWriteEvents()->back()->getTime();
int64_t writeDuration =
(int64_t)millisecondsBetween(timeLastWrite, timeFirstWrite).count();
EXPECT_GT(writeDuration, 800);
}
TEST_F(SPDY3DownstreamSessionTest, spdy_rate_limit_normal) {
// The rate-limiting code grabs the event base from the EventBaseManager,
// so we need to set it.
folly::EventBaseManager::get()->setEventBase(&eventBase_, false);
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
MockHTTPHandler handler1;
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY3);
auto streamID = HTTPCodec::StreamID(1);
clientCodec.generateConnectionPreface(requests);
clientCodec.getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
100000);
clientCodec.generateSettings(requests);
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillRepeatedly(Return(&handler1));
EXPECT_CALL(mockController_, detachSession(_));
InSequence handlerSequence;
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
uint32_t rateLimit_kbps = 640;
txn->setEgressRateLimit(rateLimit_kbps * 1024);
handler1.txn_ = txn;
}));
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM())
.WillOnce(InvokeWithoutArgs([&handler1, this] {
// At 640kbps, this should take slightly over 800ms
uint32_t rspLengthBytes = 100000;
handler1.sendHeaders(200, rspLengthBytes);
handler1.sendBody(rspLengthBytes);
handler1.txn_->sendEOM();
}));
EXPECT_CALL(handler1, detachTransaction());
transport_->addReadEvent(requests, std::chrono::milliseconds(10));
transport_->addReadEOF(std::chrono::milliseconds(50));
transport_->startReadEvents();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
proxygen::TimePoint timeFirstWrite =
transport_->getWriteEvents()->front()->getTime();
proxygen::TimePoint timeLastWrite =
transport_->getWriteEvents()->back()->getTime();
int64_t writeDuration =
(int64_t)millisecondsBetween(timeLastWrite, timeFirstWrite).count();
EXPECT_GT(writeDuration, 800);
}
/**
* This test will reset the connection while the server is waiting around
* to send more bytes (so as to keep under the rate limit).
*/
TEST_F(SPDY3DownstreamSessionTest, spdy_rate_limit_rst) {
// The rate-limiting code grabs the event base from the EventBaseManager,
// so we need to set it.
folly::EventBaseManager::get()->setEventBase(&eventBase_, false);
IOBufQueue requests{IOBufQueue::cacheChainLength()};
IOBufQueue rst{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
MockHTTPHandler handler1;
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY3);
auto streamID = HTTPCodec::StreamID(1);
clientCodec.generateConnectionPreface(requests);
clientCodec.getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
100000);
clientCodec.generateSettings(requests);
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
clientCodec.generateRstStream(rst, streamID, ErrorCode::CANCEL);
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillRepeatedly(Return(&handler1));
EXPECT_CALL(mockController_, detachSession(_));
InSequence handlerSequence;
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
uint32_t rateLimit_kbps = 640;
txn->setEgressRateLimit(rateLimit_kbps * 1024);
handler1.txn_ = txn;
}));
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM())
.WillOnce(InvokeWithoutArgs([&handler1, this] {
uint32_t rspLengthBytes = 100000;
handler1.sendHeaders(200, rspLengthBytes);
handler1.sendBody(rspLengthBytes);
handler1.txn_->sendEOM();
}));
EXPECT_CALL(handler1, onError(_));
EXPECT_CALL(handler1, detachTransaction());
transport_->addReadEvent(requests, std::chrono::milliseconds(10));
transport_->addReadEvent(rst, std::chrono::milliseconds(10));
transport_->addReadEOF(std::chrono::milliseconds(50));
transport_->startReadEvents();
eventBase_.loop();
}
// Send a 1.0 request, egress the EOM with the last body chunk on a paused
// socket, and let it timeout. shutdownTransportWithReset will result in a call
// to removeTransaction with writesDraining_=true
TEST_F(HTTPDownstreamSessionTest, write_timeout) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
MockHTTPHandler handler1;
HTTPMessage req = getGetRequest();
req.setHTTPVersion(1, 0);
HTTP1xCodec clientCodec(TransportDirection::UPSTREAM);
auto streamID = HTTPCodec::StreamID(0);
clientCodec.generateConnectionPreface(requests);
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler1));
InSequence handlerSequence;
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
handler1.txn_ = txn; }));
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM())
.WillOnce(InvokeWithoutArgs([&handler1, this] {
handler1.sendHeaders(200, 100);
eventBase_.tryRunAfterDelay([&handler1, this] {
transport_->pauseWrites();
handler1.sendBody(100);
handler1.txn_->sendEOM();
}, 50);
}));
EXPECT_CALL(handler1, onError(_))
.WillOnce(Invoke([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(
folly::to<std::string>("WriteTimeout on transaction id: ",
handler1.txn_->getID()),
std::string(ex.what()));
}));
EXPECT_CALL(handler1, detachTransaction());
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent(requests, std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
// Send an abort from the write timeout path while pipelining
TEST_F(HTTPDownstreamSessionTest, write_timeout_pipeline) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
MockHTTPHandler handler1;
HTTPMessage req = getGetRequest();
HTTP1xCodec clientCodec(TransportDirection::UPSTREAM);
const char* buf = "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n"
"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler1));
InSequence handlerSequence;
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
handler1.txn_ = txn; }));
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM())
.WillOnce(InvokeWithoutArgs([&handler1, this] {
handler1.sendHeaders(200, 100);
eventBase_.tryRunAfterDelay([&handler1, this] {
transport_->pauseWrites();
handler1.sendBody(100);
handler1.txn_->sendEOM();
}, 50);
}));
EXPECT_CALL(handler1, onError(_))
.WillOnce(Invoke([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorWriteTimeout);
ASSERT_EQ(
folly::to<std::string>("WriteTimeout on transaction id: ",
handler1.txn_->getID()),
std::string(ex.what()));
handler1.txn_->sendAbort();
}));
EXPECT_CALL(handler1, detachTransaction());
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent(buf, std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, body_packetization) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
MockHTTPHandler handler1;
HTTPMessage req = getGetRequest();
req.setHTTPVersion(1, 0);
req.setWantsKeepalive(false);
HTTP1xCodec clientCodec(TransportDirection::UPSTREAM);
auto streamID = HTTPCodec::StreamID(0);
clientCodec.generateConnectionPreface(requests);
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler1));
InSequence handlerSequence;
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
handler1.txn_ = txn; }));
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM())
.WillOnce(InvokeWithoutArgs([&handler1, this] {
handler1.sendReplyWithBody(200, 32768);
}));
EXPECT_CALL(handler1, detachTransaction());
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent(requests, std::chrono::milliseconds(0));
transport_->startReadEvents();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
EXPECT_EQ(transport_->getWriteEvents()->size(), 1);
}
TEST_F(HTTPDownstreamSessionTest, http_malformed_pkt1) {
// Create a HTTP connection and keep sending just '\n' to the HTTP1xCodec.
std::string data(90000, '\n');
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent(data.c_str(), data.length(),
std::chrono::milliseconds(0));
transport_->addReadEOF(std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
}
TEST_F(HTTPDownstreamSessionTest, big_explcit_chunk_write) {
// even when the handler does a massive write, the transport only gets small
// writes
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
HTTP1xCodec clientCodec(TransportDirection::UPSTREAM);
auto streamID = HTTPCodec::StreamID(0);
clientCodec.generateConnectionPreface(requests);
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
MockHTTPHandler handler;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler));
EXPECT_CALL(handler, setTransaction(_))
.WillOnce(Invoke([&handler] (HTTPTransaction* txn) {
handler.txn_ = txn; }));
EXPECT_CALL(handler, onHeadersComplete(_))
.WillOnce(Invoke([&handler] (std::shared_ptr<HTTPMessage> msg) {
handler.sendHeaders(200, 100, false);
size_t len = 16 * 1024 * 1024;
handler.txn_->sendChunkHeader(len);
auto chunk = makeBuf(len);
handler.txn_->sendBody(std::move(chunk));
handler.txn_->sendChunkTerminator();
handler.txn_->sendEOM();
}));
EXPECT_CALL(handler, detachTransaction());
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent(requests, std::chrono::milliseconds(0));
transport_->startReadEvents();
// Keep the session around even after the event base loop completes so we can
// read the counters on a valid object.
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
EXPECT_GT(transport_->getWriteEvents()->size(), 250);
}
TEST_F(SPDY2DownstreamSessionTest, spdy_prio) {
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY2);
testPriorities(clientCodec, 4);
}
TEST_F(SPDY3DownstreamSessionTest, spdy_prio) {
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY3);
testPriorities(clientCodec, 8);
}
template <class C>
void HTTPDownstreamTest<C>::testPriorities(
HTTPCodec& clientCodec, uint32_t numPriorities) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
uint32_t iterations = 10;
uint32_t maxPriority = numPriorities - 1;
HTTPMessage req = getGetRequest();
auto streamID = HTTPCodec::StreamID(1);
clientCodec.generateConnectionPreface(requests);
for (int pri = numPriorities - 1; pri >= 0; pri--) {
req.setPriority(pri * (8 / numPriorities));
for (uint32_t i = 0; i < iterations; i++) {
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
MockHTTPHandler* handler = new MockHTTPHandler();
InSequence handlerSequence;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(handler));
EXPECT_CALL(*handler, setTransaction(_))
.WillOnce(Invoke([handler] (HTTPTransaction* txn) {
handler->txn_ = txn; }));
EXPECT_CALL(*handler, onHeadersComplete(_));
EXPECT_CALL(*handler, onEOM())
.WillOnce(InvokeWithoutArgs([handler] {
handler->sendReplyWithBody(200, 1000);
}));
EXPECT_CALL(*handler, detachTransaction())
.WillOnce(InvokeWithoutArgs([handler] { delete handler; }));
streamID += 2;
}
}
unique_ptr<IOBuf> head = requests.move();
head->coalesce();
transport_->addReadEvent(head->data(), head->length(),
std::chrono::milliseconds(0));
transport_->startReadEvents();
eventBase_.loop();
NiceMock<MockHTTPCodecCallback> callbacks;
std::list<HTTPCodec::StreamID> streams;
EXPECT_CALL(callbacks, onMessageBegin(_, _))
.Times(iterations * numPriorities);
EXPECT_CALL(callbacks, onHeadersComplete(_, _))
.Times(iterations * numPriorities);
// body is variable and hence ignored
EXPECT_CALL(callbacks, onMessageComplete(_, _))
.Times(iterations * numPriorities)
.WillRepeatedly(Invoke([&] (HTTPCodec::StreamID stream, bool upgrade) {
streams.push_back(stream);
}));
clientCodec.setCallback(&callbacks);
parseOutput(clientCodec);
// transactions finish in priority order (higher streamIDs first)
EXPECT_EQ(streams.size(), iterations * numPriorities);
auto txn = streams.begin();
for (int band = maxPriority; band >= 0; band--) {
auto upperID = iterations * 2 * (band + 1);
auto lowerID = iterations * 2 * band;
for (uint32_t i = 0; i < iterations; i++) {
EXPECT_LE(lowerID, (uint32_t)*txn);
EXPECT_GE(upperID, (uint32_t)*txn);
++txn;
}
}
}
// Verifies that the read timeout is not running when no ingress is expected/
// required to proceed
TEST_F(SPDY3DownstreamSessionTest, spdy_timeout) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY3);
clientCodec.generateConnectionPreface(requests);
for (auto streamID = HTTPCodec::StreamID(1); streamID <= 3; streamID += 2) {
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
}
MockHTTPHandler* handler1 = new StrictMock<MockHTTPHandler>();
MockHTTPHandler* handler2 = new StrictMock<MockHTTPHandler>();
HTTPSession::setPendingWriteMax(512);
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(handler1))
.WillOnce(Return(handler2));
InSequence handlerSequence;
EXPECT_CALL(*handler1, setTransaction(_))
.WillOnce(Invoke([handler1] (HTTPTransaction* txn) {
handler1->txn_ = txn; }));
EXPECT_CALL(*handler1, onHeadersComplete(_))
.WillOnce(InvokeWithoutArgs([this] { transport_->pauseWrites(); }));
EXPECT_CALL(*handler1, onEOM())
.WillOnce(InvokeWithoutArgs([handler1] {
handler1->sendHeaders(200, 1000);
handler1->sendBody(1000);
}));
EXPECT_CALL(*handler1, onEgressPaused());
EXPECT_CALL(*handler2, setTransaction(_))
.WillOnce(Invoke([handler2] (HTTPTransaction* txn) {
handler2->txn_ = txn; }));
EXPECT_CALL(*handler2, onEgressPaused());
EXPECT_CALL(*handler2, onHeadersComplete(_));
EXPECT_CALL(*handler2, onEOM())
.WillOnce(InvokeWithoutArgs([handler2, this] {
// This transaction should start egress paused. We've received the
// EOM, so the timeout shouldn't be running delay 400ms and resume
// writes, this keeps txn1 from getting a write timeout
eventBase_.tryRunAfterDelay([this] {
transport_->resumeWrites();
}, 400);
}));
EXPECT_CALL(*handler1, onEgressResumed())
.WillOnce(InvokeWithoutArgs([handler1] { handler1->txn_->sendEOM(); }));
EXPECT_CALL(*handler2, onEgressResumed())
.WillOnce(InvokeWithoutArgs([handler2, this] {
// delay an additional 200ms. The total 600ms delay shouldn't fire
// onTimeout
eventBase_.tryRunAfterDelay([handler2] {
handler2->sendReplyWithBody(200, 400); }, 200
);
}));
EXPECT_CALL(*handler1, detachTransaction())
.WillOnce(InvokeWithoutArgs([handler1] { delete handler1; }));
EXPECT_CALL(*handler2, detachTransaction())
.WillOnce(InvokeWithoutArgs([handler2] { delete handler2; }));
transport_->addReadEvent(requests, std::chrono::milliseconds(10));
transport_->startReadEvents();
eventBase_.loop();
}
// Verifies that the read timer is running while a transaction is blocked
// on a window update
TEST_F(SPDY3DownstreamSessionTest, spdy_timeout_win) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY3);
auto streamID = HTTPCodec::StreamID(1);
clientCodec.generateConnectionPreface(requests);
clientCodec.getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
500);
clientCodec.generateSettings(requests);
clientCodec.generateHeader(requests, streamID, req, 0, false, nullptr);
clientCodec.generateEOM(requests, streamID);
StrictMock<MockHTTPHandler> handler;
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler));
InSequence handlerSequence;
EXPECT_CALL(handler, setTransaction(_))
.WillOnce(Invoke([&] (HTTPTransaction* txn) {
handler.txn_ = txn; }));
EXPECT_CALL(handler, onHeadersComplete(_));
EXPECT_CALL(handler, onEOM())
.WillOnce(InvokeWithoutArgs([&] {
handler.sendReplyWithBody(200, 1000);
}));
EXPECT_CALL(handler, onEgressPaused());
EXPECT_CALL(handler, onError(_))
.WillOnce(Invoke([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorTimeout);
ASSERT_EQ(
folly::to<std::string>("ingress timeout, streamID=", streamID),
std::string(ex.what()));
handler.terminate();
}));
EXPECT_CALL(handler, detachTransaction());
transport_->addReadEvent(requests, std::chrono::milliseconds(10));
transport_->startReadEvents();
eventBase_.loop();
}
TYPED_TEST_CASE_P(HTTPDownstreamTest);
TYPED_TEST_P(HTTPDownstreamTest, testWritesDraining) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
auto clientCodec =
makeClientCodec<typename TypeParam::Codec>(TypeParam::version);
auto badCodec =
makeServerCodec<typename TypeParam::Codec>(TypeParam::version);
auto streamID = HTTPCodec::StreamID(1);
clientCodec->generateConnectionPreface(requests);
clientCodec->generateHeader(requests, streamID, req);
clientCodec->generateEOM(requests, streamID);
streamID += 1;
badCodec->generateHeader(requests, streamID, req, 1);
MockHTTPHandler handler1;
EXPECT_CALL(this->mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler1));
EXPECT_CALL(this->mockController_, detachSession(_));
InSequence handlerSequence;
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
handler1.txn_ = txn; }));
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM());
EXPECT_CALL(handler1, onError(_))
.WillOnce(Invoke([&] (const HTTPException& ex) {
ASSERT_EQ(ex.getProxygenError(), kErrorEOF);
ASSERT_EQ("Shutdown transport: EOF", std::string(ex.what()));
}));
EXPECT_CALL(handler1, detachTransaction());
this->transport_->addReadEvent(requests, std::chrono::milliseconds(10));
this->transport_->startReadEvents();
this->eventBase_.loop();
}
TYPED_TEST_P(HTTPDownstreamTest, testBodySizeLimit) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
auto clientCodec =
makeClientCodec<typename TypeParam::Codec>(TypeParam::version);
auto streamID = HTTPCodec::StreamID(1);
clientCodec->generateConnectionPreface(requests);
clientCodec->generateHeader(requests, streamID, req);
clientCodec->generateEOM(requests, streamID);
streamID += 2;
clientCodec->generateHeader(requests, streamID, req, 0);
clientCodec->generateEOM(requests, streamID);
MockHTTPHandler handler1;
MockHTTPHandler handler2;
EXPECT_CALL(this->mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler1))
.WillOnce(Return(&handler2));
InSequence handlerSequence;
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
handler1.txn_ = txn; }));
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM());
EXPECT_CALL(handler2, setTransaction(_))
.WillOnce(Invoke([&handler2] (HTTPTransaction* txn) {
handler2.txn_ = txn; }));
EXPECT_CALL(handler2, onHeadersComplete(_));
EXPECT_CALL(handler2, onEOM())
.WillOnce(InvokeWithoutArgs([&] {
handler1.sendReplyWithBody(200, 5000);
handler2.sendReplyWithBody(200, 5000);
}));
EXPECT_CALL(handler1, detachTransaction());
EXPECT_CALL(handler2, detachTransaction());
this->transport_->addReadEvent(requests, std::chrono::milliseconds(10));
this->transport_->startReadEvents();
this->eventBase_.loop();
NiceMock<MockHTTPCodecCallback> callbacks;
std::list<HTTPCodec::StreamID> streams;
EXPECT_CALL(callbacks, onMessageBegin(1, _));
EXPECT_CALL(callbacks, onHeadersComplete(1, _));
EXPECT_CALL(callbacks, onMessageBegin(3, _));
EXPECT_CALL(callbacks, onHeadersComplete(3, _));
EXPECT_CALL(callbacks, onBody(1, _));
EXPECT_CALL(callbacks, onBody(3, _));
EXPECT_CALL(callbacks, onBody(1, _));
EXPECT_CALL(callbacks, onMessageComplete(1, _));
EXPECT_CALL(callbacks, onBody(3, _));
EXPECT_CALL(callbacks, onMessageComplete(3, _));
clientCodec->setCallback(&callbacks);
this->parseOutput(*clientCodec);
}
TYPED_TEST_P(HTTPDownstreamTest, testUniformPauseState) {
HTTPSession::setPendingWriteMax(12000);
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
req.setPriority(1);
auto clientCodec =
makeClientCodec<typename TypeParam::Codec>(TypeParam::version);
auto streamID = HTTPCodec::StreamID(1);
clientCodec->generateConnectionPreface(requests);
clientCodec->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
1000000);
clientCodec->generateSettings(requests);
clientCodec->generateWindowUpdate(requests, 0, 1000000);
clientCodec->generateHeader(requests, streamID, req);
clientCodec->generateEOM(requests, streamID);
streamID += 2;
clientCodec->generateHeader(requests, streamID, req, 0);
clientCodec->generateEOM(requests, streamID);
StrictMock<MockHTTPHandler> handler1;
StrictMock<MockHTTPHandler> handler2;
EXPECT_CALL(this->mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler1))
.WillOnce(Return(&handler2));
InSequence handlerSequence;
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
handler1.txn_ = txn; }));
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM());
EXPECT_CALL(handler2, setTransaction(_))
.WillOnce(Invoke([&handler2] (HTTPTransaction* txn) {
handler2.txn_ = txn; }));
EXPECT_CALL(handler2, onHeadersComplete(_));
EXPECT_CALL(handler2, onEOM())
.WillOnce(InvokeWithoutArgs([&] {
handler1.sendHeaders(200, 24000);
// triggers pause of all txns
this->transport_->pauseWrites();
handler1.txn_->sendBody(std::move(makeBuf(12000)));
this->eventBase_.runAfterDelay([this] {
this->transport_->resumeWrites();
}, 50);
}));
EXPECT_CALL(handler1, onEgressPaused());
EXPECT_CALL(handler2, onEgressPaused());
EXPECT_CALL(handler1, onEgressResumed())
.WillOnce(InvokeWithoutArgs([&] {
// resume does not trigger another pause,
handler1.txn_->sendBody(std::move(makeBuf(12000)));
}));
EXPECT_CALL(handler2, onEgressResumed())
.WillOnce(InvokeWithoutArgs([&] {
handler2.sendHeaders(200, 12000);
handler2.txn_->sendBody(std::move(makeBuf(12000)));
this->transport_->pauseWrites();
this->eventBase_.runAfterDelay([this] {
this->transport_->resumeWrites();
}, 50);
}));
EXPECT_CALL(handler1, onEgressPaused());
EXPECT_CALL(handler2, onEgressPaused());
EXPECT_CALL(handler1, onEgressResumed());
EXPECT_CALL(handler2, onEgressResumed())
.WillOnce(InvokeWithoutArgs([&] {
handler1.txn_->sendEOM();
handler2.txn_->sendEOM();
}));
EXPECT_CALL(handler1, detachTransaction());
EXPECT_CALL(handler2, detachTransaction());
this->transport_->addReadEvent(requests, std::chrono::milliseconds(10));
this->transport_->startReadEvents();
this->eventBase_.loop();
}
// Set max streams=1
// send two spdy requests a few ms apart.
// Block writes
// generate a complete response for txn=1 before parsing txn=3
// HTTPSession should allow the txn=3 to be served rather than refusing it
TEST_F(SPDY3DownstreamSessionTest, spdy_max_concurrent_streams) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
StrictMock<MockHTTPHandler> handler1;
StrictMock<MockHTTPHandler> handler2;
HTTPMessage req = getGetRequest();
req.setHTTPVersion(1, 0);
req.setWantsKeepalive(false);
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY3);
auto streamID = HTTPCodec::StreamID(1);
clientCodec.generateConnectionPreface(requests);
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
streamID += 2;
clientCodec.generateHeader(requests, streamID, req);
clientCodec.generateEOM(requests, streamID);
httpSession_->getCodecFilterChain()->getEgressSettings()->setSetting(
SettingsId::MAX_CONCURRENT_STREAMS, 1);
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handler1))
.WillOnce(Return(&handler2));
InSequence handlerSequence;
EXPECT_CALL(handler1, setTransaction(_))
.WillOnce(Invoke([&handler1] (HTTPTransaction* txn) {
handler1.txn_ = txn; }));
EXPECT_CALL(handler1, onHeadersComplete(_));
EXPECT_CALL(handler1, onEOM())
.WillOnce(InvokeWithoutArgs([&handler1, this] {
transport_->pauseWrites();
handler1.sendReplyWithBody(200, 100);
}));
EXPECT_CALL(handler2, setTransaction(_))
.WillOnce(Invoke([&handler2] (HTTPTransaction* txn) {
handler2.txn_ = txn; }));
EXPECT_CALL(handler2, onHeadersComplete(_));
EXPECT_CALL(handler2, onEOM())
.WillOnce(InvokeWithoutArgs([&handler2, this] {
handler2.sendReplyWithBody(200, 100);
eventBase_.runInLoop([this] {
transport_->resumeWrites();
});
}));
EXPECT_CALL(handler1, detachTransaction());
EXPECT_CALL(handler2, detachTransaction());
EXPECT_CALL(mockController_, detachSession(_));
transport_->addReadEvent(requests, std::chrono::milliseconds(10));
transport_->startReadEvents();
transport_->addReadEOF(std::chrono::milliseconds(10));
eventBase_.loop();
}
REGISTER_TYPED_TEST_CASE_P(HTTPDownstreamTest,
testWritesDraining, testBodySizeLimit,
testUniformPauseState);
typedef ::testing::Types<SPDY2CodecPair, SPDY3CodecPair, SPDY3_1CodecPair,
HTTP2CodecPair> ParallelCodecs;
INSTANTIATE_TYPED_TEST_CASE_P(ParallelCodecs,
HTTPDownstreamTest,
ParallelCodecs);
class SPDY31DownstreamTest : public HTTPDownstreamTest<SPDY3_1CodecPair> {
public:
SPDY31DownstreamTest()
: HTTPDownstreamTest<SPDY3_1CodecPair>(2 * spdy::kInitialWindow) {}
};
TEST_F(SPDY31DownstreamTest, testSessionFlowControl) {
eventBase_.loopOnce();
NiceMock<MockHTTPCodecCallback> callbacks;
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY3_1);
InSequence sequence;
EXPECT_CALL(callbacks, onSettings(_));
EXPECT_CALL(callbacks, onWindowUpdate(0, spdy::kInitialWindow));
clientCodec.setCallback(&callbacks);
parseOutput(clientCodec);
}
TEST_F(SPDY3DownstreamSessionTest, new_txn_egress_paused) {
// Send 1 request with prio=0
// Have egress pause while sending the first response
// Send a second request with prio=1
// -- the new txn should start egress paused
// Finish the body and eom both responses
// Unpause egress
// The first txn should complete first
std::array<StrictMock<MockHTTPHandler>, 2> handlers;
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY3);
auto streamID = HTTPCodec::StreamID(1);
clientCodec.generateConnectionPreface(requests);
req.setPriority(0);
clientCodec.generateHeader(requests, streamID, req, 0, nullptr);
clientCodec.generateEOM(requests, streamID);
streamID += 2;
req.setPriority(1);
clientCodec.generateHeader(requests, streamID, req, 0, nullptr);
clientCodec.generateEOM(requests, streamID);
EXPECT_CALL(mockController_, getRequestHandler(_, _))
.WillOnce(Return(&handlers[0]))
.WillOnce(Return(&handlers[1]));
HTTPSession::setPendingWriteMax(200); // lower the per session buffer limit
{
InSequence handlerSequence;
EXPECT_CALL(handlers[0], setTransaction(_))
.WillOnce(Invoke([&handlers] (HTTPTransaction* txn) {
handlers[0].txn_ = txn; }));
EXPECT_CALL(handlers[0], onHeadersComplete(_));
EXPECT_CALL(handlers[0], onEOM())
.WillOnce(Invoke([this, &handlers] {
this->transport_->pauseWrites();
handlers[0].sendHeaders(200, 1000);
handlers[0].sendBody(100); // headers + 100 bytes - over the limit
}));
EXPECT_CALL(handlers[0], onEgressPaused())
.WillOnce(InvokeWithoutArgs([] {
LOG(INFO) << "paused 1";
}));
EXPECT_CALL(handlers[1], setTransaction(_))
.WillOnce(Invoke([&handlers] (HTTPTransaction* txn) {
handlers[1].txn_ = txn; }));
EXPECT_CALL(handlers[1], onEgressPaused()); // starts paused
EXPECT_CALL(handlers[1], onHeadersComplete(_));
EXPECT_CALL(handlers[1], onEOM())
.WillOnce(InvokeWithoutArgs([&handlers, this] {
// Technically shouldn't send while handler is egress
// paused, but meh.
handlers[0].sendBody(900);
handlers[0].txn_->sendEOM();
handlers[1].sendReplyWithBody(200, 1000);
eventBase_.runInLoop([this] {
transport_->resumeWrites();
});
}));
EXPECT_CALL(handlers[0], detachTransaction());
EXPECT_CALL(handlers[1], detachTransaction());
}
transport_->addReadEvent(requests, std::chrono::milliseconds(10));
transport_->startReadEvents();
transport_->addReadEOF(std::chrono::milliseconds(10));
HTTPSession::DestructorGuard g(httpSession_);
eventBase_.loop();
NiceMock<MockHTTPCodecCallback> callbacks;
std::list<HTTPCodec::StreamID> streams;
EXPECT_CALL(callbacks, onMessageBegin(_, _))
.Times(2);
EXPECT_CALL(callbacks, onHeadersComplete(_, _))
.Times(2);
// body is variable and hence ignored;
EXPECT_CALL(callbacks, onMessageComplete(_, _))
.WillRepeatedly(Invoke([&] (HTTPCodec::StreamID stream, bool upgrade) {
streams.push_back(stream);
}));
clientCodec.setCallback(&callbacks);
parseOutput(clientCodec);
EXPECT_CALL(mockController_, detachSession(_));
}
|
Java
|
#include "farversion.hpp"
#define PLUGIN_BUILD 37
#define PLUGIN_DESC L"File names case conversion for Far Manager"
#define PLUGIN_NAME L"FileCase"
#define PLUGIN_FILENAME L"FileCase.dll"
#define PLUGIN_AUTHOR FARCOMPANYNAME
#define PLUGIN_VERSION MAKEFARVERSION(FARMANAGERVERSION_MAJOR,FARMANAGERVERSION_MINOR,FARMANAGERVERSION_REVISION,PLUGIN_BUILD,VS_RELEASE)
|
Java
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_host/pepper/device_id_fetcher.h"
#include "base/file_util.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string_number_conversions.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#if defined(OS_CHROMEOS)
#include "chromeos/cryptohome/cryptohome_library.h"
#endif
#include "components/user_prefs/pref_registry_syncable.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_ppapi_host.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/render_process_host.h"
#include "crypto/encryptor.h"
#include "crypto/random.h"
#include "crypto/sha2.h"
#if defined(ENABLE_RLZ)
#include "rlz/lib/machine_id.h"
#endif
using content::BrowserPpapiHost;
using content::BrowserThread;
using content::RenderProcessHost;
namespace chrome {
namespace {
const char kDRMIdentifierFile[] = "Pepper DRM ID.0";
const uint32_t kSaltLength = 32;
void GetMachineIDAsync(const DeviceIDFetcher::IDCallback& callback) {
std::string result;
#if defined(OS_WIN) && defined(ENABLE_RLZ)
rlz_lib::GetMachineId(&result);
#elif defined(OS_CHROMEOS)
result = chromeos::CryptohomeLibrary::Get()->GetSystemSalt();
if (result.empty()) {
// cryptohome must not be running; re-request after a delay.
const int64 kRequestSystemSaltDelayMs = 500;
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&GetMachineIDAsync, callback),
base::TimeDelta::FromMilliseconds(kRequestSystemSaltDelayMs));
return;
}
#else
// Not implemented for other platforms.
NOTREACHED();
#endif
callback.Run(result);
}
} // namespace
DeviceIDFetcher::DeviceIDFetcher(int render_process_id)
: in_progress_(false),
render_process_id_(render_process_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
}
DeviceIDFetcher::~DeviceIDFetcher() {
}
bool DeviceIDFetcher::Start(const IDCallback& callback) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
if (in_progress_)
return false;
in_progress_ = true;
callback_ = callback;
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&DeviceIDFetcher::CheckPrefsOnUIThread, this));
return true;
}
// static
void DeviceIDFetcher::RegisterProfilePrefs(
user_prefs::PrefRegistrySyncable* prefs) {
prefs->RegisterBooleanPref(prefs::kEnableDRM,
true,
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
prefs->RegisterStringPref(
prefs::kDRMSalt,
"",
user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
}
// static
base::FilePath DeviceIDFetcher::GetLegacyDeviceIDPath(
const base::FilePath& profile_path) {
return profile_path.AppendASCII(kDRMIdentifierFile);
}
void DeviceIDFetcher::CheckPrefsOnUIThread() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
Profile* profile = NULL;
RenderProcessHost* render_process_host =
RenderProcessHost::FromID(render_process_id_);
if (render_process_host && render_process_host->GetBrowserContext()) {
profile = Profile::FromBrowserContext(
render_process_host->GetBrowserContext());
}
if (!profile ||
profile->IsOffTheRecord() ||
!profile->GetPrefs()->GetBoolean(prefs::kEnableDRM)) {
RunCallbackOnIOThread(std::string());
return;
}
// Check if the salt pref is set. If it isn't, set it.
std::string salt = profile->GetPrefs()->GetString(prefs::kDRMSalt);
if (salt.empty()) {
uint8_t salt_bytes[kSaltLength];
crypto::RandBytes(salt_bytes, arraysize(salt_bytes));
// Since it will be stored in a string pref, convert it to hex.
salt = base::HexEncode(salt_bytes, arraysize(salt_bytes));
profile->GetPrefs()->SetString(prefs::kDRMSalt, salt);
}
#if defined(OS_CHROMEOS)
// Try the legacy path first for ChromeOS. We pass the new salt in as well
// in case the legacy id doesn't exist.
BrowserThread::PostBlockingPoolTask(
FROM_HERE,
base::Bind(&DeviceIDFetcher::LegacyComputeOnBlockingPool,
this,
profile->GetPath(), salt));
#else
// Get the machine ID and call ComputeOnUIThread with salt + machine_id.
GetMachineIDAsync(base::Bind(&DeviceIDFetcher::ComputeOnUIThread,
this, salt));
#endif
}
void DeviceIDFetcher::ComputeOnUIThread(const std::string& salt,
const std::string& machine_id) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (machine_id.empty()) {
LOG(ERROR) << "Empty machine id";
RunCallbackOnIOThread(std::string());
return;
}
// Build the identifier as follows:
// SHA256(machine-id||service||SHA256(machine-id||service||salt))
std::vector<uint8> salt_bytes;
if (!base::HexStringToBytes(salt, &salt_bytes))
salt_bytes.clear();
if (salt_bytes.size() != kSaltLength) {
LOG(ERROR) << "Unexpected salt bytes length: " << salt_bytes.size();
RunCallbackOnIOThread(std::string());
return;
}
char id_buf[256 / 8]; // 256-bits for SHA256
std::string input = machine_id;
input.append(kDRMIdentifierFile);
input.append(salt_bytes.begin(), salt_bytes.end());
crypto::SHA256HashString(input, &id_buf, sizeof(id_buf));
std::string id = StringToLowerASCII(
base::HexEncode(reinterpret_cast<const void*>(id_buf), sizeof(id_buf)));
input = machine_id;
input.append(kDRMIdentifierFile);
input.append(id);
crypto::SHA256HashString(input, &id_buf, sizeof(id_buf));
id = StringToLowerASCII(base::HexEncode(
reinterpret_cast<const void*>(id_buf),
sizeof(id_buf)));
RunCallbackOnIOThread(id);
}
// TODO(raymes): This is temporary code to migrate ChromeOS devices to the new
// scheme for generating device IDs. Delete this once we are sure most ChromeOS
// devices have been migrated.
void DeviceIDFetcher::LegacyComputeOnBlockingPool(
const base::FilePath& profile_path,
const std::string& salt) {
std::string id;
// First check if the legacy device ID file exists on ChromeOS. If it does, we
// should just return that.
base::FilePath id_path = GetLegacyDeviceIDPath(profile_path);
if (base::PathExists(id_path)) {
if (base::ReadFileToString(id_path, &id) && !id.empty()) {
RunCallbackOnIOThread(id);
return;
}
}
// If we didn't find an ID, get the machine ID and call the new code path to
// generate an ID.
BrowserThread::PostTask(
BrowserThread::UI, FROM_HERE,
base::Bind(&GetMachineIDAsync,
base::Bind(&DeviceIDFetcher::ComputeOnUIThread,
this, salt)));
}
void DeviceIDFetcher::RunCallbackOnIOThread(const std::string& id) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&DeviceIDFetcher::RunCallbackOnIOThread, this, id));
return;
}
in_progress_ = false;
callback_.Run(id);
}
} // namespace chrome
|
Java
|
exports.dbname = "lrdata";
exports.dbuser = "lrdata";
exports.dbpassword = "test";
exports.lfmApiKey = 'c0db7c8bfb98655ab25aa2e959fdcc68';
exports.lfmApiSecret = 'aff4890d7cb9492bc72250abbeffc3e1';
exports.tagAgeBeforeRefresh = 14; // In days
exports.tagFetchFrequency = 1000; // In milliseconds
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.