answer
stringlengths 15
1.25M
|
|---|
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
|
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.<API key>([]byte("to_handle"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
_, err = tx.<API key>([]byte("handled"))
if err != nil {
return fmt.Errorf("create bucket: %s", err)
}
_, err = tx.<API key>([]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.<API key>([]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.<API key>([]byte("to_handle"))
if err != nil {
return err
}
_, err = tx.<API key>([]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
})
}
|
@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;
-<API key>: antialiased;
-<API key>: 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: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;
-<API key>: 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";
}
.<API key>:before {
content: "\e731";
}
.icon-arrow-right3:before {
content: "\e732";
}
.<API key>:before {
content: "\e733";
}
.icon-arrow-down3:before {
content: "\e734";
}
.<API key>: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;
}
}
|
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.<API key>;
import eu.monnetproject.lang.Language;
import eu.monnetproject.ontology.Entity;
import eu.monnetproject.sim.<API key>;
import eu.monnetproject.sim.<API key>;
import eu.monnetproject.sim.string.Levenshtein;
import eu.monnetproject.sim.token.<API key>;
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 <API key> implements <API key> {
private Logger log = Logging.getLogger(this);
private final String name = this.getClass().getName();
private <API key> lef;
private LabelExtractor lex = null;
private Collection<Language> languages = Collections.emptySet();
private <API key> measure;
private boolean includePuns = false;
private Translator translator;
public <API key>(<API key> 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.<API key>(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.<API key>(srcEntity,lex);
tgtMap = SimilarityUtils.<API key>(tgtEntity,lex);
} else {
srcMap = SimilarityUtils.<API key>(srcEntity,lex);
tgtMap = SimilarityUtils.<API key>(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[] <API key> = new double[intralingualScores.size()];
for (int i = 0; i < intralingualScores.size(); i++) {
<API key>[i] = intralingualScores.get(i);
}
return Functions.max(<API key>);
}
@Override
public String getName() {
return this.name;
}
}
|
<?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-><API key>($verifyEmail);
// If the email verification code is correct, update the user information
if($result){
$user->setEmailVerified(1);
$user-><API key>([]);
$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-><API key>();
$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::<API key>($timeList);
return $stats;
}
|
{% 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 %}
|
#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-><API key>( );
SetProp( this->m_Hwnd, "dcx_cthis", (HANDLE) this );
}
/*!
* \brief blah
*
* blah
*/
DcxTab::~DcxTab( ) {
ImageList_Destroy( this->getImageList( ) );
int n = 0, nItems = <API key>( this->m_Hwnd );
while ( n < nItems ) {
this->deleteLParamInfo( n );
++n;
}
this-><API key>( );
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::parseControlStyles( TString & styles, LONG * Styles, LONG * ExStyles, BOOL * bNoTheme ) {
unsigned int i = 1, numtok = styles.numtok( );
/*!
* \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 < <API key>( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_TEXT;
tci.pszText = szReturnValue;
tci.cchTextMax = <API key>;
TabCtrl_GetItem( this->m_Hwnd, nItem, &tci );
return;
}
}
else if ( prop == "num" ) {
wnsprintf( szReturnValue, <API key>, "%d", <API key>( 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 < <API key>( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_IMAGE;
TabCtrl_GetItem( this->m_Hwnd, iTab, &tci );
wnsprintf( szReturnValue, <API key>, "%d", tci.iImage + 1 );
return;
}
}
else if ( prop == "sel" ) {
int nItem = TabCtrl_GetCurSel( this->m_Hwnd );
if ( nItem > -1 && nItem < <API key>( this->m_Hwnd ) ) {
wnsprintf( szReturnValue, <API key>, "%d", nItem + 1 );
return;
}
}
else if ( prop == "seltext" ) {
int nItem = TabCtrl_GetCurSel( this->m_Hwnd );
if ( nItem > -1 && nItem < <API key>( this->m_Hwnd ) ) {
TCITEM tci;
ZeroMemory( &tci, sizeof( TCITEM ) );
tci.mask = TCIF_TEXT;
tci.pszText = szReturnValue;
tci.cchTextMax = <API key>;
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 < <API key>( 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, <API key>, "%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, <API key>, "%d", tab +1);
return;
}
else if ( this-><API key>( 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 = <API key>(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;
}
<API key>(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 += <API key>( 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 < <API key>( 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 < <API key>( 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 < <API key>(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 < <API key>( 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 < <API key>( 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 > <API key>(this->m_Hwnd)))
return;
else if ((pos < 1) || (pos > <API key>(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[<API key>];
TCITEM tci;
ZeroMemory(&tci, sizeof(TCITEM));
tci.pszText = text;
tci.cchTextMax = <API key>;
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-><API key>( input, flags );
}
/*!
* \brief blah
*
* blah
*/
HIMAGELIST DcxTab::getImageList( ) {
return <API key>( this->m_Hwnd );
}
/*!
* \brief blah
*
* blah
*/
void DcxTab::setImageList( HIMAGELIST himl ) {
<API key>( 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 = <API key>( 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 <API key>(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 & <API key>)
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[<API key>];
TCITEM tci;
for (int i = 0; i < count; i++) {
tci.cchTextMax = <API key> -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;
}
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(), <API key>() is only temporary
DcxControl::DrawCtrlBackground(idata->hDC, this, &rect);
//<API key>(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)<API key>);
TC_ITEM tci;
tci.mask = TCIF_TEXT | TCIF_IMAGE | TCIF_STATE;
tci.pszText = label.to_chr();
tci.cchTextMax = <API key>;
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;
<API key>( 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);
//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-><API key>((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;
}
|
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.<API key>;
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 <API key> 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.<API key>(img));
base.add(ic);
}
outer.add(base);
return outer;
}
@Override
public void close() {
// do nothing
}
public static void main(String[] args) throws IOException {
new <API key>(new <API key>(), 1024, 768, Utils.BACKGROUND_IMAGE);
}
}
|
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();
}
|
# -*- 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
<API key> #{@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 <API key>
assert_equal [], @admin.get_hosts
args = { :ip => @test_host, :port => @mogstored_http_port }
@admin.create_host("me", args)
<API key> { @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 <API key>
domain = "rbmogtest#{Time.now.strftime('%Y%m%d%H%M%S')}.#{uuid}"
@admin.create_domain(domain)
<API key> { @admin.get_domains.include?(domain) and break }
<API key> do
@admin.create_class(domain, "klassy", 1)
end
assert_raises(MogileFS::Backend::ClassExistsError) do
@admin.create_class(domain, "klassy", 1)
end
<API key> do
@admin.update_class(domain, "klassy",
:mindevcount => 1, :replpolicy => "MultipleHosts(1)")
end
tmp = nil
<API key> 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"]
<API key> { @admin.update_class(domain, "klassy", 2) }
ensure
@admin.delete_class(domain, "klassy") rescue nil
end
def <API key>
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")
<API key> { @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)
<API key> { @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)
<API key> { @admin.get_domains.include?(domain) and break }
@domain = domain
end
def <API key>
<API key>
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("
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
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('setlist', '<API key>'),
]
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,),
),
]
|
{-# 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 = <API key> s
attrmask = cWOverrideRedirect
<API key> $
\attributes -> do
<API key> attributes True
createWindow d rw x y w h 0 (<API key> 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 = <API key> 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)
|
// 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
// <API key>
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.<API key>,
'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 '<API key>':
this.redirectKey = restOptions.<API key>;
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.<API key>();
}).then(() => {
return this.<API key>();
}).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 <API key> is set.
// Returns a promise.
RestQuery.prototype.<API key> = function() {
if (!this.redirectKey) {
return Promise.resolve();
}
// We need to change the class name based on the schema
return this.config.database.<API key>(
this.className, this.redirectKey).then((newClassName) => {
this.className = newClassName;
this.redirectClassName = newClassName;
});
};
// Validates this operation against the <API key> config.
RestQuery.prototype.<API key> = function() {
let sysClass = ['_User', '_Installation', '_Role', '_Session', '_Product'];
if (this.config.<API key> === 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;
|
<?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() ?>
|
<h1 id="title_header"></h1>
<div id="calendar" class="{{ css_classes }}">
</div>
|
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 = .r
private val ShortSquashedOption = .r
private val LongOption = .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)
}
}
|
#include <sys/cdefs.h>
__FBSDID("$FreeBSD$");
#ifndef <API key>
#define <API key>
/* IANA assigned port number for SCTP over UDP encapsulation */
#define <API key> 9899
/* Number of packets to get before sack sent by default */
#define <API key> 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 <API key> (65535 - 2048)
/* Number of addresses where we just skip the counting */
#define SCTP_COUNT_LIMIT 40
#define <API key> (((100 * hz) + 999) / 1000)
#define <API key> (((100 * hz) + 999) / 1000)
/* Number of ticks to delay before running
* iterator on an address change.
*/
#define <API key> 2
#define SCTP_VERSION_STRING "KAME-BSD 1.1"
/* #define <API key> 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 <API key> 4
/* constants for rto calc */
#define <API key> 0
#define <API key> 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 <API key> 1
#define <API key> 2
#define <API key> 3
#define <API key> 4
#define <API key> 5
#define <API key> 6
#define <API key> 7
#define <API key> 8
#define <API key> 9
#define <API key> 10
#define <API key> 11
#define <API key> 12
#define <API key> 13
#define <API key> 14
#define <API key> 15
#define <API key> 16
#define <API key> 17
#define <API key> 18
#define <API key> 19
#define SCTP_FR_T3_TIMEOUT 20
#define <API key> 21
#define SCTP_MAP_SLIDE_FROM 22
#define <API key> 23
#define <API key> 24
#define SCTP_MAP_SLIDE_NONE 25
#define <API key> 26
#define SCTP_FR_T3_MARKED 27
#define SCTP_FR_T3_STOPPED 28
#define SCTP_FR_MARKED 30
#define <API key> 31
#define <API key> 32
#define <API key> 33
#define <API key> 34
#define <API key> 35
#define <API key> 36
#define <API key> 37
#define <API key> 38
#define <API key> 39
#define <API key> 40
#define <API key> 41
#define SCTP_LOG_NEW_SACK 42
#define SCTP_LOG_TSN_ACKED 43
#define <API key> 44
#define SCTP_LOG_LOCK_TCB 45
#define SCTP_LOG_LOCK_INP 46
#define SCTP_LOG_LOCK_SOCK 47
#define <API key> 48
#define <API key> 49
#define <API key> 50
#define <API key> 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 <API key> 57
#define SCTP_FR_CWND_REPORT 58
#define <API key> 59
#define <API key> 60
#define <API key> 61
#define <API key> 62
#define <API key> 63
#define <API key> 64
#define <API key> 65
#define <API key> 66
#define <API key> 67
#define <API key> 68
#define <API key> 69
#define <API key> 70
#define SCTP_LOG_FREE_SENT 71
#define SCTP_NAGLE_APPLIED 72
#define SCTP_NAGLE_SKIPPED 73
#define <API key> 74
#define <API key> 75
#define <API key> 76
#define <API key> 77
#define <API key> 78
#define SCTP_AT_END_OF_SACK 79
#define SCTP_REASON_FOR_SC 80
#define <API key> 81
#define <API key> 82
#define <API key> 83
#define SCTP_SORECV_BLOCKSA 84
#define SCTP_SORECV_BLOCKSB 85
#define SCTP_SORECV_DONE 86
#define <API key> 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 <API key> 105
#define <API key> 106
#define <API key> 107
#define SCTP_FLIGHT_LOG_UP 108
#define <API key> 109
#define <API key> 110
#define <API key> 111
#define <API key> 112
#define <API key> 113
#define <API key> 114
#define <API key> 115
#define <API key> 116
#define <API key> 117
#define <API key> 118
#define SCTP_MAP_TSN_ENTERS 119
#define <API key> 120
#define SCTP_THRESHOLD_INCR 121
#define <API key> 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 <API key> 0
#define SCTP_LOG_EVENT_CWND 1
#define <API key> 2
#define SCTP_LOG_EVENT_STRM 3
#define SCTP_LOG_EVENT_FR 4
#define SCTP_LOG_EVENT_MAP 5
#define <API key> 6
#define SCTP_LOG_EVENT_RWND 7
#define <API key> 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 <API key> 13
#define SCTP_LOG_EVENT_WAKE 14
#define SCTP_LOG_MISC_EVENT 15
#define <API key> 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 <API key> 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 <API key> 0
/*
* Theshold for rwnd updates, we have to read (sb_hiwat >>
* <API key>) 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 <API key> 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 <API key> 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 <API key>
#define SCTP_SIGNATURE_SIZE SCTP_<API key>
#define <API key> 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 <API key> 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 <API key> 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 <API key> 1
/* default max I can burst out after a fast retransmit, 0 disables it */
#define SCTP_DEF_MAX_BURST 4
#define <API key> 4
#define <API key> 4
/* RTO calculation flag to say if it
* is safe to determine local lan or not.
*/
#define <API key> 0
#define SCTP_RTT_FROM_DATA 1
/* IP hdr (20/40) + 12+2+2 (enet) + sctp common 12 */
#define <API key> 68
/* Packet transmit states in the sent field */
#define <API key> 0
#define SCTP_DATAGRAM_SENT 1
#define <API key> 2 /* not used (in code, but may
* hit this value) */
#define <API key> 3 /* not used (in code, but may
* hit this value) */
#define <API key> 4
#define SCTP_DATAGRAM_ACKED 10010
#define <API key> 20010
#define <API key> 30010
#define <API key> 40010
/* chunk output send from locations */
#define <API key> 0
#define SCTP_OUTPUT_FROM_T3 1
#define <API key> 2
#define <API key> 3
#define <API key> 4
#define <API key> 5
#define <API key> 6
#define <API key> 7
#define <API key> 8
#define <API key> 9
#define <API key> 10
#define <API key> 11
#define <API key> 12
#define <API key> 13
#define <API key> 14
#define <API key> 15
#define <API key> 16
#define <API key> 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 */
#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 <API key> 0x0009
#define <API key> 0x000b
#define <API key> 0x000c
/* <API key> */
#define <API key> 0x000d
#define <API key> 0x000e
#define <API key> 0x000f
#define <API key> 0x0010
#define <API key> 0x0011
#define <API key> 0x0012
#define <API key> 2
#define <API key> 0x1000
#define SCTP_ECN_CAPABLE 0x8000
/* <API key> */
#define SCTP_RANDOM 0x8002
#define SCTP_CHUNK_LIST 0x8003
#define SCTP_HMAC_LIST 0x8004
/*
* <API key> 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 <API key> 0x8008
#define <API key> 0xc000
/* <API key> */
#define SCTP_ADD_IP_ADDRESS 0xc001
#define SCTP_DEL_IP_ADDRESS 0xc002
#define <API key> 0xc003
#define SCTP_SET_PRIM_ADDR 0xc004
#define SCTP_SUCCESS_REPORT 0xc005
#define SCTP_ULP_ADAPTATION 0xc006
/* behave-nat-draft */
#define <API key> 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 <API key> 0x20
#define SCTP_NO_HEARTBEAT 0x40
/* mask to get sticky */
#define <API key> 0x0c
/*
* SCTP states for internal state machine XXX (should match "user" values)
*/
#define SCTP_STATE_EMPTY 0x0000
#define SCTP_STATE_INUSE 0x0001
#define <API key> 0x0002
#define <API key> 0x0004
#define SCTP_STATE_OPEN 0x0008
#define <API key> 0x0010
#define <API key> 0x0020
#define <API key> 0x0040
#define <API key> 0x0080
#define <API key> 0x0100
#define <API key> 0x0200
#define <API key> 0x0400
#define <API key> 0x0800
#define <API key> 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 <API key> 0x008
#define <API key> 0x010
#define <API key> 0x080
#define <API key> 0x200
#define <API key> 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 <API key> 5
/* How long a cookie lives in milli-seconds */
#define <API key> 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 <API key> 16
/* how much we grow the mapping array each call */
#define <API key> 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 <API key> 3
#define SCTP_TIMER_PMTU 4
#define <API key> 5
#define <API key> 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 <API key> 0
#define <API key> 1
#define <API key> 2
#define <API key> 3
#define <API key> 4
#define <API key> 5
#define <API key> 6
#define <API key> 7
#define <API key> 8
#define <API key> 9
#define <API key> 10
#define <API key> 11
#define <API key> 12
#define <API key> 13
#define <API key> 14
#define <API key> 15
#define <API key> 16
#define <API key> 17
#define <API key> 18
#define <API key> 19
#define <API key> 20
/* add new timers here - and increment LAST */
#define <API key> 21
#define <API key>(t) (((t) > <API key>) && \
((t) < <API key>))
/* 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 <API key> 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 <API key> 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 <API key> 250
/* The floor this value is allowed to fall to when starting a timer. */
#define <API key> 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 <API key> 30000
/* Max time I will wait for Shutdown to complete */
#define <API key> 180
/*
* This is how long a secret lives, NOT how long a cookie lives how many
* ticks the current secret will live.
*/
#define <API key> 3600
#define <API key> (60000) /* 60 sec in ms */
#define <API key> (1000) /* 1 sec is ms */
#define SCTP_RTO_INITIAL (3000) /* 3 sec in ms */
#define <API key> 20/* number of ms to retry kill of inpcb */
#define <API key> 10 /* number of ms to retry kill of inpcb */
#define SCTP_DEF_MAX_INIT 8
#define SCTP_DEF_MAX_SEND 10
#define <API key> 5
#define <API key> <API key>
#define <API key> 600 /* 10 min between raise attempts */
/* How many streams I request initally by default */
#define <API key> 10
#define <API key> 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 <API key> 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 <API key> 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 <API key> 65535
#define <API key> 512
#define <API key> 512
/* small chunk store for looking at chunk_list in auth */
#define <API key> 260
#define <API key> 2 /* how many secrets I keep */
#define <API key> 8 /* or 8 * 4 = 32 octets */
#define SCTP_SECRET_SIZE 32 /* number of octets in a 256 bits */
/*
* SCTP upper layer notifications
*/
#define <API key> 1
#define <API key> 2
#define <API key> 3
#define <API key> 4
#define <API key> 5
#define <API key> 6
#define <API key> 7
#define <API key> 8
#define <API key> 9
#define <API key> 10
#define <API key> 11
#define <API key> 12
#define <API key> 13
#define <API key> 14
#define <API key> 15
#define <API key> 16
#define <API key> 17
#define <API key> 18
#define <API key> 19
#define <API key> 20
#define <API key> 21
#define <API key> 22
#define <API key> 23
#define <API key> 24
#define <API key> 25
#define <API key> 26
#define <API key> 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 <API key> 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 <API key> 0x10000000
#define SCTP_FROM_SCTP_PCB 0x20000000
#define <API key> 0x30000000
#define <API key> 0x40000000
#define <API key> 0x50000000
#define SCTP_FROM_SCTPUTIL 0x60000000
#define <API key> 0x70000000
#define <API key> 0x80000000
#define <API key> 0x90000000
#define <API key> 0xa0000000
#define <API key> 0xb0000000
#define <API key> 0xc0000000
#define <API key> 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 <API key> 1
#define SCTP_PCBFREE_FORCE 2
/* From codes for adding addresses */
#define <API key> 8
#define <API key> 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 <API key> 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 <API key>
#define <API key> 10
#endif
/* clock variance is 1 ms */
#define <API key> 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 <API key> 0
#define <API key> 1
#define <API key> 2
/* second argument */
#define <API key> 1
#define <API key> 0
#ifndef IPPROTO_SCTP
#define IPPROTO_SCTP 132 /* the Official IANA number :-) */
#endif /* !IPPROTO_SCTP */
#define <API key> 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 <API key>(arry, gap) (arry[(gap >> 3)] |= (0x01 << ((gap & 0x07))))
#define <API key>(arry, gap) (arry[(gap >> 3)] &= ((~(0x01 << ((gap & 0x07)))) & 0xff))
#define <API key>(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 <API key> 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 <API key> 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 <API key> 0x00000001
#define <API key> 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 <API key> 10
#define <API key> 1000
/*-
* defines for socket lock states.
* Used by __APPLE__ and <API key>
*/
#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 <API key> 0
#define <API key>(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 <API key>(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 <API key>(a) \
((((uint8_t *)&(a)->s_addr)[0] == 169) && \
(((uint8_t *)&(a)->s_addr)[1] == 254))
#if defined(_KERNEL)
#define <API key>(x) (getmicrouptime(x))
#define <API key>(x) (microuptime(x))
#endif
#if defined(_KERNEL) || defined(__Userspace__)
#define sctp_sowwakeup(inp, so) \
do { \
if (inp->sctp_flags & <API key>) { \
inp->sctp_flags |= <API key>; \
} else { \
sowwakeup(so); \
} \
} while (0)
#define <API key>(inp, so) \
do { \
if (inp->sctp_flags & <API key>) { \
SOCKBUF_UNLOCK(&((so)->so_snd)); \
inp->sctp_flags |= <API key>; \
} else { \
sowwakeup_locked(so); \
} \
} while (0)
#define sctp_sorwakeup(inp, so) \
do { \
if (inp->sctp_flags & <API key>) { \
inp->sctp_flags |= <API key>; \
} else { \
sorwakeup(so); \
} \
} while (0)
#define <API key>(inp, so) \
do { \
if (inp->sctp_flags & <API key>) { \
inp->sctp_flags |= <API key>; \
SOCKBUF_UNLOCK(&((so)->so_rcv)); \
} else { \
sorwakeup_locked(so); \
} \
} while (0)
#endif /* _KERNEL || __Userspace__ */
#endif
|
{% load <API key> 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.<API key> %}data-aos-duration="{{ widget.<API key> }}"{% 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.<API key> == 0 %}false{% elif widget.<API key> == 1 %}true{% endif %}">
<div class="jumbotron {{ widget.<API key> }}">
{% 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" %}
|
<?php
/** 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
|
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;
}
}
}
|
#!/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.<API key>(2, 2)
def <API key>(self):
self.<API key>(2, 1000)
def <API key>(self):
self.<API key>(100, 1000)
def <API key>(self):
self.<API key>(500, 100)
# # Stress it should handle
def <API key>(self):
self.<API key>(1, 1)
def __ensure_list(self,arg):
if type(arg)!=list:
return [arg]
else:
return arg
def <API key>(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()
|
# -*- 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):
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 <API key>(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,
<API key>=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,
<API key>=True).\
filter(institution=institution,
charge_type=charge_type)
n_tot = qs.count()
n_fem = qs.filter(<API key>='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
|
#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_
|
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* 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 <API key> = 3;
static final int <API key> = 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] = <API key>;
m_buttons[ButtonType.kTrigger.value] = <API key>;
m_buttons[ButtonType.kTop.value] = kDefaultTopButton;
HAL.report(tResourceType.<API key>, 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);
}
}
|
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.<API key>(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
}
|
<?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';
}
}
|
// modification, are permitted provided that the following conditions are
// met:
// 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
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef <API key>
#define <API key>
// Omaha is the code name of Google Update, which is not used in
// OSS version of Mozc.
#if !defined(<API key>)
#error OmahaUtil must be used with Google Japanese Input, not OSS Mozc
#endif // !<API key>
#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:
<API key>(OmahaUtil);
};
} // namespace win32
} // namespace mozc
#endif // <API key>
|
<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>
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<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>
|
#include "stdfx.h"
//#include "tfxparam.h"
#include "trop.h"
class PremultiplyFx : public TStandardRasterFx {
<API key>(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());
}
<API key>(PremultiplyFx, "premultiplyFx");
|
/* $NetBSD: proc.h,v 1.8 1996/11/25 22:09:11 gwr Exp $ */
/*
* 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 */
|
#include "ash/components/phonehub/<API key>.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/<API key>.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 <API key>::RegisterPrefs(PrefRegistrySimple* registry) {
registry->RegisterBooleanPref(prefs::<API key>, false);
}
<API key>::<API key>(
PrefService* pref_service,
multidevice_setup::<API key>* <API key>,
<API key>* <API key>)
: pref_service_(pref_service),
<API key>(<API key>),
<API key>(<API key>) {
<API key>->AddObserver(this);
<API key>->AddObserver(this);
}
<API key>::~<API key>() {
<API key>->RemoveObserver(this);
<API key>->RemoveObserver(this);
}
void <API key>::<API key>() {
switch (<API key>->GetAccessStatus()) {
case <API key>::AccessStatus::kAccessGranted:
if (<API key>()) {
PA_LOG(INFO) << "Enabling <API key> for the first time now "
<< "that access has been granted by the phone.";
<API key>-><API key>(
Feature::<API key>, /*enabled=*/true,
/*auth_token=*/absl::nullopt, base::DoNothing());
}
break;
case <API key>::AccessStatus::<API key>:
FALLTHROUGH;
case <API key>::AccessStatus::kProhibited:
// Disable <API key> if notification access has been revoked
// by the phone.
PA_LOG(INFO) << "Disabling <API key> feature.";
<API key>-><API key>(
Feature::<API key>, /*enabled=*/false,
/*auth_token=*/absl::nullopt, base::DoNothing());
break;
}
}
void <API key>::OnHostStatusChanged(
const multidevice_setup::<API key>::<API key>&
<API key>) {
<API key>();
}
void <API key>::<API key>(
const multidevice_setup::<API key>::FeatureStatesMap&
feature_state_map) {
<API key>();
}
bool <API key>::
<API key>() 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::<API key>(
Feature::<API key>, pref_service_) &&
<API key>->GetFeatureState(Feature::kPhoneHub) ==
FeatureState::kEnabledByUser;
}
void <API key>::<API key>() {
bool <API key> =
pref_service_->GetBoolean(prefs::<API key>);
const HostStatus host_status =
<API key>->GetHostStatus().first;
const FeatureState feature_state =
<API key>->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 <API key> or kProhibitedByPolicy.
if (<API key> && host_status == HostStatus::kHostVerified &&
feature_state == FeatureState::kDisabledByUser) {
<API key>-><API key>(
Feature::kPhoneHub, /*enabled=*/true, /*auth_token=*/absl::nullopt,
base::DoNothing());
util::<API key>(util::OptInEntryPoint::kSetupFlow);
}
<API key>();
}
void <API key>::<API key>() {
// 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 =
<API key>->GetHostStatus().first;
if (host_status ==
HostStatus::<API key>) {
pref_service_->SetBoolean(prefs::<API key>, 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 <API key> =
pref_service_->GetBoolean(prefs::<API key>);
const FeatureState feature_state =
<API key>->GetFeatureState(Feature::kPhoneHub);
if (<API key> && host_status == HostStatus::kHostVerified &&
feature_state == FeatureState::kEnabledByUser) {
pref_service_->SetBoolean(prefs::<API key>, false);
return;
}
}
} // namespace phonehub
} // namespace chromeos
|
/* 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('<API key>');
$.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('<API key>');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
}
});
|
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[:<API key>])
@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, :<API key>)
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
|
/*
* 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;
}
|
<?php namespace xp\runtime;
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;
}
}
|
#!/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': {}}
|
<?php
namespace yiicms\components\core;
# Websun template parser, version 0.1.80
class websun
{
public $vars;
public $templates_root_dir;
public $<API key>;
public $TIMES;
public $no_global_vars;
private $profiling;
private $predecessor;
function __construct($options)
{
$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 {
// $this->templates_root_dir = getcwd();
foreach (debug_backtrace() as $trace) {
if (preg_match('/^<API key>/', $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-><API key> = $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);
$template = str_replace('\\\\', "\x01", $template);
$template = str_replace('\*', "\x02", $template);
// (?P<args>\([^*]*\))?
// array($this, 'addvars'),
// $template
$template = $this-><API key>($template);
$template = $this->find_and_parse_if($template);
$template = <API key>(
'/
{\*
(.*?)
\*}
/x',
[$this, '<API key>'],
$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;
}
// function addvars($matches) {
// // if ($this->profiling)
// // // $start = microtime(1);
// // $module_name = 'module_'.$matches[1];
// //
// // $args = (isset($matches['args']))
// // // : array();
// // $this->vars = array_merge(
// // // $this->vars,
// // // <API key>($module_name, $args)
// // 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) : '';
}
elseif (mb_strpos($string, '|') !== false) {
$f = __FUNCTION__;
foreach (explode('|', $string) as $str) {
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;
}
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;
}
}
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;
}
}
$out = (!$return_mode)
? $value
: (is_array($value) ? count($value) : false);
}
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function <API key>($template)
{
if ($this->profiling) {
$start = microtime(1);
}
$out = <API key>(
'/
{%\* ([^*]*) \*}
(.*?)
{\* \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 . '"',
'"' . $i . '"',
'"' . $n . '"',
$array_name . $dot . $key . '.'
],
$matches[2]
);
$i++;
$n++;
}
$parsed = $this-><API key>($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 = <API key>(
'/
{ (\?\!?) \*([^*]*)\* }
(.*?)
{\*\2\* \1}
/sx',
[$this, 'parse_if'],
$template
);
if ($this->profiling) {
$this->write_time(__FUNCTION__, $start, microtime(1));
}
return $out;
}
function parse_if($matches)
{
if ($this->profiling) {
$start = microtime(1);
}
$final_check = false;
$separator = (strpos($matches[2], '&'))
? '&' // "AND"
: '|';
$parts = explode($separator, $matches[2]);
$parts = array_map('trim', $parts);
$checks = [];
foreach ($parts as $p) {
$checks[] = $this-><API key>($p);
}
if ($separator == '|')
{
$final_check = in_array(true, $checks);
} else
{
$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 <API key>($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 <API key>($matches)
{
if ($this->profiling) {
$start = microtime(1);
}
$work = $matches[1];
$work = trim($work);
if (mb_substr($work, 0, 1) == '@') {
$p = '/
^
([^(|]++)
(?: \( ([^)]*+) \) \s* )?
(?: \| \s* (.*+) )?
$
/x';
if (preg_match($p, mb_substr($work, 1), $m)) {
$function_name = $this->get_var_or_string($m[1]);
// else
global $<API key>;
$list = $<API key>;
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 = <API key>($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) == '+') {
$html = '';
$parts = preg_split(
'/(?<=[\*\s])\|(?=[\*\s])/',
mb_substr($work, 1)
);
$parts = array_map('trim', $parts);
if (!isset($parts[1])) {
$html = $this->call_template($parts[0], $this->vars);
} else {
$varname_string = mb_substr($parts[0], 1, -1);
$indicator = mb_substr($varname_string, 0, 1);
if ($indicator == '?') {
if ($subvars = $this->var_value(mb_substr($varname_string, 1))) // 0.1.27 $html = $this-><API key>($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-><API key>($tplname, $row);
$html .= $this->call_template($parts[1], $row);
}
}
} else {
$subvars = $this->var_value($varname_string);
// 0.1.27 $html = $this-><API key>($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);
}
$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-><API key> = $this-><API key>;
} else {
$path = $this->get_var_or_string($template_notation);
$subobject-><API key> = 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)
{
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) == ':')
{
$dir = '';
} else {
$dir = $this-><API key>;
}
$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 <API key>(
$data,
$template_path,
$templates_root_dir = false,
$no_global_vars = false
)
{
$W = new websun([
'data' => $data,
'templates_root' => $templates_root_dir,
'no_global_vars' => $no_global_vars
]);
$tpl = $W->get_template($template_path);
$W-><API key> = pathinfo($W->template_real_path($template_path), PATHINFO_DIRNAME) . '/';
$string = $W->parse_template($tpl);
return $string;
}
function <API key>(
$data,
$template_code,
$templates_root_dir = false,
$no_global_vars = false
)
{
$W = new websun([
'data' => $data,
'templates_root' => $templates_root_dir,
'no_global_vars' => $no_global_vars
]);
$string = $W->parse_template($template_code);
return $string;
}
?>
|
/* 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;
}
|
'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.<API key> = function(){
return ++this.connCount;
};
proto.<API key> = 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
};
};
|
// <API key>: 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;
}
|
#ifndef <API key>
#define <API key>
#include "itkObject.h"
#include "itkObjectFactory.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "itkImage.h"
#include "itkMacro.h"
#include "ReadWriteImage.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "itkFixedArray.h"
#include "<API key>.h"
#include "<API key>.h"
//#include "<API key>.h"
#include "<API key>.h"
#include "itkWarpImageFilter.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "itkPointSet.h"
#include "itkVector.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
#include "<API key>.h"
namespace itk {
template<unsigned int TDimension = 3, class TReal = float>
class ITK_EXPORT <API key>
: public Object
{
public:
/** Standard class typedefs. */
typedef <API key> 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( <API key>, Object );
itkStaticConstMacro( Dimension, unsigned int, TDimension );
itkStaticConstMacro( ImageDimension, unsigned int, TDimension );
typedef TReal RealType;
typedef Image<RealType,
<API key>( Dimension )> ImageType;
typedef typename ImageType::Pointer ImagePointer;
typedef itk::<API key>< double, ImageDimension, ImageDimension > TransformType;
/** Point Types for landmarks and labeled point-sets */
typedef itk::ANTSLabeledPointSet<Dimension> LabeledPointSetType;
typedef typename LabeledPointSetType::Pointer <API key>;
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::<API key><double, TDimension, TDimension> AffineTransformType;
typedef typename AffineTransformType::Pointer <API key>;
typedef OptAffine<<API key>, ImagePointer> OptAffineType;
typedef itk::Vector<float,ImageDimension> VectorType;
typedef itk::Image<VectorType,ImageDimension> <API key>;
typedef typename <API key>::Pointer <API key>;
typedef itk::Image<VectorType,ImageDimension+1> <API key>;
typedef typename <API key>::Pointer <API key>;
typedef itk::<API key><<API key>,float> <API key>;
typedef itk::<API key><<API key>,float> <API key>;
typedef typename <API key>::IndexType IndexType;
typedef ants::CommandLineParser ParserType;
typedef typename ParserType::OptionType OptionType;
typedef <API key><<API key>> BSplineFilterType;
typedef FixedArray<RealType,
<API key>( ImageDimension )> ArrayType;
/** Typedefs for similarity metrics */
typedef <API key> <<API key>( Dimension ), float> <API key>;
typedef typename <API key>::Pointer <API key>;
typedef std::vector<<API key>> <API key>;
/** <API key> type. */
typedef <API key><<API key>> <API key>;
typedef typename <API key>::TimeStepType TimeStepType;
typedef typename
<API key>::Pointer <API key>;
typedef <API key><ImageType,ImageType,
<API key>> MetricBaseType;
typedef typename MetricBaseType::Pointer <API key>;
/* Jacobian and other calculations */
typedef itk::<API key><<API key>> <API key>;
/** Set functions */
void SetAffineTransform(<API key> A) {this->m_AffineTransform=A;}
void SetDeformationField(<API key> A) {this->m_DeformationField=A;}
void <API key>(<API key> A) {this-><API key>=A;}
void SetMaskImage( ImagePointer m) { this->m_MaskImage=m; }
void <API key>(<API key> A) {this-><API key>=A;}
<API key> <API key>() {return this-><API key>;}
/** Get functions */
<API key> GetAffineTransform() {return this->m_AffineTransform;}
<API key> GetDeformationField( ) {return this->m_DeformationField;}
<API key> <API key>() {return this-><API key>;}
/** Initialize all parameters */
void SetNumberOfLevels(unsigned int i) {this->m_NumberOfLevels=i;}
void SetParser( typename ParserType::Pointer P ) {this->m_Parser=P;}
/** Basic operations */
<API key> <API key>( <API key> input );
std::string <API key>(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 <API key>(<API key> field, bool <API key> )
{
typename ParserType::OptionType::Pointer <API key>
= this->m_Parser->GetOption( "regularization" );
if ( ( <API key>->GetValue() ).find( "DMFFD" )
!= std::string::npos )
{
if( ( !<API key> && this-><API key> == 0.0 ) ||
( <API key> && this-><API key> == 0.0 ) )
{
return;
}
ArrayType meshSize;
unsigned int splineOrder = this->m_BSplineFieldOrder;
float <API key> = static_cast<float>( splineOrder + 1 ) / 12.0;
unsigned int numberOfLevels = 1;
if( <API key> )
{
if( this-><API key> < 0.0 )
{
meshSize = this-><API key>;
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-><API key> /
<API key> );
for( unsigned int d = 0; d < ImageDimension; d++ )
{
meshSize[d] = static_cast<unsigned int>(
field-><API key>().GetSize()[d] /
spanLength + 0.5 );
}
}
this-><API key>( field, meshSize, splineOrder,
numberOfLevels );
}
else
{
if( this-><API key> < 0.0 )
{
meshSize = this-><API key>;
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-><API key> /
<API key> );
for( unsigned int d = 0; d < ImageDimension; d++ )
{
meshSize[d] = static_cast<unsigned int>(
field-><API key>().GetSize()[d] /
spanLength + 0.5 );
}
}
RealType maxMagnitude = 0.0;
ImageRegionIterator<<API key>> It( field,
field-><API key>() );
for( It.GoToBegin(); !It.IsAtEnd(); ++It )
{
RealType magnitude = ( It.Get() ).GetNorm();
if( magnitude > maxMagnitude )
{
maxMagnitude = magnitude;
}
}
this-><API key>( 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 (<API key>) sig=this-><API key>;
else sig=this-><API key>;
this-><API key>(field,sig);
}
}
void <API key>(<API key> field = NULL,
float sig=0.0, bool useparamimage=false, unsigned int lodim=ImageDimension);
// float = smoothingparam, int = maxdim to smooth
void SmoothVelocityGauss(<API key> field,float,unsigned int);
void <API key>(<API key> field, ArrayType meshSize,
unsigned int splineorder, unsigned int numberoflevels );
<API key> <API key>(<API key> fixedwarp, <API key> movingwarp, PointSetPointer fpoints=NULL, PointSetPointer wpoints=NULL,<API key> updateFieldInv=NULL, bool updateenergy=true);
<API key> ComputeUpdateField(<API key> fixedwarp, <API key> movingwarp, PointSetPointer fpoints=NULL, PointSetPointer wpoints=NULL,<API key> updateFieldInv=NULL, bool updateenergy=true);
<API key> 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-><API key>-><API key>().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 <API key><<API key>, <API key>> ExpanderType;
typename ExpanderType::Pointer m_FieldExpander = ExpanderType::New();
m_FieldExpander->SetInput(this-><API key>);
m_FieldExpander->SetExpandFactors( expandFactors );
m_FieldExpander->SetEdgePaddingValue( pad );
m_FieldExpander-><API key>();
return m_FieldExpander->GetOutput();
}
<API key> ExpandField(<API key> 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-><API key>().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 <API key><<API key>, <API key>> ExpanderType;
typename ExpanderType::Pointer m_FieldExpander = ExpanderType::New();
m_FieldExpander->SetInput(field);
m_FieldExpander->SetExpandFactors( expandFactors );
// use default
m_FieldExpander->SetEdgePaddingValue( pad );
m_FieldExpander-><API key>();
typename <API key>::Pointer fieldout=m_FieldExpander->GetOutput();
fieldout->SetSpacing(targetSpacing);
fieldout->SetOrigin(field->GetOrigin());
if (this->m_Debug) std::cout << " Field size " << fieldout-><API key>().GetSize() << std::endl;
//this->m_Debug=false;
return fieldout;
}
ImagePointer GetVectorComponent(<API key> field, unsigned int index)
{
// Initialize the Moving to the displacement field
typedef <API key> FieldType;
typename ImageType::Pointer sfield=ImageType::New();
sfield->SetSpacing( field->GetSpacing() );
sfield->SetOrigin( field->GetOrigin() );
sfield->SetDirection( field->GetDirection() );
sfield-><API key>(field-><API key>() );
sfield->SetRequestedRegion(field->GetRequestedRegion() );
sfield->SetBufferedRegion( field->GetBufferedRegion() );
sfield->Allocate();
typedef itk::<API key><FieldType> Iterator;
Iterator vfIter( field, field-><API key>() );
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, <API key> aff = NULL);
<API key> SubsampleField( <API key> 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 <API key>::Pointer sfield=<API key>::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-><API key>(comp-><API key>() );
sfield->SetRequestedRegion(comp->GetRequestedRegion() );
sfield->SetBufferedRegion( comp->GetBufferedRegion() );
sfield->Allocate();
}
typedef itk::<API key><<API key>> Iterator;
typedef typename <API key>::PixelType VectorType;
VectorType v1;
VectorType zero;
zero.Fill(0.0);
Iterator vfIter( sfield, sfield-><API key>() );
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, <API key> aff , <API key> totalField, bool doinverse , <API key> fixedaff )
{
if (!movingpoints) { std::cout << " NULL POINTS " << std::endl; return NULL; }
<API key> affinverse=NULL;
if (aff)
{
affinverse=AffineTransformType::New();
aff->GetInverse(affinverse);
}
<API key> fixedaffinverse=NULL;
if (fixedaff)
{
fixedaffinverse=AffineTransformType::New();
fixedaff->GetInverse(fixedaffinverse);
}
typedef itk::<API key><ImageType,ImageType, <API key>, TransformType> WarperType;
typename WarperType::Pointer warper = WarperType::New();
warper->SetInput(movingImage);
warper->SetEdgePaddingValue( 0);
warper->SetSmoothScale(1);
if (!doinverse)
{
if (totalField) warper-><API key>(totalField);
if (fixedaff) warper-><API key>(fixedaff);
else if (aff) warper-><API key>(aff);
}
else
{
if (aff) warper-><API key>( affinverse );
else if (fixedaff) warper-><API key>(fixedaffinverse);
if (totalField) warper-><API key>(totalField);
}
warper->SetOutputOrigin(referenceimage->GetOrigin());
typename ImageType::SizeType size=referenceimage-><API key>().GetSize();
if (totalField) size=totalField-><API key>().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-><API key>(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, <API key> aff , <API key> totalField, bool doinverse , <API key> fixedaff )
{
typedef typename ImageType::DirectionType DirectionType;
DirectionType rdirection=referenceimage->GetDirection();
DirectionType mdirection=movingImage->GetDirection();
<API key> affinverse=NULL;
if (aff)
{
affinverse=AffineTransformType::New();
aff->GetInverse(affinverse);
}
<API key> 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::<API key><ImageType,double> InterpolatorType1;
typedef itk::<API key><ImageType,double> InterpolatorType2;
typedef itk::<API key><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, <API key>> 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-><API key>) warper->SetInterpolator(interpcu);
// warper->SetOutputSize(this->m_CurrentDomainSize);
// warper->SetEdgePaddingValue( 0 );
warper->Update();
return warper->GetOutput();
}
typedef itk::<API key><ImageType,ImageType, <API key>, 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-><API key>(totalField);
if (fixedaff) warper-><API key>(fixedaff);
else if (aff) warper-><API key>(aff);
}
else
{
if (aff) warper-><API key>( affinverse );
else if (fixedaff) warper-><API key>(fixedaffinverse);
if (totalField) warper-><API key>(totalField);
}
warper->SetOutputOrigin(referenceimage->GetOrigin());
typename ImageType::SizeType size=referenceimage-><API key>().GetSize();
if (totalField) size=totalField-><API key>().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()-><API key>().GetSize() << " requested size " << totalField-><API key>().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 <API key><ImageType, ImageType> GaussianFilterType;
typename GaussianFilterType::Pointer smoother = GaussianFilterType::New();
smoother->SetInputImage( image );
smoother->SetDirection( d );
smoother-><API key>( 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 <API key><TDimension, TReal>::<API key>
<API key>(<API key> totalField, unsigned int ntimesteps, float timeweight);
/** Base optimization functions */
// <API key> AffineOptimization(<API key> &aff_init, OptAffine &affine_opt); // {return NULL;}
<API key> AffineOptimization(OptAffineType &affine_opt); // {return NULL;}
std::string <API key>( ) { return this-><API key>; }
void <API key>( std::string s) {
this-><API key>=s;
std::cout << " Requested Transformation Model: " << this-><API key> << " : Using " << std::endl;
if ( this-><API key> == std::string("Elast") )
{
std::cout << "Elastic model for transformation. " << std::endl;
}
else if ( this-><API key> == std::string("SyN") )
{
std::cout << "SyN diffeomorphic model for transformation. " << std::endl;
}
else if ( this-><API key> == std::string("GreedyExp") )
{
std::cout << "Greedy Exp Diff model for transformation. Similar to Diffeomorphic Demons. Params same as Exp model. " << std::endl;
this-><API key>=std::string("GreedyExp");
}
else
{
std::cout << "Exp Diff model for transformation. " << std::endl;
this-><API key>=std::string("Exp");
}
}
void SetUpParameters()
{
/** Univariate Deformable Mapping */
// set up parameters for deformation restriction
std::string temp=this->m_Parser->GetOption( "<API key>" )->GetValue();
this-><API key> = this->m_Parser->template ConvertVector<float>(temp);
if ( this-><API key>.size() != ImageDimension ) {
std::cout <<" You input a vector of size : " << this-><API key>.size() << " for --<API key>. The vector length does not match the image dimension. Ignoring. " << std::endl;
for (unsigned int jj=0; jj<this-><API key>.size(); jj++ )
this-><API key>[jj]=0;
}
// set up max iterations per level
temp=this->m_Parser->GetOption( "<API key>" )->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-><API key>=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( "<API key>" );
this-><API key>( transformOption->GetValue() );
if ( transformOption-><API key>() >= 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-><API key>() >= 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-><API key>() >= 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-><API key>() >= 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-><API key> = -1;
this-><API key> = -1;
this-><API key>.Fill( 0 );
this-><API key>.Fill( 0 );
typename ParserType::OptionType::Pointer <API key>
= this->m_Parser->GetOption( "regularization" );
if( <API key>->GetValue() == "Gauss" )
{
if ( <API key>-><API key>() >= 1 )
{
std::string parameter = <API key>->GetParameter( 0, 0 );
this-><API key> = this->m_Parser->template Convert<float>( parameter );
}
else this-><API key>=3;
if ( <API key>-><API key>() >= 2 )
{
std::string parameter = <API key>->GetParameter( 0, 1 );
this-><API key> = this->m_Parser->template Convert<float>( parameter );
}
else this-><API key>=0.5;
if ( <API key>-><API key>() >= 3 )
{
std::string parameter = <API key>->GetParameter( 0, 2 );
this-><API key> = this->m_Parser->template Convert<float>( parameter );
}
else this-><API key> = 256;
std::cout <<" Grad Step " << this->m_Gradstep << " total-smoothing " << this-><API key> << " gradient-smoothing " << this-><API key> << std::endl;
}
else if( ( <API key>->GetValue() ).find( "DMFFD" )
!= std::string::npos )
{
if ( <API key>-><API key>() >= 1 )
{
std::string parameter = <API key>->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-><API key>[d] = gradMeshSize[d];
}
}
else
{
this-><API key>
= this->m_Parser->template Convert<float>( parameter );
}
}
else
{
this-><API key> = 3.0;
}
if ( <API key>-><API key>() >= 2 )
{
std::string parameter = <API key>->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-><API key>[d] = totalMeshSize[d];
}
}
else
{
this-><API key>
= this->m_Parser->template Convert<float>( parameter );
}
}
else
{
this-><API key>=0.5;
}
if ( <API key>-><API key>() >= 3 )
{
std::string parameter = <API key>->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-><API key>
<< " gradient-smoothing " << this-><API key>
<< " bspline-field-order " << this->m_BSplineFieldOrder
<< std::endl;
}
else
{
this-><API key>=3;
this-><API key>=0.5;
std::cout <<" Default Regularization is Gaussian smoothing with : " << this-><API key> << " & " << this-><API key> << std::endl;
// itkExceptionMacro( "Invalid regularization: " << <API key>->GetValue() );
}
}
void <API key>(ImagePointer fixedImage )
{
VectorType zero;
zero.Fill(0);
/** Compute scale factors */
this->m_FullDomainSpacing = fixedImage->GetSpacing();
this->m_FullDomainSize = fixedImage->GetRequestedRegion().GetSize();
this-><API key> = fixedImage->GetSpacing();
this->m_CurrentDomainSize = fixedImage->GetRequestedRegion().GetSize();
this-><API key>=fixedImage->GetDirection();
this->m_FullDomainOrigin.Fill(0);
this-><API key>.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-><API key>[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-><API key>[d] + 0.5 );
this-><API key>[d] = static_cast<unsigned long>( this->m_FullDomainSpacing[d] *static_cast<RealType>( this->m_FullDomainOrigin[d] ) / this-><API key>[d] + 0.5 );
}
// this->m_Debug=true;
if (this->m_Debug) std::cout << " outsize " << this->m_CurrentDomainSize << " curspc " << this-><API key> << " 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=<API key>::New();
this->m_DeformationField->SetSpacing( this-><API key>);
this->m_DeformationField->SetOrigin( fixedImage->GetOrigin() );
this->m_DeformationField->SetDirection( fixedImage->GetDirection() );
typename ImageType::RegionType region;
region.SetSize( this->m_CurrentDomainSize);
this->m_DeformationField-><API key>(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-><API key>);
if ( this-><API key> ) this->ExpandVelocity();
}
}
ImagePointer NormalizeImage( ImagePointer image) {
typedef itk::<API key><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::<API key><ImageType,ImageType> FilterType;
typename FilterType::Pointer filter = FilterType::New();
filter->SetInput( image );
filter->SetShift( shift );
filter->SetScale( scale );
filter->Update();
return filter->GetOutput();
}
void <API key>()
{
<API key> updateField = NULL;
this->SetUpParameters();
typename ImageType::SpacingType spacing;
VectorType zero;
zero.Fill(0);
std::cout << " setting N-TimeSteps = "
<< this->m_NTimeSteps << " trunc " << this-><API key> << 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-><API key>=NULL;
// this-><API key>(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-><API key>.resize(numberOfMetrics,NULL);
for ( unsigned int currentLevel = 0; currentLevel < this->m_NumberOfLevels; currentLevel++ )
{
this->m_CurrentLevel = currentLevel;
typedef Vector<float,1> <API key>;
typedef Image<<API key>, 1> CurveType;
typedef PointSet<<API key>, 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-><API key> ) );
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-><API key>(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-><API key>[metricCount] = this->SmoothImageToScale(this->m_SimilarityMetrics[metricCount]->GetMovingImage(), this->m_ScaleFactor);
}
fixedImage=this->m_SmoothFixedImages[0];
movingImage=this-><API key>[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-><API key>() != std::string("SyN")) this-><API key>=NULL;
while (!converged)
{
for (unsigned int metricCount=0; metricCount < numberOfMetrics; metricCount++)
this->m_SimilarityMetrics[metricCount]->GetMetric()->SetIterations(this->m_CurrentIteration);
if ( this-><API key>() == std::string("Elast"))
{
if (this->m_Iterations[currentLevel] > 0)
this-><API key>(fixedImage, movingImage);
}
else if (this-><API key>() == std::string("SyN"))
{
if ( currentLevel > 0 )
{
this->m_SyNF=this->ExpandField(this->m_SyNF,this-><API key>);
this->m_SyNFInv=this->ExpandField(this->m_SyNFInv,this-><API key>);
this->m_SyNM=this->ExpandField(this->m_SyNM,this-><API key>);
this->m_SyNMInv=this->ExpandField(this->m_SyNMInv,this-><API key>);
}
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-><API key>(fixedImage, movingImage, this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() );
else
this-><API key>(fixedImage, movingImage, this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() );
}
else if (this->m_SyNType)
this-><API key>( );
// this-><API key>( this->m_SyNF, 0 , false);
}
else if (this-><API key>() == std::string("Exp"))
{
if(this->m_Iterations[currentLevel] > 0)
{
this-><API key>(fixedImage, movingImage,this->m_SimilarityMetrics[0]->GetFixedPointSet(), this->m_SimilarityMetrics[0]->GetMovingPointSet() );
}
}
else if (this-><API key>() == std::string("GreedyExp"))
{
if(this->m_Iterations[currentLevel] > 0)
{
this-><API key>(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-><API key>;
<API key> energy;
energy[0] = this->m_Energy[qq];
energyProfiles[qq]->SetPoint( this-><API key>, point );
energyProfiles[qq]->SetPointData( this-><API key>, 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 <API key>
<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-><API key>; }
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;
<API key> 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++ )
{
<API key> 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-><API key>( ncps );
bspliner->Update();
ProfilePointType endPoint;
endPoint[0] = static_cast<float>( this-><API key>*0.5 );
typename BSplinerType::GradientType gradient;
gradient.Fill(0);
bspliner-><API key>( 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-><API key>() == 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-><API key>(this->m_SyNF, nts, timestep*(-1.));
// this->m_SyNMInv = this-><API key>(this->m_SyNM, nts, timestep*(-1.));
// this->m_SyNF= this-><API key>(this->m_SyNF, nts, timestep);
// this->m_SyNM= this-><API key>(this->m_SyNM,
// nts, timestep);
// <API key> fdiffmap = this->IntegrateVelocity(0,0.5);
// this->m_SyNFInv = this->IntegrateVelocity(0.5,0);
// <API key> mdiffmap = this->IntegrateVelocity(0.5,1);
// this->m_SyNMInv = this->IntegrateVelocity(1,0.5);
// this->m_SyNM=this-><API key>(mdiffmap);
// this->m_SyNF=this-><API key>(fdiffmap);
this->m_DeformationField = this->IntegrateVelocity(0,1);
// ImagePointer wmimage= this->WarpMultiTransform( this->m_SmoothFixedImages[0],this-><API key>[0], this->m_AffineTransform, this->m_DeformationField, false , this->m_ScaleFactor );
this-><API key>=this->IntegrateVelocity(1,0);
}
else
{
this-><API key>=this-><API key>( this->m_SyNM);
this->ComposeDiffs(this->m_SyNF,this->m_SyNMInv,this->m_DeformationField,1);
this->ComposeDiffs(this->m_SyNM,this->m_SyNFInv,this-><API key>,1);
}
}
else if (this-><API key>() == std::string("Exp"))
{
<API key> diffmap = this-><API key>( this->m_DeformationField, (unsigned int)this->m_NTimeSteps , 1 ); // 1.0/ (float)this->m_NTimeSteps);
<API key> invdiffmap = this-><API key>(this->m_DeformationField,(unsigned int) this->m_NTimeSteps, -1 ); // -1.0/(float)this->m_NTimeSteps);
this-><API key>=invdiffmap;
this->m_DeformationField=diffmap;
<API key> 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-><API key>() == std::string("GreedyExp"))
{
<API key> diffmap = this->m_DeformationField;
this-><API key>=NULL;
this->m_DeformationField=diffmap;
<API key> 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-><API key>)
{
this-><API key>->SetOrigin( this->m_SimilarityMetrics[0]->GetFixedImage()->GetOrigin() );
this-><API key>->SetDirection( this->m_SimilarityMetrics[0]->GetFixedImage()->GetDirection() );
}
if ( this-><API key> ) {
std::string outname=<API key>(this-><API key>.c_str())+std::string("velocity.mhd");
typename itk::ImageFileWriter<<API key>>::Pointer writer = itk::ImageFileWriter<<API key>>::New();
writer->SetFileName(outname.c_str());
writer->SetInput( this-><API key>);
writer-><API key>();
// writer->Write();
std::cout << " write tv field " << outname << std::endl;
// WriteImage<<API key>>( this-><API key> , outname.c_str());
}
}
void <API key>(ImagePointer fixedImage, ImagePointer movingImage,PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL);
void <API key>(ImagePointer fixedImage, ImagePointer movingImage,PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL);
void <API key>(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL);
void <API key>(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints=NULL, PointSetPointer mpoints=NULL);
void <API key>(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 <API key>( );
void <API key>( <API key> velocity, <API key> update1, <API key> update2 , float timept);
//void <API key>( <API key> update, unsigned int timeindex, bool <API key>);
void <API key>(ImagePointer fixedImage, ImagePointer movingImage)
{
typename ImageType::SpacingType spacing;
VectorType zero;
zero.Fill(0);
<API key> updateField;
updateField=this->ComputeUpdateField(this->m_DeformationField,NULL,NULL,NULL,NULL);
typedef <API key><<API key>> Iterator;
Iterator dIter(this->m_DeformationField,this->m_DeformationField-><API key>() );
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-><API key>() << std::endl;
std::cout << " t-sz " << this->m_DeformationField-><API key>() << std::endl;
}
this-><API key>(this->m_DeformationField, false);
return;
}
ImagePointer WarpImageBackward( ImagePointer image, <API key> field )
{
typedef WarpImageFilter<ImageType,ImageType, <API key>> WarperType;
typename WarperType::Pointer warper = WarperType::New();
typedef <API key><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(<API key> fieldtowarpby, <API key> field, <API key> fieldout, float sign);
void <API key>( <API key> 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(<API key> field,
<API key> 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-><API key>() < 2 ) maxiter=10;
ImagePointer floatImage = ImageType::New();
floatImage-><API key>( field-><API key>() );
floatImage->SetBufferedRegion( field-><API key>().GetSize() );
floatImage->SetSpacing(field->GetSpacing());
floatImage->SetOrigin(field->GetOrigin());
floatImage->SetDirection(field->GetDirection());
floatImage->Allocate();
typedef typename <API key>::PixelType VectorType;
typedef typename <API key>::IndexType IndexType;
typedef typename VectorType::ValueType ScalarType;
typedef <API key><<API key>> Iterator;
<API key> lagrangianInitCond=<API key>::New();
lagrangianInitCond->SetSpacing( field->GetSpacing() );
lagrangianInitCond->SetOrigin( field->GetOrigin() );
lagrangianInitCond->SetDirection( field->GetDirection() );
lagrangianInitCond-><API key>( field-><API key>() );
lagrangianInitCond->SetRequestedRegion(field->GetRequestedRegion() );
lagrangianInitCond->SetBufferedRegion( field-><API key>() );
lagrangianInitCond->Allocate();
<API key> eulerianInitCond=<API key>::New();
eulerianInitCond->SetSpacing( field->GetSpacing() );
eulerianInitCond->SetOrigin( field->GetOrigin() );
eulerianInitCond->SetDirection( field->GetDirection() );
eulerianInitCond-><API key>( field-><API key>() );
eulerianInitCond->SetRequestedRegion(field->GetRequestedRegion() );
eulerianInitCond->SetBufferedRegion( field-><API key>() );
eulerianInitCond->Allocate();
typedef typename <API key>::SizeType SizeType;
SizeType size=field-><API key>().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-><API key>().GetSize()[j];
}
subpix=pow((float)ImageDimension,(float)ImageDimension)*0.5;
float max=0;
Iterator iter( field, field-><API key>() );
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-><API key>() );
// 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 <API key>( bool useNN) { this->m_UseNN=useNN; }
void <API key>( bool useNN) { this-><API key>=useNN; }
protected:
<API key> IntegrateVelocity(float,float);
<API key> <API key>(float,float, PointSetPointer movingpoints, ImagePointer referenceimage );
VectorType <API key>(float starttimein, float finishtimein , IndexType startPoint);
ImagePointer MakeSubImage( ImagePointer bigimage)
{
typedef itk::<API key><ImageType> Iterator;
ImagePointer varimage=ImageType::New();
typename ImageType::RegionType region;
typename ImageType::SizeType size=bigimage-><API key>().GetSize();
region.SetSize( this->m_CurrentDomainSize);
typename ImageType::IndexType index; index.Fill(0);
region.SetIndex(index);
varimage->SetRegions( region );
varimage->SetSpacing(this-><API key>);
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-><API key>[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-><API key>() );
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-><API key>[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-><API key>().GetSize() << " bigimage " << bigimage-><API key>().GetSize() << std::endl;
return varimage;
}
float MeasureDeformation(<API key> field, int option=0)
{
typedef typename <API key>::PixelType VectorType;
typedef typename <API key>::IndexType IndexType;
typedef typename <API key>::SizeType SizeType;
typedef typename VectorType::ValueType ScalarType;
typedef <API key><<API key>> Iterator;
// all we have to do here is add the local field to the global field.
Iterator vfIter( field, field-><API key>() );
SizeType size=field-><API key>().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;
}
<API key>();
virtual ~<API key>() {}
void PrintSelf( std::ostream& os, Indent indent ) const;
private:
<API key>( const Self& ); //purposely not implemented
void operator=( const Self& ); //purposely not implemented
typename <API key>::Pointer <API key>;
typename ImageType::SizeType m_CurrentDomainSize;
typename ImageType::PointType <API key>;
typename ImageType::SpacingType <API key>;
typename ImageType::DirectionType <API key>;
typename ImageType::SizeType m_FullDomainSize;
typename ImageType::PointType m_FullDomainOrigin;
typename ImageType::SpacingType m_FullDomainSpacing;
<API key> m_AffineTransform;
<API key> <API key>;
<API key> m_DeformationField;
<API key> <API key>;
std::vector<float> <API key>;
std::vector<float> <API key>;
std::vector<ImagePointer> m_SmoothFixedImages;
std::vector<ImagePointer> <API key>;
bool m_Debug;
unsigned int m_NumberOfLevels;
typename ParserType::Pointer m_Parser;
<API key> m_SimilarityMetrics;
ImagePointer m_MaskImage;
float m_ScaleFactor;
bool m_UseMulti;
bool m_UseROI;
bool m_UseNN;
bool <API key>;
unsigned int m_CurrentIteration;
unsigned int m_CurrentLevel;
std::string <API key>;
std::string <API key>;
PointSetPointer m_FixedPointSet;
PointSetPointer m_MovingPointSet;
std::vector<unsigned int> m_Iterations;
std::vector<float> <API key>;
std::vector<float> m_RoiNumbers;
float <API key>;
float <API key>;
float m_Gradstep;
float m_GradstepAltered;
float m_NTimeSteps;
float <API key>;
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 */
<API key> m_SyNF;
<API key> m_SyNFInv;
<API key> m_SyNM;
<API key> m_SyNMInv;
<API key> <API key>;
<API key> <API key>;
<API key> <API key>;
unsigned int m_SyNType;
/** for BSpline stuff */
unsigned int m_BSplineFieldOrder;
ArrayType <API key>;
ArrayType <API key>;
/** For thickness calculation */
ImagePointer m_HitImage;
ImagePointer m_ThickImage;
unsigned int m_ComputeThickness;
unsigned int m_SyNFullTime;
};
}
// end namespace itk
#ifndef <API key>
#include "<API key>.cxx"
#endif
#endif
|
#!/bin/bash
# Time-stamp: <2013-04-16 22:35:22 leo>
# Append a pdf to the end of another.
if (( $
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 (( $
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
|
# 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.
+
| client |
+
| +
+
| +
| +
+
+
## 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\>
|
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 <API key>
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 :<API key>
# 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 += <API key>
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 <API key> 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 <API key> if the specified column does not exist in every
# Raises an <API key> 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 <API key> 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
<API key>.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
<API key>.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
<API key>.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 <API key>, "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
|
<?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']]];
}
}
|
<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>
|
#include "chrome/browser/optimization_guide/<API key>.h"
#include "chrome/browser/optimization_guide/<API key>.h"
#include "chrome/browser/optimization_guide/<API key>.h"
#include "chrome/browser/optimization_guide/<API key>.h"
#include "chrome/browser/prefetch/no_state_prefetch/<API key>.h"
#include "chrome/browser/profiles/profile.h"
#include "components/no_state_prefetch/browser/<API key>.h"
#include "components/optimization_guide/core/hints_fetcher.h"
#include "components/optimization_guide/core/<API key>.h"
#include "components/optimization_guide/core/<API key>.h"
#include "components/optimization_guide/core/<API key>.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 <API key>(
content::NavigationHandle* navigation_handle) {
if (!navigation_handle-><API key>())
return false;
if (!navigation_handle->GetURL().SchemeIsHTTPOrHTTPS())
return false;
// Now check if this is a NSP navigation. NSP is not a valid navigation.
prerender::<API key>* <API key> =
prerender::<API key>::<API key>(
navigation_handle->GetWebContents()->GetBrowserContext());
if (!<API key>) {
// Not a NSP navigation if there is no NSP manager.
return true;
}
return !(<API key>-><API key>(
navigation_handle->GetWebContents()));
}
} // namespace
<API key>::<API key>(
content::WebContents* web_contents)
: content::WebContentsObserver(web_contents) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
<API key> =
<API key>::GetForProfile(
Profile::FromBrowserContext(web_contents->GetBrowserContext()));
}
<API key>::~<API key>() =
default;
<API key>* <API key>::
<API key>(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
DCHECK_EQ(web_contents(), navigation_handle->GetWebContents());
<API key>* <API key> =
<API key>::<API key>(*navigation_handle);
<API key>* navigation_data =
<API key>-><API key>();
if (!navigation_data) {
// We do not have one already - create one.
<API key>-><API key>(
std::make_unique<<API key>>(
navigation_handle->GetNavigationId(),
navigation_handle->NavigationStart()));
navigation_data =
<API key>-><API key>();
}
DCHECK(navigation_data);
return navigation_data;
}
void <API key>::DidStartNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!<API key>(navigation_handle))
return;
if (!<API key>)
return;
<API key>* navigation_data =
<API key>(navigation_handle);
navigation_data->set_navigation_url(navigation_handle->GetURL());
<API key>-><API key>(
navigation_data);
}
void <API key>::<API key>(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!<API key>(navigation_handle))
return;
if (!<API key>)
return;
<API key>* navigation_data =
<API key>(navigation_handle);
navigation_data->set_navigation_url(navigation_handle->GetURL());
<API key>-><API key>(
navigation_data);
}
void <API key>::DidFinishNavigation(
content::NavigationHandle* navigation_handle) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!<API key>(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.
<API key>* <API key> =
<API key>::<API key>(*navigation_handle);
if (!<API key>)
return;
base::<API key>::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&<API key>::<API key>,
weak_factory_.GetWeakPtr(),
<API key>-><API key>(),
navigation_handle->GetRedirectChain()));
}
void <API key>::<API key>(
content::RenderFrameHost* render_frame_host) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (!render_frame_host->GetLastCommittedURL().SchemeIsHTTPOrHTTPS())
return;
if (!<API key>)
return;
base::<API key>::Get()->PostTask(
FROM_HERE,
base::BindOnce(
&<API key>::<API key>,
weak_factory_.GetWeakPtr(),
<API key>->GetHintsManager(),
web_contents()->GetPrimaryPage().GetWeakPtr()));
}
void <API key>::<API key>(
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.<API key>();
hints_manager->FetchHintsForURLs(
page_data.GetHintsTargetUrls(),
optimization_guide::proto::<API key>);
}
void <API key>::<API key>(
std::unique_ptr<<API key>> navigation_data,
const std::vector<GURL>& <API key>) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
if (<API key>) {
<API key>->OnNavigationFinish(
<API key>);
}
// 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 <API key>::<API key>() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
PageData& page_data = GetPageData(web_contents()->GetPrimaryPage());
page_data.SetNavigationData(nullptr);
}
void <API key>::<API key>(
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.<API key>())
return;
page_data.<API key>(urls);
<API key>(web_contents->GetMainFrame());
}
<API key>::PageData&
<API key>::GetPageData(content::Page& page) {
return *PageData::GetOrCreateForPage(page);
}
<API key>::PageData::PageData(content::Page& page)
: PageUserData(page) {}
<API key>::PageData::~PageData() = default;
void <API key>::PageData::<API key>(
const std::vector<GURL>& urls) {
DCHECK(!<API key>);
for (const GURL& url : urls)
hints_target_urls_.insert(url);
}
std::vector<GURL>
<API key>::PageData::GetHintsTargetUrls() {
std::vector<GURL> target_urls = std::move(hints_target_urls_.vector());
hints_target_urls_.clear();
return target_urls;
}
<API key>::<API key>::
<API key>(content::NavigationHandle&) {}
<API key>::<API key>::
~<API key>() = default;
<API key>(<API key>::PageData);
<API key>(
<API key>::<API key>);
<API key>(<API key>);
|
// GLFW Engine.
#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();
}
}
}
|
#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/<API key>.h>
#include <proxygen/lib/http/session/<API key>.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/<API key>.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_)),
<API key>(makeTimeoutSet(&eventBase_)) {
EXPECT_CALL(mockController_, attachSession(_));
httpSession_ = new <API key>(
<API key>.get(),
std::move(<API key>::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 <API key>;
StrictMock<MockController> mockController_;
<API key>* httpSession_;
};
// Uses TestAsyncTransport
typedef HTTPDownstreamTest<HTTP1xCodecPair> <API key>;
typedef HTTPDownstreamTest<SPDY2CodecPair> <API key>;
typedef HTTPDownstreamTest<SPDY3CodecPair> <API key>;
TEST_F(<API key>, 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(<API key>, 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(<API key>, <API key>) {
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(<API key>, 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(<API key>, <API key>) {
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(<API key>, 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(<API key>, 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(<API key>, 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(<API key>, 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(<API key>, 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(<API key>, 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 = <API key>();
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::<API key>::WriteCallback* callback,
const shared_ptr<IOBuf> iob,
WriteFlags flags) {
callback->writeSuccess();
}));
// Create the downstream session, thus initializing codecCallback
auto transactionTimeouts = <API key>(&evb);
auto session = new <API key>(
transactionTimeouts.get(),
<API key>::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-><API key>(<API key>);
evb.loop();
}
TEST(HTTPDownstreamTest, byte_events_drained) {
// Test that byte events are drained before socket is closed
EventBase evb;
NiceMock<MockController> mockController;
auto codec = <API key>();
auto byteEventTracker = new <API key>(nullptr);
auto transport = newMockTransport(&evb);
auto transactionTimeouts = <API key>(&evb);
// Create the downstream session
auto session = new <API key>(
transactionTimeouts.get(),
<API key>::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-><API key>(<API key>);
evb.loop();
}
TEST_F(<API key>, trailers) {
testChunks(true);
}
TEST_F(<API key>, 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.<API key>(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<<API key>> 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(<API key>, 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_-><API key>();
}));
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(<API key>, <API key>) {
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_-><API key>();
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(<API key>, 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(<API key>, <API key>) {
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.<API key>(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(<API key>, <API key>) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
MockHTTPHandler handler1;
HTTP1xCodec clientCodec(TransportDirection::UPSTREAM);
auto streamID = HTTPCodec::StreamID(0);
clientCodec.<API key>(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(<API key>, <API key>) {
// 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.<API key>(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(<API key>, <API key>) {
// 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.<API key>(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(<API key>, 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.<API key>(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. <API key> will result in a call
// to removeTransaction with writesDraining_=true
TEST_F(<API key>, 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.<API key>(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(<API key>, <API key>) {
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(<API key>, 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.<API key>(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(<API key>, 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(<API key>, <API key>) {
// 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.<API key>(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(<API key>, spdy_prio) {
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY2);
testPriorities(clientCodec, 4);
}
TEST_F(<API key>, 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.<API key>(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<<API key>> 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(<API key>, spdy_timeout) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY3);
clientCodec.<API key>(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(<API key>, spdy_timeout_win) {
IOBufQueue requests{IOBufQueue::cacheChainLength()};
HTTPMessage req = getGetRequest();
SPDYCodec clientCodec(TransportDirection::UPSTREAM,
SPDYVersion::SPDY3);
auto streamID = HTTPCodec::StreamID(1);
clientCodec.<API key>(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-><API key>(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-><API key>(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<<API key>> 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, <API key>) {
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-><API key>(requests);
clientCodec->getEgressSettings()->setSetting(SettingsId::INITIAL_WINDOW_SIZE,
1000000);
clientCodec->generateSettings(requests);
clientCodec-><API key>(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(<API key>, <API key>) {
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.<API key>(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::<API key>, 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();
}
<API key>(HTTPDownstreamTest,
testWritesDraining, testBodySizeLimit,
<API key>);
typedef ::testing::Types<SPDY2CodecPair, SPDY3CodecPair, SPDY3_1CodecPair,
HTTP2CodecPair> ParallelCodecs;
<API key>(ParallelCodecs,
HTTPDownstreamTest,
ParallelCodecs);
class <API key> : public HTTPDownstreamTest<SPDY3_1CodecPair> {
public:
<API key>()
: HTTPDownstreamTest<SPDY3_1CodecPair>(2 * spdy::kInitialWindow) {}
};
TEST_F(<API key>, <API key>) {
eventBase_.loopOnce();
NiceMock<<API key>> 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(<API key>, <API key>) {
// 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.<API key>(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<<API key>> 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(_));
}
|
#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(<API key>,<API key>,<API key>,PLUGIN_BUILD,VS_RELEASE)
|
#include "chrome/browser/renderer_host/pepper/device_id_fetcher.h"
#include "base/file_util.h"
#include "base/prefs/pref_service.h"
#include "base/strings/<API key>.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/<API key>.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 <API key> = 500;
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::Bind(&GetMachineIDAsync, callback),
base::TimeDelta::FromMilliseconds(<API key>));
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::<API key>, this));
return true;
}
// static
void DeviceIDFetcher::<API key>(
user_prefs::<API key>* prefs) {
prefs->RegisterBooleanPref(prefs::kEnableDRM,
true,
user_prefs::<API key>::UNSYNCABLE_PREF);
prefs->RegisterStringPref(
prefs::kDRMSalt,
"",
user_prefs::<API key>::UNSYNCABLE_PREF);
}
// static
base::FilePath DeviceIDFetcher::<API key>(
const base::FilePath& profile_path) {
return profile_path.AppendASCII(kDRMIdentifierFile);
}
void DeviceIDFetcher::<API key>() {
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)) {
<API key>(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::<API key>(
FROM_HERE,
base::Bind(&DeviceIDFetcher::<API key>,
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";
<API key>(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();
<API key>(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)));
<API key>(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::<API key>(
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 = <API key>(profile_path);
if (base::PathExists(id_path)) {
if (base::ReadFileToString(id_path, &id) && !id.empty()) {
<API key>(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::<API key>(const std::string& id) {
if (!BrowserThread::CurrentlyOn(BrowserThread::IO)) {
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
base::Bind(&DeviceIDFetcher::<API key>, this, id));
return;
}
in_progress_ = false;
callback_.Run(id);
}
} // namespace chrome
|
exports.dbname = "lrdata";
exports.dbuser = "lrdata";
exports.dbpassword = "test";
exports.lfm<API key>;
exports.lfmApi<API key>;
exports.tagAgeBeforeRefresh = 14; // In days
exports.tagFetchFrequency = 1000; // In milliseconds
|
"""
Room Typeclasses for the TutorialWorld.
This defines special types of Rooms available in the tutorial. To keep
everything in one place we define them together with the custom
commands needed to control them. Those commands could also have been
in a separate module (e.g. if they could have been re-used elsewhere.)
"""
from __future__ import print_function
import random
from evennia import TICKER_HANDLER
from evennia import CmdSet, Command, DefaultRoom
from evennia import utils, create_object, search_object
from evennia import syscmdkeys, default_cmds
from evennia.contrib.tutorial_world.objects import LightSource
# the system error-handling module is defined in the settings. We load the
# given setting here using utils.object_from_module. This way we can use
# it regardless of if we change settings later.
from django.conf import settings
_SEARCH_AT_RESULT = utils.object_from_module(settings.SEARCH_AT_RESULT)
# Tutorial room - parent room class
# This room is the parent of all rooms in the tutorial.
# It defines a tutorial command on itself (available to
# all those who are in a tutorial room).
# Special command available in all tutorial rooms
class CmdTutorial(Command):
"""
Get help during the tutorial
Usage:
tutorial [obj]
This command allows you to get behind-the-scenes info
about an object or the current location.
"""
key = "tutorial"
aliases = ["tut"]
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""
All we do is to scan the current location for an Attribute
called `tutorial_info` and display that.
"""
caller = self.caller
if not self.args:
target = self.obj # this is the room the command is defined on
else:
target = caller.search(self.args.strip())
if not target:
return
helptext = target.db.tutorial_info
if helptext:
caller.msg("|G%s|n" % helptext)
else:
caller.msg("|RSorry, there is no tutorial help available here.|n")
# for the @detail command we inherit from MuxCommand, since
# we want to make use of MuxCommand's pre-parsing of '=' in the
# argument.
class <API key>(default_cmds.MuxCommand):
"""
sets a detail on a room
Usage:
@detail <key> = <description>
@detail <key>;<alias>;... = description
Example:
@detail walls = The walls are covered in ...
@detail castle;ruin;tower = The distant ruin ...
This sets a "detail" on the object this command is defined on
(TutorialRoom for this tutorial). This detail can be accessed with
the TutorialRoomLook command sitting on TutorialRoom objects (details
are set as a simple dictionary on the room). This is a Builder command.
We custom parse the key for the ;-separator in order to create
multiple aliases to the detail all at once.
"""
key = "@detail"
locks = "cmd:perm(Builder)"
help_category = "TutorialWorld"
def func(self):
"""
All this does is to check if the object has
the set_detail method and uses it.
"""
if not self.args or not self.rhs:
self.caller.msg("Usage: @detail key = description")
return
if not hasattr(self.obj, "set_detail"):
self.caller.msg("Details cannot be set on %s." % self.obj)
return
for key in self.lhs.split(";"):
# loop over all aliases, if any (if not, this will just be
# the one key to loop over)
self.obj.set_detail(key, self.rhs)
self.caller.msg("Detail set: '%s': '%s'" % (self.lhs, self.rhs))
class CmdTutorialLook(default_cmds.CmdLook):
"""
looks at the room and on details
Usage:
look <obj>
look <room detail>
look *<account>
Observes your location, details at your location or objects
in your vicinity.
Tutorial: This is a child of the default Look command, that also
allows us to look at "details" in the room. These details are
things to examine and offers some extra description without
actually having to be actual database objects. It uses the
return_detail() hook on TutorialRooms for this.
"""
# we don't need to specify key/locks etc, this is already
# set by the parent.
help_category = "TutorialWorld"
def func(self):
"""
Handle the looking. This is a copy of the default look
code except for adding in the details.
"""
caller = self.caller
args = self.args
if args:
# we use quiet=True to turn off automatic error reporting.
# This tells search that we want to handle error messages
# ourself. This also means the search function will always
# return a list (with 0, 1 or more elements) rather than
# result/None.
looking_at_obj = caller.search(args,
# note: excludes room/room aliases
candidates=caller.location.contents + caller.contents,
use_nicks=True, quiet=True)
if len(looking_at_obj) != 1:
# no target found or more than one target found (multimatch)
# look for a detail that may match
detail = self.obj.return_detail(args)
if detail:
self.caller.msg(detail)
return
else:
# no detail found, delegate our result to the normal
# error message handler.
_SEARCH_AT_RESULT(None, caller, args, looking_at_obj)
return
else:
# we found a match, extract it from the list and carry on
# normally with the look handling.
looking_at_obj = looking_at_obj[0]
else:
looking_at_obj = caller.location
if not looking_at_obj:
caller.msg("You have no location to look at!")
return
if not hasattr(looking_at_obj, 'return_appearance'):
# this is likely due to us having an account instead
looking_at_obj = looking_at_obj.character
if not looking_at_obj.access(caller, "view"):
caller.msg("Could not find '%s'." % args)
return
# get object's appearance
caller.msg(looking_at_obj.return_appearance(caller))
# the object's at_desc() method.
looking_at_obj.at_desc(looker=caller)
return
class TutorialRoomCmdSet(CmdSet):
"""
Implements the simple tutorial cmdset. This will overload the look
command in the default CharacterCmdSet since it has a higher
priority (ChracterCmdSet has prio 0)
"""
key = "tutorial_cmdset"
priority = 1
def at_cmdset_creation(self):
"""add the tutorial-room commands"""
self.add(CmdTutorial())
self.add(<API key>())
self.add(CmdTutorialLook())
class TutorialRoom(DefaultRoom):
"""
This is the base room type for all rooms in the tutorial world.
It defines a cmdset on itself for reading tutorial info about the location.
"""
def at_object_creation(self):
"""Called when room is first created"""
self.db.tutorial_info = "This is a tutorial room. It allows you to use the 'tutorial' command."
self.cmdset.add_default(TutorialRoomCmdSet)
def at_object_receive(self, new_arrival, source_location):
"""
When an object enter a tutorial room we tell other objects in
the room about it by trying to call a hook on them. The Mob object
uses this to cheaply get notified of enemies without having
to constantly scan for them.
Args:
new_arrival (Object): the object that just entered this room.
source_location (Object): the previous location of new_arrival.
"""
if new_arrival.has_account and not new_arrival.is_superuser:
# this is a character
for obj in self.contents_get(exclude=new_arrival):
if hasattr(obj, "at_new_arrival"):
obj.at_new_arrival(new_arrival)
def return_detail(self, detailkey):
"""
This looks for an Attribute "obj_details" and possibly
returns the value of it.
Args:
detailkey (str): The detail being looked at. This is
case-insensitive.
"""
details = self.db.details
if details:
return details.get(detailkey.lower(), None)
def set_detail(self, detailkey, description):
"""
This sets a new detail, using an Attribute "details".
Args:
detailkey (str): The detail identifier to add (for
aliases you need to add multiple keys to the
same description). Case-insensitive.
description (str): The text to return when looking
at the given detailkey.
"""
if self.db.details:
self.db.details[detailkey.lower()] = description
else:
self.db.details = {detailkey.lower(): description}
# Weather room - room with a ticker
# These are rainy weather strings
WEATHER_STRINGS = (
"The rain coming down from the iron-grey sky intensifies.",
"A gust of wind throws the rain right in your face. Despite your cloak you shiver.",
"The rainfall eases a bit and the sky momentarily brightens.",
"For a moment it looks like the rain is slowing, then it begins anew with renewed force.",
"The rain pummels you with large, heavy drops. You hear the rumble of thunder in the distance.",
"The wind is picking up, howling around you, throwing water droplets in your face. It's cold.",
"Bright fingers of lightning flash over the sky, moments later followed by a deafening rumble.",
"It rains so hard you can hardly see your hand in front of you. You'll soon be drenched to the bone.",
"Lightning strikes in several thundering bolts, striking the trees in the forest to your west.",
"You hear the distant howl of what sounds like some sort of dog or wolf.",
"Large clouds rush across the sky, throwing their load of rain over the world.")
class WeatherRoom(TutorialRoom):
"""
This should probably better be called a rainy room...
This sets up an outdoor room typeclass. At irregular intervals,
the effects of weather will show in the room. Outdoor rooms should
inherit from this.
"""
def at_object_creation(self):
"""
Called when object is first created.
We set up a ticker to update this room regularly.
Note that we could in principle also use a Script to manage
the ticking of the room; the TickerHandler works fine for
simple things like this though.
"""
super(WeatherRoom, self).at_object_creation()
# subscribe ourselves to a ticker to repeatedly call the hook
# "update_weather" on this object. The interval is randomized
# so as to not have all weather rooms update at the same time.
self.db.interval = random.randint(50, 70)
TICKER_HANDLER.add(interval=self.db.interval, callback=self.update_weather, idstring="tutorial")
# this is parsed by the 'tutorial' command on TutorialRooms.
self.db.tutorial_info = \
"This room has a Script running that has it echo a weather-related message at irregular intervals."
def update_weather(self, *args, **kwargs):
"""
Called by the tickerhandler at regular intervals. Even so, we
only update 20% of the time, picking a random weather message
when we do. The tickerhandler requires that this hook accepts
any arguments and keyword arguments (hence the *args, **kwargs
even though we don't actually use them in this example)
"""
if random.random() < 0.2:
# only update 20 % of the time
self.msg_contents("|w%s|n" % random.choice(WEATHER_STRINGS))
SUPERUSER_WARNING = "\nWARNING: You are playing as a superuser ({name}). Use the {quell} command to\n" \
"play without superuser privileges (many functions and puzzles ignore the \n" \
"presence of a superuser, making this mode useful for exploring things behind \n" \
"the scenes later).\n" \
# Intro Room - unique room
# This room marks the start of the tutorial. It sets up properties on
# the player char that is needed for the tutorial.
class IntroRoom(TutorialRoom):
"""
Intro room
properties to customize:
char_health - integer > 0 (default 20)
"""
def at_object_creation(self):
"""
Called when the room is first created.
"""
super(IntroRoom, self).at_object_creation()
self.db.tutorial_info = "The first room of the tutorial. " \
"This assigns the health Attribute to "\
"the account."
def at_object_receive(self, character, source_location):
"""
Assign properties on characters
"""
# setup character for the tutorial
health = self.db.char_health or 20
if character.has_account:
character.db.health = health
character.db.health_max = health
if character.is_superuser:
string = "-" * 78 + SUPERUSER_WARNING + "-" * 78
character.msg("|r%s|n" % string.format(name=character.key, quell="|w@quell|r"))
# Bridge - unique room
# Defines a special west-eastward "bridge"-room, a large room that takes
# several steps to cross. It is complete with custom commands and a
# chance of falling off the bridge. This room has no regular exits,
# instead the exitings are handled by custom commands set on the account
# upon first entering the room.
# Since one can enter the bridge room from both ends, it is
# divided into five steps:
# westroom <- 0 1 2 3 4 -> eastroom
class CmdEast(Command):
"""
Go eastwards across the bridge.
Tutorial info:
This command relies on the caller having two Attributes
(assigned by the room when entering):
- east_exit: a unique name or dbref to the room to go to
when exiting east.
- west_exit: a unique name or dbref to the room to go to
when exiting west.
The room must also have the following Attributes
- <API key>: the current position on
on the bridge, 0 - 4.
"""
key = "east"
aliases = ["e"]
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""move one step eastwards"""
caller = self.caller
bridge_step = min(5, caller.db.<API key> + 1)
if bridge_step > 4:
# we have reached the far east end of the bridge.
# Move to the east room.
eexit = search_object(self.obj.db.east_exit)
if eexit:
caller.move_to(eexit[0])
else:
caller.msg("No east exit was found for this room. Contact an admin.")
return
caller.db.<API key> = bridge_step
# since we are really in one room, we have to notify others
# in the room when we move.
caller.location.msg_contents("%s steps eastwards across the bridge." % caller.name, exclude=caller)
caller.execute_cmd("look")
# go back across the bridge
class CmdWest(Command):
"""
Go westwards across the bridge.
Tutorial info:
This command relies on the caller having two Attributes
(assigned by the room when entering):
- east_exit: a unique name or dbref to the room to go to
when exiting east.
- west_exit: a unique name or dbref to the room to go to
when exiting west.
The room must also have the following property:
- <API key>: the current position on
on the bridge, 0 - 4.
"""
key = "west"
aliases = ["w"]
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""move one step westwards"""
caller = self.caller
bridge_step = max(-1, caller.db.<API key> - 1)
if bridge_step < 0:
# we have reached the far west end of the bridge.
# Move to the west room.
wexit = search_object(self.obj.db.west_exit)
if wexit:
caller.move_to(wexit[0])
else:
caller.msg("No west exit was found for this room. Contact an admin.")
return
caller.db.<API key> = bridge_step
# since we are really in one room, we have to notify others
# in the room when we move.
caller.location.msg_contents("%s steps westwards across the bridge." % caller.name, exclude=caller)
caller.execute_cmd("look")
BRIDGE_POS_MESSAGES = ("You are standing |wvery close to the the bridge's western foundation|n."
" If you go west you will be back on solid ground ...",
"The bridge slopes precariously where it extends eastwards"
" towards the lowest point - the center point of the hang bridge.",
"You are |whalfways|n out on the unstable bridge.",
"The bridge slopes precariously where it extends westwards"
" towards the lowest point - the center point of the hang bridge.",
"You are standing |wvery close to the bridge's eastern foundation|n."
" If you go east you will be back on solid ground ...")
BRIDGE_MOODS = ("The bridge sways in the wind.", "The hanging bridge creaks dangerously.",
"You clasp the ropes firmly as the bridge sways and creaks under you.",
"From the castle you hear a distant howling sound, like that of a large dog or other beast.",
"The bridge creaks under your feet. Those planks does not seem very sturdy.",
"Far below you the ocean roars and throws its waves against the cliff,"
" as if trying its best to reach you.",
"Parts of the bridge come loose behind you, falling into the chasm far below!",
"A gust of wind causes the bridge to sway precariously.",
"Under your feet a plank comes loose, tumbling down. For a moment you dangle over the abyss ...",
"The section of rope you hold onto crumble in your hands,"
" parts of it breaking apart. You sway trying to regain balance.")
FALL_MESSAGE = "Suddenly the plank you stand on gives way under your feet! You fall!" \
"\nYou try to grab hold of an adjoining plank, but all you manage to do is to " \
"divert your fall westwards, towards the cliff face. This is going to hurt ... " \
"\n ... The world goes dark ...\n\n"
class CmdLookBridge(Command):
"""
looks around at the bridge.
Tutorial info:
This command assumes that the room has an Attribute
"fall_exit", a unique name or dbref to the place they end upp
if they fall off the bridge.
"""
key = 'look'
aliases = ["l"]
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""Looking around, including a chance to fall."""
caller = self.caller
bridge_position = self.caller.db.<API key>
# this command is defined on the room, so we get it through self.obj
location = self.obj
# randomize the look-echo
message = "|c%s|n\n%s\n%s" % (location.key,
BRIDGE_POS_MESSAGES[bridge_position],
random.choice(BRIDGE_MOODS))
chars = [obj for obj in self.obj.contents_get(exclude=caller) if obj.has_account]
if chars:
# we create the You see: message manually here
message += "\n You see: %s" % ", ".join("|c%s|n" % char.key for char in chars)
self.caller.msg(message)
# there is a chance that we fall if we are on the western or central
# part of the bridge.
if bridge_position < 3 and random.random() < 0.05 and not self.caller.is_superuser:
# we fall 5% of time.
fall_exit = search_object(self.obj.db.fall_exit)
if fall_exit:
self.caller.msg("|r%s|n" % FALL_MESSAGE)
self.caller.move_to(fall_exit[0], quiet=True)
# inform others on the bridge
self.obj.msg_contents("A plank gives way under %s's feet and "
"they fall from the bridge!" % self.caller.key)
# custom help command
class CmdBridgeHelp(Command):
"""
Overwritten help command while on the bridge.
"""
key = "help"
aliases = ["h", "?"]
locks = "cmd:all()"
help_category = "Tutorial world"
def func(self):
"""Implements the command."""
string = "You are trying hard not to fall off the bridge ..." \
"\n\nWhat you can do is trying to cross the bridge |weast|n" \
" or try to get back to the mainland |wwest|n)."
self.caller.msg(string)
class BridgeCmdSet(CmdSet):
"""This groups the bridge commands. We will store it on the room."""
key = "Bridge commands"
priority = 1 # this gives it precedence over the normal look/help commands.
def at_cmdset_creation(self):
"""Called at first cmdset creation"""
self.add(CmdTutorial())
self.add(CmdEast())
self.add(CmdWest())
self.add(CmdLookBridge())
self.add(CmdBridgeHelp())
BRIDGE_WEATHER = (
"The rain intensifies, making the planks of the bridge even more slippery.",
"A gust of wind throws the rain right in your face.",
"The rainfall eases a bit and the sky momentarily brightens.",
"The bridge shakes under the thunder of a closeby thunder strike.",
"The rain pummels you with large, heavy drops. You hear the distinct howl of a large hound in the distance.",
"The wind is picking up, howling around you and causing the bridge to sway from side to side.",
"Some sort of large bird sweeps by overhead, giving off an eery screech. Soon it has disappeared in the gloom.",
"The bridge sways from side to side in the wind.",
"Below you a particularly large wave crashes into the rocks.",
"From the ruin you hear a distant, otherwordly howl. Or maybe it was just the wind.")
class BridgeRoom(WeatherRoom):
"""
The bridge room implements an unsafe bridge. It also enters the player into
a state where they get new commands so as to try to cross the bridge.
We want this to result in the account getting a special set of
commands related to crossing the bridge. The result is that it
will take several steps to cross it, despite it being represented
by only a single room.
We divide the bridge into steps:
self.db.west_exit - - | - - self.db.east_exit
0 1 2 3 4
The position is handled by a variable stored on the character
when entering and giving special move commands will
increase/decrease the counter until the bridge is crossed.
We also has self.db.fall_exit, which points to a gathering
location to end up if we happen to fall off the bridge (used by
the CmdLookBridge command).
"""
def at_object_creation(self):
"""Setups the room"""
# this will start the weather room's ticker and tell
# it to call update_weather regularly.
super(BridgeRoom, self).at_object_creation()
# this identifies the exits from the room (should be the command
# needed to leave through that exit). These are defaults, but you
# could of course also change them after the room has been created.
self.db.west_exit = "cliff"
self.db.east_exit = "gate"
self.db.fall_exit = "cliffledge"
# add the cmdset on the room.
self.cmdset.add_default(BridgeCmdSet)
# since the default Character's at_look() will access the room's
# return_description (this skips the cmdset) when
# first entering it, we need to explicitly turn off the room
# as a normal view target - once inside, our own look will
# handle all return messages.
self.locks.add("view:false()")
def update_weather(self, *args, **kwargs):
"""
This is called at irregular intervals and makes the passage
over the bridge a little more interesting.
"""
if random.random() < 80:
# send a message most of the time
self.msg_contents("|w%s|n" % random.choice(BRIDGE_WEATHER))
def at_object_receive(self, character, source_location):
"""
This hook is called by the engine whenever the player is moved
into this room.
"""
if character.has_account:
# we only run this if the entered object is indeed a player object.
# check so our east/west exits are correctly defined.
wexit = search_object(self.db.west_exit)
eexit = search_object(self.db.east_exit)
fexit = search_object(self.db.fall_exit)
if not (wexit and eexit and fexit):
character.msg("The bridge's exits are not properly configured. "
"Contact an admin. Forcing west-end placement.")
character.db.<API key> = 0
return
if source_location == eexit[0]:
# we assume we enter from the same room we will exit to
character.db.<API key> = 4
else:
# if not from the east, then from the west!
character.db.<API key> = 0
character.execute_cmd("look")
def at_object_leave(self, character, target_location):
"""
This is triggered when the player leaves the bridge room.
"""
if character.has_account:
# clean up the position attribute
del character.db.<API key>
# Dark Room - a room with states
# This room limits the movemenets of its denizens unless they carry an active
# LightSource object (LightSource is defined in
# tutorialworld.objects.LightSource)
DARK_MESSAGES = ("It is pitch black. You are likely to be eaten by a grue.",
"It's pitch black. You fumble around but cannot find anything.",
"You don't see a thing. You feel around, managing to bump your fingers hard against something. Ouch!",
"You don't see a thing! Blindly grasping the air around you, you find nothing.",
"It's totally dark here. You almost stumble over some un-evenness in the ground.",
"You are completely blind. For a moment you think you hear someone breathing nearby ... "
"\n ... surely you must be mistaken.",
"Blind, you think you find some sort of object on the ground, but it turns out to be just a stone.",
"Blind, you bump into a wall. The wall seems to be covered with some sort of vegetation,"
" but its too damp to burn.",
"You can't see anything, but the air is damp. It feels like you are far underground.")
ALREADY_LIGHTSOURCE = "You don't want to stumble around in blindness anymore. You already " \
"found what you need. Let's get light already!"
FOUND_LIGHTSOURCE = "Your fingers bump against a splinter of wood in a corner." \
" It smells of resin and seems dry enough to burn! " \
"You pick it up, holding it firmly. Now you just need to" \
" |wlight|n it using the flint and steel you carry with you."
class CmdLookDark(Command):
"""
Look around in darkness
Usage:
look
Look around in the darkness, trying
to find something.
"""
key = "look"
aliases = ["l", 'feel', 'search', 'feel around', 'fiddle']
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""
Implement the command.
This works both as a look and a search command; there is a
random chance of eventually finding a light source.
"""
caller = self.caller
if random.random() < 0.8:
# we don't find anything
caller.msg(random.choice(DARK_MESSAGES))
else:
# we could have found something!
if any(obj for obj in caller.contents if utils.inherits_from(obj, LightSource)):
# we already carry a LightSource object.
caller.msg(ALREADY_LIGHTSOURCE)
else:
# don't have a light source, create a new one.
create_object(LightSource, key="splinter", location=caller)
caller.msg(FOUND_LIGHTSOURCE)
class CmdDarkHelp(Command):
"""
Help command for the dark state.
"""
key = "help"
locks = "cmd:all()"
help_category = "TutorialWorld"
def func(self):
"""
Replace the the help command with a not-so-useful help
"""
string = "Can't help you until you find some light! Try looking/feeling around for something to burn. " \
"You shouldn't give up even if you don't find anything right away."
self.caller.msg(string)
class CmdDarkNoMatch(Command):
"""
This is a system command. Commands with special keys are used to
override special sitations in the game. The CMD_NOMATCH is used
when the given command is not found in the current command set (it
replaces Evennia's default behavior or offering command
suggestions)
"""
key = syscmdkeys.CMD_NOMATCH
locks = "cmd:all()"
def func(self):
"""Implements the command."""
self.caller.msg("Until you find some light, there's not much you can do. Try feeling around.")
class DarkCmdSet(CmdSet):
"""
Groups the commands of the dark room together. We also import the
default say command here so that players can still talk in the
darkness.
We give the cmdset the mergetype "Replace" to make sure it
completely replaces whichever command set it is merged onto
(usually the default cmdset)
"""
key = "darkroom_cmdset"
mergetype = "Replace"
priority = 2
def at_cmdset_creation(self):
"""populate the cmdset."""
self.add(CmdTutorial())
self.add(CmdLookDark())
self.add(CmdDarkHelp())
self.add(CmdDarkNoMatch())
self.add(default_cmds.CmdSay)
class DarkRoom(TutorialRoom):
"""
A dark room. This tries to start the DarkState script on all
objects entering. The script is responsible for making sure it is
valid (that is, that there is no light source shining in the room).
The is_lit Attribute is used to define if the room is currently lit
or not, so as to properly echo state changes.
Since this room (in the tutorial) is meant as a sort of catch-all,
we also make sure to heal characters ending up here, since they
may have been beaten up by the ghostly apparition at this point.
"""
def at_object_creation(self):
"""
Called when object is first created.
"""
super(DarkRoom, self).at_object_creation()
self.db.tutorial_info = "This is a room with custom command sets on itself."
# the room starts dark.
self.db.is_lit = False
self.cmdset.add(DarkCmdSet, permanent=True)
def at_init(self):
"""
Called when room is first recached (such as after a reload)
"""
self.check_light_state()
def _carries_light(self, obj):
"""
Checks if the given object carries anything that gives light.
Note that we do NOT look for a specific LightSource typeclass,
but for the Attribute is_giving_light - this makes it easy to
later add other types of light-giving items. We also accept
if there is a light-giving object in the room overall (like if
a splinter was dropped in the room)
"""
return obj.is_superuser or obj.db.is_giving_light or any(o for o in obj.contents if o.db.is_giving_light)
def _heal(self, character):
"""
Heal a character.
"""
health = character.db.health_max or 20
character.db.health = health
def check_light_state(self, exclude=None):
"""
This method checks if there are any light sources in the room.
If there isn't it makes sure to add the dark cmdset to all
characters in the room. It is called whenever characters enter
the room and also by the Light sources when they turn on.
Args:
exclude (Object): An object to not include in the light check.
"""
if any(self._carries_light(obj) for obj in self.contents if obj != exclude):
self.locks.add("view:all()")
self.cmdset.remove(DarkCmdSet)
self.db.is_lit = True
for char in (obj for obj in self.contents if obj.has_account):
# this won't do anything if it is already removed
char.msg("The room is lit up.")
else:
# noone is carrying light - darken the room
self.db.is_lit = False
self.locks.add("view:false()")
self.cmdset.add(DarkCmdSet, permanent=True)
for char in (obj for obj in self.contents if obj.has_account):
if char.is_superuser:
char.msg("You are Superuser, so you are not affected by the dark state.")
else:
# put players in darkness
char.msg("The room is completely dark.")
def at_object_receive(self, obj, source_location):
"""
Called when an object enters the room.
"""
if obj.has_account:
# a puppeted object, that is, a Character
self._heal(obj)
# in case the new guy carries light with them
self.check_light_state()
def at_object_leave(self, obj, target_location):
"""
In case people leave with the light, we make sure to clear the
DarkCmdSet if necessary. This also works if they are
teleported away.
"""
# since this hook is called while the object is still in the room,
# we exclude it from the light check, to ignore any light sources
# it may be carrying.
self.check_light_state(exclude=obj)
# Teleport room - puzzles solution
# This is a sort of puzzle room that requires a certain
# attribute on the entering character to be the same as
# an attribute of the room. If not, the character will
# be teleported away to a target location. This is used
# by the Obelisk - grave chamber puzzle, where one must
# have looked at the obelisk to get an attribute set on
# oneself, and then pick the grave chamber with the
# matching imagery for this attribute.
class TeleportRoom(TutorialRoom):
"""
Teleporter - puzzle room.
Important attributes (set at creation):
puzzle_key - which attr to look for on character
puzzle_value - what char.db.puzzle_key must be set to
success_teleport_to - where to teleport in case if success
<API key> - message to echo while teleporting to success
failure_teleport_to - where to teleport to in case of failure
<API key> - message to echo while teleporting to failure
"""
def at_object_creation(self):
"""Called at first creation"""
super(TeleportRoom, self).at_object_creation()
# what character.db.puzzle_clue must be set to, to avoid teleportation.
self.db.puzzle_value = 1
# target of successful teleportation. Can be a dbref or a
# unique room name.
self.db.<API key> = "You are successful!"
self.db.success_teleport_to = "treasure room"
# the target of the failure teleportation.
self.db.<API key> = "You fail!"
self.db.failure_teleport_to = "dark cell"
def at_object_receive(self, character, source_location):
"""
This hook is called by the engine whenever the player is moved into
this room.
"""
if not character.has_account:
# only act on player characters.
return
# determine if the puzzle is a success or not
is_success = str(character.db.puzzle_clue) == str(self.db.puzzle_value)
teleport_to = self.db.success_teleport_to if is_success else self.db.failure_teleport_to
# note that this returns a list
results = search_object(teleport_to)
if not results or len(results) > 1:
# we cannot move anywhere since no valid target was found.
character.msg("no valid teleport target for %s was found." % teleport_to)
return
if character.is_superuser:
# superusers don't get teleported
character.msg("Superuser block: You would have been teleported to %s." % results[0])
return
# perform the teleport
if is_success:
character.msg(self.db.<API key>)
else:
character.msg(self.db.<API key>)
# teleport quietly to the new place
character.move_to(results[0], quiet=True, move_hooks=False)
# we have to call this manually since we turn off move_hooks
# - this is necessary to make the target dark room aware of an
# already carried light.
results[0].at_object_receive(character, self)
# Outro room - unique exit room
# Cleans up the character from all tutorial-related properties.
class OutroRoom(TutorialRoom):
"""
Outro room.
Called when exiting the tutorial, cleans the
character of tutorial-related attributes.
"""
def at_object_creation(self):
"""
Called when the room is first created.
"""
super(OutroRoom, self).at_object_creation()
self.db.tutorial_info = "The last room of the tutorial. " \
"This cleans up all temporary Attributes " \
"the tutorial may have assigned to the "\
"character."
def at_object_receive(self, character, source_location):
"""
Do cleanup.
"""
if character.has_account:
del character.db.health_max
del character.db.health
del character.db.last_climbed
del character.db.puzzle_clue
del character.db.combat_parry_mode
del character.db.<API key>
for obj in character.contents:
if obj.typeclass_path.startswith("evennia.contrib.tutorial_world"):
obj.delete()
character.tags.clear(category="tutorial_world")
|
<?php
namespace asdfstudio\admin\helpers;
use Yii;
use asdfstudio\admin\Module;
use asdfstudio\admin\base\Admin;
use yii\db\ActiveRecord;
class AdminHelper
{
/**
* @param string $entity Admin class name or Id
* @return Admin|null
*/
public static function getEntity($entity)
{
/* @var Module $module */
$module = Yii::$app->controller->module;
if (isset($module->entities[$entity])) {
return $module->entities[$entity];
} elseif (isset($module->entitiesClasses[$entity])) {
return static::getEntity($module->entitiesClasses[$entity]);
}
return null;
}
/**
* Return value of nested attribute.
*
* ```php
* // e.g. $post is Post model. We need to get a name of owmer. Owner is related model.
*
* AdminHelper::resolveAttribute('owner.username', $post); // it returns username from owner attribute
* ```
*
* @param string $attribute
* @param ActiveRecord $model
* @return string
*/
public static function resolveAttribute($attribute, $model)
{
$path = explode('.', $attribute);
$attr = $model;
foreach ($path as $a) {
$attr = $attr->{$a};
}
return $attr;
}
}
|
#include <core/Runtime.h>
#include <stdlib.h>
#include <math.h>
int runtime_f32_mul(Stack stack)
{
Value* operand1 = NULL;
Value* operand2 = NULL;
pop_Value(stack, &operand2);
pop_Value(stack, &operand1);
if(isnan(operand1->value.f32) || isnan(operand2->value.f32)) {
push_Value(stack, new_f32Value(nanf("")));
} else if(isinf(operand1->value.f32) || isinf(operand2->value.f32)) {
if(operand1->value.f32 == 0 || operand2->value.f32 == 0) {
push_Value(stack, new_f32Value(nanf("")));
} else if(signbit(operand1->value.f32) ^ signbit(operand2->value.f32)) {
push_Value(stack, new_f32Value(-strtof("INF", NULL)));
} else {
push_Value(stack, new_f32Value(strtof("INF", NULL)));
}
} else if(operand1->value.f32 == 0 && operand2->value.f32 == 0) {
if(signbit(operand1->value.f32) ^ signbit(operand2->value.f32)) {
push_Value(stack, new_f32Value(-0.0f));
} else {
push_Value(stack, new_f32Value(+0.0f));
}
} else {
push_Value(stack, new_f32Value(operand1->value.f32 * operand2->value.f32));
}
free_Value(operand1);
free_Value(operand2);
return 0;
}
|
package com.logicalpractice.collections;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.* ;
import org.junit.Test;
public class ExpressionTest {
@Test
public void script1() throws Exception {
Person billy = new Person("Billy", "Smith");
Expression<Person,String> testObject = new Expression<Person,String>(){{
each(Person.class).getFirstName();
}};
String result = testObject.apply(billy);
assertThat(result, equalTo("Billy"));
}
}
|
<?php
declare(strict_types=1);
namespace LizardsAndPumpkins\Context\Country;
use LizardsAndPumpkins\Context\ContextPartBuilder;
class <API key> implements ContextPartBuilder
{
private $defaultCountryCode = 'DE';
/**
* @param mixed[] $inputDataSet
* @return string
*/
public function getValue(array $inputDataSet) : string
{
if (isset($inputDataSet[Country::CONTEXT_CODE])) {
return (string) $inputDataSet[Country::CONTEXT_CODE];
}
return $this->defaultCountryCode;
}
public function getCode() : string
{
return Country::CONTEXT_CODE;
}
}
|
const initialState = {
country: 'es',
language: 'es-ES'
}
const settings = (state = initialState, action) => {
switch (action.type) {
default:
return state
}
}
export default settings
|
<?php
// This is the configuration for yiic console application.
// Any writable CConsoleApplication properties can be configured here.
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'My Console Application',
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
),
// preloading 'log' component
'preload'=>array('log'),
// application components
'components'=>array(
// database settings are configured in database.php
'db'=>require(dirname(__FILE__).'/database.php'),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
),
),
),
);
|
#based on SilkJS Makefile
ARCH := $(shell getconf LONG_BIT)
COREMQ= mqdb.o
OBJ=
HMQ = include/lru_cache/lru_cache.h include/lru_cache/scoped_mutex.h fstools.cc
CORECL= client.o
OBJ=
V8DIR= ./v8-read-only
V8LIB_64 := $(V8DIR)/out/x64.release/obj.target/tools/gyp
V8LIB_32 := $(V8DIR)/out/ia32.release/obj.target/tools/gyp
V8LIB_DIR := $(V8LIB_$(ARCH))
V8VERSION_64 := x64.release
V8VERSION_32 := ia32.release
V8VERSION := $(V8VERSION_$(ARCH))
V8= $(V8LIB_DIR)/libv8_base.a $(V8LIB_DIR)/libv8_snapshot.a
CFLAGS = -O6 -fomit-frame-pointer -fdata-sections -ffunction-sections -fno-strict-aliasing -fno-rtti -fno-exceptions -fvisibility=hidden -Wall -W -<API key> -Wnon-virtual-dtor -m$(ARCH) -O3 -fomit-frame-pointer -fdata-sections -ffunction-sections -ansi -fno-strict-aliasing -fexceptions
all: mqdb client mqdb2 tasksink taskvent taskvs asclient
%.o: %.cpp Makefile
g++ $(CFLAGS) -c -I./include -I$(V8DIR)/include -g -o $*.o $*.cpp
mqdb: $(V8) $(COREMQ) $(OBJ) $(HMQ) Makefile
g++ $(CFLAGS) -I./include -I$(V8DIR)/include -o mqdb mqdb.cpp -L$(V8LIB_DIR)/ -L./leveldb/ -lv8_base -lv8_snapshot -lmm -lpthread -lzmq -lleveldb
#-lgd
client: $(V8) $(CORECL) $(OBJ) Makefile
g++ $(CFLAGS) -o client $(CORECL) $(OBJ) -L$(V8LIB_DIR)/ -lmm -lpthread -lzmq
$(V8):
cd $(V8DIR) && make dependencies && GYP_GENERATORS=make make $(V8VERSION)
update:
cd $(V8DIR) && svn update && make dependencies && GYP_GENERATORS=make make $(V8VERSION)
git pull
|
// All right reserved.
// Authors: Justin Madsen
// model a single track chain system, as part of a tracked vehicle.
// TODO: read in subsystem data w/ JSON input files
#include <cstdio>
#include <sstream>
#include "subsys/trackSystem/TrackSystem.h"
namespace chrono {
// Static variables
// idler, right side
const ChVector<> TrackSystem::m_idlerPos(-2.1904, -0.1443, 0.2447); // relative to local csys
const ChQuaternion<> TrackSystem::m_idlerRot(QUNIT);
// drive gear, right side
const ChVector<> TrackSystem::m_gearPos(1.7741, -0.0099, 0.2447); // relative to local csys
const ChQuaternion<> TrackSystem::m_gearRot(QUNIT);
// suspension
const int TrackSystem::m_numSuspensions = 5;
TrackSystem::TrackSystem(const std::string& name, int track_idx, const double idler_preload)
: m_track_idx(track_idx), m_name(name), m_idler_preload(idler_preload) {
// FILE* fp = fopen(filename.c_str(), "r");
// char readBuffer[65536];
// fclose(fp);
Create(track_idx);
}
// Create: 1) load/set the subsystem data, resize vectors 2) BuildSubsystems()
// TODO: replace hard-coded junk with JSON input files for each subsystem
void TrackSystem::Create(int track_idx) {
/*
// read idler info
assert(d.HasMember("Idler"));
m_idlerMass = d["Idler"]["Mass"].GetDouble();
m_idlerPos = loadVector(d["Idler"]["Location"]);
m_idlerInertia = loadVector(d["Idler"]["Inertia"]);
m_idlerRadius = d["Spindle"]["Radius"].GetDouble();
m_idlerWidth = d["Spindle"]["Width"].GetDouble();
m_idler_K = d["Idler"]["SpringK"].GetDouble();
m_idler_C = d["Idler"]["SpringC"].GetDouble();
*/
/*
// Read Drive Gear data
assert(d.HasMember("Drive Gear"));
assert(d["Drive Gear"].IsObject());
m_gearMass = d["Drive Gear"]["Mass"].GetDouble();
m_gearPos = loadVector(d["Drive Gear"]["Location"]);
m_gearInertia = loadVector(d["Drive Gear"]["Inertia"]);
m_gearRadius = d["Drive Gear"]["Radius"].GetDouble();
m_gearWidth = d["Drive Gear"]["Width"].GetDouble();
// Read Suspension data
assert(d.HasMember("Suspension"));
assert(d["Suspension"].IsObject());
assert(d["Suspension"]["Location"].IsArray() );
<API key> = d["Suspension"]["Input File"].GetString();
m_NumSuspensions = d["Suspension"]["Location"].Size();
*/
m_suspensions.resize(m_numSuspensions);
m_suspensionLocs.resize(m_numSuspensions);
// hard-code positions relative to trackSystem csys. Start w/ one nearest sprocket
m_suspensionLocs[0] = ChVector<>(1.3336, 0, 0);
m_suspensionLocs[1] = ChVector<>(0.6668, 0, 0);
// trackSystem c-sys aligned with middle suspension subsystem arm/chassis revolute constraint position
m_suspensionLocs[2] = ChVector<>(0, 0, 0);
m_suspensionLocs[3] = ChVector<>(-0.6682, 0, 0);
m_suspensionLocs[4] = ChVector<>(-1.3368, 0, 0);
/*
for(int j = 0; j < m_numSuspensions; j++)
{
m_suspensionLocs[j] = loadVector(d["Suspension"]["Locaiton"][j]);
}
// Read Track Chain data
assert(d.HasMember("Track Chain"));
assert(d["Track Chain"].IsObject());
<API key> = d["Track Chain"]["Input File"].GetString()
*/
// create the various subsystems, from the hardcoded static variables in each subsystem class
BuildSubsystems();
}
void TrackSystem::BuildSubsystems() {
std::stringstream gearName;
gearName << "drive gear " << m_track_idx;
// build one of each of the following subsystems. VisualizationType and CollisionType defaults are PRIMITIVES
m_driveGear = ChSharedPtr<DriveGear>(new DriveGear(gearName.str(), VisualizationType::Mesh,
// CollisionType::Primitives) );
// VisualizationType::Primitives,
CollisionType::CallbackFunction));
std::stringstream idlerName;
idlerName << "idler " << m_track_idx;
m_idler =
ChSharedPtr<IdlerSimple>(new IdlerSimple(idlerName.str(), VisualizationType::Mesh, CollisionType::Primitives));
std::stringstream chainname;
chainname << "chain " << m_track_idx;
m_chain = ChSharedPtr<TrackChain>(new TrackChain(chainname.str(),
// VisualizationType::Primitives,
VisualizationType::CompoundPrimitives, CollisionType::Primitives));
// CollisionType::CompoundPrimitives) );
// build suspension/road wheel subsystems
for (int i = 0; i < m_numSuspensions; i++) {
std::stringstream susp_name;
susp_name << "suspension " << i << ", chain " << m_track_idx;
m_suspensions[i] = ChSharedPtr<<API key>>(
new <API key>(susp_name.str(), VisualizationType::Primitives, CollisionType::Primitives,
0, i ));
}
}
void TrackSystem::Initialize(ChSharedPtr<ChBodyAuxRef> chassis,
const ChVector<>& local_pos,
ChTrackVehicle* vehicle,
double pin_damping) {
m_local_pos = local_pos;
m_gearPosRel = m_gearPos;
m_idlerPosRel = m_idlerPos;
// if we're on the left side of the vehicle, switch lateral z-axis on all relative positions
if (m_local_pos.z < 0) {
m_gearPosRel.z *= -1;
m_idlerPosRel.z *= -1;
}
// Create list of the center location of the rolling elements and their clearance.
// Clearance is a sphere shaped envelope at each center location, where it can
// be guaranteed that the track chain geometry will not penetrate the sphere.
std::vector<ChVector<> > rolling_elem_locs; // w.r.t. chassis ref. frame
std::vector<double> clearance; // 1 per rolling elem
std::vector<ChVector<> > <API key>; /// w.r.t. abs. frame
// initialize 1 of each of the following subsystems.
// will use the chassis ref frame to do the transforms, since the TrackSystem
// local ref. frame has same rot (just difference in position)
// NOTE: move drive Gear Init() AFTER the chain of shoes is created, since
// need the list of shoes to be passed in to create custom collision w/ gear
// HOWEVER, still add the info to the rolling element lists passed into TrackChain Init().
// drive sprocket is First added to the lists passed into TrackChain Init()
rolling_elem_locs.push_back(m_local_pos + Get_gearPosRel());
clearance.push_back(m_driveGear->GetRadius());
<API key>.push_back(m_driveGear->GetBody()->GetRot().GetZaxis());
// initialize the torsion arm suspension subsystems
for (int s_idx = 0; s_idx < m_suspensionLocs.size(); s_idx++) {
m_suspensions[s_idx]->Initialize(chassis, chassis->GetFrame_REF_to_abs(),
ChCoordsys<>(m_local_pos + m_suspensionLocs[s_idx], QUNIT));
// add to the lists passed into the track chain, find location of each wheel center w.r.t. chassis coords.
rolling_elem_locs.push_back(m_local_pos + m_suspensionLocs[s_idx] + m_suspensions[s_idx]->GetWheelPosRel());
clearance.push_back(m_suspensions[s_idx]->GetWheelRadius());
<API key>.push_back(m_suspensions[s_idx]->GetWheelBody()->GetRot().GetZaxis());
}
// last control point: the idler body
m_idler->Initialize(chassis, chassis->GetFrame_REF_to_abs(),
ChCoordsys<>(m_local_pos + Get_idlerPosRel(), Q_from_AngAxis(CH_C_PI, VECT_Z)),
m_idler_preload);
// add to the lists passed into the track chain Init()
rolling_elem_locs.push_back(m_local_pos + Get_idlerPosRel());
clearance.push_back(m_idler->GetRadius());
<API key>.push_back(m_idler->GetBody()->GetRot().GetZaxis());
// After all rolling elements have been initialized, now able to setup the TrackChain.
// Assumed that start_pos is between idler and gear control points, e.g., on the top
// of the track chain.
ChVector<> start_pos = (rolling_elem_locs.front() + rolling_elem_locs.back()) / 2.0;
start_pos.y += (clearance.front() + clearance.back()) / 2.0;
// Assumption: start_pos should lie close to where the actual track chain would
// pass between the idler and driveGears.
// MUST be on the top part of the chain so the chain wrap rotation direction can be assumed.
m_chain->Initialize(chassis, chassis->GetFrame_REF_to_abs(), rolling_elem_locs, clearance, <API key>,
start_pos);
// add some initial damping to the inter-shoe pin joints
if (pin_damping > 0)
m_chain->Set_pin_friction(pin_damping);
// chain of shoes available for gear init
m_driveGear->Initialize(chassis, chassis->GetFrame_REF_to_abs(),
ChCoordsys<>(m_local_pos + Get_gearPosRel(), QUNIT), m_chain->GetShoeBody(), vehicle);
}
const ChVector<> TrackSystem::<API key>() {
return m_idler->m_shock->Get_react_force();
}
} // end namespace chrono
|
# eXist Book Example Code
[) of the
code and examples discussed in the [eXist book](http://shop.oreilly.com/product/0636920026525.do) published by O'Reilly.
This version contains code compatible with eXist-db 2.1 which was the latest version at the time the book was authored. Versions for eXist-db [3.0.RC1](https:
The repository has the following layout:
* [chapters/](https://github.com/eXist-book/book-code/tree/master/chapters)
Under this folder each chapter of the book that has example code is represented.
* [xml-examples-xar/](https://github.com/eXist-book/book-code/tree/master/xml-examples-xar)
These are the files needed to build an EXPath Package XAR from other files distributed
in the chapters folders. In particular the content of the XAR package is assembled using
the the `fileSet`s set out in the assembly [xml-examples-xar/expath-pkg.assembly.xml](https://github.com/eXist-book/book-code/blob/master/xml-examples-xar/expath-pkg.assembly.xml)
All other files are related to the Maven build process.
Building
=====
The EXPath Package XAR and the Java projects are all built using Apache Maven. You will need to have Git and at least Maven 3.1.1
installed. Git can be downloaded and installed from http:
Once you have Maven installed you can simply run the following from your Unix/Linux/Mac terminal or Windows command prompt:
bash
git clone https://github.com/eXist-book/book-code.git
cd book-code
mvn clean install
You should then find the EXPath PKG XAR located at `xml-examples-xar/target/exist-book.xar`. The Java projects artifacts will be located within the `target` sub-folders
of each Java project respectively.
|
<?php
// uncomment the following to define a path alias
// Yii::setPathOfAlias('local','path/to/local-folder');
// This is the main Web application configuration. Any writable
// CWebApplication properties can be configured here.
return array(
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'Plataforma LAEL',
'language'=>'es',
'sourceLanguage'=>'en',
'charset'=>'utf-8',
'theme'=>'classic',
// preloading 'log' component
'preload'=>array('log'),
// autoloading model and component classes
'import'=>array(
'application.models.*',
'application.components.*',
),
'modules'=>array(
// uncomment the following to enable the Gii tool
/*
'gii'=>array(
'class'=>'system.gii.GiiModule',
'password'=>'Enter Your Password Here',
// If removed, Gii defaults to localhost only. Edit carefully to taste.
'ipFilters'=>array('127.0.0.1','::1'),
),
*/
),
// application components
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
// uncomment the following to enable URLs in path-format
/*
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
),
*/
'db'=>array(
'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',
),
// uncomment the following to use a MySQL database
/*
'db'=>array(
'connectionString' => 'mysql:host=localhost;dbname=testdrive',
'emulatePrepare' => true,
'username' => 'root',
'password' => '',
'charset' => 'utf8',
),
*/
'errorHandler'=>array(
// use 'site/error' action to display errors
'errorAction'=>'site/error',
),
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'levels'=>'error, warning',
),
// uncomment the following to show log messages on web pages
/*
array(
'class'=>'CWebLogRoute',
),
*/
),
),
),
// application-level parameters that can be accessed
// using Yii::app()->params['paramName']
'params'=>array(
// this is used in contact page
'adminEmail'=>'webmaster@example.com',
),
);
|
# $FreeBSD: releng/9.3/sys/modules/drm2/radeonkmsfw/R300_cp/Makefile 254885 2013-08-25 19:37:15Z dumbbell $
KMOD= radeonkmsfw_R300_cp
IMG= R300_cp
.include <bsd.kmod.mk>
|
/*
* Required libraries
*
* You will need these libraries to interface with the services and hardware.
*/
var MRAA = require('mraa'); //require MRAA for communicating with hardware pins
var LCD = require('jsupm_i2clcd'); //require LCD libraries for signaling the LCD screen
var LED = require('jsupm_grove'); //require SEEED Grove library for photoresister
var BUZZ = require("jsupm_buzzer"); //require SEEED Grove library for buzzer
var MAILER = require('nodemailer'); //require for sending emails over SMTP
var NET = require('net'); //require for sending cloud data to Edison service on TCP
/**
* Change the constants properties to customize the operation of the TEETH Smart Toothbrush Timer
* @global
*/
var constants = {
'LOG_LEVEL': 3, //Change this value to limit loggin output: 0-none, 1-err, 2-warn, 3-info, 4-debug, 5-all
'USE_SOUND': true,
'PINS': { //Change these values to match the pins on your Edison build
'brushSwitch': [8, 4], //digital pins monitoring switches for toothbrushes
'buzzer': 3, //digital pin for signaling the buzzer
'roomLightSensor': 0, //analog pin for getting room light readings from photoresister on 10K external pullup
'roomLightThreshold' : 80 //value that indicates that room is dark
},
'MAIL': { //Change these values based on documentation at nodemailer to use your SMTP account
'service': 'Gmail', //Account service name, ex. "Gmail"
'user': 'your.name@gmail.com', //user name to login to your service
'pass': 'pass****', //password to login to your service
'from': 'TEETH <teeth@server.com>', //appears in the "From:" section of your emails
'brushTo': ['brush.1@gmail.com', 'brush.2@gmail.com'], //email value for each toothbrush
'subject': 'Great job on TEETH!', //appears as the subject of your emails
'body': 'You met the goal today. Way to go!' //the body text of your emails
},
'METRICS': { //Change these values to match the custom components of your Intel Cloud Analytics
'brushComponent': ['brush1', 'brush2'] //component value for each toothbrush
},
'SCREEN_MSG': { //Messages that appear on the LCD screen during the timer prep and countdown
'ready': '...get ready', //message to display during start of prep time
'set': '.....get set', //message to display last five seconds of prep time
'countdown': 'Countdown:', //message to display during countdown
'percent25': '...almost there!', //message to display 25% of the way through countdown
'percent50': 'good...halfway ', //message to display 50% of the way through countdown
'percent75': 'you\'re doing it ', //message to display 75% of the way through countdown
'finish': 'GREAT JOB!', //message to display at the end of countdown
'brushName': ['Nathan', 'Sarah'] //name to display during countdwon, one value for each toothbrush
},
'TIME': { //Time focused constants for timer, buzzer sounds
'brushPreptime': [10, 30], //seconds of prep time for each toothbrush
'brushGoaltime': [30, 120], //seconds of countdown time for each toothbrush
'buzzDuration': 20, //milliseconds of buzzer time for start and stop sounds
'buzzInterval': 150 //milliseconds between buzzer sounds for start and stop signals
},
'COLOR': { //Colors to use on the LCD screen
'off': [ 0, 0, 0], //black - use when LCD is off
'ready': [100, 100, 100], //light grey - use during prep time
'percent0': [255, 68, 29], //red - use at start of countdown
'percent25': [232, 114, 12], //brown - use when countdown is 25% finished
'percent50': [255, 179, 0], //orange - use when countdown is 50% finished
'percent75': [232, 211, 12], //yellow - use when countdown is 75% finished
'finish': [ 89, 132, 13], //green - use when countdown is finished
'colorFadeDuration': 1000, //milliseconds to fade to new color during countdown mode
'fadeSteps': 100 //number of fading steps to take during colorFadeDuration
}
};
/**
* These values hold the setTimeout and setInterval handles so they can be cleared as part of a timer interuption
* @global
*/
var timers = {
'fadeColor': null, //timer fading the color on the LCD screen
'buzzerPlay': null, //timer playing the buzzer sounds
'buzzerWait': null, //timer waiting in between buzzer sounds
'prepCountdown': null, //timer for the main prep time
'startCountdown': null, //timer for the last five seconds of prep time
'countdown': null, //timer for the main countdown
'lightsOut': null //timer lookin for "lights out" interuption
};
/**
* Creates a new Logger object and the helper methods used to send messages to console.
* Highest level of logging, ERR (1), only outputs errors during code execution.
* Lowest level DEBUG (4) outputs all logging messages.
*
* @see constants.LOG_LEVEL Use the constant constants.LOG_LEVEL to adjust the level of output.
* @class
*/
var Logger = function () {
this.ERR = 1;
this.WARN = 2;
this.INFO = 3;
this.DEBUG = 4;
/**
* @private
*/
var logLevels = ['', 'err', 'warn', 'info', 'debug'];
/**
* @param {string} msg message to send to logger
* @param {int} level log level for this message
* @public
*/
this.it = function (msg, level) {
if (constants.LOG_LEVEL >= level || level === undefined) {
console.log('%s - %s: %s', new Date(), logLevels[level], msg);
}
};
/*
* @param {string} msg message to send to logger at log level ERR (1)
* @public
*/
this.err = function (msg) {
this.it(msg, this.ERR);
};
/*
* @param {string} msg message to send to logger at log level WARN (2)
* @public
*/
this.warn = function (msg) {
this.it(msg, this.WARN);
};
/*
* @param {string} msg message to send to logger at log level INFO (3)
* @public
*/
this.info = function (msg) {
this.it(msg, this.INFO);
};
/*
* @param {string} msg message to send to logger at log level DEBUG (4)
* @public
*/
this.debug = function (msg) {
this.it(msg, this.DEBUG);
};
};
/**
* Creates a new Sensors object to monitor the hardware connected to the Edison
* @requires mraa:Gpio
* @requires mraa:Aio
* @param {Logger} log object for logging output
* @see constants.PINS Use the constant constants.PINS to identify the hardware connections
* @class
*/
var Sensors = function (log) {
log.info('instatiate Sensors');
/**
* @private
*/
var i;
/**
* the array of switches associated with each toothbrush are initialized
* as INPUT pins during instatiation.
* @public
*/
this.brushSwitch = [];
for (i = 0; i < constants.PINS.brushSwitch.length; i = i + 1) {
this.brushSwitch[i] = new MRAA.Gpio(constants.PINS.brushSwitch[i]);
this.brushSwitch[i].dir(MRAA.DIR_IN);
}
/**
* the analog pin for monitoring the phototransister is initialized
* during instatiation. Expected that this photo cell will have a 10K
* external pulldown resistor.
* @public
*/
// this.roomLightSensor = new MRAA.Aio(constants.PINS.roomLightSensor);
};
/**
* Creates a new Buzzer object to play a sound on the buzzer connected to the Edison
* @requires jsupm_buzzer:Buzzer
* @param {Logger} log object for logging output
* @see constants.TIME Use the properties of constants.TIME to adjust the buzzer sounds
* @class
*/
var Buzzer = function (log) {
log.info('instatiate Buzzer');
var buzzer = new BUZZ.Buzzer(constants.PINS.buzzer);
/**
* play calls the playSound method of the low-level buzzer class for a simple tone value
* @private
*/
function play(buzzingTime) {
log.debug('(buzzer.play for ' + buzzingTime + ')');
if (!constants.USE_SOUND) {
return;
}
buzzer.playSound(BUZZ.DO, 5000);
timers.buzzerPlay = setTimeout(function () {
buzzer.playSound(BUZZ.DO, 0);
}, buzzingTime);
}
/**
* plays the standard sound for the buzz duration, then waits, and plays again
* expected to be called at the beginning of the countdown
* @public
*/
this.playStartSound = function () {
log.info('buzzer.playStartSound');
play(constants.TIME.buzzDuration);
timers.buzzerWait = setTimeout(function () {
play(constants.TIME.buzzDuration);
}, constants.TIME.buzzInterval);
};
/**
* plays the standard sound for the buzz duration, then waits, and plays again
* expected to be called at the end of the countdown
* @public
*/
this.playStopSound = function () {
log.info('buzzer.playStopSound');
play(constants.TIME.buzzDuration);
timers.buzzerWait = setTimeout(function () {
play(constants.TIME.buzzDuration);
}, constants.TIME.buzzInterval);
};
};
/**
* Creates a new Screen object to display messages and colors RGB LCD connected to the Edison over I2C
* @requires jsupm_i2clcd:Jhd1313m1
* @param {Logger} log object for logging output
* @see constants.COLOR Use the properties of constants.COLOR to adjust the screen background colors
* @see constants.SCREEN_MSG Use the properties of constants.SCREEN_MSG to change the messages displayed on screen
* @class
*/
var Screen = function (log) {
log.info('instatiate Screen');
/**
* Instance variables to connect to LCD screen and manage the color fading
* @private
*/
var lcd = new LCD.Jhd1313m1(6, 0x3E, 0x62), //standard I2C bus
interval = constants.COLOR.colorFadeDuration / constants.COLOR.fadeSteps,
lastColor = constants.COLOR.off,
steps = constants.COLOR.fadeSteps;
/**
* getRemainingSteps identifies how many more steps are needed before fade is finished
* @returns {int} number of steps remaining
* @private
*/
function getRemainingSteps() {
log.debug('(screen.getRemainingSteps)');
return steps;
}
/**
* setRemainingSteps sets how many more steps are needed before fade is finished
* @params {int} remainingSteps new number of steps remaining
* @private
*/
function setRemainingSteps(remainingSteps) {
log.debug('(screen.setRemainingSteps: ' + remainingSteps + ')');
steps = remainingSteps;
}
/**
* setScreen color calls low-level methods to set RGB values of screen background
* also sets the instance variable "lastColor" to help with fade control
* @param {array} colorArray array of decimal color values in Red Green Blue order [r,g,b]
* @private
*/
function setScreenColor(colorArray) {
log.debug('(screen.setScreenColor to ' + colorArray + ')');
lcd.setColor(colorArray[0], colorArray[1], colorArray[2]);
lastColor = colorArray;
}
/**
* Inner method called by timeouts to fade background color from current color to the
* updated color passed RGB color array
* @private
*/
function _fadeColor(colorArray) {
log.debug('(screen._fadeColor: ' + colorArray + ')');
var step = getRemainingSteps();
if (step > 0) {
var diffRed = colorArray[0] - lastColor[0],
diffGrn = colorArray[1] - lastColor[1],
diffBlu = colorArray[2] - lastColor[2],
stepRed = parseInt(diffRed / step, 10),
stepGrn = parseInt(diffGrn / step, 10),
stepBlu = parseInt(diffBlu / step, 10),
nextRed = lastColor[0] + stepRed,
nextGrn = lastColor[1] + stepGrn,
nextBlu = lastColor[2] + stepBlu;
setScreenColor([nextRed, nextGrn, nextBlu]);
setRemainingSteps(step - 1);
timers.fadeColor = setTimeout(function () {
_fadeColor(colorArray);
}, interval);
}
}
/**
* Starts a timout sequence to slowy change the LCD RGB screen background from its current
* color to the one passed in the parameters. The speed and number of steps used for fading
* are controlled by the constants.
*
* @param {array} colorArray a 3-member array of decimal numbers describing the color to display
* on the screen background: [r,g,b]
* @public
*/
this.fadeColor = function (colorArray) {
log.info('screen.fadeColor: ' + colorArray);
setRemainingSteps(constants.COLOR.fadeSteps);
_fadeColor(colorArray);
};
/**
* Helper method combines clearing the screen of all text content and returning the cursor
* position back to the top left.
* @public
*/
this.reset = function () {
log.info('screen.reset');
lcd.clear();
lcd.setCursor(0, 0);
};
/**
* Helper method combines reseting the screen and returning the screen color to "off"
* @public
*/
this.resetAndTurnOff = function () {
log.info('screen.resetAndTurnOff');
this.reset();
setScreenColor(constants.COLOR.off);
};
/**
* Turns the screen on and displays the "ready" message defined in constants for the given toothbrush
*
* @param {int} componentIndex identifies the toothbrush by it's array index
* @public
*/
this.displayReady = function (componentIndex) {
log.info('screen.displayReady for ' + componentIndex);
lcd.clear();
setScreenColor(constants.COLOR.ready);
this.write(constants.SCREEN_MSG.brushName[componentIndex], 0, 0);
this.write(constants.SCREEN_MSG.ready, 1, 0);
};
/**
* Changes the "ready" message to the "set" message defined in constants for the given toothbrush
*
* @param {int} componentIndex identifies the toothbrush by it's array index
* @public
*/
this.displaySet = function (componentIndex) {
log.info('screen.displaySet for ' + componentIndex);
this.write(constants.SCREEN_MSG.set, 1, 0);
};
/**
* Helper message combines writing the given message to the screen at (optional) given coordinates
*
* @param {string} msg the string to ouput to the screen
* @param {int} col (optional) 0-indexed column number to set the cursor
* @param {int} row (optional) 0-indexed row number to set the cursor
* @public
*/
this.write = function (msg, col, row) {
//log.info('screen.write msg ' + msg);
var i;
if (!(col === undefined || row === undefined)) {
lcd.setCursor(col, row);
for (i = 0; i < 10000000; i = i + 1) {
//wait for slow LCD
}
}
lcd.write(msg);
};
//initialize the LCD screen during instatiation
this.resetAndTurnOff();
};
/**
* Creates a new Mailer object to send mail over SMTP
* @requires nodemailer
* @param {Logger} log object for logging output
* @see constants.MAIL Use the properties of constants.MAIL to configure your SMTP service
* @class
*/
var Mailer = function (log) {
log.info('instatiate Mailer');
/**
* Instance options taken from constants.MAIL are used by createTransport to authenticate SMTP
* @private
*/
var mailOptions = {
from: constants.MAIL.from, // sender address
to: constants.MAIL.brushTo[0], // list of receivers
subject: constants.MAIL.subject, // Subject line
text: constants.MAIL.body, // plaintext body
html: constants.MAIL.body // html body
},
transporter = MAILER.createTransport({
service: constants.MAIL.service,
auth: {
user: constants.MAIL.user,
pass: constants.MAIL.pass
}
});
/**
* Sends the message defined in constants.MAIL for the given toothbrush.
* Errors are sent to the log Logger object.
* @param {int} componentIndex identifies the toothbrush by it's array index in constants
* @public
*/
this.sendCongratsEmail = function (componentIndex) {
log.info('mailer.sendCongratsEmail for ' + componentIndex);
mailOptions.to = constants.MAIL.brushTo[componentIndex];
transporter.sendMail(mailOptions, function (error, info) {
if (error) {
log.err('mail error ' + error + '.');
} else {
log.info('mail sent.');
}
});
};
};
/**
* Creates a new Metrics object to connect to Intel Cloud Analytics over TCP
* @requires net:socket
* @param {Logger} log object for logging output
* @class
*/
var Metrics = function (log) {
log.info('instatiate metrics');
/**
* instance objects and options to connect over TCP to Edison iot-agent
* @private
*/
var client = new NET.Socket(),
options = {
host : 'localhost', //use the Intel analytics client running locally on the Edison
port : 7070 //on default TCP port
};
/**
* sendObservation concatenates the string expected by cloud analytics based on the parameter values
* @param {string} name custom component name registered with Intel analytics
* @param {float} value data value to send to cloud
* @private
*/
function sendObservation(name, value) {
log.debug('(metrics.sendObservation for ' + name + ', ' + value + ')');
var msg = JSON.stringify({
n: name,
v: value
}),
sentMsg = msg.length + "#" + msg; //syntax for Intel analytics
client.write(sentMsg);
}
/**
* Method combines the activity of connecting to the Edision service and then sending data to the cloud
* @param {int} itemIndex array index of component names registered with Intel analytics
* @param {float} timeValue data value to send to cloud, expecting fractional number of seconds
* @public
*/
this.addDataToCloud = function (itemIndex, timeValue) {
log.info('metrics.addDataToCloud for ' + itemIndex + ', ' + timeValue);
client.on('error', function () {
log.err('Could not connect to cloud');
});
client.connect(options.port, options.host, function () {
sendObservation(constants.METRICS.brushComponent[itemIndex], timeValue);
});
};
};
/**
* Creates a new Teeth object to manage the countdown timer
* @param {Logger} log object for logging output
* @param {Sensors} sensor object for listening to hardware sensors
* @param {Buzzer} buzzer object for controlling the sounds
* @param {Screen} screen object for display on the RGB LCD screen
* @param {Mailer} mailer object for sending email
* @param {Metrics} metrics object for sending data to cloud
* @see constants.TIME Use the properties of constants.TIME to adjust the length of the countdown
* @class
*/
var Teeth = function (log, sensors, buzzer, lcdScreen, mailer, metrics) {
log.info('instatiate teeth');
/**
* flags to make sure fadeColor only called once for each color
* @private
*/
var fades = [],
currentComponent = -1,
timeSpent = 0;
/**
* clearAllTimers loops through all timers in constants to clear them and set to null
* @private
*/
function clearAllTimers() {
log.debug('(teeth.clearAllTimers)');
var key,
timer;
for (key in timers) {
if (timers.hasOwnProperty(key)) {
timer = timers[key];
if (timer !== null) {
clearTimeout(timer);
timer = null;
}
}
}
fades = [];
currentComponent = -1;
}
/**
* finishCountdown clears the screen, plays the stop sound, and starts the waiting process again
* @param {int} componentIndex array index number of the toothbrush that is finishing the countdown
* @private
*/
function finishCountdown(componentIndex) {
log.debug('(teeth.finishCountdown for ' + componentIndex + ')');
clearAllTimers();
lcdScreen.reset();
buzzer.playStopSound();
mailer.sendCongratsEmail(componentIndex);
lcdScreen.write(constants.SCREEN_MSG.finish);
metrics.addDataToCloud(componentIndex, constants.TIME.brushGoaltime[componentIndex]);
setTimeout(function () {
lcdScreen.resetAndTurnOff();
wait();
}, 1000);
}
/**
* countdown generates messages and colors to the screen during the countdown,
* called continuously until time is over
* @param {int} componentIndex array index number of the toothbrush that is in the middle of the countdown
* @param {int} timeRemaining the amount of time remaining in seconds before the countdown is over
* @private
*/
function countdown(componentIndex, timeRemaining) {
log.debug('(teeth.countdown for ' + componentIndex + ': ' + timeRemaining + ')');
var originalValue = constants.TIME.brushGoaltime[componentIndex];
timeSpent = originalValue - timeRemaining;
if (timeRemaining > 0) {
lcdScreen.write(constants.SCREEN_MSG.countdown + timeRemaining + ' ', 0, 0);
if (timeRemaining <= (0.25 * originalValue)) {
lcdScreen.write(constants.SCREEN_MSG.percent25, 1, 0);
if (fades[constants.COLOR.percent25] !== 1) {
lcdScreen.fadeColor(constants.COLOR.percent25);
fades[constants.COLOR.percent25] = 1;
}
} else if (timeRemaining <= (0.5 * originalValue)) {
lcdScreen.write(constants.SCREEN_MSG.percent50, 1, 0);
if (fades[constants.COLOR.percent50] !== 1) {
lcdScreen.fadeColor(constants.COLOR.percent50);
fades[constants.COLOR.percent50] = 1;
}
} else if (timeRemaining <= (0.75 * originalValue)) {
lcdScreen.write(constants.SCREEN_MSG.percent75, 1, 0);
if (fades[constants.COLOR.percent75] !== 1) {
lcdScreen.fadeColor(constants.COLOR.percent75);
fades[constants.COLOR.percent75] = 1;
}
}
timers.countdown = setTimeout(function () {
countdown(componentIndex, timeRemaining - 1);
}, 1000);
} else {
finishCountdown(componentIndex);
}
}
/**
* startCountdown plays the sound and begins the first call to countdown
* @param {int} componentIndex array index number of the toothbrush that is starting the countdown
* @private
*/
function startCountdown(componentIndex) {
log.info('(teeth.startCountdown for ' + componentIndex + ')');
buzzer.playStartSound();
lcdScreen.reset();
currentComponent = componentIndex;
countdown(componentIndex, constants.TIME.brushGoaltime[componentIndex]);
}
/**
* prepCountdown prepares the screen and waits for real countdown to begin, displays
* an additional warning with five seconds to go
* @param {int} componentIndex array index number of the toothbrush that is starting the countdown
* @private
*/
function prepCountdown(componentIndex) {
log.debug('(teeth.prepCountdown for ' + componentIndex + ')');
lcdScreen.displayReady(componentIndex);
var prepTime = constants.TIME.brushPreptime[componentIndex];
timers.prepCountdown = setTimeout(function () {
log.debug('setTimeout: prepCountdown');
lcdScreen.displaySet(componentIndex);
}, (prepTime - 5) * 1000);
timers.startCountdown = setTimeout(function () {
log.debug('setTimeout: startCountdown');
startCountdown(componentIndex);
}, prepTime * 1000);
}
/**
* watchForLightsOut polls the photoresistor to see if the room is dark, then stops all activity
* @private
*/
function watchForLightsOut() {
//do not log.debug >> called every 50ms
return;
var val = sensors.roomLightSensor.read();
if (val < constants.PINS.roomLightThreshold) {
log.info('Trigger for lights out: Stop Timer (early) then wait 5 seconds to start again');
if (currentComponent >= 0) {
metrics.addDataToCloud(currentComponent, timeSpent);
}
clearAllTimers();
lcdScreen.resetAndTurnOff();
setTimeout(wait, 5000);
}
}
/**
* wait is the main entry to this class, it polls the switches regularly to see if it should start the countdown
* @private
*/
function wait() {
//do not log.debug >> called every 100ms
var i,
val;
for (i = 0; i < sensors.brushSwitch.length; i = i + 1) {
val = sensors.brushSwitch[i].read();
if (val === 0) { //0 for NO (normally open switch), 1 for NC (normally closed)
log.info('Trigger for toothbrush ' + i + ': Start Timer');
prepCountdown(i);
timers.lightsOut = setInterval(watchForLightsOut, 50);
break;
}
}
if (i >= sensors.brushSwitch.length) {
setTimeout(wait, 100);
}
}
/**
* Entry point to Teeth, the start command initiates the Smart Toothbrush Holder and begins the process of waiting for a countdown
* @public
*/
this.start = function () {
log.info('Teeth.start waiting for toothbrush events');
wait();
};
};
/* Create instance objects of the classes needed by TEETH */
var log = new Logger(),
sensors = new Sensors(log),
buzzer = new Buzzer(log),
lcdScreen = new Screen(log),
mailer = new Mailer(log),
metrics = new Metrics(log),
teeth = new Teeth(log, sensors, buzzer, lcdScreen, mailer, metrics);
/* Get the code running by invoking the start method of the Teeth controller */
teeth.start();
|
<?php
use app\core\helpers\Html;
use app\core\helpers\Url;
$this->title = ' ';
$this->params['breadcrumbs'][] = $this->title;
?>
<style type="text/css">
.nopad{padding-left: 0}
.panel-default>.panel-heading{
padding: 10px 15px;
background-color: #f5f5f5;
border-color: #ddd;
}
</style>
<div class="page-content">
<!-- /section:settings.box -->
<div class="page-content-area">
<div class="page-header">
<h1>
<small>
<a data-loading-text=", ..." href="<?=Url::toRoute('sync')?>" class="btn btn-danger auth-sync"></a>
</small>
<?= $this->render('@app/modules/sys/views/admin/layout/_nav.php') ?>
</h1>
</div><!-- /.page-header -->
<div class="row">
<div class="col-md-12">
<?php foreach ($classes as $key => $value):?>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<?=$key;?>
</h4>
</div>
<div class="panel-body">
<?php foreach ($value as $ke => $val):?>
<dl class="col-md-12 col-sm-12 nopad">
<dt><?php echo $ke;?> </dt>
<?php foreach ($val as $k => $v):?>
<dd class="col-md-3 nopad">
<span class="lbl ">
<?php echo $k?>
<input value="<?= $v['title']?>" class="action_des input-small form-control" key="<?=$v['name']?>" />
</span>
</dd>
<?php endforeach;?>
</dl>
<hr/>
<?php endforeach;?>
</div>
</div>
<?php endforeach;?>
</div>
</div><!-- /.row -->
</div><!-- /.page-content-area -->
</div><!-- /.page-content -->
<?php $this->beginBlock('auth') ?>
$(function(){
$('.auth-sync').click(function(e){
e.preventDefault();
var btn = $(this).button('loading');
$.get($(this).attr('href'),null,function(xhr){
if (xhr.status) {
location.reload();
};
btn.button('reset');
},'json');
});
$('.action_des').change(function(e){
e.preventDefault();
var url = "<?=Url::toRoute('title')?>";
var csrf = $('meta[name=csrf-token]').attr('content');
var data = {name:$(this).attr('key'), title:$(this).val(), _csrf:csrf};
$.post(url, data, function(xhr){
if (!xhr.status) {
alert(xhr.info);
};
},'json');
});
})
<?php $this->endBlock() ?>
<?php $this->registerJs($this->blocks['auth'], \yii\web\View::POS_END); ?>
|
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>System\Browser\assets\scripts\Flash.js </title>
<link href="../../assets/styles/prettify.css" type="text/css" rel="stylesheet" />
<script src="../../assets/scripts/prettify.js" type="text/javascript"></script>
<style type="text/css">.highlight { display: block; background-color: #ddd; }</style>
</head>
<body onload="setTimeout('prettyPrint()', 0);var node = document.getElementById(location.hash.replace(/
// Swf swiff.js A
using("System.Controls.Control");
namespace(".Swiff", JPlus.Control.extend({
options: {
id: null,
height: 1,
width: 1,
container: null,
properties: {},
params: {
quality: 'high',
allowScriptAccess: 'always',
wMode: 'window',
swLiveConnect: true
},
callBacks: {},
vars: {}
},
constructor: function (path, options) {
this.instance = 'Swiff_' + String.uniqueID();
this.setOptions(options);
options = this.options;
var id = this.id = options.id || this.instance;
var container = document.id(options.container);
Swiff.CallBacks[this.instance] = {};
var params = options.params, vars = options.vars, callBacks = options.callBacks;
var properties = Object.append({ height: options.height, width: options.width }, options.properties);
var self = this;
for (var callBack in callBacks) {
Swiff.CallBacks[this.instance][callBack] = (function (option) {
return function () {
return option.apply(self.object, arguments);
};
})(callBacks[callBack]);
vars[callBack] = 'Swiff.CallBacks.' + this.instance + '.' + callBack;
}
params.flashVars = Object.toQueryString(vars);
if (Browser.ie) {
properties.classid = 'clsid:<API key>';
params.movie = path;
} else {
properties.type = 'application/x-shockwave-flash';
}
properties.data = path;
var build = '<object id="' + id + '"';
for (var property in properties) build += ' ' + property + '="' + properties[property] + '"';
build += '>';
for (var param in params) {
if (params[param]) build += '<param name="' + param + '" value="' + params[param] + '" />';
}
build += '</object>';
this.object = ((container) ? container.empty() : new Element('div')).set('html', build).firstChild;
},
remote: function () {
return Swiff.remote.apply(Swiff, [this.node || this].append(arguments));
}
}));
Swiff.CallBacks = {};
Swiff.remote = function (obj, fn) {
var rs = obj.CallFunction('<invoke name="' + fn + '" returntype="javascript">' + <API key>(arguments, 2) + '</invoke>');
return eval(rs);
};</pre>
</body>
</html>
|
define(['App', 'jquery', 'underscore', 'backbone', 'hbs!template/<API key>', 'view/basem-view'],
function(App, $, _, Backbone, SRPitemTmpl, BaseView) {
return BaseView.extend({
template: SRPitemTmpl,
events: {
'click .add': 'subscribe',
'click .remove': 'unsubscribe'
},
initialize: function(data) {
this.model = data.model;
},
subscribe: function(e) {
e.preventDefault()
e.stopPropagation()
var target = this.$(e.currentTarget)
target.removeClass('add').addClass('remove').html('unsubscribe')
var params = {
action: 'sub',
sr: this.model.get('name'),
sr_name: this.model.get('name'),
uh: $.cookie('modhash')
};
console.log(params)
this.api("api/subscribe", 'POST', params, function(data) {
console.log("subscribe done", data)
//edit the window and cookie
App.trigger('header:refreshSubreddits')
});
},
unsubscribe: function(e) {
e.preventDefault()
e.stopPropagation()
var target = this.$(e.currentTarget)
target.removeClass('remove').addClass('add').html('subscribe')
var params = {
action: 'unsub',
sr: this.model.get('name'),
uh: $.cookie('modhash')
};
console.log(params)
this.api("api/subscribe", 'POST', params, function(data) {
console.log("unsubscribe done", data)
App.trigger('header:refreshSubreddits')
});
}
});
});
|
<?php
namespace yii\helpers;
use Yii;
use yii\base\<API key>;
use yii\db\<API key>;
use yii\validators\StringValidator;
use yii\web\Request;
use yii\base\Model;
/**
* BaseHtml provides concrete implementation for [[Html]].
*
* Do not use BaseHtml. Use [[Html]] instead.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class BaseHtml
{
public static $voidElements = [
'area' => 1,
'base' => 1,
'br' => 1,
'col' => 1,
'command' => 1,
'embed' => 1,
'hr' => 1,
'img' => 1,
'input' => 1,
'keygen' => 1,
'link' => 1,
'meta' => 1,
'param' => 1,
'source' => 1,
'track' => 1,
'wbr' => 1,
];
/**
* @var array the preferred order of attributes in a tag. This mainly affects the order of the attributes
* that are rendered by [[renderTagAttributes()]].
*/
public static $attributeOrder = [
'type',
'id',
'class',
'name',
'value',
'href',
'src',
'action',
'method',
'selected',
'checked',
'readonly',
'disabled',
'multiple',
'size',
'maxlength',
'width',
'height',
'rows',
'cols',
'alt',
'title',
'rel',
'media',
];
/**
* @var array list of tag attributes that should be specially handled when their values are of array type.
* In particular, if the value of the `data` attribute is `['name' => 'xyz', 'age' => 13]`, two attributes
* will be generated instead of one: `data-name="xyz" data-age="13"`.
* @since 2.0.3
*/
public static $dataAttributes = ['data', 'data-ng', 'ng'];
public static function encode($content, $doubleEncode = true)
{
return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app ? Yii::$app->charset : 'UTF-8', $doubleEncode);
}
public static function decode($content)
{
return <API key>($content, ENT_QUOTES);
}
/**
* Generates a complete HTML tag.
* @param string $name the tag name
* @param string $content the content to be enclosed between the start and end tags. It will not be HTML-encoded.
* If this is coming from end users, you should consider [[encode()]] it to prevent XSS attacks.
* @param array $options the HTML tag attributes (HTML options) in terms of name-value pairs.
* These will be rendered as the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
*
* For example when using `['class' => 'my-class', 'target' => '_blank', 'value' => null]` it will result in the
* html attributes rendered like this: `class="my-class" target="_blank"`.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated HTML tag
* @see beginTag()
* @see endTag()
*/
public static function tag($name, $content = '', $options = [])
{
$html = "<$name" . static::renderTagAttributes($options) . '>';
return isset(static::$voidElements[strtolower($name)]) ? $html : "$html$content</$name>";
}
/**
* Generates a start tag.
* @param string $name the tag name
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated start tag
* @see endTag()
* @see tag()
*/
public static function beginTag($name, $options = [])
{
return "<$name" . static::renderTagAttributes($options) . '>';
}
/**
* Generates an end tag.
* @param string $name the tag name
* @return string the generated end tag
* @see beginTag()
* @see tag()
*/
public static function endTag($name)
{
return "</$name>";
}
/**
* Generates a style tag.
* @param string $content the style content
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated style tag
*/
public static function style($content, $options = [])
{
return static::tag('style', $content, $options);
}
/**
* Generates a script tag.
* @param string $content the script content
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated script tag
*/
public static function script($content, $options = [])
{
return static::tag('script', $content, $options);
}
/**
* Generates a link tag that refers to an external CSS file.
* @param array|string $url the URL of the external CSS file. This parameter will be processed by [[Url::to()]].
* @param array $options the tag options in terms of name-value pairs. The following option is specially handled:
*
* - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified,
* the generated `link` tag will be enclosed within the conditional comments. This is mainly useful
* for supporting old versions of IE browsers.
* - noscript: if set to true, `link` tag will be wrapped into `<noscript>` tags.
*
* The rest of the options will be rendered as the attributes of the resulting link tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated link tag
* @see Url::to()
*/
public static function cssFile($url, $options = [])
{
if (!isset($options['rel'])) {
$options['rel'] = 'stylesheet';
}
$options['href'] = Url::to($url);
if (isset($options['condition'])) {
$condition = $options['condition'];
unset($options['condition']);
return self::wrapIntoCondition(static::tag('link', '', $options), $condition);
} elseif (isset($options['noscript']) && $options['noscript'] === true) {
unset($options['noscript']);
return "<noscript>" . static::tag('link', '', $options) . "</noscript>";
} else {
return static::tag('link', '', $options);
}
}
/**
* Generates a script tag that refers to an external JavaScript file.
* @param string $url the URL of the external JavaScript file. This parameter will be processed by [[Url::to()]].
* @param array $options the tag options in terms of name-value pairs. The following option is specially handled:
*
* - condition: specifies the conditional comments for IE, e.g., `lt IE 9`. When this is specified,
* the generated `script` tag will be enclosed within the conditional comments. This is mainly useful
* for supporting old versions of IE browsers.
*
* The rest of the options will be rendered as the attributes of the resulting script tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated script tag
* @see Url::to()
*/
public static function jsFile($url, $options = [])
{
$options['src'] = Url::to($url);
if (isset($options['condition'])) {
$condition = $options['condition'];
unset($options['condition']);
return self::wrapIntoCondition(static::tag('script', '', $options), $condition);
} else {
return static::tag('script', '', $options);
}
}
/**
* Wraps given content into conditional comments for IE, e.g., `lt IE 9`.
* @param string $content raw HTML content.
* @param string $condition condition string.
* @return string generated HTML.
*/
private static function wrapIntoCondition($content, $condition)
{
if (strpos($condition, '!IE') !== false) {
return "<!--[if $condition]><!-->\n" . $content . "\n<!--<![endif]-->";
}
return "<!--[if $condition]>\n" . $content . "\n<![endif]-->";
}
/**
* Generates the meta tags containing CSRF token information.
* @return string the generated meta tags
* @see Request::<API key>
*/
public static function csrfMetaTags()
{
$request = Yii::$app->getRequest();
if ($request instanceof Request && $request-><API key>) {
return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $request->csrfParam]) . "\n "
. static::tag('meta', '', ['name' => 'csrf-token', 'content' => $request->getCsrfToken()]) . "\n";
} else {
return '';
}
}
/**
* Generates a form start tag.
* @param array|string $action the form action URL. This parameter will be processed by [[Url::to()]].
* @param string $method the form submission method, such as "post", "get", "put", "delete" (case-insensitive).
* Since most browsers only support "post" and "get", if other methods are given, they will
* be simulated using "post", and a hidden input will be added which contains the actual method type.
* See [[\yii\web\Request::methodParam]] for more details.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated form start tag.
* @see endForm()
*/
public static function beginForm($action = '', $method = 'post', $options = [])
{
$action = Url::to($action);
$hiddenInputs = [];
$request = Yii::$app->getRequest();
if ($request instanceof Request) {
if (strcasecmp($method, 'get') && strcasecmp($method, 'post')) {
// simulate PUT, DELETE, etc. via POST
$hiddenInputs[] = static::hiddenInput($request->methodParam, $method);
$method = 'post';
}
if ($request-><API key> && !strcasecmp($method, 'post')) {
$hiddenInputs[] = static::hiddenInput($request->csrfParam, $request->getCsrfToken());
}
}
if (!strcasecmp($method, 'get') && ($pos = strpos($action, '?')) !== false) {
// query parameters in the action are ignored for GET method
// we use hidden fields to add them back
foreach (explode('&', substr($action, $pos + 1)) as $pair) {
if (($pos1 = strpos($pair, '=')) !== false) {
$hiddenInputs[] = static::hiddenInput(
urldecode(substr($pair, 0, $pos1)),
urldecode(substr($pair, $pos1 + 1))
);
} else {
$hiddenInputs[] = static::hiddenInput(urldecode($pair), '');
}
}
$action = substr($action, 0, $pos);
}
$options['action'] = $action;
$options['method'] = $method;
$form = static::beginTag('form', $options);
if (!empty($hiddenInputs)) {
$form .= "\n" . implode("\n", $hiddenInputs);
}
return $form;
}
/**
* Generates a form end tag.
* @return string the generated tag
* @see beginForm()
*/
public static function endForm()
{
return '</form>';
}
/**
* Generates a hyperlink tag.
* @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
* such as an image tag. If this is coming from end users, you should consider [[encode()]]
* it to prevent XSS attacks.
* @param array|string|null $url the URL for the hyperlink tag. This parameter will be processed by [[Url::to()]]
* and will be used for the "href" attribute of the tag. If this parameter is null, the "href" attribute
* will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated hyperlink
* @see \yii\helpers\Url::to()
*/
public static function a($text, $url = null, $options = [])
{
if ($url !== null) {
$options['href'] = Url::to($url);
}
return static::tag('a', $text, $options);
}
/**
* Generates a mailto hyperlink.
* @param string $text link body. It will NOT be HTML-encoded. Therefore you can pass in HTML code
* such as an image tag. If this is coming from end users, you should consider [[encode()]]
* it to prevent XSS attacks.
* @param string $email email address. If this is null, the first parameter (link body) will be treated
* as the email address and used.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated mailto link
*/
public static function mailto($text, $email = null, $options = [])
{
$options['href'] = 'mailto:' . ($email === null ? $text : $email);
return static::tag('a', $text, $options);
}
/**
* Generates an image tag.
* @param array|string $src the image URL. This parameter will be processed by [[Url::to()]].
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated image tag
*/
public static function img($src, $options = [])
{
$options['src'] = Url::to($src);
if (!isset($options['alt'])) {
$options['alt'] = '';
}
return static::tag('img', '', $options);
}
/**
* Generates a label tag.
* @param string $content label text. It will NOT be HTML-encoded. Therefore you can pass in HTML code
* such as an image tag. If this is is coming from end users, you should [[encode()]]
* it to prevent XSS attacks.
* @param string $for the ID of the HTML element that this label is associated with.
* If this is null, the "for" attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated label tag
*/
public static function label($content, $for = null, $options = [])
{
$options['for'] = $for;
return static::tag('label', $content, $options);
}
/**
* Generates a button tag.
* @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
* Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
* you should consider [[encode()]] it to prevent XSS attacks.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated button tag
*/
public static function button($content = 'Button', $options = [])
{
if (!isset($options['type'])) {
$options['type'] = 'button';
}
return static::tag('button', $content, $options);
}
/**
* Generates a submit button tag.
* @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
* Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
* you should consider [[encode()]] it to prevent XSS attacks.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated submit button tag
*/
public static function submitButton($content = 'Submit', $options = [])
{
$options['type'] = 'submit';
return static::button($content, $options);
}
/**
* Generates a reset button tag.
* @param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
* Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
* you should consider [[encode()]] it to prevent XSS attacks.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated reset button tag
*/
public static function resetButton($content = 'Reset', $options = [])
{
$options['type'] = 'reset';
return static::button($content, $options);
}
/**
* Generates an input type of the given type.
* @param string $type the type attribute.
* @param string $name the name attribute. If it is null, the name attribute will not be generated.
* @param string $value the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated input tag
*/
public static function input($type, $name = null, $value = null, $options = [])
{
if (!isset($options['type'])) {
$options['type'] = $type;
}
$options['name'] = $name;
$options['value'] = $value === null ? null : (string) $value;
return static::tag('input', '', $options);
}
/**
* Generates an input button.
* @param string $label the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated button tag
*/
public static function buttonInput($label = 'Button', $options = [])
{
$options['type'] = 'button';
$options['value'] = $label;
return static::tag('input', '', $options);
}
/**
* Generates a submit input button.
* @param string $label the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated button tag
*/
public static function submitInput($label = 'Submit', $options = [])
{
$options['type'] = 'submit';
$options['value'] = $label;
return static::tag('input', '', $options);
}
/**
* Generates a reset input button.
* @param string $label the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the attributes of the button tag. The values will be HTML-encoded using [[encode()]].
* Attributes whose value is null will be ignored and not put in the tag returned.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated button tag
*/
public static function resetInput($label = 'Reset', $options = [])
{
$options['type'] = 'reset';
$options['value'] = $label;
return static::tag('input', '', $options);
}
/**
* Generates a text input field.
* @param string $name the name attribute.
* @param string $value the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated text input tag
*/
public static function textInput($name, $value = null, $options = [])
{
return static::input('text', $name, $value, $options);
}
/**
* Generates a hidden input field.
* @param string $name the name attribute.
* @param string $value the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated hidden input tag
*/
public static function hiddenInput($name, $value = null, $options = [])
{
return static::input('hidden', $name, $value, $options);
}
/**
* Generates a password input field.
* @param string $name the name attribute.
* @param string $value the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated password input tag
*/
public static function passwordInput($name, $value = null, $options = [])
{
return static::input('password', $name, $value, $options);
}
/**
* Generates a file input field.
* To use a file input field, you should set the enclosing form's "enctype" attribute to
* be "multipart/form-data". After the form is submitted, the uploaded file information
* can be obtained via $_FILES[$name] (see PHP documentation).
* @param string $name the name attribute.
* @param string $value the value attribute. If it is null, the value attribute will not be generated.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated file input tag
*/
public static function fileInput($name, $value = null, $options = [])
{
return static::input('file', $name, $value, $options);
}
/**
* Generates a text area input.
* @param string $name the input name
* @param string $value the input value. Note that it will be encoded using [[encode()]].
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated text area tag
*/
public static function textarea($name, $value = '', $options = [])
{
$options['name'] = $name;
return static::tag('textarea', static::encode($value), $options);
}
/**
* Generates a radio button input.
* @param string $name the name attribute.
* @param boolean $checked whether the radio button should be checked.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - uncheck: string, the value associated with the uncheck state of the radio button. When this attribute
* is present, a hidden input will be generated so that if the radio button is not checked and is submitted,
* the value of this attribute will still be submitted to the server via the hidden input.
* - label: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass
* in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
* When this option is specified, the radio button will be enclosed by a label tag.
* - labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option.
*
* The rest of the options will be rendered as the attributes of the resulting radio button tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated radio button tag
*/
public static function radio($name, $checked = false, $options = [])
{
$options['checked'] = (bool) $checked;
$value = array_key_exists('value', $options) ? $options['value'] : '1';
if (isset($options['uncheck'])) {
// add a hidden field so that if the radio button is not selected, it still submits a value
$hidden = static::hiddenInput($name, $options['uncheck']);
unset($options['uncheck']);
} else {
$hidden = '';
}
if (isset($options['label'])) {
$label = $options['label'];
$labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
unset($options['label'], $options['labelOptions']);
$content = static::label(static::input('radio', $name, $value, $options) . ' ' . $label, null, $labelOptions);
return $hidden . $content;
} else {
return $hidden . static::input('radio', $name, $value, $options);
}
}
/**
* Generates a checkbox input.
* @param string $name the name attribute.
* @param boolean $checked whether the checkbox should be checked.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - uncheck: string, the value associated with the uncheck state of the checkbox. When this attribute
* is present, a hidden input will be generated so that if the checkbox is not checked and is submitted,
* the value of this attribute will still be submitted to the server via the hidden input.
* - label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass
* in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
* When this option is specified, the checkbox will be enclosed by a label tag.
* - labelOptions: array, the HTML attributes for the label tag. Do not set this option unless you set the "label" option.
*
* The rest of the options will be rendered as the attributes of the resulting checkbox tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated checkbox tag
*/
public static function checkbox($name, $checked = false, $options = [])
{
$options['checked'] = (bool) $checked;
$value = array_key_exists('value', $options) ? $options['value'] : '1';
if (isset($options['uncheck'])) {
// add a hidden field so that if the checkbox is not selected, it still submits a value
$hidden = static::hiddenInput($name, $options['uncheck']);
unset($options['uncheck']);
} else {
$hidden = '';
}
if (isset($options['label'])) {
$label = $options['label'];
$labelOptions = isset($options['labelOptions']) ? $options['labelOptions'] : [];
unset($options['label'], $options['labelOptions']);
$content = static::label(static::input('checkbox', $name, $value, $options) . ' ' . $label, null, $labelOptions);
return $hidden . $content;
} else {
return $hidden . static::input('checkbox', $name, $value, $options);
}
}
/**
* Generates a drop-down list.
* @param string $name the input name
* @param string $selection the selected value
* @param array $items the option data items. The array keys are option values, and the array values
* are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
* For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
* If you have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
*
* Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
* the labels will also be HTML-encoded.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - prompt: string, a prompt text to be displayed as the first option;
* - options: array, the attributes for the select option tags. The array keys must be valid option values,
* and the array values are the extra attributes for the corresponding option tags. For example,
*
* ~~~
* [
* 'value1' => ['disabled' => true],
* 'value2' => ['label' => 'value 2'],
* ];
* ~~~
*
* - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
* except that the array keys represent the optgroup labels specified in $items.
* - encodeSpaces: bool, whether to encode spaces in option prompt and option value with ` ` character.
* Defaults to false.
* - encode: bool, whether to encode option prompt and option value characters.
* Defaults to `true`. This option is available since 2.0.3.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated drop-down list tag
*/
public static function dropDownList($name, $selection = null, $items = [], $options = [])
{
if (!empty($options['multiple'])) {
return static::listBox($name, $selection, $items, $options);
}
$options['name'] = $name;
unset($options['unselect']);
$selectOptions = static::renderSelectOptions($selection, $items, $options);
return static::tag('select', "\n" . $selectOptions . "\n", $options);
}
/**
* Generates a list box.
* @param string $name the input name
* @param string|array $selection the selected value(s)
* @param array $items the option data items. The array keys are option values, and the array values
* are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
* For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
* If you have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
*
* Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
* the labels will also be HTML-encoded.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - prompt: string, a prompt text to be displayed as the first option;
* - options: array, the attributes for the select option tags. The array keys must be valid option values,
* and the array values are the extra attributes for the corresponding option tags. For example,
*
* ~~~
* [
* 'value1' => ['disabled' => true],
* 'value2' => ['label' => 'value 2'],
* ];
* ~~~
*
* - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
* except that the array keys represent the optgroup labels specified in $items.
* - unselect: string, the value that will be submitted when no option is selected.
* When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
* mode, we can still obtain the posted unselect value.
* - encodeSpaces: bool, whether to encode spaces in option prompt and option value with ` ` character.
* Defaults to false.
* - encode: bool, whether to encode option prompt and option value characters.
* Defaults to `true`. This option is available since 2.0.3.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated list box tag
*/
public static function listBox($name, $selection = null, $items = [], $options = [])
{
if (!array_key_exists('size', $options)) {
$options['size'] = 4;
}
if (!empty($options['multiple']) && !empty($name) && substr_compare($name, '[]', -2, 2)) {
$name .= '[]';
}
$options['name'] = $name;
if (isset($options['unselect'])) {
// add a hidden field so that if the list box has no option being selected, it still submits a value
if (!empty($name) && substr_compare($name, '[]', -2, 2) === 0) {
$name = substr($name, 0, -2);
}
$hidden = static::hiddenInput($name, $options['unselect']);
unset($options['unselect']);
} else {
$hidden = '';
}
$selectOptions = static::renderSelectOptions($selection, $items, $options);
return $hidden . static::tag('select', "\n" . $selectOptions . "\n", $options);
}
/**
* Generates a list of checkboxes.
* A checkbox list allows multiple selection, like [[listBox()]].
* As a result, the corresponding submitted value is an array.
* @param string $name the name attribute of each checkbox.
* @param string|array $selection the selected value(s).
* @param array $items the data item used to generate the checkboxes.
* The array keys are the checkbox values, while the array values are the corresponding labels.
* @param array $options options (name => config) for the checkbox list container tag.
* The following options are specially handled:
*
* - tag: string, the tag name of the container element.
* - unselect: string, the value that should be submitted when none of the checkboxes is selected.
* By setting this option, a hidden input will be generated.
* - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
* This option is ignored if `item` option is set.
* - separator: string, the HTML code that separates items.
* - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
* - item: callable, a callback that can be used to customize the generation of the HTML code
* corresponding to a single item in $items. The signature of this callback must be:
*
* ~~~
* function ($index, $label, $name, $checked, $value)
* ~~~
*
* where $index is the zero-based index of the checkbox in the whole list; $label
* is the label for the checkbox; and $name, $value and $checked represent the name,
* value and the checked status of the checkbox input, respectively.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated checkbox list
*/
public static function checkboxList($name, $selection = null, $items = [], $options = [])
{
if (substr($name, -2) !== '[]') {
$name .= '[]';
}
$formatter = isset($options['item']) ? $options['item'] : null;
$itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
$encode = !isset($options['encode']) || $options['encode'];
$lines = [];
$index = 0;
foreach ($items as $value => $label) {
$checked = $selection !== null &&
(!is_array($selection) && !strcmp($value, $selection)
|| is_array($selection) && in_array($value, $selection));
if ($formatter !== null) {
$lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
} else {
$lines[] = static::checkbox($name, $checked, array_merge($itemOptions, [
'value' => $value,
'label' => $encode ? static::encode($label) : $label,
]));
}
$index++;
}
if (isset($options['unselect'])) {
// add a hidden field so that if the list box has no option being selected, it still submits a value
$name2 = substr($name, -2) === '[]' ? substr($name, 0, -2) : $name;
$hidden = static::hiddenInput($name2, $options['unselect']);
} else {
$hidden = '';
}
$separator = isset($options['separator']) ? $options['separator'] : "\n";
$tag = isset($options['tag']) ? $options['tag'] : 'div';
unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']);
return $hidden . static::tag($tag, implode($separator, $lines), $options);
}
/**
* Generates a list of radio buttons.
* A radio button list is like a checkbox list, except that it only allows single selection.
* @param string $name the name attribute of each radio button.
* @param string|array $selection the selected value(s).
* @param array $items the data item used to generate the radio buttons.
* The array keys are the radio button values, while the array values are the corresponding labels.
* @param array $options options (name => config) for the radio button list container tag.
* The following options are specially handled:
*
* - tag: string, the tag name of the container element.
* - unselect: string, the value that should be submitted when none of the radio buttons is selected.
* By setting this option, a hidden input will be generated.
* - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
* This option is ignored if `item` option is set.
* - separator: string, the HTML code that separates items.
* - itemOptions: array, the options for generating the radio button tag using [[radio()]].
* - item: callable, a callback that can be used to customize the generation of the HTML code
* corresponding to a single item in $items. The signature of this callback must be:
*
* ~~~
* function ($index, $label, $name, $checked, $value)
* ~~~
*
* where $index is the zero-based index of the radio button in the whole list; $label
* is the label for the radio button; and $name, $value and $checked represent the name,
* value and the checked status of the radio button input, respectively.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated radio button list
*/
public static function radioList($name, $selection = null, $items = [], $options = [])
{
$encode = !isset($options['encode']) || $options['encode'];
$formatter = isset($options['item']) ? $options['item'] : null;
$itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
$lines = [];
$index = 0;
foreach ($items as $value => $label) {
$checked = $selection !== null &&
(!is_array($selection) && !strcmp($value, $selection)
|| is_array($selection) && in_array($value, $selection));
if ($formatter !== null) {
$lines[] = call_user_func($formatter, $index, $label, $name, $checked, $value);
} else {
$lines[] = static::radio($name, $checked, array_merge($itemOptions, [
'value' => $value,
'label' => $encode ? static::encode($label) : $label,
]));
}
$index++;
}
$separator = isset($options['separator']) ? $options['separator'] : "\n";
if (isset($options['unselect'])) {
// add a hidden field so that if the list box has no option being selected, it still submits a value
$hidden = static::hiddenInput($name, $options['unselect']);
} else {
$hidden = '';
}
$tag = isset($options['tag']) ? $options['tag'] : 'div';
unset($options['tag'], $options['unselect'], $options['encode'], $options['separator'], $options['item'], $options['itemOptions']);
return $hidden . static::tag($tag, implode($separator, $lines), $options);
}
/**
* Generates an unordered list.
* @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
* Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
* @param array $options options (name => config) for the radio button list. The following options are supported:
*
* - encode: boolean, whether to HTML-encode the items. Defaults to true.
* This option is ignored if the `item` option is specified.
* - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
* - item: callable, a callback that is used to generate each individual list item.
* The signature of this callback must be:
*
* ~~~
* function ($item, $index)
* ~~~
*
* where $index is the array key corresponding to `$item` in `$items`. The callback should return
* the whole list item tag.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated unordered list. An empty list tag will be returned if `$items` is empty.
*/
public static function ul($items, $options = [])
{
$tag = isset($options['tag']) ? $options['tag'] : 'ul';
$encode = !isset($options['encode']) || $options['encode'];
$formatter = isset($options['item']) ? $options['item'] : null;
$itemOptions = isset($options['itemOptions']) ? $options['itemOptions'] : [];
unset($options['tag'], $options['encode'], $options['item'], $options['itemOptions']);
if (empty($items)) {
return static::tag($tag, '', $options);
}
$results = [];
foreach ($items as $index => $item) {
if ($formatter !== null) {
$results[] = call_user_func($formatter, $item, $index);
} else {
$results[] = static::tag('li', $encode ? static::encode($item) : $item, $itemOptions);
}
}
return static::tag($tag, "\n" . implode("\n", $results) . "\n", $options);
}
/**
* Generates an ordered list.
* @param array|\Traversable $items the items for generating the list. Each item generates a single list item.
* Note that items will be automatically HTML encoded if `$options['encode']` is not set or true.
* @param array $options options (name => config) for the radio button list. The following options are supported:
*
* - encode: boolean, whether to HTML-encode the items. Defaults to true.
* This option is ignored if the `item` option is specified.
* - itemOptions: array, the HTML attributes for the `li` tags. This option is ignored if the `item` option is specified.
* - item: callable, a callback that is used to generate each individual list item.
* The signature of this callback must be:
*
* ~~~
* function ($item, $index)
* ~~~
*
* where $index is the array key corresponding to `$item` in `$items`. The callback should return
* the whole list item tag.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated ordered list. An empty string is returned if `$items` is empty.
*/
public static function ol($items, $options = [])
{
$options['tag'] = 'ol';
return static::ul($items, $options);
}
/**
* Generates a label tag for the given model attribute.
* The label text is the label associated with the attribute, obtained via [[Model::getAttributeLabel()]].
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* The following options are specially handled:
*
* - label: this specifies the label to be displayed. Note that this will NOT be [[encode()|encoded]].
* If this is not set, [[Model::getAttributeLabel()]] will be called to get the label for display
* (after encoding).
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated label tag
*/
public static function activeLabel($model, $attribute, $options = [])
{
$for = array_key_exists('for', $options) ? $options['for'] : static::getInputId($model, $attribute);
$attribute = static::getAttributeName($attribute);
$label = isset($options['label']) ? $options['label'] : static::encode($model->getAttributeLabel($attribute));
unset($options['label'], $options['for']);
return static::label($label, $for, $options);
}
/**
* Generates a hint tag for the given model attribute.
* The hint text is the hint associated with the attribute, obtained via [[Model::getAttributeHint()]].
* If no hint content can be obtained, method will return an empty string.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* If a value is null, the corresponding attribute will not be rendered.
* The following options are specially handled:
*
* - hint: this specifies the hint to be displayed. Note that this will NOT be [[encode()|encoded]].
* If this is not set, [[Model::getAttributeHint()]] will be called to get the hint for display
* (without encoding).
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated hint tag
* @since 2.0.4
*/
public static function activeHint($model, $attribute, $options = [])
{
$attribute = static::getAttributeName($attribute);
$hint = isset($options['hint']) ? $options['hint'] : $model->getAttributeHint($attribute);
if (empty($hint)) {
return '';
}
$tag = ArrayHelper::remove($options, 'tag', 'div');
unset($options['hint']);
return static::tag($tag, $hint, $options);
}
/**
* Generates a summary of the validation errors.
* If there is no validation error, an empty error summary markup will still be generated, but it will be hidden.
* @param Model|Model[] $models the model(s) whose validation errors are to be displayed
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - header: string, the header HTML for the error summary. If not set, a default prompt string will be used.
* - footer: string, the footer HTML for the error summary.
* - encode: boolean, if set to false then the error messages won't be encoded.
*
* The rest of the options will be rendered as the attributes of the container tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* @return string the generated error summary
*/
public static function errorSummary($models, $options = [])
{
$header = isset($options['header']) ? $options['header'] : '<p>' . Yii::t('yii', 'Please fix the following errors:') . '</p>';
$footer = isset($options['footer']) ? $options['footer'] : '';
$encode = !isset($options['encode']) || $options['encode'] !== false;
unset($options['header'], $options['footer'], $options['encode']);
$lines = [];
if (!is_array($models)) {
$models = [$models];
}
foreach ($models as $model) {
/* @var $model Model */
foreach ($model->getFirstErrors() as $error) {
$lines[] = $encode ? Html::encode($error) : $error;
}
}
if (empty($lines)) {
// still render the placeholder for client-side validation use
$content = "<ul></ul>";
$options['style'] = isset($options['style']) ? rtrim($options['style'], ';') . '; display:none' : 'display:none';
} else {
$content = "<ul><li>" . implode("</li>\n<li>", $lines) . "</li></ul>";
}
return Html::tag('div', $header . $content . $footer, $options);
}
/**
* Generates a tag that contains the first validation error of the specified model attribute.
* Note that even if there is no validation error, this method will still return an empty error tag.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. The values will be HTML-encoded
* using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
*
* The following options are specially handled:
*
* - tag: this specifies the tag name. If not set, "div" will be used.
* - encode: boolean, if set to false then the error message won't be encoded.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated label tag
*/
public static function error($model, $attribute, $options = [])
{
$attribute = static::getAttributeName($attribute);
$error = $model->getFirstError($attribute);
$tag = isset($options['tag']) ? $options['tag'] : 'div';
$encode = !isset($options['encode']) || $options['encode'] !== false;
unset($options['tag'], $options['encode']);
return Html::tag($tag, $encode ? Html::encode($error) : $error, $options);
}
/**
* Generates an input tag for the given model attribute.
* This method will generate the "name" and "value" tag attributes automatically for the model attribute
* unless they are explicitly specified in `$options`.
* @param string $type the input type (e.g. 'text', 'password')
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated input tag
*/
public static function activeInput($type, $model, $attribute, $options = [])
{
$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
$value = isset($options['value']) ? $options['value'] : static::getAttributeValue($model, $attribute);
if (!array_key_exists('id', $options)) {
$options['id'] = static::getInputId($model, $attribute);
}
return static::input($type, $name, $value, $options);
}
/**
* If `maxlength` option is set true and the model attribute is validated by a string validator,
* the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
* @param Model $model the model object
* @param string $attribute the attribute name or expression.
* @param array $options the tag options in terms of name-value pairs.
*/
private static function normalizeMaxLength($model, $attribute, &$options)
{
if (isset($options['maxlength']) && $options['maxlength'] === true) {
unset($options['maxlength']);
$attrName = static::getAttributeName($attribute);
foreach ($model->getActiveValidators($attrName) as $validator) {
if ($validator instanceof StringValidator && $validator->max !== null) {
$options['maxlength'] = $validator->max;
break;
}
}
}
}
/**
* Generates a text input tag for the given model attribute.
* This method will generate the "name" and "value" tag attributes automatically for the model attribute
* unless they are explicitly specified in `$options`.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* The following special options are recognized:
*
* - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
* by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
* This is available since version 2.0.3.
*
* @return string the generated input tag
*/
public static function activeTextInput($model, $attribute, $options = [])
{
self::normalizeMaxLength($model, $attribute, $options);
return static::activeInput('text', $model, $attribute, $options);
}
/**
* Generates a hidden input tag for the given model attribute.
* This method will generate the "name" and "value" tag attributes automatically for the model attribute
* unless they are explicitly specified in `$options`.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated input tag
*/
public static function activeHiddenInput($model, $attribute, $options = [])
{
return static::activeInput('hidden', $model, $attribute, $options);
}
/**
* Generates a password input tag for the given model attribute.
* This method will generate the "name" and "value" tag attributes automatically for the model attribute
* unless they are explicitly specified in `$options`.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* The following special options are recognized:
*
* - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
* by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
* This option is available since version 2.0.6.
*
* @return string the generated input tag
*/
public static function activePasswordInput($model, $attribute, $options = [])
{
self::normalizeMaxLength($model, $attribute, $options);
return static::activeInput('password', $model, $attribute, $options);
}
/**
* Generates a file input tag for the given model attribute.
* This method will generate the "name" and "value" tag attributes automatically for the model attribute
* unless they are explicitly specified in `$options`.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* @return string the generated input tag
*/
public static function activeFileInput($model, $attribute, $options = [])
{
// add a hidden field so that if a model only has a file field, we can
// still use isset($_POST[$modelClass]) to detect if the input is submitted
return static::activeHiddenInput($model, $attribute, ['id' => null, 'value' => ''])
. static::activeInput('file', $model, $attribute, $options);
}
/**
* Generates a textarea tag for the given model attribute.
* The model attribute value will be used as the content in the textarea.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. These will be rendered as
* the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
* The following special options are recognized:
*
* - maxlength: integer|boolean, when `maxlength` is set true and the model attribute is validated
* by a string validator, the `maxlength` option will take the value of [[\yii\validators\StringValidator::max]].
* This option is available since version 2.0.6.
*
* @return string the generated textarea tag
*/
public static function activeTextarea($model, $attribute, $options = [])
{
$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
if (isset($options['value'])) {
$value = $options['value'];
unset($options['value']);
} else {
$value = static::getAttributeValue($model, $attribute);
}
if (!array_key_exists('id', $options)) {
$options['id'] = static::getInputId($model, $attribute);
}
self::normalizeMaxLength($model, $attribute, $options);
return static::textarea($name, $value, $options);
}
/**
* Generates a radio button tag together with a label for the given model attribute.
* This method will generate the "checked" tag attribute according to the model attribute value.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - uncheck: string, the value associated with the uncheck state of the radio button. If not set,
* it will take the default value '0'. This method will render a hidden input so that if the radio button
* is not checked and is submitted, the value of this attribute will still be submitted to the server
* via the hidden input. If you do not want any hidden input, you should explicitly set this option as null.
* - label: string, a label displayed next to the radio button. It will NOT be HTML-encoded. Therefore you can pass
* in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
* The radio button will be enclosed by the label tag. Note that if you do not specify this option, a default label
* will be used based on the attribute label declaration in the model. If you do not want any label, you should
* explicitly set this option as null.
* - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated radio button tag
*/
public static function activeRadio($model, $attribute, $options = [])
{
$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
$value = static::getAttributeValue($model, $attribute);
if (!array_key_exists('value', $options)) {
$options['value'] = '1';
}
if (!array_key_exists('uncheck', $options)) {
$options['uncheck'] = '0';
}
if (!array_key_exists('label', $options)) {
$options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
}
$checked = "$value" === "{$options['value']}";
if (!array_key_exists('id', $options)) {
$options['id'] = static::getInputId($model, $attribute);
}
return static::radio($name, $checked, $options);
}
/**
* Generates a checkbox tag together with a label for the given model attribute.
* This method will generate the "checked" tag attribute according to the model attribute value.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - uncheck: string, the value associated with the uncheck state of the radio button. If not set,
* it will take the default value '0'. This method will render a hidden input so that if the radio button
* is not checked and is submitted, the value of this attribute will still be submitted to the server
* via the hidden input. If you do not want any hidden input, you should explicitly set this option as null.
* - label: string, a label displayed next to the checkbox. It will NOT be HTML-encoded. Therefore you can pass
* in HTML code such as an image tag. If this is is coming from end users, you should [[encode()]] it to prevent XSS attacks.
* The checkbox will be enclosed by the label tag. Note that if you do not specify this option, a default label
* will be used based on the attribute label declaration in the model. If you do not want any label, you should
* explicitly set this option as null.
* - labelOptions: array, the HTML attributes for the label tag. This is only used when the "label" option is specified.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated checkbox tag
*/
public static function activeCheckbox($model, $attribute, $options = [])
{
$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
$value = static::getAttributeValue($model, $attribute);
if (!array_key_exists('value', $options)) {
$options['value'] = '1';
}
if (!array_key_exists('uncheck', $options)) {
$options['uncheck'] = '0';
}
if (!array_key_exists('label', $options)) {
$options['label'] = static::encode($model->getAttributeLabel(static::getAttributeName($attribute)));
}
$checked = "$value" === "{$options['value']}";
if (!array_key_exists('id', $options)) {
$options['id'] = static::getInputId($model, $attribute);
}
return static::checkbox($name, $checked, $options);
}
/**
* Generates a drop-down list for the given model attribute.
* The selection of the drop-down list is taken from the value of the model attribute.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $items the option data items. The array keys are option values, and the array values
* are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
* For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
* If you have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
*
* Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
* the labels will also be HTML-encoded.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - prompt: string, a prompt text to be displayed as the first option;
* - options: array, the attributes for the select option tags. The array keys must be valid option values,
* and the array values are the extra attributes for the corresponding option tags. For example,
*
* ~~~
* [
* 'value1' => ['disabled' => true],
* 'value2' => ['label' => 'value 2'],
* ];
* ~~~
*
* - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
* except that the array keys represent the optgroup labels specified in $items.
* - encodeSpaces: bool, whether to encode spaces in option prompt and option value with ` ` character.
* Defaults to false.
* - encode: bool, whether to encode option prompt and option value characters.
* Defaults to `true`. This option is available since 2.0.3.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated drop-down list tag
*/
public static function activeDropDownList($model, $attribute, $items, $options = [])
{
if (empty($options['multiple'])) {
return static::activeListInput('dropDownList', $model, $attribute, $items, $options);
} else {
return static::activeListBox($model, $attribute, $items, $options);
}
}
/**
* Generates a list box.
* The selection of the list box is taken from the value of the model attribute.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $items the option data items. The array keys are option values, and the array values
* are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
* For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
* If you have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
*
* Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
* the labels will also be HTML-encoded.
* @param array $options the tag options in terms of name-value pairs. The following options are specially handled:
*
* - prompt: string, a prompt text to be displayed as the first option;
* - options: array, the attributes for the select option tags. The array keys must be valid option values,
* and the array values are the extra attributes for the corresponding option tags. For example,
*
* ~~~
* [
* 'value1' => ['disabled' => true],
* 'value2' => ['label' => 'value 2'],
* ];
* ~~~
*
* - groups: array, the attributes for the optgroup tags. The structure of this is similar to that of 'options',
* except that the array keys represent the optgroup labels specified in $items.
* - unselect: string, the value that will be submitted when no option is selected.
* When this attribute is set, a hidden field will be generated so that if no option is selected in multiple
* mode, we can still obtain the posted unselect value.
* - encodeSpaces: bool, whether to encode spaces in option prompt and option value with ` ` character.
* Defaults to false.
* - encode: bool, whether to encode option prompt and option value characters.
* Defaults to `true`. This option is available since 2.0.3.
*
* The rest of the options will be rendered as the attributes of the resulting tag. The values will
* be HTML-encoded using [[encode()]]. If a value is null, the corresponding attribute will not be rendered.
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated list box tag
*/
public static function activeListBox($model, $attribute, $items, $options = [])
{
return static::activeListInput('listBox', $model, $attribute, $items, $options);
}
/**
* Generates a list of checkboxes.
* A checkbox list allows multiple selection, like [[listBox()]].
* As a result, the corresponding submitted value is an array.
* The selection of the checkbox list is taken from the value of the model attribute.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $items the data item used to generate the checkboxes.
* The array keys are the checkbox values, and the array values are the corresponding labels.
* Note that the labels will NOT be HTML-encoded, while the values will.
* @param array $options options (name => config) for the checkbox list container tag.
* The following options are specially handled:
*
* - tag: string, the tag name of the container element.
* - unselect: string, the value that should be submitted when none of the checkboxes is selected.
* You may set this option to be null to prevent default value submission.
* If this option is not set, an empty string will be submitted.
* - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
* This option is ignored if `item` option is set.
* - separator: string, the HTML code that separates items.
* - itemOptions: array, the options for generating the checkbox tag using [[checkbox()]].
* - item: callable, a callback that can be used to customize the generation of the HTML code
* corresponding to a single item in $items. The signature of this callback must be:
*
* ~~~
* function ($index, $label, $name, $checked, $value)
* ~~~
*
* where $index is the zero-based index of the checkbox in the whole list; $label
* is the label for the checkbox; and $name, $value and $checked represent the name,
* value and the checked status of the checkbox input.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated checkbox list
*/
public static function activeCheckboxList($model, $attribute, $items, $options = [])
{
return static::activeListInput('checkboxList', $model, $attribute, $items, $options);
}
/**
* Generates a list of radio buttons.
* A radio button list is like a checkbox list, except that it only allows single selection.
* The selection of the radio buttons is taken from the value of the model attribute.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $items the data item used to generate the radio buttons.
* The array keys are the radio values, and the array values are the corresponding labels.
* Note that the labels will NOT be HTML-encoded, while the values will.
* @param array $options options (name => config) for the radio button list container tag.
* The following options are specially handled:
*
* - tag: string, the tag name of the container element.
* - unselect: string, the value that should be submitted when none of the radio buttons is selected.
* You may set this option to be null to prevent default value submission.
* If this option is not set, an empty string will be submitted.
* - encode: boolean, whether to HTML-encode the checkbox labels. Defaults to true.
* This option is ignored if `item` option is set.
* - separator: string, the HTML code that separates items.
* - itemOptions: array, the options for generating the radio button tag using [[radio()]].
* - item: callable, a callback that can be used to customize the generation of the HTML code
* corresponding to a single item in $items. The signature of this callback must be:
*
* ~~~
* function ($index, $label, $name, $checked, $value)
* ~~~
*
* where $index is the zero-based index of the radio button in the whole list; $label
* is the label for the radio button; and $name, $value and $checked represent the name,
* value and the checked status of the radio button input.
*
* See [[renderTagAttributes()]] for details on how attributes are being rendered.
*
* @return string the generated radio button list
*/
public static function activeRadioList($model, $attribute, $items, $options = [])
{
return static::activeListInput('radioList', $model, $attribute, $items, $options);
}
/**
* Generates a list of input fields.
* This method is mainly called by [[activeListBox()]], [[activeRadioList()]] and [[activeCheckBoxList()]].
* @param string $type the input type. This can be 'listBox', 'radioList', or 'checkBoxList'.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for the format
* about attribute expression.
* @param array $items the data item used to generate the input fields.
* The array keys are the input values, and the array values are the corresponding labels.
* Note that the labels will NOT be HTML-encoded, while the values will.
* @param array $options options (name => config) for the input list. The supported special options
* depend on the input type specified by `$type`.
* @return string the generated input list
*/
protected static function activeListInput($type, $model, $attribute, $items, $options = [])
{
$name = isset($options['name']) ? $options['name'] : static::getInputName($model, $attribute);
$selection = static::getAttributeValue($model, $attribute);
if (!array_key_exists('unselect', $options)) {
$options['unselect'] = '';
}
if (!array_key_exists('id', $options)) {
$options['id'] = static::getInputId($model, $attribute);
}
return static::$type($name, $selection, $items, $options);
}
/**
* Renders the option tags that can be used by [[dropDownList()]] and [[listBox()]].
* @param string|array $selection the selected value(s). This can be either a string for single selection
* or an array for multiple selections.
* @param array $items the option data items. The array keys are option values, and the array values
* are the corresponding option labels. The array can also be nested (i.e. some array values are arrays too).
* For each sub-array, an option group will be generated whose label is the key associated with the sub-array.
* If you have a list of data models, you may convert them into the format described above using
* [[\yii\helpers\ArrayHelper::map()]].
*
* Note, the values and labels will be automatically HTML-encoded by this method, and the blank spaces in
* the labels will also be HTML-encoded.
* @param array $tagOptions the $options parameter that is passed to the [[dropDownList()]] or [[listBox()]] call.
* This method will take out these elements, if any: "prompt", "options" and "groups". See more details
* in [[dropDownList()]] for the explanation of these elements.
*
* @return string the generated list options
*/
public static function renderSelectOptions($selection, $items, &$tagOptions = [])
{
$lines = [];
$encodeSpaces = ArrayHelper::remove($tagOptions, 'encodeSpaces', false);
$encode = ArrayHelper::remove($tagOptions, 'encode', true);
if (isset($tagOptions['prompt'])) {
$prompt = $encode ? static::encode($tagOptions['prompt']) : $tagOptions['prompt'];
if ($encodeSpaces) {
$prompt = str_replace(' ', ' ', $prompt);
}
$lines[] = static::tag('option', $prompt, ['value' => '']);
}
$options = isset($tagOptions['options']) ? $tagOptions['options'] : [];
$groups = isset($tagOptions['groups']) ? $tagOptions['groups'] : [];
unset($tagOptions['prompt'], $tagOptions['options'], $tagOptions['groups']);
$options['encodeSpaces'] = ArrayHelper::getValue($options, 'encodeSpaces', $encodeSpaces);
$options['encode'] = ArrayHelper::getValue($options, 'encode', $encode);
foreach ($items as $key => $value) {
if (is_array($value)) {
$groupAttrs = isset($groups[$key]) ? $groups[$key] : [];
if (!isset($groupAttrs['label'])) {
$groupAttrs['label'] = $key;
}
$attrs = ['options' => $options, 'groups' => $groups, 'encodeSpaces' => $encodeSpaces, 'encode' => $encode];
$content = static::renderSelectOptions($selection, $value, $attrs);
$lines[] = static::tag('optgroup', "\n" . $content . "\n", $groupAttrs);
} else {
$attrs = isset($options[$key]) ? $options[$key] : [];
$attrs['value'] = (string) $key;
$attrs['selected'] = $selection !== null &&
(!is_array($selection) && !strcmp($key, $selection)
|| is_array($selection) && in_array($key, $selection));
$text = $encode ? static::encode($value) : $value;
if ($encodeSpaces) {
$text = str_replace(' ', ' ', $text);
}
$lines[] = static::tag('option', $text, $attrs);
}
}
return implode("\n", $lines);
}
public static function renderTagAttributes($attributes)
{
if (count($attributes) > 1) {
$sorted = [];
foreach (static::$attributeOrder as $name) {
if (isset($attributes[$name])) {
$sorted[$name] = $attributes[$name];
}
}
$attributes = array_merge($sorted, $attributes);
}
$html = '';
foreach ($attributes as $name => $value) {
if (is_bool($value)) {
if ($value) {
$html .= " $name";
}
} elseif (is_array($value)) {
if (in_array($name, static::$dataAttributes)) {
foreach ($value as $n => $v) {
if (is_array($v)) {
$html .= " $name-$n='" . Json::htmlEncode($v) . "'";
} else {
$html .= " $name-$n=\"" . static::encode($v) . '"';
}
}
} elseif ($name === 'class') {
if (empty($value)) {
continue;
}
$html .= " $name=\"" . static::encode(implode(' ', $value)) . '"';
} elseif ($name === 'style') {
if (empty($value)) {
continue;
}
$html .= " $name=\"" . static::encode(static::cssStyleFromArray($value)) . '"';
} else {
$html .= " $name='" . Json::htmlEncode($value) . "'";
}
} elseif ($value !== null) {
$html .= " $name=\"" . static::encode($value) . '"';
}
}
return $html;
}
/**
* Adds a CSS class (or several classes) to the specified options.
* If the CSS class is already in the options, it will not be added again.
* If class specification at given options is an array, and some class placed there with the named (string) key,
* overriding of such key will have no effect. For example:
*
* ~~~php
* $options = ['class' => ['persistent' => 'initial']];
* Html::addCssClass($options, ['persistent' => 'override']);
* var_dump($options['class']); // outputs: array('persistent' => 'initial');
* ~~~
*
* @param array $options the options to be modified.
* @param string|array $class the CSS class(es) to be added
*/
public static function addCssClass(&$options, $class)
{
if (isset($options['class'])) {
if (is_array($options['class'])) {
$options['class'] = self::mergeCssClasses($options['class'], (array) $class);
} else {
$classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
$options['class'] = implode(' ', self::mergeCssClasses($classes, (array) $class));
}
} else {
$options['class'] = $class;
}
}
/**
* Merges already existing CSS classes with new one.
* This method provides the priority for named existing classes over additional.
* @param array $existingClasses already existing CSS classes.
* @param array $additionalClasses CSS classes to be added.
* @return array merge result.
*/
private static function mergeCssClasses(array $existingClasses, array $additionalClasses)
{
foreach ($additionalClasses as $key => $class) {
if (is_int($key) && !in_array($class, $existingClasses)) {
$existingClasses[] = $class;
} elseif (!isset($existingClasses[$key])) {
$existingClasses[$key] = $class;
}
}
return array_unique($existingClasses);
}
/**
* Removes a CSS class from the specified options.
* @param array $options the options to be modified.
* @param string|array $class the CSS class(es) to be removed
*/
public static function removeCssClass(&$options, $class)
{
if (isset($options['class'])) {
if (is_array($options['class'])) {
$classes = array_diff($options['class'], (array) $class);
if (empty($classes)) {
unset($options['class']);
} else {
$options['class'] = $classes;
}
} else {
$classes = preg_split('/\s+/', $options['class'], -1, PREG_SPLIT_NO_EMPTY);
$classes = array_diff($classes, (array) $class);
if (empty($classes)) {
unset($options['class']);
} else {
$options['class'] = implode(' ', $classes);
}
}
}
}
/**
* Adds the specified CSS style to the HTML options.
*
* If the options already contain a `style` element, the new style will be merged
* with the existing one. If a CSS property exists in both the new and the old styles,
* the old one may be overwritten if `$overwrite` is true.
*
* For example,
*
* ```php
* Html::addCssStyle($options, 'width: 100px; height: 200px');
* ```
*
* @param array $options the HTML options to be modified.
* @param string|array $style the new style string (e.g. `'width: 100px; height: 200px'`) or
* array (e.g. `['width' => '100px', 'height' => '200px']`).
* @param boolean $overwrite whether to overwrite existing CSS properties if the new style
* contain them too.
* @see removeCssStyle()
* @see cssStyleFromArray()
* @see cssStyleToArray()
*/
public static function addCssStyle(&$options, $style, $overwrite = true)
{
if (!empty($options['style'])) {
$oldStyle = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
$newStyle = is_array($style) ? $style : static::cssStyleToArray($style);
if (!$overwrite) {
foreach ($newStyle as $property => $value) {
if (isset($oldStyle[$property])) {
unset($newStyle[$property]);
}
}
}
$style = array_merge($oldStyle, $newStyle);
}
$options['style'] = is_array($style) ? static::cssStyleFromArray($style) : $style;
}
/**
* Removes the specified CSS style from the HTML options.
*
* For example,
*
* ```php
* Html::removeCssStyle($options, ['width', 'height']);
* ```
*
* @param array $options the HTML options to be modified.
* @param string|array $properties the CSS properties to be removed. You may use a string
* if you are removing a single property.
* @see addCssStyle()
*/
public static function removeCssStyle(&$options, $properties)
{
if (!empty($options['style'])) {
$style = is_array($options['style']) ? $options['style'] : static::cssStyleToArray($options['style']);
foreach ((array) $properties as $property) {
unset($style[$property]);
}
$options['style'] = static::cssStyleFromArray($style);
}
}
/**
* Converts a CSS style array into a string representation.
*
* For example,
*
* ```php
* print_r(Html::cssStyleFromArray(['width' => '100px', 'height' => '200px']));
* // will display: 'width: 100px; height: 200px;'
* ```
*
* @param array $style the CSS style array. The array keys are the CSS property names,
* and the array values are the corresponding CSS property values.
* @return string the CSS style string. If the CSS style is empty, a null will be returned.
*/
public static function cssStyleFromArray(array $style)
{
$result = '';
foreach ($style as $name => $value) {
$result .= "$name: $value; ";
}
// return null if empty to avoid rendering the "style" attribute
return $result === '' ? null : rtrim($result);
}
/**
* Converts a CSS style string into an array representation.
*
* The array keys are the CSS property names, and the array values
* are the corresponding CSS property values.
*
* For example,
*
* ```php
* print_r(Html::cssStyleToArray('width: 100px; height: 200px;'));
* // will display: ['width' => '100px', 'height' => '200px']
* ```
*
* @param string $style the CSS style string
* @return array the array representation of the CSS style
*/
public static function cssStyleToArray($style)
{
$result = [];
foreach (explode(';', $style) as $property) {
$property = explode(':', $property);
if (count($property) > 1) {
$result[trim($property[0])] = trim($property[1]);
}
}
return $result;
}
/**
* Returns the real attribute name from the given attribute expression.
*
* An attribute expression is an attribute name prefixed and/or suffixed with array indexes.
* It is mainly used in tabular data input and/or input of array type. Below are some examples:
*
* - `[0]content` is used in tabular data input to represent the "content" attribute
* for the first model in tabular input;
* - `dates[0]` represents the first array element of the "dates" attribute;
* - `[0]dates[0]` represents the first array element of the "dates" attribute
* for the first model in tabular input.
*
* If `$attribute` has neither prefix nor suffix, it will be returned back without change.
* @param string $attribute the attribute name or expression
* @return string the attribute name without prefix and suffix.
* @throws <API key> if the attribute name contains non-word characters.
*/
public static function getAttributeName($attribute)
{
if (preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
return $matches[2];
} else {
throw new <API key>('Attribute name must contain word characters only.');
}
}
/**
* Returns the value of the specified attribute name or expression.
*
* For an attribute expression like `[0]dates[0]`, this method will return the value of `$model->dates[0]`.
* See [[getAttributeName()]] for more details about attribute expression.
*
* If an attribute value is an instance of [[<API key>]] or an array of such instances,
* the primary value(s) of the AR instance(s) will be returned instead.
*
* @param Model $model the model object
* @param string $attribute the attribute name or expression
* @return string|array the corresponding attribute value
* @throws <API key> if the attribute name contains non-word characters.
*/
public static function getAttributeValue($model, $attribute)
{
if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
throw new <API key>('Attribute name must contain word characters only.');
}
$attribute = $matches[2];
$value = $model->$attribute;
if ($matches[3] !== '') {
foreach (explode('][', trim($matches[3], '[]')) as $id) {
if ((is_array($value) || $value instanceof \ArrayAccess) && isset($value[$id])) {
$value = $value[$id];
} else {
return null;
}
}
}
if (is_array($value)) {
foreach ($value as $i => $v) {
if ($v instanceof <API key>) {
$v = $v->getPrimaryKey(false);
$value[$i] = is_array($v) ? json_encode($v) : $v;
}
}
} elseif ($value instanceof <API key>) {
$value = $value->getPrimaryKey(false);
return is_array($value) ? json_encode($value) : $value;
}
return $value;
}
/**
* Generates an appropriate input name for the specified attribute name or expression.
*
* This method generates a name that can be used as the input name to collect user input
* for the specified attribute. The name is generated according to the [[Model::formName|form name]]
* of the model and the given attribute name. For example, if the form name of the `Post` model
* is `Post`, then the input name generated for the `content` attribute would be `Post[content]`.
*
* See [[getAttributeName()]] for explanation of attribute expression.
*
* @param Model $model the model object
* @param string $attribute the attribute name or expression
* @return string the generated input name
* @throws <API key> if the attribute name contains non-word characters.
*/
public static function getInputName($model, $attribute)
{
$formName = $model->formName();
if (!preg_match('/(^|.*\])([\w\.]+)(\[.*|$)/', $attribute, $matches)) {
throw new <API key>('Attribute name must contain word characters only.');
}
$prefix = $matches[1];
$attribute = $matches[2];
$suffix = $matches[3];
if ($formName === '' && $prefix === '') {
return $attribute . $suffix;
} elseif ($formName !== '') {
return $formName . $prefix . "[$attribute]" . $suffix;
} else {
throw new <API key>(get_class($model) . '::formName() cannot be empty for tabular inputs.');
}
}
/**
* Generates an appropriate input ID for the specified attribute name or expression.
*
* This method converts the result [[getInputName()]] into a valid input ID.
* For example, if [[getInputName()]] returns `Post[content]`, this method will return `post-content`.
* @param Model $model the model object
* @param string $attribute the attribute name or expression. See [[getAttributeName()]] for explanation of attribute expression.
* @return string the generated input ID
* @throws <API key> if the attribute name contains non-word characters.
*/
public static function getInputId($model, $attribute)
{
$name = strtolower(static::getInputName($model, $attribute));
return str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name);
}
/**
* Escapes regular expression to use in JavaScript
* @param string $regexp the regular expression to be escaped.
* @return string the escaped result.
* @since 2.0.6
*/
public static function <API key>($regexp)
{
$pattern = preg_replace('/\\\\x\{?([0-9a-fA-F]+)\}?/', '\u$1', $regexp);
$deliminator = substr($pattern, 0, 1);
$pos = strrpos($pattern, $deliminator, 1);
$flag = substr($pattern, $pos + 1);
if ($deliminator !== '/') {
$pattern = '/' . str_replace('/', '\\/', substr($pattern, 1, $pos - 1)) . '/';
} else {
$pattern = substr($pattern, 0, $pos + 1);
}
if (!empty($flag)) {
$pattern .= preg_replace('/[^igm]/', '', $flag);
}
return $pattern;
}
}
|
<!DOCTYPE html>
<html xmlns="http:
<head>
<meta charset="utf-8" />
<title>statsmodels.base.model.<API key>.remove_data — statsmodels v0.10.0 documentation</title>
<link rel="stylesheet" href="../../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../../_static/graphviz.css" />
<script type="text/javascript" id="<API key>" data-url_root="../../" src="../../_static/<API key>.js"></script>
<script type="text/javascript" src="../../_static/jquery.js"></script>
<script type="text/javascript" src="../../_static/underscore.js"></script>
<script type="text/javascript" src="../../_static/doctools.js"></script>
<script type="text/javascript" src="../../_static/language_data.js"></script>
<script async="async" type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/latest.js?config=<API key>"></script>
<link rel="shortcut icon" href="../../_static/<API key>.ico"/>
<link rel="author" title="About these documents" href="../../about.html" />
<link rel="index" title="Index" href="../../genindex.html" />
<link rel="search" title="Search" href="../../search.html" />
<link rel="next" title="statsmodels.base.model.<API key>.save" href="statsmodels.base.model.<API key>.save.html" />
<link rel="prev" title="statsmodels.base.model.<API key>.pvalues" href="statsmodels.base.model.<API key>.pvalues.html" />
<link rel="stylesheet" href="../../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../../_static/scripts.js">
</script>
<script type="text/javascript" src="../../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../../_static/closelabel.png"
$.facebox.settings.loadingImage = "../../_static/loading.gif"
</script>
<script>
$(document).ready(function() {
$.getJSON("../../../versions.json", function(versions) {
var dropdown = document.createElement("div");
dropdown.className = "dropdown";
var button = document.createElement("button");
button.className = "dropbtn";
button.innerHTML = "Other Versions";
var content = document.createElement("div");
content.className = "dropdown-content";
dropdown.appendChild(button);
dropdown.appendChild(content);
$(".header").prepend(dropdown);
for (var i = 0; i < versions.length; i++) {
if (versions[i].substring(0, 1) == "v") {
versions[i] = [versions[i], versions[i].substring(1)];
} else {
versions[i] = [versions[i], versions[i]];
};
};
for (var i = 0; i < versions.length; i++) {
var a = document.createElement("a");
a.innerHTML = versions[i][1];
a.href = "../../../" + versions[i][0] + "/index.html";
a.title = versions[i][1];
$(".dropdown-content").append(a);
};
});
});
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../../index.html">
<img src="../../_static/<API key>.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.base.model.<API key>.save.html" title="statsmodels.base.model.<API key>.save"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.base.model.<API key>.pvalues.html" title="statsmodels.base.model.<API key>.pvalues"
accesskey="P">previous</a> |</li>
<li><a href ="../../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../index.html">Develop</a></li> |
<li><a href="../../examples/index.html">Examples</a></li> |
<li><a href="../../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../index.html" >Developer Page</a> |</li>
<li class="nav-item nav-item-2"><a href="../internal.html" >Internal Classes</a> |</li>
<li class="nav-item nav-item-3"><a href="statsmodels.base.model.<API key>.html" accesskey="U">statsmodels.base.model.<API key></a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="<API key>">
<h1>statsmodels.base.model.<API key>.remove_data<a class="headerlink" href="
<p>method</p>
<dl class="method">
<dt id="statsmodels.base.model.<API key>.remove_data">
<code class="sig-prename descclassname"><API key>.</code><code class="sig-name descname">remove_data</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="
<dd><p>remove data arrays, all nobs arrays from result and model</p>
<p>This reduces the size of the instance, so it can be pickled with less
memory. Currently tested for use with predict from an unpickled
results and model instance.</p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>Since data and some intermediate results have been removed
calculating new statistics that require them will raise exceptions.
The exception will occur the first time an attribute is accessed
that has been set to None.</p>
</div>
<p>Not fully tested for time series models, tsa, and might delete too much
for prediction or not all that would be possible.</p>
<p>The lists of arrays to delete are maintained as attributes of
the result and model instance, except for cached values. These
lists could be changed before calling remove_data.</p>
<p>The attributes to remove are named in:</p>
<dl class="simple">
<dt>model._data_attr<span class="classifier">arrays attached to both the model instance</span></dt><dd><p>and the results instance with the same attribute name.</p>
</dd>
<dt>result.data_in_cache<span class="classifier">arrays that may exist as values in</span></dt><dd><p>result._cache (TODO : should privatize name)</p>
</dd>
<dt>result._data_attr_model<span class="classifier">arrays attached to the model</span></dt><dd><p>instance but not to the results instance</p>
</dd>
</dl>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="<API key>">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.base.model.<API key>.pvalues.html"
title="previous chapter">statsmodels.base.model.<API key>.pvalues</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.base.model.<API key>.save.html"
title="next chapter">statsmodels.base.model.<API key>.save</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../../_sources/dev/generated/statsmodels.base.model.<API key>.remove_data.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3 id="searchlabel">Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../../search.html" method="get">
<input type="text" name="q" aria-labelledby="searchlabel" />
<input type="submit" value="Go" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
&
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 2.1.2.
</div>
</body>
</html>
|
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'css/foundation.css' %}" />
</head>
<body>
<div class="row">
<div class="panel">
<h2> You have successfully logged out </h2>
<p> You can <a href="/pta/">login</a> again and access the PTA application</p>
</div>
</div>
</body>
</html>
|
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include "CanvasOGL.hpp"
#include "ShadersOpenGL.hpp"
#include "TextureOpenGL.hpp"
namespace KRE
{
namespace
{
CanvasPtr& get_instance()
{
static CanvasPtr res = CanvasPtr(new CanvasOGL());
return res;
}
}
CanvasOGL::CanvasOGL()
{
<API key>();
}
CanvasOGL::~CanvasOGL()
{
}
void CanvasOGL::<API key>()
{
mvp_ = glm::ortho(0.0f, float(width()), float(height()), 0.0f);
}
void CanvasOGL::blitTexture(const TexturePtr& tex, const rect& src, float rotation, const rect& dst, const Color& color) const
{
auto texture = std::<API key><OpenGLTexture>(tex);
ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type.");
const float tx1 = float(src.x()) / texture->width();
const float ty1 = float(src.y()) / texture->height();
const float tx2 = src.w() == 0 ? 1.0f : float(src.x2()) / texture->width();
const float ty2 = src.h() == 0 ? 1.0f : float(src.y2()) / texture->height();
const float uv_coords[] = {
tx1, ty1,
tx2, ty1,
tx1, ty2,
tx2, ty2,
};
const float vx1 = float(dst.x());
const float vy1 = float(dst.y());
const float vx2 = float(dst.x2());
const float vy2 = float(dst.y2());
const float vtx_coords[] = {
vx1, vy1,
vx2, vy1,
vx1, vy2,
vx2, vy2,
};
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vx2)/2.0f,-(vy1+vy2)/2.0f,0.0f));
glm::mat4 mvp = mvp_ * model * getModelMatrix();
auto shader = OpenGL::ShaderProgram::defaultSystemShader();
shader->makeActive();
texture->bind();
shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp));
if(color != KRE::Color::colorWhite()) {
shader->setUniformValue(shader->getColorUniform(), (color*getColor()).asFloatVector());
} else {
shader->setUniformValue(shader->getColorUniform(), getColor().asFloatVector());
}
shader->setUniformValue(shader->getTexMapUniform(), 0);
// XXX the following line are only temporary, obviously.
//shader->SetUniformValue(shader->GetUniformIterator("discard"), 0);
<API key>(shader->getVertexAttribute()->second.location);
<API key>(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords);
<API key>(shader-><API key>()->second.location);
<API key>(shader-><API key>()->second.location, 2, GL_FLOAT, GL_FALSE, 0, uv_coords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
<API key>(shader-><API key>()->second.location);
<API key>(shader->getVertexAttribute()->second.location);
}
void CanvasOGL::blitTexture(const TexturePtr& tex, const std::vector<vertex_texcoord>& vtc, float rotation, const Color& color)
{
ASSERT_LOG(false, "XXX CanvasOGL::blitTexture()");
}
void CanvasOGL::blitTexture(const MaterialPtr& mat, float rotation, const rect& dst, const Color& color) const
{
ASSERT_LOG(mat != NULL, "Material was null");
const float vx1 = float(dst.x());
const float vy1 = float(dst.y());
const float vx2 = float(dst.x2());
const float vy2 = float(dst.y2());
const float vtx_coords[] = {
vx1, vy1,
vx2, vy1,
vx1, vy2,
vx2, vy2,
};
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vy1)/2.0f,-(vy1+vy1)/2.0f,0.0f));
glm::mat4 mvp = mvp_ * model * getModelMatrix();
auto shader = OpenGL::ShaderProgram::defaultSystemShader();
shader->makeActive();
shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp));
//if(color != KRE::Color::colorWhite()) {
shader->setUniformValue(shader->getColorUniform(), color.asFloatVector());
shader->setUniformValue(shader->getTexMapUniform(), 0);
mat->apply();
for(auto it = mat->getTexture().begin(); it != mat->getTexture().end(); ++it) {
auto texture = std::<API key><OpenGLTexture>(*it);
ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type.");
auto uv_coords = mat-><API key>(it);
texture->bind();
// XXX the following line are only temporary, obviously.
//shader->SetUniformValue(shader->GetUniformIterator("discard"), 0);
<API key>(shader->getVertexAttribute()->second.location);
<API key>(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords);
<API key>(shader-><API key>()->second.location);
<API key>(shader-><API key>()->second.location, 2, GL_FLOAT, GL_FALSE, 0, &uv_coords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
<API key>(shader-><API key>()->second.location);
<API key>(shader->getVertexAttribute()->second.location);
}
mat->unapply();
}
void CanvasOGL::blitTexture(const MaterialPtr& mat, const rect& src, float rotation, const rect& dst, const Color& color) const
{
ASSERT_LOG(mat != NULL, "Material was null");
const float vx1 = float(dst.x());
const float vy1 = float(dst.y());
const float vx2 = float(dst.x2());
const float vy2 = float(dst.y2());
const float vtx_coords[] = {
vx1, vy1,
vx2, vy1,
vx1, vy2,
vx2, vy2,
};
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3((vx1+vx2)/2.0f,(vy1+vy2)/2.0f,0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-(vx1+vy1)/2.0f,-(vy1+vy1)/2.0f,0.0f));
glm::mat4 mvp = mvp_ * model * getModelMatrix();
auto shader = OpenGL::ShaderProgram::defaultSystemShader();
shader->makeActive();
shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp));
//if(color) {
shader->setUniformValue(shader->getColorUniform(), color.asFloatVector());
shader->setUniformValue(shader->getTexMapUniform(), 0);
mat->apply();
for(auto it = mat->getTexture().begin(); it != mat->getTexture().end(); ++it) {
auto texture = std::<API key><OpenGLTexture>(*it);
ASSERT_LOG(texture != NULL, "Texture passed in was not of expected type.");
const float tx1 = float(src.x()) / texture->width();
const float ty1 = float(src.y()) / texture->height();
const float tx2 = src.w() == 0 ? 1.0f : float(src.x2()) / texture->width();
const float ty2 = src.h() == 0 ? 1.0f : float(src.y2()) / texture->height();
const float uv_coords[] = {
tx1, ty1,
tx2, ty1,
tx1, ty2,
tx2, ty2,
};
texture->bind();
// XXX the following line are only temporary, obviously.
//shader->SetUniformValue(shader->GetUniformIterator("discard"), 0);
<API key>(shader->getVertexAttribute()->second.location);
<API key>(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords);
<API key>(shader-><API key>()->second.location);
<API key>(shader-><API key>()->second.location, 2, GL_FLOAT, GL_FALSE, 0, &uv_coords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
<API key>(shader-><API key>()->second.location);
<API key>(shader->getVertexAttribute()->second.location);
}
mat->unapply();
}
void CanvasOGL::drawSolidRect(const rect& r, const Color& fill_color, const Color& stroke_color, float rotation) const
{
rectf vtx = r.as_type<float>();
const float vtx_coords[] = {
vtx.x1(), vtx.y1(),
vtx.x2(), vtx.y1(),
vtx.x1(), vtx.y2(),
vtx.x2(), vtx.y2(),
};
glm::mat4 model = glm::translate(glm::mat4(1.0f), glm::vec3(vtx.mid_x(),vtx.mid_y(),0.0f)) * glm::rotate(glm::mat4(1.0f), rotation, glm::vec3(0.0f,0.0f,1.0f)) * glm::translate(glm::mat4(1.0f), glm::vec3(-vtx.mid_x(),-vtx.mid_y(),0.0f));
glm::mat4 mvp = mvp_ * model * getModelMatrix();
static OpenGL::ShaderProgramPtr shader = OpenGL::ShaderProgram::factory("simple");
shader->makeActive();
shader->setUniformValue(shader->getMvpUniform(), glm::value_ptr(mvp));
// Draw a filled rect
shader->setUniformValue(shader->getColorUniform(), fill_color.asFloatVector());
<API key>(shader->getVertexAttribute()->second.location);
<API key>(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
// Draw stroke if stroke_color is specified.
// XXX I think there is an easier way of doing this, with modern GL
const float vtx_coords_line[] = {
vtx.x1(), vtx.y1(),
vtx.x2(), vtx.y1(),
vtx.x2(), vtx.y2(),
vtx.x1(), vtx.y2(),
vtx.x1(), vtx.y1(),
};
shader->setUniformValue(shader->getColorUniform(), stroke_color.asFloatVector());
<API key>(shader->getVertexAttribute()->second.location);
<API key>(shader->getVertexAttribute()->second.location, 2, GL_FLOAT, GL_FALSE, 0, vtx_coords_line);
// XXX this may not be right.
glDrawArrays(GL_LINE_STRIP, 0, 5);
}
void CanvasOGL::drawSolidRect(const rect& r, const Color& fill_color, float rotate) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidRect()");
}
void CanvasOGL::drawHollowRect(const rect& r, const Color& stroke_color, float rotate) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowRect()");
}
void CanvasOGL::drawLine(const point& p1, const point& p2, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLine()");
}
void CanvasOGL::drawLines(const std::vector<glm::vec2>& varray, float line_width, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLines()");
}
void CanvasOGL::drawLines(const std::vector<glm::vec2>& varray, float line_width, const std::vector<glm::u8vec4>& carray) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLines()");
}
void CanvasOGL::drawLineStrip(const std::vector<glm::vec2>& points, float line_width, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLineStrip()");
}
void CanvasOGL::drawLineLoop(const std::vector<glm::vec2>& varray, float line_width, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLineLoop()");
}
void CanvasOGL::drawLine(const pointf& p1, const pointf& p2, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawLine()");
}
void CanvasOGL::drawPolygon(const std::vector<glm::vec2>& points, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawPolygon()");
}
void CanvasOGL::drawSolidCircle(const point& centre, double radius, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()");
}
void CanvasOGL::drawSolidCircle(const point& centre, double radius, const std::vector<uint8_t>& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()");
}
void CanvasOGL::drawHollowCircle(const point& centre, double radius, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowCircle()");
}
void CanvasOGL::drawSolidCircle(const pointf& centre, double radius, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()");
}
void CanvasOGL::drawSolidCircle(const pointf& centre, double radius, const std::vector<uint8_t>& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawSolidCircle()");
}
void CanvasOGL::drawHollowCircle(const pointf& centre, double radius, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawHollowCircle()");
}
void CanvasOGL::drawPoints(const std::vector<glm::vec2>& points, float radius, const Color& color) const
{
ASSERT_LOG(false, "XXX write function CanvasOGL::drawPoints()");
}
CanvasPtr CanvasOGL::getInstance()
{
return get_instance();
}
}
|
// Use of this source code is governed by a BSD
package libkey
import (
"context"
"github.com/keybase/client/go/kbfs/idutil"
"github.com/keybase/client/go/kbfs/kbfscrypto"
"github.com/keybase/client/go/kbfs/kbfsmd"
"github.com/keybase/client/go/protocol/keybase1"
)
// KeyOpsConfig is a config object containing the outside helper
// instances needed by KeyOps.
type KeyOpsConfig interface {
KeyServer() KeyServer
KBPKI() idutil.KBPKI
}
// KeyOpsStandard implements the KeyOps interface and relays get/put
// requests for server-side key halves from/to the key server.
type KeyOpsStandard struct {
config KeyOpsConfig
}
// NewKeyOpsStandard creates a new KeyOpsStandard instance.
func NewKeyOpsStandard(config KeyOpsConfig) *KeyOpsStandard {
return &KeyOpsStandard{config}
}
// Test that KeyOps standard fully implements the KeyOps interface.
var _ KeyOps = (*KeyOpsStandard)(nil)
// <API key> is an implementation of the KeyOps interface.
func (k *KeyOpsStandard) <API key>(
ctx context.Context, serverHalfID kbfscrypto.<API key>,
key kbfscrypto.CryptPublicKey) (kbfscrypto.<API key>, error) {
// get the key half from the server
serverHalf, err := k.config.KeyServer().<API key>(
ctx, serverHalfID, key)
if err != nil {
return kbfscrypto.<API key>{}, err
}
// get current uid and deviceKID
session, err := k.config.KBPKI().GetCurrentSession(ctx)
if err != nil {
return kbfscrypto.<API key>{}, err
}
// verify we got the expected key
err = kbfscrypto.<API key>(
serverHalfID, session.UID, key, serverHalf)
if err != nil {
return kbfscrypto.<API key>{}, err
}
return serverHalf, nil
}
// <API key> is an implementation of the KeyOps interface.
func (k *KeyOpsStandard) <API key>(
ctx context.Context,
keyServerHalves kbfsmd.<API key>) error {
// upload the keys
return k.config.KeyServer().<API key>(ctx, keyServerHalves)
}
// <API key> is an implementation of the KeyOps interface.
func (k *KeyOpsStandard) <API key>(
ctx context.Context, uid keybase1.UID, key kbfscrypto.CryptPublicKey,
serverHalfID kbfscrypto.<API key>) error {
return k.config.KeyServer().<API key>(
ctx, uid, key, serverHalfID)
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DataExplorer.Domain.Columns;
using DataExplorer.Domain.Layouts;
namespace DataExplorer.Domain.Maps.SizeMaps
{
public class SizeMapFactory : ISizeMapFactory
{
public SizeMap Create(Column column, double targetMin, double targetMax, SortOrder sortOrder)
{
if (column.DataType == typeof(Boolean))
return new BooleanToSizeMap(targetMin, targetMax, sortOrder);
if (column.DataType == typeof(DateTime))
return new DateTimeToSizeMap(
(DateTime)column.Min,
(DateTime)column.Max,
targetMin,
targetMax,
sortOrder);
if (column.DataType == typeof(Double))
return new FloatToSizeMap(
(double)column.Min,
(double)column.Max,
targetMin,
targetMax,
sortOrder);
if (column.DataType == typeof(Int32))
return new IntegerToSizeMap(
(int)column.Min,
(int)column.Max,
targetMin,
targetMax,
sortOrder);
if (column.DataType == typeof(String))
return new StringToSizeMap(
column.Values.Cast<string>().ToList(),
targetMin,
targetMax,
sortOrder);
throw new ArgumentException("Column data type is not valid data type for an axis map.");
}
}
}
|
package com.btr.proxy.search.desktop.gnome;
import java.io.File;
import java.io.IOException;
import java.net.ProxySelector;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.<API key>;
import javax.xml.parsers.<API key>;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import com.btr.proxy.search.ProxySearchStrategy;
import com.btr.proxy.selector.direct.NoProxySelector;
import com.btr.proxy.selector.fixed.FixedProxySelector;
import com.btr.proxy.selector.misc.<API key>;
import com.btr.proxy.selector.whitelist.<API key>;
import com.btr.proxy.util.EmptyXMLResolver;
import com.btr.proxy.util.Logger;
import com.btr.proxy.util.PlatformUtil;
import com.btr.proxy.util.ProxyException;
import com.btr.proxy.util.ProxyUtil;
import com.btr.proxy.util.Logger.LogLevel;
public class <API key> implements ProxySearchStrategy {
public <API key>() {
super();
}
public ProxySelector getProxySelector() throws ProxyException {
Logger.log(getClass(), LogLevel.TRACE, "Detecting Gnome proxy settings");
Properties settings = readSettings();
String type = settings.getProperty("/system/proxy/mode");
ProxySelector result = null;
if (type == null) {
String useProxy = settings.getProperty("/system/http_proxy/use_http_proxy");
if (useProxy == null) {
return null;
}
type = Boolean.parseBoolean(useProxy)?"manual":"none";
}
if ("none".equals(type)) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses no proxy");
result = NoProxySelector.getInstance();
}
if ("manual".equals(type)) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses manual proxy settings");
result = <API key>(settings);
}
if ("auto".equals(type)) {
String pacScriptUrl = settings.getProperty("/system/proxy/autoconfig_url", "");
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses autodetect script {0}", pacScriptUrl);
result = ProxyUtil.<API key>(pacScriptUrl);
}
// Wrap into white-list filter?
String noProxyList = settings.getProperty("/system/http_proxy/ignore_hosts", null);
if (result != null && noProxyList != null && noProxyList.trim().length() > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome uses proxy bypass list: {0}", noProxyList);
result = new <API key>(noProxyList, result);
}
return result;
}
public Properties readSettings() throws ProxyException {
Properties settings = new Properties();
try {
parseSettings("/system/proxy/", settings);
parseSettings("/system/http_proxy/", settings);
} catch (IOException e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings file error.", e);
throw new ProxyException(e);
}
return settings;
}
private File findSettingsFile(String context) {
// Normally we should inspect /etc/gconf/<version>/path to find out where the actual file is.
// But for normal systems this is always stored in .gconf folder in the user's home directory.
File userDir = new File(PlatformUtil.getUserHomeDir());
// Build directory path for context
StringBuilder path = new StringBuilder();
String[] parts = context.split("/");
for (String part : parts) {
path.append(part);
path.append(File.separator);
}
File settingsFile = new File(userDir, ".gconf"+File.separator+path.toString()+"%gconf.xml");
if (!settingsFile.exists()) {
Logger.log(getClass(), LogLevel.WARNING, "Gnome settings: {0} not found.", settingsFile);
return null;
}
return settingsFile;
}
private ProxySelector <API key>(Properties settings) {
if (!hasProxySettings(settings)) {
return null;
}
<API key> ps = new <API key>();
installHttpSelector(settings, ps);
if (useForAllProtocols(settings)) {
ps.setFallbackSelector(ps.getSelector("http"));
} else {
<API key>(settings, ps);
installFtpSelector(settings, ps);
<API key>(settings, ps);
}
return ps;
}
private boolean useForAllProtocols(Properties settings) {
return Boolean.parseBoolean(
settings.getProperty("/system/http_proxy/use_same_proxy", "false"));
}
private boolean hasProxySettings(Properties settings) {
String proxyHost = settings.getProperty("/system/http_proxy/host", null);
return proxyHost != null && proxyHost.length() > 0;
}
private void installHttpSelector(Properties settings,
<API key> ps) throws <API key> {
String proxyHost = settings.getProperty("/system/http_proxy/host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/http_proxy/port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome http proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("http", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
private void <API key>(Properties settings,
<API key> ps) throws <API key> {
String proxyHost = settings.getProperty("/system/proxy/socks_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/socks_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome socks proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("socks", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
private void installFtpSelector(Properties settings,
<API key> ps) throws <API key> {
String proxyHost = settings.getProperty("/system/proxy/ftp_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/ftp_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome ftp proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("ftp", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
private void <API key>(Properties settings,
<API key> ps) throws <API key> {
String proxyHost = settings.getProperty("/system/proxy/secure_host", null);
int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/secure_port", "0").trim());
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0) {
Logger.log(getClass(), LogLevel.TRACE, "Gnome secure proxy is {0}:{1}", proxyHost, proxyPort);
ps.setSelector("https", new FixedProxySelector(proxyHost.trim(), proxyPort));
ps.setSelector("sftp", new FixedProxySelector(proxyHost.trim(), proxyPort));
}
}
private Properties parseSettings(String context, Properties settings) throws IOException {
// Read settings from file
File settingsFile = findSettingsFile(context);
if (settingsFile == null) {
return settings;
}
try {
DocumentBuilder documentBuilder = <API key>.newInstance().newDocumentBuilder();
documentBuilder.setEntityResolver(new EmptyXMLResolver());
Document doc = documentBuilder.parse(settingsFile);
Element root = doc.getDocumentElement();
Node entry = root.getFirstChild();
while (entry != null) {
if ("entry".equals(entry.getNodeName()) && entry instanceof Element) {
String entryName = ((Element)entry).getAttribute("name");
settings.setProperty(context+entryName, getEntryValue((Element) entry));
}
entry = entry.getNextSibling();
}
} catch (SAXException e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e);
throw new IOException(e.getMessage());
} catch (<API key> e) {
Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e);
throw new IOException(e.getMessage());
}
return settings;
}
private String getEntryValue(Element entry) {
String type = entry.getAttribute("type");
if ("int".equals(type) || "bool".equals(type)) {
return entry.getAttribute("value");
}
if ("string".equals(type)) {
NodeList list = entry.<API key>("stringvalue");
if (list.getLength() > 0) {
return list.item(0).getTextContent();
}
}
if ("list".equals(type)) {
StringBuilder result = new StringBuilder();
NodeList list = entry.<API key>("li");
// Build comma separated list of items
for (int i = 0; i < list.getLength(); i++) {
if (result.length() > 0) {
result.append(",");
}
result.append(getEntryValue((Element) list.item(i)));
}
return result.toString();
}
return null;
}
}
|
package org.hbase.async;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mock;
import java.nio.charset.Charset;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.<API key>;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import org.hbase.async.HBaseClient.ZKClient;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.socket.SocketChannel;
import org.jboss.netty.channel.socket.SocketChannelConfig;
import org.jboss.netty.channel.socket.nio.NioClientBossPool;
import org.jboss.netty.channel.socket.nio.<API key>;
import org.jboss.netty.channel.socket.nio.NioWorkerPool;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.TimerTask;
import org.junit.Before;
import org.junit.Ignore;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.reflect.Whitebox;
import com.stumbleupon.async.Deferred;
@PrepareForTest({ HBaseClient.class, RegionClient.class, HBaseRpc.class,
GetRequest.class, RegionInfo.class, <API key>.class,
Executors.class, HashedWheelTimer.class, NioClientBossPool.class,
NioWorkerPool.class })
@Ignore // ignore for test runners
public class BaseTestHBaseClient {
protected static final Charset CHARSET = Charset.forName("ASCII");
protected static final byte[] COMMA = { ',' };
protected static final byte[] TIMESTAMP = "1234567890".getBytes();
protected static final byte[] INFO = getStatic("INFO");
protected static final byte[] REGIONINFO = getStatic("REGIONINFO");
protected static final byte[] SERVER = getStatic("SERVER");
protected static final byte[] TABLE = { 't', 'a', 'b', 'l', 'e' };
protected static final byte[] KEY = { 'k', 'e', 'y' };
protected static final byte[] KEY2 = { 'k', 'e', 'y', '2' };
protected static final byte[] FAMILY = { 'f' };
protected static final byte[] QUALIFIER = { 'q', 'u', 'a', 'l' };
protected static final byte[] VALUE = { 'v', 'a', 'l', 'u', 'e' };
protected static final byte[] EMPTY_ARRAY = new byte[0];
protected static final KeyValue KV = new KeyValue(KEY, FAMILY, QUALIFIER, VALUE);
protected static final RegionInfo meta = mkregion(".META.", ".META.,,1234567890");
protected static final RegionInfo region = mkregion("table", "table,,1234567890");
protected static final int RS_PORT = 50511;
protected static final String ROOT_IP = "192.168.0.1";
protected static final String META_IP = "192.168.0.2";
protected static final String REGION_CLIENT_IP = "192.168.0.3";
protected static String MOCK_RS_CLIENT_NAME = "Mock RegionClient";
protected static String <API key> = "Mock RootClient";
protected static String <API key> = "Mock MetaClient";
protected HBaseClient client = null;
/** Extracted from {@link #client}. */
protected <API key><byte[], RegionInfo> regions_cache;
/** Extracted from {@link #client}. */
protected ConcurrentHashMap<RegionInfo, RegionClient> region2client;
/** Extracted from {@link #client}. */
protected ConcurrentHashMap<RegionClient, ArrayList<RegionInfo>> client2regions;
/** Extracted from {@link #client}. */
protected <API key><byte[], ArrayList<HBaseRpc>> got_nsre;
/** Extracted from {@link #client}. */
protected HashMap<String, RegionClient> ip2client;
/** Extracted from {@link #client}. */
protected Counter num_nsre_rpcs;
/** Fake client supposedly connected to -ROOT-. */
protected RegionClient rootclient;
/** Fake client supposedly connected to .META.. */
protected RegionClient metaclient;
/** Fake client supposedly connected to our fake test table. */
protected RegionClient regionclient;
/** Each new region client is dumped here */
protected List<RegionClient> region_clients = new ArrayList<RegionClient>();
/** Fake Zookeeper client */
protected ZKClient zkclient;
/** Fake channel factory */
protected <API key> channel_factory;
/** Fake channel returned from the factory */
protected SocketChannel chan;
/** Fake timer for testing */
protected FakeTimer timer;
@Before
public void before() throws Exception {
region_clients.clear();
rootclient = mock(RegionClient.class);
when(rootclient.toString()).thenReturn(<API key>);
metaclient = mock(RegionClient.class);
when(metaclient.toString()).thenReturn(<API key>);
regionclient = mock(RegionClient.class);
when(regionclient.toString()).thenReturn(MOCK_RS_CLIENT_NAME);
zkclient = mock(ZKClient.class);
channel_factory = mock(<API key>.class);
chan = mock(SocketChannel.class);
timer = new FakeTimer();
when(zkclient.getDeferredRoot()).thenReturn(new Deferred<Object>());
PowerMockito.mockStatic(Executors.class);
PowerMockito.when(Executors.<API key>())
.thenReturn(mock(ThreadFactory.class));
PowerMockito.when(Executors.newCachedThreadPool())
.thenReturn(mock(ExecutorService.class));
PowerMockito.whenNew(<API key>.class).withAnyArguments()
.thenReturn(channel_factory);
PowerMockito.whenNew(HashedWheelTimer.class).withAnyArguments()
.thenReturn(timer);
PowerMockito.whenNew(NioClientBossPool.class).withAnyArguments()
.thenReturn(mock(NioClientBossPool.class));
PowerMockito.whenNew(NioWorkerPool.class).withAnyArguments()
.thenReturn(mock(NioWorkerPool.class));
client = PowerMockito.spy(new HBaseClient("test-quorum-spec"));
Whitebox.setInternalState(client, "zkclient", zkclient);
Whitebox.setInternalState(client, "rootregion", rootclient);
Whitebox.setInternalState(client, "jitter_percent", 0);
regions_cache = Whitebox.getInternalState(client, "regions_cache");
region2client = Whitebox.getInternalState(client, "region2client");
client2regions = Whitebox.getInternalState(client, "client2regions");
got_nsre = Whitebox.getInternalState(client, "got_nsre");
ip2client = Whitebox.getInternalState(client, "ip2client");
injectRegionInCache(meta, metaclient, META_IP + ":" + RS_PORT);
injectRegionInCache(region, regionclient, REGION_CLIENT_IP + ":" + RS_PORT);
when(channel_factory.newChannel(any(ChannelPipeline.class)))
.thenReturn(chan);
when(chan.getConfig()).thenReturn(mock(SocketChannelConfig.class));
when(rootclient.toString()).thenReturn("Mock RootClient");
PowerMockito.doAnswer(new Answer<RegionClient>(){
@Override
public RegionClient answer(InvocationOnMock invocation) throws Throwable {
final Object[] args = invocation.getArguments();
final String endpoint = (String)args[0] + ":" + (Integer)args[1];
final RegionClient rc = mock(RegionClient.class);
when(rc.getRemoteAddress()).thenReturn(endpoint);
client2regions.put(rc, new ArrayList<RegionInfo>());
region_clients.add(rc);
return rc;
}
}).when(client, "newClient", anyString(), anyInt());
}
/**
* Injects an entry in the local caches of the client.
*/
protected void injectRegionInCache(final RegionInfo region,
final RegionClient client,
final String ip) {
regions_cache.put(region.name(), region);
region2client.put(region, client);
ArrayList<RegionInfo> regions = client2regions.get(client);
if (regions == null) {
regions = new ArrayList<RegionInfo>(1);
client2regions.put(client, regions);
}
regions.add(region);
ip2client.put(ip, client);
}
// Helper functions. //
protected void clearCaches(){
regions_cache.clear();
region2client.clear();
client2regions.clear();
}
protected static <T> T getStatic(final String fieldname) {
return Whitebox.getInternalState(HBaseClient.class, fieldname);
}
/**
* Creates a fake {@code .META.} row.
* The row contains a single entry for all keys of {@link #TABLE}.
*/
protected static ArrayList<KeyValue> metaRow() {
return metaRow(HBaseClient.EMPTY_ARRAY, HBaseClient.EMPTY_ARRAY);
}
/**
* Creates a fake {@code .META.} row.
* The row contains a single entry for {@link #TABLE}.
* @param start_key The start key of the region in this entry.
* @param stop_key The stop key of the region in this entry.
*/
protected static ArrayList<KeyValue> metaRow(final byte[] start_key,
final byte[] stop_key) {
final ArrayList<KeyValue> row = new ArrayList<KeyValue>(2);
row.add(metaRegionInfo(start_key, stop_key, false, false, TABLE));
row.add(new KeyValue(region.name(), INFO, SERVER, "localhost:54321".getBytes()));
return row;
}
protected static KeyValue metaRegionInfo( final byte[] start_key,
final byte[] stop_key, final boolean offline, final boolean splitting,
final byte[] table) {
final byte[] name = concat(table, COMMA, start_key, COMMA, TIMESTAMP);
final byte is_splitting = (byte) (splitting ? 1 : 0);
final byte[] regioninfo = concat(
new byte[] {
0, // version
(byte) stop_key.length, // vint: stop key length
},
stop_key,
offline ? new byte[] { 1 } : new byte[] { 0 }, // boolean: offline
Bytes.fromLong(name.hashCode()), // long: region ID (make it random)
new byte[] { (byte) name.length }, // vint: region name length
name, // region name
new byte[] {
is_splitting, // boolean: splitting
(byte) start_key.length, // vint: start key length
},
start_key
);
return new KeyValue(region.name(), INFO, REGIONINFO, regioninfo);
}
protected static RegionInfo mkregion(final String table, final String name) {
return new RegionInfo(table.getBytes(), name.getBytes(),
HBaseClient.EMPTY_ARRAY);
}
protected static byte[] anyBytes() {
return any(byte[].class);
}
/** Concatenates byte arrays together. */
protected static byte[] concat(final byte[]... arrays) {
int len = 0;
for (final byte[] array : arrays) {
len += array.length;
}
final byte[] result = new byte[len];
len = 0;
for (final byte[] array : arrays) {
System.arraycopy(array, 0, result, len, array.length);
len += array.length;
}
return result;
}
/** Creates a new Deferred that's already called back. */
protected static <T> Answer<Deferred<T>> newDeferred(final T result) {
return new Answer<Deferred<T>>() {
public Deferred<T> answer(final InvocationOnMock invocation) {
return Deferred.fromResult(result);
}
};
}
/**
* A fake {@link Timer} implementation that fires up tasks immediately.
* Tasks are called immediately from the current thread and a history of the
* various tasks is logged.
*/
static final class FakeTimer extends HashedWheelTimer {
final List<Map.Entry<TimerTask, Long>> tasks =
new ArrayList<Map.Entry<TimerTask, Long>>();
final ArrayList<Timeout> timeouts = new ArrayList<Timeout>();
boolean run = true;
@Override
public Timeout newTimeout(final TimerTask task,
final long delay,
final TimeUnit unit) {
try {
tasks.add(new AbstractMap.SimpleEntry<TimerTask, Long>(task, delay));
if (run) {
task.run(null); // Argument never used in this code base.
}
final Timeout timeout = mock(Timeout.class);
timeouts.add(timeout);
return timeout; // Return value never used in this code base.
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Timer task failed: " + task, e);
}
}
@Override
public Set<Timeout> stop() {
run = false;
return new HashSet<Timeout>(timeouts);
}
}
/**
* A fake {@link org.jboss.netty.util.Timer} implementation.
* Instead of executing the task it will store that task in a internal state
* and provides a function to start the execution of the stored task.
* This implementation thus allows the flexibility of simulating the
* things that will be going on during the time out period of a TimerTask.
* This was mainly return to simulate the timeout period for
* alreadyNSREdRegion test, where the region will be in the NSREd mode only
* during this timeout period, which was difficult to simulate using the
* above {@link FakeTimer} implementation, as we don't get back the control
* during the timeout period
*
* Here it will hold at most two Tasks. We have two tasks here because when
* one is being executed, it may call for newTimeOut for another task.
*/
static final class FakeTaskTimer extends HashedWheelTimer {
protected TimerTask newPausedTask = null;
protected TimerTask pausedTask = null;
@Override
public synchronized Timeout newTimeout(final TimerTask task,
final long delay,
final TimeUnit unit) {
if (pausedTask == null) {
pausedTask = task;
} else if (newPausedTask == null) {
newPausedTask = task;
} else {
throw new <API key>("Cannot Pause Two Timer Tasks");
}
return null;
}
@Override
public Set<Timeout> stop() {
return null;
}
public boolean continuePausedTask() {
if (pausedTask == null) {
return false;
}
try {
if (newPausedTask != null) {
throw new <API key>("Cannot be in this state");
}
pausedTask.run(null); // Argument never used in this code base
pausedTask = newPausedTask;
newPausedTask = null;
return true;
} catch (Exception e) {
throw new RuntimeException("Timer task failed: " + pausedTask, e);
}
}
}
/**
* Generate and return a mocked HBase RPC for testing purposes with a valid
* Deferred that can be called on execution.
* @param deferred A deferred to watch for results
* @return The RPC to pass through unit tests.
*/
protected HBaseRpc getMockHBaseRpc(final Deferred<Object> deferred) {
final HBaseRpc rpc = mock(HBaseRpc.class);
rpc.attempt = 0;
when(rpc.getDeferred()).thenReturn(deferred);
when(rpc.toString()).thenReturn("MockRPC");
PowerMockito.doAnswer(new Answer<Void>() {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
if (deferred != null) {
deferred.callback(invocation.getArguments()[0]);
} else {
System.out.println("Deferred was null!!");
}
return null;
}
}).when(rpc).callback(Object.class);
return rpc;
}
}
|
#include "gb_thread.hpp"
#include "z80.hpp"
#include "memory.hpp"
#include "rom.hpp"
#include "cart_rom_only.hpp"
#include "cart_mbc1.hpp"
#include "cart_mbc5.hpp"
#include "internal_ram.hpp"
#include "video.hpp"
#include "timer.hpp"
#include "joypad.hpp"
#include "sound.hpp"
#include "debug.hpp"
#include "assert.hpp"
#include <cstdlib>
#include <vector>
#include <fstream>
#include <memory>
#include <chrono>
namespace
{
class stop_exception {};
std::unique_ptr<gb::memory_mapping> init_cartridge(gb::rom rom)
{
switch (rom.cartridge())
{
case 0x00: // ROM only (could have little RAM)
return std::make_unique<gb::cart_rom_only>(std::move(rom));
case 0x01: // MBC1
case 0x02: // MBC1+RAM
case 0x03: // MBC1+RAM+BATTERY
return std::make_unique<gb::cart_mbc1>(std::move(rom));
case 0x19: // MBC5
case 0x1A: // MBC5+RAM
case 0x1B: // MBC5+RAM+BATTERY
return std::make_unique<gb::cart_mbc5>(std::move(rom));
default:
throw gb::<API key>("Unknown cartridge type");
}
}
std::unique_ptr<gb::z80_cpu> init_cpu(gb::memory_mapping &cart, gb::internal_ram &internal_ram,
gb::video &video, gb::timer &timer, gb::joypad &joypad, gb::sound &sound)
{
// Make Memory
gb::memory_map memory;
memory.add_mapping(&cart);
memory.add_mapping(&internal_ram);
memory.add_mapping(&video);
memory.add_mapping(&timer);
memory.add_mapping(&joypad);
memory.add_mapping(&sound);
memory.write8(0xff05, 0x00);
memory.write8(0xff06, 0x00);
memory.write8(0xff07, 0x00);
memory.write8(0xff10, 0x80);
memory.write8(0xff11, 0xbf);
memory.write8(0xff12, 0xf3);
memory.write8(0xff14, 0xbf);
memory.write8(0xff16, 0x3f);
memory.write8(0xff17, 0x00);
memory.write8(0xff19, 0xbf);
memory.write8(0xff1a, 0x7f);
memory.write8(0xff1b, 0xff);
memory.write8(0xff1c, 0x9f);
memory.write8(0xff1e, 0xbf);
memory.write8(0xff20, 0xff);
memory.write8(0xff21, 0x00);
memory.write8(0xff22, 0x00);
memory.write8(0xff23, 0xbf);
memory.write8(0xff24, 0x77);
memory.write8(0xff25, 0xf3);
memory.write8(0xff26, 0xf1);
memory.write8(0xff40, 0x91);
memory.write8(0xff42, 0x00);
memory.write8(0xff43, 0x00);
memory.write8(0xff45, 0x00);
memory.write8(0xff47, 0xfc);
memory.write8(0xff48, 0xff);
memory.write8(0xff49, 0xff);
memory.write8(0xff4a, 0x00);
memory.write8(0xff4b, 0x00);
memory.write8(0xffff, 0x00);
// Register file
gb::register_file registers;
registers.write8<gb::register8::a>(0x11);
registers.write8<gb::register8::f>(0xb0);
registers.write16<gb::register16::bc>(0x0013);
registers.write16<gb::register16::de>(0x00d8);
registers.write16<gb::register16::hl>(0x014d);
registers.write16<gb::register16::sp>(0xfffe);
registers.write16<gb::register16::pc>(0x0100);
// Make Cpu
return std::make_unique<gb::z80_cpu>(std::move(memory), std::move(registers));
}
}
gb::gb_hardware::gb_hardware(rom arg_rom) :
cartridge(init_cartridge(std::move(arg_rom))),
cpu(init_cpu(*cartridge, internal_ram, video, timer, joypad, sound))
{
}
#define HEAVY_DEBUG 0
gb::cputime gb::gb_hardware::tick()
{
const auto time_fde = cpu-><API key>();
#if HEAVY_DEBUG
switch (cpu->current_opcode()->extra_bytes)
{
case 0:
debug(cpu->current_opcode()->mnemonic);
break;
case 1:
debug(cpu->current_opcode()->mnemonic, " $=", static_cast<int>(cpu->value8()));
break;
case 2:
debug(cpu->current_opcode()->mnemonic, " $=", static_cast<int>(cpu->value16()));
break;
default:
ASSERT_UNREACHABLE();
}
#endif
timer.tick(*cpu, time_fde);
const auto time_r = cpu->read();
timer.tick(*cpu, time_r);
const auto time_w = cpu->write();
timer.tick(*cpu, time_w);
const auto time = time_fde + time_r + time_w;
video.tick(*cpu, time);
#if HEAVY_DEBUG
cpu->registers().debug_print();
#endif
return time;
}
gb::gb_thread::gb_thread() :
_running(false)
{
}
gb::gb_thread::~gb_thread()
{
post_stop();
join();
}
void gb::gb_thread::start(gb::rom rom)
{
ASSERT(!_running);
_gb = std::make_unique<gb_hardware>(std::move(rom));
_thread = std::thread(&gb_thread::run, this);
_running = true;
}
void gb::gb_thread::join()
{
if (_running)
{
_thread.join();
}
}
void gb::gb_thread::post_stop()
{
command fn([](){
throw stop_exception();
});
std::lock_guard<std::mutex> lock(_mutex);
_command_queue.emplace_back(std::move(fn));
}
std::future<gb::video::raw_image> gb::gb_thread::post_get_image()
{
// TODO use capture by move (Visual Studio 2015/C++14)
auto promise = std::make_shared<std::promise<video::raw_image>>();
auto future = promise->get_future();
command fn([this, promise]() {
promise->set_value(_gb->video.image());
});
std::lock_guard<std::mutex> lock(_mutex);
_command_queue.emplace_back(std::move(fn));
return future;
}
void gb::gb_thread::post_key_down(gb::key key)
{
command fn([this, key]() {
_gb->joypad.down(key);
});
std::lock_guard<std::mutex> lock(_mutex);
_command_queue.emplace_back(std::move(fn));
}
void gb::gb_thread::post_key_up(gb::key key)
{
command fn([this, key]() {
_gb->joypad.up(key);
});
std::lock_guard<std::mutex> lock(_mutex);
_command_queue.emplace_back(std::move(fn));
}
void gb::gb_thread::run()
{
using namespace std::chrono;
using clock = steady_clock;
static_assert(clock::is_steady, "clock not steady");
static_assert(std::ratio_less_equal<clock::period, std::ratio_multiply<std::ratio<100>, std::nano>>::value,
"clock too inaccurate (period > 100ns)");
if (ASSERT_ENABLED)
debug("WARNING: asserts are enabled!");
debug("=====================================================");
// Let's go :)
std::vector<command> current_commands;
cputime gb_time(0);
auto real_time_start = clock::now();
cputime performance_gb_time(0);
nanoseconds <API key>(0);
auto performance_start = clock::now();
try
{
while (true)
{
// Command stream
{
std::lock_guard<std::mutex> lock(_mutex);
if (!_command_queue.empty())
{
std::swap(current_commands, _command_queue);
}
}
if (!current_commands.empty())
{
for (const auto &command : current_commands)
{
command();
}
current_commands.clear();
}
// Simulation itself
const auto time = _gb->tick();
// Time bookkeeping
gb_time += time;
const auto real_time = clock::now() - real_time_start;
const auto drift = duration_cast<nanoseconds>(gb_time) - real_time;
if (drift > milliseconds(5))
{
// Simulation is too fast
const auto sleep_start = clock::now();
std::this_thread::sleep_for(drift);
<API key> += (clock::now() - sleep_start);
const auto new_current_time = clock::now();
const auto new_real_time = new_current_time - real_time_start;
const auto new_drift = gb_time - duration_cast<cputime>(new_real_time);
gb_time = new_drift;
real_time_start = new_current_time;
}
else if (drift < milliseconds(-100))
{
// Simulation is too slow (reset counter to avoid an endless accumulation of negaitve time)
// This is a resync-attempt in case of a spike and avoids underflow
gb_time = cputime(0);
real_time_start = clock::now();
}
// Performance-o-meter
performance_gb_time += time;
const auto performance_now = clock::now();
const auto <API key> = performance_now - performance_start;
if (<API key> > seconds(10))
{
const auto accuracy =
duration_cast<milliseconds>(performance_gb_time - <API key>).count();
const double speed =
static_cast<double>(duration_cast<nanoseconds>(performance_gb_time).count()) /
static_cast<double>(duration_cast<nanoseconds>(<API key> - <API key>).count()) *
100.0;
debug("PERF: simulation drift in the last 10 s was ", accuracy, " ms");
debug("PERF: simulation speed in the last 10 s was ", speed, " % of required speed");
if (speed < 110.0)
{
debug("PERF WARNING: simulation speed is too low (< 110 %)");
}
<API key> = seconds(0);
performance_gb_time = cputime(0);
performance_start = performance_now;
}
}
}
catch (const stop_exception &)
{
// this might be ugly but it works well :)
}
}
|
"use strict";
var mapnik = require('../');
var assert = require('assert');
var path = require('path');
mapnik.register_datasource(path.join(mapnik.settings.paths.input_plugins,'geojson.input'));
describe('mapnik.Geometry ', function() {
it('should throw with invalid usage', function() {
// geometry cannot be created directly for now
assert.throws(function() { mapnik.Geometry(); });
});
it('should access a geometry from a feature', function() {
var feature = new mapnik.Feature(1);
var point = {
"type": "MultiPoint",
"coordinates": [[0,0],[1,1]]
};
var input = {
type: "Feature",
properties: {},
geometry: point
};
var f = new mapnik.Feature.fromJSON(JSON.stringify(input));
var geom = f.geometry();
assert.equal(geom.type(),mapnik.Geometry.MultiPoint);
assert.deepEqual(JSON.parse(geom.toJSONSync()),point);
var expected_wkb = new Buffer('0104000000020000000101000000000000000000000000000000000000000101000000000000000000f03f000000000000f03f', 'hex');
assert.deepEqual(geom.toWKB(),expected_wkb);
});
it('should fail on toJSON due to bad parameters', function() {
var feature = new mapnik.Feature(1);
var point = {
"type": "MultiPoint",
"coordinates": [[0,0],[1,1]]
};
var input = {
type: "Feature",
properties: {},
geometry: point
};
var f = new mapnik.Feature.fromJSON(JSON.stringify(input));
var geom = f.geometry();
assert.equal(geom.type(),mapnik.Geometry.MultiPoint);
assert.throws(function() { geom.toJSONSync(null); });
assert.throws(function() { geom.toJSONSync({transform:null}); });
assert.throws(function() { geom.toJSONSync({transform:{}}); });
assert.throws(function() { geom.toJSON(null, function(err,json) {}); });
assert.throws(function() { geom.toJSON({transform:null}, function(err, json) {}); });
assert.throws(function() { geom.toJSON({transform:{}}, function(err, json) {}); });
});
it('should throw if we attempt to create a Feature from a geojson geometry (rather than geojson feature)', function() {
var geometry = {
type: 'Point',
coordinates: [ 7.415119300000001, 43.730364300000005 ]
};
if (mapnik.versions.mapnik_number >= 300009) {
assert.throws(function() {
var transformed = mapnik.Feature.fromJSON(JSON.stringify(geometry));
});
}
});
it('should throw from empty geometry from toWKB', function() {
var s = new mapnik.Feature(1);
assert.throws(function() {
var geom = s.geometry().toWKB();
});
});
});
|
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model frontend\models\ManagerTrain */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => 'Manager Trains', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="manager-train-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'<API key>',
'cat_id',
'location',
'state_id',
'district_id',
'mukim_id',
'sub_base_id',
'cluster_id',
'kampung_id',
'alamat',
'poskod',
'nama_pengurus',
'ic',
'jantina',
'no_fon',
'date_enter',
'enter_by',
],
]) ?>
</div>
|
#ifndef <API key>
#define <API key>
#include <pcl/registration/<API key>.h>
template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> bool
pcl::registration::<API key><PointSource, PointTarget, NormalT, Scalar>::initCompute ()
{
if (!source_normals_ || !target_normals_)
{
PCL_WARN ("[pcl::registration::%s::initCompute] Datasets containing normals for source/target have not been given!\n", getClassName ().c_str ());
return (false);
}
return (<API key><PointSource, PointTarget, Scalar>::initCompute ());
}
template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void
pcl::registration::<API key><PointSource, PointTarget, NormalT, Scalar>::<API key> (
const pcl::PointCloud<NormalT> &cloud_in,
pcl::PointCloud<NormalT> &cloud_out,
const Eigen::Matrix<Scalar, 4, 4> &transform)
{
if (&cloud_in != &cloud_out)
{
// Note: could be replaced by cloud_out = cloud_in
cloud_out.header = cloud_in.header;
cloud_out.width = cloud_in.width;
cloud_out.height = cloud_in.height;
cloud_out.is_dense = cloud_in.is_dense;
cloud_out.points.reserve (cloud_out.points.size ());
cloud_out.points.assign (cloud_in.points.begin (), cloud_in.points.end ());
}
for (size_t i = 0; i < cloud_out.points.size (); ++i)
{
// Rotate normals (WARNING: transform.rotation () uses SVD internally!)
Eigen::Matrix<Scalar, 3, 1> nt (cloud_in[i].normal_x, cloud_in[i].normal_y, cloud_in[i].normal_z);
cloud_out[i].normal_x = static_cast<float> (transform (0, 0) * nt.coeffRef (0) + transform (0, 1) * nt.coeffRef (1) + transform (0, 2) * nt.coeffRef (2));
cloud_out[i].normal_y = static_cast<float> (transform (1, 0) * nt.coeffRef (0) + transform (1, 1) * nt.coeffRef (1) + transform (1, 2) * nt.coeffRef (2));
cloud_out[i].normal_z = static_cast<float> (transform (2, 0) * nt.coeffRef (0) + transform (2, 1) * nt.coeffRef (1) + transform (2, 2) * nt.coeffRef (2));
}
}
template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void
pcl::registration::<API key><PointSource, PointTarget, NormalT, Scalar>::<API key> (
pcl::Correspondences &correspondences, double max_distance)
{
if (!initCompute ())
return;
typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget;
correspondences.resize (indices_->size ());
std::vector<int> nn_indices (k_);
std::vector<float> nn_dists (k_);
float min_dist = std::numeric_limits<float>::max ();
int min_index = 0;
pcl::Correspondence corr;
unsigned int <API key> = 0;
// Check if the template types are the same. If true, avoid a copy.
// Both point types MUST be registered using the <API key> macro!
if (isSamePointType<PointSource, PointTarget> ())
{
PointTarget pt;
// Iterate over the input set of source indices
for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i)
{
tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists);
// Among the K nearest neighbours find the one with minimum perpendicular distance to the normal
min_dist = std::numeric_limits<float>::max ();
// Find the best correspondence
for (size_t j = 0; j < nn_indices.size (); j++)
{
float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x +
source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y +
source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ;
float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle);
if (dist < min_dist)
{
min_dist = dist;
min_index = static_cast<int> (j);
}
}
if (min_dist > max_distance)
continue;
corr.index_query = *idx_i;
corr.index_match = nn_indices[min_index];
corr.distance = nn_dists[min_index];//min_dist;
correspondences[<API key>++] = corr;
}
}
else
{
PointTarget pt;
// Iterate over the input set of source indices
for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i)
{
tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists);
// Among the K nearest neighbours find the one with minimum perpendicular distance to the normal
min_dist = std::numeric_limits<float>::max ();
// Find the best correspondence
for (size_t j = 0; j < nn_indices.size (); j++)
{
PointSource pt_src;
// Copy the source data to a target PointTarget format so we can search in the tree
pcl::for_each_type <FieldListTarget> (pcl::<API key> <PointSource, PointTarget> (
input_->points[*idx_i],
pt_src));
float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x +
source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y +
source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ;
float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle);
if (dist < min_dist)
{
min_dist = dist;
min_index = static_cast<int> (j);
}
}
if (min_dist > max_distance)
continue;
corr.index_query = *idx_i;
corr.index_match = nn_indices[min_index];
corr.distance = nn_dists[min_index];//min_dist;
correspondences[<API key>++] = corr;
}
}
correspondences.resize (<API key>);
deinitCompute ();
}
template <typename PointSource, typename PointTarget, typename NormalT, typename Scalar> void
pcl::registration::<API key><PointSource, PointTarget, NormalT, Scalar>::<API key> (
pcl::Correspondences &correspondences, double max_distance)
{
if (!initCompute ())
return;
typedef typename pcl::traits::fieldList<PointSource>::type FieldListSource;
typedef typename pcl::traits::fieldList<PointTarget>::type FieldListTarget;
typedef typename pcl::intersect<FieldListSource, FieldListTarget>::type FieldList;
// setup tree for reciprocal search
pcl::KdTreeFLANN<PointSource> tree_reciprocal;
// Set the internal point representation of choice
if (<API key>)
tree_reciprocal.<API key> (<API key>);
tree_reciprocal.setInputCloud (input_, indices_);
correspondences.resize (indices_->size ());
std::vector<int> nn_indices (k_);
std::vector<float> nn_dists (k_);
std::vector<int> index_reciprocal (1);
std::vector<float> distance_reciprocal (1);
float min_dist = std::numeric_limits<float>::max ();
int min_index = 0;
pcl::Correspondence corr;
unsigned int <API key> = 0;
int target_idx = 0;
// Check if the template types are the same. If true, avoid a copy.
// Both point types MUST be registered using the <API key> macro!
if (isSamePointType<PointSource, PointTarget> ())
{
PointTarget pt;
// Iterate over the input set of source indices
for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i)
{
tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists);
// Among the K nearest neighbours find the one with minimum perpendicular distance to the normal
min_dist = std::numeric_limits<float>::max ();
// Find the best correspondence
for (size_t j = 0; j < nn_indices.size (); j++)
{
float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x +
source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y +
source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ;
float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle);
if (dist < min_dist)
{
min_dist = dist;
min_index = static_cast<int> (j);
}
}
if (min_dist > max_distance)
continue;
// Check if the correspondence is reciprocal
target_idx = nn_indices[min_index];
tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal);
if (*idx_i != index_reciprocal[0])
continue;
corr.index_query = *idx_i;
corr.index_match = nn_indices[min_index];
corr.distance = nn_dists[min_index];//min_dist;
correspondences[<API key>++] = corr;
}
}
else
{
PointTarget pt;
// Iterate over the input set of source indices
for (std::vector<int>::const_iterator idx_i = indices_->begin (); idx_i != indices_->end (); ++idx_i)
{
tree_->nearestKSearch (input_->points[*idx_i], k_, nn_indices, nn_dists);
// Among the K nearest neighbours find the one with minimum perpendicular distance to the normal
min_dist = std::numeric_limits<float>::max ();
// Find the best correspondence
for (size_t j = 0; j < nn_indices.size (); j++)
{
PointSource pt_src;
// Copy the source data to a target PointTarget format so we can search in the tree
pcl::for_each_type <FieldListTarget> (pcl::<API key> <PointSource, PointTarget> (
input_->points[*idx_i],
pt_src));
float cos_angle = source_normals_->points[*idx_i].normal_x * target_normals_->points[nn_indices[j]].normal_x +
source_normals_->points[*idx_i].normal_y * target_normals_->points[nn_indices[j]].normal_y +
source_normals_->points[*idx_i].normal_z * target_normals_->points[nn_indices[j]].normal_z ;
float dist = nn_dists[min_index] * (2.0f - cos_angle * cos_angle);
if (dist < min_dist)
{
min_dist = dist;
min_index = static_cast<int> (j);
}
}
if (min_dist > max_distance)
continue;
// Check if the correspondence is reciprocal
target_idx = nn_indices[min_index];
tree_reciprocal.nearestKSearch (target_->points[target_idx], 1, index_reciprocal, distance_reciprocal);
if (*idx_i != index_reciprocal[0])
continue;
corr.index_query = *idx_i;
corr.index_match = nn_indices[min_index];
corr.distance = nn_dists[min_index];//min_dist;
correspondences[<API key>++] = corr;
}
}
correspondences.resize (<API key>);
deinitCompute ();
}
#endif // <API key>
|
package xcordion.impl.command;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.junit.Test;
import org.junit.Ignore;
public class ForEachCommandTest {
@Test
@Ignore
public void testPlaceholder() {
Assert.fail("WRITE ME");
}
}
|
#ifndef <API key>
#define <API key>
// .NAME <API key> - a subclass of <API key> for vtkDataSet objects.
// .SECTION Description
// This is a subclass of <API key> that is used for
// tessellating cells of a vtkDataSet, particularly nonlinear
// cells.
// It provides functions for setting the current cell being tessellated and a
// convenience routine, \a EvaluateFields() to evaluate field values at a
// point. You should call \a EvaluateFields() from inside \a EvaluateEdge()
// whenever the result of \a EvaluateEdge() will be true. Otherwise, do
// not call \a EvaluateFields() as the midpoint is about to be discarded.
// (<i>Implementor's note</i>: This isn't true if <API key>
// has been defined. But in that case, we don't want the exact field values;
// we need the linearly interpolated ones at the midpoint for continuity.)
// .SECTION See Also
// <API key>
#include "<API key>.h" // For export macro
#include "<API key>.h"
class vtkCell;
class vtkDataSet;
class <API key> <API key> : public <API key>
{
public:
vtkTypeMacro(<API key>,<API key>);
static <API key>* New();
virtual void PrintSelf( ostream& os, vtkIndent indent );
virtual void SetMesh( vtkDataSet* );
vtkDataSet* GetMesh();
//BTX
const vtkDataSet* GetMesh() const;
//ETX
virtual void SetCellId( vtkIdType cell );
vtkIdType GetCellId() const;
//BTX
vtkIdType& GetCellId();
//ETX
vtkCell* GetCell();
//BTX
const vtkCell* GetCell() const;
//ETX
virtual bool EvaluateEdge( const double* p0, double* midpt, const double* p1, int field_start );
// Description:
// Evaluate all of the fields that should be output with the
// given \a vertex and store them just past the parametric coordinates
// of \a vertex, at the offsets given by
// \p <API key>::GetFieldOffsets() plus \a field_start.
// \a field_start contains the number of world-space coordinates (always 3)
// plus the embedding dimension (the size of the parameter-space in which
// the cell is embedded). It will range between 3 and 6, inclusive.
// You must have called SetCellId() before calling this routine or there
// will not be a mesh over which to evaluate the fields.
// You must have called \p <API key>::PassDefaultFields()
// or \p <API key>::PassField() or there will be no fields
// defined for the output vertex.
// This routine is public and returns its input argument so that it
// may be used as an argument to
// \p <API key>::<API key>():
// @verbatim
// <API key>* t = <API key>::New();
// <API key>* s;
// t-><API key>( s->EvaluateFields( p0 ), s->EvaluateFields( p1 ) );
// @endverbatim
// Although this will work, using \p EvaluateFields() in this manner
// should be avoided. It's much more efficient to fetch the corner values
// for each attribute and copy them into \a p0, \a p1, ... as opposed to
// performing shape function evaluations. The only case where you wouldn't
// want to do this is when the field you are interpolating is discontinuous
// at cell borders, such as with a discontinuous galerkin method or when
// all the Gauss points for quadrature are interior to the cell.
// The final argument, \a weights, is the array of weights to apply to each
// point's data when interpolating the field. This is returned by
// \a vtkCell::EvaluateLocation() when evaluating the geometry.
double* EvaluateFields( double* vertex, double* weights, int field_start );
// Description:
// Evaluate either a cell or nodal field.
// This exists because of the funky way that Exodus data will be handled.
// Sure, it's a hack, but what are ya gonna do?
void <API key>( double* result, double* weights, int field );
void <API key>( double* result, double* weights, int field );
// Description:
// Get/Set the square of the allowable chord error at any edge's midpoint.
// This value is used by EvaluateEdge.
vtkSetMacro(ChordError2,double);
vtkGetMacro(ChordError2,double);
// Description:
// Get/Set the square of the allowable error magnitude for the
// scalar field \a s at any edge's midpoint.
// A value less than or equal to 0 indicates that the field
// should not be used as a criterion for subdivision.
virtual void SetFieldError2( int s, double err );
double GetFieldError2( int s ) const;
// Description:
// Tell the subdivider not to use any field values as subdivision criteria.
// Effectively calls SetFieldError2( a, -1. ) for all fields.
virtual void ResetFieldError2();
// Description:
// Return a bitfield specifying which FieldError2 criteria are positive (i.e., actively
// used to decide edge subdivisions).
// This is stored as separate state to make subdivisions go faster.
vtkGetMacro(ActiveFieldCriteria,int);
int <API key>() const { return this->ActiveFieldCriteria; }
protected:
<API key>();
virtual ~<API key>();
vtkDataSet* CurrentMesh;
vtkIdType CurrentCellId;
vtkCell* CurrentCellData;
double ChordError2;
double* FieldError2;
int FieldError2Length;
int FieldError2Capacity;
int ActiveFieldCriteria;
private:
<API key>( const <API key>& ); // Not implemented.
void operator = ( const <API key>& ); // Not implemented.
};
//BTX
inline vtkIdType& <API key>::GetCellId() { return this->CurrentCellId; }
inline vtkIdType <API key>::GetCellId() const { return this->CurrentCellId; }
inline vtkDataSet* <API key>::GetMesh() { return this->CurrentMesh; }
inline const vtkDataSet* <API key>::GetMesh() const { return this->CurrentMesh; }
inline vtkCell* <API key>::GetCell() { return this->CurrentCellData; }
inline const vtkCell* <API key>::GetCell() const { return this->CurrentCellData; }
//ETX
#endif // <API key>
|
// Use of this source code is governed by a BSD-style
package asm
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"testing"
"cmd/asm/internal/lex"
"cmd/internal/obj"
"cmd/internal/objabi"
)
// An end-to-end test for the assembler: Do we print what we parse?
// Output is generated by, in effect, turning on -S and comparing the
// result against a golden file.
func testEndToEnd(t *testing.T, goarch, file string) {
input := filepath.Join("testdata", file+".s")
architecture, ctxt := setArch(goarch)
architecture.Init(ctxt)
lexer := lex.NewLexer(input)
parser := NewParser(ctxt, architecture, lexer)
pList := new(obj.Plist)
var ok bool
testOut = new(bytes.Buffer) // The assembler writes test output to this buffer.
ctxt.Bso = bufio.NewWriter(os.Stdout)
defer ctxt.Bso.Flush()
failed := false
ctxt.DiagFunc = func(format string, args ...interface{}) {
failed = true
t.Errorf(format, args...)
}
pList.Firstpc, ok = parser.Parse()
if !ok || failed {
t.Errorf("asm: %s assembly failed", goarch)
return
}
output := strings.Split(testOut.String(), "\n")
// Reconstruct expected output by independently "parsing" the input.
data, err := ioutil.ReadFile(input)
if err != nil {
t.Error(err)
return
}
lineno := 0
seq := 0
hexByLine := map[string]string{}
lines := strings.SplitAfter(string(data), "\n")
Diff:
for _, line := range lines {
lineno++
// Ignore include of textflag.h.
if strings.HasPrefix(line, "#include ") {
continue
}
// The general form of a test input line is:
// // comment
// INST args [// printed form] [// hex encoding]
parts := strings.Split(line, "
printed := strings.TrimSpace(parts[0])
if printed == "" || strings.HasSuffix(printed, ":") { // empty or label
continue
}
seq++
var hexes string
switch len(parts) {
default:
t.Errorf("%s:%d: unable to understand comments: %s", input, lineno, line)
case 1:
// no comment
case 2:
// might be printed form or hex
note := strings.TrimSpace(parts[1])
if isHexes(note) {
hexes = note
} else {
printed = note
}
case 3:
// printed form, then hex
printed = strings.TrimSpace(parts[1])
hexes = strings.TrimSpace(parts[2])
if !isHexes(hexes) {
t.Errorf("%s:%d: malformed hex instruction encoding: %s", input, lineno, line)
}
}
if hexes != "" {
hexByLine[fmt.Sprintf("%s:%d", input, lineno)] = hexes
}
// Canonicalize spacing in printed form.
// First field is opcode, then tab, then arguments separated by spaces.
// Canonicalize spaces after commas first.
// Comma to separate argument gets a space; comma within does not.
var buf []byte
nest := 0
for i := 0; i < len(printed); i++ {
c := printed[i]
switch c {
case '{', '[':
nest++
case '}', ']':
nest
case ',':
buf = append(buf, ',')
if nest == 0 {
buf = append(buf, ' ')
}
for i+1 < len(printed) && (printed[i+1] == ' ' || printed[i+1] == '\t') {
i++
}
continue
}
buf = append(buf, c)
}
f := strings.Fields(string(buf))
// Turn relative (PC) into absolute (PC) automatically,
// so that most branch instructions don't need comments
// giving the absolute form.
if len(f) > 0 && strings.HasSuffix(printed, "(PC)") {
last := f[len(f)-1]
n, err := strconv.Atoi(last[:len(last)-len("(PC)")])
if err == nil {
f[len(f)-1] = fmt.Sprintf("%d(PC)", seq+n)
}
}
if len(f) == 1 {
printed = f[0]
} else {
printed = f[0] + "\t" + strings.Join(f[1:], " ")
}
want := fmt.Sprintf("%05d (%s:%d)\t%s", seq, input, lineno, printed)
for len(output) > 0 && (output[0] < want || output[0] != want && len(output[0]) >= 5 && output[0][:5] == want[:5]) {
if len(output[0]) >= 5 && output[0][:5] == want[:5] {
t.Errorf("mismatched output:\nhave %s\nwant %s", output[0], want)
output = output[1:]
continue Diff
}
t.Errorf("unexpected output: %q", output[0])
output = output[1:]
}
if len(output) > 0 && output[0] == want {
output = output[1:]
} else {
t.Errorf("missing output: %q", want)
}
}
for len(output) > 0 {
if output[0] == "" {
// spurious blank caused by Split on "\n"
output = output[1:]
continue
}
t.Errorf("unexpected output: %q", output[0])
output = output[1:]
}
// Checked printing.
// Now check machine code layout.
top := pList.Firstpc
var text *obj.LSym
ok = true
ctxt.DiagFunc = func(format string, args ...interface{}) {
t.Errorf(format, args...)
ok = false
}
obj.Flushplist(ctxt, pList, nil, "")
for p := top; p != nil; p = p.Link {
if p.As == obj.ATEXT {
text = p.From.Sym
}
hexes := hexByLine[p.Line()]
if hexes == "" {
continue
}
delete(hexByLine, p.Line())
if text == nil {
t.Errorf("%s: instruction outside TEXT", p)
}
size := int64(len(text.P)) - p.Pc
if p.Link != nil {
size = p.Link.Pc - p.Pc
} else if p.Isize != 0 {
size = int64(p.Isize)
}
var code []byte
if p.Pc < int64(len(text.P)) {
code = text.P[p.Pc:]
if size < int64(len(code)) {
code = code[:size]
}
}
codeHex := fmt.Sprintf("%x", code)
if codeHex == "" {
codeHex = "empty"
}
ok := false
for _, hex := range strings.Split(hexes, " or ") {
if codeHex == hex {
ok = true
break
}
}
if !ok {
t.Errorf("%s: have encoding %s, want %s", p, codeHex, hexes)
}
}
if len(hexByLine) > 0 {
var missing []string
for key := range hexByLine {
missing = append(missing, key)
}
sort.Strings(missing)
for _, line := range missing {
t.Errorf("%s: did not find instruction encoding", line)
}
}
}
func isHexes(s string) bool {
if s == "" {
return false
}
if s == "empty" {
return true
}
for _, f := range strings.Split(s, " or ") {
if f == "" || len(f)%2 != 0 || strings.TrimLeft(f, "0123456789abcdef") != "" {
return false
}
}
return true
}
// It would be nice if the error messages began with
// the standard file:line: prefix,
// but that's not where we are today.
// It might be at the beginning but it might be in the middle of the printed instruction.
var fileLineRE = regexp.MustCompile(`(?:^|\()(testdata[/\\][0-9a-z]+\.s:[0-9]+)(?:$|\))`)
// Same as in test/run.go
var (
errRE = regexp.MustCompile(`// ERROR ?(.*)`)
errQuotesRE = regexp.MustCompile(`"([^"]*)"`)
)
func testErrors(t *testing.T, goarch, file string) {
input := filepath.Join("testdata", file+".s")
architecture, ctxt := setArch(goarch)
lexer := lex.NewLexer(input)
parser := NewParser(ctxt, architecture, lexer)
pList := new(obj.Plist)
var ok bool
testOut = new(bytes.Buffer) // The assembler writes test output to this buffer.
ctxt.Bso = bufio.NewWriter(os.Stdout)
defer ctxt.Bso.Flush()
failed := false
var errBuf bytes.Buffer
ctxt.DiagFunc = func(format string, args ...interface{}) {
failed = true
s := fmt.Sprintf(format, args...)
if !strings.HasSuffix(s, "\n") {
s += "\n"
}
errBuf.WriteString(s)
}
pList.Firstpc, ok = parser.Parse()
obj.Flushplist(ctxt, pList, nil, "")
if ok && !failed {
t.Errorf("asm: %s had no errors", goarch)
}
errors := map[string]string{}
for _, line := range strings.Split(errBuf.String(), "\n") {
if line == "" || strings.HasPrefix(line, "\t") {
continue
}
m := fileLineRE.FindStringSubmatch(line)
if m == nil {
t.Errorf("unexpected error: %v", line)
continue
}
fileline := m[1]
if errors[fileline] != "" && errors[fileline] != line {
t.Errorf("multiple errors on %s:\n\t%s\n\t%s", fileline, errors[fileline], line)
continue
}
errors[fileline] = line
}
// Reconstruct expected errors by independently "parsing" the input.
data, err := ioutil.ReadFile(input)
if err != nil {
t.Error(err)
return
}
lineno := 0
lines := strings.Split(string(data), "\n")
for _, line := range lines {
lineno++
fileline := fmt.Sprintf("%s:%d", input, lineno)
if m := errRE.FindStringSubmatch(line); m != nil {
all := m[1]
mm := errQuotesRE.<API key>(all, -1)
if len(mm) != 1 {
t.Errorf("%s: invalid errorcheck line:\n%s", fileline, line)
} else if err := errors[fileline]; err == "" {
t.Errorf("%s: missing error, want %s", fileline, all)
} else if !strings.Contains(err, mm[0][1]) {
t.Errorf("%s: wrong error for %s:\n%s", fileline, all, err)
}
} else {
if errors[fileline] != "" {
t.Errorf("unexpected error on %s: %v", fileline, errors[fileline])
}
}
delete(errors, fileline)
}
var extra []string
for key := range errors {
extra = append(extra, key)
}
sort.Strings(extra)
for _, fileline := range extra {
t.Errorf("unexpected error on %s: %v", fileline, errors[fileline])
}
}
func Test386EndToEnd(t *testing.T) {
defer func(old string) { objabi.GO386 = old }(objabi.GO386)
for _, go386 := range []string{"387", "sse2"} {
t.Logf("GO386=%v", go386)
objabi.GO386 = go386
testEndToEnd(t, "386", "386")
}
}
func TestARMEndToEnd(t *testing.T) {
defer func(old int) { objabi.GOARM = old }(objabi.GOARM)
for _, goarm := range []int{5, 6, 7} {
t.Logf("GOARM=%d", goarm)
objabi.GOARM = goarm
testEndToEnd(t, "arm", "arm")
if goarm == 6 {
testEndToEnd(t, "arm", "armv6")
}
}
}
func TestARMErrors(t *testing.T) {
testErrors(t, "arm", "armerror")
}
func TestARM64EndToEnd(t *testing.T) {
testEndToEnd(t, "arm64", "arm64")
}
func TestARM64Encoder(t *testing.T) {
testEndToEnd(t, "arm64", "arm64enc")
}
func TestARM64Errors(t *testing.T) {
testErrors(t, "arm64", "arm64error")
}
func TestAMD64EndToEnd(t *testing.T) {
testEndToEnd(t, "amd64", "amd64")
}
func Test386Encoder(t *testing.T) {
testEndToEnd(t, "386", "386enc")
}
func TestAMD64Encoder(t *testing.T) {
testEndToEnd(t, "amd64", "amd64enc")
testEndToEnd(t, "amd64", "amd64enc_extra")
}
func TestAMD64Errors(t *testing.T) {
testErrors(t, "amd64", "amd64error")
}
func TestMIPSEndToEnd(t *testing.T) {
testEndToEnd(t, "mips", "mips")
testEndToEnd(t, "mips64", "mips64")
}
func TestPPC64EndToEnd(t *testing.T) {
testEndToEnd(t, "ppc64", "ppc64")
}
func TestPPC64Encoder(t *testing.T) {
testEndToEnd(t, "ppc64", "ppc64enc")
}
func TestS390XEndToEnd(t *testing.T) {
testEndToEnd(t, "s390x", "s390x")
}
|
#include "chrome/app/android/chrome_jni_onload.h"
#include "chrome/app/android/<API key>.h"
#include "content/public/app/content_jni_onload.h"
namespace android {
bool OnJNIOnLoadInit() {
if (!content::android::OnJNIOnLoadInit())
return false;
return RunChrome();
}
} // namespace android
|
/*
* ctm-cvb
*
* <API key>
*/
#ifndef <API key>
#define <API key>
#include "InferenceEngine.h"
#include <gsl/gsl_vector.h>
#include <gsl/gsl_matrix.h>
namespace ctm
{
class <API key> : public InferenceEngine
{
/***
* Model hyperparameters learnt by maximisation
*/
struct Model
{
gsl_vector* mu;
gsl_matrix* cov;
gsl_matrix* inv_cov;
gsl_matrix* log_beta;
double gamma;
double log_det_inv_cov;
Model( int D, int K, int V );
~Model();
};
/***
* Data collected in the 'expectation' step, to be used in the
* maximisation step.
*/
struct CollectedData
{
// Expected counts
gsl_matrix* n_ij;
gsl_matrix* n_jk;
double ndata;
CollectedData( int D, int K, int V );
~CollectedData();
};
/***
* Variational parameters to be optimised in the expectation step
*/
struct Parameters
{
// Stores \phi_{*kj}
gsl_matrix* phi;
gsl_matrix* log_phi;
// Likelihood saved for optimisation purposes
double lhood;
Parameters( int K, int V );
~Parameters();
};
public:
<API key>(InferenceOptions& options);
// Load/Store in a file
virtual void init( string filename );
virtual void save( string filename );
// Parse a single file
virtual double infer( Corpus& data );
virtual double infer( Corpus& data, CollectedData* cd );
virtual void estimate( Corpus& data );
protected:
Model* model;
};
};
#endif // <API key>
|
isPrime :: Integral a => a -> Bool
isPrime 2 = True
isPrime 3 = True
isPrime n =
all (\ x -> x /= 0)
[n `mod` x | x <- [2..(truncate $ sqrt (fromIntegral n) + 1)]]
goldbach :: (Integral t, Integral t1) => t1 -> (t, t1)
goldbach n = goldbach' 3 (n - 3)
where
goldbach' a b
| isPrime a && isPrime b = (a, b)
| otherwise = goldbach' (a + 2) (b - 2)
|
package visualoozie.api;
public class WorkflowNode {
public enum NodeType{
START
, KILL
, DECISION
, FORK
, JOIN
, END
, ACTION
}
private String name;
private NodeType type;
private String[] to;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public NodeType getType() { return type; }
public void setType(NodeType type) { this.type = type; }
public String[] getTo() { return to; }
public void setTo(String[] to) { this.to = to; }
}
|
/* TEMPLATE GENERATED TESTCASE FILE
Filename: <API key>.cpp
Label Definition File: <API key>.strings.label.xml
Template File: sources-sink-43.tmpl.cpp
*/
/*
* @description
* CWE: 78 OS Command Injection
* BadSource: file Read input from a file
* GoodSource: Fixed string
* Sinks: execl
* BadSink : execute command with execl
* Flow Variant: 43 Data flow: data flows using a C++ reference from one function to another in the same source file
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifdef _WIN32
#define COMMAND_INT_PATH "%WINDIR%\\system32\\cmd.exe"
#define COMMAND_INT "cmd.exe"
#define COMMAND_ARG1 "/c"
#define COMMAND_ARG2 "dir "
#define COMMAND_ARG3 data
#else /* NOT _WIN32 */
#include <unistd.h>
#define COMMAND_INT_PATH "/bin/sh"
#define COMMAND_INT "sh"
#define COMMAND_ARG1 "-c"
#define COMMAND_ARG2 "ls "
#define COMMAND_ARG3 data
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#ifdef _WIN32
#include <process.h>
#define EXECL _execl
#else /* NOT _WIN32 */
#define EXECL execl
#endif
namespace <API key>
{
#ifndef OMITBAD
static void badSource(char * &data)
{
{
/* Read input from a file */
size_t dataLen = strlen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (100-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgets(data+dataLen, (int)(100-dataLen), pFile) == NULL)
{
printLine("fgets() failed");
/* Restore NUL terminator if fgets fails */
data[dataLen] = '\0';
}
fclose(pFile);
}
}
}
}
void bad()
{
char * data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
badSource(data);
/* execl - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL);
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSource(char * &data)
{
/* FIX: Append a fixed string to data (not user / external input) */
strcat(data, "*.*");
}
static void goodG2B()
{
char * data;
char dataBuffer[100] = COMMAND_ARG2;
data = dataBuffer;
goodG2BSource(data);
/* execl - specify the path where the command is located */
/* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */
EXECL(COMMAND_INT_PATH, COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG3, NULL);
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
using namespace <API key>; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
|
INSTALL_DIR=usr/local/lib
DEPS="coreutils" "sudo"
REBARPROFILE ?= default
include ../../config.mk
include ../../_build/${REBARPROFILE}/lib/fifo_utils/priv/pkgng.mk
.PHONY: prepare
prepare:
-rm -r $(STAGE_DIR)/$(INSTALL_DIR)/$(COMPONENT_INTERNAL)
-rm $(STAGE_DIR)/+*
-rm $(STAGE_DIR)/plist
mkdir -p $(STAGE_DIR)/$(INSTALL_DIR)
cp -r ../../_build/${REBARPROFILE}/rel/$(COMPONENT_INTERNAL) $(STAGE_DIR)/$(INSTALL_DIR)/$(COMPONENT_INTERNAL)
|
#include "atkbdc.h"
#include "opt_kbd.h"
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/syslog.h>
#include <machine/clock.h>
#include <dev/kbd/atkbdcreg.h>
#ifndef __i386__
#include <isa/isareg.h>
#else
#include <i386/isa/isa.h>
#endif
/* constants */
#define MAXKBDC MAX(NATKBDC, 1)
/* macros */
#ifndef MAX
#define MAX(x, y) ((x) > (y) ? (x) : (y))
#endif
#define kbdcp(p) ((atkbdc_softc_t *)(p))
#define nextq(i) (((i) + 1) % KBDQ_BUFSIZE)
#define availq(q) ((q)->head != (q)->tail)
#if KBDIO_DEBUG >= 2
#define emptyq(q) ((q)->tail = (q)->head = (q)->qcount = 0)
#else
#define emptyq(q) ((q)->tail = (q)->head = 0)
#endif
/* local variables */
/*
* We always need at least one copy of the kbdc_softc struct for the
* low-level console. As the low-level console accesses the keyboard
* controller before kbdc, and all other devices, is probed, we
* statically allocate one entry. XXX
*/
static atkbdc_softc_t default_kbdc;
static atkbdc_softc_t *atkbdc_softc[MAXKBDC] = { &default_kbdc };
static int verbose = KBDIO_DEBUG;
/* function prototypes */
static int atkbdc_setup(atkbdc_softc_t *sc, int port);
static int addq(kqueue *q, int c);
static int removeq(kqueue *q);
static int <API key>(atkbdc_softc_t *kbdc);
static int wait_for_data(atkbdc_softc_t *kbdc);
static int wait_for_kbd_data(atkbdc_softc_t *kbdc);
static int wait_for_kbd_ack(atkbdc_softc_t *kbdc);
static int wait_for_aux_data(atkbdc_softc_t *kbdc);
static int wait_for_aux_ack(atkbdc_softc_t *kbdc);
#if NATKBDC > 0
atkbdc_softc_t
*atkbdc_get_softc(int unit)
{
atkbdc_softc_t *sc;
if (unit >= sizeof(atkbdc_softc)/sizeof(atkbdc_softc[0]))
return NULL;
sc = atkbdc_softc[unit];
if (sc == NULL) {
sc = atkbdc_softc[unit]
= malloc(sizeof(*sc), M_DEVBUF, M_NOWAIT);
if (sc == NULL)
return NULL;
bzero(sc, sizeof(*sc));
sc->port = -1; /* XXX */
}
return sc;
}
int
atkbdc_probe_unit(atkbdc_softc_t *sc, int unit, int port)
{
return atkbdc_setup(sc, port);
}
#endif /* NATKBDC > 0 */
/* the backdoor to the keyboard controller! XXX */
int
atkbdc_configure(void)
{
return atkbdc_setup(atkbdc_softc[0], -1);
}
static int
atkbdc_setup(atkbdc_softc_t *sc, int port)
{
if (port <= 0)
port = IO_KBD;
if (sc->port <= 0) {
sc->command_byte = -1;
sc->command_mask = 0;
sc->lock = FALSE;
sc->kbd.head = sc->kbd.tail = 0;
sc->aux.head = sc->aux.tail = 0;
#if KBDIO_DEBUG >= 2
sc->kbd.call_count = 0;
sc->kbd.qcount = sc->kbd.max_qcount = 0;
sc->aux.call_count = 0;
sc->aux.qcount = sc->aux.max_qcount = 0;
#endif
}
sc->port = port; /* may override the previous value */
return 0;
}
/* associate a port number with a KBDC */
KBDC
kbdc_open(int port)
{
int s;
int i;
if (port <= 0)
port = IO_KBD;
s = spltty();
for (i = 0; i < sizeof(atkbdc_softc)/sizeof(atkbdc_softc[0]); ++i) {
if (atkbdc_softc[i] == NULL)
continue;
if (atkbdc_softc[i]->port == port) {
splx(s);
return (KBDC)atkbdc_softc[i];
}
if (atkbdc_softc[i]->port <= 0) {
if (atkbdc_setup(atkbdc_softc[i], port))
break;
splx(s);
return (KBDC)atkbdc_softc[i];
}
}
splx(s);
return NULL;
}
/*
* I/O access arbitration in `kbdio'
*
* The `kbdio' module uses a simplistic convention to arbitrate
* I/O access to the controller/keyboard/mouse. The convention requires
* close cooperation of the calling device driver.
*
* The device driver which utilizes the `kbdio' module are assumed to
* have the following set of routines.
* a. An interrupt handler (the bottom half of the driver).
* b. Timeout routines which may briefly polls the keyboard controller.
* c. Routines outside interrupt context (the top half of the driver).
* They should follow the rules below:
* 1. The interrupt handler may assume that it always has full access
* to the controller/keyboard/mouse.
* 2. The other routines must issue `spltty()' if they wish to
* prevent the interrupt handler from accessing
* the controller/keyboard/mouse.
* 3. The timeout routines and the top half routines of the device driver
* arbitrate I/O access by observing the lock flag in `kbdio'.
* The flag is manipulated via `kbdc_lock()'; when one wants to
* perform I/O, call `kbdc_lock(kbdc, TRUE)' and proceed only if
* the call returns with TRUE. Otherwise the caller must back off.
* Call `kbdc_lock(kbdc, FALSE)' when necessary I/O operaion
* is finished. This mechanism does not prevent the interrupt
* handler from being invoked at any time and carrying out I/O.
* Therefore, `spltty()' must be strategically placed in the device
* driver code. Also note that the timeout routine may interrupt
* `kbdc_lock()' called by the top half of the driver, but this
* interruption is OK so long as the timeout routine observes the
* the rule 4 below.
* 4. The interrupt and timeout routines should not extend I/O operation
* across more than one interrupt or timeout; they must complete
* necessary I/O operation within one invokation of the routine.
* This measns that if the timeout routine acquires the lock flag,
* it must reset the flag to FALSE before it returns.
*/
/* set/reset polling lock */
int
kbdc_lock(KBDC p, int lock)
{
int prevlock;
prevlock = kbdcp(p)->lock;
kbdcp(p)->lock = lock;
return (prevlock != lock);
}
/* check if any data is waiting to be processed */
int
kbdc_data_ready(KBDC p)
{
return (availq(&kbdcp(p)->kbd) || availq(&kbdcp(p)->aux)
|| (inb(kbdcp(p)->port + KBD_STATUS_PORT) & <API key>));
}
/* queuing functions */
static int
addq(kqueue *q, int c)
{
if (nextq(q->tail) != q->head) {
q->q[q->tail] = c;
q->tail = nextq(q->tail);
#if KBDIO_DEBUG >= 2
++q->call_count;
++q->qcount;
if (q->qcount > q->max_qcount)
q->max_qcount = q->qcount;
#endif
return TRUE;
}
return FALSE;
}
static int
removeq(kqueue *q)
{
int c;
if (q->tail != q->head) {
c = q->q[q->head];
q->head = nextq(q->head);
#if KBDIO_DEBUG >= 2
--q->qcount;
#endif
return c;
}
return -1;
}
/*
* device I/O routines
*/
static int
<API key>(struct atkbdc_softc *kbdc)
{
/* CPU will stay inside the loop for 100msec at most */
int retry = 5000;
int port = kbdc->port;
int f;
while ((f = inb(port + KBD_STATUS_PORT)) & <API key>) {
if ((f & KBDS_BUFFER_FULL) == <API key>) {
DELAY(KBDD_DELAYTIME);
addq(&kbdc->kbd, inb(port + KBD_DATA_PORT));
} else if ((f & KBDS_BUFFER_FULL) == <API key>) {
DELAY(KBDD_DELAYTIME);
addq(&kbdc->aux, inb(port + KBD_DATA_PORT));
}
DELAY(KBDC_DELAYTIME);
if (--retry < 0)
return FALSE;
}
return TRUE;
}
/*
* wait for any data; whether it's from the controller,
* the keyboard, or the aux device.
*/
static int
wait_for_data(struct atkbdc_softc *kbdc)
{
/* CPU will stay inside the loop for 200msec at most */
int retry = 10000;
int port = kbdc->port;
int f;
while ((f = inb(port + KBD_STATUS_PORT) & <API key>) == 0) {
DELAY(KBDC_DELAYTIME);
if (--retry < 0)
return 0;
}
DELAY(KBDD_DELAYTIME);
return f;
}
/* wait for data from the keyboard */
static int
wait_for_kbd_data(struct atkbdc_softc *kbdc)
{
/* CPU will stay inside the loop for 200msec at most */
int retry = 10000;
int port = kbdc->port;
int f;
while ((f = inb(port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL)
!= <API key>) {
if (f == <API key>) {
DELAY(KBDD_DELAYTIME);
addq(&kbdc->aux, inb(port + KBD_DATA_PORT));
}
DELAY(KBDC_DELAYTIME);
if (--retry < 0)
return 0;
}
DELAY(KBDD_DELAYTIME);
return f;
}
/*
* wait for an ACK(FAh), RESEND(FEh), or RESET_FAIL(FCh) from the keyboard.
* queue anything else.
*/
static int
wait_for_kbd_ack(struct atkbdc_softc *kbdc)
{
/* CPU will stay inside the loop for 200msec at most */
int retry = 10000;
int port = kbdc->port;
int f;
int b;
while (retry
if ((f = inb(port + KBD_STATUS_PORT)) & <API key>) {
DELAY(KBDD_DELAYTIME);
b = inb(port + KBD_DATA_PORT);
if ((f & KBDS_BUFFER_FULL) == <API key>) {
if ((b == KBD_ACK) || (b == KBD_RESEND)
|| (b == KBD_RESET_FAIL))
return b;
addq(&kbdc->kbd, b);
} else if ((f & KBDS_BUFFER_FULL) == <API key>) {
addq(&kbdc->aux, b);
}
}
DELAY(KBDC_DELAYTIME);
}
return -1;
}
/* wait for data from the aux device */
static int
wait_for_aux_data(struct atkbdc_softc *kbdc)
{
/* CPU will stay inside the loop for 200msec at most */
int retry = 10000;
int port = kbdc->port;
int f;
while ((f = inb(port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL)
!= <API key>) {
if (f == <API key>) {
DELAY(KBDD_DELAYTIME);
addq(&kbdc->kbd, inb(port + KBD_DATA_PORT));
}
DELAY(KBDC_DELAYTIME);
if (--retry < 0)
return 0;
}
DELAY(KBDD_DELAYTIME);
return f;
}
/*
* wait for an ACK(FAh), RESEND(FEh), or RESET_FAIL(FCh) from the aux device.
* queue anything else.
*/
static int
wait_for_aux_ack(struct atkbdc_softc *kbdc)
{
/* CPU will stay inside the loop for 200msec at most */
int retry = 10000;
int port = kbdc->port;
int f;
int b;
while (retry
if ((f = inb(port + KBD_STATUS_PORT)) & <API key>) {
DELAY(KBDD_DELAYTIME);
b = inb(port + KBD_DATA_PORT);
if ((f & KBDS_BUFFER_FULL) == <API key>) {
if ((b == PSM_ACK) || (b == PSM_RESEND)
|| (b == PSM_RESET_FAIL))
return b;
addq(&kbdc->aux, b);
} else if ((f & KBDS_BUFFER_FULL) == <API key>) {
addq(&kbdc->kbd, b);
}
}
DELAY(KBDC_DELAYTIME);
}
return -1;
}
/* write a one byte command to the controller */
int
<API key>(KBDC p, int c)
{
if (!<API key>(kbdcp(p)))
return FALSE;
outb(kbdcp(p)->port + KBD_COMMAND_PORT, c);
return TRUE;
}
/* write a one byte data to the controller */
int
<API key>(KBDC p, int c)
{
if (!<API key>(kbdcp(p)))
return FALSE;
outb(kbdcp(p)->port + KBD_DATA_PORT, c);
return TRUE;
}
/* write a one byte keyboard command */
int
write_kbd_command(KBDC p, int c)
{
if (!<API key>(kbdcp(p)))
return FALSE;
outb(kbdcp(p)->port + KBD_DATA_PORT, c);
return TRUE;
}
/* write a one byte auxiliary device command */
int
write_aux_command(KBDC p, int c)
{
if (!<API key>(p, KBDC_WRITE_TO_AUX))
return FALSE;
return <API key>(p, c);
}
/* send a command to the keyboard and wait for ACK */
int
send_kbd_command(KBDC p, int c)
{
int retry = KBD_MAXRETRY;
int res = -1;
while (retry
if (!write_kbd_command(p, c))
continue;
res = wait_for_kbd_ack(kbdcp(p));
if (res == KBD_ACK)
break;
}
return res;
}
/* send a command to the auxiliary device and wait for ACK */
int
send_aux_command(KBDC p, int c)
{
int retry = KBD_MAXRETRY;
int res = -1;
while (retry
if (!write_aux_command(p, c))
continue;
/*
* FIXME: XXX
* The aux device may have already sent one or two bytes of
* status data, when a command is received. It will immediately
* stop data transmission, thus, leaving an incomplete data
* packet in our buffer. We have to discard any unprocessed
* data in order to remove such packets. Well, we may remove
* unprocessed, but necessary data byte as well...
*/
emptyq(&kbdcp(p)->aux);
res = wait_for_aux_ack(kbdcp(p));
if (res == PSM_ACK)
break;
}
return res;
}
/* send a command and a data to the keyboard, wait for ACKs */
int
<API key>(KBDC p, int c, int d)
{
int retry;
int res = -1;
for (retry = KBD_MAXRETRY; retry > 0; --retry) {
if (!write_kbd_command(p, c))
continue;
res = wait_for_kbd_ack(kbdcp(p));
if (res == KBD_ACK)
break;
else if (res != KBD_RESEND)
return res;
}
if (retry <= 0)
return res;
for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) {
if (!write_kbd_command(p, d))
continue;
res = wait_for_kbd_ack(kbdcp(p));
if (res != KBD_RESEND)
break;
}
return res;
}
/* send a command and a data to the auxiliary device, wait for ACKs */
int
<API key>(KBDC p, int c, int d)
{
int retry;
int res = -1;
for (retry = KBD_MAXRETRY; retry > 0; --retry) {
if (!write_aux_command(p, c))
continue;
emptyq(&kbdcp(p)->aux);
res = wait_for_aux_ack(kbdcp(p));
if (res == PSM_ACK)
break;
else if (res != PSM_RESEND)
return res;
}
if (retry <= 0)
return res;
for (retry = KBD_MAXRETRY, res = -1; retry > 0; --retry) {
if (!write_aux_command(p, d))
continue;
res = wait_for_aux_ack(kbdcp(p));
if (res != PSM_RESEND)
break;
}
return res;
}
/*
* read one byte from any source; whether from the controller,
* the keyboard, or the aux device
*/
int
<API key>(KBDC p)
{
if (availq(&kbdcp(p)->kbd))
return removeq(&kbdcp(p)->kbd);
if (availq(&kbdcp(p)->aux))
return removeq(&kbdcp(p)->aux);
if (!wait_for_data(kbdcp(p)))
return -1; /* timeout */
return inb(kbdcp(p)->port + KBD_DATA_PORT);
}
#if KBDIO_DEBUG >= 2
static int call = 0;
#endif
/* read one byte from the keyboard */
int
read_kbd_data(KBDC p)
{
#if KBDIO_DEBUG >= 2
if (++call > 2000) {
call = 0;
log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, "
"aux q: %d calls, max %d chars\n",
kbdcp(p)->kbd.call_count, kbdcp(p)->kbd.max_qcount,
kbdcp(p)->aux.call_count, kbdcp(p)->aux.max_qcount);
}
#endif
if (availq(&kbdcp(p)->kbd))
return removeq(&kbdcp(p)->kbd);
if (!wait_for_kbd_data(kbdcp(p)))
return -1; /* timeout */
return inb(kbdcp(p)->port + KBD_DATA_PORT);
}
/* read one byte from the keyboard, but return immediately if
* no data is waiting
*/
int
<API key>(KBDC p)
{
int f;
#if KBDIO_DEBUG >= 2
if (++call > 2000) {
call = 0;
log(LOG_DEBUG, "kbdc: kbd q: %d calls, max %d chars, "
"aux q: %d calls, max %d chars\n",
kbdcp(p)->kbd.call_count, kbdcp(p)->kbd.max_qcount,
kbdcp(p)->aux.call_count, kbdcp(p)->aux.max_qcount);
}
#endif
if (availq(&kbdcp(p)->kbd))
return removeq(&kbdcp(p)->kbd);
f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL;
if (f == <API key>) {
DELAY(KBDD_DELAYTIME);
addq(&kbdcp(p)->aux, inb(kbdcp(p)->port + KBD_DATA_PORT));
f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL;
}
if (f == <API key>) {
DELAY(KBDD_DELAYTIME);
return inb(kbdcp(p)->port + KBD_DATA_PORT);
}
return -1; /* no data */
}
/* read one byte from the aux device */
int
read_aux_data(KBDC p)
{
if (availq(&kbdcp(p)->aux))
return removeq(&kbdcp(p)->aux);
if (!wait_for_aux_data(kbdcp(p)))
return -1; /* timeout */
return inb(kbdcp(p)->port + KBD_DATA_PORT);
}
/* read one byte from the aux device, but return immediately if
* no data is waiting
*/
int
<API key>(KBDC p)
{
int f;
if (availq(&kbdcp(p)->aux))
return removeq(&kbdcp(p)->aux);
f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL;
if (f == <API key>) {
DELAY(KBDD_DELAYTIME);
addq(&kbdcp(p)->kbd, inb(kbdcp(p)->port + KBD_DATA_PORT));
f = inb(kbdcp(p)->port + KBD_STATUS_PORT) & KBDS_BUFFER_FULL;
}
if (f == <API key>) {
DELAY(KBDD_DELAYTIME);
return inb(kbdcp(p)->port + KBD_DATA_PORT);
}
return -1; /* no data */
}
/* discard data from the keyboard */
void
empty_kbd_buffer(KBDC p, int wait)
{
int t;
int b;
int f;
#if KBDIO_DEBUG >= 2
int c1 = 0;
int c2 = 0;
#endif
int delta = 2;
for (t = wait; t > 0; ) {
if ((f = inb(kbdcp(p)->port + KBD_STATUS_PORT)) & <API key>) {
DELAY(KBDD_DELAYTIME);
b = inb(kbdcp(p)->port + KBD_DATA_PORT);
if ((f & KBDS_BUFFER_FULL) == <API key>) {
addq(&kbdcp(p)->aux, b);
#if KBDIO_DEBUG >= 2
++c2;
} else {
++c1;
#endif
}
t = wait;
} else {
t -= delta;
}
DELAY(delta*1000);
}
#if KBDIO_DEBUG >= 2
if ((c1 > 0) || (c2 > 0))
log(LOG_DEBUG, "kbdc: %d:%d char read (empty_kbd_buffer)\n", c1, c2);
#endif
emptyq(&kbdcp(p)->kbd);
}
/* discard data from the aux device */
void
empty_aux_buffer(KBDC p, int wait)
{
int t;
int b;
int f;
#if KBDIO_DEBUG >= 2
int c1 = 0;
int c2 = 0;
#endif
int delta = 2;
for (t = wait; t > 0; ) {
if ((f = inb(kbdcp(p)->port + KBD_STATUS_PORT)) & <API key>) {
DELAY(KBDD_DELAYTIME);
b = inb(kbdcp(p)->port + KBD_DATA_PORT);
if ((f & KBDS_BUFFER_FULL) == <API key>) {
addq(&kbdcp(p)->kbd, b);
#if KBDIO_DEBUG >= 2
++c1;
} else {
++c2;
#endif
}
t = wait;
} else {
t -= delta;
}
DELAY(delta*1000);
}
#if KBDIO_DEBUG >= 2
if ((c1 > 0) || (c2 > 0))
log(LOG_DEBUG, "kbdc: %d:%d char read (empty_aux_buffer)\n", c1, c2);
#endif
emptyq(&kbdcp(p)->aux);
}
/* discard any data from the keyboard or the aux device */
void
empty_both_buffers(KBDC p, int wait)
{
int t;
int f;
#if KBDIO_DEBUG >= 2
int c1 = 0;
int c2 = 0;
#endif
int delta = 2;
for (t = wait; t > 0; ) {
if ((f = inb(kbdcp(p)->port + KBD_STATUS_PORT)) & <API key>) {
DELAY(KBDD_DELAYTIME);
(void)inb(kbdcp(p)->port + KBD_DATA_PORT);
#if KBDIO_DEBUG >= 2
if ((f & KBDS_BUFFER_FULL) == <API key>)
++c1;
else
++c2;
#endif
t = wait;
} else {
t -= delta;
}
DELAY(delta*1000);
}
#if KBDIO_DEBUG >= 2
if ((c1 > 0) || (c2 > 0))
log(LOG_DEBUG, "kbdc: %d:%d char read (empty_both_buffers)\n", c1, c2);
#endif
emptyq(&kbdcp(p)->kbd);
emptyq(&kbdcp(p)->aux);
}
/* keyboard and mouse device control */
/* NOTE: enable the keyboard port but disable the keyboard
* interrupt before calling "reset_kbd()".
*/
int
reset_kbd(KBDC p)
{
int retry = KBD_MAXRETRY;
int again = KBD_MAXWAIT;
int c = KBD_RESEND; /* keep the compiler happy */
while (retry
empty_both_buffers(p, 10);
if (!write_kbd_command(p, KBDC_RESET_KBD))
continue;
emptyq(&kbdcp(p)->kbd);
c = <API key>(p);
if (verbose || bootverbose)
log(LOG_DEBUG, "kbdc: RESET_KBD return code:%04x\n", c);
if (c == KBD_ACK) /* keyboard has agreed to reset itself... */
break;
}
if (retry < 0)
return FALSE;
while (again
/* wait awhile, well, in fact we must wait quite loooooooooooong */
DELAY(KBD_RESETDELAY*1000);
c = <API key>(p); /* RESET_DONE/RESET_FAIL */
if (c != -1) /* wait again if the controller is not ready */
break;
}
if (verbose || bootverbose)
log(LOG_DEBUG, "kbdc: RESET_KBD status:%04x\n", c);
if (c != KBD_RESET_DONE)
return FALSE;
return TRUE;
}
/* NOTE: enable the aux port but disable the aux interrupt
* before calling `reset_aux_dev()'.
*/
int
reset_aux_dev(KBDC p)
{
int retry = KBD_MAXRETRY;
int again = KBD_MAXWAIT;
int c = PSM_RESEND; /* keep the compiler happy */
while (retry
empty_both_buffers(p, 10);
if (!write_aux_command(p, PSMC_RESET_DEV))
continue;
emptyq(&kbdcp(p)->aux);
/* NOTE: Compaq Armada laptops require extra delay here. XXX */
for (again = KBD_MAXWAIT; again > 0; --again) {
DELAY(KBD_RESETDELAY*1000);
c = <API key>(p);
if (c != -1)
break;
}
if (verbose || bootverbose)
log(LOG_DEBUG, "kbdc: RESET_AUX return code:%04x\n", c);
if (c == PSM_ACK) /* aux dev is about to reset... */
break;
}
if (retry < 0)
return FALSE;
for (again = KBD_MAXWAIT; again > 0; --again) {
/* wait awhile, well, quite looooooooooooong */
DELAY(KBD_RESETDELAY*1000);
c = <API key>(p); /* RESET_DONE/RESET_FAIL */
if (c != -1) /* wait again if the controller is not ready */
break;
}
if (verbose || bootverbose)
log(LOG_DEBUG, "kbdc: RESET_AUX status:%04x\n", c);
if (c != PSM_RESET_DONE) /* reset status */
return FALSE;
c = read_aux_data(p); /* device ID */
if (verbose || bootverbose)
log(LOG_DEBUG, "kbdc: RESET_AUX ID:%04x\n", c);
/* NOTE: we could check the device ID now, but leave it later... */
return TRUE;
}
/* controller diagnostics and setup */
int
test_controller(KBDC p)
{
int retry = KBD_MAXRETRY;
int again = KBD_MAXWAIT;
int c = KBD_DIAG_FAIL;
while (retry
empty_both_buffers(p, 10);
if (<API key>(p, KBDC_DIAGNOSE))
break;
}
if (retry < 0)
return FALSE;
emptyq(&kbdcp(p)->kbd);
while (again
/* wait awhile */
DELAY(KBD_RESETDELAY*1000);
c = <API key>(p); /* DIAG_DONE/DIAG_FAIL */
if (c != -1) /* wait again if the controller is not ready */
break;
}
if (verbose || bootverbose)
log(LOG_DEBUG, "kbdc: DIAGNOSE status:%04x\n", c);
return (c == KBD_DIAG_DONE);
}
int
test_kbd_port(KBDC p)
{
int retry = KBD_MAXRETRY;
int again = KBD_MAXWAIT;
int c = -1;
while (retry
empty_both_buffers(p, 10);
if (<API key>(p, KBDC_TEST_KBD_PORT))
break;
}
if (retry < 0)
return FALSE;
emptyq(&kbdcp(p)->kbd);
while (again
c = <API key>(p);
if (c != -1) /* try again if the controller is not ready */
break;
}
if (verbose || bootverbose)
log(LOG_DEBUG, "kbdc: TEST_KBD_PORT status:%04x\n", c);
return c;
}
int
test_aux_port(KBDC p)
{
int retry = KBD_MAXRETRY;
int again = KBD_MAXWAIT;
int c = -1;
while (retry
empty_both_buffers(p, 10);
if (<API key>(p, KBDC_TEST_AUX_PORT))
break;
}
if (retry < 0)
return FALSE;
emptyq(&kbdcp(p)->kbd);
while (again
c = <API key>(p);
if (c != -1) /* try again if the controller is not ready */
break;
}
if (verbose || bootverbose)
log(LOG_DEBUG, "kbdc: TEST_AUX_PORT status:%04x\n", c);
return c;
}
int
<API key>(KBDC p)
{
return kbdcp(p)->command_mask;
}
void
<API key>(KBDC p, int mask)
{
kbdcp(p)->command_mask =
mask & (<API key> | <API key>);
}
int
<API key>(KBDC p)
{
if (kbdcp(p)->command_byte != -1)
return kbdcp(p)->command_byte;
if (!<API key>(p, <API key>))
return -1;
emptyq(&kbdcp(p)->kbd);
kbdcp(p)->command_byte = <API key>(p);
return kbdcp(p)->command_byte;
}
int
<API key>(KBDC p, int mask, int command)
{
if (<API key>(p) == -1)
return FALSE;
command = (kbdcp(p)->command_byte & ~mask) | (command & mask);
if (command & <API key>) {
if (!<API key>(p, <API key>))
return FALSE;
}
if (!<API key>(p, <API key>))
return FALSE;
if (!<API key>(p, command))
return FALSE;
kbdcp(p)->command_byte = command;
if (verbose)
log(LOG_DEBUG, "kbdc: new command byte:%04x (set_controller...)\n",
command);
return TRUE;
}
|
// +build l476xx
// Peripheral: <API key> Controller Area Network TxMailBox.
// Instances:
// Registers:
// 0x00 32 TIR CAN TX mailbox identifier register.
// 0x04 32 TDTR CAN mailbox data length control and time stamp register.
// 0x08 32 TDLR CAN mailbox data low register.
// 0x0C 32 TDHR CAN mailbox data high register.
// Import:
// stm32/o/l476xx/mmap
package can
// DO NOT EDIT THIS FILE. GENERATED BY stm32xgen.
|
"""
Vision-specific analysis functions.
$Id: featureresponses.py 7714 2008-01-24 16:42:21Z antolikjan $
"""
__version__='$Revision: 7714 $'
from math import fmod,floor,pi,sin,cos,sqrt
import numpy
from numpy.oldnumeric import Float
from numpy import zeros, array, size, empty, object_
#import scipy
try:
import pylab
except ImportError:
print "Warning: Could not import matplotlib; pylab plots will not work."
import param
import topo
from topo.base.cf import CFSheet
from topo.base.sheetview import SheetView
from topo.misc.filepath import normalize_path
from topo.misc.numbergenerator import UniformRandom
from topo.plotting.plotgroup import create_plotgroup, plotgroups
from topo.command.analysis import measure_sine_pref
max_value = 0
global_index = ()
def _complexity_rec(x,y,index,depth,fm):
"""
Recurrent helper function for complexity()
"""
global max_value
global global_index
if depth<size(fm.features):
for i in range(size(fm.features[depth].values)):
_complexity_rec(x,y,index + (i,),depth+1,fm)
else:
if max_value < fm.full_matrix[index][x][y]:
global_index = index
max_value = fm.full_matrix[index][x][y]
def complexity(full_matrix):
global global_index
global max_value
"""This function expects as an input a object of type FullMatrix which contains
responses of all neurons in a sheet to stimuly with different varying parameter values.
One of these parameters (features) has to be phase. In such case it computes the classic
modulation ratio (see Hawken et al. for definition) for each neuron and returns them as a matrix.
"""
rows,cols = full_matrix.matrix_shape
complexity = zeros(full_matrix.matrix_shape)
complex_matrix = zeros(full_matrix.matrix_shape,object_)
fftmeasure = zeros(full_matrix.matrix_shape,Float)
i = 0
for f in full_matrix.features:
if f.name == "phase":
phase_index = i
break
i=i+1
sum = 0.0
res = 0.0
average = 0.0
for x in range(rows):
for y in range(cols):
complex_matrix[x,y] = []
max_value=-0.01
global_index = ()
_complexity_rec(x,y,(),0,full_matrix)
#compute the sum of the responses over phases given the found index of highest response
iindex = array(global_index)
sum = 0.0
for i in range(size(full_matrix.features[phase_index].values)):
iindex[phase_index] = i
sum = sum + full_matrix.full_matrix[tuple(iindex.tolist())][x][y]
#average
average = sum / float(size(full_matrix.features[phase_index].values))
res = 0.0
#compute the sum of absolute values of the responses minus average
for i in range(size(full_matrix.features[phase_index].values)):
iindex[phase_index] = i
res = res + abs(full_matrix.full_matrix[tuple(iindex.tolist())][x][y] - average)
complex_matrix[x,y] = complex_matrix[x,y] + [full_matrix.full_matrix[tuple(iindex.tolist())][x][y]]
#this is taking away the DC component
#complex_matrix[x,y] -= numpy.min(complex_matrix[x,y])
if x==15 and y==15:
pylab.figure()
pylab.plot(complex_matrix[x,y])
if x==26 and y==26:
pylab.figure()
pylab.plot(complex_matrix[x,y])
#complexity[x,y] = res / (2*sum)
fft = numpy.fft.fft(complex_matrix[x,y]+complex_matrix[x,y]+complex_matrix[x,y]+complex_matrix[x,y],2048)
first_har = 2048/len(complex_matrix[0,0])
if abs(fft[0]) != 0:
fftmeasure[x,y] = 2 *abs(fft[first_har]) /abs(fft[0])
else:
fftmeasure[x,y] = 0
return fftmeasure
def <API key>(full_matrix,curve_label,sheet):
""" This function allows and alternative computation of orientation tuning curve where
for each given orientation the response is computed as a maximum of AC or DC component
across the phases instead of the maximum used as a standard in Topographica"""
# this method assumes that only single frequency has been used
i = 0
for f in full_matrix.features:
if f.name == "phase":
phase_index = i
if f.name == "orientation":
orientation_index = i
if f.name == "frequency":
frequency_index = i
i=i+1
print sheet.curve_dict
if not sheet.curve_dict.has_key("orientationACDC"):
sheet.curve_dict["orientationACDC"]={}
sheet.curve_dict["orientationACDC"][curve_label]={}
rows,cols = full_matrix.matrix_shape
for o in xrange(size(full_matrix.features[orientation_index].values)):
s_w = zeros(full_matrix.matrix_shape)
for x in range(rows):
for y in range(cols):
or_response=[]
for p in xrange(size(full_matrix.features[phase_index].values)):
index = [0,0,0]
index[phase_index] = p
index[orientation_index] = o
index[frequency_index] = 0
or_response.append(full_matrix.full_matrix[tuple(index)][x][y])
fft = numpy.fft.fft(or_response+or_response+or_response+or_response,2048)
first_har = 2048/len(or_response)
s_w[x][y] = numpy.maximum(2 *abs(fft[first_har]),abs(fft[0]))
s = SheetView((s_w,sheet.bounds), sheet.name , sheet.precedence, topo.sim.time(),sheet.row_precedence)
sheet.curve_dict["orientationACDC"][curve_label].update({full_matrix.features[orientation_index].values[o]:s})
def <API key>(sheet_name,diameter=0.39):
r = UniformRandom(seed=1023)
preference_map = topo.sim[sheet_name].sheet_views['PhasePreference']
offset_magnitude = 0.03
datax = []
datay = []
(v,bb) = preference_map.view()
for z in zeros(66):
x = (r() - 0.5)*2*diameter
y = (r() - 0.5)*2*diameter
rand = r()
xoff = sin(rand*2*pi)*offset_magnitude
yoff = cos(rand*2*pi)*offset_magnitude
xx = max(min(x+xoff,diameter),-diameter)
yy = max(min(y+yoff,diameter),-diameter)
x = max(min(x,diameter),-diameter)
y = max(min(y,diameter),-diameter)
[xc1,yc1] = topo.sim[sheet_name].sheet2matrixidx(xx,yy)
[xc2,yc2] = topo.sim[sheet_name].sheet2matrixidx(x,y)
if((xc1==xc2) & (yc1==yc2)): continue
datax = datax + [v[xc1,yc1]]
datay = datay + [v[xc2,yc2]]
for i in range(0,len(datax)):
datax[i] = datax[i] * 360
datay[i] = datay[i] * 360
if(datay[i] > datax[i] + 180): datay[i]= datay[i]- 360
if((datax[i] > 180) & (datay[i]> 180)): datax[i] = datax[i] - 360; datay[i] = datay[i] - 360
if((datax[i] > 180) & (datay[i] < (datax[i]-180))): datax[i] = datax[i] - 360; #datay[i] = datay[i] - 360
f = pylab.figure()
ax = f.add_subplot(111, aspect='equal')
pylab.plot(datax,datay,'ro')
pylab.plot([0,360],[-180,180])
pylab.plot([-180,180],[0,360])
pylab.plot([-180,-180],[360,360])
ax.axis([-180,360,-180,360])
pylab.xticks([-180,0,180,360], [-180,0,180,360])
pylab.yticks([-180,0,180,360], [-180,0,180,360])
pylab.grid()
pylab.savefig(normalize_path(str(topo.sim.timestr()) + sheet_name + "_scatter.png"))
# JABALERT: Should we move this plot and command to analysis.py or
# pylabplots.py, where all the rest are?
# In any case, it requires generalization; it should not be hardcoded
# to any particular map name, and should just do the right thing for
# most networks for which it makes sense. E.g. it already measures
# the ComplexSelectivity for all measured_sheets, but then
# <API key> only accepts two with specific names.
# <API key> should just plot whatever it is given, and
# then analyze_complexity can simply pass in whatever was measured,
# with the user controlling what is measured using the measure_map
# attribute of each Sheet. That way the complexity of any sheet could
# be measured, which is what we want.
# Specific changes needed:
# - Make <API key> accept a list of sheets and
# plot their individual modulation ratios and combined ratio.
# - Remove complex_sheet_name argument, which is no longer needed
# - Make sure it still works fine even if V1Simple doesn't exist;
# as this is just for an optional scatter plot, it's fine to skip
# - Preferably remove the filename argument by default, so that
# plots will show up in the GUI
def analyze_complexity(full_matrix,simple_sheet_name,complex_sheet_name,filename=None):
"""
Compute modulation ratio for each neuron, to distinguish complex from simple cells.
Uses full_matrix data obtained from measure_or_pref().
If there is a sheet named as specified in simple_sheet_name,
also plots its phase preference as a scatter plot.
"""
import topo
measured_sheets = [s for s in topo.sim.objects(CFSheet).values()
if hasattr(s,'measure_maps') and s.measure_maps]
for sheet in measured_sheets:
# Divide by two to get into 0-1 scale - that means simple/complex boundry is now at 0.5
complx = array(complexity(full_matrix[sheet]))/2.0
# Should this be renamed to ModulationRatio?
sheet.sheet_views['ComplexSelectivity']=SheetView((complx,sheet.bounds), sheet.name , sheet.precedence, topo.sim.time(),sheet.row_precedence)
import topo.command.pylabplots
topo.command.pylabplots.<API key>(full_matrix,simple_sheet_name=simple_sheet_name,complex_sheet_name=complex_sheet_name,filename=filename)
# Avoid error if no simple sheet exists
try:
<API key>(simple_sheet_name,diameter=0.24999)
except AttributeError:
print "Skipping phase preference scatter plot; could not analyze region %s." \
% simple_sheet_name
class <API key>(measure_sine_pref):
"""Macro for measuring orientation preference and then analyzing its complexity."""
def __call__(self,**params):
fm = super(<API key>,self).__call__(**params)
#from topo.command.analysis import measure_or_pref
#fm = measure_or_pref()
analyze_complexity(fm,simple_sheet_name="V1Simple",complex_sheet_name="V1Complex",filename="ModulationRatio")
pg= create_plotgroup(name='Orientation Preference and Complexity',category="Preference Maps",
doc='Measure preference for sine grating orientation.',
pre_plot_hooks=[<API key>.instance()])
pg.add_plot('Orientation Preference',[('Hue','<API key>')])
pg.add_plot('Orientation Preference&Selectivity',[('Hue','<API key>'),
('Confidence','<API key>')])
pg.add_plot('Orientation Selectivity',[('Strength','<API key>')])
pg.add_plot('Modulation Ratio',[('Strength','ComplexSelectivity')])
pg.add_plot('Phase Preference',[('Hue','PhasePreference')])
pg.add_static_image('Color Key','command/<API key>.png')
|
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* @var $this yii\web\View */
/* @var $model common\models\Offer */
$this->title = $model->id;
$this->params['breadcrumbs'][] = ['label' => Yii::t('app', 'Offers'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="offer-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a(Yii::t('app', 'Update'), ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Delete'), ['delete', 'id' => $model->id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => Yii::t('app', 'Are you sure you want to delete this item?'),
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'id',
'code',
'text:ntext',
'created_at',
'updated_at',
],
]) ?>
</div>
|
/* $OpenBSD: isp_sbus.c,v 1.7 1999/03/25 22:58:37 mjacob Exp $ */
/* release_03_25_99 */
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/kernel.h>
#include <sys/malloc.h>
#include <sys/queue.h>
#include <machine/autoconf.h>
#include <machine/cpu.h>
#include <machine/param.h>
#include <machine/vmparam.h>
#include <sparc/sparc/cpuvar.h>
#include <dev/ic/isp_openbsd.h>
#include <dev/microcode/isp/asm_sbus.h>
static u_int16_t isp_sbus_rd_reg __P((struct ispsoftc *, int));
static void isp_sbus_wr_reg __P((struct ispsoftc *, int, u_int16_t));
static int isp_sbus_mbxdma __P((struct ispsoftc *));
static int isp_sbus_dmasetup __P((struct ispsoftc *, struct scsi_xfer *,
ispreq_t *, u_int8_t *, u_int8_t));
static void <API key> __P((struct ispsoftc *, struct scsi_xfer *,
u_int32_t));
static struct ispmdvec mdvec = {
isp_sbus_rd_reg,
isp_sbus_wr_reg,
isp_sbus_mbxdma,
isp_sbus_dmasetup,
<API key>,
NULL,
NULL,
NULL,
ISP_RISC_CODE,
ISP_CODE_LENGTH,
ISP_CODE_ORG,
ISP_CODE_VERSION,
BIU_BURST_ENABLE,
0
};
struct isp_sbussoftc {
struct ispsoftc sbus_isp;
sdparam sbus_dev;
struct intrhand sbus_ih;
volatile u_char *sbus_reg;
int sbus_node;
int sbus_pri;
struct ispmdvec sbus_mdvec;
vm_offset_t sbus_kdma_allocs[MAXISPREQUEST];
int16_t sbus_poff[_NREG_BLKS];
};
static int isp_match __P((struct device *, void *, void *));
static void isp_sbus_attach __P((struct device *, struct device *, void *));
struct cfattach isp_sbus_ca = {
sizeof (struct isp_sbussoftc), isp_match, isp_sbus_attach
};
static int
isp_match(parent, cfarg, aux)
struct device *parent;
void *cfarg;
void *aux;
{
int rv;
struct cfdata *cf = cfarg;
#ifdef DEBUG
static int oneshot = 1;
#endif
struct confargs *ca = aux;
register struct romaux *ra = &ca->ca_ra;
rv = (strcmp(cf->cf_driver->cd_name, ra->ra_name) == 0 ||
strcmp("PTI,ptisp", ra->ra_name) == 0 ||
strcmp("ptisp", ra->ra_name) == 0 ||
strcmp("SUNW,isp", ra->ra_name) == 0 ||
strcmp("QLGC,isp", ra->ra_name) == 0);
if (rv == 0)
return (rv);
#ifdef DEBUG
if (rv && oneshot) {
oneshot = 0;
printf("Qlogic ISP Driver, NetBSD (sbus) Platform Version "
"%d.%d Core Version %d.%d\n",
<API key>, <API key>,
<API key>, <API key>);
}
#endif
if (ca->ca_bustype == BUS_SBUS)
return (1);
ra->ra_len = NBPG;
return (probeget(ra->ra_vaddr, 1) != -1);
}
static void
isp_sbus_attach(parent, self, aux)
struct device *parent, *self;
void *aux;
{
int freq;
struct confargs *ca = aux;
struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) self;
struct ispsoftc *isp = &sbc->sbus_isp;
ISP_LOCKVAL_DECL;
if (ca->ca_ra.ra_nintr != 1) {
printf(": expected 1 interrupt, got %d\n", ca->ca_ra.ra_nintr);
return;
}
printf("\n");
sbc->sbus_pri = ca->ca_ra.ra_intr[0].int_pri;
sbc->sbus_mdvec = mdvec;
if (ca->ca_ra.ra_vaddr) {
sbc->sbus_reg = (volatile u_char *) ca->ca_ra.ra_vaddr;
} else {
sbc->sbus_reg = (volatile u_char *)
mapiodev(ca->ca_ra.ra_reg, 0, ca->ca_ra.ra_len);
}
sbc->sbus_node = ca->ca_ra.ra_node;
freq = getpropint(ca->ca_ra.ra_node, "clock-frequency", 0);
if (freq) {
/*
* Convert from HZ to MHz, rounding up.
*/
freq = (freq + 500000)/1000000;
#if 0
printf("%s: %d MHz\n", self->dv_xname, freq);
#endif
}
sbc->sbus_mdvec.dv_clock = freq;
/*
* XXX: Now figure out what the proper burst sizes, etc., to use.
*/
sbc->sbus_mdvec.dv_conf1 |= <API key>;
/*
* Some early versions of the PTI SBus adapter
* would fail in trying to download (via poking)
* FW. We give up on them.
*/
if (strcmp("PTI,ptisp", ca->ca_ra.ra_name) == 0 ||
strcmp("ptisp", ca->ca_ra.ra_name) == 0) {
sbc->sbus_mdvec.dv_fwlen = 0;
}
isp->isp_mdvec = &sbc->sbus_mdvec;
isp->isp_bustype = ISP_BT_SBUS;
isp->isp_type = ISP_HA_SCSI_UNKNOWN;
isp->isp_param = &sbc->sbus_dev;
bzero(isp->isp_param, sizeof (sdparam));
sbc->sbus_poff[BIU_BLOCK >> _BLK_REG_SHFT] = BIU_REGS_OFF;
sbc->sbus_poff[MBOX_BLOCK >> _BLK_REG_SHFT] = SBUS_MBOX_REGS_OFF;
sbc->sbus_poff[SXP_BLOCK >> _BLK_REG_SHFT] = SBUS_SXP_REGS_OFF;
sbc->sbus_poff[RISC_BLOCK >> _BLK_REG_SHFT] = SBUS_RISC_REGS_OFF;
sbc->sbus_poff[DMA_BLOCK >> _BLK_REG_SHFT] = DMA_REGS_OFF;
/* Establish interrupt channel */
sbc->sbus_ih.ih_fun = (void *) isp_intr;
sbc->sbus_ih.ih_arg = sbc;
intr_establish(sbc->sbus_pri, &sbc->sbus_ih);
ISP_LOCK(isp);
isp_reset(isp);
if (isp->isp_state != ISP_RESETSTATE) {
ISP_UNLOCK(isp);
return;
}
isp_init(isp);
if (isp->isp_state != ISP_INITSTATE) {
isp_uninit(isp);
ISP_UNLOCK(isp);
return;
}
/*
* do generic attach.
*/
isp_attach(isp);
if (isp->isp_state != ISP_RUNSTATE) {
isp_uninit(isp);
}
ISP_UNLOCK(isp);
}
static u_int16_t
isp_sbus_rd_reg(isp, regoff)
struct ispsoftc *isp;
int regoff;
{
struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp;
int offset = sbc->sbus_poff[(regoff & _BLK_REG_MASK) >> _BLK_REG_SHFT];
offset += (regoff & 0xff);
return (*((u_int16_t *) &sbc->sbus_reg[offset]));
}
static void
isp_sbus_wr_reg (isp, regoff, val)
struct ispsoftc *isp;
int regoff;
u_int16_t val;
{
struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp;
int offset = sbc->sbus_poff[(regoff & _BLK_REG_MASK) >> _BLK_REG_SHFT];
offset += (regoff & 0xff);
*((u_int16_t *) &sbc->sbus_reg[offset]) = val;
}
static int
isp_sbus_mbxdma(isp)
struct ispsoftc *isp;
{
size_t len;
/*
* NOTE: Since most Sun machines aren't I/O coherent,
* map the mailboxes through kdvma space to force them
* to be uncached.
*/
/*
* Allocate and map the request queue.
*/
len = ISP_QUEUE_SIZE(RQUEST_QUEUE_LEN);
isp->isp_rquest = (volatile caddr_t)malloc(len, M_DEVBUF, M_NOWAIT);
if (isp->isp_rquest == 0)
return (1);
isp->isp_rquest_dma = (u_int32_t)kdvma_mapin((caddr_t)isp->isp_rquest,
len, 0);
if (isp->isp_rquest_dma == 0)
return (1);
/*
* Allocate and map the result queue.
*/
len = ISP_QUEUE_SIZE(RESULT_QUEUE_LEN);
isp->isp_result = (volatile caddr_t)malloc(len, M_DEVBUF, M_NOWAIT);
if (isp->isp_result == 0)
return (1);
isp->isp_result_dma = (u_int32_t)kdvma_mapin((caddr_t)isp->isp_result,
len, 0);
if (isp->isp_result_dma == 0)
return (1);
return (0);
}
/*
* TODO: If kdvma_mapin fails, try using multiple smaller chunks..
*/
static int
isp_sbus_dmasetup(isp, xs, rq, iptrp, optr)
struct ispsoftc *isp;
struct scsi_xfer *xs;
ispreq_t *rq;
u_int8_t *iptrp;
u_int8_t optr;
{
struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp;
vm_offset_t kdvma;
int dosleep = (xs->flags & SCSI_NOSLEEP) != 0;
if (xs->datalen == 0) {
rq->req_seg_count = 1;
return (CMD_QUEUED);
}
if (rq->req_handle > RQUEST_QUEUE_LEN ||
rq->req_handle < 1) {
panic("%s: bad handle (%d) in isp_sbus_dmasetup\n",
isp->isp_name, rq->req_handle);
/* NOTREACHED */
}
if (CPU_ISSUN4M) {
kdvma = (vm_offset_t)
kdvma_mapin((caddr_t)xs->data, xs->datalen, dosleep);
if (kdvma == (vm_offset_t) 0) {
XS_SETERR(xs, HBA_BOTCH);
return (CMD_COMPLETE);
}
} else {
kdvma = (vm_offset_t) xs->data;
}
if (sbc->sbus_kdma_allocs[rq->req_handle - 1] != (vm_offset_t) 0) {
panic("%s: kdma handle already allocated\n", isp->isp_name);
/* NOTREACHED */
}
sbc->sbus_kdma_allocs[rq->req_handle - 1] = kdvma;
if (xs->flags & SCSI_DATA_IN) {
rq->req_flags |= REQFLAG_DATA_IN;
} else {
rq->req_flags |= REQFLAG_DATA_OUT;
}
rq->req_dataseg[0].ds_count = xs->datalen;
rq->req_dataseg[0].ds_base = (u_int32_t) kdvma;
rq->req_seg_count = 1;
return (CMD_QUEUED);
}
static void
<API key>(isp, xs, handle)
struct ispsoftc *isp;
struct scsi_xfer *xs;
u_int32_t handle;
{
struct isp_sbussoftc *sbc = (struct isp_sbussoftc *) isp;
vm_offset_t kdvma;
if (xs->flags & SCSI_DATA_IN) {
cpuinfo.cache_flush(xs->data, xs->datalen - xs->resid);
}
if (handle >= RQUEST_QUEUE_LEN) {
panic("%s: bad handle (%d) in <API key>\n",
isp->isp_name, handle);
/* NOTREACHED */
}
if (sbc->sbus_kdma_allocs[handle] == (vm_offset_t) 0) {
panic("%s: kdma handle not already allocated\n", isp->isp_name);
/* NOTREACHED */
}
kdvma = sbc->sbus_kdma_allocs[handle];
sbc->sbus_kdma_allocs[handle] = (vm_offset_t) 0;
if (CPU_ISSUN4M) {
dvma_mapout(kdvma, (vm_offset_t) xs->data, xs->datalen);
}
}
|
#include "sky/engine/config.h"
#include "sky/engine/core/events/UIEvent.h"
namespace blink {
UIEventInit::UIEventInit()
: view(nullptr)
, detail(0)
{
}
UIEvent::UIEvent()
: m_detail(0)
{
}
UIEvent::UIEvent(const AtomicString& eventType, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg)
: Event(eventType, canBubbleArg, cancelableArg)
, m_view(viewArg)
, m_detail(detailArg)
{
}
UIEvent::UIEvent(const AtomicString& eventType, const UIEventInit& initializer)
: Event(eventType, initializer)
, m_view(initializer.view)
, m_detail(initializer.detail)
{
}
UIEvent::~UIEvent()
{
}
void UIEvent::initUIEvent(const AtomicString& typeArg, bool canBubbleArg, bool cancelableArg, PassRefPtr<AbstractView> viewArg, int detailArg)
{
if (dispatched())
return;
initEvent(typeArg, canBubbleArg, cancelableArg);
m_view = viewArg;
m_detail = detailArg;
}
bool UIEvent::isUIEvent() const
{
return true;
}
const AtomicString& UIEvent::interfaceName() const
{
return EventNames::UIEvent;
}
int UIEvent::keyCode() const
{
return 0;
}
int UIEvent::charCode() const
{
return 0;
}
int UIEvent::layerX()
{
return 0;
}
int UIEvent::layerY()
{
return 0;
}
int UIEvent::pageX() const
{
return 0;
}
int UIEvent::pageY() const
{
return 0;
}
int UIEvent::which() const
{
return 0;
}
} // namespace blink
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_45) on Tue Apr 17 08:41:58 IDT 2018 -->
<title>DNXConstants.PRESERVATIONLEVEL</title>
<meta name="date" content="2018-04-17">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="DNXConstants.PRESERVATIONLEVEL";
}
}
catch(err) {
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar.top">
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRODUCER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html" target="_top">Frames</a></li>
<li><a href="DNXConstants.PRESERVATIONLEVEL.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip.navbar.top">
</a></div>
<div class="header">
<div class="subTitle">com.exlibris.digitool.common.dnx</div>
<h2 title="Interface DNXConstants.PRESERVATIONLEVEL" class="title">Interface DNXConstants.PRESERVATIONLEVEL</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants</a></dd>
</dl>
<hr>
<br>
<pre>public static interface <span class="typeNameLabel">DNXConstants.PRESERVATIONLEVEL</span></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="field.summary">
</a>
<h3>Field Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation">
<caption><span>Fields</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#<API key>"><API key></a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#<API key>"><API key></a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#<API key>"><API key></a></span></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a></code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#<API key>"><API key></a></span></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html#sectionId">sectionId</a></span></code> </td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="field.detail">
</a>
<h3>Field Detail</h3>
<a name="sectionId">
</a>
<ul class="blockList">
<li class="blockList">
<h4>sectionId</h4>
<pre>static final java.lang.String sectionId</pre>
<dl>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../../../constant-values.html#com.exlibris.digitool.common.dnx.DNXConstants.PRESERVATIONLEVEL.sectionId">Constant Field Values</a></dd>
</dl>
</li>
</ul>
<a name="<API key>">
</a>
<ul class="blockList">
<li class="blockList">
<h4><API key></h4>
<pre>static final <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> <API key></pre>
</li>
</ul>
<a name="<API key>">
</a>
<ul class="blockList">
<li class="blockList">
<h4><API key></h4>
<pre>static final <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> <API key></pre>
</li>
</ul>
<a name="<API key>">
</a>
<ul class="blockList">
<li class="blockList">
<h4><API key></h4>
<pre>static final <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> <API key></pre>
</li>
</ul>
<a name="<API key>">
</a>
<ul class="blockListLast">
<li class="blockList">
<h4><API key></h4>
<pre>static final <a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.SectionKey.html" title="class in com.exlibris.digitool.common.dnx">DNXConstants.SectionKey</a> <API key></pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<div class="bottomNav"><a name="navbar.bottom">
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.OBJECTIDENTIFIER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Prev Class</span></a></li>
<li><a href="../../../../../com/exlibris/digitool/common/dnx/DNXConstants.PRODUCER.html" title="interface in com.exlibris.digitool.common.dnx"><span class="typeNameLink">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/exlibris/digitool/common/dnx/DNXConstants.PRESERVATIONLEVEL.html" target="_top">Frames</a></li>
<li><a href="DNXConstants.PRESERVATIONLEVEL.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="<API key>">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!
allClassesLink = document.getElementById("<API key>");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#field.summary">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#field.detail">Field</a> | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip.navbar.bottom">
</a></div>
</body>
</html>
|
import { takeLatest, call, put } from 'redux-saga/effects';
import { gql } from 'react-apollo';
import { push } from 'react-router-redux';
import jwtDecode from 'jwt-decode';
import { setJwtToken } from '../../utils/auth';
import { bootstrap } from '../../utils/sagas';
import { registerError, registerSuccess } from './actions';
import { REGISTER } from './constants';
import { loginSuccess } from '../Login/actions';
import { client } from '../../graphql';
import { homePage } from '../../local-urls';
const RegisterMutation = gql`
mutation RegisterMutation($nick: String!, $password: String!, $name: String!, $email: String!){
register(nick: $nick, password: $password, name: $name, email: $email)
}
`;
function sendRegister(user) {
return client.mutate({ mutation: RegisterMutation, variables: user });
}
function* register({ user }) {
try {
const response = yield call(sendRegister, user);
const token = response.data.register;
const userInfo = jwtDecode(token);
setJwtToken(token);
yield put(registerSuccess());
yield put(loginSuccess(userInfo));
yield put(push(homePage()));
} catch (e) {
yield put(registerError());
}
}
function* registerSaga() {
yield takeLatest(REGISTER, register);
}
export default bootstrap([
registerSaga,
]);
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>statsmodels.tsa.vector_ar.var_model.VARResults.pvalues — statsmodels 0.9.0 documentation</title>
<link rel="stylesheet" href="../_static/nature.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript" src="../_static/<API key>.js"></script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=<API key>"></script>
<link rel="shortcut icon" href="../_static/<API key>.ico"/>
<link rel="author" title="About these documents" href="../about.html" />
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<link rel="next" title="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt" href="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt.html" />
<link rel="prev" title="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim" href="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim.html" />
<link rel="stylesheet" href="../_static/examples.css" type="text/css" />
<link rel="stylesheet" href="../_static/facebox.css" type="text/css" />
<script type="text/javascript" src="../_static/scripts.js">
</script>
<script type="text/javascript" src="../_static/facebox.js">
</script>
<script type="text/javascript">
$.facebox.settings.closeImage = "../_static/closelabel.png"
$.facebox.settings.loadingImage = "../_static/loading.gif"
</script>
</head><body>
<div class="headerwrap">
<div class = "header">
<a href = "../index.html">
<img src="../_static/<API key>.png" alt="Logo"
style="padding-left: 15px"/></a>
</div>
</div>
<div class="related" role="navigation" aria-label="related navigation">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="../py-modindex.html" title="Python Module Index"
>modules</a> |</li>
<li class="right" >
<a href="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt.html" title="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim.html" title="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim"
accesskey="P">previous</a> |</li>
<li><a href ="../install.html">Install</a></li> |
<li><a href="https://groups.google.com/forum/?hl=en#!forum/pystatsmodels">Support</a></li> |
<li><a href="https://github.com/statsmodels/statsmodels/issues">Bugs</a></li> |
<li><a href="../dev/index.html">Develop</a></li> |
<li><a href="../examples/index.html">Examples</a></li> |
<li><a href="../faq.html">FAQ</a></li> |
<li class="nav-item nav-item-1"><a href="../tsa.html" >Time Series analysis <code class="docutils literal notranslate"><span class="pre">tsa</span></code></a> |</li>
<li class="nav-item nav-item-2"><a href="statsmodels.tsa.vector_ar.var_model.VARResults.html" accesskey="U">statsmodels.tsa.vector_ar.var_model.VARResults</a> |</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body" role="main">
<div class="section" id="<API key>">
<h1>statsmodels.tsa.vector_ar.var_model.VARResults.pvalues<a class="headerlink" href="
<dl class="method">
<dt id="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues">
<code class="descclassname">VARResults.</code><code class="descname">pvalues</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="../_modules/statsmodels/tsa/vector_ar/var_model.html
<dd><p>Two-sided p-values for model coefficients from Student t-distribution</p>
</dd></dl>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar" role="navigation" aria-label="main navigation">
<div class="<API key>">
<h4>Previous topic</h4>
<p class="topless"><a href="statsmodels.tsa.vector_ar.var_model.VARResults.plotsim.html"
title="previous chapter">statsmodels.tsa.vector_ar.var_model.VARResults.plotsim</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt.html"
title="next chapter">statsmodels.tsa.vector_ar.var_model.VARResults.pvalues_dt</a></p>
<div role="note" aria-label="source link">
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/generated/statsmodels.tsa.vector_ar.var_model.VARResults.pvalues.rst.txt"
rel="nofollow">Show Source</a></li>
</ul>
</div>
<div id="searchbox" style="display: none" role="search">
<h3>Quick search</h3>
<div class="searchformwrapper">
<form class="search" action="../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
</div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="footer" role="contentinfo">
&
Created using <a href="http://sphinx-doc.org/">Sphinx</a> 1.7.4.
</div>
</body>
</html>
|
<!doctype html>
<html>
<head>
<title>LazyLoad Test</title>
<style type="text/css">
fieldset {
border: 1px solid #afafaf;
margin-bottom: 1em;
}
.log {
font: 10pt Consolas, Monaco, fixed;
width: 100%;
}
#css-status {
background-color: #fff;
height: 30px;
margin: 10px auto;
width: 100px;
}
#n1,#n2,#n3,#n4,#n5 { width: 0; }
</style>
</head>
<body>
<h1>LazyLoad Test</h1>
<form action="" method="get">
<fieldset>
<legend>JavaScript</legend>
<p>
<input type="button" id="btnLoadJS" value="Load JS (sequential calls)" />
<input type="button" id="btnLoadJSSingle" value="Load JS (single call)" />
</p>
<p>
<textarea id="jslog" class="log" rows="15" cols="50"></textarea>
</p>
</fieldset>
<fieldset>
<legend>CSS</legend>
<p>
<input type="button" id="btnLoadCSS" value="Load CSS (sequential calls)" />
<input type="button" id="btnLoadCSSSingle" value="Load CSS (single call)" />
</p>
<p>
<textarea id="csslog" class="log" rows="15" cols="50"></textarea>
</p>
<div id="css-status"></div>
<div id="n1"></div>
<div id="n2"></div>
<div id="n3"></div>
<div id="n4"></div>
<div id="n5"></div>
</fieldset>
</form>
<script src="../lazyload.js"></script>
<script type="text/javascript">
var btnLoadCSS = document.getElementById('btnLoadCSS'),
btnLoadCSSSingle = document.getElementById('btnLoadCSSSingle'),
btnLoadJS = document.getElementById('btnLoadJS'),
btnLoadJSSingle = document.getElementById('btnLoadJSSingle'),
cssLogEl = document.getElementById('csslog'),
jsLogEl = document.getElementById('jslog'),
n1 = document.getElementById('n1'),
n2 = document.getElementById('n2'),
n3 = document.getElementById('n3'),
n4 = document.getElementById('n4'),
n5 = document.getElementById('n5'),
cssInterval = null,
css = [
'http://pieisgood.org/test/lazyload/../lazyload/css.php?num=1',
'http://pieisgood.org/test/lazyload/css.php?num=2',
'http://pieisgood.org/test/lazyload/css.php?num=3',
'http://pieisgood.org/test/lazyload/css.php?num=4',
'http://pieisgood.org/test/lazyload/css.php?num=5'
],
js = [
'http://pieisgood.org/test/lazyload/js.php?num=1',
'http://pieisgood.org/test/lazyload/js.php?num=2',
'http://pieisgood.org/test/lazyload/js.php?num=3',
'http://pieisgood.org/test/lazyload/js.php?num=4',
'http://pieisgood.org/test/lazyload/js.php?num=5'
];
function cssComplete() {
csslog('callback');
}
function csslog(message) {
cssLogEl.value += "[" + (new Date()).toTimeString() + "] " + message + "\r\n";
}
function cssPollStart() {
var check = [n1, n2, n3, n4, n5],
i, item;
cssPollStop();
var links = document.<API key>('link');
cssInterval = setInterval(function () {
for (i = 0; i < check.length; ++i) {
item = check[i];
if (item.offsetWidth > 0) {
check.splice(i, 1);
i -= 1;
csslog('stylesheet ' + item.id.substr(1) + ' applied');
}
}
if (!check.length) {
cssPollStop();
}
}, 15);
}
function cssPollStop() {
clearInterval(cssInterval);
}
function jsComplete() {
jslog('callback');
}
function jslog(message) {
jsLogEl.value += "[" + (new Date()).toTimeString() + "] " + message + "\r\n";
}
btnLoadCSS.onclick = function () {
cssPollStart();
csslog('loading (sequential calls)');
for (var i = 0; i < css.length; i += 1) {
LazyLoad.css(css[i], cssComplete);
}
}
btnLoadCSSSingle.onclick = function () {
cssPollStart();
csslog('loading (single call)');
LazyLoad.css(css, cssComplete);
}
btnLoadJS.onclick = function () {
jslog('loading (sequential calls)');
for (var i = 0; i < js.length; i += 1) {
LazyLoad.js(js[i], jsComplete);
}
}
btnLoadJSSingle.onclick = function () {
jslog('loading (single call)');
LazyLoad.js(js, jsComplete);
}
</script>
</body>
</html>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.