answer
stringlengths 15
1.25M
|
|---|
var request = require("request");
var yaml = require("js-yaml");
var jsonfile = require("jsonfile");
request("https://raw.githubusercontent.com/unitedstates/<API key>/master/legislators-current.yaml", function(error, response, body) {
if (!error && response.statusCode == 200) {
var legislators = yaml.safeLoad(body);
legislators = legislators.map(function(legislator) {
var term = legislator.terms[legislator.terms.length-1];
return {
firstName: legislator.name.first,
lastName: legislator.name.last,
bioguideId: legislator.id.bioguide,
chamber: term.type == "rep" ? "house" : "senate",
title: term.type == "rep" ? "Rep" : "Sen",
state: term.state,
district: typeof term.district == "undefined" ? null : term.district.toString()
};
});
jsonfile.writeFileSync("congress.json", legislators, { spaces: 2 });
} else if (error) {
console.error("Failed to fetch legislators-current.yaml", error);
} else {
console.error("Failed to fetch legislators-current.yaml",
"("+response.statusCode+" "+response.statusMessage+")");
}
});
|
if(!Ckeditor) var Ckeditor = {};
Ckeditor.Files = new Class({
Extends: Files.App,
Implements: [Events, Options],
options: {
types: ['file', 'image'],
editor: null,
preview: 'files-preview',
grid: {
cookie: false,
layout: 'compact',
batch_delete: false
},
history: {
enabled: false
}
},
initialize: function(options) {
this.parent(options);
this.editor = this.options.editor;
this.preview = document.id(this.options.preview);
},
setPaginator: function() {
},
setPathway: function() {
},
setState: function() {
// TODO: Implement pagination into the view
this.fireEvent('beforeSetState');
var opts = this.options.state;
this.state = new Files.State(opts);
this.fireEvent('afterSetState');
},
setGrid: function() {
var opts = this.options.grid;
var that = this;
$extend(opts, {
'onClickImage': function(e) {
that.setPreview(document.id(e.target), 'image');
},
'onClickFile': function(e) {
that.setPreview(document.id(e.target), 'file');
}
});
this.grid = new Files.Grid(this.options.grid.element, opts);
},
setPreview: function(target, type) {
var node = target.getParent('.files-node-shadow') || target.getParent('.files-node');
var row = node.retrieve('row');
var copy = $extend({}, row);
var path = row.baseurl+"/"+row.filepath;
var url = path.replace(Files.sitebase+'/', '').replace(/files\/[^\/]+\
// Update active row
node.getParent().getChildren().removeClass('active');
node.addClass('active');
// Load preview template
copy.template = 'details_'+type;
this.preview.empty();
copy.render('compact').inject(this.preview);
// Inject preview image
if (type == 'image') {
this.preview.getElement('img').set('src', copy.image);
}
// When no text is selected use the file name
if (type == 'file') {
if(document.id('image-text').get('value') == ""){
document.id('image-text').set('value', row.name);
}
}
document.id('image-url').set('value', url);
document.id('image-type').set('value',row.metadata.mimetype);
}
});
|
var articles = null;
function <API key>() {
$("#allbtn").button('toggle');
$('#articleslist').empty();
$('#articleslist').append(articles);
$('#filterwarning').hide();
}
function switch_category(category) {
if (typeof category != "undefined") {
$("#articleslist").empty();
var filtered = articles.filter('.'.concat(category));
$("#articleslist").append(filtered);
} else {
<API key>();
}
timeandtips("#articleslist");
}
$(document).ready(function() {
timeandtips();
articles = $('#articleslist article');
$('#searchfield').removeAttr("disabled");
});
$("#searchfield").keyup(function(event) {
var text = $('#searchfield').val();
if (text.length >= 3) {
$("#allbtn").button('toggle');
var found = articles.filter('article:containsi("'.concat(text, '")'));
$('#filterwarning').show();
$('#articleslist').empty();
$('#articleslist').append(found);
} else if (text.length == 0) {
<API key>();
}
});
|
package lxc_test
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
stdtesting "testing"
gc "launchpad.net/gocheck"
"launchpad.net/golxc"
"launchpad.net/goyaml"
"launchpad.net/loggo"
"launchpad.net/juju-core/container/lxc"
"launchpad.net/juju-core/environs"
"launchpad.net/juju-core/instance"
instancetest "launchpad.net/juju-core/instance/testing"
jujutesting "launchpad.net/juju-core/juju/testing"
jc "launchpad.net/juju-core/testing/checkers"
"launchpad.net/juju-core/testing/testbase"
"launchpad.net/juju-core/tools"
"launchpad.net/juju-core/version"
)
func Test(t *stdtesting.T) {
gc.TestingT(t)
}
type LxcSuite struct {
lxc.TestSuite
}
var _ = gc.Suite(&LxcSuite{})
func (s *LxcSuite) SetUpSuite(c *gc.C) {
s.TestSuite.SetUpSuite(c)
tmpDir := c.MkDir()
restore := testbase.PatchEnvironment("PATH", tmpDir)
s.AddSuiteCleanup(func(*gc.C) { restore() })
err := ioutil.WriteFile(
filepath.Join(tmpDir, "apt-config"),
[]byte(aptConfigScript),
0755)
c.Assert(err, gc.IsNil)
}
func (s *LxcSuite) SetUpTest(c *gc.C) {
s.TestSuite.SetUpTest(c)
loggo.GetLogger("juju.container.lxc").SetLogLevel(loggo.TRACE)
}
const (
aptHTTPProxy = "http://1.2.3.4:3142"
configProxyExtra = `Acquire::https::Proxy "false";
Acquire::ftp::Proxy "false";`
)
var (
configHttpProxy = fmt.Sprintf(`Acquire::http::Proxy "%s";`, aptHTTPProxy)
aptConfigScript = fmt.Sprintf("#!/bin/sh\n echo '%s\n%s'", configHttpProxy, configProxyExtra)
)
func StartContainer(c *gc.C, manager lxc.ContainerManager, machineId string) instance.Instance {
stateInfo := jujutesting.FakeStateInfo(machineId)
apiInfo := jujutesting.FakeAPIInfo(machineId)
machineConfig := environs.NewMachineConfig(machineId, "fake-nonce", stateInfo, apiInfo)
machineConfig.Tools = &tools.Tools{
Version: version.MustParseBinary("2.3.4-foo-bar"),
URL: "http://tools.testing.invalid/2.3.4-foo-bar.tgz",
}
series := "series"
network := lxc.BridgeNetworkConfig("nic42")
inst, err := manager.StartContainer(machineConfig, series, network)
c.Assert(err, gc.IsNil)
return inst
}
func (s *LxcSuite) TestStartContainer(c *gc.C) {
manager := lxc.NewContainerManager(lxc.ManagerConfig{})
instance := StartContainer(c, manager, "1/lxc/0")
name := string(instance.Id())
// Check our container config files.
lxcConfContents, err := ioutil.ReadFile(filepath.Join(s.ContainerDir, name, "lxc.conf"))
c.Assert(err, gc.IsNil)
c.Assert(string(lxcConfContents), jc.Contains, "lxc.network.link = nic42")
cloudInitFilename := filepath.Join(s.ContainerDir, name, "cloud-init")
c.Assert(cloudInitFilename, jc.IsNonEmptyFile)
data, err := ioutil.ReadFile(cloudInitFilename)
c.Assert(err, gc.IsNil)
c.Assert(string(data), jc.HasPrefix, "#cloud-config\n")
x := make(map[interface{}]interface{})
err = goyaml.Unmarshal(data, &x)
c.Assert(err, gc.IsNil)
c.Assert(x["apt_proxy"], gc.Equals, aptHTTPProxy)
var scripts []string
for _, s := range x["runcmd"].([]interface{}) {
scripts = append(scripts, s.(string))
}
c.Assert(scripts[len(scripts)-4:], gc.DeepEquals, []string{
"start <API key>",
"install -m 644 /dev/null '/etc/apt/apt.conf.d/99proxy-extra'",
fmt.Sprintf(`printf '%%s\n' '%s' > '/etc/apt/apt.conf.d/99proxy-extra'`, configProxyExtra),
"ifconfig",
})
// Check the mount point has been created inside the container.
c.Assert(filepath.Join(s.LxcDir, name, "rootfs/var/log/juju"), jc.IsDirectory)
// Check that the config file is linked in the restart dir.
<API key> := filepath.Join(s.RestartDir, name+".conf")
expectedTarget := filepath.Join(s.LxcDir, name, "config")
linkInfo, err := os.Lstat(<API key>)
c.Assert(err, gc.IsNil)
c.Assert(linkInfo.Mode()&os.ModeSymlink, gc.Equals, os.ModeSymlink)
location, err := os.Readlink(<API key>)
c.Assert(err, gc.IsNil)
c.Assert(location, gc.Equals, expectedTarget)
}
func (s *LxcSuite) TestContainerState(c *gc.C) {
manager := lxc.NewContainerManager(lxc.ManagerConfig{})
instance := StartContainer(c, manager, "1/lxc/0")
// The mock container will be immediately "running".
c.Assert(instance.Status(), gc.Equals, string(golxc.StateRunning))
// StopContainer stops and then destroys the container, putting it
// into "unknown" state.
err := manager.StopContainer(instance)
c.Assert(err, gc.IsNil)
c.Assert(instance.Status(), gc.Equals, string(golxc.StateUnknown))
}
func (s *LxcSuite) TestStopContainer(c *gc.C) {
manager := lxc.NewContainerManager(lxc.ManagerConfig{})
instance := StartContainer(c, manager, "1/lxc/0")
err := manager.StopContainer(instance)
c.Assert(err, gc.IsNil)
name := string(instance.Id())
// Check that the container dir is no longer in the container dir
c.Assert(filepath.Join(s.ContainerDir, name), jc.DoesNotExist)
// but instead, in the removed container dir
c.Assert(filepath.Join(s.RemovedDir, name), jc.IsDirectory)
}
func (s *LxcSuite) <API key>(c *gc.C) {
manager := lxc.NewContainerManager(lxc.ManagerConfig{})
instance := StartContainer(c, manager, "1/lxc/0")
name := string(instance.Id())
targetDir := filepath.Join(s.RemovedDir, name)
err := os.MkdirAll(targetDir, 0755)
c.Assert(err, gc.IsNil)
err = manager.StopContainer(instance)
c.Assert(err, gc.IsNil)
// Check that the container dir is no longer in the container dir
c.Assert(filepath.Join(s.ContainerDir, name), jc.DoesNotExist)
// but instead, in the removed container dir with a ".1" suffix as there was already a directory there.
c.Assert(filepath.Join(s.RemovedDir, fmt.Sprintf("%s.1", name)), jc.IsDirectory)
}
func (s *LxcSuite) <API key>(c *gc.C) {
manager := lxc.NewContainerManager(lxc.ManagerConfig{Name: "eric"})
instance := StartContainer(c, manager, "1/lxc/0")
c.Assert(string(instance.Id()), gc.Equals, "<API key>")
}
func (s *LxcSuite) TestListContainers(c *gc.C) {
foo := lxc.NewContainerManager(lxc.ManagerConfig{Name: "foo"})
bar := lxc.NewContainerManager(lxc.ManagerConfig{Name: "bar"})
foo1 := StartContainer(c, foo, "1/lxc/0")
foo2 := StartContainer(c, foo, "1/lxc/1")
foo3 := StartContainer(c, foo, "1/lxc/2")
bar1 := StartContainer(c, bar, "1/lxc/0")
bar2 := StartContainer(c, bar, "1/lxc/1")
result, err := foo.ListContainers()
c.Assert(err, gc.IsNil)
instancetest.MatchInstances(c, result, foo1, foo2, foo3)
result, err = bar.ListContainers()
c.Assert(err, gc.IsNil)
instancetest.MatchInstances(c, result, bar1, bar2)
}
func (s *LxcSuite) <API key>(c *gc.C) {
manager := lxc.NewContainerManager(lxc.ManagerConfig{})
instance := StartContainer(c, manager, "1/lxc/0")
autostartLink := lxc.RestartSymlink(string(instance.Id()))
c.Assert(autostartLink, jc.IsSymlink)
}
func (s *LxcSuite) <API key>(c *gc.C) {
manager := lxc.NewContainerManager(lxc.ManagerConfig{})
instance := StartContainer(c, manager, "1/lxc/0")
err := manager.StopContainer(instance)
c.Assert(err, gc.IsNil)
autostartLink := lxc.RestartSymlink(string(instance.Id()))
c.Assert(autostartLink, jc.SymlinkDoesNotExist)
}
type NetworkSuite struct {
testbase.LoggingSuite
}
var _ = gc.Suite(&NetworkSuite{})
func (*NetworkSuite) <API key>(c *gc.C) {
for _, test := range []struct {
config *lxc.NetworkConfig
net string
link string
}{{
config: nil,
net: "veth",
link: "lxcbr0",
}, {
config: lxc.<API key>(),
net: "veth",
link: "lxcbr0",
}, {
config: lxc.BridgeNetworkConfig("foo"),
net: "veth",
link: "foo",
}, {
config: lxc.<API key>("foo"),
net: "phys",
link: "foo",
}} {
config := lxc.<API key>(test.config)
c.Assert(config, jc.Contains, fmt.Sprintf("lxc.network.type = %s\n", test.net))
c.Assert(config, jc.Contains, fmt.Sprintf("lxc.network.link = %s\n", test.link))
}
}
func (*NetworkSuite) <API key>(c *gc.C) {
config := lxc.<API key>("foo", "bar")
expected := `
lxc.network.type = foo
lxc.network.link = bar
lxc.network.flags = up
`
c.Assert(config, gc.Equals, expected)
}
|
#include "WowCrypt.hpp"
#include <algorithm>
#include <openssl/hmac.h>
WowCrypt::WowCrypt()
{
m_isInitialized = false;
<API key>.x = 0;
<API key>.y = 0;
<API key>.x = 0;
<API key>.y = 0;
m_sendI = 0;
m_sendJ = 0;
m_recvI = 0;
m_recvJ = 0;
}
WowCrypt::~WowCrypt()
{
}
bool WowCrypt::isInitialized()
{
return m_isInitialized;
}
// WotLK
void WowCrypt::initWotlkCrypt(uint8_t* key)
{
static const uint8_t send[seedLenght] = { 0xC2, 0xB3, 0x72, 0x3C, 0xC6, 0xAE, 0xD9, 0xB5, 0x34, 0x3C, 0x53, 0xEE, 0x2F, 0x43, 0x67, 0xCE };
static const uint8_t recv[seedLenght] = { 0xCC, 0x98, 0xAE, 0x04, 0xE8, 0x97, 0xEA, 0xCA, 0x12, 0xDD, 0xC0, 0x93, 0x42, 0x91, 0x53, 0x57 };
uint8_t encryptHash[SHA_DIGEST_LENGTH];
uint8_t decryptHash[SHA_DIGEST_LENGTH];
uint8_t pass[1024];
uint32_t mdLength;
HMAC(EVP_sha1(), send, seedLenght, key, 40, decryptHash, &mdLength);
assert(mdLength == SHA_DIGEST_LENGTH);
HMAC(EVP_sha1(), recv, seedLenght, key, 40, encryptHash, &mdLength);
assert(mdLength == SHA_DIGEST_LENGTH);
RC4_set_key(&<API key>, SHA_DIGEST_LENGTH, decryptHash);
RC4_set_key(&<API key>, SHA_DIGEST_LENGTH, encryptHash);
RC4(&<API key>, 1024, pass, pass);
RC4(&<API key>, 1024, pass, pass);
m_isInitialized = true;
}
void WowCrypt::initMopCrypt(uint8_t* key)
{
static const uint8_t send[seedLenght] = { 0x40, 0xAA, 0xD3, 0x92, 0x26, 0x71, 0x43, 0x47, 0x3A, 0x31, 0x08, 0xA6, 0xE7, 0xDC, 0x98, 0x2A };
static const uint8_t recv[seedLenght] = { 0x08, 0xF1, 0x95, 0x9F, 0x47, 0xE5, 0xD2, 0xDB, 0xA1, 0x3D, 0x77, 0x8F, 0x3F, 0x3E, 0xE7, 0x00 };
uint8_t encryptHash[SHA_DIGEST_LENGTH];
uint8_t decryptHash[SHA_DIGEST_LENGTH];
uint8_t pass[1024];
uint32_t mdLength;
HMAC(EVP_sha1(), send, seedLenght, key, 40, decryptHash, &mdLength);
assert(mdLength == SHA_DIGEST_LENGTH);
HMAC(EVP_sha1(), recv, seedLenght, key, 40, encryptHash, &mdLength);
assert(mdLength == SHA_DIGEST_LENGTH);
RC4_set_key(&<API key>, SHA_DIGEST_LENGTH, decryptHash);
RC4_set_key(&<API key>, SHA_DIGEST_LENGTH, encryptHash);
RC4(&<API key>, 1024, pass, pass);
RC4(&<API key>, 1024, pass, pass);
m_isInitialized = true;
}
void WowCrypt::decryptWotlkReceive(uint8_t* data, size_t length)
{
if (!m_isInitialized)
return;
RC4(&<API key>, (unsigned long)length, data, data);
}
void WowCrypt::encryptWotlkSend(uint8_t* data, size_t length)
{
if (!m_isInitialized)
return;
RC4(&<API key>, (unsigned long)length, data, data);
}
// Legacy
void WowCrypt::initLegacyCrypt()
{
m_isInitialized = true;
}
void WowCrypt::<API key>(uint8_t* data, size_t length)
{
if (!m_isInitialized)
return;
if (length < <API key>)
return;
uint8_t x;
for (size_t t = 0; t < <API key>; ++t)
{
m_recvI %= crypKeyVector.size();
x = (data[t] - m_recvJ) ^ crypKeyVector[m_recvI];
++m_recvI;
m_recvJ = data[t];
data[t] = x;
}
}
void WowCrypt::encryptLegacySend(uint8_t* data, size_t length)
{
if (!m_isInitialized)
return;
if (length < cryptedSendLength)
return;
for (size_t t = 0; t < cryptedSendLength; ++t)
{
m_sendI %= crypKeyVector.size();
data[t] = m_sendJ = (data[t] ^ crypKeyVector[m_sendI]) + m_sendJ;
++m_sendI;
}
}
void WowCrypt::setLegacyKey(uint8_t* key, size_t length)
{
crypKeyVector.resize(length);
std::copy(key, key + length, crypKeyVector.begin());
}
void WowCrypt::generateTbcKey(uint8_t* key, uint8_t* sessionkey)
{
uint8_t seedKey[seedLenght] = { 0x38, 0xA7, 0x83, 0x15, 0xF8, 0x92, 0x25, 0x30, 0x71, 0x98, 0x67, 0xB1, 0x8C, 0x4, 0xE2, 0xAA };
uint8_t firstBuffer[64];
uint8_t secondBuffer[64];
memset(firstBuffer, 0x36, 64);
memset(secondBuffer, 0x5C, 64);
for (uint8_t i = 0; i < seedLenght; ++i)
{
firstBuffer[i] = (uint8_t)(seedKey[i] ^ firstBuffer[i]);
secondBuffer[i] = (uint8_t)(seedKey[i] ^ secondBuffer[i]);
}
Sha1Hash sha1;
sha1.UpdateData(firstBuffer, 64);
sha1.UpdateData(sessionkey, 40);
sha1.Finalize();
uint8_t* tempDigest = sha1.GetDigest();
Sha1Hash sha2;
sha2.UpdateData(secondBuffer, 64);
sha2.UpdateData(tempDigest, SHA_DIGEST_LENGTH);
sha2.Finalize();
memcpy(key, sha2.GetDigest(), SHA_DIGEST_LENGTH);
}
|
<?php
/**
* @see <API key>
*/
//$1 'Zend/Service/Amazon/Item.php';
class <API key> implements SeekableIterator
{
/**
* A DOMNodeList of <Item> elements
*
* @var DOMNodeList
*/
protected $_results = null;
/**
* Amazon Web Service Return Document
*
* @var DOMDocument
*/
protected $_dom;
/**
* XPath Object for $this->_dom
*
* @var DOMXPath
*/
protected $_xpath;
/**
* Current index for SeekableIterator
*
* @var int
*/
protected $_currentIndex = 0;
/**
* Create an instance of <API key> and create the necessary data objects
*
* @param DOMDocument $dom
* @return void
*/
public function __construct(DOMDocument $dom)
{
$this->_dom = $dom;
$this->_xpath = new DOMXPath($dom);
$this->_xpath->registerNamespace('az', 'http://webservices.amazon.com/AWSECommerceService/2005-10-05');
$this->_results = $this->_xpath->query('//az:Item');
}
/**
* Total Number of results returned
*
* @return int Total number of results returned
*/
public function totalResults()
{
$result = $this->_xpath->query('//az:TotalResults/text()');
return (int) $result->item(0)->data;
}
/**
* Total Number of pages returned
*
* @return int Total number of pages returned
*/
public function totalPages()
{
$result = $this->_xpath->query('//az:TotalPages/text()');
return (int) $result->item(0)->data;
}
/**
* Implement SeekableIterator::current()
*
* @return <API key>
*/
public function current()
{
return new <API key>($this->_results->item($this->_currentIndex));
}
/**
* Implement SeekableIterator::key()
*
* @return int
*/
public function key()
{
return $this->_currentIndex;
}
/**
* Implement SeekableIterator::next()
*
* @return void
*/
public function next()
{
$this->_currentIndex += 1;
}
/**
* Implement SeekableIterator::rewind()
*
* @return void
*/
public function rewind()
{
$this->_currentIndex = 0;
}
/**
* Implement SeekableIterator::seek()
*
* @param int $index
* @throws <API key>
* @return void
*/
public function seek($index)
{
$indexInt = (int) $index;
if ($indexInt >= 0 && (null === $this->_results || $indexInt < $this->_results->length)) {
$this->_currentIndex = $indexInt;
} else {
throw new <API key>("Illegal index '$index'");
}
}
/**
* Implement SeekableIterator::valid()
*
* @return boolean
*/
public function valid()
{
return null !== $this->_results && $this->_currentIndex < $this->_results->length;
}
}
|
DELETE FROM `weenie` WHERE `class_Id` = 28184;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (28184, '<API key>', 10, '2019-02-10 00:00:00') /* Creature */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (28184, 1, 16) /* ItemType - Creature */
, (28184, 2, 31) /* CreatureType - Human */
, (28184, 6, -1) /* ItemsCapacity */
, (28184, 7, -1) /* ContainersCapacity */
, (28184, 16, 32) /* ItemUseable - Remote */
, (28184, 25, 5) /* Level */
, (28184, 93, 6292504) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity, <API key>, EdgeSlide */
, (28184, 95, 8) /* RadarBlipColor - Yellow */
, (28184, 113, 2) /* Gender - Female */
, (28184, 133, 4) /* ShowableOnRadar - ShowAlways */
, (28184, 134, 16) /* PlayerKillerStatus - RubberGlue */
, (28184, 188, 3) /* HeritageGroup - Sho */
, (28184, 8007, 0) /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (28184, 1, True ) /* Stuck */
, (28184, 19, False) /* Attackable */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (28184, 54, 3) /* UseRadius */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (28184, 1, 'Apprentice Alchemist') /* Name */
, (28184, 5, 'Apprentice Alchemist') /* Template */
, (28184, 8006, 'AAA9AAAAAAA=') /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (28184, 1, 0x0200004E) /* Setup */
, (28184, 2, 0x09000001) /* MotionTable */
, (28184, 3, 0x20000002) /* SoundTable */
, (28184, 6, 0x0400007E) /* PaletteBase */
, (28184, 8, 0x06000FEF) /* Icon */
, (28184, 9, 0x05001043) /* EyesTexture */
, (28184, 10, 0x05001086) /* NoseTexture */
, (28184, 11, 0x050010A0) /* MouthTexture */
, (28184, 15, 0x04001FC5) /* HairPalette */
, (28184, 16, 0x040004AF) /* EyesPalette */
, (28184, 17, 0x040004AB) /* SkinPalette */
, (28184, 8001, 9437238) /* <API key> - ItemsCapacity, ContainersCapacity, Usable, UseRadius, RadarBlipColor, RadarBehavior */
, (28184, 8003, 4) /* <API key> - Stuck */
, (28184, 8005, 100355) /* <API key> - CSetup, MTable, STable, Position, Movement */;
INSERT INTO `<API key>` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (28184, 8040, 0xDB3B010D, 55.4016, 82.3784, 28.005, 0.874849, 0, 0, -0.484396) /* <API key> */
/* @teleloc 0xDB3B010D [55.401600 82.378400 28.005000] 0.874849 0.000000 0.000000 -0.484396 */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (28184, 8000, 0xDBAC4E38) /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`)
VALUES (28184, 1, 80, 0, 0) /* Strength */
, (28184, 2, 90, 0, 0) /* Endurance */
, (28184, 3, 70, 0, 0) /* Quickness */
, (28184, 4, 70, 0, 0) /* Coordination */
, (28184, 5, 50, 0, 0) /* Focus */
, (28184, 6, 60, 0, 0) /* Self */;
INSERT INTO `<API key>` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`, `current_Level`)
VALUES (28184, 1, 80, 0, 0, 125) /* MaxHealth */
, (28184, 3, 110, 0, 0, 200) /* MaxStamina */
, (28184, 5, 40, 0, 0, 100) /* MaxMana */;
INSERT INTO `<API key>` (`object_Id`, `sub_Palette_Id`, `offset`, `length`)
VALUES (28184, 67109969, 92, 4)
, (28184, 67110059, 0, 24)
, (28184, 67110063, 32, 8)
, (28184, 67110349, 64, 8)
, (28184, 67110539, 72, 8)
, (28184, 67111246, 160, 8)
, (28184, 67112919, 40, 24)
, (28184, 67116997, 24, 8);
INSERT INTO `<API key>` (`object_Id`, `index`, `old_Id`, `new_Id`)
VALUES (28184, 0, 83889072, 83886685)
, (28184, 0, 83889342, 83889386)
, (28184, 1, 83887064, 83886241)
, (28184, 2, 83887066, 83887051)
, (28184, 3, 83889344, 83887054)
, (28184, 4, 83887068, 83887054)
, (28184, 5, 83887064, 83886241)
, (28184, 6, 83887066, 83887051)
, (28184, 7, 83889344, 83887054)
, (28184, 8, 83887068, 83887054)
, (28184, 9, 83887070, 83886781)
, (28184, 9, 83887062, 83886686)
, (28184, 10, 83887069, 83886782)
, (28184, 11, 83887067, 83891213)
, (28184, 13, 83887069, 83886782)
, (28184, 14, 83887067, 83891213)
, (28184, 16, 83886232, 83890685)
, (28184, 16, 83886668, 83890243)
, (28184, 16, 83886837, 83890310)
, (28184, 16, 83886684, 83890336);
INSERT INTO `<API key>` (`object_Id`, `index`, `animation_Id`)
VALUES (28184, 0, 16778359)
, (28184, 1, 16778430)
, (28184, 2, 16778436)
, (28184, 3, 16778361)
, (28184, 4, 16778426)
, (28184, 5, 16778438)
, (28184, 6, 16778437)
, (28184, 7, 16778360)
, (28184, 8, 16778428)
, (28184, 9, 16778425)
, (28184, 10, 16778431)
, (28184, 11, 16778429)
, (28184, 12, 16778423)
, (28184, 13, 16778434)
, (28184, 14, 16778424)
, (28184, 15, 16778435)
, (28184, 16, 16795640);
|
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.http import <API key>, Http404
from django.db.models import Q
from django.contrib import messages
from cc.general.util import render
import cc.ripple.api as ripple
from cc.profile.models import Profile
from cc.relate.forms import EndorseForm, AcknowledgementForm
from cc.relate.models import Endorsement
from cc.feed.models import FeedItem
from cc.general.mail import send_notification
from django.utils.translation import ugettext as _
MESSAGES = {
'endorsement_saved': _("Endorsement saved."),
'endorsement_deleted': _("Endorsement deleted."),
'<API key>': _("Acknowledgement sent."),
}
@login_required
@render()
def endorse_user(request, recipient_username):
recipient = get_object_or_404(Profile, user__username=recipient_username)
if recipient == request.profile:
raise Http404()
try:
endorsement = Endorsement.objects.get(
endorser=request.profile, recipient=recipient)
except Endorsement.DoesNotExist:
endorsement = None
if request.method == 'POST':
if 'delete' in request.POST and endorsement:
endorsement.delete()
messages.info(request, MESSAGES['endorsement_deleted'])
return <API key>(
endorsement.recipient.get_absolute_url())
form = EndorseForm(request.POST, instance=endorsement,
endorser=request.profile, recipient=recipient)
if form.is_valid():
is_new = endorsement is None
endorsement = form.save()
if is_new:
<API key>(endorsement)
messages.info(request, MESSAGES['endorsement_saved'])
return <API key>(endorsement.get_absolute_url())
else:
form = EndorseForm(instance=endorsement, endorser=request.profile,
recipient=recipient)
profile = recipient # For profile_base.html.
return locals()
def <API key>(endorsement):
subject = _("%s has endorsed you on Villages.cc") % endorsement.endorser
send_notification(subject, endorsement.endorser, endorsement.recipient,
'<API key>.txt',
{'endorsement': endorsement})
@login_required
@render()
def endorsement(request, endorsement_id):
endorsement = get_object_or_404(Endorsement, pk=endorsement_id)
return locals()
@login_required
@render()
def relationships(request):
accounts = ripple.get_user_accounts(request.profile)
return locals()
@login_required
@render()
def relationship(request, partner_username):
partner = get_object_or_404(Profile, user__username=partner_username)
if partner == request.profile:
raise Http404 # Can't have relationship with yourself.
account = request.profile.account(partner)
if account:
entries = account.entries
balance = account.balance
else:
entries = []
balance = 0
profile = partner # For profile_base.html.
return locals()
@login_required
@render()
def acknowledge_user(request, recipient_username):
recipient = get_object_or_404(Profile, user__username=recipient_username)
if recipient == request.profile:
raise Http404
# TODO: Don't recompute max_amount on form submit? Cache, or put in form
# as hidden field?
max_amount = ripple.max_payment(request.profile, recipient)
if request.method == 'POST':
form = AcknowledgementForm(request.POST, max_ripple=max_amount)
if form.is_valid():
acknowledgement = form.<API key>(
request.profile, recipient)
<API key>(acknowledgement)
messages.info(request, MESSAGES['<API key>'])
return <API key>(acknowledgement.get_absolute_url())
else:
form = AcknowledgementForm(max_ripple=max_amount, initial=request.GET)
can_ripple = max_amount > 0
profile = recipient # For profile_base.html.
return locals()
def <API key>(acknowledgement):
subject = _("%s has acknowledged you on Villages.cc") % (
acknowledgement.payer)
send_notification(subject, acknowledgement.payer, acknowledgement.recipient,
'<API key>.txt',
{'acknowledgement': acknowledgement})
@login_required
@render()
def <API key>(request, payment_id):
try:
payment = ripple.get_payment(payment_id)
except ripple.RipplePayment.DoesNotExist:
raise Http404
entries = payment.entries_for_user(request.profile)
if not entries:
raise Http404 # Non-participants don't get to see anything.
sent_entries = []
received_entries = []
for entry in entries:
if entry.amount < 0:
sent_entries.append(entry)
else:
received_entries.append(entry)
return locals()
|
package nl.mpi.yams.common.data;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "Highlight")
public class DataNodeHighlight implements Serializable {
private String dataNodeId = null;
private String highlightPath = null;
public String getDataNodeId() {
return dataNodeId;
}
@XmlAttribute(name = "ID")
public void setDataNodeId(String dataNodeId) {
this.dataNodeId = dataNodeId;
}
public String getHighlightPath() {
return highlightPath;
}
@XmlAttribute(name = "Path")
public void setHighlightPath(String highlightPath) {
this.highlightPath = highlightPath;
}
}
|
DELETE FROM `weenie` WHERE `class_Id` = 3140;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (3140, '<API key>', 34, '2019-02-10 00:00:00') /* Scroll */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (3140, 1, 8192) /* ItemType - Writable */
, (3140, 5, 30) /* EncumbranceVal */
, (3140, 16, 8) /* ItemUseable - Contained */
, (3140, 19, 100) /* Value */
, (3140, 93, 1044) /* PhysicsState - Ethereal, IgnoreCollisions, Gravity */
, (3140, 8041, 101) /* <API key> - Resting */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (3140, 22, True ) /* Inscribable */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (3140, 39, 1.5) /* DefaultScale */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (3140, 1, 'Scroll of Arcane Enlightenment Self IV') /* Name */
, (3140, 14, 'Use this item to attempt to learn its spell.') /* Use */
, (3140, 16, 'Inscribed spell: Arcane Enlightenment Self IV
Increases the caster''s Arcane Lore skill by 25 points.') /* LongDesc */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (3140, 1, 33554826) /* Setup */
, (3140, 8, 100676447) /* Icon */
, (3140, 22, 872415275) /* PhysicsEffectTable */
, (3140, 28, 681) /* Spell - <API key> */
, (3140, 8001, 6307864) /* <API key> - Value, Usable, Container, Burden, Spell */
, (3140, 8003, 18) /* <API key> - Inscribable, Attackable */
, (3140, 8005, 135297) /* <API key> - CSetup, ObjScale, PeTable, AnimationFrame */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (3140, 8000, 3694570528) /* <API key> */;
|
# -*- coding: utf-8 -*-
# Ingenieria ADHOC - ADHOC SA
# This program is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
import waybill
import wizard
import travel
import vehicle
import requirement
import res_partner
import waybill_expense
import account_invoice
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
// Genesis is free software: you can redistribute it and/or modify
// (at your option) any later version.
// Genesis is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
#![allow(dead_code)]
use super::ioport;
const PORT_BASE: u16 = 0x3F8;
// when DLAB = 0
const DATA_REG: u16 = 0;
const INT_ENABLE: u16 = 1;
// when DLAB = 1
const BAUD_DIV_LSB: u16 = 0;
const BAUD_DIV_MSB: u16 = 1;
const LINE_CTRL_REG: u16 = 3;
const <API key>: u8 = 1 | 1 << 1;
const LINE_CTRL_REG_DLAB: u8 = 1 << 7;
const LINE_STATUS_REG: u16 = 5;
const <API key>: u8 = 1 << 5;
Initialize the Serial Port
pub fn init() {
<API key>!("serial::init() function \
must only be called once");
unsafe {
ioport::out(PORT_BASE + INT_ENABLE, 0u8); // disable interrupts
// enable dlab
ioport::out(PORT_BASE + LINE_CTRL_REG, LINE_CTRL_REG_DLAB);
// XXX: hard coded 115200 baud
ioport::out(PORT_BASE + BAUD_DIV_LSB, 1u8);
ioport::out(PORT_BASE + BAUD_DIV_MSB, 0u8);
// XXX: hard coded as 8N1 (8 bits, no parity, one stop bit)
ioport::out(PORT_BASE + LINE_CTRL_REG, <API key>);
}
}
unsafe fn is_transmit_empty() -> bool {
ioport::inb(PORT_BASE + LINE_STATUS_REG) & <API key> != 0
}
unsafe fn putc(c: u8) {
while !is_transmit_empty() {}
ioport::out(PORT_BASE + DATA_REG, c);
}
Write `str` to the Serial Port
pub unsafe fn write_str(s: &str) {
for c in s.bytes() {
putc(c);
}
}
|
# <API key>
This repository serves as a mirror of the GNU social [translation project](https:
Instructions - how to use the translations:
1. Make sure you have **Git** and **GNU Make** installed. On Ubuntu, or similar linux distribution, use `sudo apt-get install git make`
2. Clone this repository using `git clone https://github.com/digital-dreamer/<API key>.git`, or if you already cloned it some time ago, update it using `git pull`
3. Copy the 2 folders you see in the cloned repository (`locale` and `plugins`), and paste them into the folder where you installed your GNU social instance.
4. Go to that folder (where GNU social is installed) and run this command: `make translations`
If you encounter any problems, please go to the issues section of this repository and open a new issue.
[GNU social](http:
|
package com.sapienter.jbilling.server.pluggableTask.admin;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.collections.iterators.ArrayListIterator;
import org.apache.log4j.Logger;
import com.sapienter.jbilling.common.<API key>;
import com.sapienter.jbilling.server.pluggableTask.PluggableTask;
import com.sapienter.jbilling.server.util.Constants;
import com.sapienter.jbilling.server.util.Context;
import com.sapienter.jbilling.server.util.audit.EventLogger;
public class PluggableTaskBL<T> {
private static final Logger LOG = Logger.getLogger(PluggableTaskBL.class);
private EventLogger eLogger = null;
private PluggableTaskDAS das = null;
private <API key> dasParameter = null;
private PluggableTaskDTO pluggableTask = null;
public PluggableTaskBL(Integer pluggableTaskId) {
init();
set(pluggableTaskId);
}
public PluggableTaskBL() {
init();
}
private void init() {
eLogger = EventLogger.getInstance();
das = (PluggableTaskDAS) Context.getBean(Context.Name.PLUGGABLE_TASK_DAS);
dasParameter = new <API key>();
}
public void set(Integer id) {
pluggableTask = das.find(id);
}
public void set(Integer entityId, Integer typeId) {
pluggableTask = das.findByEntityType(entityId, typeId);
}
public void set(PluggableTaskDTO task) {
pluggableTask = task;
}
public PluggableTaskDTO getDTO() {
return pluggableTask;
}
public int create(Integer executorId, PluggableTaskDTO dto) {
validate(dto);
LOG.debug("Creating a new pluggable task row " + dto);
pluggableTask = das.save(dto);
eLogger.audit(executorId, null, Constants.<API key>,
pluggableTask.getId(), EventLogger.<API key>,
EventLogger.ROW_CREATED, null, null, null);
return pluggableTask.getId();
}
public void createParameter(Integer taskId,
<API key> dto) {
PluggableTaskDTO task = das.find(taskId);
dto.setTask(task);
task.getParameters().add(dasParameter.save(dto));
// clear the rules cache (just in case this plug-in was ruled based)
PluggableTask.invalidateRuleCache(taskId);
}
public void update(Integer executorId, PluggableTaskDTO dto) {
if (dto == null || dto.getId() == null) {
throw new <API key>("task to update can't be null");
}
validate(dto);
List<<API key>> parameterDTOList = dasParameter.findAllByTask(dto);
for (<API key> param: dto.getParameters()) {
parameterDTOList.remove(dasParameter.find(param.getId()));
param.expandValue();
}
for (<API key> param: parameterDTOList){
dasParameter.delete(param);
}
LOG.debug("updating " + dto);
pluggableTask = das.save(dto);
eLogger.audit(executorId, null
, Constants.<API key>,
dto.getId(), EventLogger.<API key>,
EventLogger.ROW_UPDATED, null, null, null);
// clear the rules cache (just in case this plug-in was ruled based)
PluggableTask.invalidateRuleCache(dto.getId());
das.invalidateCache(); // 3rd level cache
pluggableTask.populateParamValues();
}
public void delete(Integer executor) {
eLogger.audit(executor, null, Constants.<API key>,
pluggableTask.getId(), EventLogger.<API key>,
EventLogger.ROW_DELETED, null, null, null);
das.delete(pluggableTask);
// clear the rules cache (just in case this plug-in was ruled based)
PluggableTask.invalidateRuleCache(pluggableTask.getId());
}
public void deleteParameter(Integer executor, Integer id) {
eLogger.audit(executor, null, Constants.<API key>,
id, EventLogger.<API key>,
EventLogger.ROW_DELETED, null, null, null);
<API key> toDelete = dasParameter.find(id);
toDelete.getTask().getParameters().remove(toDelete);
// clear the rules cache (just in case this plug-in was ruled based)
PluggableTask.invalidateRuleCache(toDelete.getTask().getId());
dasParameter.delete(toDelete);
}
public void updateParameters(PluggableTaskDTO dto) {
// update the parameters from the dto
for (<API key> parameter: dto.getParameters()) {
updateParameter(parameter);
}
}
private void updateParameter(<API key> dto) {
dto.expandValue();
dasParameter.save(dto);
// clear the rules cache (just in case this plug-in was ruled based)
PluggableTask.invalidateRuleCache(dto.getTask().getId());
}
public T instantiateTask()
throws <API key> {
PluggableTaskDTO localTask = getDTO();
String fqn = localTask.getType().getClassName();
T result;
try {
Class taskClazz = Class.forName(fqn);
//.asSubclass(result.getClass());
result = (T) taskClazz.newInstance();
} catch (ClassCastException e) {
throw new <API key>("Task id: " + pluggableTask.getId()
+ ": implementation class does not implements PaymentTask:"
+ fqn, e);
} catch (<API key> e) {
throw new <API key>("Task id: " + pluggableTask.getId()
+ ": Can not instantiate : " + fqn, e);
} catch (<API key> e) {
throw new <API key>("Task id: " + pluggableTask.getId()
+ ": Can not find public constructor for : " + fqn, e);
} catch (<API key> e) {
throw new <API key>("Task id: " + pluggableTask.getId()
+ ": Unknown class: " + fqn, e);
}
if (result instanceof PluggableTask) {
PluggableTask pluggable = (PluggableTask) result;
pluggable.initializeParamters(localTask);
} else {
throw new <API key>("Plug-in has to extend PluggableTask " +
pluggableTask.getId());
}
return result;
}
private void validate(PluggableTaskDTO task) {
List<<API key>> missingParameters = new ArrayList<<API key>>();
try {
// start by getting an instance of this type
PluggableTask instance = (PluggableTask) <API key>.getInstance(
task.getType().getClassName(), task.getType().getCategory().getInterfaceName());
// loop through the descriptions of parameters
for (<API key> param: instance.<API key>()) {
if (param.isRequired()) {
if(task.getParameters()== null || task.getParameters().size() == 0) {
missingParameters.add(param);
} else {
boolean found = false;
for (<API key> parameter:task.getParameters()) {
if (parameter.getName().equals(param.getName()) && parameter.getStrValue() != null &&
parameter.getStrValue().trim().length() > 0) {
found = true;
break;
}
}
if (!found) {
missingParameters.add(param);
}
}
}
}
} catch (<API key> e) {
LOG.error("Getting instance of plug-in for validation", e);
throw new <API key>("Validating plug-in");
}
if (missingParameters.size() > 0) {
<API key> exception = new <API key>("Validation of new plug-in");
String messages[] = new String[missingParameters.size()];
int f=0;
for (<API key> param: missingParameters) {
messages[f] = new String("PluggableTaskWS,parameter,plugins.error.required_parameter," + param.getName());
f++;
}
exception.setErrorMessages(messages);
throw exception;
}
// now validate that the processing order is not already taken
boolean nonUniqueResult= false;
try {
PluggableTaskDTO samePlugin = das.<API key>(task.getEntityId(), task.getType().getCategory().getId(),
task.getProcessingOrder());
if (samePlugin != null && !samePlugin.getId().equals(task.getId())) {
nonUniqueResult=true;
}
} catch (Exception e) {
nonUniqueResult=true;
}
if (nonUniqueResult) {
<API key> exception = new <API key>("Validation of new plug-in");
exception.setErrorMessages(new String[] {
"PluggableTaskWS,processingOrder,plugins.error.same_order," + task.getProcessingOrder()});
throw exception;
}
}
}
|
<?php
define('DB_ADAPTER', 'mysql');
define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', 'e3i71BFGRqda3');
define('DB_NAME', 'ppdev_mf');
define('DB_PREFIX', 'pp088_');
define('DB_CHARSET', 'utf8');
define('DB_PERSIST', false);
return true;
?>
|
class CreateDidNotVotes < ActiveRecord::Migration[4.2]
def change
create_table :did_not_votes do |t|
t.references :user
t.references :motion
t.timestamps
end
add_index :did_not_votes, :user_id
add_index :did_not_votes, :motion_id
end
end
|
module Isi
module FreeChat
Isi::db_hello __FILE__, name
require 'pathname'
ModuleRootDir = Pathname(__FILE__).dirname + name.split('::').last
# require all files for this module
require ModuleRootDir + 'protocol' # this should include everything else
require ModuleRootDir + 'free_chat_u_i' # except for this
Isi::db_bye __FILE__, name
end
end
|
from . import mass_reconcile
from . import <API key>
|
# == Schema Information
# Table name: terms
# id :integer not null, primary key
# sourced_id :string
# title :string
# start_at :datetime
# end_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
class Term < ApplicationRecord
has_many :courses, -> { where('courses.enabled = ?', true) }
validates :end_at, presence: true
validates :sourced_id, uniqueness: true, allow_nil: true
validates :start_at, presence: true
validates :title, presence: true
validates :title, uniqueness: true
validate :<API key>
# Public Functions
def self.sync_roster(rterms)
# Create and Update with OneRoster data
# Synchronous term condition
now = Time.zone.now
rterms.select!{|rt| ((Time.zone.parse(rt['startDate']) - 1.month)...Time.zone.parse(rt['endDate'])).cover? now}
ids = []
rterms.each do |rt|
term = Term.<API key>(sourced_id: rt['sourcedId'])
if term.update_attributes(title: rt['title'], start_at: rt['startDate'], end_at: rt['endDate'])
ids.push({id: term.id, sourced_id: term.sourced_id, status: term.status})
end
end
ids
end
def self.creatable?(user_id)
# Not permitted when SYSTEM_ROSTER_SYNC is :suspended
return false if %i[on off].exclude? SYSTEM_ROSTER_SYNC
user = User.find user_id
user.system_staff?
end
def destroyable?(user_id)
return false if new_record?
return false unless courses.size.zero?
updatable? user_id
end
def updatable?(user_id)
return false if SYSTEM_ROSTER_SYNC == :on && sourced_id.blank?
return false if SYSTEM_ROSTER_SYNC == :off && sourced_id.present?
Term.creatable? user_id
end
def status
now = Time.zone.now
if now < start_at
'draft'
elsif end_at <= now
'archived'
else
'open'
end
end
def to_roster_hash
hash = {
title: self.title,
type: 'term',
startDate: self.start_at,
endDate: self.end_at,
schoolYear: self.end_at.year
}
end
# Private Functions
private
def <API key>
# start_at: inclusive start date for the term
# end_at: exclusive end date for the term
if start_at.present? && end_at.present?
errors.add(:end_at) unless end_at > start_at
end
end
end
|
OC.L10N.register(
"templateeditor",
{
"Could not load template" : "امکان بارگذاری قالب وجود ندارد",
"Saved" : "ذخیره شد",
"Reset" : "تنظیم مجدد",
"An error occurred" : "یک خطا رخ داده است",
"Sharing email - public link shares (HTML)" : "ایمیل اشتراک گذاری-لینک عمومی اشتراک گذاری(HTML)",
"Sharing email - public link shares (plain text fallback)" : "ایمیل اشتراک گذاری-لینک عمومی اشتراک گذاری(plain text fallback)",
"Sharing email (HTML)" : "اشتراکگذاری ایمیل (HTML)",
"Sharing email (plain text fallback)" : "ایمیل اشتراک گذاری (plain text fallback)",
"Lost password mail" : "ایمیل فراموش کردن رمز عبور",
"New user email (HTML)" : "ایمیل کاربری جدید (HTML)",
"New user email (plain text fallback)" : "ایمیل کاربر جدید (plain text fallback)",
"Activity notification mail" : "ایمیل هشدار فعالیت",
"Mail Templates" : "قالبهای ایمیل",
"Theme" : "تم",
"Template" : "قالب",
"Please choose a template" : "لطفا یک قالب انتخاب کنید",
"Save" : "ذخیره"
},
"nplurals=1; plural=0;");
|
<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>{% block title %}{% endblock %}</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="{{ request.static_url('cnxpublishing:static/css/normalize.min.css') }}">
<link rel="stylesheet" href="{{ request.static_url('cnxpublishing:static/css/main.css') }}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<script src="{{ request.static_url('cnxpublishing:static/js/vendor/modernizr-2.8.3.min.js') }}"></script>
{% block head %}
{% endblock %}
</head>
<body>
<div id='content'>
{% block content %}
{% endblock %}
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="' + "{{ request.static_url('cnxpublishing:static/js/vendor/jquery-1.11.2.min.js') }}" + '"><\/script>')</script>
<script src="{{ request.static_url('cnxpublishing:static/js/plugins.js') }}"></script>
<script src="{{ request.static_url('cnxpublishing:static/js/main.js') }}"></script>
<script>
{% block script %}
{% endblock %}
</script>
</body>
</html>
|
<?php
namespace FOS\UserBundle\Model;
/**
* Interface to be implemented by group managers. This adds an additional level
* of abstraction between your application, and the actual repository.
*
* All changes to groups should happen through this interface.
*
* @author Christophe Coevoet <stof@notk.org>
*/
interface <API key> {
/**
* Returns an empty group instance.
*
* @param string $name
* @return GroupInterface
*/
function createGroup($name);
/**
* Deletes a group.
*
* @param GroupInterface $group
* @return void
*/
function deleteGroup(GroupInterface $group);
/**
* Finds one group by the given criteria.
*
* @param array $criteria
* @return GroupInterface
*/
function findGroupBy(array $criteria);
/**
* Finds a group by name.
*
* @param string $name
* @return GroupInterface
*/
function findGroupByName($name);
/**
* Returns a collection with all user instances.
*
* @return \Traversable
*/
function findGroups();
/**
* Returns the group's fully qualified class name.
*
* @return string
*/
function getClass();
/**
* Updates a group.
*
* @param GroupInterface $group
*/
function updateGroup(GroupInterface $group);
}
|
package org.rstudio.studio.client.workbench.views.source.editors.text.status;
import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.*;
import org.rstudio.core.client.widget.IsWidgetWithHeight;
public class StatusBarWidget extends Composite
implements StatusBar, IsWidgetWithHeight
{
private int height_;
interface Binder extends UiBinder<HorizontalPanel, StatusBarWidget>
{
}
public StatusBarWidget()
{
Binder binder = GWT.create(Binder.class);
HorizontalPanel hpanel = binder.createAndBindUi(this);
hpanel.<API key>(HorizontalPanel.ALIGN_TOP);
hpanel.setCellWidth(hpanel.getWidget(2), "100%");
initWidget(hpanel);
height_ = 16;
}
public int getHeight()
{
return height_;
}
public Widget asWidget()
{
return this;
}
public StatusBarElement getPosition()
{
return position_;
}
public StatusBarElement getFunction()
{
return function_;
}
public StatusBarElement getLanguage()
{
return language_;
}
public void setFunctionVisible(boolean visible)
{
function_.setContentsVisible(visible);
funcIcon_.setVisible(visible);
}
@UiField
<API key> position_;
@UiField
<API key> function_;
@UiField
<API key> language_;
@UiField
Image funcIcon_;
}
|
CKEDITOR.plugins.setLang( 'specialchar', 'cs', {
options: 'Nastavení speciálních znaků',
title: 'Výběr speciálního znaku',
toolbar: 'Vložit speciální znaky'
} );
|
<div class="row">
<div class="span9">
<span id="<API key>"></span>
</div>
</div>
<div class="row">
<div class="span9">
<span id="<API key>"></span>
</div>
</div>
<script type="text/javascript" src="/static/js/pybossa/pybossa.js"></script>
<script type="text/javascript" src="/cellspotting/static/js/jquery.i18n.min.js"></script>
<script type="text/javascript" src="/cellspotting/static/js/<API key>.js"></script>
<script type="text/javascript">
$("[rel=tooltip]").tooltip();
</script>
<script>
var language;
var dict;
pybossa.setEndpoint("/pybossa");
pybossa.getSettings().done(function(data){
language = data.language;
if (language == null) {
// Detect browser language
var userLang = navigator.language || navigator.userLanguage;
if (userLang.indexOf("en") != -1)
language = "en";
else if (userLang.indexOf("es") != -1)
language = "es";
else if (userLang.indexOf("pt") != -1)
language = "pt";
}
console.log("1"+language);
switch(language){
case "en": dict = en_US_dict; break;
case "pt": dict = pt_dict; break;
case "es": dict = es_dict; break;
default: dict = default_dict;
}
$.i18n.setDictionary(dict);
$('#<API key>').html($.i18n._('<API key>'));
$('#<API key>').html($.i18n._('<API key>'));
});
</script>
|
package scrum.client.communication;
import ilarkesto.core.logging.Log;
import ilarkesto.core.time.Tm;
import java.util.LinkedList;
import scrum.client.DataTransferObject;
import scrum.client.core.<API key>;
import scrum.client.core.<API key>;
import scrum.client.project.Requirement;
import scrum.client.workspace.BlockCollapsedEvent;
import scrum.client.workspace.<API key>;
import scrum.client.workspace.BlockExpandedEvent;
import scrum.client.workspace.<API key>;
import com.google.gwt.user.client.Timer;
public class Pinger extends GPinger implements <API key>, <API key>, <API key>,
<API key> {
private static Log log = Log.get(Pinger.class);
public static final int MIN_DELAY = 1000;
public static final int MAX_DELAY = 5000;
private Timer timer;
private int maxDelay = MAX_DELAY;
private long lastDataReceiveTime = Tm.<API key>();
private LinkedList<Long> pingTimes = new LinkedList<Long>();
private boolean disabled;
@Override
public void <API key>(<API key> event) {
timer = new Timer() {
@Override
public void run() {
if (!disabled && !serviceCaller.containsServiceCall(PingServiceCall.class)) {
final long start = Tm.<API key>();
new PingServiceCall().execute(new Runnable() {
@Override
public void run() {
long time = Tm.<API key>() - start;
pingTimes.add(time);
if (pingTimes.size() > 10) pingTimes.removeFirst();
}
});
}
reschedule();
}
};
reschedule();
}
public void setDisabled(boolean disabled) {
this.disabled = disabled;
}
public boolean isDisabled() {
return disabled;
}
public void shutdown() {
log.info("Shutting down");
if (timer == null) return;
timer.cancel();
timer = null;
}
@Override
public void <API key>(<API key> event) {
DataTransferObject data = event.getData();
if (data.containsEntities()) {
lastDataReceiveTime = Tm.<API key>();
reschedule();
}
}
@Override
public void onBlockCollapsed(BlockCollapsedEvent event) {
<API key>();
}
@Override
public void onBlockExpanded(BlockExpandedEvent event) {
Object object = event.getObject();
if (object instanceof Requirement) {
Requirement requirement = (Requirement) object;
if (requirement.<API key>()) <API key>();
}
}
public void reschedule() {
if (timer == null) return;
long idle = Tm.<API key>() - lastDataReceiveTime;
idle = (int) (idle * 0.15);
if (idle < MIN_DELAY) idle = MIN_DELAY;
if (idle > maxDelay) idle = maxDelay;
timer.scheduleRepeating((int) idle);
}
private void <API key>() {
maxDelay = MIN_DELAY;
log.debug("PowerPolling activated");
}
private void <API key>() {
if (maxDelay == MAX_DELAY) return;
maxDelay = MAX_DELAY;
lastDataReceiveTime = Tm.<API key>();
log.debug("PowerPolling deactivated");
}
public Long getAvaragePingTime() {
if (pingTimes.isEmpty()) return null;
long sum = 0;
for (Long time : pingTimes) {
sum += time;
}
return sum / pingTimes.size();
}
public String <API key>() {
Long time = getAvaragePingTime();
if (time == null) return null;
return "Current response time: " + time + " ms.";
}
}
|
# Bold - more than just blogging.
# This file is part of Bold.
# Bold is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# Bold is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
require 'test_helper'
class AssetSearchTest < ActiveSupport::TestCase
setup do
Bold::current_site = @site = create :site
@asset = create :asset
end
test 'empty search should be blank' do
assert AssetSearch.new.blank?
end
test 'should search assets' do
IndexAsset.call @asset
assert s = AssetSearch.new(query: 'photo')
assert !s.blank?
assert r = s.search(@site.assets)
assert r.where(id: @asset.id).any?
assert s = AssetSearch.new(query: 'photos')
assert s.search(@site.assets).where(id:@asset.id).any?
assert s = AssetSearch.new(query: 'foobar')
assert !s.blank?
assert s.search(@site.assets).blank?
end
end
|
<?php
namespace Nooku\Library;
class CommandCallback extends ObjectMixinCallback implements CommandInterface
{
/**
* The command priority
*
* @var integer
*/
protected $_priority;
/**
* Object constructor
*
* @param ObjectConfig $config Configuration options
* @throws \<API key>
*/
public function __construct(ObjectConfig $config)
{
parent::__construct($config);
//Set the command priority
$this->_priority = $config->priority;
}
/**
* Initializes the options for the object
*
* Called from {@link __construct()} as a first step of object instantiation.
*
* @param ObjectConfig $config Configuration options
* @return void
*/
protected function _initialize(ObjectConfig $config)
{
$config->append(array(
'priority' => self::PRIORITY_NORMAL,
));
parent::_initialize($config);
}
/**
* Command handler
*
* If params are passed as a associative array or as a KConfig object they will be merged with the context of the
* command chain and passed along. If they are passed as an indexed array they will be passed to the callback
* directly.
*
* @param string $name The command name
* @param CommandContext $context The command context
* @return boolean
*/
public function execute( $name, CommandContext $context)
{
$result = true;
$callbacks = $this->getCallbacks($name);
foreach($callbacks as $key => $callback)
{
$params = $this->_params[$name][$key];
if(is_array($params) && is_numeric(key($params))) {
$result = <API key>($callback, $params);
} else {
$result = call_user_func($callback, $context->append($params));
}
//Call the callback
if ( $result === false) {
break;
}
}
return $result === false ? false : true;
}
/**
* Get the methods that are available for mixin.
*
* @param Object $mixer Mixer object
* @return array An array of methods
*/
public function getMixableMethods(ObjectMixable $mixer = null)
{
$methods = parent::getMixableMethods();
unset($methods['execute']);
unset($methods['getPriority']);
return $methods;
}
/**
* Get the priority of a behavior
*
* @return integer The command priority
*/
public function getPriority()
{
return $this->_priority;
}
}
|
<?php
// File name : tce_page_timer.php
// Begin : 2004-04-29
// Last Update : 2010-10-05
// Description : Display timer (date-time + countdown).
// Nicola Asuni
// Tecnick.com LTD
// info@tecnick.com
/**
* @file
* Display client timer (date-time + countdown).
* @package com.tecnick.tcexam.shared
* @author Nicola Asuni
* @since 2004-04-29
*/
if (!isset($_REQUEST['examtime'])) {
$examtime = 0; // remaining exam time in seconds
$enable_countdown = 'false';
$timeout_logout = 'false';
} else {
$examtime = floatval($_REQUEST['examtime']);
$enable_countdown = 'true';
if (isset($_REQUEST['timeout_logout']) AND ($_REQUEST['timeout_logout'])) {
$timeout_logout = 'true';
} else {
$timeout_logout = 'false';
}
}
echo '<form action="'.$_SERVER['SCRIPT_NAME'].'" id="timerform">'.K_NEWLINE;
echo '<div>'.K_NEWLINE;
//echo '<label for="timer" class="timerlabel">'.$l['w_time'].':</label>'.K_NEWLINE;
echo '<input type="text" name="timer" id="timer" value="" size="29" maxlength="29" title="'.$l['w_clock_timer'].'" readonly="readonly"/>'.K_NEWLINE;
echo ' </div>'.K_NEWLINE;
echo '</form>'.K_NEWLINE;
echo '<script src="'.<API key>.'timer.js" type="text/javascript"></script>'.K_NEWLINE;
echo '<script type="text/javascript">'.K_NEWLINE;
echo '//<![CDATA['.K_NEWLINE;
echo 'FJ_start_timer('.$enable_countdown.', '.(time() - $examtime).', \''.addslashes($l['m_exam_end_time']).'\', '.$timeout_logout.', '.(round(microtime(true) * 1000)).');'.K_NEWLINE;
echo '//]]>'.K_NEWLINE;
echo '</script>'.K_NEWLINE;
// END OF FILE
|
#ifndef <API key>
#define <API key>
#include <asn_application.h>
/* Including external dependencies */
#include <asn_SEQUENCE_OF.h>
#include <constr_SEQUENCE_OF.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Forward declarations */
struct <API key>;
/* <API key> */
typedef struct <API key> {
A_SEQUENCE_OF(struct <API key>) list;
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} <API key>;
/* Implementation */
extern <API key> <API key>;
extern <API key> <API key>;
extern asn_TYPE_member_t <API key>[1];
extern <API key> <API key>;
#ifdef __cplusplus
}
#endif
#endif /* <API key> */
#include <asn_internal.h>
|
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2017.11.06 at 05:19:55 PM ICT
package org.opencps.api.dossierlog.model;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"total",
"data"
})
@XmlRootElement(name = "<API key>")
public class <API key> {
protected Integer total;
protected List<DossierLogModel> data;
/**
* Gets the value of the total property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getTotal() {
return total;
}
/**
* Sets the value of the total property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setTotal(Integer value) {
this.total = value;
}
/**
* Gets the value of the data property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the data property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getData().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DossierLogModel }
*
*
*/
public List<DossierLogModel> getData() {
if (data == null) {
data = new ArrayList<DossierLogModel>();
}
return this.data;
}
}
|
<?php
namespace App\AdminBundle\Entity;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;
/**
* @ORM\Entity
* @ORM\Table(name="User")
* @ORM\Entity(repositoryClass="App\AdminBundle\Entity\UserRepository")
*/
class User
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\Column(type="string")
* @Assert\NotBlank()
*/
private $nombre;
/**
* @ORM\Column(type="string")
* @Assert\NotBlank()
*/
private $apellido;
/**
* @ORM\Column(type="string")
*/
private $sexo;
private $edad;
/**
* @ORM\Column(type="string",name="fecha_nacimiento")
*/
private $fechaNacimiento;
/**
* @ORM\Column(type="string",name="lugar_nacimiento")
*/
private $lugarNacimiento;
/**
* @ORM\Column(type="string",name="documento_id")
*/
private $documentoId;
/**
* @ORM\Column(type="string")
*/
private $departamento;
/**
* @ORM\Column(type="string")
*/
private $ciudad;
/**
* @ORM\Column(type="string")
*/
private $direccion;
private $estrato;
/**
* @ORM\Column(type="string")
*/
private $telefono;
/**
* @ORM\Column(type="string")
*/
private $correo;
/**
* @ORM\Column(type="string")
*/
private $acudiente;
/**
* @ORM\Column(type="string")
*/
private $parentesco;
/**
* @ORM\Column(type="string",name="estado_civil")
*/
private $estadoCivil;
/**
* @ORM\Column(type="integer",name="numeros_hermanos")
*/
private $numerosHermanos;
/**
* @ORM\Column(type="string",name="<API key>")
*/
private $carreraDelAspirante;
/**
* @ORM\Column(type="string",name="nombre_colegio")
*/
private $nombreColegio;
/**
* @ORM\Column(type="string",name="municipio_colegio")
*/
private $municipioColegio;
/**
* @ORM\Column(type="string",name="telefono_colegio")
*/
private $telefonoColegio;
/**
* @ORM\Column(type="string",name="<API key>")
*/
private $nombreRectorColegio;
/**
* @ORM\Column(type="string",name="fecha_graduacion")
*/
private $fechaGraduacion;
/**
* @ORM\Column(type="string",name="<API key>")
*/
private $tipoDocumentoIcfes;
/**
* @ORM\Column(type="string",name="documento_id_icfes")
*/
private $documentoIdIcfes;
/**
* @ORM\Column(type="decimal",name="promedio_icfes")
*/
private $promedioIcfes;
/**
* @ORM\Column(type="decimal",name="punt_matem_icfes")
*/
private $puntMatemIcfes;
/**
* @ORM\Column(type="decimal",name="punt_lengu_icfes")
*/
private $puntLenguIcfes;
/**
* @ORM\Column(type="decimal",name="punt_fisica_icfes")
*/
private $puntFisicaIcfes;
/**
* @ORM\Column(type="decimal",name="punt_filos_icfes")
*/
private $puntFilosIcfes;
/**
* @ORM\Column(type="decimal",name="punt_min_nucleo")
*/
private $puntMinNucleo;
/**
* @ORM\Column(type="string",name="nombre_padre")
*/
private $nombrePadre;
/**
* @ORM\Column(type="string",name="<API key>")
*/
private $estadoTrabajoPadre;
/**
* @ORM\Column(type="string",name="trabajo_padre")
*/
private $trabajoPadre;
/**
* @ORM\Column(type="string",name="ocupacion_padre")
*/
private $ocupacionPadre;
/**
* @ORM\Column(type="string",name="telefono_padre")
*/
private $telefonoPadre;
/**
* @ORM\Column(type="string",name="nombre_madre")
*/
private $nombreMadre;
/**
* @ORM\Column(type="string",name="<API key>")
*/
private $estadoTrabajoMadre;
/**
* @ORM\Column(type="string",name="trabajo_madre")
*/
private $trabajoMadre;
/**
* @ORM\Column(type="string",name="ocupacion_madre")
*/
private $ocupacionMadre;
/**
* @ORM\Column(type="string",name="telefono_madre")
*/
private $telefonoMadre;
/**
* @ORM\Column(type="string",name="estado_civil_padres")
*/
private $estadoCivilPadres;
/**
* @ORM\Column(type="string",name="<API key>")
*/
private $<API key>;
/**
* @ORM\Column(type="string",name="dirrecion_familiar")
*/
private $dirrecionFamiliar;
/**
* @ORM\Column(type="string",name="tipo_de_vivienda")
*/
private $tipoDeVivienda;
/**
* @ORM\Column(type="integer",name="<API key>")
*/
private $<API key>;
/**
* @ORM\Column(type="string",name="creado")
*/
private $creado;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set nombre
*
* @param string $nombre
*/
public function setNombre($nombre)
{
$this->nombre = $nombre;
}
/**
* Get nombre
*
* @return string
*/
public function getNombre()
{
return $this->nombre;
}
/**
* Set apellido
*
* @param string $apellido
*/
public function setApellido($apellido)
{
$this->apellido = $apellido;
}
/**
* Get apellidoe
*
* @return string
*/
public function getApellido()
{
return $this->apellido;
}
/**
* Set sexo
*
* @param string $sexo
*/
public function setSexo($sexo)
{
$this->sexo = $sexo;
}
/**
* Get sexo
*
* @return string
*/
public function getSexo()
{
return $this->sexo;
}
/**
* Set edad
*
* @param integer $edad
*/
public function setEdad($edad)
{
$this->edad = $edad;
}
/**
* Get edad
*
* @return integer
*/
public function getEdad()
{
return $this->edad;
}
/**
* Set fechaNacimiento
*
* @param string $fechaNacimiento
*/
public function setFechaNacimiento($fn)
{
$this->fechaNacimiento = $fn ;
}
/**
* Get fechaNacimiento
*
* @return string
*/
public function getFechaNacimiento()
{
return $this->fechaNacimiento;
}
/**
* Set lugarNacimiento
*
* @param string $lugarNacimiento
*/
public function setLugarNacimiento($lugarNacimiento)
{
$this->lugarNacimiento = $lugarNacimiento;
}
/**
* Get lugarNacimiento
*
* @return string
*/
public function getLugarNacimiento()
{
return $this->lugarNacimiento;
}
/**
* Set documentoId
*
* @param string $documentoId
*/
public function setDocumentoId($documentoId)
{
$this->creado = \time();
$this->documentoId = $documentoId;
}
/**
* Get documentoId
*
* @return string
*/
public function getDocumentoId()
{
return $this->documentoId;
}
/**
* Set departamento
*
* @param string $departamento
*/
public function setDepartamento($departamento)
{
$this->departamento = $departamento;
}
/**
* Get departamento
*
* @return string
*/
public function getDepartamento()
{
return $this->departamento;
}
/**
* Set ciudad
*
* @param string $ciudad
*/
public function setCiudad($ciudad)
{
$this->ciudad = $ciudad;
}
/**
* Get ciudad
*
* @return string
*/
public function getCiudad()
{
return $this->ciudad;
}
/**
* Set direccion
*
* @param string $direccion
*/
public function setDireccion($direccion)
{
$this->direccion = $direccion;
}
/**
* Get direccion
*
* @return string
*/
public function getDireccion()
{
return $this->direccion;
}
/**
* Set estrato
*
* @param string $estrato
*/
public function setEstrato($estrato)
{
$this->estrato = $estrato;
}
/**
* Get estrato
*
* @return string
*/
public function getEstrato()
{
return $this->estrato;
}
/**
* Set telefono
*
* @param string $telefono
*/
public function setTelefono($telefono)
{
$this->telefono = $telefono;
}
/**
* Get telefono
*
* @return string
*/
public function getTelefono()
{
return $this->telefono;
}
/**
* Set correo
*
* @param string $correo
*/
public function setCorreo($correo)
{
$this->correo = $correo;
}
/**
* Get correo
*
* @return string
*/
public function getCorreo()
{
return $this->correo;
}
/**
* Set acudiente
*
* @param string $acudiente
*/
public function setAcudiente($acudiente)
{
$this->acudiente = $acudiente;
}
/**
* Get acudiente
*
* @return string
*/
public function getAcudiente()
{
return $this->acudiente;
}
/**
* Set parentesco
*
* @param string $parentesco
*/
public function setParentesco($parentesco)
{
$this->parentesco = $parentesco;
}
/**
* Get parentesco
*
* @return string
*/
public function getParentesco()
{
return $this->parentesco;
}
/**
* Set estadoCivil
*
* @param string $estadoCivil
*/
public function setEstadoCivil($estadoCivil)
{
$this->estadoCivil = $estadoCivil;
}
/**
* Get estadoCivil
*
* @return string
*/
public function getEstadoCivil()
{
return $this->estadoCivil;
}
/**
* Set numerosHermanos
*
* @param integer $numerosHermanos
*/
public function setNumerosHermanos($numerosHermanos)
{
$this->numerosHermanos = $numerosHermanos;
}
/**
* Get numerosHermanos
*
* @return integer
*/
public function getNumerosHermanos()
{
return $this->numerosHermanos;
}
/**
* Set carreraDelAspirante
*
* @param integer $carreraDelAspirante
*/
public function <API key>($carreraDelAspirante)
{
$this->carreraDelAspirante = $carreraDelAspirante;
}
/**
* Get carreraDelAspirante
*
* @return integer
*/
public function <API key>()
{
return $this->carreraDelAspirante;
}
/**
* Set nombreColegio
*
* @param string $nombreColegio
*/
public function setNombreColegio($nombreColegio)
{
$this->nombreColegio = $nombreColegio;
}
/**
* Get nombreColegio
*
* @return string
*/
public function getNombreColegio()
{
return $this->nombreColegio;
}
/**
* Set municipioColegio
*
* @param string $municipioColegio
*/
public function setMunicipioColegio($municipioColegio)
{
$this->municipioColegio = $municipioColegio;
}
/**
* Get municipioColegio
*
* @return string
*/
public function getMunicipioColegio()
{
return $this->municipioColegio;
}
/**
* Set telefonoColegio
*
* @param string $telefonoColegio
*/
public function setTelefonoColegio($telefonoColegio)
{
$this->telefonoColegio = $telefonoColegio;
}
/**
* Get telefonoColegio
*
* @return string
*/
public function getTelefonoColegio()
{
return $this->telefonoColegio;
}
/**
* Set nombreRectorColegio
*
* @param string $nombreRectorColegio
*/
public function <API key>($nombreRectorColegio)
{
$this->nombreRectorColegio = $nombreRectorColegio;
}
/**
* Get nombreRectorColegio
*
* @return string
*/
public function <API key>()
{
return $this->nombreRectorColegio;
}
/**
* Set fechaGraduacion
*
* @param string $fechaGraduacion
*/
public function setFechaGraduacion($fechaGraduacion)
{
$this->fechaGraduacion = $fechaGraduacion;
}
/**
* Get fechaGraduacion
*
* @return string
*/
public function getFechaGraduacion()
{
return $this->fechaGraduacion;
}
/**
* Set tipoDocumentoIcfes
*
* @param string $tipoDocumentoIcfes
*/
public function <API key>($tipoDocumentoIcfes)
{
$this->tipoDocumentoIcfes = $tipoDocumentoIcfes;
}
/**
* Get tipoDocumentoIcfes
*
* @return string
*/
public function <API key>()
{
return $this->tipoDocumentoIcfes;
}
/**
* Set documentoIdIcfes
*
* @param string $documentoIdIcfes
*/
public function setDocumentoIdIcfes($documentoIdIcfes)
{
$this->documentoIdIcfes = $documentoIdIcfes;
}
/**
* Get documentoIdIcfess
*
* @return string
*/
public function getDocumentoIdIcfes()
{
return $this->documentoIdIcfes;
}
/**
* Set promedioIcfes
*
* @param decimal $promedioIcfes
*/
public function setPromedioIcfes($promedioIcfes)
{
$this->promedioIcfes = $promedioIcfes;
}
/**
* Get promedioIcfes
*
* @return decimal
*/
public function getPromedioIcfes()
{
return $this->promedioIcfes;
}
/**
* Set puntMatemIcfes
*
* @param decimal $puntMatemIcfes
*/
public function setPuntMatemIcfes($puntMatemIcfes)
{
$this->puntMatemIcfes = $puntMatemIcfes;
}
/**
* Get puntMatemIcfes
*
* @return decimal
*/
public function getPuntMatemIcfes()
{
return $this->puntMatemIcfes;
}
/**
* Set puntLenguIcfes
*
* @param decimal $puntLenguIcfes
*/
public function setPuntLenguIcfes($puntLenguIcfes)
{
$this->puntLenguIcfes = $puntLenguIcfes;
}
/**
* Get puntLenguIcfes
*
* @return decimal
*/
public function getPuntLenguIcfes()
{
return $this->puntLenguIcfes;
}
/**
* Set puntFisicaIcfes
*
* @param decimal $puntFisicaIcfes
*/
public function setPuntFisicaIcfes($puntFisicaIcfes)
{
$this->puntFisicaIcfes = $puntFisicaIcfes;
}
/**
* Get puntFisicaIcfes
*
* @return decimal
*/
public function getPuntFisicaIcfes()
{
return $this->puntFisicaIcfes;
}
/**
* Set puntFilosIcfes
*
* @param decimal $puntFilosIcfes
*/
public function setPuntFilosIcfes($puntFilosIcfes)
{
$this->puntFilosIcfes = $puntFilosIcfes;
}
/**
* Get puntFilosIcfes
*
* @return decimal
*/
public function getPuntFilosIcfes()
{
return $this->puntFilosIcfes;
}
/**
* Set puntMinNucleo
*
* @param decimal $puntMinNucleo
*/
public function setPuntMinNucleo($puntMinNucleo)
{
$this->puntMinNucleo = $puntMinNucleo;
}
/**
* Get puntMinNucleo
*
* @return decimal
*/
public function getPuntMinNucleo()
{
return $this->puntMinNucleo;
}
/**
* Set nombrePadre
*
* @param string $nombrePadre
*/
public function setNombrePadre($nombrePadre)
{
$this->nombrePadre = $nombrePadre;
}
/**
* Get nombrePadre
*
* @return string
*/
public function getNombrePadre()
{
return $this->nombrePadre;
}
/**
* Set estadoTrabajoPadre
*
* @param string $estadoTrabajoPadre
*/
public function <API key>($estadoTrabajoPadre)
{
$this->estadoTrabajoPadre = $estadoTrabajoPadre;
}
/**
* Get estadoTrabajoPadre
*
* @return string
*/
public function <API key>()
{
return $this->estadoTrabajoPadre;
}
/**
* Set trabajoPadre
*
* @param string $trabajoPadre
*/
public function setTrabajoPadre($trabajoPadre)
{
$this->trabajoPadre = $trabajoPadre;
}
/**
* Get trabajoPadre
*
* @return string
*/
public function getTrabajoPadre()
{
return $this->trabajoPadre;
}
/**
* Set ocupacionPadre
*
* @param string $ocupacionPadre
*/
public function setOcupacionPadre($ocupacionPadre)
{
$this->ocupacionPadre = $ocupacionPadre;
}
/**
* Get ocupacionPadre
*
* @return string
*/
public function getOcupacionPadre()
{
return $this->ocupacionPadre;
}
/**
* Set telefonoPadre
*
* @param string $telefonoPadre
*/
public function setTelefonoPadre($telefonoPadre)
{
$this->telefonoPadre = $telefonoPadre;
}
/**
* Get telefonoPadre
*
* @return string
*/
public function getTelefonoPadre()
{
return $this->telefonoPadre;
}
/**
* Set nombreMadre
*
* @param string $nombreMadre
*/
public function setNombreMadre($nombreMadre)
{
$this->nombreMadre = $nombreMadre;
}
/**
* Get nombreMadre
*
* @return string
*/
public function getNombreMadre()
{
return $this->nombreMadre;
}
/**
* Set estadoTrabajoMadre
*
* @param string $estadoTrabajoMadre
*/
public function <API key>($estadoTrabajoMadre)
{
$this->estadoTrabajoMadre = $estadoTrabajoMadre;
}
/**
* Get estadoTrabajoMadre
*
* @return string
*/
public function <API key>()
{
return $this->estadoTrabajoMadre;
}
/**
* Set trabajoMadre
*
* @param string $trabajoMadre
*/
public function setTrabajoMadre($trabajoMadre)
{
$this->trabajoMadre = $trabajoMadre;
}
/**
* Get trabajoMadre
*
* @return string
*/
public function getTrabajoMadre()
{
return $this->trabajoMadre;
}
/**
* Set ocupacionMadre
*
* @param string $ocupacionMadre
*/
public function setOcupacionMadre($ocupacionMadre)
{
$this->ocupacionMadre = $ocupacionMadre;
}
/**
* Get ocupacionMadre
*
* @return string
*/
public function getOcupacionMadre()
{
return $this->ocupacionMadre;
}
/**
* Set telefonoMadre
*
* @param integer $telefonoMadre
*/
public function setTelefonoMadre($telefonoMadre)
{
$this->telefonoMadre = $telefonoMadre;
}
/**
* Get telefonoMadre
*
* @return integer
*/
public function getTelefonoMadre()
{
return $this->telefonoMadre;
}
/**
* Set estadoCivilPadres
*
* @param string $estadoCivilPadres
*/
public function <API key>($estadoCivilPadres)
{
$this->estadoCivilPadres = $estadoCivilPadres;
}
/**
* Get estadoCivilPadres
*
* @return string
*/
public function <API key>()
{
return $this->estadoCivilPadres;
}
/**
* Set <API key>
*
* @param string $<API key>
*/
public function <API key>($<API key>)
{
$this-><API key> = $<API key>;
}
/**
* Get <API key>
*
* @return string
*/
public function <API key>()
{
return $this-><API key>;
}
/**
* Set dirrecionFamiliar
*
* @param string $dirrecionFamiliar
*/
public function <API key>($dirrecionFamiliar)
{
$this->dirrecionFamiliar = $dirrecionFamiliar;
}
/**
* Get dirrecionFamiliar
*
* @return string
*/
public function <API key>()
{
return $this->dirrecionFamiliar;
}
/**
* Set tipoDeVivienda
*
* @param string $tipoDeVivienda
*/
public function setTipoDeVivienda($tipoDeVivienda)
{
$this->tipoDeVivienda = $tipoDeVivienda;
}
/**
* Get tipoDeVivienda
*
* @return string
*/
public function getTipoDeVivienda()
{
return $this->tipoDeVivienda;
}
/**
* Set <API key>
*
* @param integer $<API key>
*/
public function <API key>($<API key>)
{
$this-><API key> = $<API key>;
}
/**
* Get <API key>
*
* @return integer
*/
public function <API key>()
{
return $this-><API key>;
}
}
|
import factory
from .models import User
USER_PASSWORD = "2fast2furious"
class UserFactory(factory.DjangoModelFactory):
name = "John Doe"
email = factory.Sequence(lambda n: "john{}@example.com".format(n))
password = factory.<API key>('set_password', USER_PASSWORD)
gender = "male"
class Meta:
model = User
|
// generator: ilarkesto.mda.legacy.generator.DaoGenerator
package scrum.server.admin;
import java.util.*;
import ilarkesto.persistence.*;
import ilarkesto.core.logging.Log;
import ilarkesto.base.*;
import ilarkesto.base.time.*;
import ilarkesto.auth.*;
import ilarkesto.fp.*;
public abstract class GUserDao
extends ilarkesto.auth.AUserDao<User> {
public final String getEntityName() {
return User.TYPE;
}
public final Class getEntityClass() {
return User.class;
}
public Set<User> <API key>(final scrum.server.admin.User user) {
return getEntities(new Predicate<User>() {
public boolean test(User e) {
return Auth.isVisible(e, user);
}
});
}
public void clearCaches() {
namesCache = null;
usersByAdminCache.clear();
<API key>.clear();
emailsCache = null;
<API key>.clear();
<API key> = null;
usersByColorCache.clear();
colorsCache = null;
<API key>.clear();
<API key> = null;
<API key>.clear();
<API key> = null;
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
<API key>.clear();
loginTokensCache = null;
openIdsCache = null;
}
@Override
public void entityDeleted(EntityEvent event) {
super.entityDeleted(event);
if (event.getEntity() instanceof User) {
clearCaches();
}
}
@Override
public void entitySaved(EntityEvent event) {
super.entitySaved(event);
if (event.getEntity() instanceof User) {
clearCaches();
}
}
// - name
public final User getUserByName(java.lang.String name) {
return getEntity(new IsName(name));
}
private Set<java.lang.String> namesCache;
public final Set<java.lang.String> getNames() {
if (namesCache == null) {
namesCache = new HashSet<java.lang.String>();
for (User e : getEntities()) {
if (e.isNameSet()) namesCache.add(e.getName());
}
}
return namesCache;
}
private static class IsName implements Predicate<User> {
private java.lang.String value;
public IsName(java.lang.String value) {
this.value = value;
}
public boolean test(User e) {
return e.isName(value);
}
}
// - admin
private final Cache<Boolean,Set<User>> usersByAdminCache = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean admin) {
return getEntities(new IsAdmin(admin));
}
});
public final Set<User> getUsersByAdmin(boolean admin) {
return usersByAdminCache.get(admin);
}
private static class IsAdmin implements Predicate<User> {
private boolean value;
public IsAdmin(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.isAdmin();
}
}
// - emailVerified
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean emailVerified) {
return getEntities(new IsEmailVerified(emailVerified));
}
});
public final Set<User> <API key>(boolean emailVerified) {
return <API key>.get(emailVerified);
}
private static class IsEmailVerified implements Predicate<User> {
private boolean value;
public IsEmailVerified(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.isEmailVerified();
}
}
// - email
public final User getUserByEmail(java.lang.String email) {
return getEntity(new IsEmail(email));
}
private Set<java.lang.String> emailsCache;
public final Set<java.lang.String> getEmails() {
if (emailsCache == null) {
emailsCache = new HashSet<java.lang.String>();
for (User e : getEntities()) {
if (e.isEmailSet()) emailsCache.add(e.getEmail());
}
}
return emailsCache;
}
private static class IsEmail implements Predicate<User> {
private java.lang.String value;
public IsEmail(java.lang.String value) {
this.value = value;
}
public boolean test(User e) {
return e.isEmail(value);
}
}
// - currentProject
private final Cache<scrum.server.project.Project,Set<User>> <API key> = new Cache<scrum.server.project.Project,Set<User>>(
new Cache.Factory<scrum.server.project.Project,Set<User>>() {
public Set<User> create(scrum.server.project.Project currentProject) {
return getEntities(new IsCurrentProject(currentProject));
}
});
public final Set<User> <API key>(scrum.server.project.Project currentProject) {
return <API key>.get(currentProject);
}
private Set<scrum.server.project.Project> <API key>;
public final Set<scrum.server.project.Project> getCurrentProjects() {
if (<API key> == null) {
<API key> = new HashSet<scrum.server.project.Project>();
for (User e : getEntities()) {
if (e.isCurrentProjectSet()) <API key>.add(e.getCurrentProject());
}
}
return <API key>;
}
private static class IsCurrentProject implements Predicate<User> {
private scrum.server.project.Project value;
public IsCurrentProject(scrum.server.project.Project value) {
this.value = value;
}
public boolean test(User e) {
return e.isCurrentProject(value);
}
}
// - color
private final Cache<java.lang.String,Set<User>> usersByColorCache = new Cache<java.lang.String,Set<User>>(
new Cache.Factory<java.lang.String,Set<User>>() {
public Set<User> create(java.lang.String color) {
return getEntities(new IsColor(color));
}
});
public final Set<User> getUsersByColor(java.lang.String color) {
return usersByColorCache.get(color);
}
private Set<java.lang.String> colorsCache;
public final Set<java.lang.String> getColors() {
if (colorsCache == null) {
colorsCache = new HashSet<java.lang.String>();
for (User e : getEntities()) {
if (e.isColorSet()) colorsCache.add(e.getColor());
}
}
return colorsCache;
}
private static class IsColor implements Predicate<User> {
private java.lang.String value;
public IsColor(java.lang.String value) {
this.value = value;
}
public boolean test(User e) {
return e.isColor(value);
}
}
// - <API key>
private final Cache<ilarkesto.base.time.DateAndTime,Set<User>> <API key> = new Cache<ilarkesto.base.time.DateAndTime,Set<User>>(
new Cache.Factory<ilarkesto.base.time.DateAndTime,Set<User>>() {
public Set<User> create(ilarkesto.base.time.DateAndTime <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(ilarkesto.base.time.DateAndTime <API key>) {
return <API key>.get(<API key>);
}
private Set<ilarkesto.base.time.DateAndTime> <API key>;
public final Set<ilarkesto.base.time.DateAndTime> <API key>() {
if (<API key> == null) {
<API key> = new HashSet<ilarkesto.base.time.DateAndTime>();
for (User e : getEntities()) {
if (e.<API key>()) <API key>.add(e.<API key>());
}
}
return <API key>;
}
private static class <API key> implements Predicate<User> {
private ilarkesto.base.time.DateAndTime value;
public <API key>(ilarkesto.base.time.DateAndTime value) {
this.value = value;
}
public boolean test(User e) {
return e.<API key>(value);
}
}
// - <API key>
private final Cache<ilarkesto.base.time.DateAndTime,Set<User>> <API key> = new Cache<ilarkesto.base.time.DateAndTime,Set<User>>(
new Cache.Factory<ilarkesto.base.time.DateAndTime,Set<User>>() {
public Set<User> create(ilarkesto.base.time.DateAndTime <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(ilarkesto.base.time.DateAndTime <API key>) {
return <API key>.get(<API key>);
}
private Set<ilarkesto.base.time.DateAndTime> <API key>;
public final Set<ilarkesto.base.time.DateAndTime> <API key>() {
if (<API key> == null) {
<API key> = new HashSet<ilarkesto.base.time.DateAndTime>();
for (User e : getEntities()) {
if (e.<API key>()) <API key>.add(e.<API key>());
}
}
return <API key>;
}
private static class <API key> implements Predicate<User> {
private ilarkesto.base.time.DateAndTime value;
public <API key>(ilarkesto.base.time.DateAndTime value) {
this.value = value;
}
public boolean test(User e) {
return e.<API key>(value);
}
}
// - disabled
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean disabled) {
return getEntities(new IsDisabled(disabled));
}
});
public final Set<User> getUsersByDisabled(boolean disabled) {
return <API key>.get(disabled);
}
private static class IsDisabled implements Predicate<User> {
private boolean value;
public IsDisabled(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.isDisabled();
}
}
// - hideUserGuideBlog
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean hideUserGuideBlog) {
return getEntities(new IsHideUserGuideBlog(hideUserGuideBlog));
}
});
public final Set<User> <API key>(boolean hideUserGuideBlog) {
return <API key>.get(hideUserGuideBlog);
}
private static class IsHideUserGuideBlog implements Predicate<User> {
private boolean value;
public IsHideUserGuideBlog(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.isHideUserGuideBlog();
}
}
// - <API key>
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(boolean <API key>) {
return <API key>.get(<API key>);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - hideUserGuideFiles
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean hideUserGuideFiles) {
return getEntities(new <API key>(hideUserGuideFiles));
}
});
public final Set<User> <API key>(boolean hideUserGuideFiles) {
return <API key>.get(hideUserGuideFiles);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - hideUserGuideForum
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean hideUserGuideForum) {
return getEntities(new <API key>(hideUserGuideForum));
}
});
public final Set<User> <API key>(boolean hideUserGuideForum) {
return <API key>.get(hideUserGuideForum);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - <API key>
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(boolean <API key>) {
return <API key>.get(<API key>);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - hideUserGuideIssues
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean hideUserGuideIssues) {
return getEntities(new <API key>(hideUserGuideIssues));
}
});
public final Set<User> <API key>(boolean hideUserGuideIssues) {
return <API key>.get(hideUserGuideIssues);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - <API key>
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(boolean <API key>) {
return <API key>.get(<API key>);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - <API key>
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(boolean <API key>) {
return <API key>.get(<API key>);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - <API key>
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(boolean <API key>) {
return <API key>.get(<API key>);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - <API key>
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(boolean <API key>) {
return <API key>.get(<API key>);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - <API key>
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(boolean <API key>) {
return <API key>.get(<API key>);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - <API key>
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(boolean <API key>) {
return <API key>.get(<API key>);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - hideUserGuideRisks
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean hideUserGuideRisks) {
return getEntities(new <API key>(hideUserGuideRisks));
}
});
public final Set<User> <API key>(boolean hideUserGuideRisks) {
return <API key>.get(hideUserGuideRisks);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - <API key>
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(boolean <API key>) {
return <API key>.get(<API key>);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - <API key>
private final Cache<Boolean,Set<User>> <API key> = new Cache<Boolean,Set<User>>(
new Cache.Factory<Boolean,Set<User>>() {
public Set<User> create(Boolean <API key>) {
return getEntities(new <API key>(<API key>));
}
});
public final Set<User> <API key>(boolean <API key>) {
return <API key>.get(<API key>);
}
private static class <API key> implements Predicate<User> {
private boolean value;
public <API key>(boolean value) {
this.value = value;
}
public boolean test(User e) {
return value == e.<API key>();
}
}
// - loginToken
public final User getUserByLoginToken(java.lang.String loginToken) {
return getEntity(new IsLoginToken(loginToken));
}
private Set<java.lang.String> loginTokensCache;
public final Set<java.lang.String> getLoginTokens() {
if (loginTokensCache == null) {
loginTokensCache = new HashSet<java.lang.String>();
for (User e : getEntities()) {
if (e.isLoginTokenSet()) loginTokensCache.add(e.getLoginToken());
}
}
return loginTokensCache;
}
private static class IsLoginToken implements Predicate<User> {
private java.lang.String value;
public IsLoginToken(java.lang.String value) {
this.value = value;
}
public boolean test(User e) {
return e.isLoginToken(value);
}
}
// - openId
public final User getUserByOpenId(java.lang.String openId) {
return getEntity(new IsOpenId(openId));
}
private Set<java.lang.String> openIdsCache;
public final Set<java.lang.String> getOpenIds() {
if (openIdsCache == null) {
openIdsCache = new HashSet<java.lang.String>();
for (User e : getEntities()) {
if (e.isOpenIdSet()) openIdsCache.add(e.getOpenId());
}
}
return openIdsCache;
}
private static class IsOpenId implements Predicate<User> {
private java.lang.String value;
public IsOpenId(java.lang.String value) {
this.value = value;
}
public boolean test(User e) {
return e.isOpenId(value);
}
}
@Override
protected Set<Class> <API key>() {
Set<Class> ret = new HashSet<Class>(super.<API key>());
return ret;
}
@Override
public Map<String, Class> getAliases() {
Map<String, Class> aliases = new HashMap<String, Class>(super.getAliases());
return aliases;
}
scrum.server.project.ProjectDao projectDao;
public void setProjectDao(scrum.server.project.ProjectDao projectDao) {
this.projectDao = projectDao;
}
}
|
<ol class="breadcrumb">
<li>Outil de publication</li>
<li><a ui-sref="root.account.organizations">Sélection de l'organisation</a></li>
<li><a ui-sref="root.account.organization.index({ organizationId: currentOrganization._id })">{{ currentOrganization.name }}</a></li>
<li class="active">Sélection du catalogue source</li>
</ol>
<div ng-if="currentOrganization.sourceCatalog.length" class="alert alert-info">
Actuellement votre organisation est configurée avec le catalogue <strong>{{ selectedCatalog().name }}</strong>.
</div>
<!-- Catalog -->
<div class="panel panel-primary">
<div class="panel-heading">
<h2 class="panel-title"><i class="fa fa-book"></i> Catalogue source</h2>
</div>
<div class="panel-body">
Choisissez le catalogue à partir duquel vous souhaitez importer les jeux de données :
</div>
<div class="list-group">
<a href class="list-group-item" ng-click="selectCatalog(catalog)" ng-repeat="catalog in catalogs | orderBy:'name'">{{ catalog.name }}</a>
</div>
</div>
|
package com.rapidminer.operator;
/**
* These listeners will be notified after a new operator was added to a chain.
*
* @author Ingo Mierswa
*/
public interface AddListener {
public void operatorAdded(Operator newChild);
}
|
package info.nightscout.androidaps.plugins.SmsCommunicator;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.squareup.otto.Subscribe;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Collections;
import java.util.Comparator;
import info.nightscout.androidaps.MainApp;
import info.nightscout.androidaps.R;
import info.nightscout.androidaps.plugins.Common.SubscriberFragment;
import info.nightscout.androidaps.plugins.SmsCommunicator.events.<API key>;
import info.nightscout.utils.DateUtil;
/**
* A simple {@link Fragment} subclass.
*/
public class <API key> extends SubscriberFragment {
private static Logger log = LoggerFactory.getLogger(<API key>.class);
private static <API key> <API key>;
public static <API key> getPlugin() {
if(<API key>==null){
<API key> = new <API key>();
}
return <API key>;
}
TextView logView;
public <API key>() {
super();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.<API key>, container, false);
logView = (TextView) view.findViewById(R.id.smscommunicator_log);
updateGUI();
return view;
}
@Subscribe
public void onStatusEvent(final <API key> ev) {
updateGUI();
}
@Override
protected void updateGUI() {
Activity activity = getActivity();
if (activity != null)
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
class CustomComparator implements Comparator<<API key>.Sms> {
public int compare(<API key>.Sms object1, <API key>.Sms object2) {
return (int) (object1.date.getTime() - object2.date.getTime());
}
}
Collections.sort(getPlugin().messages, new CustomComparator());
int messagesToShow = 40;
int start = Math.max(0, getPlugin().messages.size() - messagesToShow);
String logText = "";
for (int x = start; x < getPlugin().messages.size(); x++) {
<API key>.Sms sms = getPlugin().messages.get(x);
if (sms.received) {
logText += DateUtil.timeString(sms.date) + " <<< " + (sms.processed ? " " : " ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>";
} else if (sms.sent) {
logText += DateUtil.timeString(sms.date) + " >>> " + (sms.processed ? " " : " ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>";
}
}
logView.setText(Html.fromHtml(logText));
}
});
}
}
|
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<title>ByteJudge</title>
</head>
<body>
<div id="wrapper">
<?php
require('./scripts/<API key>.php');
if(!(isloggedin("admin")==true))
{
header('Location: ./home.php');
}
else
{
include("./includes/header.php");
include("includes/nav.php");
echo '
<div id="content">
';
include("./includes/<API key>.php");
echo '
</div> <!-- end #content -->
';
include("./includes/sidebar.php");
include("./includes/footer.php");
}
?>
</div> <!-- End #wrapper -->
</body>
</html>
|
_id: <API key>
date_posted: '2018-02-24'
layout: post
full_name: John
poster_email: Johnlaufman@gmail.com
business_name: Bakery
business_url: ''
location: North Lamar
title: Comment
category: management
description: >-
We are looking for an experienced pastry manager with a background in high
volume baking and management experience.
qualifications: >-
Extensive knowledge of baking and pastries is a must. Experience managing 10+
employees. Knowledge of P&L's, inventory , gross profit reports, etc. and a
serious passion for food.
job_type: full_time
hours: 5am to 3pm
start: ASAP
compensation: Salary
how_to_apply: >-
Please contact my personal email (johnlaufman@gmail.com) to discuss
application process.
date: '2018-02-24T19:04:15.083Z'
approved: false
|
package org.openehr.adl.am.mixin;
import com.google.common.collect.ImmutableMap;
import org.openehr.jaxb.am.CAttribute;
import org.openehr.jaxb.am.Cardinality;
import org.openehr.jaxb.rm.*;
import java.lang.reflect.Constructor;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* @author markopi
*/
class AmMixinsInternal {
private static final Map<Class<?>, Class<? extends AmMixin>> configuration;
private static final Map<Class<?>, Constructor<? extends AmMixin>> constructors;
static {
Map<Class<?>, Class<? extends AmMixin>> conf = ImmutableMap.<Class<?>, Class<? extends AmMixin>>builder()
.put(IntervalOfDate.class, IntervalOfDateMixin.class)
.put(IntervalOfTime.class, IntervalOfTimeMixin.class)
.put(IntervalOfDateTime.class, <API key>.class)
.put(IntervalOfInteger.class, <API key>.class)
.put(IntervalOfReal.class, IntervalOfRealMixin.class)
.put(<API key>.class, <API key>.class)
.put(CAttribute.class, CAttributeMixin.class)
.put(IntervalOfDuration.class, <API key>.class)
.put(Cardinality.class, CardinalityMixin.class)
.build();
configuration = ImmutableMap.copyOf(conf);
constructors = new ConcurrentHashMap<>();
}
static <T, M extends AmMixin<?>> M create(T from) {
Constructor<? extends AmMixin> mixinConstructor = getMixinClass(from.getClass());
try {
return (M) mixinConstructor.newInstance(from);
} catch (<API key> e) {
throw new <API key>(
"Error constructing mixin class " + mixinConstructor.getDeclaringClass() + " for class " + from.getClass());
}
}
private static Constructor<? extends AmMixin> getMixinClass(Class<?> fromClass) {
Constructor<? extends AmMixin> result = constructors.get(fromClass);
if (result == null) {
Class<?> cls = fromClass;
while (cls != null) {
Class<? extends AmMixin> mixinClass = configuration.get(cls);
if (mixinClass != null) {
try {
result = mixinClass.getConstructor(fromClass);
} catch (<API key> e) {
throw new <API key>(
"Missing mixin " + mixinClass.getName() + " constructor for " + fromClass.getName());
}
constructors.put(fromClass, result);
return result;
}
cls = cls.getSuperclass();
}
throw new <API key>("No mixin defined for class " + fromClass);
}
return result;
}
}
|
/* the style of the div around each node */
.ygtvitem {
}
table.ygtvtable {
margin-bottom: 0;
border: none;
border-collapse: collapse;
}
/*.ygtvitem td {*/
td.ygtvcell {
border: none;
padding: 0;
}
a.ygtvspacer {
text-decoration: none;
outline-style: none;
display: block;
}
/* first or middle sibling, no children */
.ygtvtn {
width: 18px;
height: 22px;
background: url(treeview-sprite.gif) 0 -5600px no-repeat;
cursor: pointer;
}
/* first or middle sibling, collapsable */
.ygtvtm {
width: 18px;
height: 22px;
cursor: pointer;
background: url(treeview-sprite.gif) 0 -4000px no-repeat;
}
/* first or middle sibling, collapsable, hover */
.ygtvtmh, .ygtvtmhh {
width: 18px;
height: 22px;
cursor: pointer;
background: url(treeview-sprite.gif) 0 -4800px no-repeat;
}
/* first or middle sibling, expandable */
.ygtvtp {
width: 18px;
height: 22px;
cursor: pointer;
background: url(treeview-sprite.gif) 0 -6400px no-repeat;
}
/* first or middle sibling, expandable, hover */
.ygtvtph, .ygtvtphh {
width: 18px;
height: 22px;
cursor: pointer;
background: url(treeview-sprite.gif) 0 -7200px no-repeat;
}
/* last sibling, no children */
.ygtvln {
width: 18px;
height: 22px;
background: url(treeview-sprite.gif) 0 -1600px no-repeat;
cursor: pointer;
}
/* Last sibling, collapsable */
.ygtvlm {
width: 18px;
height: 22px;
cursor: pointer;
background: url(treeview-sprite.gif) 0 0px no-repeat;
}
/* Last sibling, collapsable, hover */
.ygtvlmh, .ygtvlmhh {
width: 18px;
height: 22px;
cursor: pointer;
background: url(treeview-sprite.gif) 0 -800px no-repeat;
}
/* Last sibling, expandable */
.ygtvlp {
width: 18px;
height: 22px;
cursor: pointer;
background: url(treeview-sprite.gif) 0 -2400px no-repeat;
}
/* Last sibling, expandable, hover */
.ygtvlph, .ygtvlphh {
width: 18px;
height: 22px;
cursor: pointer;
background: url(treeview-sprite.gif) 0 -3200px no-repeat;
cursor: pointer;
}
/* Loading icon */
.ygtvloading {
width: 18px;
height: 22px;
background: url(treeview-loading.gif) 0 0 no-repeat;
}
/* the style for the empty cells that are used for rendering the depth
* of the node */
.ygtvdepthcell {
width: 18px;
height: 22px;
background: url(treeview-sprite.gif) 0 -8000px no-repeat;
}
.ygtvblankdepthcell {
width: 18px;
height: 22px;
}
/* the style of the div around each node's collection of children */
.ygtvchildren {
}
* html .ygtvchildren {
height: 2%;
}
/* the style of the text label in ygTextNode */
.ygtvlabel, .ygtvlabel:link, .ygtvlabel:visited, .ygtvlabel:hover {
margin-left: 2px;
text-decoration: none;
background-color: white; /* workaround for IE font smoothing bug */
cursor: pointer;
}
.ygtvcontent {
cursor: default;
}
.ygtvspacer {
height: 22px;
width: 18px;
}
.ygtvfocus {
background-color: #c0e0e0;
border: none;
}
.ygtvfocus .ygtvlabel, .ygtvfocus .ygtvlabel:link, .ygtvfocus .ygtvlabel:visited, .ygtvfocus .ygtvlabel:hover {
background-color: #c0e0e0;
}
.ygtvfocus a {
outline-style: none;
}
.ygtvok {
width: 18px;
height: 22px;
background: url(treeview-sprite.gif) 0 -8800px no-repeat;
}
.ygtvok:hover {
background: url(treeview-sprite.gif) 0 -8844px no-repeat;
}
.ygtvcancel {
width: 18px;
height: 22px;
background: url(treeview-sprite.gif) 0 -8822px no-repeat;
}
.ygtvcancel:hover {
background: url(treeview-sprite.gif) 0 -8866px no-repeat;
}
.ygtv-label-editor {
background-color: #f2f2f2;
border: 1px solid silver;
position: absolute;
display: none;
overflow: hidden;
margin: auto;
z-index: 9000;
}
.ygtv-edit-TextNode {
width: 190px;
}
.ygtv-edit-TextNode .ygtvcancel, .ygtv-edit-TextNode .ygtvok {
border: none;
}
.ygtv-edit-TextNode .<API key> {
float: right;
}
.ygtv-edit-TextNode .ygtv-input input {
width: 140px;
}
.ygtv-edit-DateNode .ygtvcancel {
border: none;
}
.ygtv-edit-DateNode .ygtvok {
display: none;
}
.ygtv-edit-DateNode .<API key> {
text-align: right;
margin: auto;
}
.ygtv-highlight .ygtv-highlight0, .ygtv-highlight .ygtv-highlight0 .ygtvlabel {
}
.ygtv-highlight .ygtv-highlight1, .ygtv-highlight .ygtv-highlight1 .ygtvlabel {
background-color: blue;
color: white;
}
.ygtv-highlight .ygtv-highlight2, .ygtv-highlight .ygtv-highlight2 .ygtvlabel {
background-color: silver;
}
.ygtv-highlight .ygtv-highlight0 .ygtvfocus .ygtvlabel,
.ygtv-highlight .ygtv-highlight1 .ygtvfocus .ygtvlabel,
.ygtv-highlight .ygtv-highlight2 .ygtvfocus .ygtvlabel {
background-color: #c0e0e0;
}
.ygtv-highlight .ygtvcontent {
padding-right: 1em;
}
.ygtv-checkbox .ygtv-highlight0 .ygtvcontent {
padding-left: 1em;
background: url(check0.gif) no-repeat;
}
.ygtv-checkbox .ygtv-highlight0 .ygtvfocus.ygtvcontent,
.ygtv-checkbox .ygtv-highlight1 .ygtvfocus.ygtvcontent,
.ygtv-checkbox .ygtv-highlight2 .ygtvfocus.ygtvcontent {
background-color: #c0e0e0;
}
.ygtv-checkbox .ygtv-highlight1 .ygtvcontent {
padding-left: 1em;
background: url(check1.gif) no-repeat;
}
.ygtv-checkbox .ygtv-highlight2 .ygtvcontent {
padding-left: 1em;
background: url(check2.gif) no-repeat;
}
|
package com.esofthead.mycollab.schedule.email.project.service
import com.esofthead.mycollab.common.domain.<API key>
import com.esofthead.mycollab.common.i18n.GenericI18Enum
import com.esofthead.mycollab.common.{<API key>, NotificationType}
import com.esofthead.mycollab.core.utils.StringUtils
import com.esofthead.mycollab.html.FormatUtils._
import com.esofthead.mycollab.html.LinkUtils
import com.esofthead.mycollab.module.mail.MailUtils
import com.esofthead.mycollab.module.project.domain._
import com.esofthead.mycollab.module.project.i18n.{BugI18nEnum, OptionI18nEnum}
import com.esofthead.mycollab.module.project.service.{MilestoneService, <API key>, <API key>, ProjectService}
import com.esofthead.mycollab.module.project.{<API key>, ProjectResources, <API key>}
import com.esofthead.mycollab.module.tracker.domain.{BugWithBLOBs, SimpleBug}
import com.esofthead.mycollab.module.tracker.service.BugService
import com.esofthead.mycollab.module.user.<API key>
import com.esofthead.mycollab.module.user.domain.SimpleUser
import com.esofthead.mycollab.module.user.service.UserService
import com.esofthead.mycollab.schedule.email.format._
import com.esofthead.mycollab.schedule.email.project.<API key>
import com.esofthead.mycollab.schedule.email.{ItemFieldMapper, MailContext}
import com.esofthead.mycollab.spring.<API key>
import com.hp.gagawa.java.elements.{A, Img, Span, Text}
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component
/**
* @author MyCollab Ltd.
* @since 4.6.0
*/
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
class <API key> extends <API key>[SimpleBug] with <API key> {
private val LOG = LoggerFactory.getLogger(classOf[<API key>])
@Autowired var bugService: BugService = _
@Autowired var <API key>: <API key> = _
@Autowired var <API key>: <API key> = _
private val mapper = new BugFieldNameMapper
protected def <API key>(context: MailContext[SimpleBug]) {
val currentProject = new WebItem(bean.getProjectname, <API key>.<API key>(siteUrl, bean.getProjectid))
val emailNotification: <API key> = context.<API key>
val summary = "#" + bean.getBugkey + " - " + bean.getSummary
val summaryLink: String = <API key>.<API key>(siteUrl, bean.getBugkey, bean.getProjectShortName)
val projectMember: SimpleProjectMember = <API key>.<API key>(emailNotification.getChangeby,
bean.getProjectid, emailNotification.getSaccountid)
val avatarId: String = if (projectMember != null) projectMember.getMemberAvatarId else ""
val userAvatar: Img = LinkUtils.newAvatar(avatarId)
val makeChangeUser: String = userAvatar.toString + emailNotification.<API key>
val actionEnum: Enum[_] = emailNotification.getAction match {
case <API key>.CREATE_ACTION => BugI18nEnum.<API key>
case <API key>.UPDATE_ACTION => BugI18nEnum.<API key>
case <API key>.ADD_COMMENT_ACTION => BugI18nEnum.<API key>
}
contentGenerator.putVariable("actionHeading", context.getMessage(actionEnum, makeChangeUser))
contentGenerator.putVariable("titles", List(currentProject))
contentGenerator.putVariable("summary", summary)
contentGenerator.putVariable("summaryLink", summaryLink)
}
protected def getBeanInContext(context: MailContext[SimpleBug]): SimpleBug = bugService.findById(context.getTypeid.toInt, context.getSaccountid)
protected def getItemName: String = StringUtils.trim(bean.getSummary, 100)
protected def getCreateSubject(context: MailContext[SimpleBug]): String = context.getMessage(BugI18nEnum.<API key>,
bean.getProjectname, context.<API key>, getItemName)
protected def getUpdateSubject(context: MailContext[SimpleBug]): String = context.getMessage(BugI18nEnum.<API key>,
bean.getProjectname, context.<API key>, getItemName)
protected def getCommentSubject(context: MailContext[SimpleBug]): String = context.getMessage(BugI18nEnum.<API key>,
bean.getProjectname, context.<API key>, getItemName)
protected def getItemFieldMapper: ItemFieldMapper = mapper
protected def <API key>(notification: <API key>): Set[SimpleUser] = {
import scala.collection.JavaConverters._
val <API key>: List[<API key>] = <API key>.
findNotifications(notification.getProjectId, notification.getSaccountid).asScala.toList
var notifyUsers: Set[SimpleUser] = notification.getNotifyUsers.asScala.toSet
for (notificationSetting <- <API key>) {
if (NotificationType.None.name == notificationSetting.getLevel) {
notifyUsers = notifyUsers.filter(notifyUser => !(notifyUser.getUsername == notificationSetting.getUsername))
}
else if (NotificationType.Minimal.name == notificationSetting.getLevel) {
val findResult: Option[SimpleUser] = notifyUsers.find(notifyUser => notifyUser.getUsername == notificationSetting.getUsername);
findResult match {
case None => {
val bug: SimpleBug = bugService.findById(notification.getTypeid.toInt, notification.getSaccountid)
if (notificationSetting.getUsername == bug.getAssignuser) {
val prjMember: SimpleUser = <API key>.<API key>(notificationSetting.getUsername,
notificationSetting.getProjectid, notificationSetting.getSaccountid)
if (prjMember != null) {
notifyUsers += prjMember
}
}
}
case Some(user) => {}
}
}
else if (NotificationType.Full.name == notificationSetting.getLevel) {
val prjMember: SimpleUser = <API key>.<API key>(notificationSetting.getUsername,
notificationSetting.getProjectid, notificationSetting.getSaccountid)
if (prjMember != null) {
notifyUsers += prjMember
}
}
}
notifyUsers
}
class BugFieldNameMapper extends ItemFieldMapper {
put(BugWithBLOBs.Field.summary, BugI18nEnum.FORM_SUMMARY, isColSpan = true)
put(BugWithBLOBs.Field.environment, BugI18nEnum.FORM_ENVIRONMENT, isColSpan = true)
put(BugWithBLOBs.Field.description, GenericI18Enum.FORM_DESCRIPTION, isColSpan = true)
put(BugWithBLOBs.Field.assignuser, new AssigneeFieldFormat(BugWithBLOBs.Field.assignuser.name, GenericI18Enum.FORM_ASSIGNEE))
put(BugWithBLOBs.Field.milestoneid, new <API key>(BugWithBLOBs.Field.milestoneid.name, BugI18nEnum.FORM_PHASE))
put(BugWithBLOBs.Field.status, new I18nFieldFormat(BugWithBLOBs.Field.status.name, BugI18nEnum.FORM_STATUS, classOf[OptionI18nEnum.BugStatus]))
put(BugWithBLOBs.Field.resolution, new I18nFieldFormat(BugWithBLOBs.Field.resolution.name, BugI18nEnum.FORM_RESOLUTION, classOf[OptionI18nEnum.BugResolution]))
put(BugWithBLOBs.Field.severity, new I18nFieldFormat(BugWithBLOBs.Field.severity.name, BugI18nEnum.FORM_SEVERITY, classOf[OptionI18nEnum.BugSeverity]))
put(BugWithBLOBs.Field.priority, new I18nFieldFormat(BugWithBLOBs.Field.priority.name, BugI18nEnum.FORM_PRIORITY, classOf[OptionI18nEnum.BugPriority]))
put(BugWithBLOBs.Field.duedate, new DateFieldFormat(BugWithBLOBs.Field.duedate.name, BugI18nEnum.FORM_DUE_DATE))
put(BugWithBLOBs.Field.logby, new LogUserFieldFormat(BugWithBLOBs.Field.logby.name, BugI18nEnum.FORM_LOG_BY))
}
class <API key>(fieldName: String, displayName: Enum[_]) extends FieldFormat(fieldName, displayName) {
def formatField(context: MailContext[_]): String = {
val bug: SimpleBug = context.getWrappedBean.asInstanceOf[SimpleBug]
if (bug.getMilestoneid == null || bug.getMilestoneName == null) {
new Span().write
} else {
val img: Text = new Text(ProjectResources.getFontIconHtml(<API key>.MILESTONE));
val milestoneLink: String = <API key>.<API key>(context.siteUrl,
bug.getProjectid, bug.getMilestoneid)
val link: A = newA(milestoneLink, bug.getMilestoneName)
newLink(img, link).write
}
}
def formatField(context: MailContext[_], value: String): String = {
if (StringUtils.isBlank(value)) {
new Span().write
} else {
try {
val milestoneId: Int = value.toInt
val milestoneService: MilestoneService = <API key>.getSpringBean(classOf[MilestoneService])
val milestone: SimpleMilestone = milestoneService.findById(milestoneId, context.getUser.getAccountId)
if (milestone != null) {
val img: Text = new Text(ProjectResources.getFontIconHtml(<API key>.MILESTONE));
val milestoneLink: String = <API key>.<API key>(context.siteUrl, milestone
.getProjectid, milestone.getId)
val link: A = newA(milestoneLink, milestone.getName)
return newLink(img, link).write
}
}
catch {
case e: Exception => LOG.error("Error", e)
}
value
}
}
}
class AssigneeFieldFormat(fieldName: String, displayName: Enum[_]) extends FieldFormat(fieldName, displayName) {
def formatField(context: MailContext[_]): String = {
val bug: SimpleBug = context.getWrappedBean.asInstanceOf[SimpleBug]
if (bug.getAssignuser != null) {
val userAvatarLink: String = MailUtils.getAvatarLink(bug.<API key>, 16)
val img: Img = newImg("avatar", userAvatarLink)
val userLink: String = <API key>.<API key>(MailUtils.getSiteUrl(bug.getSaccountid), bug.getAssignuser)
val link: A = newA(userLink, bug.<API key>)
newLink(img, link).write
}
else {
new Span().write
}
}
def formatField(context: MailContext[_], value: String): String = {
if (org.apache.commons.lang3.StringUtils.isBlank(value)) {
new Span().write
} else {
val userService: UserService = <API key>.getSpringBean(classOf[UserService])
val user: SimpleUser = userService.<API key>(value, context.getUser.getAccountId)
if (user != null) {
val userAvatarLink: String = MailUtils.getAvatarLink(user.getAvatarid, 16)
val userLink: String = <API key>.<API key>(MailUtils.getSiteUrl(user.getAccountId), user.getUsername)
val img: Img = newImg("avatar", userAvatarLink)
val link: A = newA(userLink, user.getDisplayName)
newLink(img, link).write
} else
value
}
}
}
class LogUserFieldFormat(fieldName: String, displayName: Enum[_]) extends FieldFormat(fieldName, displayName) {
def formatField(context: MailContext[_]): String = {
val bug: SimpleBug = context.getWrappedBean.asInstanceOf[SimpleBug]
if (bug.getLogby != null) {
val userAvatarLink: String = MailUtils.getAvatarLink(bug.getLoguserAvatarId, 16)
val img: Img = newImg("avatar", userAvatarLink)
val userLink: String = <API key>.<API key>(MailUtils.getSiteUrl(bug.getSaccountid), bug.getLogby)
val link: A = newA(userLink, bug.getLoguserFullName)
newLink(img, link).write
}
else
new Span().write
}
def formatField(context: MailContext[_], value: String): String = {
if (StringUtils.isBlank(value))
return new Span().write
val userService: UserService = <API key>.getSpringBean(classOf[UserService])
val user: SimpleUser = userService.<API key>(value, context.getUser.getAccountId)
if (user != null) {
val userAvatarLink: String = MailUtils.getAvatarLink(user.getAvatarid, 16)
val userLink: String = <API key>.<API key>(MailUtils.getSiteUrl(user.getAccountId), user.getUsername)
val img: Img = newImg("avatar", userAvatarLink)
val link: A = newA(userLink, user.getDisplayName)
newLink(img, link).write
} else
value
}
}
}
|
/**
* @file
* @brief Realmedia RTSP protocol (RDT) support
* @author Ronald S. Bultje <rbultje@ronald.bitfreak.net>
*/
#include "avformat.h"
#include "libavutil/avstring.h"
#include "rtpdec.h"
#include "rdt.h"
#include "libavutil/base64.h"
#include "libavutil/md5.h"
#include "rm.h"
#include "internal.h"
#include "avio_internal.h"
#include "libavcodec/get_bits.h"
struct RDTDemuxContext {
AVFormatContext *ic; /**< the containing (RTSP) demux context */
/** Each RDT stream-set (represented by one RTSPStream) can contain
* multiple streams (of the same content, but with possibly different
* codecs/bitrates). Each such stream is represented by one AVStream
* in the AVFormatContext, and this variable points to the offset in
* that array such that the first is the first stream of this set. */
AVStream **streams;
int n_streams; /**< streams with identifical content in this set */
void *<API key>;
<API key> parse_packet;
uint32_t prev_timestamp;
int prev_set_id, prev_stream_id;
};
RDTDemuxContext *
ff_rdt_parse_open(AVFormatContext *ic, int <API key>,
void *priv_data, <API key> *handler)
{
RDTDemuxContext *s = av_mallocz(sizeof(RDTDemuxContext));
if (!s)
return NULL;
s->ic = ic;
s->streams = &ic->streams[<API key>];
do {
s->n_streams++;
} while (<API key> + s->n_streams < ic->nb_streams &&
s->streams[s->n_streams]->id == s->streams[0]->id);
s->prev_set_id = -1;
s->prev_stream_id = -1;
s->prev_timestamp = -1;
s->parse_packet = handler ? handler->parse_packet : NULL;
s-><API key> = priv_data;
return s;
}
void
ff_rdt_parse_close(RDTDemuxContext *s)
{
av_free(s);
}
struct PayloadContext {
AVFormatContext *rmctx;
int nb_rmst;
RMStream **rmst;
uint8_t *mlti_data;
unsigned int mlti_data_size;
char buffer[<API key> + <API key>];
int audio_pkt_cnt; /**< remaining audio packets in rmdec */
};
void
<API key>(char response[41], char chksum[9],
const char *challenge)
{
int ch_len = strlen (challenge), i;
unsigned char zres[16],
buf[64] = { 0xa1, 0xe9, 0x14, 0x9d, 0x0e, 0x6b, 0x3b, 0x59 };
#define XOR_TABLE_SIZE 37
const unsigned char xor_table[XOR_TABLE_SIZE] = {
0x05, 0x18, 0x74, 0xd0, 0x0d, 0x09, 0x02, 0x53,
0xc0, 0x01, 0x05, 0x05, 0x67, 0x03, 0x19, 0x70,
0x08, 0x27, 0x66, 0x10, 0x10, 0x72, 0x08, 0x09,
0x63, 0x11, 0x03, 0x71, 0x08, 0x08, 0x70, 0x02,
0x10, 0x57, 0x05, 0x18, 0x54 };
/* some (length) checks */
if (ch_len == 40) /* what a hack... */
ch_len = 32;
else if (ch_len > 56)
ch_len = 56;
memcpy(buf + 8, challenge, ch_len);
/* xor challenge bytewise with xor_table */
for (i = 0; i < XOR_TABLE_SIZE; i++)
buf[8 + i] ^= xor_table[i];
av_md5_sum(zres, buf, 64);
ff_data_to_hex(response, zres, 16, 1);
/* add tail */
strcpy (response + 32, "01d0a8e3");
/* calculate checksum */
for (i = 0; i < 8; i++)
chksum[i] = response[i * 4];
chksum[8] = 0;
}
static int
rdt_load_mdpr (PayloadContext *rdt, AVStream *st, int rule_nr)
{
AVIOContext pb;
int size;
uint32_t tag;
/**
* Layout of the MLTI chunk:
* 4: MLTI
* 2: number of streams
* Then for each stream ([number_of_streams] times):
* 2: mdpr index
* 2: number of mdpr chunks
* Then for each mdpr chunk ([<API key>] times):
* 4: size
* [size]: data
* we skip MDPR chunks until we reach the one of the stream
* we're interested in, and forward that ([size]+[data]) to
* the RM demuxer to parse the stream-specific header data.
*/
if (!rdt->mlti_data)
return -1;
ffio_init_context(&pb, rdt->mlti_data, rdt->mlti_data_size, 0,
NULL, NULL, NULL, NULL);
tag = avio_rl32(&pb);
if (tag == MKTAG('M', 'L', 'T', 'I')) {
int num, chunk_nr;
/* read index of MDPR chunk numbers */
num = avio_rb16(&pb);
if (rule_nr < 0 || rule_nr >= num)
return -1;
avio_seek(&pb, rule_nr * 2, SEEK_CUR);
chunk_nr = avio_rb16(&pb);
avio_seek(&pb, (num - 1 - rule_nr) * 2, SEEK_CUR);
/* read MDPR chunks */
num = avio_rb16(&pb);
if (chunk_nr >= num)
return -1;
while (chunk_nr
avio_seek(&pb, avio_rb32(&pb), SEEK_CUR);
size = avio_rb32(&pb);
} else {
size = rdt->mlti_data_size;
avio_seek(&pb, 0, SEEK_SET);
}
if (<API key>(rdt->rmctx, &pb, st, rdt->rmst[st->index], size) < 0)
return -1;
return 0;
}
/**
* Actual data handling.
*/
int
ff_rdt_parse_header(const uint8_t *buf, int len,
int *pset_id, int *pseq_no, int *pstream_id,
int *pis_keyframe, uint32_t *ptimestamp)
{
GetBitContext gb;
int consumed = 0, set_id, seq_no, stream_id, is_keyframe,
len_included, need_reliable;
uint32_t timestamp;
/* skip status packets */
while (len >= 5 && buf[1] == 0xFF /* status packet */) {
int pkt_len;
if (!(buf[0] & 0x80))
return -1; /* not followed by a data packet */
pkt_len = AV_RB16(buf+3);
buf += pkt_len;
len -= pkt_len;
consumed += pkt_len;
}
if (len < 16)
return -1;
init_get_bits(&gb, buf, len << 3);
len_included = get_bits1(&gb);
need_reliable = get_bits1(&gb);
set_id = get_bits(&gb, 5);
skip_bits(&gb, 1);
seq_no = get_bits(&gb, 16);
if (len_included)
skip_bits(&gb, 16);
skip_bits(&gb, 2);
stream_id = get_bits(&gb, 5);
is_keyframe = !get_bits1(&gb);
timestamp = get_bits_long(&gb, 32);
if (set_id == 0x1f)
set_id = get_bits(&gb, 16);
if (need_reliable)
skip_bits(&gb, 16);
if (stream_id == 0x1f)
stream_id = get_bits(&gb, 16);
if (pset_id) *pset_id = set_id;
if (pseq_no) *pseq_no = seq_no;
if (pstream_id) *pstream_id = stream_id;
if (pis_keyframe) *pis_keyframe = is_keyframe;
if (ptimestamp) *ptimestamp = timestamp;
return consumed + (get_bits_count(&gb) >> 3);
}
/**< return 0 on packet, no more left, 1 on packet, 1 on partial packet... */
static int
rdt_parse_packet (AVFormatContext *ctx, PayloadContext *rdt, AVStream *st,
AVPacket *pkt, uint32_t *timestamp,
const uint8_t *buf, int len, int flags)
{
int seq = 1, res;
AVIOContext pb;
if (rdt->audio_pkt_cnt == 0) {
int pos;
ffio_init_context(&pb, buf, len, 0, NULL, NULL, NULL, NULL);
flags = (flags & RTP_FLAG_KEY) ? 2 : 0;
res = ff_rm_parse_packet (rdt->rmctx, &pb, st, rdt->rmst[st->index], len, pkt,
&seq, flags, *timestamp);
pos = url_ftell(&pb);
if (res < 0)
return res;
if (res > 0) {
if (st->codec->codec_id == CODEC_ID_AAC) {
memcpy (rdt->buffer, buf + pos, len - pos);
rdt->rmctx->pb = avio_alloc_context (rdt->buffer, len - pos, 0,
NULL, NULL, NULL, NULL);
}
goto get_cache;
}
} else {
get_cache:
rdt->audio_pkt_cnt =
<API key> (rdt->rmctx, rdt->rmctx->pb,
st, rdt->rmst[st->index], pkt);
if (rdt->audio_pkt_cnt == 0 &&
st->codec->codec_id == CODEC_ID_AAC)
av_freep(&rdt->rmctx->pb);
}
pkt->stream_index = st->index;
pkt->pts = *timestamp;
return rdt->audio_pkt_cnt > 0;
}
int
ff_rdt_parse_packet(RDTDemuxContext *s, AVPacket *pkt,
uint8_t **bufptr, int len)
{
uint8_t *buf = bufptr ? *bufptr : NULL;
int seq_no, flags = 0, stream_id, set_id, is_keyframe;
uint32_t timestamp;
int rv= 0;
if (!s->parse_packet)
return -1;
if (!buf && s->prev_stream_id != -1) {
/* return the next packets, if any */
timestamp= 0; ///< Should not be used if buf is NULL, but should be set to the timestamp of the packet returned....
rv= s->parse_packet(s->ic, s-><API key>,
s->streams[s->prev_stream_id],
pkt, ×tamp, NULL, 0, flags);
return rv;
}
if (len < 12)
return -1;
rv = ff_rdt_parse_header(buf, len, &set_id, &seq_no, &stream_id, &is_keyframe, ×tamp);
if (rv < 0)
return rv;
if (is_keyframe &&
(set_id != s->prev_set_id || timestamp != s->prev_timestamp ||
stream_id != s->prev_stream_id)) {
flags |= RTP_FLAG_KEY;
s->prev_set_id = set_id;
s->prev_timestamp = timestamp;
}
s->prev_stream_id = stream_id;
buf += rv;
len -= rv;
if (s->prev_stream_id >= s->n_streams) {
s->prev_stream_id = -1;
return -1;
}
rv = s->parse_packet(s->ic, s-><API key>,
s->streams[s->prev_stream_id],
pkt, ×tamp, buf, len, flags);
return rv;
}
void
<API key> (char *cmd, int size,
int stream_nr, int rule_nr)
{
av_strlcatf(cmd, size, "stream=%d;rule=%d,stream=%d;rule=%d",
stream_nr, rule_nr * 2, stream_nr, rule_nr * 2 + 1);
}
static unsigned char *
rdt_parse_b64buf (unsigned int *target_len, const char *p)
{
unsigned char *target;
int len = strlen(p);
if (*p == '\"') {
p++;
len -= 2; /* skip embracing " at start/end */
}
*target_len = len * 3 / 4;
target = av_mallocz(*target_len + <API key>);
av_base64_decode(target, p, *target_len);
return target;
}
static int
rdt_parse_sdp_line (AVFormatContext *s, int st_index,
PayloadContext *rdt, const char *line)
{
AVStream *stream = s->streams[st_index];
const char *p = line;
if (av_strstart(p, "OpaqueData:buffer;", &p)) {
rdt->mlti_data = rdt_parse_b64buf(&rdt->mlti_data_size, p);
} else if (av_strstart(p, "StartTime:integer;", &p))
stream->first_dts = atoi(p);
else if (av_strstart(p, "ASMRuleBook:string;", &p)) {
int n, first = -1;
for (n = 0; n < s->nb_streams; n++)
if (s->streams[n]->id == stream->id) {
int count = s->streams[n]->index + 1;
if (first == -1) first = n;
if (rdt->nb_rmst < count) {
RMStream **rmst= av_realloc(rdt->rmst, count*sizeof(*rmst));
if (!rmst)
return AVERROR(ENOMEM);
memset(rmst + rdt->nb_rmst, 0,
(count - rdt->nb_rmst) * sizeof(*rmst));
rdt->rmst = rmst;
rdt->nb_rmst = count;
}
rdt->rmst[s->streams[n]->index] = <API key>();
rdt_load_mdpr(rdt, s->streams[n], (n - first) * 2);
if (s->streams[n]->codec->codec_id == CODEC_ID_AAC)
s->streams[n]->codec->frame_size = 1; // FIXME
}
}
return 0;
}
static void
real_parse_asm_rule(AVStream *st, const char *p, const char *end)
{
do {
/* can be either averagebandwidth= or AverageBandwidth= */
if (sscanf(p, " %*1[Aa]verage%*1[Bb]andwidth=%d", &st->codec->bit_rate) == 1)
break;
if (!(p = strchr(p, ',')) || p > end)
p = end;
p++;
} while (p < end);
}
static AVStream *
add_dstream(AVFormatContext *s, AVStream *orig_st)
{
AVStream *st;
if (!(st = av_new_stream(s, orig_st->id)))
return NULL;
st->codec->codec_type = orig_st->codec->codec_type;
st->first_dts = orig_st->first_dts;
return st;
}
static void
<API key>(AVFormatContext *s, AVStream *orig_st,
const char *p)
{
const char *end;
int n_rules = 0, odd = 0;
AVStream *st;
/**
* The ASMRuleBook contains a list of comma-separated strings per rule,
* and each rule is separated by a ;. The last one also has a ; at the
* end so we can use it as delimiter.
* Every rule occurs twice, once for when the RTSP packet header marker
* is set and once for if it isn't. We only read the first because we
* don't care much (that's what the "odd" variable is for).
* Each rule contains a set of one or more statements, optionally
* preceeded by a single condition. If there's a condition, the rule
* starts with a '#'. Multiple conditions are merged between brackets,
* so there are never multiple conditions spread out over separate
* statements. Generally, these conditions are bitrate limits (min/max)
* for multi-bitrate streams.
*/
if (*p == '\"') p++;
while (1) {
if (!(end = strchr(p, ';')))
break;
if (!odd && end != p) {
if (n_rules > 0)
st = add_dstream(s, orig_st);
else
st = orig_st;
if (!st)
break;
real_parse_asm_rule(st, p, end);
n_rules++;
}
p = end + 1;
odd ^= 1;
}
}
void
<API key> (AVFormatContext *s, int stream_index,
const char *line)
{
const char *p = line;
if (av_strstart(p, "ASMRuleBook:string;", &p))
<API key>(s, s->streams[stream_index], p);
}
static PayloadContext *
rdt_new_context (void)
{
PayloadContext *rdt = av_mallocz(sizeof(PayloadContext));
<API key>(&rdt->rmctx, NULL, "", &ff_rdt_demuxer, NULL);
return rdt;
}
static void
rdt_free_context (PayloadContext *rdt)
{
int i;
for (i = 0; i < rdt->nb_rmst; i++)
if (rdt->rmst[i]) {
ff_rm_free_rmstream(rdt->rmst[i]);
av_freep(&rdt->rmst[i]);
}
if (rdt->rmctx)
<API key>(rdt->rmctx);
av_freep(&rdt->mlti_data);
av_freep(&rdt->rmst);
av_free(rdt);
}
#if __STDC_VERSION >= 1999001L
#define RDT_HANDLER(n, s, t) \
static <API key> ff_rdt_ ## n ## _handler = { \
.enc_name = s, \
.codec_type = t, \
.codec_id = CODEC_ID_NONE, \
.parse_sdp_a_line = rdt_parse_sdp_line, \
.open = rdt_new_context, \
.close = rdt_free_context, \
.parse_packet = rdt_parse_packet \
}
#else
#define RDT_HANDLER(n, s, t) \
static <API key> ff_rdt_ ## n ## _handler = { \
s, \
t, \
CODEC_ID_NONE, \
0, \
rdt_parse_sdp_line, \
rdt_new_context, \
rdt_free_context, \
rdt_parse_packet \
, NULL \
}
#endif
RDT_HANDLER(live_video, "<API key>", AVMEDIA_TYPE_VIDEO);
RDT_HANDLER(live_audio, "<API key>", AVMEDIA_TYPE_AUDIO);
RDT_HANDLER(video, "x-pn-realvideo", AVMEDIA_TYPE_VIDEO);
RDT_HANDLER(audio, "x-pn-realaudio", AVMEDIA_TYPE_AUDIO);
void <API key>(void)
{
<API key>(&<API key>);
<API key>(&<API key>);
<API key>(&<API key>);
<API key>(&<API key>);
}
|
#!/usr/bin/env python
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-
# NetProfile: Authentication routines
# This file is part of NetProfile.
# NetProfile is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public
# version.
# NetProfile is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# You should have received a copy of the GNU Affero General
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division
)
import hashlib
import random
import string
import time
from zope.interface import implementer
from pyramid.interfaces import I<API key>
from pyramid.security import (
Authenticated,
Everyone
)
class <API key>(object):
def __init__(self, request, policy):
self.request = request
self.policy = policy
@implementer(I<API key>)
class Plugin<API key>(object):
def __init__(self, default, routes=None):
self._default = default
if routes is None:
routes = {}
self._routes = routes
def add_plugin(self, route, policy):
self._routes[route] = policy
def match(self, request):
if hasattr(request, 'auth_policy'):
return request.auth_policy
cur = None
cur_len = 0
for route, plug in self._routes.items():
r_len = len(route)
if r_len <= cur_len:
continue
path = request.path
if route == path[:r_len]:
if len(path) > r_len:
if path[r_len:r_len + 1] != '/':
continue
cur = plug
cur_len = r_len
if cur:
request.auth_policy = cur
else:
request.auth_policy = self._default
request.registry.notify(<API key>(request, request.auth_policy))
return request.auth_policy
def <API key>(self, request):
return self.match(request).<API key>(request)
def un<API key>(self, request):
return self.match(request).un<API key>(request)
def <API key>(self, request):
return self.match(request).<API key>(request)
def remember(self, request, principal, **kw):
return self.match(request).remember(request, principal, **kw)
def forget(self, request):
return self.match(request).forget(request)
_TOKEN_FILTER_MAP = (
[chr(n) for n in range(32)] +
[chr(127), '\\', '"']
)
_TOKEN_FILTER_MAP = dict.fromkeys(_TOKEN_FILTER_MAP, None)
def _filter_token(tok):
return str(tok).translate(_TOKEN_FILTER_MAP)
def _format_kvpairs(**kwargs):
return ', '.join('{0!s}="{1}"'.format(k, _filter_token(v)) for (k, v) in kwargs.items())
def _generate_nonce(ts, secret, salt=None, chars=string.hexdigits.upper()):
# TODO: Add IP-address to nonce
if not salt:
try:
rng = random.SystemRandom()
except NotImplementedError:
rng = random
salt = ''.join(rng.choice(chars) for i in range(16))
ctx = hashlib.md5(('%s:%s:%s' % (ts, salt, secret)).encode())
return ('%s:%s:%s' % (ts, salt, ctx.hexdigest()))
def _is_valid_nonce(nonce, secret):
comp = nonce.split(':')
if len(comp) != 3:
return False
calc_nonce = _generate_nonce(comp[0], secret, comp[1])
if nonce == calc_nonce:
return True
return False
def <API key>(ts, secret, realm, opaque, stale=False):
nonce = _generate_nonce(ts, secret)
return 'Digest %s' % (_format_kvpairs(
realm=realm,
qop='auth',
nonce=nonce,
opaque=opaque,
algorithm='MD5',
stale='true' if stale else 'false'
),)
def <API key>(request, secret, realm):
resp = request.response
if not resp.www_authenticate:
resp.www_authenticate = <API key>(
round(time.time()),
secret, realm, 'NPDIGEST'
)
def <API key>(request, secret, realm):
authz = request.authorization
if (not authz) or (len(authz) != 2) or (authz[0] != 'Digest'):
<API key>(request, secret, realm)
return None
params = authz[1]
if 'algorithm' not in params:
params['algorithm'] = 'MD5'
for required in ('username', 'realm', 'nonce', 'uri', 'response', 'cnonce', 'nc', 'opaque'):
if (required not in params) or ((required == 'opaque') and (params['opaque'] != 'NPDIGEST')):
<API key>(request, secret, realm)
return None
return params
@implementer(I<API key>)
class Digest<API key>(object):
def __init__(self, secret, callback, realm='Realm'):
self.secret = secret
self.callback = callback
self.realm = realm
def <API key>(self, request):
params = <API key>(request, self.secret, self.realm)
if params is None:
return None
if not _is_valid_nonce(params['nonce'], self.secret):
<API key>(request, self.secret, self.realm)
return None
userid = params['username']
if self.callback(params, request) is not None:
return 'u:%s' % userid
<API key>(request, self.secret, self.realm)
def un<API key>(self, request):
params = <API key>(request, self.secret, self.realm)
if params is None:
return None
if not _is_valid_nonce(params['nonce'], self.secret):
<API key>(request, self.secret, self.realm)
return None
return 'u:%s' % params['username']
def <API key>(self, request):
creds = [Everyone]
params = <API key>(request, self.secret, self.realm)
if params is None:
return creds
if not _is_valid_nonce(params['nonce'], self.secret):
<API key>(request, self.secret, self.realm)
return creds
groups = self.callback(params, request)
if groups is None:
return creds
creds.append(Authenticated)
creds.append('u:%s' % params['username'])
creds.extend(groups)
return creds
def remember(self, request, principal, *kw):
return []
def forget(self, request):
return [('WWW-Authenticate', <API key>(
round(time.time()),
self.secret,
self.realm,
'NPDIGEST'
))]
|
<?php
namespace Drupal\effective_activism\<API key>;
use Drupal;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\<API key>;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Session\AccountInterface;
/**
* Access controller for the Event entity.
*
* @see \Drupal\effective_activism\Entity\Event.
*/
class <API key> extends <API key> {
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
switch ($operation) {
case 'view':
if (!$entity->isPublished()) {
return AccessControl::isManager($entity->get('parent')->entity->get('organization')->entity, $account);
}
else {
return AccessControl::isStaff($entity->get('parent')->entity->get('organization')->entity, $account);
}
case 'update':
return AccessControl::isGroupStaff([$entity->get('parent')->entity], $account);
case 'delete':
return AccessControl::isManager($entity->get('parent')->entity->get('organization')->entity, $account);
}
// Unknown operation, no opinion.
return AccessResult::neutral();
}
/**
* {@inheritdoc}
*/
protected function checkCreateAccess(AccountInterface $account, array $context, $entity_bundle = NULL) {
return AccessControl::isGroupStaff([Drupal::request()->get('group')], $account);
}
}
|
package com.rapidminer.gui.actions;
import com.rapidminer.RapidMiner;
import com.rapidminer.core.license.<API key>;
import com.rapidminer.gui.MainFrame;
import com.rapidminer.gui.tools.ResourceAction;
import com.rapidminer.gui.tools.dialogs.AboutBox;
import java.awt.event.ActionEvent;
/**
* The type About action.
*
* @author Simon Fischer
*/
public class AboutAction extends ResourceAction {
private static final long serialVersionUID = 1L;
private MainFrame mainFrame;
/**
* Instantiates a new About action.
*
* @param mainFrame the main frame
*/
public AboutAction(MainFrame mainFrame) {
super("about");
this.mainFrame = mainFrame;
setCondition(EDIT_IN_PROGRESS, DONT_CARE);
}
@Override
public void actionPerformed(ActionEvent e) {
new AboutBox(mainFrame, RapidMiner.getLongVersion(), <API key>.INSTANCE.getActiveLicense())
.setVisible(true);
}
}
|
class CreateVersions < ActiveRecord::Migration
def self.up
create_table :versions do |t|
t.string :item_type, :null => false
t.integer :item_id, :null => false
t.string :event, :null => false
t.string :whodunnit
t.text :object
t.datetime :created_at
end
add_index :versions, [:item_type, :item_id]
create_table :blog_post_versions do |t|
t.string :item_type, :null => false
t.integer :item_id, :null => false
t.string :event, :null => false
t.string :whodunnit
t.text :object
t.datetime :created_at
end
add_index :blog_post_versions, [:item_type, :item_id]
end
def self.down
drop_table :blog_post_versions
drop_table :versions
end
end
|
title: Event History
toc: [Documentation, Programming Guide, WAMP Features, PubSub, Event History]
# Event History
Event history allows a WAMP client to retrieve a set of past events for a subscription. Retrieval is by subscription ID, and for a set number of events.
## Configuration in Crossbar.io
Crossbar.io does not normally store PubSub events. To enable event history for a topic, you need to configure an event store as part of the Crossbar.io config.
An example for this is
json
{
"name": "realm1",
"roles": [
],
"store": {
"type": "memory",
"event-history": [
{
"uri": "com.example.oncounter",
"limit": 10000
}
]
}
}
The above configures a store on the realm `realm1` which resides in memory, and which stores the last 1000 events for the topic `com.example.oncounter`.
For the time being, `memory` is the only valid argument for where the store is kept, so there is no event history across restarts of Crossbar.io. We are going to implement an LMDB database which will allow persistence across program restarts.
For the time being, event history can only be stored for a specific topic URI. Use of pattern-based subscriptions is not supported.
To be able to retrieve event history, a client needs to have two permissions:
* It must be allowed to call the retrieval procedure ('wamp.subscription.get_events').
* It must be allowed to subscribe to the subscription (as identified by the subscription ID given in the call). This requirement is necessary to prevent clients for circumeventing the subscription permissions by simply periodically retrieving events for a subscription.
For the time being, the only way to get that subscription ID locally is to actually subscribe to to the topic. (We are thinking about implementing a call to retrieve the subscription ID without subscribing, or an extra argument for the subscribe request to allow this.)
## Calling to Get the Events
The actual call to retrieve events is
javascript
session.call('wamp.subscription.get_events', [subcriptionID, 20]).then(
function (history) {
console.log("got history for " + history.length + " events");
for (var i = 0; i < history.length; ++i) {
console.log(history[i].timestamp, history[i].publication, history[i].args[0]);
}
},
function (err) {
console.log("could not retrieve event history", err);
}
);
where the arguments are the subscription ID to retrieve events for and the number of past events to be retrieved.
The event history is returned as an array of event objects.
|
(function() {
'use strict';
angular.module('columbyApp')
.controller('SearchCtrl', function($log,$rootScope, $scope, SearchSrv) {
$scope.contentLoading = true;
$scope.search = {};
$rootScope.title = 'columby.com | search';
$scope.pagination = {
itemsPerPage: 20,
datasets:{
currentPage: 1
},
accounts:{
currentPage: 1
},
tags:{
currentPage: 1
}
};
$scope.doSearch = function(){
$scope.search.hits = null;
if ($scope.search.searchTerm.length>2){
$scope.search.message = 'Searching for: ' + $scope.search.searchTerm;
SearchSrv.query({
text: $scope.search.searchTerm,
limit: $scope.pagination.itemsPerPage
}).then(function (response) {
$scope.search.hits = response;
$scope.search.message = null;
$scope.pagination.datasets.numPages = response.datasets.count / $scope.pagination.itemsPerPage;
$scope.pagination.accounts.numPages = response.accounts.count / $scope.pagination.itemsPerPage;
$scope.pagination.tags.numPages = response.tags.count / $scope.pagination.itemsPerPage;
}, function(err){
$scope.search.message = 'Error: ' + err.data.message;
});
} else {
$scope.search.message = 'Type at least 3 characters.';
}
};
if ($rootScope.searchTerm){
$scope.search.searchTerm = $rootScope.searchTerm;
$log.debug($scope.search.searchTerm);
delete $rootScope.searchTerm;
$log.debug($scope.search.searchTerm);
$scope.doSearch();
}
});
})();
|
QuestionCuePoint cuePoint = new QuestionCuePoint();
cuePoint.EntryId = "0_mej0it92";
cuePoint.Question = "hello world";
OnCompletedHandler<CuePoint> handler = new OnCompletedHandler<CuePoint>(
(CuePoint result, Exception e) =>
{
CodeExample.PrintObject(result);
done = true;
});
CuePointService.Add(cuePoint)
.SetCompletion(handler)
.Execute(client);
|
from . import models
from . import lroe
|
#include <groestlcoin/groestlcoin/network/protocol.hpp>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <memory>
#include <system_error>
#include <boost/date_time.hpp>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <groestlcoin/groestlcoin/error.hpp>
#include <groestlcoin/groestlcoin/network/authority.hpp>
#include <groestlcoin/groestlcoin/network/hosts.hpp>
#include <groestlcoin/groestlcoin/network/handshake.hpp>
#include <groestlcoin/groestlcoin/network/seeder.hpp>
#include <groestlcoin/groestlcoin/utility/logger.hpp>
#include <groestlcoin/groestlcoin/utility/threadpool.hpp>
namespace libgroestlcoin {
namespace network {
using std::placeholders::_1;
using std::placeholders::_2;
using boost::filesystem::path;
using boost::format;
using boost::posix_time::time_duration;
using boost::posix_time::seconds;
#ifdef ENABLE_TESTNET
const hosts::authority_list protocol::default_seeds =
{
{ "testnet-seed.alexykot.me", 18333 },
{ "testnet-seed.bitcoin.petertodd.org", 18333 },
{ "testnet-seed.bluematt.me", 18333 },
{ "testnet-seed.bitcoin.schildbach.de", 18333 }
};
#else
const hosts::authority_list protocol::default_seeds =
{
{ "seed.bitnodes.io", 8333 },
{ "seed.bitcoinstats.com", 8333 },
{ "seed.bitcoin.sipa.be", 8333 },
{ "dnsseed.bluematt.me", 8333 },
{ "seed.bitcoin.jonasschnelli.ch", 8333 },
{ "dnsseed.bitcoin.dashjr.org", 8333 }
// Previously also included:
// bitseed.xf2.org:8333
// archivum.info:8333
// progressbar.sk:8333
// faucet.bitcoin.st:8333
// bitcoin.securepayment.cc:8333
};
#endif
const size_t protocol::<API key> = 8;
// TODO: parameterize for config access.
const size_t <API key> = 10;
const time_duration <API key> = seconds(1);
protocol::protocol(threadpool& pool, hosts& peers, handshake& shake,
network& net, const hosts::authority_list& seeds, uint16_t port,
size_t max_outbound)
: strand_(pool),
host_pool_(peers),
handshake_(shake),
network_(net),
max_outbound_(max_outbound),
watermark_timer_(pool.service()),
watermark_count_(0),
listen_port_(port),
channel_subscribe_(std::make_shared<<API key>>(pool)),
seeds_(seeds)
{
}
void protocol::start(completion_handler handle_complete)
{
// handshake.start doesn't accept an error code so we prevent its
// execution in case of start failure, using this lambda wrapper.
const auto start_handshake = [this, handle_complete]
(const std::error_code& ec)
{
if (ec)
{
handle_complete(ec);
return;
}
strand_.wrap(&handshake::start,
&handshake_, handle_complete)();
};
const auto run_protocol =
strand_.wrap(&protocol::handle_start,
this, _1, start_handshake);
host_pool_.load(
strand_.wrap(&protocol::fetch_count,
this, _1, run_protocol));
}
void protocol::handle_start(const std::error_code& ec,
completion_handler handle_complete)
{
if (ec)
{
log_error(LOG_PROTOCOL)
<< "Failure fetching height: " << ec.message();
handle_complete(ec);
return;
}
// TODO: handle run startup failure.
handle_complete(ec);
run();
}
void protocol::stop(completion_handler handle_complete)
{
host_pool_.save(
strand_.wrap(&protocol::handle_stop,
this, _1, handle_complete));
}
void protocol::handle_stop(const std::error_code& ec,
completion_handler handle_complete)
{
if (ec)
{
log_error(LOG_PROTOCOL)
<< "Failure saving hosts file: " << ec.message();
handle_complete(ec);
return;
}
channel_subscribe_->relay(error::service_stopped, nullptr);
handle_complete(error::success);
}
void protocol::fetch_count(const std::error_code& ec,
completion_handler handle_complete)
{
if (ec)
{
log_error(LOG_PROTOCOL)
<< "Failure loading hosts file: " << ec.message();
handle_complete(ec);
return;
}
host_pool_.fetch_count(
strand_.wrap(&protocol::start_seeder,
this, _1, _2, handle_complete));
}
void protocol::start_seeder(const std::error_code& ec, size_t hosts_count,
completion_handler handle_complete)
{
if (ec)
{
log_error(LOG_PROTOCOL)
<< "Failure checking existing hosts file: " << ec.message();
handle_complete(ec);
return;
}
if (hosts_count == 0)
{
seeder_ = std::make_shared<seeder>(this, seeds_, handle_complete);
seeder_->start();
return;
}
handle_complete(error::success);
}
std::string protocol::state_to_string(connect_state state) const
{
switch (state)
{
case connect_state::finding_peer:
return "finding peer";
case connect_state::connecting:
return "connecting to peer";
case connect_state::established:
return "established connection";
case connect_state::stopped:
return "stopped";
}
// Unhandled state!
BITCOIN_ASSERT(false);
return "";
}
void protocol::modify_slot(slot_index slot, connect_state state)
{
connect_states_[slot] = state;
log_debug(LOG_PROTOCOL)
<< "Outbound connection on slot ["
<< slot << "] " << state_to_string(state) << ".";
}
void protocol::run()
{
strand_.queue(
std::bind(&protocol::start_connecting,
this));
if (listen_port_ == 0)
return;
// Unhandled startup failure condition.
network_.listen(listen_port_,
strand_.wrap(&protocol::handle_listen,
this, _1, _2));
}
void protocol::start_connecting()
{
// Initialize the connection slots.
BITCOIN_ASSERT(connections_.empty());
BITCOIN_ASSERT(connect_states_.empty());
connect_states_.resize(max_outbound_);
for (size_t slot = 0; slot < connect_states_.size(); ++slot)
modify_slot(slot, connect_state::stopped);
// Start the main outbound connect loop.
<API key>();
<API key>();
}
void protocol::<API key>()
{
for (size_t slot = 0; slot < connect_states_.size(); ++slot)
if (connect_states_[slot] == connect_state::stopped)
try_connect_once(slot);
}
void protocol::try_connect_once(slot_index slot)
{
++watermark_count_;
if (watermark_count_ > <API key>)
return;
BITCOIN_ASSERT(slot <= connect_states_.size());
BITCOIN_ASSERT(connect_states_[slot] == connect_state::stopped);
// Begin connection flow: finding_peer -> connecting -> established.
// Failures end with connect_state::stopped and loop back here again.
modify_slot(slot, connect_state::finding_peer);
host_pool_.fetch_address(
strand_.wrap(&protocol::attempt_connect,
this, _1, _2, slot));
}
void protocol::<API key>()
{
// This timer just loops continuously at fixed intervals
// resetting the watermark_count_ variable and starting stopped slots.
const auto reset_watermark = [this](const boost::system::error_code& ec)
{
if (ec)
{
if (ec != boost::asio::error::operation_aborted)
log_error(LOG_PROTOCOL)
<< "Failure resetting watermark timer: " << ec.message();
BITCOIN_ASSERT(ec == boost::asio::error::operation_aborted);
return;
}
if (watermark_count_ > <API key>)
log_debug(LOG_PROTOCOL)
<< "Resuming connection attempts.";
// Perform the reset, reallowing connection attempts.
watermark_count_ = 0;
<API key>();
// Looping timer...
<API key>();
};
watermark_timer_.expires_from_now(<API key>);
watermark_timer_.async_wait(strand_.wrap(reset_watermark, _1));
}
template <typename ConnectionList>
bool already_connected(const <API key>& address,
const ConnectionList& connections)
{
for (const auto& connection: connections)
if (connection.address.ip == address.ip &&
connection.address.port == address.port)
return true;
return false;
}
void protocol::attempt_connect(const std::error_code& ec,
const <API key>& address, slot_index slot)
{
BITCOIN_ASSERT(connect_states_[slot] == connect_state::finding_peer);
modify_slot(slot, connect_state::connecting);
if (ec)
{
log_error(LOG_PROTOCOL)
<< "Failure randomly selecting a peer address for slot ["
<< slot << "] " << ec.message();
return;
}
if (already_connected(address, connections_))
{
log_debug(LOG_PROTOCOL)
<< "Already connected to selected peer ["
<< authority(address).to_string() << "]";
// Retry another connection, still in same strand.
modify_slot(slot, connect_state::stopped);
try_connect_once(slot);
return;
}
log_debug(LOG_PROTOCOL)
<< "Connecting to peer [" << authority(address).to_string()
<< "] on slot [" << slot << "]";
const authority peer(address);
connect(handshake_, network_, peer.host, peer.port,
strand_.wrap(&protocol::handle_connect,
this, _1, _2, address, slot));
}
void protocol::handle_connect(const std::error_code& ec, channel_ptr node,
const <API key>& address, slot_index slot)
{
BITCOIN_ASSERT(connect_states_[slot] == connect_state::connecting);
if (ec || !node)
{
log_debug(LOG_PROTOCOL)
<< "Failure connecting to peer ["
<< authority(address).to_string() << "] on slot [" << slot << "] "
<< ec.message();
// Retry another connection, still in same strand.
modify_slot(slot, connect_state::stopped);
try_connect_once(slot);
return;
}
modify_slot(slot, connect_state::established);
BITCOIN_ASSERT(connections_.size() <= max_outbound_);
connections_.push_back({address, node});
log_info(LOG_PROTOCOL)
<< "Connected to peer ["
<< authority(address).to_string() << "] on slot [" << slot << "] ("
<< connections_.size() << " total)";
// Remove channel from list of connections
node->subscribe_stop(
strand_.wrap(&protocol::<API key>,
this, _1, node, slot));
setup_new_channel(node);
}
void protocol::maintain_connection(const std::string& hostname, uint16_t port)
{
connect(handshake_, network_, hostname, port,
strand_.wrap(&protocol::<API key>,
this, _1, _2, hostname, port));
}
void protocol::<API key>(const std::error_code& ec,
channel_ptr node, const std::string& hostname, uint16_t port)
{
if (ec || !node)
{
log_debug(LOG_PROTOCOL)
<< "Failure connecting manually to peer ["
<< authority(hostname, port).to_string() << "] " << ec.message();
// Retry connect.
maintain_connection(hostname, port);
return;
}
manual_connections_.push_back(node);
// Connected!
log_info(LOG_PROTOCOL)
<< "Connection to peer established manually ["
<< authority(hostname, port).to_string() << "]";
// Subscript to channel stop notifications.
node->subscribe_stop(
strand_.wrap(&protocol::<API key>,
this, _1, node, hostname, port));
setup_new_channel(node);
}
void protocol::handle_listen(const std::error_code& ec, acceptor_ptr accept)
{
if (!accept)
return;
if (ec)
{
log_error(LOG_PROTOCOL)
<< "Error while starting listener: " << ec.message();
return;
}
// Listen for connections.
accept->accept(
strand_.wrap(&protocol::handle_accept,
this, _1, _2, accept));
}
void protocol::handle_accept(const std::error_code& ec, channel_ptr node,
acceptor_ptr accept)
{
if (!accept)
return;
// Relisten for connections.
accept->accept(
strand_.wrap(&protocol::handle_accept,
this, _1, _2, accept));
if (ec)
{
if (node)
log_debug(LOG_PROTOCOL)
<< "Failure accepting connection from ["
<< node->address().to_string() << "] " << ec.message();
else
log_debug(LOG_PROTOCOL)
<< "Failure accepting connection: " << ec.message();
return;
}
accepted_channels_.push_back(node);
log_info(LOG_PROTOCOL)
<< "Accepted connection from [" << node->address().to_string() << "] ("
<< accepted_channels_.size() << " total)";
const auto handshake_complete = [this, node](const std::error_code& ec)
{
if (!node)
return;
if (ec)
{
log_debug(LOG_PROTOCOL) << "Failure in handshake from ["
<< node->address().to_string() << "] " << ec.message();
return;
}
// Remove channel from list of connections
node->subscribe_stop(
strand_.wrap(&protocol::<API key>,
this, _1, node));
setup_new_channel(node);
};
handshake_.ready(node, handshake_complete);
}
void protocol::setup_new_channel(channel_ptr node)
{
if (!node)
return;
const auto handle_send = [node](const std::error_code& ec)
{
if (!node)
return;
if (ec)
{
log_debug(LOG_PROTOCOL) << "Send error ["
<< node->address().to_string() << "] " << ec.message();
}
};
// Subscribe to address messages.
node->subscribe_address(
strand_.wrap(&protocol::<API key>,
this, _1, _2, node));
node->send(get_address_type(), handle_send);
// Notify subscribers
channel_subscribe_->relay(error::success, node);
}
template <typename ConnectionsList>
void remove_connection(ConnectionsList& connections, channel_ptr node)
{
auto it = connections.begin();
for (; it != connections.end(); ++it)
if (it->node == node)
break;
BITCOIN_ASSERT(it != connections.end());
connections.erase(it);
}
void protocol::<API key>(const std::error_code& ec,
channel_ptr node, slot_index slot)
{
// We must always attempt a reconnection.
if (ec)
{
if (node)
log_debug(LOG_PROTOCOL)
<< "Channel stopped (outbound) ["
<< node->address().to_string() << "] " << ec.message();
else
log_debug(LOG_PROTOCOL)
<< "Channel stopped (outbound): " << ec.message();
}
// Erase this channel from our list and then attempt a reconnection.
remove_connection(connections_, node);
BITCOIN_ASSERT(connect_states_[slot] == connect_state::established);
modify_slot(slot, connect_state::stopped);
// Attempt reconnection.
try_connect_once(slot);
}
template <typename ChannelsList>
void remove_channel(ChannelsList& channels, channel_ptr node)
{
const auto it = std::find(channels.begin(), channels.end(), node);
BITCOIN_ASSERT(it != channels.end());
channels.erase(it);
}
void protocol::<API key>(const std::error_code& ec,
channel_ptr node, const std::string& hostname, uint16_t port)
{
// We must always attempt a reconnection.
if (ec)
{
if (node)
log_debug(LOG_PROTOCOL)
<< "Channel stopped (manual) ["
<< authority(hostname, port).to_string() << "] " << ec.message();
else
log_debug(LOG_PROTOCOL)
<< "Channel stopped (manual): " << ec.message();
}
// Remove from accepted connections.
// Timeout logic would go here if we ever need it.
remove_channel(manual_connections_, node);
// Attempt reconnection.
maintain_connection(hostname, port);
}
void protocol::<API key>(const std::error_code& ec,
channel_ptr node)
{
// We do not attempt to reconnect inbound connections.
if (ec)
{
if (node)
log_debug(LOG_PROTOCOL)
<< "Channel stopped (inbound) ["
<< node->address().to_string() << "] " << ec.message();
else
log_debug(LOG_PROTOCOL)
<< "Channel stopped (inbound): " << ec.message();
}
// Remove from accepted connections (no reconnect).
remove_channel(accepted_channels_, node);
}
void protocol::<API key>(const std::error_code& ec,
const address_type& packet, channel_ptr node)
{
if (!node)
return;
if (ec)
{
// TODO: reset the connection.
log_debug(LOG_PROTOCOL)
<< "Failure getting addresses from ["
<< node->address().to_string() << "] " << ec.message();
return;
}
log_debug(LOG_PROTOCOL)
<< "Storing addresses from [" << node->address().to_string() << "]";
for (const auto& net_address: packet.addresses)
host_pool_.store(net_address,
strand_.wrap(&protocol::<API key>,
this, _1));
// Subscribe to address messages.
node->subscribe_address(
strand_.wrap(&protocol::<API key>,
this, _1, _2, node));
}
void protocol::<API key>(const std::error_code& ec)
{
if (ec)
log_error(LOG_PROTOCOL) << "Failed to store address: "
<< ec.message();
}
void protocol::<API key>(
<API key> handle_fetch)
{
strand_.queue(
std::bind(&protocol::<API key>,
this, handle_fetch));
}
void protocol::<API key>(
<API key> handle_fetch)
{
handle_fetch(error::success, connections_.size());
}
void protocol::subscribe_channel(channel_handler handle_channel)
{
channel_subscribe_->subscribe(handle_channel);
}
size_t protocol::total_connections() const
{
return connections_.size() + manual_connections_.size() +
accepted_channels_.size();
}
void protocol::set_max_outbound(size_t max_outbound)
{
max_outbound_ = max_outbound;
}
void protocol::set_hosts_filename(const std::string& hosts_path)
{
host_pool_.file_path_ = hosts_path;
}
// Deprecated, this is problematic because there is no enabler.
void protocol::disable_listener()
{
listen_port_ = 0;
}
// Deprecated, should be private.
void protocol::bootstrap(completion_handler handle_complete)
{
}
} // namespace network
} // namespace libgroestlcoin
|
<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');
<API key>(array('plugins' => array(array('function', 'sugar_include', 'cache/modules/Accounts/EditView.tpl', 39, false),array('function', 'counter', 'cache/modules/Accounts/EditView.tpl', 45, false),array('function', 'sugar_translate', 'cache/modules/Accounts/EditView.tpl', 49, false),array('function', 'sugar_getjspath', 'cache/modules/Accounts/EditView.tpl', 150, false),array('function', 'html_options', 'cache/modules/Accounts/EditView.tpl', 389, false),array('function', 'sugar_getimagepath', 'cache/modules/Accounts/EditView.tpl', 417, false),array('modifier', 'default', 'cache/modules/Accounts/EditView.tpl', 46, false),array('modifier', 'strip_semicolon', 'cache/modules/Accounts/EditView.tpl', 57, false),array('modifier', 'lookup', 'cache/modules/Accounts/EditView.tpl', 414, false),array('modifier', 'count', 'cache/modules/Accounts/EditView.tpl', 494, false),)), $this); ?>
<div class="clear"></div>
<form action="index.php" method="POST" name="<?php echo $this->_tpl_vars['form_name']; ?>
" id="<?php echo $this->_tpl_vars['form_id']; ?>
" <?php echo $this->_tpl_vars['enctype']; ?>
>
<table width="100%" cellpadding="0" cellspacing="0" border="0" class="dcQuickEdit">
<tr>
<td class="buttons">
<input type="hidden" name="module" value="<?php echo $this->_tpl_vars['module']; ?>
">
<?php if (isset ( $_REQUEST['isDuplicate'] ) && $_REQUEST['isDuplicate'] == 'true'): ?>
<input type="hidden" name="record" value="">
<input type="hidden" name="duplicateSave" value="true">
<input type="hidden" name="duplicateId" value="<?php echo $this->_tpl_vars['fields']['id']['value']; ?>
">
<?php else: ?>
<input type="hidden" name="record" value="<?php echo $this->_tpl_vars['fields']['id']['value']; ?>
">
<?php endif; ?>
<input type="hidden" name="isDuplicate" value="false">
<input type="hidden" name="action">
<input type="hidden" name="return_module" value="<?php echo $_REQUEST['return_module']; ?>
">
<input type="hidden" name="return_action" value="<?php echo $_REQUEST['return_action']; ?>
">
<input type="hidden" name="return_id" value="<?php echo $_REQUEST['return_id']; ?>
">
<input type="hidden" name="module_tab">
<input type="hidden" name="contact_role">
<?php if (! empty ( $_REQUEST['return_module'] ) || ! empty ( $_REQUEST['relate_to'] )): ?>
<input type="hidden" name="relate_to" value="<?php if ($_REQUEST['return_relationship']): echo $_REQUEST['return_relationship']; elseif ($_REQUEST['relate_to'] && empty ( $_REQUEST['from_dcmenu'] )): echo $_REQUEST['relate_to']; elseif (empty ( $this->_tpl_vars['isDCForm'] ) && empty ( $_REQUEST['from_dcmenu'] )): echo $_REQUEST['return_module']; endif; ?>">
<input type="hidden" name="relate_id" value="<?php echo $_REQUEST['return_id']; ?>
">
<?php endif; ?>
<input type="hidden" name="offset" value="<?php echo $this->_tpl_vars['offset']; ?>
">
<input type="submit" id="SAVE" value="Save" name="button" title="Save"
accessKey="a" class="button primary"
onclick="this.form.action.value='Save'; <API key>();
if(check_form('EditView'))SUGAR.ajaxUI.submitForm(this.form);return false; " value="Save" >
<?php if (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $_REQUEST['return_id'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" accessKey="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?>
&record=<?php echo $_REQUEST['return_id']; ?>
'); return false;" name="button" value="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" type="button" id="CANCEL"> <?php elseif (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $this->_tpl_vars['fields']['id']['value'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" accessKey="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?>
&record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?>
'); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" id="CANCEL"> <?php elseif (empty ( $_REQUEST['return_action'] ) || empty ( $_REQUEST['return_id'] ) && ! empty ( $this->_tpl_vars['fields']['id']['value'] )): ?><input title="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" accessKey="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=Accounts'); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" id="CANCEL"> <?php else: ?><input title="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" accessKey="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=<?php echo $_REQUEST['return_module']; ?>
&record=<?php echo $_REQUEST['return_id']; ?>
'); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" id="CANCEL"> <?php endif; if ($this->_tpl_vars['bean']->aclAccess('detail')): if (! empty ( $this->_tpl_vars['fields']['id']['value'] ) && $this->_tpl_vars['isAuditEnabled']): ?><input id="btn_view_change_log" title="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?>
" class="button" onclick='open_popup("Audit", "600", "400", "&record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?>
&module_name=Accounts", true, false, { "call_back_function":"set_return","form_name":"EditView","field_to_name_array":[] } ); return false;' type="button" value="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?>
"><?php endif; endif; ?>
</td>
<td align='right'>
<?php echo $this->_tpl_vars['PAGINATION']; ?>
</td>
</tr>
</table><?php echo <API key>(array('include' => $this->_tpl_vars['includes']), $this);?>
<span id='tabcounterJS'><script>SUGAR.TabFields=new Array();//this will be used to track tabindexes for references</script></span>
<div id="EditView_tabs"
>
<div >
<div id="<API key>">
<?php echo <API key>(array('name' => 'panelFieldCount','start' => 0,'print' => false,'assign' => 'panelFieldCount'), $this);?>
<table width="100%" border="0" cellspacing="1" cellpadding="0" class="yui3-skin-sam <?php echo ((is_array($_tmp=@$this->_tpl_vars['def']['templateMeta']['panelClass'])) ? $this->_run_mod_handler('default', true, $_tmp, 'edit view dcQuickEdit edit508') : <API key>($_tmp, 'edit view dcQuickEdit edit508')); ?>
">
<tr>
<th align="left" colspan="8">
<h4><?php echo <API key>(array('label' => '<API key>','module' => 'Accounts'), $this);?>
</h4>
</th>
</tr>
<?php echo <API key>(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?>
<?php ob_start(); ?>
<tr>
<td valign="top" id='first_name_label' width='12.5%' scope="col">
<?php ob_start(); echo <API key>(array('label' => 'LBL_FIRST_NAME','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?>
<label for="first_name"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : <API key>($_tmp)); ?>
:</label>
<span class="required">*</span>
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' >
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<?php if (strlen ( $this->_tpl_vars['fields']['first_name']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['first_name']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['first_name']['value']); endif; ?>
<input type='text' name='<?php echo $this->_tpl_vars['fields']['first_name']['name']; ?>
'
id='<?php echo $this->_tpl_vars['fields']['first_name']['name']; ?>
' size='30'
maxlength='15'
value='<?php echo $this->_tpl_vars['value']; ?>
' title='' accesskey='7' >
<td valign="top" id='<API key>' width='12.5%' scope="col">
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' >
<td valign="top" id='_label' width='%' scope="col">
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='%' >
</tr>
<?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?>
<?php endif; echo <API key>(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?>
<?php ob_start(); ?>
<tr>
<td valign="top" id='last_name_label' width='12.5%' scope="col">
<?php ob_start(); echo <API key>(array('label' => 'LBL_LAST_NAME','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?>
<label for="last_name"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : <API key>($_tmp)); ?>
:</label>
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' colspan='3'>
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<?php if (strlen ( $this->_tpl_vars['fields']['last_name']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['last_name']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['last_name']['value']); endif; ?>
<input type='text' name='<?php echo $this->_tpl_vars['fields']['last_name']['name']; ?>
'
id='<?php echo $this->_tpl_vars['fields']['last_name']['name']; ?>
' size='30'
maxlength='15'
value='<?php echo $this->_tpl_vars['value']; ?>
' title='' >
</tr>
<?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?>
<?php endif; echo <API key>(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?>
<?php ob_start(); ?>
<tr>
<td valign="top" id='website_label' width='12.5%' scope="col">
<?php ob_start(); echo <API key>(array('label' => 'LBL_WEBSITE','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?>
<label for="website"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : <API key>($_tmp)); ?>
:</label>
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' colspan='3'>
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<?php if (! empty ( $this->_tpl_vars['fields']['website']['value'] )): ?>
<input type='text' name='<?php echo $this->_tpl_vars['fields']['website']['name']; ?>
' id='<?php echo $this->_tpl_vars['fields']['website']['name']; ?>
' size='30'
maxlength='255' value='<?php echo $this->_tpl_vars['fields']['website']['value']; ?>
' title='' tabindex='0' >
<?php else: ?>
<input type='text' name='<?php echo $this->_tpl_vars['fields']['website']['name']; ?>
' id='<?php echo $this->_tpl_vars['fields']['website']['name']; ?>
' size='30'
maxlength='255'
<?php if ($this->_tpl_vars['displayView'] == 'advanced_search' || $this->_tpl_vars['displayView'] == 'basic_search'): ?>value=''<?php else: ?>value='http://'<?php endif; ?> title='' tabindex='0' >
<?php endif; ?>
</tr>
<?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?>
<?php endif; echo <API key>(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?>
<?php ob_start(); ?>
<tr>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' colspan='2'>
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<script type="text/javascript" src='<?php echo <API key>(array('file' => "include/SugarFields/Fields/Address/SugarFieldAddress.js"), $this);?>
'></script>
<fieldset id='<API key>'>
<legend><?php echo <API key>(array('label' => 'LBL_BILLING_ADDRESS','module' => ''), $this);?>
</legend>
<table border="0" cellspacing="1" cellpadding="0" class="edit" width="100%">
<tr>
<td valign="top" id="<API key>" width='25%' scope='row' >
<label for="<API key>"><?php echo <API key>(array('label' => 'LBL_BILLING_STREET','module' => ''), $this);?>
:</label>
<?php if ($this->_tpl_vars['fields']['<API key>']['required'] || false): ?>
<span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?>
</span>
<?php endif; ?>
</td>
<td width="*">
<textarea id="<API key>" name="<API key>" maxlength="150" rows="2" cols="30" tabindex="0"><?php echo $this->_tpl_vars['fields']['<API key>']['value']; ?>
</textarea>
</td>
</tr>
<tr>
<td id="<API key>" width='%' scope='row' >
<label for="<API key>"><?php echo <API key>(array('label' => 'LBL_CITY','module' => ''), $this);?>
:
<?php if ($this->_tpl_vars['fields']['<API key>']['required'] || false): ?>
<span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?>
</span>
<?php endif; ?>
</td>
<td>
<input type="text" name="<API key>" id="<API key>" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['<API key>']['value']; ?>
' tabindex="0">
</td>
</tr>
<tr>
<td id="<API key>" width='%' scope='row' >
<label for="<API key>"><?php echo <API key>(array('label' => 'LBL_STATE','module' => ''), $this);?>
:</label>
<?php if ($this->_tpl_vars['fields']['<API key>']['required'] || false): ?>
<span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?>
</span>
<?php endif; ?>
</td>
<td>
<input type="text" name="<API key>" id="<API key>" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['<API key>']['value']; ?>
' tabindex="0">
</td>
</tr>
<tr>
<td id="<API key>" width='%' scope='row' >
<label for="<API key>"><?php echo <API key>(array('label' => 'LBL_POSTAL_CODE','module' => ''), $this);?>
:</label>
<?php if ($this->_tpl_vars['fields']['<API key>']['required'] || false): ?>
<span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?>
</span>
<?php endif; ?>
</td>
<td>
<input type="text" name="<API key>" id="<API key>" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['<API key>']['value']; ?>
' tabindex="0">
</td>
</tr>
<tr>
<td id="<API key>" width='%' scope='row' >
<label for="<API key>"><?php echo <API key>(array('label' => 'LBL_COUNTRY','module' => ''), $this);?>
:</label>
<?php if ($this->_tpl_vars['fields']['<API key>']['required'] || false): ?>
<span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?>
</span>
<?php endif; ?>
</td>
<td>
<input type="text" name="<API key>" id="<API key>" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['<API key>']['value']; ?>
' tabindex="0">
</td>
</tr>
<tr>
<td colspan='2' NOWRAP> </td>
</tr>
</table>
</fieldset>
<script type="text/javascript">
SUGAR.util.doWhen("typeof(SUGAR.AddressField) != 'undefined'", function(){
billing_address = new SUGAR.AddressField("billing_checkbox",'', 'billing');
});
</script>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' colspan='2'>
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<script type="text/javascript" src='<?php echo <API key>(array('file' => "include/SugarFields/Fields/Address/SugarFieldAddress.js"), $this);?>
'></script>
<fieldset id='<API key>'>
<legend><?php echo <API key>(array('label' => '<API key>','module' => ''), $this);?>
</legend>
<table border="0" cellspacing="1" cellpadding="0" class="edit" width="100%">
<tr>
<td valign="top" id="<API key>" width='25%' scope='row' >
<label for="<API key>"><?php echo <API key>(array('label' => 'LBL_SHIPPING_STREET','module' => ''), $this);?>
:</label>
<?php if ($this->_tpl_vars['fields']['<API key>']['required'] || false): ?>
<span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?>
</span>
<?php endif; ?>
</td>
<td width="*">
<textarea id="<API key>" name="<API key>" maxlength="150" rows="2" cols="30" tabindex="0"><?php echo $this->_tpl_vars['fields']['<API key>']['value']; ?>
</textarea>
</td>
</tr>
<tr>
<td id="<API key>" width='%' scope='row' >
<label for="<API key>"><?php echo <API key>(array('label' => 'LBL_CITY','module' => ''), $this);?>
:
<?php if ($this->_tpl_vars['fields']['<API key>']['required'] || false): ?>
<span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?>
</span>
<?php endif; ?>
</td>
<td>
<input type="text" name="<API key>" id="<API key>" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['<API key>']['value']; ?>
' tabindex="0">
</td>
</tr>
<tr>
<td id="<API key>" width='%' scope='row' >
<label for="<API key>"><?php echo <API key>(array('label' => 'LBL_STATE','module' => ''), $this);?>
:</label>
<?php if ($this->_tpl_vars['fields']['<API key>']['required'] || false): ?>
<span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?>
</span>
<?php endif; ?>
</td>
<td>
<input type="text" name="<API key>" id="<API key>" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['<API key>']['value']; ?>
' tabindex="0">
</td>
</tr>
<tr>
<td id="<API key>" width='%' scope='row' >
<label for="<API key>"><?php echo <API key>(array('label' => 'LBL_POSTAL_CODE','module' => ''), $this);?>
:</label>
<?php if ($this->_tpl_vars['fields']['<API key>']['required'] || false): ?>
<span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?>
</span>
<?php endif; ?>
</td>
<td>
<input type="text" name="<API key>" id="<API key>" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['<API key>']['value']; ?>
' tabindex="0">
</td>
</tr>
<tr>
<td id="<API key>" width='%' scope='row' >
<label for="<API key>"><?php echo <API key>(array('label' => 'LBL_COUNTRY','module' => ''), $this);?>
:</label>
<?php if ($this->_tpl_vars['fields']['<API key>']['required'] || false): ?>
<span class="required"><?php echo $this->_tpl_vars['APP']['LBL_REQUIRED_SYMBOL']; ?>
</span>
<?php endif; ?>
</td>
<td>
<input type="text" name="<API key>" id="<API key>" size="30" maxlength='150' value='<?php echo $this->_tpl_vars['fields']['<API key>']['value']; ?>
' tabindex="0">
</td>
</tr>
<tr>
<td scope='row' NOWRAP>
<?php echo <API key>(array('label' => '<API key>','module' => ''), $this);?>
:
</td>
<td>
<input id="shipping_checkbox" name="shipping_checkbox" type="checkbox" onclick="shipping_address.syncFields();">
</td>
</tr>
</table>
</fieldset>
<script type="text/javascript">
SUGAR.util.doWhen("typeof(SUGAR.AddressField) != 'undefined'", function(){
shipping_address = new SUGAR.AddressField("shipping_checkbox",'billing', 'shipping');
});
</script>
</tr>
<?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?>
<?php endif; echo <API key>(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?>
<?php ob_start(); ?>
<tr>
<td valign="top" id='email1_label' width='12.5%' scope="col">
<?php ob_start(); echo <API key>(array('label' => 'LBL_EMAIL','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?>
<label for="email1"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : <API key>($_tmp)); ?>
:</label>
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' >
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<?php echo $this->_tpl_vars['EMAIL']; ?>
<td valign="top" id='phoneno_label' width='12.5%' scope="col">
<?php ob_start(); echo <API key>(array('label' => 'LBL_PHONENO','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?>
<label for=""><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : <API key>($_tmp)); ?>
:</label>
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' >
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<?php echo $this->_tpl_vars['PHONENOS']; ?>
</tr>
<?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?>
<?php endif; echo <API key>(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?>
<?php ob_start(); ?>
<tr>
<td valign="top" id='description_label' width='12.5%' scope="col">
<?php ob_start(); echo <API key>(array('label' => 'LBL_DESCRIPTION','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?>
<label for="description"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : <API key>($_tmp)); ?>
:</label>
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' >
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<?php if (empty ( $this->_tpl_vars['fields']['description']['value'] )): $this->assign('value', $this->_tpl_vars['fields']['description']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['description']['value']); endif; ?>
<textarea id='<?php echo $this->_tpl_vars['fields']['description']['name']; ?>
' name='<?php echo $this->_tpl_vars['fields']['description']['name']; ?>
'
rows="6"
cols="80"
title='' tabindex="0"
><?php echo $this->_tpl_vars['value']; ?>
</textarea>
<td valign="top" id='phone_fax_label' width='12.5%' scope="col">
<?php ob_start(); echo <API key>(array('label' => 'LBL_FAX','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?>
<label for="phone_fax"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : <API key>($_tmp)); ?>
:</label>
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' >
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<?php if (strlen ( $this->_tpl_vars['fields']['phone_fax']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['phone_fax']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['phone_fax']['value']); endif; ?>
<input type='text' name='<?php echo $this->_tpl_vars['fields']['phone_fax']['name']; ?>
' id='<?php echo $this->_tpl_vars['fields']['phone_fax']['name']; ?>
' size='30' maxlength='100' value='<?php echo $this->_tpl_vars['value']; ?>
' title='' tabindex='0' class="phone" >
</tr>
<?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?>
<?php endif; echo <API key>(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?>
<?php ob_start(); ?>
<tr>
<td valign="top" id='client_source_label' width='12.5%' scope="col">
<?php ob_start(); echo <API key>(array('label' => 'LBL_CLIENT_SOURCE','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?>
<label for="client_source"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : <API key>($_tmp)); ?>
:</label>
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' colspan='3'>
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<?php if (! isset ( $this->_tpl_vars['config']['enable_autocomplete'] ) || $this->_tpl_vars['config']['enable_autocomplete'] == false): ?>
<select name="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
"
id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
"
title=''
>
<?php if (isset ( $this->_tpl_vars['fields']['client_source']['value'] ) && $this->_tpl_vars['fields']['client_source']['value'] != ''): echo <API key>(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['value']), $this);?>
<?php else: echo <API key>(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['default']), $this);?>
<?php endif; ?>
</select>
<?php else: $this->assign('field_options', $this->_tpl_vars['fields']['client_source']['options']); ob_start(); echo $this->_tpl_vars['fields']['client_source']['value']; $this->_smarty_vars['capture']['field_val'] = ob_get_contents(); ob_end_clean(); $this->assign('field_val', $this->_smarty_vars['capture']['field_val']); ob_start(); echo $this->_tpl_vars['fields']['client_source']['name']; $this->_smarty_vars['capture']['ac_key'] = ob_get_contents(); ob_end_clean(); $this->assign('ac_key', $this->_smarty_vars['capture']['ac_key']); ?>
<select style='display:none' name="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
"
id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
"
title=''
>
<?php if (isset ( $this->_tpl_vars['fields']['client_source']['value'] ) && $this->_tpl_vars['fields']['client_source']['value'] != ''): echo <API key>(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['value']), $this);?>
<?php else: echo <API key>(array('options' => $this->_tpl_vars['fields']['client_source']['options'],'selected' => $this->_tpl_vars['fields']['client_source']['default']), $this);?>
<?php endif; ?>
</select>
<input
id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
-input"
name="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
-input"
size="30"
value="<?php echo ((is_array($_tmp=$this->_tpl_vars['field_val'])) ? $this->_run_mod_handler('lookup', true, $_tmp, $this->_tpl_vars['field_options']) : <API key>($_tmp, $this->_tpl_vars['field_options'])); ?>
"
type="text" style="vertical-align: top;">
<span class="id-ff multiple">
<button type="button"><img src="<?php echo <API key>(array('file' => "id-ff-down.png"), $this);?>
" id="<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
-image"></button><button type="button"
id="btn-clear-<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
-input"
title="Clear"
onclick="SUGAR.clearRelateField(this.form, '<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
-input', '<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
');sync_<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
()"><img src="<?php echo <API key>(array('file' => "id-ff-clear.png"), $this);?>
"></button>
</span>
<?php echo '
<script>
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo ' = [];
'; ?>
<?php echo '
(function (){
var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '");
if (typeof select_defaults =="undefined")
select_defaults = [];
select_defaults[selectElem.id] = {key:selectElem.value,text:\'\'};
//get default
for (i=0;i<selectElem.options.length;i++){
if (selectElem.options[i].value==selectElem.value)
select_defaults[selectElem.id].text = selectElem.options[i].innerHTML;
}
//SUGAR.AutoComplete.{$ac_key}.ds =
//get options array from vardefs
var options = SUGAR.AutoComplete.getOptionsArray("");
YUI().use(\'datasource\', \'<API key>\',function (Y) {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.ds = new Y.DataSource.Function({
source: function (request) {
var ret = [];
for (i=0;i<selectElem.options.length;i++)
if (!(selectElem.options[i].value==\'\' && selectElem.options[i].innerHTML==\'\'))
ret.push({\'key\':selectElem.options[i].value,\'text\':selectElem.options[i].innerHTML});
return ret;
}
});
});
})();
'; ?>
<?php echo '
YUI().use("autocomplete", "<API key>", "<API key>", "node","node-event-simulate", function (Y) {
'; ?>
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.inputNode = Y.one('#<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
-input');
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.inputImage = Y.one('#<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
-image');
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.inputHidden = Y.one('#<?php echo $this->_tpl_vars['fields']['client_source']['name']; ?>
');
<?php echo '
function SyncToHidden(selectme){
var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '");
var doSimulateChange = false;
if (selectElem.value!=selectme)
doSimulateChange=true;
selectElem.value=selectme;
for (i=0;i<selectElem.options.length;i++){
selectElem.options[i].selected=false;
if (selectElem.options[i].value==selectme)
selectElem.options[i].selected=true;
}
if (doSimulateChange)
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'change\');
}
//global variable
sync_'; echo $this->_tpl_vars['fields']['client_source']['name']; echo ' = function(){
SyncToHidden();
}
function <API key>(){
var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '");
//if select no longer on page, kill timer
if (selectElem==null || selectElem.options == null)
return;
var currentvalue = SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.get(\'value\');
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.simulate(\'keyup\');
for (i=0;i<selectElem.options.length;i++){
if (selectElem.options[i].value==selectElem.value && document.activeElement != document.getElementById(\''; echo $this->_tpl_vars['fields']['client_source']['name']; ?>
-input<?php echo '\'))
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.set(\'value\',selectElem.options[i].innerHTML);
}
}
YAHOO.util.Event.onAvailable("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '", <API key>);
'; ?>
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.minQLen = 0;
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.queryDelay = 0;
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.numOptions = <?php echo count($this->_tpl_vars['field_options']); ?>
;
if(SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.numOptions >= 300) <?php echo '{
'; ?>
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.minQLen = 1;
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.queryDelay = 200;
<?php echo '
}
'; ?>
if(SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.numOptions >= 3000) <?php echo '{
'; ?>
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.minQLen = 1;
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.queryDelay = 500;
<?php echo '
}
'; ?>
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.optionsVisible = false;
<?php echo '
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.plug(Y.Plugin.AutoComplete, {
activateFirstItem: true,
'; ?>
minQueryLength: SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.minQLen,
queryDelay: SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.queryDelay,
zIndex: 99999,
<?php echo '
source: SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.ds,
resultTextLocator: \'text\',
resultHighlighter: \'phraseMatch\',
resultFilters: \'phraseMatch\',
});
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.expandHover = function(ex){
var hover = YAHOO.util.Dom.<API key>(\'dccontent\');
if(hover[0] != null){
if (ex) {
var h = \'1000px\';
hover[0].style.height = h;
}
else{
hover[0].style.height = \'\';
}
}
}
if('; ?>
SUGAR.AutoComplete.<?php echo $this->_tpl_vars['ac_key']; ?>
.minQLen<?php echo ' == 0){
// expand the dropdown options upon focus
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'focus\', function () {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.sendRequest(\'\');
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.optionsVisible = true;
});
}
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'click\', function(e) {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'click\');
});
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'dblclick\', function(e) {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'dblclick\');
});
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'focus\', function(e) {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'focus\');
});
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'mouseup\', function(e) {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'mouseup\');
});
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'mousedown\', function(e) {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'mousedown\');
});
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.on(\'blur\', function(e) {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.simulate(\'blur\');
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.optionsVisible = false;
var selectElem = document.getElementById("'; echo $this->_tpl_vars['fields']['client_source']['name']; echo '");
//if typed value is a valid option, do nothing
for (i=0;i<selectElem.options.length;i++)
if (selectElem.options[i].innerHTML==SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.get(\'value\'))
return;
//typed value is invalid, so set the text and the hidden to blank
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.set(\'value\', select_defaults[selectElem.id].text);
SyncToHidden(select_defaults[selectElem.id].key);
});
// when they click on the arrow image, toggle the visibility of the options
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputImage.ancestor().on(\'click\', function () {
if (SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.optionsVisible) {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.blur();
} else {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.focus();
}
});
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.on(\'query\', function () {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputHidden.set(\'value\', \'\');
});
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.on(\'visibleChange\', function (e) {
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.expandHover(e.newVal); // expand
});
// when they select an option, set the hidden input with the KEY, to be saved
SUGAR.AutoComplete.'; echo $this->_tpl_vars['ac_key']; echo '.inputNode.ac.on(\'select\', function(e) {
SyncToHidden(e.result.raw.key);
});
});
</script>
'; ?>
<?php endif; ?>
</tr>
<?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?>
<?php endif; ?>
</table>
</div>
<?php if ($this->_tpl_vars['panelFieldCount'] == 0): ?>
<script>document.getElementById("<API key>").style.display='none';</script>
<?php endif; ?>
<div id="LBL_PANEL_PASSWORD">
<?php echo <API key>(array('name' => 'panelFieldCount','start' => 0,'print' => false,'assign' => 'panelFieldCount'), $this);?>
<table width="100%" border="0" cellspacing="1" cellpadding="0" class="yui3-skin-sam <?php echo ((is_array($_tmp=@$this->_tpl_vars['def']['templateMeta']['panelClass'])) ? $this->_run_mod_handler('default', true, $_tmp, 'edit view dcQuickEdit edit508') : <API key>($_tmp, 'edit view dcQuickEdit edit508')); ?>
">
<tr>
<th align="left" colspan="8">
<h4><?php echo <API key>(array('label' => 'LBL_PANEL_PASSWORD','module' => 'Accounts'), $this);?>
</h4>
</th>
</tr>
<?php echo <API key>(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?>
<?php ob_start(); ?>
<tr>
<td valign="top" id='password_label' width='12.5%' scope="col">
<?php ob_start(); echo <API key>(array('label' => 'LBL_PASSWORD','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?>
<label for="password"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : <API key>($_tmp)); ?>
:</label>
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' >
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<?php if (strlen ( $this->_tpl_vars['fields']['password']['value'] ) <= 0): $this->assign('value', $this->_tpl_vars['fields']['password']['default_value']); else: $this->assign('value', $this->_tpl_vars['fields']['password']['value']); endif; ?>
<input type='text' name='<?php echo $this->_tpl_vars['fields']['password']['name']; ?>
'
id='<?php echo $this->_tpl_vars['fields']['password']['name']; ?>
' size='30'
maxlength='15'
value='<?php echo $this->_tpl_vars['value']; ?>
' title='' >
<td valign="top" id='LBL_PASSWORD_label' width='12.5%' scope="col">
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' >
<td valign="top" id='_label' width='%' scope="col">
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='%' >
</tr>
<?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?>
<?php endif; ?>
</table>
</div>
<?php if ($this->_tpl_vars['panelFieldCount'] == 0): ?>
<script>document.getElementById("LBL_PANEL_PASSWORD").style.display='none';</script>
<?php endif; ?>
<div id="<API key>">
<?php echo <API key>(array('name' => 'panelFieldCount','start' => 0,'print' => false,'assign' => 'panelFieldCount'), $this);?>
<table width="100%" border="0" cellspacing="1" cellpadding="0" class="yui3-skin-sam <?php echo ((is_array($_tmp=@$this->_tpl_vars['def']['templateMeta']['panelClass'])) ? $this->_run_mod_handler('default', true, $_tmp, 'edit view dcQuickEdit edit508') : <API key>($_tmp, 'edit view dcQuickEdit edit508')); ?>
">
<tr>
<th align="left" colspan="8">
<h4><?php echo <API key>(array('label' => '<API key>','module' => 'Accounts'), $this);?>
</h4>
</th>
</tr>
<?php echo <API key>(array('name' => 'fieldsUsed','start' => 0,'print' => false,'assign' => 'fieldsUsed'), $this);?>
<?php ob_start(); ?>
<tr>
<td valign="top" id='<API key>' width='12.5%' scope="col">
<?php ob_start(); echo <API key>(array('label' => 'LBL_ASSIGNED_TO','module' => 'Accounts'), $this); $this->_smarty_vars['capture']['label'] = ob_get_contents(); $this->assign('label', ob_get_contents());ob_end_clean(); ?>
<label for="assigned_user_name"><?php echo ((is_array($_tmp=$this->_tpl_vars['label'])) ? $this->_run_mod_handler('strip_semicolon', true, $_tmp) : <API key>($_tmp)); ?>
:</label>
</td>
<?php echo <API key>(array('name' => 'fieldsUsed'), $this);?>
<td valign="top" width='37.5%' colspan='3'>
<?php echo <API key>(array('name' => 'panelFieldCount'), $this);?>
<input type="text" name="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?>
" class="sqsEnabled" tabindex="0" id="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?>
" size="" value="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['value']; ?>
" title='' autocomplete="off" >
<input type="hidden" name="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['id_name']; ?>
"
id="<?php echo $this->_tpl_vars['fields']['assigned_user_name']['id_name']; ?>
"
value="<?php echo $this->_tpl_vars['fields']['assigned_user_id']['value']; ?>
">
<span class="id-ff multiple">
<button type="button" name="btn_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?>
" id="btn_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?>
" tabindex="0" title="<?php echo <API key>(array('label' => '<API key>'), $this);?>
" class="button firstChild" value="<?php echo <API key>(array('label' => '<API key>'), $this);?>
"
onclick='open_popup(
"<?php echo $this->_tpl_vars['fields']['assigned_user_name']['module']; ?>
",
600,
400,
"",
true,
false,
<?php echo '{"call_back_function":"set_return","form_name":"EditView","field_to_name_array":{"id":"assigned_user_id","user_name":"assigned_user_name"}}'; ?>
,
"single",
true
);' ><img src="<?php echo <API key>(array('file' => "id-ff-select.png"), $this);?>
"></button><button type="button" name="btn_clr_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?>
" id="btn_clr_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?>
" tabindex="0" title="<?php echo <API key>(array('label' => '<API key>'), $this);?>
" class="button lastChild"
onclick="SUGAR.clearRelateField(this.form, '<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?>
', '<?php echo $this->_tpl_vars['fields']['assigned_user_name']['id_name']; ?>
');" value="<?php echo <API key>(array('label' => '<API key>'), $this);?>
" ><img src="<?php echo <API key>(array('file' => "id-ff-clear.png"), $this);?>
"></button>
</span>
<script type="text/javascript">
SUGAR.util.doWhen(
"typeof(sqs_objects) != 'undefined' && typeof(sqs_objects['<?php echo $this->_tpl_vars['form_name']; ?>
_<?php echo $this->_tpl_vars['fields']['assigned_user_name']['name']; ?>
']) != 'undefined'",
enableQS
);
</script>
</tr>
<?php $this->_smarty_vars['capture']['tr'] = ob_get_contents(); $this->assign('tableRow', ob_get_contents());ob_end_clean(); if ($this->_tpl_vars['fieldsUsed'] > 0): echo $this->_tpl_vars['tableRow']; ?>
<?php endif; ?>
</table>
</div>
<?php if ($this->_tpl_vars['panelFieldCount'] == 0): ?>
<script>document.getElementById("<API key>").style.display='none';</script>
<?php endif; ?>
</div></div>
<div class="buttons">
<input type="submit" id="SAVE" value="Save" name="button" title="Save"
accessKey="a" class="button primary"
onclick="this.form.action.value='Save'; <API key>();
if(check_form('EditView'))SUGAR.ajaxUI.submitForm(this.form);return false; " value="Save" >
<?php if (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $_REQUEST['return_id'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" accessKey="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?>
&record=<?php echo $_REQUEST['return_id']; ?>
'); return false;" name="button" value="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" type="button" id="CANCEL"> <?php elseif (! empty ( $_REQUEST['return_action'] ) && ( $_REQUEST['return_action'] == 'DetailView' && ! empty ( $this->_tpl_vars['fields']['id']['value'] ) )): ?><input title="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" accessKey="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=DetailView&module=<?php echo $_REQUEST['return_module']; ?>
&record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?>
'); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" id="CANCEL"> <?php elseif (empty ( $_REQUEST['return_action'] ) || empty ( $_REQUEST['return_id'] ) && ! empty ( $this->_tpl_vars['fields']['id']['value'] )): ?><input title="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" accessKey="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=Accounts'); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" id="CANCEL"> <?php else: ?><input title="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" accessKey="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" class="button" onclick="SUGAR.ajaxUI.loadContent('index.php?action=index&module=<?php echo $_REQUEST['return_module']; ?>
&record=<?php echo $_REQUEST['return_id']; ?>
'); return false;" type="button" name="button" value="<?php echo $this->_tpl_vars['APP']['<API key>']; ?>
" id="CANCEL"> <?php endif; if ($this->_tpl_vars['bean']->aclAccess('detail')): if (! empty ( $this->_tpl_vars['fields']['id']['value'] ) && $this->_tpl_vars['isAuditEnabled']): ?><input id="btn_view_change_log" title="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?>
" class="button" onclick='open_popup("Audit", "600", "400", "&record=<?php echo $this->_tpl_vars['fields']['id']['value']; ?>
&module_name=Accounts", true, false, { "call_back_function":"set_return","form_name":"EditView","field_to_name_array":[] } ); return false;' type="button" value="<?php echo $this->_tpl_vars['APP']['LNK_VIEW_CHANGE_LOG']; ?>
"><?php endif; endif; ?>
</div>
</form>
<?php echo $this->_tpl_vars['set_focus_block']; ?>
<script>SUGAR.util.doWhen("document.getElementById('EditView') != null",
function(){SUGAR.util.<API key>();});
</script><?php echo $this->_tpl_vars['overlibStuff']; ?>
<script type="text/javascript">
YAHOO.util.Event.onContentReady("EditView",
function () { initEditView(document.forms.EditView) });
//window.setTimeout(, 100);
window.onbeforeunload = function () { return onUnloadEditView(); };
</script><?php echo '
<script type="text/javascript">
addForm(\'EditView\');addToValidate(\'EditView\', \'name\', \'name\', true,\''; echo <API key>(array('label' => 'LBL_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'date_entered_date\', \'date\', false,\'Date Created\' );
addToValidate(\'EditView\', \'date_modified_date\', \'date\', false,\'Date Modified\' );
addToValidate(\'EditView\', \'modified_user_id\', \'assigned_user_name\', false,\''; echo <API key>(array('label' => 'LBL_MODIFIED','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'modified_by_name\', \'relate\', false,\''; echo <API key>(array('label' => 'LBL_MODIFIED_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'created_by\', \'assigned_user_name\', false,\''; echo <API key>(array('label' => 'LBL_CREATED','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'created_by_name\', \'relate\', false,\''; echo <API key>(array('label' => 'LBL_CREATED','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'description\', \'text\', false,\''; echo <API key>(array('label' => 'LBL_DESCRIPTION','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'deleted\', \'bool\', false,\''; echo <API key>(array('label' => 'LBL_DELETED','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'assigned_user_id\', \'relate\', false,\''; echo <API key>(array('label' => 'LBL_ASSIGNED_TO_ID','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'assigned_user_name\', \'relate\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'account_type\', \'enum\', false,\''; echo <API key>(array('label' => 'LBL_TYPE','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'industry\', \'enum\', false,\''; echo <API key>(array('label' => 'LBL_INDUSTRY','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'annual_revenue\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_ANNUAL_REVENUE','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'phone_fax\', \'phone\', false,\''; echo <API key>(array('label' => 'LBL_FAX','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'rating\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_RATING','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'phone_office\', \'phone\', false,\''; echo <API key>(array('label' => 'LBL_PHONE_OFFICE','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'phone_alternate\', \'phone\', false,\''; echo <API key>(array('label' => 'LBL_PHONE_ALT','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'website\', \'url\', false,\''; echo <API key>(array('label' => 'LBL_WEBSITE','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'ownership\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_OWNERSHIP','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'employees\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_EMPLOYEES','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'ticker_symbol\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_TICKER_SYMBOL','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'<API key>\', \'varchar\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'email1\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_EMAIL','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'accountfilter\', \'enum\', false,\''; echo <API key>(array('label' => '','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'viewasfilter\', \'enum\', false,\''; echo <API key>(array('label' => '','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'client_source\', \'enum\', false,\''; echo <API key>(array('label' => 'LBL_CLIENT_SOURCE','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'first_name\', \'varchar\', true,\''; echo <API key>(array('label' => 'LBL_FIRST_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'call_time\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_CALL_TIME','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'last_name\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_LAST_NAME','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'parent_id\', \'id\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'sic_code\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_SIC_CODE','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'parent_name\', \'relate\', false,\''; echo <API key>(array('label' => 'LBL_MEMBER_OF','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'email_opt_out\', \'bool\', false,\''; echo <API key>(array('label' => 'LBL_EMAIL_OPT_OUT','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'invalid_email\', \'bool\', false,\''; echo <API key>(array('label' => 'LBL_INVALID_EMAIL','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'email\', \'email\', false,\''; echo <API key>(array('label' => 'LBL_ANY_EMAIL','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'campaign_id\', \'id\', false,\''; echo <API key>(array('label' => 'LBL_CAMPAIGN_ID','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'campaign_name\', \'relate\', false,\''; echo <API key>(array('label' => 'LBL_CAMPAIGN','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'password\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_PASSWORD','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'zohoid\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_ZOHOID','module' => 'Accounts','for_js' => true), $this); echo '\' );
addToValidate(\'EditView\', \'mobile\', \'varchar\', false,\''; echo <API key>(array('label' => 'LBL_MOBILE','module' => 'Accounts','for_js' => true), $this); echo '\' );
<API key>(\'EditView\', \'assigned_user_name\', \'alpha\', false,\''; echo <API key>(array('label' => '<API key>','module' => 'Accounts','for_js' => true), $this); echo ': '; echo <API key>(array('label' => 'LBL_ASSIGNED_TO','module' => 'Accounts','for_js' => true), $this); echo '\', \'assigned_user_id\' );
</script><script language="javascript">if(typeof sqs_objects == \'undefined\'){var sqs_objects = new Array;}sqs_objects[\'<API key>\']={"form":"EditView","method":"get_user_array","field_list":["user_name","id"],"populate_list":["assigned_user_name","assigned_user_id"],"required_list":["assigned_user_id"],"conditions":[{"name":"user_name","op":"like_custom","end":"%","value":""}],"limit":"30","no_match_text":"No Match"};</script>'; ?>
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Text;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace AnkiU.UserControls
{
public sealed partial class <API key> : ContentDialog
{
public string Text { get; set; }
public <API key>(string text)
{
this.InitializeComponent();
richEditBox.Document.SetText(TextSetOptions.None, text);
}
private void <API key>(ContentDialog sender, <API key> args)
{
string text;
richEditBox.Document.GetText(TextGetOptions.None, out text);
Text = text;
this.Hide();
}
private void <API key>(ContentDialog sender, <API key> args)
{
Text = null;
this.Hide();
}
}
}
|
package integration.tests;
import static org.junit.Assert.assertEquals;
import gr.ntua.vision.monitoring.VismoConfiguration;
import gr.ntua.vision.monitoring.VismoVMInfo;
import gr.ntua.vision.monitoring.dispatch.<API key>;
import gr.ntua.vision.monitoring.events.MonitoringEvent;
import gr.ntua.vision.monitoring.notify.VismoEventRegistry;
import gr.ntua.vision.monitoring.rules.Rule;
import gr.ntua.vision.monitoring.rules.VismoRulesEngine;
import gr.ntua.vision.monitoring.service.<API key>;
import gr.ntua.vision.monitoring.service.Service;
import gr.ntua.vision.monitoring.service.VismoService;
import gr.ntua.vision.monitoring.zmq.ZMQFactory;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zeromq.ZContext;
/**
* This is used to test the general facilities of the {@link VismoService}; thus is should receive events from producers, process
* them in a rules engine and dispatch them to consumers.
*/
public class VismoServiceTest {
/**
* This is used to count the number of events received.
*/
private final class EventCountRule extends Rule {
private int counter = 0;
/**
* Constructor.
*
* @param engine
*/
public EventCountRule(final VismoRulesEngine engine) {
super(engine);
}
/**
* @param expectedNoEvents
*/
public void <API key>(final int expectedNoEvents) {
assertEquals(expectedNoEvents, counter);
}
/**
* @see gr.ntua.vision.monitoring.rules.RuleProc#performWith(java.lang.Object)
*/
@Override
public void performWith(final MonitoringEvent e) {
if (e != null)
++counter;
}
}
/** the log target. */
private static final Logger log = LoggerFactory.getLogger(VismoServiceTest.class);
private static final int NO_GET_OPS = 100;
private static final int NO_PUT_OPS = 100;
@SuppressWarnings("serial")
private static final Properties p = new Properties() {
{
setProperty("cloud.name", "visioncloud.eu");
setProperty("cloud.heads", "10.0.2.211, 10.0.2.212");
setProperty("cluster.name", "vision-1");
setProperty("cluster.head", "10.0.2.211");
setProperty("producers.point", "tcp://127.0.0.1:56429");
setProperty("consumers.port", "56430");
setProperty("udp.port", "56431");
setProperty("cluster.head.port", "56432");
setProperty("cloud.head.port", "56433");
setProperty("mon.group.addr", "228.5.6.7");
setProperty("mon.group.port", "12345");
setProperty("mon.ping.period", "60000");
setProperty("startup.rules", "PassThroughRule");
setProperty("web.port", "9996");
}
};
EventCountRule countRule;
private final VismoConfiguration conf = new VismoConfiguration(p);
private FakeObjectService obs;
/** the object under test. */
private Service service;
/** the socket factory. */
private final ZMQFactory socketFactory = new ZMQFactory(new ZContext());
/**
* @throws IOException
*/
@Before
public void setUp() throws IOException {
obs = new FakeObjectService(new <API key>(socketFactory, conf, "fake-obs"));
service = new <API key>(conf, socketFactory) {
@Override
protected void submitRules(final VismoRulesEngine engine) {
countRule = new EventCountRule(engine);
countRule.submit();
super.submitRules(engine);
}
}.build(new VismoVMInfo());
}
@After
public void tearDown() {
if (service != null)
service.halt();
}
/**
* @throws <API key>
*/
@Test
public void <API key>() throws <API key> {
final VismoEventRegistry reg = new VismoEventRegistry(socketFactory, "tcp://127.0.0.1:" + conf.getConsumersPort());
final CountDownLatch latch = new CountDownLatch(1);
final ConsumerHandler consumer = new ConsumerHandler(latch, NO_GET_OPS + NO_PUT_OPS);
service.start();
reg.registerToAll(consumer);
final long start = System.currentTimeMillis();
doGETs(NO_GET_OPS);
doPUTs(NO_PUT_OPS);
log.debug("waiting event delivery...");
latch.await(10, TimeUnit.SECONDS);
final double dur = (System.currentTimeMillis() - start) / 1000.0;
log.debug("{} events delivered to client in {} sec ({} events/sec)", new Object[] { consumer.getNoReceivedEvents(), dur,
consumer.getNoReceivedEvents() / dur });
<API key>(consumer, NO_GET_OPS + NO_PUT_OPS);
}
/**
* @throws <API key>
*/
@Test
public void <API key>() throws <API key> {
service.start();
doGETs(NO_GET_OPS);
doPUTs(NO_PUT_OPS);
<API key>(2000);
<API key>();
}
private void <API key>() {
countRule.<API key>(NO_GET_OPS + NO_PUT_OPS);
}
/**
* @param noOps
*/
private void doGETs(final int noOps) {
for (int i = 0; i < noOps; ++i)
obs.getEvent("ntua", "bill", "foo-container", "bar-object").send();
}
/**
* @param noOps
*/
private void doPUTs(final int noOps) {
for (int i = 0; i < noOps; ++i)
obs.putEvent("ntua", "bill", "foo-container", "bar-object").send();
}
/**
* @param consumerHandler
* @param expectedNoEvents
*/
private static void <API key>(final ConsumerHandler consumerHandler, final int expectedNoEvents) {
assertEquals(expectedNoEvents, consumerHandler.getNoReceivedEvents());
}
/**
* @param n
* @throws <API key>
*/
private static void <API key>(final int n) throws <API key> {
Thread.sleep(n);
}
}
|
DELETE FROM `weenie` WHERE `class_Id` = 38241;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (38241, '<API key>', 10, '2019-02-10 00:00:00') /* Creature */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (38241, 1, 16) /* ItemType - Creature */
, (38241, 2, 31) /* CreatureType - Human */
, (38241, 6, -1) /* ItemsCapacity */
, (38241, 7, -1) /* ContainersCapacity */
, (38241, 16, 32) /* ItemUseable - Remote */
, (38241, 25, 220) /* Level */
, (38241, 93, 6292504) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity, <API key>, EdgeSlide */
, (38241, 95, 8) /* RadarBlipColor - Yellow */
, (38241, 113, 1) /* Gender - Male */
, (38241, 133, 4) /* ShowableOnRadar - ShowAlways */
, (38241, 134, 16) /* PlayerKillerStatus - RubberGlue */
, (38241, 188, 2) /* HeritageGroup - Gharundim */
, (38241, 281, 1) /* Faction1Bits */
, (38241, 287, 1001) /* SocietyRankCelhan */
, (38241, 8007, 0) /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (38241, 1, True ) /* Stuck */
, (38241, 19, False) /* Attackable */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (38241, 54, 3) /* UseRadius */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (38241, 1, 'Kaymor ibn Dumandi') /* Name */
, (38241, 5, 'High Priest Task Master') /* Template */
, (38241, 8006, 'AAA9AAAAAAA=') /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (38241, 1, 33554433) /* Setup */
, (38241, 2, 150994945) /* MotionTable */
, (38241, 3, 536870913) /* SoundTable */
, (38241, 6, 67108990) /* PaletteBase */
, (38241, 8, 100667446) /* Icon */
, (38241, 9, 83890483) /* EyesTexture */
, (38241, 10, 83890559) /* NoseTexture */
, (38241, 11, 83890601) /* MouthTexture */
, (38241, 15, 67117077) /* HairPalette */
, (38241, 16, 67109567) /* EyesPalette */
, (38241, 17, 67109553) /* SkinPalette */
, (38241, 8001, 9437238) /* <API key> - ItemsCapacity, ContainersCapacity, Usable, UseRadius, RadarBlipColor, RadarBehavior */
, (38241, 8003, 4) /* <API key> - Stuck */
, (38241, 8005, 100355) /* <API key> - CSetup, MTable, STable, Position, Movement */;
INSERT INTO `<API key>` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (38241, 8040, 11993711, 158.402, -39.5452, -17.995, -0.83954, 0, 0, 0.543297) /* <API key> */
/* @teleloc 0x00B7026F [158.402000 -39.545200 -17.995000] -0.839540 0.000000 0.000000 0.543297 */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (38241, 8000, 3359479986) /* <API key> */;
INSERT INTO `<API key>` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`)
VALUES (38241, 1, 255, 0, 0) /* Strength */
, (38241, 2, 220, 0, 0) /* Endurance */
, (38241, 3, 240, 0, 0) /* Quickness */
, (38241, 4, 240, 0, 0) /* Coordination */
, (38241, 5, 90, 0, 0) /* Focus */
, (38241, 6, 90, 0, 0) /* Self */;
INSERT INTO `<API key>` (`object_Id`, `type`, `init_Level`, `level_From_C_P`, `c_P_Spent`, `current_Level`)
VALUES (38241, 1, 125, 0, 0, 235) /* MaxHealth */
, (38241, 3, 110, 0, 0, 330) /* MaxStamina */
, (38241, 5, 55, 0, 0, 145) /* MaxMana */;
INSERT INTO `<API key>` (`object_Id`, `sub_Palette_Id`, `offset`, `length`)
VALUES (38241, 67109553, 0, 24)
, (38241, 67109567, 32, 8)
, (38241, 67110026, 136, 16)
, (38241, 67110026, 96, 12)
, (38241, 67110026, 116, 12)
, (38241, 67110347, 40, 24)
, (38241, 67110385, 160, 8)
, (38241, 67110549, 92, 4)
, (38241, 67117077, 24, 8);
INSERT INTO `<API key>` (`object_Id`, `index`, `old_Id`, `new_Id`)
VALUES (38241, 0, 83889072, 83886685)
, (38241, 0, 83889342, 83889386)
, (38241, 1, 83887064, 83886807)
, (38241, 2, 83887066, 83887051)
, (38241, 3, 83889344, 83887054)
, (38241, 4, 83887068, 83887054)
, (38241, 5, 83887064, 83886807)
, (38241, 6, 83887066, 83887051)
, (38241, 7, 83889344, 83887054)
, (38241, 8, 83887068, 83887054)
, (38241, 9, 83887061, 83886687)
, (38241, 9, 83887060, 83886686)
, (38241, 10, 83887069, 83886782)
, (38241, 10, 83886796, 83886817)
, (38241, 11, 83887067, 83891213)
, (38241, 11, 83886788, 83886802)
, (38241, 13, 83887069, 83886782)
, (38241, 13, 83886796, 83886817)
, (38241, 14, 83887067, 83891213)
, (38241, 14, 83886788, 83886802)
, (38241, 16, 83886232, 83890685)
, (38241, 16, 83886668, 83890483)
, (38241, 16, 83886837, 83890559)
, (38241, 16, 83886684, 83890601);
INSERT INTO `<API key>` (`object_Id`, `index`, `animation_Id`)
VALUES (38241, 0, 16793839)
, (38241, 1, 16781848)
, (38241, 2, 16781866)
, (38241, 3, 16781841)
, (38241, 4, 16781838)
, (38241, 5, 16781847)
, (38241, 6, 16781864)
, (38241, 7, 16781840)
, (38241, 8, 16781839)
, (38241, 9, 16793840)
, (38241, 10, 16781872)
, (38241, 11, 16781861)
, (38241, 12, 16777304)
, (38241, 13, 16781871)
, (38241, 14, 16781862)
, (38241, 15, 16777307)
, (38241, 16, 16795662);
|
package org.voltdb;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
import org.voltcore.logging.Level;
import org.voltcore.logging.VoltLogger;
import org.voltdb.<API key>.Config;
import org.voltdb.catalog.CatalogMap;
import org.voltdb.catalog.Procedure;
import org.voltdb.compiler.Language;
import org.voltdb.groovy.<API key>;
import org.voltdb.utils.LogKeys;
import com.google_voltpatches.common.collect.ImmutableMap;
public class LoadedProcedureSet {
private static final VoltLogger hostLog = new VoltLogger("HOST");
// user procedures.
ImmutableMap<String, ProcedureRunner> procs = ImmutableMap.<String, ProcedureRunner>builder().build();
// map of sysproc fragment ids to system procedures.
final HashMap<Long, ProcedureRunner> <API key> =
new HashMap<Long, ProcedureRunner>();
final <API key> m_runnerFactory;
final long m_siteId;
final int m_siteIndex;
final <API key> m_site;
public LoadedProcedureSet(<API key> site, <API key> runnerFactory, long siteId, int siteIndex) {
m_runnerFactory = runnerFactory;
m_siteId = siteId;
m_siteIndex = siteIndex;
m_site = site;
}
public ProcedureRunner getSysproc(long fragmentId) {
synchronized (<API key>) {
return <API key>.get(fragmentId);
}
}
public void <API key>(final long pfId, final ProcedureRunner proc) {
synchronized (<API key>) {
assert(<API key>.containsKey(pfId) == false);
<API key>.put(pfId, proc);
}
}
public void loadProcedures(
CatalogContext catalogContext,
BackendTarget backendTarget,
<API key> csp) {
<API key>.clear();
ImmutableMap.Builder<String, ProcedureRunner> builder =
<API key>(catalogContext, backendTarget, csp);
<API key>(catalogContext, backendTarget, csp, builder);
procs = builder.build();
}
private ImmutableMap.Builder<String, ProcedureRunner> <API key>(
CatalogContext catalogContext,
BackendTarget backendTarget,
<API key> csp) {
// load up all the stored procedures
final CatalogMap<Procedure> catalogProcedures = catalogContext.database.getProcedures();
ImmutableMap.Builder<String, ProcedureRunner> builder = ImmutableMap.<String, ProcedureRunner>builder();
for (final Procedure proc : catalogProcedures) {
// Sysprocs used to be in the catalog. Now they aren't. Ignore
// sysprocs found in old catalog versions. (PRO-365)
if (proc.getTypeName().startsWith("@")) {
continue;
}
ProcedureRunner runner = null;
VoltProcedure procedure = null;
if (proc.getHasjava()) {
final String className = proc.getClassname();
Language lang;
try {
lang = Language.valueOf(proc.getLanguage());
} catch (<API key> e) {
// default to java for earlier compiled catalogs
lang = Language.JAVA;
}
Class<?> procClass = null;
try {
procClass = catalogContext.classForProcedure(className);
}
catch (final <API key> e) {
if (className.startsWith("org.voltdb.")) {
VoltDB.crashLocalVoltDB("VoltDB does not support procedures with package names " +
"that are prefixed with \"org.voltdb\". Please use a different " +
"package name and retry. Procedure name was " + className + ".",
false, null);
}
else {
VoltDB.crashLocalVoltDB("VoltDB was unable to load a procedure (" +
className + ") it expected to be in the " +
"catalog jarfile and will now exit.", false, null);
}
}
try {
procedure = lang.accept(<API key>, procClass);
}
catch (final Exception e) {
hostLog.l7dlog( Level.WARN, LogKeys.<API key>.name(),
new Object[] { m_siteId, m_siteIndex }, e);
}
}
else {
procedure = new ProcedureRunner.StmtProcedure();
}
assert(procedure != null);
runner = m_runnerFactory.create(procedure, proc, csp);
builder.put(proc.getTypeName().intern(), runner);
}
return builder;
}
private static Language.<API key><VoltProcedure, Class<?>, Exception> <API key> =
new Language.<API key><VoltProcedure, Class<?>, Exception>() {
@Override
public VoltProcedure visitJava(Class<?> p) throws Exception {
return (VoltProcedure)p.newInstance();
}
@Override
public VoltProcedure visitGroovy(Class<?> p) throws Exception {
return new <API key>(p);
}
};
private void <API key>(
CatalogContext catalogContext,
BackendTarget backendTarget,
<API key> csp,
ImmutableMap.Builder<String, ProcedureRunner> builder) {
Set<Entry<String,Config>> entrySet = <API key>.listing.entrySet();
for (Entry<String, Config> entry : entrySet) {
Config sysProc = entry.getValue();
Procedure proc = sysProc.asCatalogProcedure();
VoltSystemProcedure procedure = null;
ProcedureRunner runner = null;
final String className = sysProc.getClassname();
Class<?> procClass = null;
// this check is for sysprocs that don't have a procedure class
if (className != null) {
try {
procClass = catalogContext.classForProcedure(className);
}
catch (final <API key> e) {
if (sysProc.commercial) {
continue;
}
hostLog.l7dlog(
Level.WARN,
LogKeys.<API key>.name(),
new Object[] { m_siteId, m_siteIndex },
e);
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
try {
procedure = (VoltSystemProcedure) procClass.newInstance();
}
catch (final <API key> e) {
hostLog.l7dlog( Level.WARN, LogKeys.<API key>.name(),
new Object[] { m_siteId, m_siteIndex }, e);
}
catch (final <API key> e) {
hostLog.l7dlog( Level.WARN, LogKeys.<API key>.name(),
new Object[] { m_siteId, m_siteIndex }, e);
}
runner = m_runnerFactory.create(procedure, proc, csp);
procedure.initSysProc(m_site, this, proc, catalogContext.cluster);
builder.put(entry.getKey().intern(), runner);
}
}
}
public ProcedureRunner getProcByName(String procName)
{
return procs.get(procName);
}
}
|
module.exports = {
organizations: require('./organizations.js'),
people: require('./people.js'),
activities: require('./activities.js'),
postProcessing: require('./post-processing.js')
};
|
package org.entcore.cursus.controllers;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import io.vertx.core.http.*;
import org.entcore.common.http.filter.ResourceFilter;
import org.entcore.common.user.UserInfos;
import org.entcore.common.user.UserUtils;
import org.entcore.common.utils.MapFactory;
import org.entcore.cursus.filters.CursusFilter;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.buffer.Buffer;
import org.vertx.java.core.http.RouteMatcher;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import fr.wseduc.rs.*;
import fr.wseduc.security.ActionType;
import fr.wseduc.security.SecuredAction;
import fr.wseduc.webutils.Either;
import fr.wseduc.webutils.http.BaseController;
public class CursusController extends BaseController {
//Service
private final CursusService service = new CursusService();
//Webservice client & endpoint
private HttpClient cursusClient;
private final URL wsEndpoint;
//Webservice auth request conf
private final JsonObject authConf;
//Auth reply data & wallets list
private Map<String, String> cursusMap;
@Override
public void init(Vertx vertx, JsonObject config, RouteMatcher rm,
Map<String, fr.wseduc.webutils.security.SecuredAction> securedActions) {
super.init(vertx, config, rm, securedActions);
HttpClientOptions cursusClientOptions = new HttpClientOptions()
.setDefaultHost(wsEndpoint.getHost());
if("https".equals(wsEndpoint.getProtocol())){
cursusClientOptions
.setSsl(true)
.setTrustAll(true)
.setDefaultPort(443);
} else {
cursusClientOptions
.setDefaultPort(wsEndpoint.getPort() == -1 ? 80 : wsEndpoint.getPort());
}
cursusClient = vertx.createHttpClient(cursusClientOptions);
cursusMap = MapFactory.getSyncClusterMap("cursusMap", vertx, false);
/*
service.refreshToken(new Handler<Boolean>() {
public void handle(Boolean res) {
if(!res)
log.error("[Cursus][refreshToken] Error while retrieving the Token.");
else
log.info("[Cursus][refreshToken] Token refreshed.");
}
});
*/
if(cursusMap.containsKey("wallets"))
return;
service.refreshWallets(new Handler<Boolean>() {
public void handle(Boolean res) {
if(!res)
log.error("[Cursus][refreshWallets] Error while retrieving the wallets list.");
else
log.info("[Cursus][refreshWallets] Wallets list refreshed.");
}
});
}
public CursusController(URL endpoint, final JsonObject conf){
wsEndpoint = endpoint;
authConf = conf;
}
@Put("/refreshToken")
@SecuredAction(value = "", type = ActionType.RESOURCE)
@ResourceFilter(CursusFilter.class)
public void refreshToken(final HttpServerRequest request){
service.refreshToken(new Handler<Boolean>() {
public void handle(Boolean success) {
if(success){
ok(request);
} else {
badRequest(request);
}
}
});
}
@Put("/refreshWallets")
@SecuredAction(value = "", type = ActionType.RESOURCE)
@ResourceFilter(CursusFilter.class)
public void refreshWallets(final HttpServerRequest request){
service.refreshWallets(new Handler<Boolean>() {
public void handle(Boolean success) {
if(success){
ok(request);
} else {
badRequest(request);
}
}
});
}
@Get("/sales")
@SecuredAction(value = "", type = ActionType.AUTHENTICATED)
public void getSales(final HttpServerRequest request){
final String cardNb = request.params().get("cardNb");
if(cardNb == null){
badRequest(request);
return;
}
service.getUserInfo(cardNb, new Handler<Either<String,JsonArray>>() {
public void handle(Either<String, JsonArray> result) {
if(result.isLeft()){
badRequest(request);
return;
}
final String id = result.right().getValue().getJsonObject(0).getInteger("id").toString();
String birthDateEncoded = result.right().getValue().getJsonObject(0).getString("dateNaissance");
try {
birthDateEncoded = birthDateEncoded.replace("/Date(", "");
birthDateEncoded = birthDateEncoded.substring(0, birthDateEncoded.indexOf("+"));
final Date birthDate = new Date(Long.parseLong(birthDateEncoded));
UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() {
public void handle(UserInfos infos) {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
try {
Date sessionBirthDate = format.parse(infos.getBirthDate());
if(sessionBirthDate.compareTo(birthDate) == 0){
service.getSales(id, cardNb, new Handler<Either<String,JsonArray>>() {
public void handle(Either<String, JsonArray> result) {
if(result.isLeft()){
badRequest(request);
return;
}
JsonObject finalResult = new JsonObject()
.put("wallets", new JsonArray(cursusMap.get("wallets")))
.put("sales", result.right().getValue());
renderJson(request, finalResult);
}
});
} else {
badRequest(request);
}
} catch (ParseException e) {
badRequest(request);
return;
}
}
});
} catch(Exception e){
badRequest(request);
}
}
});
}
/**
* Inner service class.
*/
private class CursusService{
public void authWrapper(final Handler<Boolean> handler){
JsonObject authObject = new JsonObject();
if(cursusMap.get("auth") != null)
authObject = new JsonObject(cursusMap.get("auth"));
Long currentDate = Calendar.getInstance().getTimeInMillis();
Long expirationDate = 0l;
if(authObject != null)
expirationDate = authObject.getLong("tokenInit", 0l) + authConf.getLong("tokenDelay", 1800000l);
if(expirationDate < currentDate){
log.info("[Cursus] Token seems to have expired.");
refreshToken(handler);
} else {
handler.handle(true);
}
}
public void refreshToken(final Handler<Boolean> handler){
HttpClientRequest req = cursusClient.post(wsEndpoint.getPath() + "/<API key>.svc/json/<API key>, new Handler<HttpClientResponse>() {
public void handle(HttpClientResponse response) {
if(response.statusCode() >= 300){
handler.handle(false);
log.error(response.statusMessage());
return;
}
response.bodyHandler(new Handler<Buffer>() {
public void handle(Buffer body) {
log.info("[Cursus][refreshToken] Token refreshed.");
JsonObject authData = new JsonObject(body.toString());
authData.put("tokenInit", new Date().getTime());
cursusMap.put("auth", authData.encode());
handler.handle(true);
}
});
}
});
req.putHeader(HttpHeaders.ACCEPT, "application/json; charset=UTF-8")
.putHeader(HttpHeaders.CONTENT_TYPE, "application/json");
req.end(authConf.encode());
}
public void refreshWallets(final Handler<Boolean> handler){
authWrapper(new Handler<Boolean>() {
public void handle(Boolean gotToken) {
if(!gotToken){
handler.handle(false);
return;
}
int schoolYear = Calendar.getInstance().get(Calendar.MONTH) < 8 ?
Calendar.getInstance().get(Calendar.YEAR) - 1 :
Calendar.getInstance().get(Calendar.YEAR);
/* JSON */
JsonObject reqBody = new JsonObject();
reqBody
.put("numSite", authConf.getString("numSite"))
.put("tokenId", new JsonObject(cursusMap.get("auth")).getString("tokenId"))
.put("typeListes", new JsonArray()
.add(new JsonObject()
.put("typeListe", "LST_PORTEMONNAIE")
.put("param1", schoolYear + "-" + (schoolYear + 1))
)
);
|
<!DOCTYPE HTML PUBLIC "-
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_71) on Fri Jul 10 16:43:22 IST 2015 -->
<title>Uses of Interface com.ephesoft.gxt.core.shared.dto.propertyAccessors.<API key></title>
<meta name="date" content="2015-07-10">
<link rel="stylesheet" type="text/css" href="../../../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface com.ephesoft.gxt.core.shared.dto.propertyAccessors.<API key>";
}
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<div class="topNav"><a name="navbar_top">
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/<API key>.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?com/ephesoft/gxt/core/shared/dto/propertyAccessors/class-use/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.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>
<a name="skip-navbar_top">
</a></div>
<div class="header">
<h2 title="Uses of Interface com.ephesoft.gxt.core.shared.dto.propertyAccessors.<API key>" class="title">Uses of Interface<br>com.ephesoft.gxt.core.shared.dto.propertyAccessors.<API key></h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/<API key>.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors"><API key></a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.ephesoft.gxt.core.shared.dto.propertyAccessors">com.ephesoft.gxt.core.shared.dto.propertyAccessors</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.ephesoft.gxt.core.shared.dto.propertyAccessors">
</a>
<h3>Uses of <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/<API key>.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors"><API key></a> in <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/package-summary.html">com.ephesoft.gxt.core.shared.dto.propertyAccessors</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/package-summary.html">com.ephesoft.gxt.core.shared.dto.propertyAccessors</a> declared as <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/<API key>.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors"><API key></a></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>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/<API key>.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors"><API key></a></code></td>
<td class="colLast"><span class="strong"><API key>.</span><code><strong><a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/<API key>.html#properties">properties</a></strong></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="bottomNav"><a name="navbar_bottom">
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="<API key>">
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../../../com/ephesoft/gxt/core/shared/dto/propertyAccessors/<API key>.html" title="interface in com.ephesoft.gxt.core.shared.dto.propertyAccessors">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../../../index.html?com/ephesoft/gxt/core/shared/dto/propertyAccessors/class-use/<API key>.html" target="_top">Frames</a></li>
<li><a href="<API key>.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>
<a name="skip-navbar_bottom">
</a></div>
</body>
</html>
|
#ifndef <API key>
# define <API key>
# include <boost/python/detail/cv_category.hpp>
# include <boost/python/detail/indirect_traits.hpp>
# include <boost/type_traits/object_traits.hpp>
namespace abt_boost{} namespace boost = abt_boost; namespace abt_boost{ namespace python { namespace detail {
#ifndef _MSC_VER //if forward declared, msvc6.5 does not recognize them as inline
// forward declaration, required (at least) by Tru64 cxx V6.5-042
template <class Generator, class U>
inline typename Generator::result_type
unwind_type(U const& p, Generator* = 0);
// forward declaration, required (at least) by Tru64 cxx V6.5-042
template <class Generator, class U>
inline typename Generator::result_type
unwind_type(abt_boost::type<U>*p = 0, Generator* = 0);
#endif
template <class Generator, class U>
inline typename Generator::result_type
unwind_type_cv(U* p, cv_unqualified, Generator* = 0)
{
return Generator::execute(p);
}
template <class Generator, class U>
inline typename Generator::result_type
unwind_type_cv(U const* p, const_, Generator* = 0)
{
return unwind_type(const_cast<U*>(p), (Generator*)0);
}
template <class Generator, class U>
inline typename Generator::result_type
unwind_type_cv(U volatile* p, volatile_, Generator* = 0)
{
return unwind_type(const_cast<U*>(p), (Generator*)0);
}
template <class Generator, class U>
inline typename Generator::result_type
unwind_type_cv(U const volatile* p, const_volatile_, Generator* = 0)
{
return unwind_type(const_cast<U*>(p), (Generator*)0);
}
template <class Generator, class U>
inline typename Generator::result_type
unwind_ptr_type(U* p, Generator* = 0)
{
typedef typename cv_category<U>::type tag;
return unwind_type_cv<Generator>(p, tag());
}
template <bool is_ptr>
struct unwind_helper
{
template <class Generator, class U>
static typename Generator::result_type
execute(U p, Generator* = 0)
{
return unwind_ptr_type(p, (Generator*)0);
}
};
template <>
struct unwind_helper<false>
{
template <class Generator, class U>
static typename Generator::result_type
execute(U& p, Generator* = 0)
{
return unwind_ptr_type(&p, (Generator*)0);
}
};
template <class Generator, class U>
inline typename Generator::result_type
#ifndef _MSC_VER
unwind_type(U const& p, Generator*)
#else
unwind_type(U const& p, Generator* = 0)
#endif
{
return unwind_helper<is_pointer<U>::value>::execute(p, (Generator*)0);
}
enum { direct_ = 0, pointer_ = 1, reference_ = 2, <API key> = 3 };
template <int indirection> struct unwind_helper2;
template <>
struct unwind_helper2<direct_>
{
template <class Generator, class U>
static typename Generator::result_type
execute(U(*)(), Generator* = 0)
{
return unwind_ptr_type((U*)0, (Generator*)0);
}
};
template <>
struct unwind_helper2<pointer_>
{
template <class Generator, class U>
static typename Generator::result_type
execute(U*(*)(), Generator* = 0)
{
return unwind_ptr_type((U*)0, (Generator*)0);
}
};
template <>
struct unwind_helper2<reference_>
{
template <class Generator, class U>
static typename Generator::result_type
execute(U&(*)(), Generator* = 0)
{
return unwind_ptr_type((U*)0, (Generator*)0);
}
};
template <>
struct unwind_helper2<<API key>>
{
template <class Generator, class U>
static typename Generator::result_type
execute(U&(*)(), Generator* = 0)
{
return unwind_ptr_type(U(0), (Generator*)0);
}
};
// Call this one with both template parameters explicitly specified
// and no function arguments:
// return unwind_type<my_generator,T>();
// Doesn't work if T is an array type; we could handle that case, but
// why bother?
template <class Generator, class U>
inline typename Generator::result_type
#ifndef _MSC_VER
unwind_type(abt_boost::type<U>*, Generator*)
#else
unwind_type(abt_boost::type<U>*p =0, Generator* =0)
#endif
{
<API key>(int, indirection
= (abt_boost::is_pointer<U>::value ? pointer_ : 0)
+ (indirect_traits::<API key><U>::value
? <API key>
: abt_boost::is_reference<U>::value
? reference_
: 0));
return unwind_helper2<indirection>::execute((U(*)())0,(Generator*)0);
}
}}} // namespace abt_boost::python::detail
#endif // <API key>
|
class Api::AccountsController < ApiController
def index
@accounts = current_user.accounts
respond_with(@accounts)
end
def show
find_account!
respond_with(@account)
end
def update
find_account!
@account.update(account_params)
respond_with(@account)
end
private
def find_account!
@account = Account.find_by!(id: params.fetch(:id))
authorize! AccountReadPolicy.new(@account, current_user)
end
def account_params
params.permit(:name, :website_url, :webhook_url, :prefers_archiving)
end
end
|
define(['sylvester', 'sha1', 'PrairieGeom'], function (Sylvester, Sha1, PrairieGeom) {
var $V = Sylvester.Vector.create;
var Vector = Sylvester.Vector;
var Matrix = Sylvester.Matrix;
/** Creates a PrairieDraw object.
@constructor
@this {PrairieDraw}
@param {HTMLCanvasElement or string} canvas The canvas element to draw on or the ID of the canvas elemnt.
@param {Function} drawfcn An optional function that draws on the canvas.
*/
function PrairieDraw(canvas, drawFcn) {
if (canvas) {
if (canvas instanceof HTMLCanvasElement) {
this._canvas = canvas;
} else if (canvas instanceof String || typeof canvas === 'string') {
this._canvas = document.getElementById(canvas);
} else {
//throw new Error("PrairieDraw: unknown object type for constructor")
this._canvas = undefined;
}
if (this._canvas) {
this._canvas.prairieDraw = this;
this._ctx = this._canvas.getContext('2d');
if (this._ctx.setLineDash === undefined) {
this._ctx.setLineDash = function () {};
}
this._width = this._canvas.width;
this._height = this._canvas.height;
this._trans = Matrix.I(3);
this._transStack = [];
this._initViewAngleX3D = (-Math.PI / 2) * 0.75;
this._initViewAngleY3D = 0;
this._initViewAngleZ3D = (-Math.PI / 2) * 1.25;
this._viewAngleX3D = this._initViewAngleX3D;
this._viewAngleY3D = this._initViewAngleY3D;
this._viewAngleZ3D = this._initViewAngleZ3D;
this._trans3D = PrairieGeom.rotateTransform3D(
Matrix.I(4),
this._initViewAngleX3D,
this._initViewAngleY3D,
this._initViewAngleZ3D
);
this._trans3DStack = [];
this._props = {};
this._initProps();
this._propStack = [];
this._options = {};
this._history = {};
this._images = {};
this._redrawCallbacks = [];
if (drawFcn) {
this.draw = drawFcn.bind(this);
}
this.save();
this.draw();
this.restoreAll();
}
}
}
/** Creates a new PrairieDraw from a canvas ID.
@param {string} id The ID of the canvas element to draw on.
@return {PrairieDraw} The new PrairieDraw object.
*/
PrairieDraw.fromCanvasId = function (id) {
var canvas = document.getElementById(id);
if (!canvas) {
throw new Error('PrairieDraw: unable to find canvas ID: ' + id);
}
return new PrairieDraw(canvas);
};
/** Prototype function to draw on the canvas, should be implemented by children.
*/
PrairieDraw.prototype.draw = function () {};
/** Redraw the drawing.
*/
PrairieDraw.prototype.redraw = function () {
this.save();
this.draw();
this.restoreAll();
for (var i = 0; i < this._redrawCallbacks.length; i++) {
this._redrawCallbacks[i]();
}
};
/** Add a callback on redraw() calls.
*/
PrairieDraw.prototype.<API key> = function (callback) {
this._redrawCallbacks.push(callback.bind(this));
};
/** @private Initialize properties.
*/
PrairieDraw.prototype._initProps = function () {
this._props.viewAngleXMin = -Math.PI / 2 + 1e-6;
this._props.viewAngleXMax = -1e-6;
this._props.viewAngleYMin = -Infinity;
this._props.viewAngleYMax = Infinity;
this._props.viewAngleZMin = -Infinity;
this._props.viewAngleZMax = Infinity;
this._props.arrowLineWidthPx = 2;
this._props.arrowLinePattern = 'solid';
this._props.<API key> = 7; // arrowheadLength / arrowLineWidth
this._props.arrowheadWidthRatio = 0.3; // arrowheadWidth / arrowheadLength
this._props.<API key> = 0.3; // arrowheadOffset / arrowheadLength
this._props.<API key> = 1.5;
this._props.<API key> = 5;
this._props.textOffsetPx = 4;
this._props.textFontSize = 14;
this._props.pointRadiusPx = 2;
this._props.shapeStrokeWidthPx = 2;
this._props.shapeStrokePattern = 'solid';
this._props.shapeOutlineColor = 'rgb(0, 0, 0)';
this._props.shapeInsideColor = 'rgb(255, 255, 255)';
this._props.hiddenLineDraw = true;
this._props.hiddenLineWidthPx = 2;
this._props.hiddenLinePattern = 'dashed';
this._props.hiddenLineColor = 'rgb(0, 0, 0)';
this._props.<API key> = 2;
this._props.centerOfMassColor = 'rgb(180, 49, 4)';
this._props.<API key> = 5;
this._props.rightAngleSizePx = 10;
this._props.<API key> = 1;
this._props.rightAngleColor = 'rgb(0, 0, 0)';
this._props.<API key> = 1;
this._props.<API key> = 'solid';
this._props.<API key> = 10;
this._props.measurementOffsetPx = 3;
this._props.measurementColor = 'rgb(0, 0, 0)';
this._props.groundDepthPx = 10;
this._props.groundWidthPx = 10;
this._props.groundSpacingPx = 10;
this._props.groundOutlineColor = 'rgb(0, 0, 0)';
this._props.groundInsideColor = 'rgb(220, 220, 220)';
this._props.gridColor = 'rgb(200, 200, 200)';
this._props.positionColor = 'rgb(0, 0, 255)';
this._props.angleColor = 'rgb(0, 100, 180)';
this._props.velocityColor = 'rgb(0, 200, 0)';
this._props.angVelColor = 'rgb(100, 180, 0)';
this._props.accelerationColor = 'rgb(255, 0, 255)';
this._props.rotationColor = 'rgb(150, 0, 150)';
this._props.angAccColor = 'rgb(100, 0, 180)';
this._props.angMomColor = 'rgb(255, 0, 0)';
this._props.forceColor = 'rgb(210, 105, 30)';
this._props.momentColor = 'rgb(255, 102, 80)';
};
/** The golden ratio.
*/
PrairieDraw.prototype.goldenRatio = (1 + Math.sqrt(5)) / 2;
/** Get the canvas width.
@return {number} The canvas width in Px.
*/
PrairieDraw.prototype.widthPx = function () {
return this._width;
};
/** Get the canvas height.
@return {number} The canvas height in Px.
*/
PrairieDraw.prototype.heightPx = function () {
return this._height;
};
/** Conversion constants.
*/
PrairieDraw.prototype.milesPerKilometer = 0.621371;
/** Scale the coordinate system.
@param {Vector} factor Scale factors.
*/
PrairieDraw.prototype.scale = function (factor) {
this._trans = PrairieGeom.scaleTransform(this._trans, factor);
};
/** Translate the coordinate system.
@param {Vector} offset Translation offset (drawing coords).
*/
PrairieDraw.prototype.translate = function (offset) {
this._trans = PrairieGeom.translateTransform(this._trans, offset);
};
/** Rotate the coordinate system.
@param {number} angle Angle to rotate by (radians).
*/
PrairieDraw.prototype.rotate = function (angle) {
this._trans = PrairieGeom.rotateTransform(this._trans, angle);
};
/** Transform the coordinate system (scale, translate, rotate) to
match old points to new. Drawing at the old locations will result
in points at the new locations.
@param {Vector} old1 The old location of point 1.
@param {Vector} old2 The old location of point 2.
@param {Vector} new1 The new location of point 1.
@param {Vector} new2 The new location of point 2.
*/
PrairieDraw.prototype.transformByPoints = function (old1, old2, new1, new2) {
this._trans = PrairieGeom.<API key>(this._trans, old1, old2, new1, new2);
};
/** Transform a vector from drawing to pixel coords.
@param {Vector} vDw Vector in drawing coords.
@return {Vector} Vector in pixel coords.
*/
PrairieDraw.prototype.vec2Px = function (vDw) {
return PrairieGeom.transformVec(this._trans, vDw);
};
/** Transform a position from drawing to pixel coords.
@param {Vector} pDw Position in drawing coords.
@return {Vector} Position in pixel coords.
*/
PrairieDraw.prototype.pos2Px = function (pDw) {
return PrairieGeom.transformPos(this._trans, pDw);
};
/** Transform a vector from pixel to drawing coords.
@param {Vector} vPx Vector in pixel coords.
@return {Vector} Vector in drawing coords.
*/
PrairieDraw.prototype.vec2Dw = function (vPx) {
return PrairieGeom.transformVec(this._trans.inverse(), vPx);
};
/** Transform a position from pixel to drawing coords.
@param {Vector} pPx Position in pixel coords.
@return {Vector} Position in drawing coords.
*/
PrairieDraw.prototype.pos2Dw = function (pPx) {
return PrairieGeom.transformPos(this._trans.inverse(), pPx);
};
/** @private Returns true if the current transformation is a reflection.
@return {bool} Whether the current transformation is a reflection.
*/
PrairieDraw.prototype._transIsReflection = function () {
var det = this._trans.e(1, 1) * this._trans.e(2, 2) - this._trans.e(1, 2) * this._trans.e(2, 1);
if (det < 0) {
return true;
} else {
return false;
}
};
/** Transform a position from normalized viewport [0,1] to drawing coords.
@param {Vector} pNm Position in normalized viewport coordinates.
@return {Vector} Position in drawing coordinates.
*/
PrairieDraw.prototype.posNm2Dw = function (pNm) {
var pPx = this.posNm2Px(pNm);
return this.pos2Dw(pPx);
};
/** Transform a position from normalized viewport [0,1] to pixel coords.
@param {Vector} pNm Position in normalized viewport coords.
@return {Vector} Position in pixel coords.
*/
PrairieDraw.prototype.posNm2Px = function (pNm) {
return $V([pNm.e(1) * this._width, (1 - pNm.e(2)) * this._height]);
};
/** Set the 3D view to the given angles.
@param {number} angleX The rotation angle about the X axis.
@param {number} angleY The rotation angle about the Y axis.
@param {number} angleZ The rotation angle about the Z axis.
@param {bool} clip (Optional) Whether to clip to max/min range (default: true).
@param {bool} redraw (Optional) Whether to redraw (default: true).
*/
PrairieDraw.prototype.setView3D = function (angleX, angleY, angleZ, clip, redraw) {
clip = clip === undefined ? true : clip;
redraw = redraw === undefined ? true : redraw;
this._viewAngleX3D = angleX;
this._viewAngleY3D = angleY;
this._viewAngleZ3D = angleZ;
if (clip) {
this._viewAngleX3D = PrairieGeom.clip(
this._viewAngleX3D,
this._props.viewAngleXMin,
this._props.viewAngleXMax
);
this._viewAngleY3D = PrairieGeom.clip(
this._viewAngleY3D,
this._props.viewAngleYMin,
this._props.viewAngleYMax
);
this._viewAngleZ3D = PrairieGeom.clip(
this._viewAngleZ3D,
this._props.viewAngleZMin,
this._props.viewAngleZMax
);
}
this._trans3D = PrairieGeom.rotateTransform3D(
Matrix.I(4),
this._viewAngleX3D,
this._viewAngleY3D,
this._viewAngleZ3D
);
if (redraw) {
this.redraw();
}
};
/** Reset the 3D view to default.
@param {bool} redraw (Optional) Whether to redraw (default: true).
*/
PrairieDraw.prototype.resetView3D = function (redraw) {
this.setView3D(
this._initViewAngleX3D,
this._initViewAngleY3D,
this._initViewAngleZ3D,
undefined,
redraw
);
};
/** Increment the 3D view by the given angles.
@param {number} deltaAngleX The incremental rotation angle about the X axis.
@param {number} deltaAngleY The incremental rotation angle about the Y axis.
@param {number} deltaAngleZ The incremental rotation angle about the Z axis.
@param {bool} clip (Optional) Whether to clip to max/min range (default: true).
*/
PrairieDraw.prototype.incrementView3D = function (deltaAngleX, deltaAngleY, deltaAngleZ, clip) {
this.setView3D(
this._viewAngleX3D + deltaAngleX,
this._viewAngleY3D + deltaAngleY,
this._viewAngleZ3D + deltaAngleZ,
clip
);
};
/** Scale the 3D coordinate system.
@param {Vector} factor Scale factor.
*/
PrairieDraw.prototype.scale3D = function (factor) {
this._trans3D = PrairieGeom.scaleTransform3D(this._trans3D, factor);
};
/** Translate the 3D coordinate system.
@param {Vector} offset Translation offset.
*/
PrairieDraw.prototype.translate3D = function (offset) {
this._trans3D = PrairieGeom.<API key>(this._trans3D, offset);
};
/** Rotate the 3D coordinate system.
@param {number} angleX Angle to rotate by around the X axis (radians).
@param {number} angleY Angle to rotate by around the Y axis (radians).
@param {number} angleZ Angle to rotate by around the Z axis (radians).
*/
PrairieDraw.prototype.rotate3D = function (angleX, angleY, angleZ) {
this._trans3D = PrairieGeom.rotateTransform3D(this._trans3D, angleX, angleY, angleZ);
};
/** Transform a position to the view coordinates in 3D.
@param {Vector} pDw Position in 3D drawing coords.
@return {Vector} Position in 3D viewing coords.
*/
PrairieDraw.prototype.posDwToVw = function (pDw) {
var pVw = PrairieGeom.transformPos3D(this._trans3D, pDw);
return pVw;
};
/** Transform a position from the view coordinates in 3D.
@param {Vector} pVw Position in 3D viewing coords.
@return {Vector} Position in 3D drawing coords.
*/
PrairieDraw.prototype.posVwToDw = function (pVw) {
var pDw = PrairieGeom.transformPos3D(this._trans3D.inverse(), pVw);
return pDw;
};
/** Transform a vector to the view coordinates in 3D.
@param {Vector} vDw Vector in 3D drawing coords.
@return {Vector} Vector in 3D viewing coords.
*/
PrairieDraw.prototype.vecDwToVw = function (vDw) {
var vVw = PrairieGeom.transformVec3D(this._trans3D, vDw);
return vVw;
};
/** Transform a vector from the view coordinates in 3D.
@param {Vector} vVw Vector in 3D viewing coords.
@return {Vector} Vector in 3D drawing coords.
*/
PrairieDraw.prototype.vecVwToDw = function (vVw) {
var vDw = PrairieGeom.transformVec3D(this._trans3D.inverse(), vVw);
return vDw;
};
/** Transform a position from 3D to 2D drawing coords if necessary.
@param {Vector} pDw Position in 2D or 3D drawing coords.
@return {Vector} Position in 2D drawing coords.
*/
PrairieDraw.prototype.pos3To2 = function (pDw) {
if (pDw.elements.length === 3) {
return PrairieGeom.orthProjPos3D(this.posDwToVw(pDw));
} else {
return pDw;
}
};
/** Transform a vector from 3D to 2D drawing coords if necessary.
@param {Vector} vDw Vector in 2D or 3D drawing coords.
@param {Vector} pDw Base point of vector (if in 3D).
@return {Vector} Vector in 2D drawing coords.
*/
PrairieDraw.prototype.vec3To2 = function (vDw, pDw) {
if (vDw.elements.length === 3) {
var qDw = pDw.add(vDw);
var p2Dw = this.pos3To2(pDw);
var q2Dw = this.pos3To2(qDw);
var v2Dw = q2Dw.subtract(p2Dw);
return v2Dw;
} else {
return vDw;
}
};
/** Transform a position from 2D to 3D drawing coords if necessary (adding z = 0).
@param {Vector} pDw Position in 2D or 3D drawing coords.
@return {Vector} Position in 3D drawing coords.
*/
PrairieDraw.prototype.pos2To3 = function (pDw) {
if (pDw.elements.length === 2) {
return $V([pDw.e(1), pDw.e(2), 0]);
} else {
return pDw;
}
};
/** Transform a vector from 2D to 3D drawing coords if necessary (adding z = 0).
@param {Vector} vDw Vector in 2D or 3D drawing coords.
@return {Vector} Vector in 3D drawing coords.
*/
PrairieDraw.prototype.vec2To3 = function (vDw) {
if (vDw.elements.length === 2) {
return $V([vDw.e(1), vDw.e(2), 0]);
} else {
return vDw;
}
};
/** Set a property.
@param {string} name The name of the property.
@param {number} value The value to set the property to.
*/
PrairieDraw.prototype.setProp = function (name, value) {
if (!(name in this._props)) {
throw new Error('PrairieDraw: unknown property name: ' + name);
}
this._props[name] = value;
};
/** Get a property.
@param {string} name The name of the property.
@return {number} The current value of the property.
*/
PrairieDraw.prototype.getProp = function (name) {
if (!(name in this._props)) {
throw new Error('PrairieDraw: unknown property name: ' + name);
}
return this._props[name];
};
/** @private Colors.
*/
PrairieDraw._colors = {
black: 'rgb(0, 0, 0)',
white: 'rgb(255, 255, 255)',
red: 'rgb(255, 0, 0)',
green: 'rgb(0, 255, 0)',
blue: 'rgb(0, 0, 255)',
cyan: 'rgb(0, 255, 255)',
magenta: 'rgb(255, 0, 255)',
yellow: 'rgb(255, 255, 0)',
};
/** @private Get a color property for a given type.
@param {string} type Optional type to find the color for.
*/
PrairieDraw.prototype._getColorProp = function (type) {
if (type === undefined) {
return this._props.shapeOutlineColor;
}
var col = type + 'Color';
if (col in this._props) {
var c = this._props[col];
if (c in PrairieDraw._colors) {
return PrairieDraw._colors[c];
} else {
return c;
}
} else if (type in PrairieDraw._colors) {
return PrairieDraw._colors[type];
} else {
return type;
}
};
/** @private Set shape drawing properties for drawing hidden lines.
*/
PrairieDraw.prototype.setShapeDrawHidden = function () {
this._props.shapeStrokeWidthPx = this._props.hiddenLineWidthPx;
this._props.shapeStrokePattern = this._props.hiddenLinePattern;
this._props.shapeOutlineColor = this._props.hiddenLineColor;
};
/** Add an external option for this drawing.
@param {string} name The option name.
@param {object} value The default initial value.
*/
PrairieDraw.prototype.addOption = function (name, value, triggerRedraw) {
if (!(name in this._options)) {
this._options[name] = {
value: value,
resetValue: value,
callbacks: {},
triggerRedraw: triggerRedraw === undefined ? true : triggerRedraw,
};
} else if (!('value' in this._options[name])) {
var option = this._options[name];
option.value = value;
option.resetValue = value;
for (var p in option.callbacks) {
option.callbacks[p](option.value);
}
}
};
/** Set an option to a given value.
@param {string} name The option name.
@param {object} value The new value for the option.
@param {bool} redraw (Optional) Whether to trigger a redraw() (default: true).
@param {Object} trigger (Optional) The object that triggered the change.
@param {bool} setReset (Optional) Also set this value to be the new reset value (default: false).
*/
PrairieDraw.prototype.setOption = function (name, value, redraw, trigger, setReset) {
redraw = redraw === undefined ? true : redraw;
setReset = setReset === undefined ? false : setReset;
if (!(name in this._options)) {
throw new Error('PrairieDraw: unknown option: ' + name);
}
var option = this._options[name];
option.value = value;
if (setReset) {
option.resetValue = value;
}
for (var p in option.callbacks) {
option.callbacks[p](option.value, trigger);
}
if (redraw) {
this.redraw();
}
};
/** Get the value of an option.
@param {string} name The option name.
@return {object} The current value for the option.
*/
PrairieDraw.prototype.getOption = function (name) {
if (!(name in this._options)) {
throw new Error('PrairieDraw: unknown option: ' + name);
}
if (!('value' in this._options[name])) {
throw new Error('PrairieDraw: option has no value: ' + name);
}
return this._options[name].value;
};
/** Set an option to the logical negation of its current value.
@param {string} name The option name.
*/
PrairieDraw.prototype.toggleOption = function (name) {
if (!(name in this._options)) {
throw new Error('PrairieDraw: unknown option: ' + name);
}
if (!('value' in this._options[name])) {
throw new Error('PrairieDraw: option has no value: ' + name);
}
var option = this._options[name];
option.value = !option.value;
for (var p in option.callbacks) {
option.callbacks[p](option.value);
}
this.redraw();
};
/** Register a callback on option changes.
@param {string} name The option to register on.
@param {Function} callback The callback(value) function.
@param {string} callbackID (Optional) The ID of the callback. If omitted, a new unique ID will be generated.
*/
PrairieDraw.prototype.<API key> = function (name, callback, callbackID) {
if (!(name in this._options)) {
throw new Error('PrairieDraw: unknown option: ' + name);
}
var option = this._options[name];
var useID;
if (callbackID === undefined) {
var nextIDNumber = 0,
curIDNumber;
for (var p in option.callbacks) {
curIDNumber = parseInt(p, 10);
if (isFinite(curIDNumber)) {
nextIDNumber = Math.max(nextIDNumber, curIDNumber + 1);
}
}
useID = nextIDNumber.toString();
} else {
useID = callbackID;
}
option.callbacks[useID] = callback.bind(this);
option.callbacks[useID](option.value);
};
/** Clear the value for the given option.
@param {string} name The option to clear.
*/
PrairieDraw.prototype.clearOptionValue = function (name) {
if (!(name in this._options)) {
throw new Error('PrairieDraw: unknown option: ' + name);
}
if ('value' in this._options[name]) {
delete this._options[name].value;
}
this.redraw();
};
/** Reset the value for the given option.
@param {string} name The option to reset.
*/
PrairieDraw.prototype.resetOptionValue = function (name) {
if (!(name in this._options)) {
throw new Error('PrairieDraw: unknown option: ' + name);
}
var option = this._options[name];
if (!('resetValue' in option)) {
throw new Error('PrairieDraw: option has no resetValue: ' + name);
}
option.value = option.resetValue;
for (var p in option.callbacks) {
option.callbacks[p](option.value);
}
};
/** Save the graphics state (properties, options, and transformations).
@see restore().
*/
PrairieDraw.prototype.save = function () {
this._ctx.save();
var oldProps = {};
for (var p in this._props) {
oldProps[p] = this._props[p];
}
this._propStack.push(oldProps);
this._transStack.push(this._trans.dup());
this._trans3DStack.push(this._trans3D.dup());
};
/** Restore the graphics state (properties, options, and transformations).
@see save().
*/
PrairieDraw.prototype.restore = function () {
this._ctx.restore();
if (this._propStack.length === 0) {
throw new Error('PrairieDraw: tried to restore() without corresponding save()');
}
if (this._propStack.length !== this._transStack.length) {
throw new Error('PrairieDraw: incompatible save stack lengths');
}
if (this._propStack.length !== this._trans3DStack.length) {
throw new Error('PrairieDraw: incompatible save stack lengths');
}
this._props = this._propStack.pop();
this._trans = this._transStack.pop();
this._trans3D = this._trans3DStack.pop();
};
/** Restore all outstanding saves.
*/
PrairieDraw.prototype.restoreAll = function () {
while (this._propStack.length > 0) {
this.restore();
}
if (this._saveTrans !== undefined) {
this._trans = this._saveTrans;
}
};
/** Reset the canvas image and drawing context.
*/
PrairieDraw.prototype.clearDrawing = function () {
this._ctx.clearRect(0, 0, this._width, this._height);
};
/** Reset everything to the intial state.
*/
PrairieDraw.prototype.reset = function () {
for (var optionName in this._options) {
this.resetOptionValue(optionName);
}
this.resetView3D(false);
this.redraw();
};
/** Stop all action and computation.
*/
PrairieDraw.prototype.stop = function () {};
/** Set the visable coordinate sizes.
@param {number} xSize The horizontal size of the drawing area in coordinate units.
@param {number} ySize The vertical size of the drawing area in coordinate units.
@param {number} canvasWidth (Optional) The width of the canvas in px.
@param {bool} preserveCanvasSize (Optional) If true, do not resize the canvas to match the coordinate ratio.
*/
PrairieDraw.prototype.setUnits = function (xSize, ySize, canvasWidth, preserveCanvasSize) {
this.clearDrawing();
this._trans = Matrix.I(3);
if (canvasWidth !== undefined) {
var canvasHeight = Math.floor((ySize / xSize) * canvasWidth);
if (this._width !== canvasWidth || this._height !== canvasHeight) {
this._canvas.width = canvasWidth;
this._canvas.height = canvasHeight;
this._width = canvasWidth;
this._height = canvasHeight;
}
preserveCanvasSize = true;
}
var xScale = this._width / xSize;
var yScale = this._height / ySize;
if (xScale < yScale) {
this._scale = xScale;
if (!preserveCanvasSize && xScale !== yScale) {
var newHeight = xScale * ySize;
this._canvas.height = newHeight;
this._height = newHeight;
}
this.translate($V([this._width / 2, this._height / 2]));
this.scale($V([1, -1]));
this.scale($V([xScale, xScale]));
} else {
this._scale = yScale;
if (!preserveCanvasSize && xScale !== yScale) {
var newWidth = yScale * xSize;
this._canvas.width = newWidth;
this._width = newWidth;
}
this.translate($V([this._width / 2, this._height / 2]));
this.scale($V([1, -1]));
this.scale($V([yScale, yScale]));
}
this._saveTrans = this._trans;
};
/** Draw a point.
@param {Vector} posDw Position of the point (drawing coords).
*/
PrairieDraw.prototype.point = function (posDw) {
posDw = this.pos3To2(posDw);
var posPx = this.pos2Px(posDw);
this._ctx.beginPath();
this._ctx.arc(posPx.e(1), posPx.e(2), this._props.pointRadiusPx, 0, 2 * Math.PI);
this._ctx.fillStyle = this._props.shapeOutlineColor;
this._ctx.fill();
};
/** @private Set the stroke/fill styles for drawing lines.
@param {string} type The type of line being drawn.
*/
PrairieDraw.prototype._setLineStyles = function (type) {
var col = this._getColorProp(type);
this._ctx.strokeStyle = col;
this._ctx.fillStyle = col;
};
/** Return the dash array for the given line pattern.
@param {string} type The type of the dash pattern ('solid', 'dashed', 'dotted').
@return {Array} The numerical array of dash segment lengths.
*/
PrairieDraw.prototype._dashPattern = function (type) {
if (type === 'solid') {
return [];
} else if (type === 'dashed') {
return [6, 6];
} else if (type === 'dotted') {
return [2, 2];
} else {
throw new Error('PrairieDraw: unknown dash pattern: ' + type);
}
};
/** Draw a single line given start and end positions.
@param {Vector} startDw Initial point of the line (drawing coords).
@param {Vector} endDw Final point of the line (drawing coords).
@param {string} type Optional type of line being drawn.
*/
PrairieDraw.prototype.line = function (startDw, endDw, type) {
startDw = this.pos3To2(startDw);
endDw = this.pos3To2(endDw);
var startPx = this.pos2Px(startDw);
var endPx = this.pos2Px(endDw);
this._ctx.save();
this._setLineStyles(type);
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.beginPath();
this._ctx.moveTo(startPx.e(1), startPx.e(2));
this._ctx.lineTo(endPx.e(1), endPx.e(2));
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a cubic Bezier segment.
@param {Vector} p0Dw The starting point.
@param {Vector} p1Dw The first control point.
@param {Vector} p2Dw The second control point.
@param {Vector} p3Dw The ending point.
@param {string} type (Optional) type of line being drawn.
*/
PrairieDraw.prototype.cubicBezier = function (p0Dw, p1Dw, p2Dw, p3Dw, type) {
var p0Px = this.pos2Px(this.pos3To2(p0Dw));
var p1Px = this.pos2Px(this.pos3To2(p1Dw));
var p2Px = this.pos2Px(this.pos3To2(p2Dw));
var p3Px = this.pos2Px(this.pos3To2(p3Dw));
this._ctx.save();
this._setLineStyles(type);
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.beginPath();
this._ctx.moveTo(p0Px.e(1), p0Px.e(2));
this._ctx.bezierCurveTo(p1Px.e(1), p1Px.e(2), p2Px.e(1), p2Px.e(2), p3Px.e(1), p3Px.e(2));
this._ctx.stroke();
this._ctx.restore();
};
/** @private Draw an arrowhead in pixel coords.
@param {Vector} posPx Position of the tip.
@param {Vector} dirPx Direction vector that the arrowhead points in.
@param {number} lenPx Length of the arrowhead.
*/
PrairieDraw.prototype._arrowheadPx = function (posPx, dirPx, lenPx) {
var dxPx = -(1 - this._props.<API key>) * lenPx;
var dyPx = this._props.arrowheadWidthRatio * lenPx;
this._ctx.save();
this._ctx.translate(posPx.e(1), posPx.e(2));
this._ctx.rotate(PrairieGeom.angleOf(dirPx));
this._ctx.beginPath();
this._ctx.moveTo(0, 0);
this._ctx.lineTo(-lenPx, dyPx);
this._ctx.lineTo(dxPx, 0);
this._ctx.lineTo(-lenPx, -dyPx);
this._ctx.closePath();
this._ctx.fill();
this._ctx.restore();
};
/** @private Draw an arrowhead.
@param {Vector} posDw Position of the tip (drawing coords).
@param {Vector} dirDw Direction vector that the arrowhead point in (drawing coords).
@param {number} lenPx Length of the arrowhead (pixel coords).
*/
PrairieDraw.prototype._arrowhead = function (posDw, dirDw, lenPx) {
var posPx = this.pos2Px(posDw);
var dirPx = this.vec2Px(dirDw);
this._arrowheadPx(posPx, dirPx, lenPx);
};
/** Draw an arrow given start and end positions.
@param {Vector} startDw Initial point of the arrow (drawing coords).
@param {Vector} endDw Final point of the arrow (drawing coords).
@param {string} type Optional type of vector being drawn.
*/
PrairieDraw.prototype.arrow = function (startDw, endDw, type) {
startDw = this.pos3To2(startDw);
endDw = this.pos3To2(endDw);
var offsetDw = endDw.subtract(startDw);
var offsetPx = this.vec2Px(offsetDw);
var arrowLengthPx = offsetPx.modulus();
var lineEndDw, drawArrowHead, arrowheadLengthPx;
if (arrowLengthPx < 1) {
// if too short, just draw a simple line
lineEndDw = endDw;
drawArrowHead = false;
} else {
var <API key> = this._props.<API key> * this._props.arrowLineWidthPx;
arrowheadLengthPx = Math.min(<API key>, arrowLengthPx / 2);
var <API key> = (1 - this._props.<API key>) * arrowheadLengthPx;
var lineLengthPx = arrowLengthPx - <API key>;
lineEndDw = startDw.add(offsetDw.x(lineLengthPx / arrowLengthPx));
drawArrowHead = true;
}
var startPx = this.pos2Px(startDw);
var lineEndPx = this.pos2Px(lineEndDw);
this.save();
this._ctx.lineWidth = this._props.arrowLineWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern));
this._setLineStyles(type);
this._ctx.beginPath();
this._ctx.moveTo(startPx.e(1), startPx.e(2));
this._ctx.lineTo(lineEndPx.e(1), lineEndPx.e(2));
this._ctx.stroke();
if (drawArrowHead) {
this._arrowhead(endDw, offsetDw, arrowheadLengthPx);
}
this.restore();
};
/** Draw an arrow given the start position and offset.
@param {Vector} startDw Initial point of the arrow (drawing coords).
@param {Vector} offsetDw Offset vector of the arrow (drawing coords).
@param {string} type Optional type of vector being drawn.
*/
PrairieDraw.prototype.arrowFrom = function (startDw, offsetDw, type) {
var endDw = startDw.add(offsetDw);
this.arrow(startDw, endDw, type);
};
/** Draw an arrow given the end position and offset.
@param {Vector} endDw Final point of the arrow (drawing coords).
@param {Vector} offsetDw Offset vector of the arrow (drawing coords).
@param {string} type Optional type of vector being drawn.
*/
PrairieDraw.prototype.arrowTo = function (endDw, offsetDw, type) {
var startDw = endDw.subtract(offsetDw);
this.arrow(startDw, endDw, type);
};
/** Draw an arrow out of the page (circle with centered dot).
@param {Vector} posDw The position of the arrow.
@param {string} type Optional type of vector being drawn.
*/
PrairieDraw.prototype.arrowOutOfPage = function (posDw, type) {
var posPx = this.pos2Px(posDw);
var r = this._props.<API key>;
this._ctx.save();
this._ctx.translate(posPx.e(1), posPx.e(2));
this._ctx.beginPath();
this._ctx.arc(0, 0, r, 0, 2 * Math.PI);
this._ctx.fillStyle = 'rgb(255, 255, 255)';
this._ctx.fill();
this._ctx.lineWidth = this._props.arrowLineWidthPx;
this._setLineStyles(type);
this._ctx.stroke();
this._ctx.beginPath();
this._ctx.arc(0, 0, this._props.arrowLineWidthPx * 0.7, 0, 2 * Math.PI);
this._ctx.fill();
this._ctx.restore();
};
/** Draw an arrow into the page (circle with times).
@param {Vector} posDw The position of the arrow.
@param {string} type Optional type of vector being drawn.
*/
PrairieDraw.prototype.arrowIntoPage = function (posDw, type) {
var posPx = this.pos2Px(posDw);
var r = this._props.<API key>;
var rs = r / Math.sqrt(2);
this._ctx.save();
this._ctx.lineWidth = this._props.arrowLineWidthPx;
this._setLineStyles(type);
this._ctx.translate(posPx.e(1), posPx.e(2));
this._ctx.beginPath();
this._ctx.arc(0, 0, r, 0, 2 * Math.PI);
this._ctx.fillStyle = 'rgb(255, 255, 255)';
this._ctx.fill();
this._ctx.stroke();
this._ctx.beginPath();
this._ctx.moveTo(-rs, -rs);
this._ctx.lineTo(rs, rs);
this._ctx.stroke();
this._ctx.beginPath();
this._ctx.moveTo(rs, -rs);
this._ctx.lineTo(-rs, rs);
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a circle arrow by specifying the center and extent.
@param {Vector} posDw The center of the circle arrow.
@param {number} radDw The radius at the mid-angle.
@param {number} centerAngleDw The center angle (counterclockwise from x axis, in radians).
@param {number} extentAngleDw The extent of the arrow (counterclockwise, in radians).
@param {string} type (Optional) The type of the arrow.
@param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false).
*/
PrairieDraw.prototype.circleArrowCentered = function (
posDw,
radDw,
centerAngleDw,
extentAngleDw,
type,
fixedRad
) {
var startAngleDw = centerAngleDw - extentAngleDw / 2;
var endAngleDw = centerAngleDw + extentAngleDw / 2;
this.circleArrow(posDw, radDw, startAngleDw, endAngleDw, type, fixedRad);
};
/** Draw a circle arrow.
@param {Vector} posDw The center of the circle arrow.
@param {number} radDw The radius at the mid-angle.
@param {number} startAngleDw The starting angle (counterclockwise from x axis, in radians).
@param {number} endAngleDw The ending angle (counterclockwise from x axis, in radians).
@param {string} type (Optional) The type of the arrow.
@param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false).
@param {number} idealSegmentSize (Optional) The ideal linear segment size to use (radians).
*/
PrairieDraw.prototype.circleArrow = function (
posDw,
radDw,
startAngleDw,
endAngleDw,
type,
fixedRad,
idealSegmentSize
) {
this.save();
this._ctx.lineWidth = this._props.arrowLineWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern));
this._setLineStyles(type);
// convert to Px coordinates
var startOffsetDw = PrairieGeom.vector2DAtAngle(startAngleDw).x(radDw);
var posPx = this.pos2Px(posDw);
var startOffsetPx = this.vec2Px(startOffsetDw);
var radiusPx = startOffsetPx.modulus();
var startAnglePx = PrairieGeom.angleOf(startOffsetPx);
var deltaAngleDw = endAngleDw - startAngleDw;
// assume a possibly reflected/rotated but equally scaled Dw/Px transformation
var deltaAnglePx = this._transIsReflection() ? -deltaAngleDw : deltaAngleDw;
var endAnglePx = startAnglePx + deltaAnglePx;
// compute arrowhead properties
var startRadiusPx = this._circleArrowRadius(
radiusPx,
startAnglePx,
startAnglePx,
endAnglePx,
fixedRad
);
var endRadiusPx = this._circleArrowRadius(
radiusPx,
endAnglePx,
startAnglePx,
endAnglePx,
fixedRad
);
var arrowLengthPx = radiusPx * Math.abs(endAnglePx - startAnglePx);
var <API key> = this._props.<API key> * this._props.arrowLineWidthPx;
var arrowheadLengthPx = Math.min(<API key>, arrowLengthPx / 2);
var <API key> = (1 - this._props.<API key>) * arrowheadLengthPx;
var <API key> =
(1 - this._props.<API key> / 3) * arrowheadLengthPx;
var arrowheadAnglePx = <API key> / endRadiusPx;
var <API key> = <API key> / endRadiusPx;
var preEndAnglePx = endAnglePx - PrairieGeom.sign(endAnglePx - startAnglePx) * arrowheadAnglePx;
var arrowBaseAnglePx =
endAnglePx - PrairieGeom.sign(endAnglePx - startAnglePx) * <API key>;
this._ctx.save();
this._ctx.translate(posPx.e(1), posPx.e(2));
idealSegmentSize = idealSegmentSize === undefined ? 0.2 : idealSegmentSize; // radians
var numSegments = Math.ceil(Math.abs(preEndAnglePx - startAnglePx) / idealSegmentSize);
var i, anglePx, rPx;
var offsetPx = PrairieGeom.vector2DAtAngle(startAnglePx).x(startRadiusPx);
this._ctx.beginPath();
this._ctx.moveTo(offsetPx.e(1), offsetPx.e(2));
for (i = 1; i <= numSegments; i++) {
anglePx = PrairieGeom.linearInterp(startAnglePx, preEndAnglePx, i / numSegments);
rPx = this._circleArrowRadius(radiusPx, anglePx, startAnglePx, endAnglePx, fixedRad);
offsetPx = PrairieGeom.vector2DAtAngle(anglePx).x(rPx);
this._ctx.lineTo(offsetPx.e(1), offsetPx.e(2));
}
this._ctx.stroke();
this._ctx.restore();
var arrowBaseRadiusPx = this._circleArrowRadius(
radiusPx,
arrowBaseAnglePx,
startAnglePx,
endAnglePx,
fixedRad
);
var arrowPosPx = posPx.add(PrairieGeom.vector2DAtAngle(endAnglePx).x(endRadiusPx));
var arrowBasePosPx = posPx.add(
PrairieGeom.vector2DAtAngle(arrowBaseAnglePx).x(arrowBaseRadiusPx)
);
var arrowDirPx = arrowPosPx.subtract(arrowBasePosPx);
var arrowPosDw = this.pos2Dw(arrowPosPx);
var arrowDirDw = this.vec2Dw(arrowDirPx);
this._arrowhead(arrowPosDw, arrowDirDw, arrowheadLengthPx);
this.restore();
};
/** @private Compute the radius at a certain angle within a circle arrow.
@param {number} midRadPx The radius at the midpoint of the circle arrow.
@param {number} anglePx The angle at which to find the radius.
@param {number} startAnglePx The starting angle (counterclockwise from x axis, in radians).
@param {number} endAnglePx The ending angle (counterclockwise from x axis, in radians).
@return {number} The radius at the given angle (pixel coords).
@param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false).
*/
PrairieDraw.prototype._circleArrowRadius = function (
midRadPx,
anglePx,
startAnglePx,
endAnglePx,
fixedRad
) {
if (fixedRad !== undefined && fixedRad === true) {
return midRadPx;
}
if (Math.abs(endAnglePx - startAnglePx) < 1e-4) {
return midRadPx;
}
var <API key> = this._props.<API key> * this._props.arrowLineWidthPx;
/* jshint laxbreak: true */
var spacingPx =
<API key> *
this._props.arrowheadWidthRatio *
this._props.<API key>;
var <API key> = (midRadPx * Math.PI * 2) / spacingPx;
var midAnglePx = (startAnglePx + endAnglePx) / 2;
var offsetAnglePx = (anglePx - midAnglePx) * PrairieGeom.sign(endAnglePx - startAnglePx);
if (offsetAnglePx > 0) {
return midRadPx * (1 + offsetAnglePx / <API key>);
} else {
return midRadPx * Math.exp(offsetAnglePx / <API key>);
}
};
/** Draw an arc in 3D.
@param {Vector} posDw The center of the arc.
@param {number} radDw The radius of the arc.
@param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis).
@param {Vector} refDw (Optional) The reference vector to measure angles from (default: an orthogonal vector to normDw).
@param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0).
@param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi).
@param {string} type (Optional) The type of the line.
@param {Object} options (Optional) Various options.
*/
PrairieDraw.prototype.arc3D = function (
posDw,
radDw,
normDw,
refDw,
startAngleDw,
endAngleDw,
options
) {
posDw = this.pos2To3(posDw);
normDw = normDw === undefined ? Vector.k : normDw;
refDw = refDw === undefined ? PrairieGeom.chooseNormVec(normDw) : refDw;
var fullCircle = startAngleDw === undefined && endAngleDw === undefined;
startAngleDw = startAngleDw === undefined ? 0 : startAngleDw;
endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw;
options = options === undefined ? {} : options;
var idealSegmentSize =
options.idealSegmentSize === undefined ? (2 * Math.PI) / 40 : options.idealSegmentSize;
var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector();
var vDw = normDw.toUnitVector().cross(uDw);
var numSegments = Math.ceil(Math.abs(endAngleDw - startAngleDw) / idealSegmentSize);
var points = [];
var theta, p;
for (var i = 0; i <= numSegments; i++) {
theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, i / numSegments);
p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta)));
points.push(this.pos3To2(p));
}
if (fullCircle) {
points.pop();
this.polyLine(points, true, false);
} else {
this.polyLine(points);
}
};
/** Draw a circle arrow in 3D.
@param {Vector} posDw The center of the arc.
@param {number} radDw The radius of the arc.
@param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis).
@param {Vector} refDw (Optional) The reference vector to measure angles from (default: x axis).
@param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0).
@param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi).
@param {string} type (Optional) The type of the line.
@param {Object} options (Optional) Various options.
*/
PrairieDraw.prototype.circleArrow3D = function (
posDw,
radDw,
normDw,
refDw,
startAngleDw,
endAngleDw,
type,
options
) {
posDw = this.pos2To3(posDw);
normDw = normDw || Vector.k;
refDw = refDw || Vector.i;
startAngleDw = startAngleDw === undefined ? 0 : startAngleDw;
endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw;
options = options === undefined ? {} : options;
var idealSegmentSize =
options.idealSegmentSize === undefined ? (2 * Math.PI) / 40 : options.idealSegmentSize;
var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector();
var vDw = normDw.toUnitVector().cross(uDw);
var numSegments = Math.ceil(Math.abs(endAngleDw - startAngleDw) / idealSegmentSize);
var points = [];
var theta, p;
for (var i = 0; i <= numSegments; i++) {
theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, i / numSegments);
p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta)));
points.push(this.pos3To2(p));
}
this.polyLineArrow(points, type);
};
/** Label a circle line in 3D.
@param {string} labelText The label text.
@param {Vector} labelAnchor The label anchor (first coord -1 to 1 along the line, second -1 to 1 transverse).
@param {Vector} posDw The center of the arc.
@param {number} radDw The radius of the arc.
@param {Vector} normDw (Optional) The normal vector to the plane containing the arc (default: z axis).
@param {Vector} refDw (Optional) The reference vector to measure angles from (default: x axis).
@param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0).
@param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi).
*/
PrairieDraw.prototype.labelCircleLine3D = function (
labelText,
labelAnchor,
posDw,
radDw,
normDw,
refDw,
startAngleDw,
endAngleDw
) {
if (labelText === undefined) {
return;
}
posDw = this.pos2To3(posDw);
normDw = normDw || Vector.k;
refDw = refDw || Vector.i;
startAngleDw = startAngleDw === undefined ? 0 : startAngleDw;
endAngleDw = endAngleDw === undefined ? 2 * Math.PI : endAngleDw;
var uDw = PrairieGeom.orthComp(refDw, normDw).toUnitVector();
var vDw = normDw.toUnitVector().cross(uDw);
var theta = PrairieGeom.linearInterp(startAngleDw, endAngleDw, (labelAnchor.e(1) + 1) / 2);
var p = posDw.add(uDw.x(radDw * Math.cos(theta))).add(vDw.x(radDw * Math.sin(theta)));
var p2Dw = this.pos3To2(p);
var t3Dw = uDw.x(-Math.sin(theta)).add(vDw.x(Math.cos(theta)));
var n3Dw = uDw.x(Math.cos(theta)).add(vDw.x(Math.sin(theta)));
var t2Px = this.vec2Px(this.vec3To2(t3Dw, p));
var n2Px = this.vec2Px(this.vec3To2(n3Dw, p));
n2Px = PrairieGeom.orthComp(n2Px, t2Px);
t2Px = t2Px.toUnitVector();
n2Px = n2Px.toUnitVector();
var oPx = t2Px.x(labelAnchor.e(1)).add(n2Px.x(labelAnchor.e(2)));
var oDw = this.vec2Dw(oPx);
var aDw = oDw.x(-1).toUnitVector();
var anchor = aDw.x(1.0 / Math.abs(aDw.max())).x(Math.abs(labelAnchor.max()));
this.text(p2Dw, anchor, labelText);
};
/** Draw a sphere.
@param {Vector} posDw Position of the sphere center.
@param {number} radDw Radius of the sphere.
@param {bool} filled (Optional) Whether to fill the sphere (default: false).
*/
PrairieDraw.prototype.sphere = function (posDw, radDw, filled) {
filled = filled === undefined ? false : filled;
var posVw = this.posDwToVw(posDw);
var edgeDw = posDw.add($V([radDw, 0, 0]));
var edgeVw = this.posDwToVw(edgeDw);
var radVw = edgeVw.subtract(posVw).modulus();
var posDw2 = PrairieGeom.orthProjPos3D(posVw);
this.circle(posDw2, radVw, filled);
};
/** Draw a circular slice on a sphere.
@param {Vector} posDw Position of the sphere center.
@param {number} radDw Radius of the sphere.
@param {Vector} normDw Normal vector to the circle.
@param {number} distDw Distance from sphere center to circle center along normDw.
@param {string} drawBack (Optional) Whether to draw the back line (default: true).
@param {string} drawFront (Optional) Whether to draw the front line (default: true).
@param {Vector} refDw (Optional) The reference vector to measure angles from (default: an orthogonal vector to normDw).
@param {number} startAngleDw (Optional) The starting angle (counterclockwise from refDw about normDw, in radians, default: 0).
@param {number} endAngleDw (Optional) The ending angle (counterclockwise from refDw about normDw, in radians, default: 2 pi).
*/
PrairieDraw.prototype.sphereSlice = function (
posDw,
radDw,
normDw,
distDw,
drawBack,
drawFront,
refDw,
startAngleDw,
endAngleDw
) {
var cRDwSq = radDw * radDw - distDw * distDw;
if (cRDwSq <= 0) {
return;
}
var cRDw = Math.sqrt(cRDwSq);
var circlePosDw = posDw.add(normDw.toUnitVector().x(distDw));
drawBack = drawBack === undefined ? true : drawBack;
drawFront = drawFront === undefined ? true : drawFront;
var normVw = this.vecDwToVw(normDw);
if (PrairieGeom.orthComp(Vector.k, normVw).modulus() < 1e-10) {
// looking straight down on the circle
if (distDw > 0) {
// front side, completely visible
this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw);
} else if (distDw < 0) {
// back side, completely invisible
this.save();
this.setShapeDrawHidden();
this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw);
this.restore();
}
// if distDw == 0 then it's a great circle, don't draw it
return;
}
var refVw;
if (refDw === undefined) {
refVw = PrairieGeom.orthComp(Vector.k, normVw);
refDw = this.vecVwToDw(refVw);
}
refVw = this.vecDwToVw(refDw);
var uVw = refVw.toUnitVector();
var vVw = normVw.toUnitVector().cross(uVw);
var dVw = this.vecDwToVw(normDw.toUnitVector().x(distDw));
var cRVw = this.vecDwToVw(refDw.toUnitVector().x(cRDw)).modulus();
var A = -dVw.e(3);
var B = uVw.e(3) * cRVw;
var C = vVw.e(3) * cRVw;
var BCMag = Math.sqrt(B * B + C * C);
var AN = A / BCMag;
var phi = Math.atan2(C, B);
if (AN <= -1) {
// only front
if (drawFront) {
this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw);
}
} else if (AN >= 1) {
// only back
if (drawBack && this._props.hiddenLineDraw) {
this.save();
this.setShapeDrawHidden();
this.arc3D(circlePosDw, cRDw, normDw, refDw, startAngleDw, endAngleDw);
this.restore();
}
} else {
// front and back
var acosAN = Math.acos(AN);
var theta1 = phi + acosAN;
var theta2 = phi + 2 * Math.PI - acosAN;
var i, intersections, range;
if (drawBack && this._props.hiddenLineDraw) {
this.save();
this.setShapeDrawHidden();
if (theta2 > theta1) {
if (startAngleDw === undefined || endAngleDw === undefined) {
this.arc3D(circlePosDw, cRDw, normDw, refDw, theta1, theta2);
} else {
intersections = PrairieGeom.<API key>(
[theta1, theta2],
[startAngleDw, endAngleDw]
);
for (i = 0; i < intersections.length; i++) {
range = intersections[i];
this.arc3D(circlePosDw, cRDw, normDw, refDw, range[0], range[1]);
}
}
}
this.restore();
}
if (drawFront) {
if (startAngleDw === undefined || endAngleDw === undefined) {
this.arc3D(circlePosDw, cRDw, normDw, refDw, theta2, theta1 + 2 * Math.PI);
} else {
intersections = PrairieGeom.<API key>(
[theta2, theta1 + 2 * Math.PI],
[startAngleDw, endAngleDw]
);
for (i = 0; i < intersections.length; i++) {
range = intersections[i];
this.arc3D(circlePosDw, cRDw, normDw, refDw, range[0], range[1]);
}
}
}
}
};
/** Label an angle with an inset label.
@param {Vector} pos The corner position.
@param {Vector} p1 Position of first other point.
@param {Vector} p2 Position of second other point.
@param {string} label The label text.
*/
PrairieDraw.prototype.labelAngle = function (pos, p1, p2, label) {
pos = this.pos3To2(pos);
p1 = this.pos3To2(p1);
p2 = this.pos3To2(p2);
var v1 = p1.subtract(pos);
var v2 = p2.subtract(pos);
var vMid = v1.add(v2).x(0.5);
var anchor = vMid.x(-1.8 / PrairieGeom.supNorm(vMid));
this.text(pos, anchor, label);
};
/** Draw an arc.
@param {Vector} centerDw The center of the circle.
@param {Vector} radiusDw The radius of the circle (or major axis for ellipses).
@param {number} startAngle (Optional) The start angle of the arc (radians, default: 0).
@param {number} endAngle (Optional) The end angle of the arc (radians, default: 2 pi).
@param {bool} filled (Optional) Whether to fill the arc (default: false).
@param {Number} aspect (Optional) The aspect ratio (major / minor) (default: 1).
*/
PrairieDraw.prototype.arc = function (centerDw, radiusDw, startAngle, endAngle, filled, aspect) {
startAngle = startAngle === undefined ? 0 : startAngle;
endAngle = endAngle === undefined ? 2 * Math.PI : endAngle;
filled = filled === undefined ? false : filled;
aspect = aspect === undefined ? 1 : aspect;
var centerPx = this.pos2Px(centerDw);
var offsetDw = $V([radiusDw, 0]);
var offsetPx = this.vec2Px(offsetDw);
var radiusPx = offsetPx.modulus();
var anglePx = PrairieGeom.angleOf(offsetPx);
this._ctx.save();
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.strokeStyle = this._props.shapeOutlineColor;
this._ctx.fillStyle = this._props.shapeInsideColor;
this._ctx.save();
this._ctx.translate(centerPx.e(1), centerPx.e(2));
this._ctx.rotate(anglePx);
this._ctx.scale(1, 1 / aspect);
this._ctx.beginPath();
this._ctx.arc(0, 0, radiusPx, -endAngle, -startAngle);
this._ctx.restore();
if (filled) {
this._ctx.fill();
}
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a polyLine (closed or open).
@param {Array} pointsDw A list of drawing coordinates that form the polyLine.
@param {bool} closed (Optional) Whether the shape should be closed (default: false).
@param {bool} filled (Optional) Whether the shape should be filled (default: true).
*/
PrairieDraw.prototype.polyLine = function (pointsDw, closed, filled) {
if (pointsDw.length < 2) {
return;
}
this._ctx.save();
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.strokeStyle = this._props.shapeOutlineColor;
this._ctx.fillStyle = this._props.shapeInsideColor;
this._ctx.beginPath();
var pDw = this.pos3To2(pointsDw[0]);
var pPx = this.pos2Px(pDw);
this._ctx.moveTo(pPx.e(1), pPx.e(2));
for (var i = 1; i < pointsDw.length; i++) {
pDw = this.pos3To2(pointsDw[i]);
pPx = this.pos2Px(pDw);
this._ctx.lineTo(pPx.e(1), pPx.e(2));
}
if (closed !== undefined && closed === true) {
this._ctx.closePath();
if (filled === undefined || filled === true) {
this._ctx.fill();
}
}
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a polyLine arrow.
@param {Array} pointsDw A list of drawing coordinates that form the polyLine.
*/
PrairieDraw.prototype.polyLineArrow = function (pointsDw, type) {
if (pointsDw.length < 2) {
return;
}
// convert the line to pixel coords and find its length
var pointsPx = [];
var i;
var polyLineLengthPx = 0;
for (i = 0; i < pointsDw.length; i++) {
pointsPx.push(this.pos2Px(this.pos3To2(pointsDw[i])));
if (i > 0) {
polyLineLengthPx += pointsPx[i].subtract(pointsPx[i - 1]).modulus();
}
}
// shorten the line to fit the arrowhead, dropping points and moving the last point
var drawArrowHead, arrowheadEndPx, arrowheadOffsetPx, arrowheadLengthPx;
if (polyLineLengthPx < 1) {
// if too short, don't draw the arrowhead
drawArrowHead = false;
} else {
drawArrowHead = true;
var <API key> = this._props.<API key> * this._props.arrowLineWidthPx;
arrowheadLengthPx = Math.min(<API key>, polyLineLengthPx / 2);
var <API key> = (1 - this._props.<API key>) * arrowheadLengthPx;
var lengthToRemovePx = <API key>;
i = pointsPx.length - 1;
arrowheadEndPx = pointsPx[i];
var segmentLengthPx;
while (i > 0) {
segmentLengthPx = pointsPx[i].subtract(pointsPx[i - 1]).modulus();
if (lengthToRemovePx > segmentLengthPx) {
lengthToRemovePx -= segmentLengthPx;
pointsPx.pop();
i
} else {
pointsPx[i] = PrairieGeom.linearInterpVector(
pointsPx[i],
pointsPx[i - 1],
lengthToRemovePx / segmentLengthPx
);
break;
}
}
var arrowheadBasePx = pointsPx[i];
arrowheadOffsetPx = arrowheadEndPx.subtract(arrowheadBasePx);
}
// draw the line
this._ctx.save();
this._ctx.lineWidth = this._props.arrowLineWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.arrowLinePattern));
this._setLineStyles(type);
this._ctx.beginPath();
var pPx = pointsPx[0];
this._ctx.moveTo(pPx.e(1), pPx.e(2));
for (i = 1; i < pointsPx.length; i++) {
pPx = pointsPx[i];
this._ctx.lineTo(pPx.e(1), pPx.e(2));
}
this._ctx.stroke();
// draw the arrowhead
if (drawArrowHead) {
i = pointsPx[i];
this._arrowheadPx(arrowheadEndPx, arrowheadOffsetPx, arrowheadLengthPx);
}
this._ctx.restore();
};
/** Draw a circle.
@param {Vector} centerDw The center in drawing coords.
@param {number} radiusDw the radius in drawing coords.
@param {bool} filled (Optional) Whether to fill the circle (default: true).
*/
PrairieDraw.prototype.circle = function (centerDw, radiusDw, filled) {
filled = filled === undefined ? true : filled;
var centerPx = this.pos2Px(centerDw);
var offsetDw = $V([radiusDw, 0]);
var offsetPx = this.vec2Px(offsetDw);
var radiusPx = offsetPx.modulus();
this._ctx.save();
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.strokeStyle = this._props.shapeOutlineColor;
this._ctx.fillStyle = this._props.shapeInsideColor;
this._ctx.beginPath();
this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, 0, 2 * Math.PI);
if (filled) {
this._ctx.fill();
}
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a filled circle.
@param {Vector} centerDw The center in drawing coords.
@param {number} radiusDw the radius in drawing coords.
*/
PrairieDraw.prototype.filledCircle = function (centerDw, radiusDw) {
var centerPx = this.pos2Px(centerDw);
var offsetDw = $V([radiusDw, 0]);
var offsetPx = this.vec2Px(offsetDw);
var radiusPx = offsetPx.modulus();
this._ctx.save();
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.fillStyle = this._props.shapeOutlineColor;
this._ctx.beginPath();
this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, 0, 2 * Math.PI);
this._ctx.fill();
this._ctx.restore();
};
/** Draw a triagular distributed load
@param {Vector} startDw The first point (in drawing coordinates) of the distributed load
@param {Vector} endDw The end point (in drawing coordinates) of the distributed load
@param {number} sizeStartDw length of the arrow at startDw
@param {number} sizeEndDw length of the arrow at endDw
@param {string} label the arrow size at startDw
@param {string} label the arrow size at endDw
@param {boolean} true if arrow heads are towards the line that connects points startDw and endDw, opposite direction if false
@param {boolean} true if arrow points up (positive y-axis), false otherwise
*/
PrairieDraw.prototype.<API key> = function (
startDw,
endDw,
sizeStartDw,
sizeEndDw,
labelStart,
labelEnd,
arrowToLine,
arrowDown
) {
var LengthDw = endDw.subtract(startDw);
var L = LengthDw.modulus();
if (arrowDown) {
var sizeStartDwSign = sizeStartDw;
var sizeEndDwSign = sizeEndDw;
} else {
var sizeStartDwSign = -sizeStartDw;
var sizeEndDwSign = -sizeEndDw;
}
var nSpaces = Math.ceil((2 * L) / sizeStartDw);
var spacing = L / nSpaces;
var inc = 0;
this.save();
this.setProp('shapeOutlineColor', 'rgb(255,0,0)');
this.setProp('arrowLineWidthPx', 1);
this.setProp('<API key>', 11);
if (arrowToLine) {
this.line(startDw.add($V([0, sizeStartDwSign])), endDw.add($V([0, sizeEndDwSign])));
var startArrow = startDw.add($V([0, sizeStartDwSign]));
var endArrow = startDw;
for (i = 0; i <= nSpaces; i++) {
this.arrow(
startArrow.add($V([inc, (inc * (sizeEndDwSign - sizeStartDwSign)) / L])),
endArrow.add($V([inc, 0]))
);
inc = inc + spacing;
}
this.text(startArrow, $V([2, 0]), labelStart);
this.text(
startArrow.add(
$V([inc - spacing, ((inc - spacing) * (sizeEndDwSign - sizeStartDwSign)) / L])
),
$V([-2, 0]),
labelEnd
);
} else {
this.line(startDw, endDw);
var startArrow = startDw;
var endArrow = startDw.subtract($V([0, sizeStartDwSign]));
for (i = 0; i <= nSpaces; i++) {
this.arrow(
startArrow.add($V([inc, 0])),
endArrow.add($V([inc, (-inc * (sizeEndDwSign - sizeStartDwSign)) / L]))
);
inc = inc + spacing;
}
this.text(endArrow, $V([2, 0]), labelStart);
this.text(
endArrow.add(
$V([inc - spacing, (-(inc - spacing) * (sizeEndDwSign - sizeStartDwSign)) / L])
),
$V([-2, 0]),
labelEnd
);
}
this.restore();
};
/** Draw a rod with hinge points at start and end and the given width.
@param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates.
@param {Vector} startDw The second hinge point (drawing coordinates).
@param {number} widthDw The width of the rod (drawing coordinates).
*/
PrairieDraw.prototype.rod = function (startDw, endDw, widthDw) {
var offsetLengthDw = endDw.subtract(startDw);
var offsetWidthDw = offsetLengthDw
.rotate(Math.PI / 2, $V([0, 0]))
.toUnitVector()
.x(widthDw);
var startPx = this.pos2Px(startDw);
var offsetLengthPx = this.vec2Px(offsetLengthDw);
var offsetWidthPx = this.vec2Px(offsetWidthDw);
var lengthPx = offsetLengthPx.modulus();
var rPx = offsetWidthPx.modulus() / 2;
this._ctx.save();
this._ctx.translate(startPx.e(1), startPx.e(2));
this._ctx.rotate(PrairieGeom.angleOf(offsetLengthPx));
this._ctx.beginPath();
this._ctx.moveTo(0, rPx);
this._ctx.arcTo(lengthPx + rPx, rPx, lengthPx + rPx, -rPx, rPx);
this._ctx.arcTo(lengthPx + rPx, -rPx, 0, -rPx, rPx);
this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx);
this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx);
if (this._props.shapeInsideColor !== 'none') {
this._ctx.fillStyle = this._props.shapeInsideColor;
this._ctx.fill();
}
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.strokeStyle = this._props.shapeOutlineColor;
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a L-shape rod with hinge points at start, center and end, and the given width.
@param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates.
@param {Vector} centerDw The second hinge point (drawing coordinates).
@param {Vector} endDw The third hinge point (drawing coordinates).
@param {number} widthDw The width of the rod (drawing coordinates).
*/
PrairieDraw.prototype.LshapeRod = function (startDw, centerDw, endDw, widthDw) {
var offsetLength1Dw = centerDw.subtract(startDw);
var offsetLength2Dw = endDw.subtract(centerDw);
var offsetWidthDw = offsetLength1Dw
.rotate(Math.PI / 2, $V([0, 0]))
.toUnitVector()
.x(widthDw);
var startPx = this.pos2Px(startDw);
var centerPx = this.pos2Px(centerDw);
var endPx = this.pos2Px(endDw);
var offsetLength1Px = this.vec2Px(offsetLength1Dw);
var offsetLength2Px = this.vec2Px(offsetLength2Dw);
var offsetWidthPx = this.vec2Px(offsetWidthDw);
var length1Px = offsetLength1Px.modulus();
var length2Px = offsetLength2Px.modulus();
var rPx = offsetWidthPx.modulus() / 2;
this._ctx.save();
this._ctx.translate(startPx.e(1), startPx.e(2));
this._ctx.rotate(PrairieGeom.angleOf(offsetLength1Px));
this._ctx.beginPath();
this._ctx.moveTo(0, rPx);
var beta = -PrairieGeom.angleFrom(offsetLength1Px, offsetLength2Px);
var x1 = length1Px + rPx / Math.sin(beta) - rPx / Math.tan(beta);
var y1 = rPx;
var x2 = length1Px + length2Px * Math.cos(beta);
var y2 = -length2Px * Math.sin(beta);
var x3 = x2 + rPx * Math.sin(beta);
var y3 = y2 + rPx * Math.cos(beta);
var x4 = x3 + rPx * Math.cos(beta);
var y4 = y3 - rPx * Math.sin(beta);
var x5 = x2 + rPx * Math.cos(beta);
var y5 = y2 - rPx * Math.sin(beta);
var x6 = x5 - rPx * Math.sin(beta);
var y6 = y5 - rPx * Math.cos(beta);
var x7 = length1Px - rPx / Math.sin(beta) + rPx / Math.tan(beta);
var y7 = -rPx;
this._ctx.arcTo(x1, y1, x3, y3, rPx);
this._ctx.arcTo(x4, y4, x5, y5, rPx);
this._ctx.arcTo(x6, y6, x7, y7, rPx);
this._ctx.arcTo(x7, y7, 0, -rPx, rPx);
this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx);
this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx);
if (this._props.shapeInsideColor !== 'none') {
this._ctx.fillStyle = this._props.shapeInsideColor;
this._ctx.fill();
}
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.strokeStyle = this._props.shapeOutlineColor;
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a T-shape rod with hinge points at start, center, center-end and end, and the given width.
@param {Vector} startDw The first hinge point (center of circular end) in drawing coordinates.
@param {Vector} centerDw The second hinge point (drawing coordinates).
@param {Vector} endDw The third hinge point (drawing coordinates).
@param {Vector} centerEndDw The fourth hinge point (drawing coordinates).
@param {number} widthDw The width of the rod (drawing coordinates).
*/
PrairieDraw.prototype.TshapeRod = function (startDw, centerDw, endDw, centerEndDw, widthDw) {
var offsetStartRodDw = centerDw.subtract(startDw);
var offsetEndRodDw = endDw.subtract(centerDw);
var offsetCenterRodDw = centerEndDw.subtract(centerDw);
var offsetWidthDw = offsetStartRodDw
.rotate(Math.PI / 2, $V([0, 0]))
.toUnitVector()
.x(widthDw);
var startPx = this.pos2Px(startDw);
var centerPx = this.pos2Px(centerDw);
var endPx = this.pos2Px(endDw);
var offsetStartRodPx = this.vec2Px(offsetStartRodDw);
var offsetEndRodPx = this.vec2Px(offsetEndRodDw);
var offsetCenterRodPx = this.vec2Px(offsetCenterRodDw);
var offsetWidthPx = this.vec2Px(offsetWidthDw);
var lengthStartRodPx = offsetStartRodPx.modulus();
var lengthEndRodPx = offsetEndRodPx.modulus();
var lengthCenterRodPx = offsetCenterRodPx.modulus();
var rPx = offsetWidthPx.modulus() / 2;
this._ctx.save();
this._ctx.translate(startPx.e(1), startPx.e(2));
this._ctx.rotate(PrairieGeom.angleOf(offsetStartRodPx));
this._ctx.beginPath();
this._ctx.moveTo(0, rPx);
var angleStartToEnd = PrairieGeom.angleFrom(offsetStartRodPx, offsetEndRodPx);
var angleEndToCenter = PrairieGeom.angleFrom(offsetEndRodPx, offsetCenterRodPx);
if (Math.abs(angleEndToCenter) < Math.PI) {
var length1Px = lengthStartRodPx;
var length2Px = lengthEndRodPx;
var length3Px = lengthCenterRodPx;
var beta = -angleStartToEnd;
var alpha = -angleEndToCenter;
} else {
var length1Px = lengthStartRodPx;
var length2Px = lengthCenterRodPx;
var length3Px = lengthEndRodPx;
var beta = -PrairieGeom.angleFrom(offsetStartRodPx, offsetCenterRodPx);
var alpha = angleEndToCenter;
}
var x1 = length1Px + rPx / Math.sin(beta) - rPx / Math.tan(beta);
var y1 = rPx;
var x2 = length1Px + length2Px * Math.cos(beta);
var y2 = -length2Px * Math.sin(beta);
var x3 = x2 + rPx * Math.sin(beta);
var y3 = y2 + rPx * Math.cos(beta);
var x4 = x3 + rPx * Math.cos(beta);
var y4 = y3 - rPx * Math.sin(beta);
var x5 = x2 + rPx * Math.cos(beta);
var y5 = y2 - rPx * Math.sin(beta);
var x6 = x5 - rPx * Math.sin(beta);
var y6 = y5 - rPx * Math.cos(beta);
var x7 =
length1Px +
rPx * Math.cos(beta) * (1 / Math.sin(alpha) + 1 / Math.tan(alpha) - Math.tan(beta));
var y7 =
-rPx / Math.cos(beta) -
rPx * Math.sin(beta) * (1 / Math.sin(alpha) + 1 / Math.tan(alpha) - Math.tan(beta));
var x8 = length1Px + length3Px * Math.cos(beta + alpha);
var y8 = -length3Px * Math.sin(beta + alpha);
var x9 = x8 + rPx * Math.sin(beta + alpha);
var y9 = y8 + rPx * Math.cos(beta + alpha);
var x10 = x9 + rPx * Math.cos(beta + alpha);
var y10 = y9 - rPx * Math.sin(beta + alpha);
var x11 = x8 + rPx * Math.cos(beta + alpha);
var y11 = y8 - rPx * Math.sin(beta + alpha);
var x12 = x11 - rPx * Math.sin(beta + alpha);
var y12 = y11 - rPx * Math.cos(beta + alpha);
var x13 = length1Px - rPx / Math.sin(beta + alpha) + rPx / Math.tan(beta + alpha);
var y13 = -rPx;
this._ctx.arcTo(x1, y1, x3, y3, rPx);
this._ctx.arcTo(x4, y4, x5, y5, rPx);
this._ctx.arcTo(x6, y6, x7, y7, rPx);
this._ctx.arcTo(x7, y7, x9, y9, rPx);
this._ctx.arcTo(x10, y10, x11, y11, rPx);
this._ctx.arcTo(x12, y12, x13, y13, rPx);
this._ctx.arcTo(x13, y13, 0, -rPx, rPx);
this._ctx.arcTo(-rPx, -rPx, -rPx, rPx, rPx);
this._ctx.arcTo(-rPx, rPx, 0, rPx, rPx);
if (this._props.shapeInsideColor !== 'none') {
this._ctx.fillStyle = this._props.shapeInsideColor;
this._ctx.fill();
}
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.strokeStyle = this._props.shapeOutlineColor;
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a pivot.
@param {Vector} baseDw The center of the base (drawing coordinates).
@param {Vector} hingeDw The hinge point (center of circular end) in drawing coordinates.
@param {number} widthDw The width of the pivot (drawing coordinates).
*/
PrairieDraw.prototype.pivot = function (baseDw, hingeDw, widthDw) {
var offsetLengthDw = hingeDw.subtract(baseDw);
var offsetWidthDw = offsetLengthDw
.rotate(Math.PI / 2, $V([0, 0]))
.toUnitVector()
.x(widthDw);
var basePx = this.pos2Px(baseDw);
var offsetLengthPx = this.vec2Px(offsetLengthDw);
var offsetWidthPx = this.vec2Px(offsetWidthDw);
var lengthPx = offsetLengthPx.modulus();
var rPx = offsetWidthPx.modulus() / 2;
this._ctx.save();
this._ctx.translate(basePx.e(1), basePx.e(2));
this._ctx.rotate(PrairieGeom.angleOf(offsetLengthPx));
this._ctx.beginPath();
this._ctx.moveTo(0, rPx);
this._ctx.arcTo(lengthPx + rPx, rPx, lengthPx + rPx, -rPx, rPx);
this._ctx.arcTo(lengthPx + rPx, -rPx, 0, -rPx, rPx);
this._ctx.lineTo(0, -rPx);
this._ctx.closePath();
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.strokeStyle = this._props.shapeOutlineColor;
this._ctx.fillStyle = this._props.shapeInsideColor;
this._ctx.fill();
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a square with a given base point and center.
@param {Vector} baseDw The mid-point of the base (drawing coordinates).
@param {Vector} centerDw The center of the square (drawing coordinates).
*/
PrairieDraw.prototype.square = function (baseDw, centerDw) {
var basePx = this.pos2Px(baseDw);
var centerPx = this.pos2Px(centerDw);
var offsetPx = centerPx.subtract(basePx);
var rPx = offsetPx.modulus();
this._ctx.save();
this._ctx.translate(basePx.e(1), basePx.e(2));
this._ctx.rotate(PrairieGeom.angleOf(offsetPx));
this._ctx.beginPath();
this._ctx.rect(0, -rPx, 2 * rPx, 2 * rPx);
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.strokeStyle = this._props.shapeOutlineColor;
this._ctx.fillStyle = this._props.shapeInsideColor;
this._ctx.fill();
this._ctx.stroke();
this._ctx.restore();
};
/** Draw an axis-aligned rectangle with a given width and height, centered at the origin.
@param {number} widthDw The width of the rectangle.
@param {number} heightDw The height of the rectangle.
@param {number} centerDw Optional: The center of the rectangle (default: the origin).
@param {number} angleDw Optional: The rotation angle of the rectangle (default: zero).
@param {bool} filled Optional: Whether to fill the rectangle (default: true).
*/
PrairieDraw.prototype.rectangle = function (widthDw, heightDw, centerDw, angleDw, filled) {
centerDw = centerDw === undefined ? $V([0, 0]) : centerDw;
angleDw = angleDw === undefined ? 0 : angleDw;
var pointsDw = [
$V([-widthDw / 2, -heightDw / 2]),
$V([widthDw / 2, -heightDw / 2]),
$V([widthDw / 2, heightDw / 2]),
$V([-widthDw / 2, heightDw / 2]),
];
var closed = true;
filled = filled === undefined ? true : filled;
this.save();
this.translate(centerDw);
this.rotate(angleDw);
this.polyLine(pointsDw, closed, filled);
this.restore();
};
/** Draw a rectangle with the given corners and height.
@param {Vector} pos1Dw First corner of the rectangle.
@param {Vector} pos2Dw Second corner of the rectangle.
@param {number} heightDw The height of the rectangle.
*/
PrairieDraw.prototype.rectangleGeneric = function (pos1Dw, pos2Dw, heightDw) {
var dDw = PrairieGeom.perp(pos2Dw.subtract(pos1Dw)).toUnitVector().x(heightDw);
var pointsDw = [pos1Dw, pos2Dw, pos2Dw.add(dDw), pos1Dw.add(dDw)];
var closed = true;
this.polyLine(pointsDw, closed);
};
/** Draw a ground element.
@param {Vector} posDw The position of the ground center (drawing coordinates).
@param {Vector} normDw The outward normal (drawing coordinates).
@param (number} lengthDw The total length of the ground segment.
*/
PrairieDraw.prototype.ground = function (posDw, normDw, lengthDw) {
var tangentDw = normDw
.rotate(Math.PI / 2, $V([0, 0]))
.toUnitVector()
.x(lengthDw);
var posPx = this.pos2Px(posDw);
var normPx = this.vec2Px(normDw);
var tangentPx = this.vec2Px(tangentDw);
var lengthPx = tangentPx.modulus();
var groundDepthPx = Math.min(lengthPx, this._props.groundDepthPx);
this._ctx.save();
this._ctx.translate(posPx.e(1), posPx.e(2));
this._ctx.rotate(PrairieGeom.angleOf(normPx) - Math.PI / 2);
this._ctx.beginPath();
this._ctx.rect(-lengthPx / 2, -groundDepthPx, lengthPx, groundDepthPx);
this._ctx.fillStyle = this._props.groundInsideColor;
this._ctx.fill();
this._ctx.beginPath();
this._ctx.moveTo(-lengthPx / 2, 0);
this._ctx.lineTo(lengthPx / 2, 0);
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.strokeStyle = this._props.groundOutlineColor;
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a ground element with hashed shading.
@param {Vector} posDw The position of the ground center (drawing coords).
@param {Vector} normDw The outward normal (drawing coords).
@param (number} lengthDw The total length of the ground segment (drawing coords).
@param {number} offsetDw (Optional) The offset of the shading (drawing coords).
*/
PrairieDraw.prototype.groundHashed = function (posDw, normDw, lengthDw, offsetDw) {
offsetDw = offsetDw === undefined ? 0 : offsetDw;
var tangentDw = normDw
.rotate(Math.PI / 2, $V([0, 0]))
.toUnitVector()
.x(lengthDw);
var offsetVecDw = tangentDw.toUnitVector().x(offsetDw);
var posPx = this.pos2Px(posDw);
var normPx = this.vec2Px(normDw);
var tangentPx = this.vec2Px(tangentDw);
var lengthPx = tangentPx.modulus();
var offsetVecPx = this.vec2Px(offsetVecDw);
var offsetPx = offsetVecPx.modulus() * PrairieGeom.sign(offsetDw);
this._ctx.save();
this._ctx.translate(posPx.e(1), posPx.e(2));
this._ctx.rotate(PrairieGeom.angleOf(normPx) + Math.PI / 2);
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.strokeStyle = this._props.groundOutlineColor;
this._ctx.beginPath();
this._ctx.moveTo(-lengthPx / 2, 0);
this._ctx.lineTo(lengthPx / 2, 0);
this._ctx.stroke();
var startX = offsetPx % this._props.groundSpacingPx;
var x = startX;
while (x < lengthPx / 2) {
this._ctx.beginPath();
this._ctx.moveTo(x, 0);
this._ctx.lineTo(x - this._props.groundWidthPx, this._props.groundDepthPx);
this._ctx.stroke();
x += this._props.groundSpacingPx;
}
x = startX - this._props.groundSpacingPx;
while (x > -lengthPx / 2) {
this._ctx.beginPath();
this._ctx.moveTo(x, 0);
this._ctx.lineTo(x - this._props.groundWidthPx, this._props.groundDepthPx);
this._ctx.stroke();
x -= this._props.groundSpacingPx;
}
this._ctx.restore();
};
/** Draw an arc ground element.
@param {Vector} centerDw The center of the circle.
@param {Vector} radiusDw The radius of the circle.
@param {number} startAngle (Optional) The start angle of the arc (radians, default: 0).
@param {number} endAngle (Optional) The end angle of the arc (radians, default: 2 pi).
@param {bool} outside (Optional) Whether to draw the ground outside the curve (default: true).
*/
PrairieDraw.prototype.arcGround = function (centerDw, radiusDw, startAngle, endAngle, outside) {
startAngle = startAngle === undefined ? 0 : startAngle;
endAngle = endAngle === undefined ? 2 * Math.PI : endAngle;
outside = outside === undefined ? true : outside;
var centerPx = this.pos2Px(centerDw);
var offsetDw = $V([radiusDw, 0]);
var offsetPx = this.vec2Px(offsetDw);
var radiusPx = offsetPx.modulus();
var groundDepthPx = Math.min(radiusPx, this._props.groundDepthPx);
var groundOffsetPx = outside ? groundDepthPx : -groundDepthPx;
this._ctx.save();
// fill the shaded area
this._ctx.beginPath();
this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, -endAngle, -startAngle, false);
this._ctx.arc(
centerPx.e(1),
centerPx.e(2),
radiusPx + groundOffsetPx,
-startAngle,
-endAngle,
true
);
this._ctx.fillStyle = this._props.groundInsideColor;
this._ctx.fill();
// draw the ground surface
this._ctx.beginPath();
this._ctx.arc(centerPx.e(1), centerPx.e(2), radiusPx, -endAngle, -startAngle);
this._ctx.lineWidth = this._props.shapeStrokeWidthPx;
this._ctx.setLineDash(this._dashPattern(this._props.shapeStrokePattern));
this._ctx.strokeStyle = this._props.groundOutlineColor;
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a center-of-mass object.
@param {Vector} posDw The position of the center of mass.
*/
PrairieDraw.prototype.centerOfMass = function (posDw) {
var posPx = this.pos2Px(posDw);
var r = this._props.<API key>;
this._ctx.save();
this._ctx.lineWidth = this._props.<API key>;
this._ctx.strokeStyle = this._props.centerOfMassColor;
this._ctx.translate(posPx.e(1), posPx.e(2));
this._ctx.beginPath();
this._ctx.moveTo(-r, 0);
this._ctx.lineTo(r, 0);
this._ctx.stroke();
this._ctx.beginPath();
this._ctx.moveTo(0, -r);
this._ctx.lineTo(0, r);
this._ctx.stroke();
this._ctx.beginPath();
this._ctx.arc(0, 0, r, 0, 2 * Math.PI);
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a measurement line.
@param {Vector} startDw The start position of the measurement.
@param {Vector} endDw The end position of the measurement.
@param {string} text The measurement label.
*/
PrairieDraw.prototype.measurement = function (startDw, endDw, text) {
var startPx = this.pos2Px(startDw);
var endPx = this.pos2Px(endDw);
var offsetPx = endPx.subtract(startPx);
var d = offsetPx.modulus();
var h = this._props.<API key>;
var o = this._props.measurementOffsetPx;
this._ctx.save();
this._ctx.lineWidth = this._props.<API key>;
this._ctx.setLineDash(this._dashPattern(this._props.<API key>));
this._ctx.strokeStyle = this._props.measurementColor;
this._ctx.translate(startPx.e(1), startPx.e(2));
this._ctx.rotate(PrairieGeom.angleOf(offsetPx));
this._ctx.beginPath();
this._ctx.moveTo(0, o);
this._ctx.lineTo(0, o + h);
this._ctx.stroke();
this._ctx.beginPath();
this._ctx.moveTo(d, o);
this._ctx.lineTo(d, o + h);
this._ctx.stroke();
this._ctx.beginPath();
this._ctx.moveTo(0, o + h / 2);
this._ctx.lineTo(d, o + h / 2);
this._ctx.stroke();
this._ctx.restore();
var orthPx = offsetPx
.rotate(-Math.PI / 2, $V([0, 0]))
.toUnitVector()
.x(-o - h / 2);
var lineStartPx = startPx.add(orthPx);
var lineEndPx = endPx.add(orthPx);
var lineStartDw = this.pos2Dw(lineStartPx);
var lineEndDw = this.pos2Dw(lineEndPx);
this.labelLine(lineStartDw, lineEndDw, $V([0, -1]), text);
};
/** Draw a right angle.
@param {Vector} posDw The position angle point.
@param {Vector} dirDw The baseline direction (angle is counter-clockwise from this direction in 2D).
@param {Vector} normDw (Optional) The third direction (required for 3D).
*/
PrairieDraw.prototype.rightAngle = function (posDw, dirDw, normDw) {
if (dirDw.modulus() < 1e-20) {
return;
}
var posPx, dirPx, normPx;
if (posDw.elements.length === 3) {
posPx = this.pos2Px(this.pos3To2(posDw));
var d = this.vec2To3(this.vec2Dw($V([this._props.rightAngleSizePx, 0]))).modulus();
dirPx = this.vec2Px(this.vec3To2(dirDw.toUnitVector().x(d), posDw));
normPx = this.vec2Px(this.vec3To2(normDw.toUnitVector().x(d), posDw));
} else {
posPx = this.pos2Px(posDw);
dirPx = this.vec2Px(dirDw).toUnitVector().x(this._props.rightAngleSizePx);
if (normDw !== undefined) {
normPx = this.vec2Px(normDw).toUnitVector().x(this._props.rightAngleSizePx);
} else {
normPx = dirPx.rotate(-Math.PI / 2, $V([0, 0]));
}
}
this._ctx.save();
this._ctx.translate(posPx.e(1), posPx.e(2));
this._ctx.lineWidth = this._props.<API key>;
this._ctx.strokeStyle = this._props.rightAngleColor;
this._ctx.beginPath();
this._ctx.moveTo(dirPx.e(1), dirPx.e(2));
this._ctx.lineTo(dirPx.e(1) + normPx.e(1), dirPx.e(2) + normPx.e(2));
this._ctx.lineTo(normPx.e(1), normPx.e(2));
this._ctx.stroke();
this._ctx.restore();
};
/** Draw a right angle (improved version).
@param {Vector} p0Dw The base point.
@param {Vector} p1Dw The first other point.
@param {Vector} p2Dw The second other point.
*/
PrairieDraw.prototype.rightAngleImproved = function (p0Dw, p1Dw, p2Dw) {
var p0Px = this.pos2Px(this.pos3To2(p0Dw));
var p1Px = this.pos2Px(this.pos3To2(p1Dw));
var p2Px = this.pos2Px(this.pos3To2(p2Dw));
var d1Px = p1Px.subtract(p0Px);
var d2Px = p2Px.subtract(p0Px);
var minDLen = Math.min(d1Px.modulus(), d2Px.modulus());
if (minDLen < 1e-10) {
return;
}
var rightAngleSizePx = Math.min(minDLen / 2, this._props.rightAngleSizePx);
d1Px = d1Px.toUnitVector().x(rightAngleSizePx);
d2Px = d2Px.toUnitVector().x(rightAngleSizePx);
p1Px = p0Px.add(d1Px);
p2Px = p0Px.add(d2Px);
var p12Px = p1Px.add(d2Px);
this._ctx.save();
this._ctx.lineWidth = this._props.<API key>;
this._ctx.strokeStyle = this._props.rightAngleColor;
this._ctx.beginPath();
this._ctx.moveTo(p1Px.e(1), p1Px.e(2));
this._ctx.lineTo(p12Px.e(1), p12Px.e(2));
this._ctx.lineTo(p2Px.e(1), p2Px.e(2));
this._ctx.stroke();
this._ctx.restore();
};
/** Draw text.
@param {Vector} posDw The position to draw at.
@param {Vector} anchor The anchor on the text that will be located at pos (in -1 to 1 local coordinates).
@param {string} text The text to draw. If text begins with "TEX:" then it is interpreted as LaTeX.
@param {bool} boxed (Optional) Whether to draw a white box behind the text (default: false).
@param {Number} angle (Optional) The rotation angle (radians, default: 0).
*/
PrairieDraw.prototype.text = function (posDw, anchor, text, boxed, angle) {
if (text === undefined) {
return;
}
boxed = boxed === undefined ? false : boxed;
angle = angle === undefined ? 0 : angle;
var posPx = this.pos2Px(this.pos3To2(posDw));
var offsetPx;
if (text.length >= 4 && text.slice(0, 4) === 'TEX:') {
var texText = text.slice(4);
var hash = Sha1.hash(texText);
this._texts = this._texts || {};
var img;
if (hash in this._texts) {
img = this._texts[hash];
var xPx = (-(anchor.e(1) + 1) / 2) * img.width;
var yPx = ((anchor.e(2) - 1) / 2) * img.height;
//var offsetPx = anchor.toUnitVector().x(Math.abs(anchor.max()) * this._props.textOffsetPx);
offsetPx = anchor.x(this._props.textOffsetPx);
var textBorderPx = 5;
this._ctx.save();
this._ctx.translate(posPx.e(1), posPx.e(2));
this._ctx.rotate(angle);
if (boxed) {
this._ctx.save();
this._ctx.fillStyle = 'white';
this._ctx.fillRect(
xPx - offsetPx.e(1) - textBorderPx,
yPx + offsetPx.e(2) - textBorderPx,
img.width + 2 * textBorderPx,
img.height + 2 * textBorderPx
);
this._ctx.restore();
}
this._ctx.drawImage(img, xPx - offsetPx.e(1), yPx + offsetPx.e(2));
this._ctx.restore();
} else {
var imgSrc = 'text/' + hash + '.png';
img = new Image();
var that = this;
img.onload = function () {
that.redraw();
if (that.trigger) {
that.trigger('imgLoad');
}
};
img.src = imgSrc;
this._texts[hash] = img;
}
} else {
var align, baseline, bbRelOffset;
/* jshint indent: false */
switch (PrairieGeom.sign(anchor.e(1))) {
case -1:
align = 'left';
bbRelOffset = 0;
break;
case 0:
align = 'center';
bbRelOffset = 0.5;
break;
case 1:
align = 'right';
bbRelOffset = 1;
break;
}
switch (PrairieGeom.sign(anchor.e(2))) {
case -1:
baseline = 'bottom';
break;
case 0:
baseline = 'middle';
break;
case 1:
baseline = 'top';
break;
}
this.save();
this._ctx.textAlign = align;
this._ctx.textBaseline = baseline;
this._ctx.translate(posPx.e(1), posPx.e(2));
offsetPx = anchor.toUnitVector().x(Math.abs(anchor.max()) * this._props.textOffsetPx);
var drawPx = $V([-offsetPx.e(1), offsetPx.e(2)]);
var metrics = this._ctx.measureText(text);
var d = this._props.textOffsetPx;
//var bb0 = drawPx.add($V([-metrics.<API key> - d, -metrics.<API key> - d]));
//var bb1 = drawPx.add($V([metrics.<API key> + d, metrics.<API key> + d]));
var textHeight = this._props.textFontSize;
var bb0 = drawPx.add($V([-bbRelOffset * metrics.width - d, -d]));
var bb1 = drawPx.add($V([(1 - bbRelOffset) * metrics.width + d, textHeight + d]));
if (boxed) {
this._ctx.save();
this._ctx.fillStyle = 'white';
this._ctx.fillRect(bb0.e(1), bb0.e(2), bb1.e(1) - bb0.e(1), bb1.e(2) - bb0.e(2));
this._ctx.restore();
}
this._ctx.font = this._props.textFontSize.toString() + 'px serif';
this._ctx.fillText(text, drawPx.e(1), drawPx.e(2));
this.restore();
}
};
/** Draw text to label a line.
@param {Vector} startDw The start position of the line.
@param {Vector} endDw The end position of the line.
@param {Vector} pos The position relative to the line (-1 to 1 local coordinates, x along the line, y orthogonal).
@param {string} text The text to draw.
@param {Vector} anchor (Optional) The anchor position on the text.
*/
PrairieDraw.prototype.labelLine = function (startDw, endDw, pos, text, anchor) {
if (text === undefined) {
return;
}
startDw = this.pos3To2(startDw);
endDw = this.pos3To2(endDw);
var midpointDw = startDw.add(endDw).x(0.5);
var offsetDw = endDw.subtract(startDw).x(0.5);
var pDw = midpointDw.add(offsetDw.x(pos.e(1)));
var u1Dw = offsetDw.toUnitVector();
var u2Dw = u1Dw.rotate(Math.PI / 2, $V([0, 0]));
var oDw = u1Dw.x(pos.e(1)).add(u2Dw.x(pos.e(2)));
var a = oDw.x(-1).toUnitVector().x(Math.abs(pos.max()));
if (anchor !== undefined) {
a = anchor;
}
this.text(pDw, a, text);
};
/** Draw text to label a circle line.
@param {Vector} posDw The center of the circle line.
@param {number} radDw The radius at the mid-angle.
@param {number} startAngleDw The starting angle (counterclockwise from x axis, in radians).
@param {number} endAngleDw The ending angle (counterclockwise from x axis, in radians).
@param {Vector} pos The position relative to the line (-1 to 1 local coordinates, x along the line, y orthogonal).
@param {string} text The text to draw.
@param {bool} fixedRad (Optional) Whether to use a fixed radius (default: false).
*/
PrairieDraw.prototype.labelCircleLine = function (
posDw,
radDw,
startAngleDw,
endAngleDw,
pos,
text,
fixedRad
) {
// convert to Px coordinates
var startOffsetDw = PrairieGeom.vector2DAtAngle(startAngleDw).x(radDw);
var posPx = this.pos2Px(posDw);
var startOffsetPx = this.vec2Px(startOffsetDw);
var radiusPx = startOffsetPx.modulus();
var startAnglePx = PrairieGeom.angleOf(startOffsetPx);
var deltaAngleDw = endAngleDw - startAngleDw;
// assume a possibly reflected/rotated but equally scaled Dw/Px transformation
var deltaAnglePx = this._transIsReflection() ? -deltaAngleDw : deltaAngleDw;
var endAnglePx = startAnglePx + deltaAnglePx;
var textAnglePx =
((1.0 - pos.e(1)) / 2.0) * startAnglePx + ((1.0 + pos.e(1)) / 2.0) * endAnglePx;
var u1Px = PrairieGeom.vector2DAtAngle(textAnglePx);
var u2Px = u1Px.rotate(-Math.PI / 2, $V([0, 0]));
var u1Dw = this.vec2Dw(u1Px).toUnitVector();
var u2Dw = this.vec2Dw(u2Px).toUnitVector();
var oDw = u1Dw.x(pos.e(2)).add(u2Dw.x(pos.e(1)));
var aDw = oDw.x(-1).toUnitVector();
var a = aDw.x(1.0 / Math.abs(aDw.max())).x(Math.abs(pos.max()));
var rPx = this._circleArrowRadius(radiusPx, textAnglePx, startAnglePx, endAnglePx, fixedRad);
var pPx = u1Px.x(rPx).add(posPx);
var pDw = this.pos2Dw(pPx);
this.text(pDw, a, text);
};
/** Find the anchor for the intersection of several lines.
@param {Vector} labelPoint The point to be labeled.
@param {Array} points The end of the lines that meet at labelPoint.
@return {Vector} The anchor offset.
*/
PrairieDraw.prototype.<API key> = function (labelPointDw, pointsDw) {
// find the angles on the unit circle for each of the lines
var labelPointPx = this.pos2Px(this.pos3To2(labelPointDw));
var i, v;
var angles = [];
for (i = 0; i < pointsDw.length; i++) {
v = this.pos2Px(this.pos3To2(pointsDw[i])).subtract(labelPointPx);
v = $V([v.e(1), -v.e(2)]);
if (v.modulus() > 1e-6) {
angles.push(PrairieGeom.angleOf(v));
}
}
if (angles.length === 0) {
return $V([1, 0]);
}
// save the first angle to tie-break later
var tieBreakAngle = angles[0];
// find the biggest gap between angles (might be multiple)
angles.sort(function (a, b) {
return a - b;
});
var maxAngleDiff = angles[0] - angles[angles.length - 1] + 2 * Math.PI;
var maxIs = [0];
var angleDiff;
for (i = 1; i < angles.length; i++) {
angleDiff = angles[i] - angles[i - 1];
if (angleDiff > maxAngleDiff - 1e-6) {
if (angleDiff > maxAngleDiff + 1e-6) {
// we are clearly greater
maxAngleDiff = angleDiff;
maxIs = [i];
} else {
// we are basically equal
maxIs.push(i);
}
}
}
// tie-break by choosing the first angle CCW from the tieBreakAngle
var minCCWDiff = 2 * Math.PI;
var angle, bestAngle;
for (i = 0; i < maxIs.length; i++) {
angle = angles[maxIs[i]] - maxAngleDiff / 2;
angleDiff = angle - tieBreakAngle;
if (angleDiff < 0) {
angleDiff += 2 * Math.PI;
}
if (angleDiff < minCCWDiff) {
minCCWDiff = angleDiff;
bestAngle = angle;
}
}
// find anchor from bestAngle
var dir = PrairieGeom.vector2DAtAngle(bestAngle);
dir = dir.x(1 / PrairieGeom.supNorm(dir));
return dir.x(-1);
};
/** Label the intersection of several lines.
@param {Vector} labelPoint The point to be labeled.
@param {Array} points The end of the lines that meet at labelPoint.
@param {String} label The label text.
@param {Number} scaleOffset (Optional) Scale factor for the offset (default: 1).
*/
PrairieDraw.prototype.labelIntersection = function (labelPoint, points, label, scaleOffset) {
scaleOffset = scaleOffset === undefined ? 1 : scaleOffset;
var anchor = this.<API key>(labelPoint, points);
this.text(labelPoint, anchor.x(scaleOffset), label);
};
PrairieDraw.prototype.clearHistory = function (name) {
if (name in this._history) {
delete this._history[name];
} else {
console.log('WARNING: history not found: ' + name);
}
};
PrairieDraw.prototype.clearAllHistory = function () {
this._history = {};
};
/** Save the history of a data value.
@param {string} name The history variable name.
@param {number} dt The time resolution to save at.
@param {number} maxTime The maximum age of history to save.
@param {number} curTime The current time.
@param {object} curValue The current data value.
@return {Array} A history array of vectors of the form [time, value].
*/
PrairieDraw.prototype.history = function (name, dt, maxTime, curTime, curValue) {
if (!(name in this._history)) {
this._history[name] = [[curTime, curValue]];
} else {
var h = this._history[name];
if (h.length < 2) {
h.push([curTime, curValue]);
} else {
var prevPrevTime = h[h.length - 2][0];
if (curTime - prevPrevTime < dt) {
// new time jump will still be short, replace the last record
h[h.length - 1] = [curTime, curValue];
} else {
// new time jump would be too long, just add the new record
h.push([curTime, curValue]);
}
}
// discard old values as necessary
var i = 0;
while (curTime - h[i][0] > maxTime && i < h.length - 1) {
i++;
}
if (i > 0) {
this._history[name] = h.slice(i);
}
}
return this._history[name];
};
PrairieDraw.prototype.pairsToVectors = function (pairArray) {
var vectorArray = [];
for (var i = 0; i < pairArray.length; i++) {
vectorArray.push($V(pairArray[i]));
}
return vectorArray;
};
PrairieDraw.prototype.historyToTrace = function (data) {
var trace = [];
for (var i = 0; i < data.length; i++) {
trace.push(data[i][1]);
}
return trace;
};
/** Plot a history sequence.
@param {Vector} originDw The lower-left position of the axes.
@param {Vector} sizeDw The size of the axes (vector from lower-left to upper-right).
@param {Vector} sizeData The size of the axes in data coordinates.
@param {number} timeOffset The horizontal position for the current time.
@param {string} yLabel The vertical axis label.
@param {Array} data An array of [time, value] arrays to plot.
@param {string} type (Optional) The type of line being drawn.
*/
PrairieDraw.prototype.plotHistory = function (
originDw,
sizeDw,
sizeData,
timeOffset,
yLabel,
data,
type
) {
var scale = $V([sizeDw.e(1) / sizeData.e(1), sizeDw.e(2) / sizeData.e(2)]);
var lastTime = data[data.length - 1][0];
var offset = $V([timeOffset - lastTime, 0]);
var plotData = PrairieGeom.scalePoints(
PrairieGeom.translatePoints(this.pairsToVectors(data), offset),
scale
);
this.save();
this.translate(originDw);
this.save();
this.setProp('arrowLineWidthPx', 1);
this.setProp('<API key>', 11);
this.arrow($V([0, 0]), $V([sizeDw.e(1), 0]));
this.arrow($V([0, 0]), $V([0, sizeDw.e(2)]));
this.text($V([sizeDw.e(1), 0]), $V([1, 1.5]), 'TEX:$t$');
this.text($V([0, sizeDw.e(2)]), $V([1.5, 1]), yLabel);
this.restore();
var col = this._getColorProp(type);
this.setProp('shapeOutlineColor', col);
this.setProp('pointRadiusPx', '4');
this.save();
this._ctx.beginPath();
var bottomLeftPx = this.pos2Px($V([0, 0]));
var topRightPx = this.pos2Px(sizeDw);
var offsetPx = topRightPx.subtract(bottomLeftPx);
this._ctx.rect(bottomLeftPx.e(1), 0, offsetPx.e(1), this._height);
this._ctx.clip();
this.polyLine(plotData, false);
this.restore();
this.point(plotData[plotData.length - 1]);
this.restore();
};
/** Draw a history of positions as a faded line.
@param {Array} history History data, array of [time, position] pairs, where position is a vector.
@param {number} t Current time.
@param {number} maxT Maximum history time.
@param {Array} currentRGB RGB triple for current time color.
@param {Array} oldRGB RGB triple for old time color.
*/
PrairieDraw.prototype.fadeHistoryLine = function (history, t, maxT, currentRGB, oldRGB) {
if (history.length < 2) {
return;
}
for (var i = history.length - 2; i >= 0; i
// draw line backwards so newer segments are on top
var pT = history[i][0];
var pDw1 = history[i][1];
var pDw2 = history[i + 1][1];
var alpha = (t - pT) / maxT;
var rgb = PrairieGeom.linearInterpArray(currentRGB, oldRGB, alpha);
var color =
'rgb(' + rgb[0].toFixed(0) + ', ' + rgb[1].toFixed(0) + ', ' + rgb[2].toFixed(0) + ')';
this.line(pDw1, pDw2, color);
}
};
PrairieDraw.prototype.mouseDown3D = function (event) {
event.preventDefault();
this._mouseDown3D = true;
this._lastMouseX3D = event.clientX;
this._lastMouseY3D = event.clientY;
};
PrairieDraw.prototype.mouseUp3D = function () {
this._mouseDown3D = false;
};
PrairieDraw.prototype.mouseMove3D = function (event) {
if (!this._mouseDown3D) {
return;
}
var deltaX = event.clientX - this._lastMouseX3D;
var deltaY = event.clientY - this._lastMouseY3D;
this._lastMouseX3D = event.clientX;
this._lastMouseY3D = event.clientY;
this.incrementView3D(deltaY * 0.01, 0, deltaX * 0.01);
};
PrairieDraw.prototype.activate3DControl = function () {
/* Listen just on the canvas for mousedown, but on whole window
* for move/up. This allows mouseup while off-canvas (and even
* off-window) to be captured. Ideally we should also listen for
* mousedown on the whole window and use mouseEventOnCanvas(), but
* this is broken on Canary for some reason (some areas off-canvas
* don't work). The advantage of listening for mousedown on the
* whole window is that we can get the event during the "capture"
* phase rather than the later "bubble" phase, allowing us to
* preventDefault() before things like select-drag starts. */
this._canvas.addEventListener('mousedown', this.mouseDown3D.bind(this), true);
window.addEventListener('mouseup', this.mouseUp3D.bind(this), true);
window.addEventListener('mousemove', this.mouseMove3D.bind(this), true);
};
PrairieDraw.prototype.mouseDownTracking = function (event) {
event.preventDefault();
this._mouseDownTracking = true;
this._lastMouseXTracking = event.pageX;
this._lastMouseYTracking = event.pageY;
};
PrairieDraw.prototype.mouseUpTracking = function () {
this._mouseDownTracking = false;
};
PrairieDraw.prototype.mouseMoveTracking = function (event) {
if (!this._mouseDownTracking) {
return;
}
this._lastMouseXTracking = event.pageX;
this._lastMouseYTracking = event.pageY;
};
PrairieDraw.prototype.<API key> = function () {
this._canvas.addEventListener('mousedown', this.mouseDownTracking.bind(this), true);
window.addEventListener('mouseup', this.mouseUpTracking.bind(this), true);
window.addEventListener('mousemove', this.mouseMoveTracking.bind(this), true);
};
PrairieDraw.prototype.mouseDown = function () {
if (this._mouseDownTracking !== undefined) {
return this._mouseDownTracking;
} else {
return false;
}
};
PrairieDraw.prototype.mousePositionDw = function () {
var xPx = this._lastMouseXTracking - this._canvas.offsetLeft;
var yPx = this._lastMouseYTracking - this._canvas.offsetTop;
var posPx = $V([xPx, yPx]);
var posDw = this.pos2Dw(posPx);
return posDw;
};
/** Creates a PrairieDrawAnim object.
@constructor
@this {PrairieDraw}
@param {HTMLCanvasElement or string} canvas The canvas element to draw on or the ID of the canvas elemnt.
@param {Function} drawfcn An optional function that draws on the canvas at time t.
*/
function PrairieDrawAnim(canvas, drawFcn) {
PrairieDraw.call(this, canvas, null);
this._drawTime = 0;
this._deltaTime = 0;
this._running = false;
this._sequences = {};
this._animStateCallbacks = [];
this._animStepCallbacks = [];
if (drawFcn) {
this.draw = drawFcn.bind(this);
}
this.save();
this.draw(0);
this.restoreAll();
}
PrairieDrawAnim.prototype = new PrairieDraw();
/** @private Store the appropriate version of <API key>.
Use this like:
prairieDraw.<API key>.call(window, this.callback.bind(this));
We can't do prairieDraw.<API key>(callback), because
that would run <API key> in the context of prairieDraw
("this" would be prairieDraw), and <API key> needs
"this" to be "window".
We need to pass this.callback.bind(this) as the callback function
rather than just this.callback as otherwise the callback functions
is called from "window" context, and we want it to be called from
the context of our own object.
*/
/* jshint laxbreak: true */
if (typeof window !== 'undefined') {
PrairieDrawAnim.prototype.<API key> =
window.<API key> ||
window.<API key> ||
window.<API key> ||
window.<API key>;
}
/** Prototype function to draw on the canvas, should be implemented by children.
@param {number} t Current animation time in seconds.
*/
PrairieDrawAnim.prototype.draw = function (t) {
/* jshint unused: false */
};
/** Start the animation.
*/
PrairieDrawAnim.prototype.startAnim = function () {
if (!this._running) {
this._running = true;
this._startFrame = true;
this.<API key>.call(window, this._callback.bind(this));
for (var i = 0; i < this._animStateCallbacks.length; i++) {
this._animStateCallbacks[i](true);
}
}
};
/** Stop the animation.
*/
PrairieDrawAnim.prototype.stopAnim = function () {
this._running = false;
for (var i = 0; i < this._animStateCallbacks.length; i++) {
this._animStateCallbacks[i](false);
}
};
/** Toggle the animation.
*/
PrairieDrawAnim.prototype.toggleAnim = function () {
if (this._running) {
this.stopAnim();
} else {
this.startAnim();
}
};
/** Register a callback on animation state changes.
@param {Function} callback The callback(animated) function.
*/
PrairieDrawAnim.prototype.<API key> = function (callback) {
this._animStateCallbacks.push(callback.bind(this));
callback.apply(this, [this._running]);
};
/** Register a callback on animation steps.
@param {Function} callback The callback(t) function.
*/
PrairieDrawAnim.prototype.<API key> = function (callback) {
this._animStepCallbacks.push(callback.bind(this));
};
/** @private Callback function to handle the animationFrame events.
*/
PrairieDrawAnim.prototype._callback = function (tMS) {
if (this._startFrame) {
this._startFrame = false;
this._timeOffset = tMS - this._drawTime;
}
var animTime = tMS - this._timeOffset;
this._deltaTime = (animTime - this._drawTime) / 1000;
this._drawTime = animTime;
var t = animTime / 1000;
for (var i = 0; i < this._animStepCallbacks.length; i++) {
this._animStepCallbacks[i](t);
}
this.save();
this.draw(t);
this._deltaTime = 0;
this.restoreAll();
if (this._running) {
this.<API key>.call(window, this._callback.bind(this));
}
};
/** Get the elapsed time since the last redraw.
return {number} Elapsed time in seconds.
*/
PrairieDrawAnim.prototype.deltaTime = function () {
return this._deltaTime;
};
/** Redraw the drawing at the current time.
*/
PrairieDrawAnim.prototype.redraw = function () {
if (!this._running) {
this.save();
this.draw(this._drawTime / 1000);
this.restoreAll();
}
};
/** Reset the animation time to zero.
@param {bool} redraw (Optional) Whether to redraw (default: true).
*/
PrairieDrawAnim.prototype.resetTime = function (redraw) {
this._drawTime = 0;
for (var i = 0; i < this._animStepCallbacks.length; i++) {
this._animStepCallbacks[i](0);
}
this._startFrame = true;
if (redraw === undefined || redraw === true) {
this.redraw();
}
};
/** Reset everything to the intial state.
*/
PrairieDrawAnim.prototype.reset = function () {
for (var optionName in this._options) {
this.resetOptionValue(optionName);
}
this.resetAllSequences();
this.clearAllHistory();
this.stopAnim();
this.resetView3D(false);
this.resetTime(false);
this.redraw();
};
/** Stop all action and computation.
*/
PrairieDrawAnim.prototype.stop = function () {
this.stopAnim();
};
PrairieDrawAnim.prototype.lastDrawTime = function () {
return this._drawTime / 1000;
};
PrairieDrawAnim.prototype.<API key> = function (event) {
event.preventDefault();
this.startAnim();
};
PrairieDrawAnim.prototype.activateAnimOnClick = function () {
this._canvas.addEventListener('mousedown', this.<API key>.bind(this), true);
};
/** Interpolate between different states in a sequence.
@param {Array} states An array of objects, each specifying scalar or vector state values.
@param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1].
@param {Array} holdTimes Hold times for the corresponding state.
@param {Array} t Current time.
@return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding).
*/
PrairieDrawAnim.prototype.sequence = function (states, transTimes, holdTimes, t) {
var totalTime = 0;
var i;
for (i = 0; i < states.length; i++) {
totalTime += transTimes[i];
totalTime += holdTimes[i];
}
var ts = t % totalTime;
totalTime = 0;
var state = {};
var e, ip;
var lastTotalTime = 0;
for (i = 0; i < states.length; i++) {
ip = i === states.length - 1 ? 0 : i + 1;
totalTime += transTimes[i];
if (totalTime > ts) {
// in transition from i to i+1
state.t = ts - lastTotalTime;
state.index = i;
state.alpha = state.t / (totalTime - lastTotalTime);
for (e in states[i]) {
state[e] = PrairieGeom.linearInterp(states[i][e], states[ip][e], state.alpha);
}
return state;
}
lastTotalTime = totalTime;
totalTime += holdTimes[i];
if (totalTime > ts) {
// holding at i+1
state.t = 0;
state.index = ip;
state.alpha = 0;
for (e in states[i]) {
state[e] = states[ip][e];
}
return state;
}
lastTotalTime = totalTime;
}
};
/** Interpolate between different states in a sequence under external prompting.
@param {string} name Name of this transition sequence.
@param {Array} states An array of objects, each specifying scalar or vector state values.
@param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1].
@param {Array} t Current animation time.
@return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding).
*/
PrairieDrawAnim.prototype.controlSequence = function (name, states, transTimes, t) {
if (!(name in this._sequences)) {
this._sequences[name] = {
index: 0,
inTransition: false,
startTransition: false,
indefiniteHold: true,
callbacks: [],
};
}
var seq = this._sequences[name];
var state;
var transTime = 0;
if (seq.startTransition) {
seq.startTransition = false;
seq.inTransition = true;
seq.indefiniteHold = false;
seq.startTime = t;
}
if (seq.inTransition) {
transTime = t - seq.startTime;
}
if (seq.inTransition && transTime >= transTimes[seq.index]) {
seq.inTransition = false;
seq.indefiniteHold = true;
seq.index = (seq.index + 1) % states.length;
delete seq.startTime;
}
if (!seq.inTransition) {
state = PrairieGeom.dupState(states[seq.index]);
state.index = seq.index;
state.t = 0;
state.alpha = 0;
state.inTransition = false;
return state;
}
var alpha = transTime / transTimes[seq.index];
var nextIndex = (seq.index + 1) % states.length;
state = PrairieGeom.linearInterpState(states[seq.index], states[nextIndex], alpha);
state.t = transTime;
state.index = seq.index;
state.alpha = alpha;
state.inTransition = true;
return state;
};
/** Start the next transition for the given sequence.
@param {string} name Name of the sequence to transition.
@param {string} stateName (Optional) Only transition if we are currently in stateName.
*/
PrairieDrawAnim.prototype.stepSequence = function (name, stateName) {
if (!(name in this._sequences)) {
throw new Error('PrairieDraw: unknown sequence: ' + name);
}
var seq = this._sequences[name];
if (!seq.lastState.indefiniteHold) {
return;
}
if (stateName !== undefined) {
if (seq.lastState.name !== stateName) {
return;
}
}
seq.startTransition = true;
this.startAnim();
};
/** Interpolate between different states (new version).
@param {string} name Name of this transition sequence.
@param {Array} states An array of objects, each specifying scalar or vector state values.
@param {Array} transTimes Transition times. transTimes[i] is the transition time from states[i] to states[i+1].
@param {Array} holdtimes Hold times for each state. A negative value means to hold until externally triggered.
@param {Array} t Current animation time.
@return Object with state variables set to current values, as well as t being the time within the current transition (0 if holding), index being the current state index (or the next state if transitioning), and alpha being the proportion of the current transition (0 if holding).
*/
PrairieDrawAnim.prototype.newSequence = function (
name,
states,
transTimes,
holdTimes,
interps,
names,
t
) {
var seq = this._sequences[name];
if (seq === undefined) {
this._sequences[name] = {
startTransition: false,
lastState: {},
callbacks: [],
initialized: false,
};
seq = this._sequences[name];
}
var i;
if (!seq.initialized) {
seq.initialized = true;
for (var e in states[0]) {
if (typeof states[0][e] === 'number') {
seq.lastState[e] = states[0][e];
} else if (typeof states[0][e] === 'function') {
seq.lastState[e] = states[0][e](null, 0);
}
}
seq.lastState.inTransition = false;
seq.lastState.indefiniteHold = false;
seq.lastState.index = 0;
seq.lastState.name = names[seq.lastState.index];
seq.lastState.t = 0;
seq.lastState.realT = t;
if (holdTimes[0] < 0) {
seq.lastState.indefiniteHold = true;
}
for (i = 0; i < seq.callbacks.length; i++) {
seq.callbacks[i]('enter', seq.lastState.index, seq.lastState.name);
}
}
if (seq.startTransition) {
seq.startTransition = false;
seq.lastState.inTransition = true;
seq.lastState.indefiniteHold = false;
seq.lastState.t = 0;
seq.lastState.realT = t;
for (i = 0; i < seq.callbacks.length; i++) {
seq.callbacks[i]('exit', seq.lastState.index, seq.lastState.name);
}
}
var endTime, nextIndex;
while (true) {
nextIndex = (seq.lastState.index + 1) % states.length;
if (seq.lastState.inTransition) {
endTime = seq.lastState.realT + transTimes[seq.lastState.index];
if (t >= endTime) {
seq.lastState = this._interpState(
seq.lastState,
states[nextIndex],
interps,
endTime,
endTime
);
seq.lastState.inTransition = false;
seq.lastState.index = nextIndex;
seq.lastState.name = names[seq.lastState.index];
if (holdTimes[nextIndex] < 0) {
seq.lastState.indefiniteHold = true;
} else {
seq.lastState.indefiniteHold = false;
}
for (i = 0; i < seq.callbacks.length; i++) {
seq.callbacks[i]('enter', seq.lastState.index, seq.lastState.name);
}
} else {
return this._interpState(seq.lastState, states[nextIndex], interps, t, endTime);
}
} else {
endTime = seq.lastState.realT + holdTimes[seq.lastState.index];
if (holdTimes[seq.lastState.index] >= 0 && t > endTime) {
seq.lastState = this._extrapState(seq.lastState, states[seq.lastState.index], endTime);
seq.lastState.inTransition = true;
seq.lastState.indefiniteHold = false;
for (i = 0; i < seq.callbacks.length; i++) {
seq.callbacks[i]('exit', seq.lastState.index, seq.lastState.name);
}
} else {
return this._extrapState(seq.lastState, states[seq.lastState.index], t);
}
}
}
};
PrairieDrawAnim.prototype._interpState = function (lastState, nextState, interps, t, tFinal) {
var s1 = PrairieGeom.dupState(nextState);
s1.realT = tFinal;
s1.t = tFinal - lastState.realT;
var s = {};
var alpha = (t - lastState.realT) / (tFinal - lastState.realT);
for (var e in nextState) {
if (e in interps) {
s[e] = interps[e](lastState, s1, t - lastState.realT);
} else {
s[e] = PrairieGeom.linearInterp(lastState[e], s1[e], alpha);
}
}
s.realT = t;
s.t = Math.min(t - lastState.realT, s1.t);
s.index = lastState.index;
s.inTransition = lastState.inTransition;
s.indefiniteHold = lastState.indefiniteHold;
return s;
};
PrairieDrawAnim.prototype._extrapState = function (lastState, lastStateData, t) {
var s = {};
for (var e in lastStateData) {
if (typeof lastStateData[e] === 'number') {
s[e] = lastStateData[e];
} else if (typeof lastStateData[e] === 'function') {
s[e] = lastStateData[e](lastState, t - lastState.realT);
}
}
s.realT = t;
s.t = t - lastState.realT;
s.index = lastState.index;
s.inTransition = lastState.inTransition;
s.indefiniteHold = lastState.indefiniteHold;
return s;
};
/** Register a callback on animation sequence events.
@param {string} seqName The sequence to register on.
@param {Function} callback The callback(event, index, stateName) function.
*/
PrairieDrawAnim.prototype.registerSeqCallback = function (seqName, callback) {
if (!(seqName in this._sequences)) {
throw new Error('PrairieDraw: unknown sequence: ' + seqName);
}
var seq = this._sequences[seqName];
seq.callbacks.push(callback.bind(this));
if (seq.inTransition) {
callback.apply(this, ['exit', seq.lastState.index, seq.lastState.name]);
} else {
callback.apply(this, ['enter', seq.lastState.index, seq.lastState.name]);
}
};
/** Make a two-state sequence transitioning to and from 0 and 1.
@param {string} name The name of the sequence;
@param {number} transTime The transition time between the two states.
@return {number} The current state (0 to 1).
*/
PrairieDrawAnim.prototype.activationSequence = function (name, transTime, t) {
var stateZero = { trans: 0 };
var stateOne = { trans: 1 };
var states = [stateZero, stateOne];
var transTimes = [transTime, transTime];
var holdTimes = [-1, -1];
var interps = {};
var names = ['zero', 'one'];
var state = this.newSequence(name, states, transTimes, holdTimes, interps, names, t);
return state.trans;
};
PrairieDrawAnim.prototype.resetSequence = function (name) {
var seq = this._sequences[name];
if (seq !== undefined) {
seq.initialized = false;
}
};
PrairieDrawAnim.prototype.resetAllSequences = function () {
for (var name in this._sequences) {
this.resetSequence(name);
}
};
PrairieDraw.prototype.drawImage = function (imgSrc, posDw, anchor, widthDw) {
var img;
if (imgSrc in this._images) {
// FIXME: should check that the image is really loaded, in case we are fired beforehand (also for text images).
img = this._images[imgSrc];
var posPx = this.pos2Px(posDw);
var scale;
if (widthDw === undefined) {
scale = 1;
} else {
var offsetDw = $V([widthDw, 0]);
var offsetPx = this.vec2Px(offsetDw);
var widthPx = offsetPx.modulus();
scale = widthPx / img.width;
}
var xPx = (-(anchor.e(1) + 1) / 2) * img.width;
var yPx = ((anchor.e(2) - 1) / 2) * img.height;
this._ctx.save();
this._ctx.translate(posPx.e(1), posPx.e(2));
this._ctx.scale(scale, scale);
this._ctx.translate(xPx, yPx);
this._ctx.drawImage(img, 0, 0);
this._ctx.restore();
} else {
img = new Image();
var that = this;
img.onload = function () {
that.redraw();
if (that.trigger) {
that.trigger('imgLoad');
}
};
img.src = imgSrc;
this._images[imgSrc] = img;
}
};
PrairieDraw.prototype.mouseEventPx = function (event) {
var element = this._canvas;
var xPx = event.pageX;
var yPx = event.pageY;
do {
xPx -= element.offsetLeft;
yPx -= element.offsetTop;
/* jshint boss: true */ // suppress warning for assignment on next line
} while ((element = element.offsetParent));
xPx *= this._canvas.width / this._canvas.scrollWidth;
yPx *= this._canvas.height / this._canvas.scrollHeight;
var posPx = $V([xPx, yPx]);
return posPx;
};
PrairieDraw.prototype.mouseEventDw = function (event) {
var posPx = this.mouseEventPx(event);
var posDw = this.pos2Dw(posPx);
return posDw;
};
PrairieDraw.prototype.mouseEventOnCanvas = function (event) {
var posPx = this.mouseEventPx(event);
console.log(posPx.e(1), posPx.e(2), this._width, this._height);
/* jshint laxbreak: true */
if (
posPx.e(1) >= 0 &&
posPx.e(1) <= this._width &&
posPx.e(2) >= 0 &&
posPx.e(2) <= this._height
) {
console.log(true);
return true;
}
console.log(false);
return false;
};
PrairieDraw.prototype.reportMouseSample = function (event) {
var posDw = this.mouseEventDw(event);
var numDecPlaces = 2;
/* jshint laxbreak: true */
console.log(
'$V([' + posDw.e(1).toFixed(numDecPlaces) + ', ' + posDw.e(2).toFixed(numDecPlaces) + ']),'
);
};
PrairieDraw.prototype.<API key> = function () {
this._canvas.addEventListener('click', this.reportMouseSample.bind(this));
};
PrairieDraw.prototype.<API key> = function () {
if (this.<API key> === true) {
return;
}
this.<API key> = true;
this.mouseLineDraw = false;
this.mouseLineDrawing = false;
if (this.<API key> !== true) {
this.<API key> = true;
if (this._mouseDrawCallbacks === undefined) {
this._mouseDrawCallbacks = [];
}
this._canvas.addEventListener('mousedown', this.<API key>.bind(this), true);
window.addEventListener('mouseup', this.<API key>.bind(this), true);
window.addEventListener('mousemove', this.<API key>.bind(this), true);
}
/*
for (var i = 0; i < this._mouseDrawCallbacks.length; i++) {
this._mouseDrawCallbacks[i]();
}
this.redraw();
*/
};
PrairieDraw.prototype.<API key> = function () {
this.<API key> = false;
this.mouseLineDraw = false;
this.mouseLineDrawing = false;
this.redraw();
};
PrairieDraw.prototype.<API key> = function (event) {
if (!this.<API key>) {
return;
}
event.preventDefault();
var posDw = this.mouseEventDw(event);
this.mouseLineDrawStart = posDw;
this.mouseLineDrawEnd = posDw;
this.mouseLineDrawing = true;
this.mouseLineDraw = true;
for (var i = 0; i < this._mouseDrawCallbacks.length; i++) {
this._mouseDrawCallbacks[i]();
}
this.redraw();
};
PrairieDraw.prototype.<API key> = function (event) {
if (!this.<API key>) {
return;
}
if (!this.mouseLineDrawing) {
return;
}
this.mouseLineDrawEnd = this.mouseEventDw(event);
for (var i = 0; i < this._mouseDrawCallbacks.length; i++) {
this._mouseDrawCallbacks[i]();
}
this.redraw(); // FIXME: add rate-limiting
};
PrairieDraw.prototype.<API key> = function () {
if (!this.<API key>) {
return;
}
if (!this.mouseLineDrawing) {
return;
}
this.mouseLineDrawing = false;
for (var i = 0; i < this._mouseDrawCallbacks.length; i++) {
this._mouseDrawCallbacks[i]();
}
this.redraw();
};
PrairieDraw.prototype.<API key> = function (event) {
if (!this.<API key>) {
return;
}
if (!this.mouseLineDrawing) {
return;
}
this.mouseLineDrawEnd = this.mouseEventDw(event);
this.mouseLineDrawing = false;
for (var i = 0; i < this._mouseDrawCallbacks.length; i++) {
this._mouseDrawCallbacks[i]();
}
this.redraw();
};
PrairieDraw.prototype.<API key> = function (callback) {
if (this._mouseDrawCallbacks === undefined) {
this._mouseDrawCallbacks = [];
}
this._mouseDrawCallbacks.push(callback.bind(this));
};
/** Plot a line graph.
@param {Array} data Array of vectors to plot.
@param {Vector} originDw The lower-left position of the axes.
@param {Vector} sizeDw The size of the axes (vector from lower-left to upper-right).
@param {Vector} originData The lower-left position of the axes in data coordinates.
@param {Vector} sizeData The size of the axes in data coordinates.
@param {string} xLabel The vertical axis label.
@param {string} yLabel The vertical axis label.
@param {string} type (Optional) The type of line being drawn.
@param {string} drawAxes (Optional) Whether to draw the axes (default: true).
@param {string} drawPoint (Optional) Whether to draw the last point (default: true).
@param {string} pointLabel (Optional) Label for the last point (default: undefined).
@param {string} pointAnchor (Optional) Anchor for the last point label (default: $V([0, -1])).
@param {Object} options (Optional) Plotting options:
horizAxisPos: "bottom", "top", or a numerical value in data coordinates (default: "bottom")
vertAxisPos: "left", "right", or a numerical value in data coordinates (default: "left")
*/
PrairieDraw.prototype.plot = function (
data,
originDw,
sizeDw,
originData,
sizeData,
xLabel,
yLabel,
type,
drawAxes,
drawPoint,
pointLabel,
pointAnchor,
options
) {
drawAxes = drawAxes === undefined ? true : drawAxes;
drawPoint = drawPoint === undefined ? true : drawPoint;
options = options === undefined ? {} : options;
var horizAxisPos = options.horizAxisPos === undefined ? 'bottom' : options.horizAxisPos;
var vertAxisPos = options.vertAxisPos === undefined ? 'left' : options.vertAxisPos;
var drawXGrid = options.drawXGrid === undefined ? false : options.drawXGrid;
var drawYGrid = options.drawYGrid === undefined ? false : options.drawYGrid;
var dXGrid = options.dXGrid === undefined ? 1 : options.dXGrid;
var dYGrid = options.dYGrid === undefined ? 1 : options.dYGrid;
var drawXTickLabels = options.drawXTickLabels === undefined ? false : options.drawXTickLabels;
var drawYTickLabels = options.drawYTickLabels === undefined ? false : options.drawYTickLabels;
var xLabelPos = options.xLabelPos === undefined ? 1 : options.xLabelPos;
var yLabelPos = options.yLabelPos === undefined ? 1 : options.yLabelPos;
var xLabelAnchor = options.xLabelAnchor === undefined ? $V([1, 1.5]) : options.xLabelAnchor;
var yLabelAnchor = options.yLabelAnchor === undefined ? $V([1.5, 1]) : options.yLabelAnchor;
var yLabelRotate = options.yLabelRotate === undefined ? false : options.yLabelRotate;
this.save();
this.translate(originDw);
// grid
var ix0 = Math.ceil(originData.e(1) / dXGrid);
var ix1 = Math.floor((originData.e(1) + sizeData.e(1)) / dXGrid);
var x0 = 0;
var x1 = sizeDw.e(1);
var iy0 = Math.ceil(originData.e(2) / dYGrid);
var iy1 = Math.floor((originData.e(2) + sizeData.e(2)) / dYGrid);
var y0 = 0;
var y1 = sizeDw.e(2);
var i, x, y;
if (drawXGrid) {
for (i = ix0; i <= ix1; i++) {
x = PrairieGeom.linearMap(
originData.e(1),
originData.e(1) + sizeData.e(1),
0,
sizeDw.e(1),
i * dXGrid
);
this.line($V([x, y0]), $V([x, y1]), 'grid');
}
}
if (drawYGrid) {
for (i = iy0; i <= iy1; i++) {
y = PrairieGeom.linearMap(
originData.e(2),
originData.e(2) + sizeData.e(2),
0,
sizeDw.e(2),
i * dYGrid
);
this.line($V([x0, y]), $V([x1, y]), 'grid');
}
}
var label;
if (drawXTickLabels) {
for (i = ix0; i <= ix1; i++) {
x = PrairieGeom.linearMap(
originData.e(1),
originData.e(1) + sizeData.e(1),
0,
sizeDw.e(1),
i * dXGrid
);
label = String(i * dXGrid);
this.text($V([x, y0]), $V([0, 1]), label);
}
}
if (drawYTickLabels) {
for (i = iy0; i <= iy1; i++) {
y = PrairieGeom.linearMap(
originData.e(2),
originData.e(2) + sizeData.e(2),
0,
sizeDw.e(2),
i * dYGrid
);
label = String(i * dYGrid);
this.text($V([x0, y]), $V([1, 0]), label);
}
}
// axes
var axisX, axisY;
if (vertAxisPos === 'left') {
axisX = 0;
} else if (vertAxisPos === 'right') {
axisX = sizeDw.e(1);
} else {
axisX = PrairieGeom.linearMap(
originData.e(1),
originData.e(1) + sizeData.e(1),
0,
sizeDw.e(1),
vertAxisPos
);
}
if (horizAxisPos === 'bottom') {
axisY = 0;
} else if (horizAxisPos === 'top') {
axisY = sizeDw.e(2);
} else {
axisY = PrairieGeom.linearMap(
originData.e(2),
originData.e(2) + sizeData.e(2),
0,
sizeDw.e(2),
horizAxisPos
);
}
if (drawAxes) {
this.save();
this.setProp('arrowLineWidthPx', 1);
this.setProp('<API key>', 11);
this.arrow($V([0, axisY]), $V([sizeDw.e(1), axisY]));
this.arrow($V([axisX, 0]), $V([axisX, sizeDw.e(2)]));
x = xLabelPos * sizeDw.e(1);
y = yLabelPos * sizeDw.e(2);
this.text($V([x, axisY]), xLabelAnchor, xLabel);
var angle = yLabelRotate ? -Math.PI / 2 : 0;
this.text($V([axisX, y]), yLabelAnchor, yLabel, undefined, angle);
this.restore();
}
var col = this._getColorProp(type);
this.setProp('shapeOutlineColor', col);
this.setProp('pointRadiusPx', '4');
var bottomLeftPx = this.pos2Px($V([0, 0]));
var topRightPx = this.pos2Px(sizeDw);
var offsetPx = topRightPx.subtract(bottomLeftPx);
this.save();
this.scale(sizeDw);
this.scale($V([1 / sizeData.e(1), 1 / sizeData.e(2)]));
this.translate(originData.x(-1));
this.save();
this._ctx.beginPath();
this._ctx.rect(bottomLeftPx.e(1), 0, offsetPx.e(1), this._height);
this._ctx.clip();
this.polyLine(data, false);
this.restore();
if (drawPoint) {
this.point(data[data.length - 1]);
if (pointLabel !== undefined) {
if (pointAnchor === undefined) {
pointAnchor = $V([0, -1]);
}
this.text(data[data.length - 1], pointAnchor, pointLabel);
}
}
this.restore();
this.restore();
};
return {
PrairieDraw: PrairieDraw,
PrairieDrawAnim: PrairieDrawAnim,
};
});
|
# This program is free software: you can redistribute it and/or modify
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
require File.dirname(__FILE__) + '/../spec_helper'
describe Project do
def create_project(options={})
Project.new({
:title => "foo project",
:slug => "foo",
:description => "my little project",
:user => users(:johan)
}.merge(options))
end
it "should have valid associations" do
create_project.should <API key>
end
it "should have a title to be valid" do
project = create_project(:title => nil)
project.should_not be_valid
project.title = "foo"
project.should be_valid
end
it "should have a slug to be valid" do
project = create_project(:slug => nil)
project.should_not be_valid
end
it "should have a unique slug to be valid" do
p1 = create_project
p1.save!
p2 = create_project(:slug => "FOO")
p2.should_not be_valid
p2.should have(1).error_on(:slug)
end
it "should have an alphanumeric slug" do
project = create_project(:slug => "asd asd")
project.valid?
project.should_not be_valid
end
it "should downcase the slug before validation" do
project = create_project(:slug => "FOO")
project.valid?
project.slug.should == "foo"
end
it "creates an initial repository for itself" do
project = create_project
project.save
project.repositories.should_not == []
project.repositories.first.name.should == "mainline"
project.repositories.first.user.should == project.user
project.user.can_write_to?(project.repositories.first).should == true
end
it "creates the wiki repository on create" do
project = create_project(:slug => "my-new-project")
project.save!
project.wiki_repository.should be_instance_of(Repository)
project.wiki_repository.name.should == "my-new-project#{Repository::WIKI_NAME_SUFFIX}"
project.wiki_repository.kind.should == Repository::KIND_WIKI
project.repositories.should_not include(project.wiki_repository)
end
it "finds a project by slug or raises" do
Project.find_by_slug!(projects(:johans).slug).should == projects(:johans)
proc{
Project.find_by_slug!("asdasdasd")
}.should raise_error(ActiveRecord::RecordNotFound)
end
it "has the slug as its params" do
projects(:johans).to_param.should == projects(:johans).slug
end
it "knows if a user is a admin on a project" do
projects(:johans).admin?(users(:johan)).should == true
projects(:johans).admin?(users(:moe)).should == false
projects(:johans).admin?(:false).should == false
end
it "knows if a user can delete the project" do
project = projects(:johans)
project.can_be_deleted_by?(users(:moe)).should == false
project.can_be_deleted_by?(users(:johan)).should == false # since it has > 1 repos
project.repositories.last.destroy
project.reload.can_be_deleted_by?(users(:johan)).should == true
end
it "should strip html tags" do
project = create_project(:description => "<h1>Project A</h1>\n<b>Project A</b> is a....")
project.<API key>.should == "Project A\nProject A is a...."
end
# it "should strip html tags, except highlights" do
# project = create_project(:description => %Q{<h1>Project A</h1>\n<strong class="highlight">Project A</strong> is a....})
# project.<API key>.should == %Q(Project A\n<strong class="highlight">Project A</strong> is a....)
# end
it "should have valid urls ( prepending http:// if needed )" do
project = projects(:johans)
[ :home_url, :mailinglist_url, :bugtracker_url ].each do |attr|
project.should be_valid
project.send("
project.should be_valid
project.send("
project.should_not be_valid
project.send("#{attr}=", 'blah.com')
project.should be_valid
project.send(attr).should == 'http://blah.com'
end
end
it "should not prepend http:// to empty urls" do
project = projects(:johans)
[ :home_url, :mailinglist_url, :bugtracker_url ].each do |attr|
project.send("#{attr}=", '')
project.send(attr).should be_blank
project.send("#{attr}=", nil)
project.send(attr).should be_blank
end
end
it "should find or create an associated wiki repo" do
project = projects(:johans)
repo = repositories(:johans)
repo.kind = Repository::KIND_WIKI
project.wiki_repository = repo
project.save!
project.reload.wiki_repository.should == repo
end
it "should have a wiki repository" do
project = projects(:johans)
project.wiki_repository.should == repositories(:johans_wiki)
project.repositories.should_not include(repositories(:johans_wiki))
project.repository_clones.should_not include(repositories(:johans_wiki))
end
describe "Project events" do
before(:each) do
@project = projects(:johans)
@user = users(:johan)
@repository = @project.repositories.first
end
it "should create an event from the action name" do
@project.create_event(Action::CREATE_PROJECT, @repository, @user, "", "").should_not == nil
end
it "should create an event even without a valid id" do
@project.create_event(52342, @repository, @user).should_not == nil
end
it "creates valid attributes on the event" do
e = @project.create_event(Action::COMMIT, @repository, @user, "somedata", "a body")
e.should be_valid
e.new_record?.should == false
e.reload
e.action.should == Action::COMMIT
e.target.should == @repository
e.project.should == @project
e.user.should == @user
e.data.should == "somedata"
e.body.should == "a body"
end
end
end
|
package fr.treeptik.cloudunit.modules.redis;
import fr.treeptik.cloudunit.modules.<API key>;
public class <API key> extends <API key> {
public <API key>() {
super.server = "wildfly-8";
super.module = "redis-3-2";
super.numberPort = "6379";
super.managerPrefix = "";
super.managerSuffix = "";
super.managerPageContent = "";
}
@Override
protected void checkConnection(String forwardedPort) {
new <API key>().invoke(forwardedPort);
}
}
|
# Bold - more than just blogging.
# This file is part of Bold.
# Bold is free software: you can redistribute it and/or modify
# published by the Free Software Foundation, either version 3 of the
# Bold is distributed in the hope that it will be useful,
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Base class for controllers delivering content to the public
# Does site lookup by hostname / alias and runs requests in the context of the
# site's configured time zone and locale.
class FrontendController < BaseController
layout :determine_layout
<API key> :set_site
around_action :use_site_time_zone
# in dev mode, Rails' standard error handling is fine.
unless Rails.env.development?
# order matters, least specific has to be first
rescue_from Exception, with: :handle_error
rescue_from Bold::SetupNeeded, with: :handle_404
rescue_from Bold::NotFound, with: :handle_404
rescue_from Bold::SiteNotFound, with: :<API key>
rescue_from ActionController::<API key>, with: :handle_error
rescue_from ActionController::UnknownFormat, with: :handle_404
end
decorate_assigned :site, :content, :tag, :author, :category
private
def find_content
if params[:path].blank?
current_site.homepage
elsif @permalink = current_site.permalinks.find_by_path(params[:path])
@destination = @permalink.destination
(@destination.is_a?(Content) && @destination.published?) ?
@destination : nil
end
end
def render_content(content = @content, options = {})
original_content = @content
@content = content
options[:status] ||= :ok
respond_to do |format|
format.html do
options[:template] = content.get_template.file
render options
end
format.any { head options[:status] }
end
@content = original_content
end
def determine_layout
current_site.theme.layout.present? ? 'content' : 'default_content'
end
def <API key>
if request.host == Bold::Config['backend_host']
redirect_to bold_sites_url
else
handle_404
end
end
# Finds the current site based on http host or server_name header
# For the dev environment there is a fallback to the first site
# found when none matched. Other environments will yield a
# SiteNotFound error instead.
# Override #find_current_site or Site::for_request to customize the
# detection of the current site.
def set_site
@site = Bold.current_site = find_current_site
raise Bold::SiteNotFound unless site_selected?
end
def available_locales
super.tap do |locales|
if (site_locales = current_site.available_locales).present?
locales &= site_locales
end
end
end
def auto_locale
if current_site.detect_user_locale?
return <API key>.<API key> available_locales
end
end
def use_site_time_zone(&block)
if site_selected?
current_site.in_time_zone &block
else
block.call
end
end
def find_current_site
Site.for_hostname(request.host)
end
def handle_404(*args)
# we enforce rendering of html even if it was an image or something else
# that wasn't found.
if site = Bold.current_site and page = site.notfound_page
render_content page, status: :not_found
else
respond_to do |format|
format.html {
render 'errors/404', layout: 'error', status: 404, formats: :html
}
format.any { head :not_found }
end
end
end
def handle_error(*args)
unless performed? # avoid DoubleRenderError
if site = Bold.current_site and page = site.error_page
render_content page, status: 500, formats: :html
else
render 'errors/500', layout: 'error', status: 500, formats: :html
end
end
if exception = args.first
Rails.logger.warn exception
Rails.logger.info exception.backtrace.join("\n")
if defined? Airbrake
Airbrake.notify exception
end
end
end
def do_not_track?
request.headers['DNT'] == '1'
end
helper_method :do_not_track?
end
|
#include "fitz-imp.h"
#include <assert.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
struct fz_style_context_s
{
int refs;
char *user_css;
int use_document_css;
};
static void <API key>(fz_context *ctx)
{
if (ctx)
{
ctx->style = fz_malloc_struct(ctx, fz_style_context);
ctx->style->refs = 1;
ctx->style->user_css = NULL;
ctx->style->use_document_css = 1;
}
}
static fz_style_context *<API key>(fz_context *ctx)
{
if (!ctx)
return NULL;
return fz_keep_imp(ctx, ctx->style, &ctx->style->refs);
}
static void <API key>(fz_context *ctx)
{
if (!ctx)
return;
if (fz_drop_imp(ctx, ctx->style, &ctx->style->refs))
{
fz_free(ctx, ctx->style->user_css);
fz_free(ctx, ctx->style);
}
}
/*
Toggle whether to respect document styles in HTML and EPUB.
*/
void <API key>(fz_context *ctx, int use)
{
ctx->style->use_document_css = use;
}
/*
Return whether to respect document styles in HTML and EPUB.
*/
int fz_use_document_css(fz_context *ctx)
{
return ctx->style->use_document_css;
}
/*
Set the user stylesheet source text for use with HTML and EPUB.
*/
void fz_set_user_css(fz_context *ctx, const char *user_css)
{
fz_free(ctx, ctx->style->user_css);
ctx->style->user_css = user_css ? fz_strdup(ctx, user_css) : NULL;
}
/*
Get the user stylesheet source text.
*/
const char *fz_user_css(fz_context *ctx)
{
return ctx->style->user_css;
}
static void <API key>(fz_context *ctx)
{
if (ctx)
{
ctx->tuning = fz_malloc_struct(ctx, fz_tuning_context);
ctx->tuning->refs = 1;
ctx->tuning->image_decode = <API key>;
ctx->tuning->image_scale = <API key>;
}
}
static fz_tuning_context *<API key>(fz_context *ctx)
{
if (!ctx)
return NULL;
return fz_keep_imp(ctx, ctx->tuning, &ctx->tuning->refs);
}
static void <API key>(fz_context *ctx)
{
if (!ctx)
return;
if (fz_drop_imp(ctx, ctx->tuning, &ctx->tuning->refs))
{
fz_free(ctx, ctx->tuning);
}
}
/*
Set the tuning function to use for
image decode.
image_decode: Function to use.
arg: Opaque argument to be passed to tuning function.
*/
void <API key>(fz_context *ctx, <API key> *image_decode, void *arg)
{
ctx->tuning->image_decode = image_decode ? image_decode : <API key>;
ctx->tuning->image_decode_arg = arg;
}
/*
Set the tuning function to use for
image scaling.
image_scale: Function to use.
arg: Opaque argument to be passed to tuning function.
*/
void fz_tune_image_scale(fz_context *ctx, <API key> *image_scale, void *arg)
{
ctx->tuning->image_scale = image_scale ? image_scale : <API key>;
ctx->tuning->image_scale_arg = arg;
}
static void <API key>(fz_context *ctx)
{
if (!ctx)
return;
ctx->seed48[0] = 0;
ctx->seed48[1] = 0;
ctx->seed48[2] = 0;
ctx->seed48[3] = 0xe66d;
ctx->seed48[4] = 0xdeec;
ctx->seed48[5] = 0x5;
ctx->seed48[6] = 0xb;
fz_srand48(ctx, (uint32_t)time(NULL));
}
/*
Free a context and its global state.
The context and all of its global state is freed, and any
buffered warnings are flushed (see fz_flush_warnings). If NULL
is passed in nothing will happen.
*/
void
fz_drop_context(fz_context *ctx)
{
if (!ctx)
return;
/* Other finalisation calls go here (in reverse order) */
<API key>(ctx);
<API key>(ctx);
<API key>(ctx);
<API key>(ctx);
<API key>(ctx);
<API key>(ctx);
<API key>(ctx);
fz_flush_warnings(ctx);
assert(ctx->error.top == ctx->error.stack);
/* Free the context itself */
ctx->alloc.free(ctx->alloc.user, ctx);
}
static void
<API key>(fz_context *ctx)
{
ctx->error.top = ctx->error.stack;
ctx->error.errcode = FZ_ERROR_NONE;
ctx->error.message[0] = 0;
ctx->warn.message[0] = 0;
ctx->warn.count = 0;
}
/*
Allocate context containing global state.
The global state contains an exception stack, resource store,
etc. Most functions in MuPDF take a context argument to be
able to reference the global state. See fz_drop_context for
freeing an allocated context.
alloc: Supply a custom memory allocator through a set of
function pointers. Set to NULL for the standard library
allocator. The context will keep the allocator pointer, so the
data it points to must not be modified or freed during the
lifetime of the context.
locks: Supply a set of locks and functions to lock/unlock
them, intended for multi-threaded applications. Set to NULL
when using MuPDF in a single-threaded applications. The
context will keep the locks pointer, so the data it points to
must not be modified or freed during the lifetime of the
context.
max_store: Maximum size in bytes of the resource store, before
it will start evicting cached resources such as fonts and
images. FZ_STORE_UNLIMITED can be used if a hard limit is not
desired. Use FZ_STORE_DEFAULT to get a reasonable size.
May return NULL.
*/
fz_context *
fz_new_context_imp(const fz_alloc_context *alloc, const fz_locks_context *locks, size_t max_store, const char *version)
{
fz_context *ctx;
if (strcmp(version, FZ_VERSION))
{
fprintf(stderr, "cannot create context: incompatible header (%s) and library (%s) versions\n", version, FZ_VERSION);
return NULL;
}
if (!alloc)
alloc = &fz_alloc_default;
if (!locks)
locks = &fz_locks_default;
ctx = Memento_label(alloc->malloc(alloc->user, sizeof(fz_context)), "fz_context");
if (!ctx)
{
fprintf(stderr, "cannot create context (phase 1)\n");
return NULL;
}
memset(ctx, 0, sizeof *ctx);
ctx->user = NULL;
ctx->alloc = *alloc;
ctx->locks = *locks;
ctx->error.print = <API key>;
ctx->warn.print = <API key>;
<API key>(ctx);
fz_init_aa_context(ctx);
<API key>(ctx);
/* Now initialise sections that are shared */
fz_try(ctx)
{
<API key>(ctx, max_store);
<API key>(ctx);
<API key>(ctx);
fz_new_font_context(ctx);
<API key>(ctx);
<API key>(ctx);
<API key>(ctx);
}
fz_catch(ctx)
{
fprintf(stderr, "cannot create context (phase 2)\n");
fz_drop_context(ctx);
return NULL;
}
return ctx;
}
/*
Make a clone of an existing context.
This function is meant to be used in multi-threaded
applications where each thread requires its own context, yet
parts of the global state, for example caching, are shared.
ctx: Context obtained from fz_new_context to make a copy of.
ctx must have had locks and lock/functions setup when created.
The two contexts will share the memory allocator, resource
store, locks and lock/unlock functions. They will each have
their own exception stacks though.
May return NULL.
*/
fz_context *
fz_clone_context(fz_context *ctx)
{
fz_context *new_ctx;
/* We cannot safely clone the context without having locking/
* unlocking functions. */
if (ctx == NULL || (ctx->locks.lock == fz_locks_default.lock && ctx->locks.unlock == fz_locks_default.unlock))
return NULL;
new_ctx = ctx->alloc.malloc(ctx->alloc.user, sizeof(fz_context));
if (!new_ctx)
return NULL;
/* First copy old context, including pointers to shared contexts */
memcpy(new_ctx, ctx, sizeof (fz_context));
/* Reset error context to initial state. */
<API key>(new_ctx);
/* Then keep lock checking happy by keeping shared contexts with new context */
<API key>(new_ctx);
<API key>(new_ctx);
<API key>(new_ctx);
<API key>(new_ctx);
<API key>(new_ctx);
<API key>(new_ctx);
fz_keep_glyph_cache(new_ctx);
return new_ctx;
}
/*
Set the user field in the context.
NULL initially, this field can be set to any opaque value
required by the user. It is copied on clones.
*/
void fz_set_user_context(fz_context *ctx, void *user)
{
if (ctx != NULL)
ctx->user = user;
}
/*
Read the user field from the context.
*/
void *fz_user_context(fz_context *ctx)
{
if (ctx == NULL)
return NULL;
return ctx->user;
}
|
<?php declare(strict_types=1);
namespace OCA\Mail\Events;
use Horde_Mime_Mail;
use OCA\Mail\Account;
use OCA\Mail\Model\IMessage;
use OCA\Mail\Model\NewMessageData;
use OCA\Mail\Model\RepliedMessageData;
use OCP\EventDispatcher\Event;
class MessageSentEvent extends Event {
/** @var Account */
private $account;
/** @var NewMessageData */
private $newMessageData;
/** @var null|RepliedMessageData */
private $repliedMessageData;
/** @var int|null */
private $draftUid;
/** @var IMessage */
private $message;
/** @var Horde_Mime_Mail */
private $mail;
public function __construct(Account $account,
NewMessageData $newMessageData,
?RepliedMessageData $repliedMessageData,
?int $draftUid = null,
IMessage $message,
Horde_Mime_Mail $mail) {
parent::__construct();
$this->account = $account;
$this->newMessageData = $newMessageData;
$this->repliedMessageData = $repliedMessageData;
$this->draftUid = $draftUid;
$this->message = $message;
$this->mail = $mail;
}
public function getAccount(): Account {
return $this->account;
}
public function getNewMessageData(): NewMessageData {
return $this->newMessageData;
}
public function <API key>(): ?RepliedMessageData {
return $this->repliedMessageData;
}
public function getDraftUid(): ?int {
return $this->draftUid;
}
public function getMessage(): IMessage {
return $this->message;
}
public function getMail(): Horde_Mime_Mail {
return $this->mail;
}
}
|
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>The source code</title>
<link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="../resources/prettify/prettify.js"></script>
<style type="text/css">
.highlight { display: block; background-color: #ddd; }
</style>
<script type="text/javascript">
function highlight() {
document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
}
</script>
</head>
<body onload="prettyPrint(); highlight();">
<pre class="prettyprint lang-js"><span id='jslet-ui-DBSpinEdit'>/**
</span> * @class
* @extend jslet.ui.DBFieldControl
*
* DBSpinEdit.
*
* @example
* var jsletParam = {type:"DBSpinEdit",dataset:"employee",field:"age", minValue:18, maxValue: 100, step: 5};
*
* //1. Declaring:
* <div data-jslet='type:"DBSpinEdit",dataset:"employee",field:"age", minValue:18, maxValue: 100, step: 5'></div>
* or
* <div data-jslet='jsletParam'></div>
*
* //2. Binding
* <div id="ctrlId"></div>
* //Js snippet
* var el = document.getElementById('ctrlId');
* jslet.ui.bindControl(el, jsletParam);
*
* //3. Create dynamically
* jslet.ui.createControl(jsletParam, document.body);
*/
jslet.ui.DBSpinEdit = jslet.Class.create(jslet.ui.DBFieldControl, {
<span id='<API key>'> /**
</span> * @protected
* @override
*/
initialize: function ($super, el, params) {
var Z = this;
Z.allProperties = 'styleClass,dataset,field,step';
Z._step = 1;
$super(el, params);
},
<span id='<API key>'> /**
</span> * @property
*
* Set or get step.
*
* @param {Integer | undefined} step Step value.
*
* @return {this | Integer}
*/
step: function(step) {
if(step === undefined) {
return this._step;
}
jslet.Checker.test('DBSpinEdit.step', step).isNumber();
this._step = step;
return this;
},
<span id='<API key>'> /**
</span> * @protected
* @override
*/
isValidTemplateTag: function (el) {
var tag = el.tagName.toLowerCase();
return tag == 'div';
},
<span id='<API key>'> /**
</span> * @protected
* @override
*/
bind: function () {
var Z = this,
jqEl = jQuery(Z.el);
if(!jqEl.hasClass('jl-spinedit')) {
jqEl.addClass('input-group jl-spinedit');
}
Z._createControl();
Z.renderAll();
},
_createControl: function() {
var Z = this,
jqEl = jQuery(Z.el),
s = '<input type="text" class="form-control">' +
'<div class="<API key>">' +
'<button class="btn btn-default jl-spinedit-up" tabindex="-1"><i class="fa fa-caret-up"></i></button>' +
'<button class="btn btn-default jl-spinedit-down" tabindex="-1"><i class="fa fa-caret-down"></i></button>';
jqEl.html(s);
var editor = jqEl.find('input')[0],
upButton = jqEl.find('.jl-spinedit-up')[0],
downButton = jqEl.find('.jl-spinedit-down')[0];
Z.editor = editor;
editor.name = Z._field;
jQuery(Z.editor).on("keydown", function(event){
if(Z._isDisabled()) {
return;
}
var keyCode = event.keyCode;
if(keyCode === jslet.ui.KeyCode.UP) {
Z.decValue();
event.preventDefault();
return;
}
if(keyCode === jslet.ui.KeyCode.DOWN) {
Z.incValue();
event.preventDefault();
return;
}
});
new jslet.ui.DBText(editor, {
dataset: Z._dataset,
field: Z._field,
<API key>: Z.<API key>,
valueIndex: Z._valueIndex,
tabIndex: Z._tabIndex
});
var jqBtn = jQuery(upButton);
jqBtn.on('click', function () {
Z.incValue();
});
jqBtn.focus(function(event) {
jslet.ui.globalFocusManager.activeDataset(Z._dataset.name()).activeField(Z._field).activeValueIndex(Z._valueIndex);
});
jqBtn.blur(function(event) {
jslet.ui.globalFocusManager.activeDataset(null).activeField(null).activeValueIndex(null);
});
jqBtn = jQuery(downButton);
jqBtn.on('click', function () {
Z.decValue();
});
jqBtn.focus(function(event) {
jslet.ui.globalFocusManager.activeDataset(Z._dataset.name()).activeField(Z._field).activeValueIndex(Z._valueIndex);
});
jqBtn.blur(function(event) {
jslet.ui.globalFocusManager.activeDataset(null).activeField(null).activeValueIndex(null);
});
},
_isDisabled: function() {
var Z = this,
fldObj = Z._dataset.getField(Z._field);
return fldObj.disabled() || fldObj.readOnly();
},
<API key>: function () {
var Z = this,
val = Z.el.value;
var fldObj = Z._dataset.getField(Z._field),
range = fldObj.dataRange(),
minValue = Number.NEGATIVE_INFINITY,
maxValue = Number.POSITIVE_INFINITY;
if(range) {
if(range.min || range.min === 0) {
minValue = parseFloat(range.min);
}
if(range.max || range.min === 0) {
maxValue = parseFloat(range.max);
}
}
if (val) {
val = parseFloat(val);
}
jQuery(Z.el).attr('aria-valuenow', val);
Z.el.value = val;
return true;
},
setValueToDataset: function (val) {
var Z = this;
if (Z.silence) {
return;
}
Z.silence = true;
if (val === undefined) {
val = Z.value;
}
try {
Z._dataset.setFieldValue(Z._field, val, Z._valueIndex);
} finally {
Z.silence = false;
}
},
incValue: function () {
var Z = this,
val = Z.getValue();
if (!val) {
val = 0;
}
var maxValue = Z._getRange().maxValue;
if (val === maxValue) {
return;
} else if (val < maxValue) {
val += Z._step;
} else {
val = maxValue;
}
if (val > maxValue) {
val = maxValue;
}
jQuery(Z.el).attr('aria-valuenow', val);
Z.setValueToDataset(val);
return this;
},
_getRange: function() {
var Z = this,
fldObj = Z._dataset.getField(Z._field),
range = fldObj.dataRange(),
minValue = Number.NEGATIVE_INFINITY,
maxValue = Number.POSITIVE_INFINITY;
if(range) {
if(range.min || range.min === 0) {
minValue = parseFloat(range.min);
}
if(range.max || range.min === 0) {
maxValue = parseFloat(range.max);
}
}
return {minValue: minValue, maxValue: maxValue};
},
decValue: function () {
var Z = this,
val = Z.getValue();
if (!val) {
val = 0;
}
var minValue = Z._getRange().minValue;
if (val === minValue) {
return;
} else if (val > minValue) {
val -= Z._step;
} else {
val = minValue;
}
if (val < minValue)
val = minValue;
jQuery(Z.el).attr('aria-valuenow', val);
Z.setValueToDataset(val);
return this;
},
<span id='<API key>'> /**
</span> * @protected
* @override
*/
innerFocus: function() {
this.editor.focus();
},
<span id='<API key>'> /**
</span> * @protected
* @override
*/
doMetaChanged: function($super, metaName) {
$super(metaName);
var Z = this,
jqEl = jQuery(this.el),
fldObj = Z._dataset.getField(Z._field);
if(!metaName || metaName == 'disabled' || metaName == 'readOnly') {
var disabled = fldObj.disabled() || fldObj.readOnly(),
jqUpBtn = jqEl.find('.jl-spinedit-up'),
jqDownBtn = jqEl.find('.jl-spinedit-down');
if (disabled) {
jqUpBtn.attr('disabled', 'disabled');
jqDownBtn.attr('disabled', 'disabled');
} else {
jqUpBtn.attr('disabled', false);
jqDownBtn.attr('disabled', false);
}
}
if(!metaName || metaName == 'dataRange') {
var range = fldObj.dataRange();
jqEl.attr('aria-valuemin', range && (range.min || range.min === 0) ? range.min: '');
jqEl.attr('aria-valuemin', range && (range.max || range.max === 0) ? range.max: '');
}
if(!metaName || metaName == 'tabIndex') {
Z.setTabIndex();
}
},
<span id='<API key>'> /**
</span> * @override
*/
renderAll: function(){
this.refreshControl(jslet.data.RefreshEvent.updateAllEvent(), true);
return this;
},
<span id='<API key>'> /**
</span> * @protected
* @override
*/
tableId: function($super, tableId){
$super(tableId);
this.editor.jslet.tableId(tableId);
},
<span id='<API key>'> /**
</span> * @override
*/
destroy: function(){
var jqEl = jQuery(this.el);
jQuery(this.editor).off();
this.editor = null;
jqEl.find('.jl-upbtn-up').off();
jqEl.find('.jl-downbtn-up').off();
}
});
jslet.ui.register('DBSpinEdit', jslet.ui.DBSpinEdit);
jslet.ui.DBSpinEdit.htmlTemplate = '<div></div>';
</pre>
</body>
</html>
|
<?php
/**
* I am a generated class and am required for communicating with plentymarkets.
*/
class <API key>
{
/**
* @var string
*/
public $Lang;
}
|
var clover = new Object();
// JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]}
clover.pageData = {"classes":[{"el":162,"id":11268,"methods":[{"el":52,"sc":2,"sl":50},{"el":138,"sc":2,"sl":54},{"el":147,"sc":2,"sl":140},{"el":161,"sc":2,"sl":149}],"name":"ChiSquaredWeighting","sl":46}]}
// JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...};
clover.testTargets = {}
// JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]};
clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
|
DELETE FROM `weenie` WHERE `class_Id` = 19384;
INSERT INTO `weenie` (`class_Id`, `class_Name`, `type`, `last_Modified`)
VALUES (19384, 'gagindwellingssign', 1, '2019-02-10 00:00:00') /* Generic */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (19384, 1, 128) /* ItemType - Misc */
, (19384, 5, 9000) /* EncumbranceVal */
, (19384, 16, 1) /* ItemUseable - No */
, (19384, 19, 125) /* Value */
, (19384, 93, 1048) /* PhysicsState - ReportCollisions, IgnoreCollisions, Gravity */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (19384, 1, True ) /* Stuck */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (19384, 1, 'Gajin Dwellings') /* Name */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (19384, 1, 33557697) /* Setup */
, (19384, 8, 100667499) /* Icon */
, (19384, 8001, 2097176) /* <API key> - Value, Usable, Burden */
, (19384, 8003, 20) /* <API key> - Stuck, Attackable */
, (19384, 8005, 32769) /* <API key> - CSetup, Position */;
INSERT INTO `<API key>` (`object_Id`, `position_Type`, `obj_Cell_Id`, `origin_X`, `origin_Y`, `origin_Z`, `angles_W`, `angles_X`, `angles_Y`, `angles_Z`)
VALUES (19384, 8040, 1449197825, 2.66, -50.119, 0, -0.707107, 0, 0, -0.707107) /* <API key> */
/* @teleloc 0x56610101 [2.660000 -50.119000 0.000000] -0.707107 0.000000 0.000000 -0.707107 */;
INSERT INTO `<API key>` (`object_Id`, `type`, `value`)
VALUES (19384, 8000, 1969623043) /* <API key> */;
|
import _ from 'underscore'
import Base from '../graphs/base'
import DayBinner from '../graphs/DayBinner'
import WeekBinner from '../graphs/WeekBinner'
import MonthBinner from '../graphs/MonthBinner'
import ScaleByBins from '../graphs/ScaleByBins'
import helpers from '../helpers'
import I18n from 'i18n!page_views'
//
// Parent class for all graphs that have a date-aligned x-axis. Note: Left
// padding for this graph style is space from the frame to the start date's
// tick mark, not the leading graph element's edge. Similarly, right padding
// is space from the frame to the end date's tick, not the trailing graph
// element's edge. This is necessary to keep the date graphs aligned.
const defaultOptions = {
//
// The date for the left end of the graph. Required.
startDate: null,
//
// The date for the right end of the graph. Required.
endDate: null,
//
// The size of the date tick marks, in pixels.
tickSize: 5,
//
// If any date is outside the bounds of the graph, we have a clipped date
clippedDate: false
}
export default class DateAlignedGraph extends Base {
//
// Takes an element and options, same as for Base. Recognizes the options
// described above in addition to the options for Base.
constructor(div, options) {
super(...arguments)
// mixin ScaleByBins functionality
_.extend(this, ScaleByBins)
// check for required options
if (options.startDate == null) throw new Error('startDate is required')
if (options.endDate == null) throw new Error('endDate is required')
// copy in recognized options with defaults
for (const key in defaultOptions) {
const defaultValue = defaultOptions[key]
this[key] = options[key] != null ? options[key] : defaultValue
}
this.initScale()
}
//
// Set up X-axis scale
initScale() {
const interior = this.width - this.leftPadding - this.rightPadding
// mixin for the appropriate bin size
// use a minimum of 10 pixels for bar width plus spacing before consolidating
this.binner = new DayBinner(this.startDate, this.endDate)
if (this.binner.count() * 10 > interior)
this.binner = new WeekBinner(this.startDate, this.endDate)
if (this.binner.count() * 10 > interior)
this.binner = new MonthBinner(this.startDate, this.endDate)
// scale the x-axis for the number of bins
return this.scaleByBins(this.binner.count())
}
//
// Reset the graph chrome. Adds an x-axis with daily ticks and weekly (on
// Mondays) labels.
reset() {
super.reset(...arguments)
if (this.startDate) this.initScale()
return this.drawDateAxis()
}
//
// Convert a date to a bin index.
dateBin(date) {
return this.binner.bin(date)
}
//
// Convert a date to its bin's x-coordinate.
binnedDateX(date) {
return this.binX(this.dateBin(date))
}
//
// Given a datetime, return the floor and ceil as calculated by the binner
dateExtent(datetime) {
const floor = this.binner.reduce(datetime)
return [floor, this.binner.nextTick(floor)]
}
//
// Given a datetime and a datetime range, return a number from 0.0 to 1.0
dateFraction(datetime, floorDate, ceilDate) {
const deltaSeconds = datetime.getTime() - floorDate.getTime()
const totalSeconds = ceilDate.getTime() - floorDate.getTime()
return deltaSeconds / totalSeconds
}
//
// Convert a date to an intra-bin x-coordinate.
dateX(datetime) {
const minX = this.leftMargin
const maxX = this.leftMargin + this.width
const [floorDate, ceilDate] = this.dateExtent(datetime)
const floorX = this.binnedDateX(floorDate)
const ceilX = this.binnedDateX(ceilDate)
const fraction = this.dateFraction(datetime, floorDate, ceilDate)
if (datetime.getTime() < this.startDate.getTime()) {
// out of range, left
this.clippedDate = true
return minX
} else if (datetime.getTime() > this.endDate.getTime()) {
// out of range, right
this.clippedDate = true
return maxX
} else {
// in range
return floorX + fraction * (ceilX - floorX)
}
}
//
// Draw a guide along the x-axis. Each day gets a pair of ticks; one from
// the top of the frame, the other from the bottom. The ticks are replaced
// by a full vertical grid line on Mondays, accompanied by a label.
drawDateAxis() {
// skip if we haven't set start/end dates yet (@reset will be called by
// Base's constructor before we set startDate or endDate)
if (this.startDate == null || this.endDate == null) return
return this.binner.eachTick((tick, chrome) => {
const x = this.binnedDateX(tick)
if (chrome && chrome.label) return this.dateLabel(x, this.topMargin + this.height, chrome.label)
})
}
//
// Draw label text at (x, y).
dateLabel(x, y, text) {
const label = this.paper.text(x, y, text)
return label.attr({fill: this.frameColor})
}
//
// Get date text for a bin
binDateText(bin) {
const lastDay = this.binner.nextTick(bin.date).addDays(-1)
const daysBetween = helpers.daysBetween(bin.date, lastDay)
if (daysBetween < 1) {
// single-day bucket: label the date
return I18n.l('date.formats.medium', bin.date)
} else if (daysBetween < 7) {
// one-week bucket: label the start and end days; include the year only with the end day unless they're different
return I18n.t('%{start_date} - %{end_date}', {
start_date: I18n.l(
bin.date.getFullYear() === lastDay.getFullYear()
? 'date.formats.short'
: 'date.formats.medium',
bin.date
),
end_date: I18n.l('date.formats.medium', lastDay)
})
} else {
// one-month bucket; label the month and year
return I18n.l('date.formats.medium_month', bin.date)
}
}
}
|
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-
<html xmlns="http:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>operator>=</title>
<link rel="stylesheet" href="apiReference.css" type="text/css" />
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2" />
<link rel="start" href="index.html" title="Berkeley DB C++ Standard Template Library API Reference" />
<link rel="up" href="<API key>.html" title="Chapter 12. <API key>" />
<link rel="prev" href="<API key>.html" title="operator<=" />
<link rel="next" href="<API key>.html" title="operator>" />
</head>
<body>
<div xmlns="" class="navheader">
<div class="libver">
<p>Library Version 12.1.6.0</p>
</div>
<table width="100%" summary="Navigation header">
<tr>
<th colspan="3" align="center">operator>=</th>
</tr>
<tr>
<td width="20%" align="left"><a accesskey="p" href="<API key>.html">Prev</a> </td>
<th width="60%" align="center">Chapter 12.
<API key> </th>
<td width="20%" align="right"> <a accesskey="n" href="<API key>.html">Next</a></td>
</tr>
</table>
<hr />
</div>
<div class="sect1" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h2 class="title" style="clear: both"><a id="<API key>"></a>operator>=</h2>
</div>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="<API key>"></a>Function Details</h3>
</div>
</div>
</div>
<pre class="programlisting">
bool operator>=(const self &itr) const
</pre>
<p>Greater equal comparison operator. </p>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="idp1167176"></a>Parameters</h4>
</div>
</div>
</div>
<div class="sect4" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h5 class="title"><a id="idp1175480"></a>itr</h5>
</div>
</div>
</div>
<p>The iterator to compare against. </p>
</div>
</div>
<div class="sect3" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h4 class="title"><a id="idp1172856"></a>Return Value</h4>
</div>
</div>
</div>
<p>True if this iterator is greater than or equal to itr. </p>
</div>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="idp1171776"></a>Group: Iterator comparison operators</h3>
</div>
</div>
</div>
<p>The way to compare two iterators is to compare the index values of the two elements they point to.</p>
<p>The iterator sitting on an element with less index is regarded to be smaller. And the invalid iterator sitting after last element is greater than any other iterators, because it is assumed to have an index equal to last element's index plus one; The invalid iterator sitting before first element is less than any other iterators because it is assumed to have an index -1. </p>
</div>
<div class="sect2" lang="en" xml:lang="en">
<div class="titlepage">
<div>
<div>
<h3 class="title"><a id="idp1171096"></a>Class</h3>
</div>
</div>
</div>
<p>
<a class="link" href="<API key>.html" title="Chapter 12. <API key>"><API key></a>
</p>
</div>
</div>
<div class="navfooter">
<hr />
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left"><a accesskey="p" href="<API key>.html">Prev</a> </td>
<td width="20%" align="center">
<a accesskey="u" href="<API key>.html">Up</a>
</td>
<td width="40%" align="right"> <a accesskey="n" href="<API key>.html">Next</a></td>
</tr>
<tr>
<td width="40%" align="left" valign="top">operator<= </td>
<td width="20%" align="center">
<a accesskey="h" href="index.html">Home</a>
</td>
<td width="40%" align="right" valign="top"> operator></td>
</tr>
</table>
</div>
</body>
</html>
|
SavedSearchSelect.$inject = ['session', 'savedSearch'];
export function SavedSearchSelect(session, savedSearch) {
return {
link: function(scope) {
savedSearch.<API key>(session.identity).then(function(res) {
scope.searches = res;
});
}
};
}
|
#!/usr/bin/env python
# This file is part of Essentia
# Essentia is free software: you can redistribute it and/or modify it under
# option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT
# details.
from essentia_test import *
from essentia.streaming import TCToTotal as sTCToTotal
class TestTCToTotal(TestCase):
def testEmpty(self):
gen = VectorInput([])
tcToTotal = sTCToTotal()
p = Pool()
gen.data >> tcToTotal.envelope
tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal')
run(gen)
self.assertRaises(KeyError, lambda: p['lowlevel.tctototal'])
def testOneValue(self):
gen = VectorInput([1])
tcToTotal = sTCToTotal()
p = Pool()
gen.data >> tcToTotal.envelope
tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal')
self.assertRaises(RuntimeError, lambda: run(gen))
def testRegression(self):
envelope = range(22050)
envelope.reverse()
envelope = range(22050) + envelope
gen = VectorInput(envelope)
tcToTotal = sTCToTotal()
p = Pool()
gen.data >> tcToTotal.envelope
tcToTotal.TCToTotal >> (p, 'lowlevel.tctototal')
run(gen)
self.assertAlmostEqual(p['lowlevel.tctototal'],
TCToTotal()(envelope))
suite = allTests(TestTCToTotal)
if __name__ == '__main__':
TextTestRunner(verbosity=2).run(suite)
|
from odoo import fields, models
class PosConfig(models.Model):
_inherit = "pos.config"
account_analytic_id = fields.Many2one(
comodel_name="account.analytic.account", string="Analytic Account"
)
|
package context_test
import (
jc "github.com/juju/testing/checkers"
"github.com/juju/utils"
"github.com/juju/utils/set"
gc "gopkg.in/check.v1"
"gopkg.in/juju/names.v2"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/provider/dummy"
"github.com/juju/juju/state"
"github.com/juju/juju/storage"
"github.com/juju/juju/storage/poolmanager"
"github.com/juju/juju/storage/provider"
"github.com/juju/juju/worker/uniter/runner/context"
)
type unitStorageSuite struct {
HookContextSuite
<API key> set.Strings
charmName string
initCons map[string]state.StorageConstraints
ch *state.Charm
<API key> int
}
var _ = gc.Suite(&unitStorageSuite{})
const (
testPool = "block"
testPersistentPool = "block-persistent"
)
func (s *unitStorageSuite) SetUpTest(c *gc.C) {
s.HookContextSuite.SetUpTest(c)
<API key>(c, s.State)
}
func (s *unitStorageSuite) TestAddUnitStorage(c *gc.C) {
s.<API key>(c)
count := uint64(1)
s.<API key>(c,
map[string]params.StorageConstraints{
"allecto": params.StorageConstraints{Count: &count}})
}
func (s *unitStorageSuite) <API key>(c *gc.C) {
s.<API key>(c)
count := uint64(1)
s.BlockDestroyModel(c, "<API key>")
s.BlockRemoveObject(c, "<API key>")
s.BlockAllChanges(c, "<API key>")
s.<API key>(c,
map[string]params.StorageConstraints{
"allecto": params.StorageConstraints{Count: &count}})
}
func (s *unitStorageSuite) <API key>(c *gc.C) {
s.<API key>(c)
cons := map[string]params.StorageConstraints{
"allecto": params.StorageConstraints{}}
ctx := s.addUnitStorage(c, cons)
// Flush the context with a success.
err := ctx.Flush("success", nil)
c.Assert(err, gc.ErrorMatches, `.*count must be specified.*`)
// Make sure no storage instances was added
after, err := s.State.AllStorageInstances()
c.Assert(err, jc.ErrorIsNil)
c.Assert(len(after)-s.<API key>, gc.Equals, 0)
s.<API key>(c, after)
}
func (s *unitStorageSuite) <API key>(c *gc.C) {
s.<API key>(c)
size := uint64(1)
cons := map[string]params.StorageConstraints{
"allecto": params.StorageConstraints{Size: &size}}
ctx := s.addUnitStorage(c, cons)
// Flush the context with a success.
err := ctx.Flush("success", nil)
c.Assert(err, gc.ErrorMatches, `.*only count can be specified.*`)
// Make sure no storage instances was added
after, err := s.State.AllStorageInstances()
c.Assert(err, jc.ErrorIsNil)
c.Assert(len(after)-s.<API key>, gc.Equals, 0)
s.<API key>(c, after)
}
func (s *unitStorageSuite) <API key>(c *gc.C) {
s.<API key>(c)
cons := map[string]params.StorageConstraints{
"allecto": params.StorageConstraints{Pool: "loop"}}
ctx := s.addUnitStorage(c, cons)
// Flush the context with a success.
err := ctx.Flush("success", nil)
c.Assert(err, gc.ErrorMatches, `.*only count can be specified.*`)
// Make sure no storage instances was added
after, err := s.State.AllStorageInstances()
c.Assert(err, jc.ErrorIsNil)
c.Assert(len(after)-s.<API key>, gc.Equals, 0)
s.<API key>(c, after)
}
func (s *unitStorageSuite) <API key>(c *gc.C) {
s.<API key>(c)
count := uint64(1)
s.<API key>(c,
map[string]params.StorageConstraints{
"multi2up": params.StorageConstraints{Count: &count}},
map[string]params.StorageConstraints{
"multi1to10": params.StorageConstraints{Count: &count}})
}
func (s *unitStorageSuite) <API key>(c *gc.C) {
s.<API key>(c)
count := uint64(1)
s.<API key>(c,
map[string]params.StorageConstraints{
"multi2up": params.StorageConstraints{Count: &count}},
map[string]params.StorageConstraints{
"multi2up": params.StorageConstraints{Count: &count}})
}
func <API key>(c *gc.C, s *state.State) {
stsetts := state.NewStateSettings(s)
poolManager := poolmanager.New(stsetts, storage.<API key>{
dummy.StorageProviders(),
provider.<API key>(),
})
_, err := poolManager.Create(testPool, provider.LoopProviderType, map[string]interface{}{"it": "works"})
c.Assert(err, jc.ErrorIsNil)
_, err = poolManager.Create(testPersistentPool, "modelscoped", map[string]interface{}{"persistent": true})
c.Assert(err, jc.ErrorIsNil)
}
func (s *unitStorageSuite) <API key>(c *gc.C) {
s.ch = s.AddTestingCharm(c, s.charmName)
s.service = s.<API key>(c, s.charmName, s.ch, s.initCons)
s.unit = s.AddUnit(c, s.service)
s.<API key>(c)
s.createHookSupport(c)
}
func (s *unitStorageSuite) <API key>(c *gc.C) {
s.charmName = "storage-block"
s.initCons = map[string]state.StorageConstraints{
"data": makeStorageCons("block", 1024, 1),
}
s.<API key>(c)
s.<API key>(c)
s.createHookSupport(c)
}
func (s *unitStorageSuite) <API key>(c *gc.C) {
s.charmName = "storage-block2"
s.initCons = map[string]state.StorageConstraints{
"multi1to10": makeStorageCons("loop", 0, 3),
}
s.<API key>(c)
s.<API key>(c)
s.createHookSupport(c)
}
func (s *unitStorageSuite) <API key>(c *gc.C) {
all, err := s.State.AllStorageInstances()
c.Assert(err, jc.ErrorIsNil)
s.<API key> = len(all)
s.<API key> = set.NewStrings()
for _, one := range all {
s.<API key>.Add(one.StorageName())
}
}
func (s *unitStorageSuite) createHookSupport(c *gc.C) {
password, err := utils.RandomPassword()
err = s.unit.SetPassword(password)
c.Assert(err, jc.ErrorIsNil)
s.st = s.OpenAPIAs(c, s.unit.Tag(), password)
s.uniter, err = s.st.Uniter()
c.Assert(err, jc.ErrorIsNil)
c.Assert(s.uniter, gc.NotNil)
s.apiUnit, err = s.uniter.Unit(s.unit.Tag().(names.UnitTag))
c.Assert(err, jc.ErrorIsNil)
err = s.unit.SetCharmURL(s.ch.URL())
c.Assert(err, jc.ErrorIsNil)
}
func makeStorageCons(pool string, size, count uint64) state.StorageConstraints {
return state.StorageConstraints{Pool: pool, Size: size, Count: count}
}
func (s *unitStorageSuite) addUnitStorage(c *gc.C, cons ...map[string]params.StorageConstraints) *context.HookContext {
// Get the context.
ctx := s.getHookContext(c, s.State.ModelUUID(), -1, "", noProxies)
c.Assert(ctx.UnitName(), gc.Equals, s.unit.Name())
for _, one := range cons {
for storage, _ := range one {
s.<API key>.Add(storage)
}
ctx.AddUnitStorage(one)
}
return ctx
}
func (s *unitStorageSuite) <API key>(c *gc.C, cons ...map[string]params.StorageConstraints) {
ctx := s.addUnitStorage(c, cons...)
// Flush the context with a success.
err := ctx.Flush("success", nil)
c.Assert(err, jc.ErrorIsNil)
after, err := s.State.AllStorageInstances()
c.Assert(err, jc.ErrorIsNil)
c.Assert(len(after)-s.<API key>, gc.Equals, len(cons))
s.<API key>(c, after)
}
func (s *unitStorageSuite) <API key>(c *gc.C, all []state.StorageInstance) {
for _, one := range all {
c.Assert(s.<API key>.Contains(one.StorageName()), jc.IsTrue)
}
}
|
OC.L10N.register(
"encryption",
{
"Missing recovery key password" : "Brakujące hasło klucza odzyskiwania",
"Please repeat the recovery key password" : "Proszę powtórz nowe hasło klucza odzyskiwania",
"Repeated recovery key password does not match the provided recovery key password" : "Hasła klucza odzyskiwania nie zgadzają się",
"Recovery key successfully enabled" : "Klucz odzyskiwania włączony",
"Could not enable recovery key. Please check your recovery key password!" : "Nie można włączyć klucza odzyskiwania. Proszę sprawdzić swoje hasło odzyskiwania!",
"Recovery key successfully disabled" : "Klucz odzyskiwania wyłączony",
"Could not disable recovery key. Please check your recovery key password!" : "Nie można wyłączyć klucza odzyskiwania. Proszę sprawdzić swoje hasło odzyskiwania!",
"Missing parameters" : "Brakujące dane",
"Please provide the old recovery password" : "Podaj stare hasło odzyskiwania",
"Please provide a new recovery password" : "Podaj nowe hasło odzyskiwania",
"Please repeat the new recovery password" : "Proszę powtórz nowe hasło odzyskiwania",
"Password successfully changed." : "Zmiana hasła udana.",
"Could not change the password. Maybe the old password was not correct." : "Nie można zmienić hasła. Może stare hasło nie było poprawne.",
"Recovery Key disabled" : "Klucz odzyskiwania wyłączony",
"Recovery Key enabled" : "Klucz odzyskiwania włączony",
"Could not enable the recovery key, please try again or contact your administrator" : "Nie można włączyć klucza odzyskiwania. Proszę spróbować ponownie lub skontakuj sie z administratorem",
"Could not update the private key password." : "Nie można zmienić hasła klucza prywatnego.",
"The old password was not correct, please try again." : "Stare hasło nie było poprawne. Spróbuj jeszcze raz.",
"The current log-in password was not correct, please try again." : "Obecne hasło logowania nie było poprawne. Spróbuj ponownie.",
"Private key password successfully updated." : "Pomyślnie zaktualizowano hasło klucza prywatnego.",
"You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one. Please run 'occ encryption:migrate' or contact your administrator" : "Musisz przenieść swoje klucze szyfrowania ze starego sposobu szyfrowania (Nextcloud <= 8,0) na nowy. Proszę uruchomić 'occ encryption:migrate' lub skontaktować się z administratorem",
"Invalid private key for encryption app. Please update your private key password in your personal settings to recover access to your encrypted files." : "Nieprawidłowy klucz prywatny do szyfrowania aplikacji. Należy zaktualizować hasło klucza prywatnego w ustawieniach osobistych, aby odzyskać dostęp do zaszyfrowanych plików.",
"Encryption App is enabled, but your keys are not initialized. Please log-out and log-in again." : "Aplikacja szyfrująca jest włączona, ale Twoje klucze nie są zainicjowane. Proszę się wylogować i zalogować ponownie.",
"Please enable server side encryption in the admin settings in order to use the encryption module." : "Aby móc korzystać z modułu szyfrowania trzeba włączyć w panelu administratora szyfrowanie po stronie serwera. ",
"Encryption app is enabled and ready" : "Szyfrowanie aplikacja jest włączone i gotowe",
"Bad Signature" : "Zła sygnatura",
"Missing Signature" : "Brakująca sygnatura",
"one-time password for <API key>" : "jednorazowe hasło do serwera szyfrowania strony",
"Can not decrypt this file, probably this is a shared file. Please ask the file owner to reshare the file with you." : "Nie można odszyfrować tego pliku, prawdopodobnie jest to plik udostępniony. Poproś właściciela pliku o ponowne udostępnianie pliku Tobie.",
"Can not read this file, probably this is a shared file. Please ask the file owner to reshare the file with you." : "Nie można odczytać tego pliku, prawdopodobnie plik nie jest współdzielony. Proszę zwrócić się do właściciela pliku, aby udostępnił go dla Ciebie.",
"Default encryption module" : "Domyślny moduł szyfrujący",
"Hey there,\n\nthe admin enabled <API key>. Your files were encrypted using the password '%s'.\n\nPlease login to the web interface, go to the section 'basic encryption module' of your personal settings and update your encryption password by entering this password into the 'old log-in password' field and your current login-password.\n\n" : "Hej tam,\n\nadmin włączył szyfrowanie po stronie serwera. Twoje pliki zostały zaszyfrowane przy użyciu hasła '%s'.\n\nProszę zalogować się do interfejsu internetowego, przejdź do sekcji Nextcloud podstawowy moduł szyfrowania, następnie osobiste ustawienia i zaktualizuj hasło szyfrowania wpisując aktualny login, w polu stare hasło logowania wpisz stare hasło, a następnie aktualne hasło.\n\n",
"The share will expire on %s." : "Ten zasób wygaśnie %s",
"Cheers!" : "Dzięki!",
"Hey there,<br><br>the admin enabled <API key>. Your files were encrypted using the password <strong>%s</strong>.<br><br>Please login to the web interface, go to the section \"basic encryption module\" of your personal settings and update your encryption password by entering this password into the \"old log-in password\" field and your current login-password.<br><br>" : "Hej tam,<br><br>admin włączył szyfrowanie po stronie serwera. Twoje pliki zostały zaszyfrowane przy użyciu hasła <strong>%s</strong>.<br><br>Proszę zalogować się do interfejsu internetowego, przejdź do sekcji Nextcloud podstawowy moduł szyfrowania, następnie osobiste ustawienia i zaktualizuj hasło szyfrowania wpisując aktualny login, w polu stare hasło logowania wpisz stare hasło, a następnie aktualne hasło.<br><br>",
"Encryption app is enabled but your keys are not initialized, please log-out and log-in again" : "Szyfrowanie w aplikacji jest włączone, ale klucze nie są zainicjowane. Prosimy wylogować się i ponownie zalogować się.",
"Encrypt the home storage" : "Szyfrowanie przechowywanie w domu",
"Enabling this option encrypts all files stored on the main storage, otherwise only files on external storage will be encrypted" : "Włączenie tej opcji spowoduje szyfrowanie wszystkich plików zapisanych na pamięci wewnętrznej. W innym wypadku szyfrowane będą tylko pliki na pamięci zewnętrznej.",
"Enable recovery key" : "Włącz klucz odzyskiwania",
"Disable recovery key" : "Wyłącz klucz odzyskiwania",
"The recovery key is an extra encryption key that is used to encrypt files. It allows recovery of a user's files if the user forgets his or her password." : "Kluczem do odzyskiwania jest dodatkowy klucz szyfrujący, który służy do szyfrowania plików. Umożliwia on odzyskanie plików użytkownika, jeśli użytkownik zapomni swoje hasło.",
"Recovery key password" : "Hasło klucza odzyskiwania",
"Repeat recovery key password" : "Powtórz hasło klucza odzyskiwania",
"Change recovery key password:" : "Zmień hasło klucza odzyskiwania",
"Old recovery key password" : "Stare hasło klucza odzyskiwania",
"New recovery key password" : "Nowe hasło klucza odzyskiwania",
"Repeat new recovery key password" : "Powtórz nowe hasło klucza odzyskiwania",
"Change Password" : "Zmień hasło",
"Basic encryption module" : "Podstawowy moduł szyfrujący",
"Your private key password no longer matches your log-in password." : "Hasło Twojego klucza prywatnego nie pasuje już do Twojego hasła logowania.",
"Set your old private key password to your current log-in password:" : "Ustaw stare hasło klucza prywatnego na aktualne hasło logowania:",
" If you don't remember your old password you can ask your administrator to recover your files." : "Jeśli nie pamiętasz swojego starego hasła, poproś swojego administratora, aby odzyskać pliki.",
"Old log-in password" : "Stare hasło logowania",
"Current log-in password" : "Bieżące hasło logowania",
"Update Private Key Password" : "Aktualizacja hasła klucza prywatnego",
"Enable password recovery:" : "Włącz hasło odzyskiwania:",
"Enabling this option will allow you to reobtain access to your encrypted files in case of password loss" : "Włączenie tej opcji umożliwia otrzymać dostęp do zaszyfrowanych plików w przypadku utraty hasła",
"Enabled" : "Włączone",
"Disabled" : "Wyłączone"
},
"nplurals=4; plural=(n==1 ? 0 : (n%10>=2 && n%10<=4) && (n%100<12 || n%100>14) ? 1 : n!=1 && (n%10>=0 && n%10<=1) || (n%10>=5 && n%10<=9) || (n%100>=12 && n%100<=14) ? 2 : 3);");
|
import { Ability } from "./ability";
import { search } from "./utility/pathfinding";
import { Hex } from "./utility/hex";
import * as arrayUtils from "./utility/arrayUtils";
import { Drop } from "./drops";
import { Effect } from "./effect";
/**
* Creature Class
*
* Creature contains all creatures properties and attacks
*/
export class Creature {
/* Attributes
*
* NOTE : attributes and variables starting with $ are jquery element
* and jquery function can be called dirrectly from them.
*
* // Jquery attributes
* $display : Creature representation
* $effects : Effects container (inside $display)
*
* // Normal attributes
* x : Integer : Hex coordinates
* y : Integer : Hex coordinates
* pos : Object : Pos object for hex comparison {x,y}
*
* name : String : Creature name
* id : Integer : Creature Id incrementing for each creature starting to 1
* size : Integer : Creature size in hexes (1,2 or 3)
* type : Integer : Type of the creature stocked in the database
* team : Integer : Owner's ID (0,1,2 or 3)
* player : Player : Player object shortcut
* hexagons : Array : Array containing the hexes where the creature is
*
* dead : Boolean : True if dead
* stats : Object : Object containing stats of the creature
* statsAlt : Object : Object containing the alteration value for each stat //todo
* abilities : Array : Array containing the 4 abilities
* remainingMove : Integer : Remaining moves allowed untill the end of turn
*
*/
/* Constructor(obj)
*
* obj : Object : Object containing all creature stats
*
*/
constructor(obj, game) {
// Engine
this.game = game;
this.name = obj.name;
this.id = game.creatureIdCounter++;
this.x = obj.x - 0;
this.y = obj.y - 0;
this.pos = {
x: this.x,
y: this.y
};
this.size = obj.size - 0;
this.type = obj.type;
this.level = obj.level - 0;
this.realm = obj.realm;
this.animation = obj.animation;
this.display = obj.display;
this.drop = obj.drop;
this._movementType = "normal";
if (obj.movementType) {
this._movementType = obj.movementType;
}
this.hexagons = [];
// Game
this.team = obj.team; // = playerID (0,1,2,3)
this.player = game.players[obj.team];
this.dead = false;
this.killer = undefined;
this.hasWait = false;
this.travelDist = 0;
this.effects = [];
this.dropCollection = [];
this.<API key> = (this.type == "--") ? true : false;
this.turnsActive = 0;
// Statistics
this.baseStats = {
health: obj.stats.health - 0,
regrowth: obj.stats.regrowth - 0,
endurance: obj.stats.endurance - 0,
energy: obj.stats.energy - 0,
meditation: obj.stats.meditation - 0,
initiative: obj.stats.initiative - 0,
offense: obj.stats.offense - 0,
defense: obj.stats.defense - 0,
movement: obj.stats.movement - 0,
pierce: obj.stats.pierce - 0,
slash: obj.stats.slash - 0,
crush: obj.stats.crush - 0,
shock: obj.stats.shock - 0,
burn: obj.stats.burn - 0,
frost: obj.stats.frost - 0,
poison: obj.stats.poison - 0,
sonic: obj.stats.sonic - 0,
mental: obj.stats.mental - 0,
moveable: true,
fatigueImmunity: false,
frozen: false,
// Extra energy required for abilities
reqEnergy: 0
};
this.stats = $j.extend({}, this.baseStats); //Copy
this.health = obj.stats.health;
this.endurance = obj.stats.endurance;
this.energy = obj.stats.energy;
this.remainingMove = 0; //Default value recovered each turn
// Abilities
this.abilities = [
new Ability(this, 0, game),
new Ability(this, 1, game),
new Ability(this, 2, game),
new Ability(this, 3, game)
];
this.updateHex();
let dp = (this.type !== "
(this.team === 0) ? "red" :
(this.team === 1) ? "blue" :
(this.team === 2) ? "orange" : "green";
// Creature Container
this.grp = game.Phaser.add.group(game.grid.creatureGroup, "creatureGrp_" + this.id);
this.grp.alpha = 0;
// Adding sprite
this.sprite = this.grp.create(0, 0, this.name + dp + '_cardboard');
this.sprite.anchor.setTo(0.5, 1);
// Placing sprite
this.sprite.x = ((!this.player.flipped) ? this.display["offset-x"] : 90 * this.size - this.sprite.texture.width - this.display["offset-x"]) + this.sprite.texture.width / 2;
this.sprite.y = this.display["offset-y"] + this.sprite.texture.height;
// Placing Group
this.grp.x = this.hexagons[this.size - 1].displayPos.x;
this.grp.y = this.hexagons[this.size - 1].displayPos.y;
this.facePlayerDefault();
// Hint Group
this.hintGrp = game.Phaser.add.group(this.grp, "creatureHintGrp_" + this.id);
this.hintGrp.x = 45 * this.size;
this.hintGrp.y = -this.sprite.texture.height + 5;
// Health indicator
this.<API key> = game.Phaser.add.group(this.grp, "creatureHealthGrp_" + this.id);
// Adding background sprite
this.<API key> = this.<API key>.create(
this.player.flipped ? 19 : 19 + 90 * (this.size - 1),
49,
"p" + this.team + '_health');
// Add text
this.healthIndicatorText = game.Phaser.add.text(
this.player.flipped ? 45 : 45 + 90 * (this.size - 1),
63,
this.health, {
font: "bold 15pt Play",
fill: "#fff",
align: "center",
stroke: "#000",
strokeThickness: 6
});
this.healthIndicatorText.anchor.setTo(0.5, 0.5);
this.<API key>.add(this.healthIndicatorText);
// Hide it
this.<API key>.alpha = 0;
// State variable for displaying endurance/fatigue text
this.fatigueText = "";
// Adding Himself to creature arrays and queue
game.creatures[this.id] = this;
this.delayable = true;
this.delayed = false;
this.<API key> = (this.type == "--") ? false : true;
this.noActionPossible = false;
}
/* summon()
*
* Summon animation
*
*/
summon() {
let game = this.game;
game.queue.addByInitiative(this);
game.updateQueueDisplay();
game.grid.orderCreatureZ();
if (game.grid.materialize_overlay) {
game.grid.materialize_overlay.alpha = 0.5;
game.Phaser.add.tween(game.grid.materialize_overlay)
.to({
alpha: 0
}, 500, Phaser.Easing.Linear.None)
.start();
}
game.Phaser.add.tween(this.grp)
.to({
alpha: 1
}, 500, Phaser.Easing.Linear.None)
.start();
// Reveal and position health indicator
this.updateHealth();
this.healthShow();
// Trigger trap under
this.hexagons.forEach((hex) => {
hex.activateTrap(game.triggers.onStepIn, this);
});
// Pickup drop
this.pickupDrop();
}
healthHide() {
this.<API key>.alpha = 0;
}
healthShow() {
this.<API key>.alpha = 1;
}
/* activate()
*
* Activate the creature by showing movement range and binding controls to this creature
*
*/
activate() {
this.travelDist = 0;
this.oldEnergy = this.energy;
this.oldHealth = this.health;
this.noActionPossible = false;
let game = this.game;
let stats = this.stats;
let varReset = function () {
this.game.onReset(this);
// Variables reset
this.updateAlteration();
this.remainingMove = stats.movement;
if (!this.<API key>) {
// Fatigued creatures (endurance 0) should not regenerate, but fragile
// ones (max endurance 0) should anyway
if (!this.isFatigued()) {
this.heal(stats.regrowth, true);
if (stats.meditation > 0) {
this.recharge(stats.meditation);
}
} else {
if (stats.regrowth < 0) {
this.heal(stats.regrowth, true);
} else {
this.hint("", 'damage');
}
}
} else {
this.hint("", 'damage');
}
setTimeout(() => {
game.UI.energyBar.animSize(this.energy / stats.energy);
game.UI.healthBar.animSize(this.health / stats.health);
}, 1000);
this.endurance = stats.endurance;
this.abilities.forEach((ability) => {
ability.reset();
});
}.bind(this);
// Frozen effect
if (stats.frozen) {
varReset();
var interval = setInterval(() => {
if (!game.turnThrottle) {
clearInterval(interval);
game.skipTurn({
tooltip: "Frozen"
});
}
}, 50);
return;
}
if (!this.hasWait) {
varReset();
// Trigger
game.onStartPhase(this);
}
this.<API key> = false;
var interval = setInterval(() => {
if (!game.freezedInput) {
clearInterval(interval);
if (game.turn >= game.<API key>) {
game.UI.btnFlee.changeState("normal");
}
game.startTimer();
this.queryMove();
}
}, 50);
}
/* deactivate(wait)
*
* wait : Boolean : Deactivate while waiting or not
*
* Preview the creature position at the given coordinates
*
*/
deactivate(wait) {
let game = this.game;
this.hasWait = this.delayed = !!wait;
this.stats.frozen = false;
// Effects triggers
if (!wait) {
this.turnsActive += 1;
game.onEndPhase(this);
}
this.delayable = false;
}
/* wait()
*
* Move the creature to the end of the queue
*
*/
wait() {
let abilityAvailable = false;
if (this.delayed) {
return;
}
// If at least one ability has not been used
this.abilities.forEach((ability) => {
abilityAvailable = abilityAvailable || !ability.used;
});
if (this.remainingMove > 0 && abilityAvailable) {
this.delay(this.game.activeCreature === this);
this.deactivate(true);
}
}
delay(<API key>) {
let game = this.game;
game.queue.delay(this);
this.delayable = false;
this.delayed = true;
this.hint("Delayed", "msg_effects");
game.updateQueueDisplay(<API key>);
}
/* queryMove()
*
* launch move action query
*
*/
queryMove(o) {
let game = this.game;
if (this.dead) {
// Creatures can die during their turns from trap effects; make sure this
// function doesn't do anything
return;
}
// Once Per Damage Abilities recover
game.creatures.forEach((creature) => { //For all Creature
if (creature instanceof Creature) {
creature.abilities.forEach((ability) => {
if (game.triggers.oncePerDamageChain.test(ability.getTrigger())) {
ability.setUsed(false);
}
});
}
});
let remainingMove = this.remainingMove;
// No movement range if unmoveable
if (!this.stats.moveable) {
remainingMove = 0;
}
o = $j.extend({
targeting:false,
noPath: false,
isAbility: false,
ownCreatureHexShade: true,
range: game.grid.getMovementRange(
this.x, this.y, remainingMove, this.size, this.id),
callback: function (hex, args) {
if (hex.x == args.creature.x && hex.y == args.creature.y) {
// Prevent null movement
game.activeCreature.queryMove();
return;
}
game.gamelog.add({
action: "move",
target: {
x: hex.x,
y: hex.y
}
});
args.creature.delayable = false;
game.UI.btnDelay.changeState("disabled");
args.creature.moveTo(hex, {
animation: args.creature.movementType() === "flying" ? "fly" : "walk",
callback: function () {
game.activeCreature.queryMove();
}
});
}
}, o);
if (!o.isAbility) {
if (game.UI.selectedAbility != -1) {
this.hint("Canceled", 'gamehintblack');
}
$j("#abilities .ability").removeClass("active");
game.UI.selectAbility(-1);
game.UI.checkAbilities();
game.UI.updateQueueDisplay();
}
game.grid.orderCreatureZ();
this.facePlayerDefault();
this.updateHealth();
if (this.movementType() === "flying") {
o.range = game.grid.getFlyingRange(
this.x, this.y, remainingMove, this.size, this.id);
}
let selectNormal = function (hex, args) {
args.creature.tracePath(hex);
};
let selectFlying = function (hex, args) {
args.creature.tracePosition({
x: hex.x,
y: hex.y,
overlayClass: "creature moveto selected player" + args.creature.team
});
};
let select = (o.noPath || this.movementType() === "flying") ? selectFlying : selectNormal;
if (this.noActionPossible) {
game.grid.querySelf({
fnOnConfirm: function () {
game.UI.btnSkipTurn.click();
},
fnOnCancel: function () { },
confirmText: "Skip turn"
});
} else {
game.grid.queryHexes({
fnOnSelect: select,
fnOnConfirm: o.callback,
args: {
creature: this,
args: o.args
}, // Optional args
size: this.size,
flipped: this.player.flipped,
id: this.id,
hexes: o.range,
ownCreatureHexShade: o.ownCreatureHexShade,
targeting: o.targeting
});
}
}
/* previewPosition(hex)
*
* hex : Hex : Position
*
* Preview the creature position at the given Hex
*
*/
previewPosition(hex) {
let game = this.game;
game.grid.cleanOverlay("hover h_player" + this.team);
if (!game.grid.hexes[hex.y][hex.x].isWalkable(this.size, this.id)) {
return; // Break if not walkable
}
this.tracePosition({
x: hex.x,
y: hex.y,
overlayClass: "hover h_player" + this.team
});
}
/* cleanHex()
*
* Clean current creature hexagons
*
*/
cleanHex() {
this.hexagons.forEach((hex) => {
hex.creature = undefined;
});
this.hexagons = [];
}
/* updateHex()
*
* Update the current hexes containing the creature and their display
*
*/
updateHex() {
let count = this.size,
i;
for (i = 0; i < count; i++) {
this.hexagons.push(this.game.grid.hexes[this.y][this.x - i]);
}
this.hexagons.forEach((hex) => {
hex.creature = this;
});
}
/* faceHex(facefrom,faceto)
*
* facefrom : Hex or Creature : Hex to face from
* faceto : Hex or Creature : Hex to face
*
* Face creature at given hex
*
*/
faceHex(faceto, facefrom, ignoreCreaHex, attackFix) {
if (!facefrom) {
facefrom = (this.player.flipped) ? this.hexagons[this.size - 1] : this.hexagons[0];
}
if (ignoreCreaHex && this.hexagons.indexOf(faceto) != -1 && this.hexagons.indexOf(facefrom) != -1) {
this.facePlayerDefault();
return;
}
if (faceto instanceof Creature) {
faceto = (faceto.size < 2) ? faceto.hexagons[0] : faceto.hexagons[1];
}
if (faceto.x == facefrom.x && faceto.y == facefrom.y) {
this.facePlayerDefault();
return;
}
if (attackFix && this.size > 1) {
//only works on 2hex creature targeting the adjacent row
if (facefrom.y % 2 === 0) {
if (faceto.x - this.player.flipped == facefrom.x) {
this.facePlayerDefault();
return;
}
} else {
if (faceto.x + 1 - this.player.flipped == facefrom.x) {
this.facePlayerDefault();
return;
}
}
}
if (facefrom.y % 2 === 0) {
var flipped = (faceto.x <= facefrom.x);
} else {
var flipped = (faceto.x < facefrom.x);
}
if (flipped) {
this.sprite.scale.setTo(-1, 1);
} else {
this.sprite.scale.setTo(1, 1);
}
this.sprite.x = ((!flipped) ? this.display["offset-x"] : 90 * this.size - this.sprite.texture.width - this.display["offset-x"]) + this.sprite.texture.width / 2;
}
/* facePlayerDefault()
*
* Face default direction
*
*/
facePlayerDefault() {
if (this.player.flipped) {
this.sprite.scale.setTo(-1, 1);
} else {
this.sprite.scale.setTo(1, 1);
}
this.sprite.x = ((!this.player.flipped) ? this.display["offset-x"] : 90 * this.size - this.sprite.texture.width - this.display["offset-x"]) + this.sprite.texture.width / 2;
}
/* moveTo(hex,opts)
*
* hex : Hex : Destination Hex
* opts : Object : Optional args object
*
* Move the creature along a calculated path to the given coordinates
*
*/
moveTo(hex, opts) {
let game = this.game,
defaultOpt = {
callback: function () {
return true;
},
callbackStepIn: function () {
return true;
},
animation: this.movementType() === "flying" ? "fly" : "walk",
ignoreMovementPoint: false,
ignorePath: false,
customMovementPoint: 0,
overrideSpeed: 0,
<API key>: true
},
path;
opts = $j.extend(defaultOpt, opts);
// Teleportation ignores moveable
if (this.stats.moveable || opts.animation === "teleport") {
let x = hex.x;
let y = hex.y;
if (opts.ignorePath || opts.animation == "fly") {
path = [hex];
} else {
path = this.calculatePath(x, y);
}
if (path.length === 0) {
return; // Break if empty path
}
game.grid.xray(new Hex(0, 0, false, game)); // Clean Xray
this.travelDist = 0;
game.animations[opts.animation](this, path, opts);
} else {
game.log("This creature cannot be moved");
}
let interval = setInterval(() => {
if (!game.freezedInput) {
clearInterval(interval);
opts.callback();
}
}, 100);
}
/* tracePath(hex)
*
* hex : Hex : Destination Hex
*
* Trace the path from the current possition to the given coordinates
*
*/
tracePath(hex) {
let game = this.game,
x = hex.x,
y = hex.y,
path = this.calculatePath(x, y); // Store path in grid to be able to compare it later
if (path.length === 0) {
return; // Break if empty path
}
path.forEach((item) => {
this.tracePosition({
x: item.x,
y: item.y,
displayClass: "adj",
<API key>: false
});
}); // Trace path
// Highlight final position
var last = arrayUtils.last(path);
this.tracePosition({
x: last.x,
y: last.y,
overlayClass: "creature moveto selected player" + this.team,
<API key>: false
});
}
tracePosition(args) {
let defaultArgs = {
x: this.x,
y: this.y,
overlayClass: "",
displayClass: "",
<API key>: true
};
args = $j.extend(defaultArgs, args);
for (let i = 0; i < this.size; i++) {
let canDraw = true;
if(!args.<API key>){ // then check to ensure this is not a creature tile
for(let j = 0; j < this.hexagons.length;j++){
if(this.hexagons[j].x == args.x-i && this.hexagons[j].y == args.y){
canDraw = false;
break;
}
}
}
if(canDraw){
let hex = this.game.grid.hexes[args.y][args.x - i];
this.game.grid.cleanHex(hex);
hex.overlayVisualState(args.overlayClass);
hex.displayVisualState(args.displayClass);
}
}
}
/* calculatePath(x,y)
*
* x : Integer : Destination coordinates
* y : Integer : Destination coordinates
*
* return : Array : Array containing the path hexes
*
*/
calculatePath(x, y) {
let game = this.game;
return search(
game.grid.hexes[this.y][this.x],
game.grid.hexes[y][x],
this.size,
this.id,
this.game.grid
); // Calculate path
}
/* calcOffset(x,y)
*
* x : Integer : Destination coordinates
* y : Integer : Destination coordinates
*
* return : Object : New position taking into acount the size, orientation and obstacle {x,y}
*
* Return the first possible position for the creature at the given coordinates
*
*/
calcOffset(x, y) {
let offset = (game.players[this.team].flipped) ? this.size - 1 : 0,
mult = (game.players[this.team].flipped) ? 1 : -1, // For FLIPPED player
game = this.game;
for (let i = 0; i < this.size; i++) { // Try next hexagons to see if they fit
if ((x + offset - i * mult >= game.grid.hexes[y].length) || (x + offset - i * mult < 0)) {
continue;
}
if (game.grid.hexes[y][x + offset - i * mult].isWalkable(this.size, this.id)) {
x += offset - i * mult;
break;
}
}
return {
x: x,
y: y
};
}
/* getInitiative()
*
* return : Integer : Initiative value to order the queue
*
*/
getInitiative() {
// To avoid 2 identical initiative
return this.stats.initiative * 500 - this.id;
}
/* adjacentHexes(dist)
*
* dist : Integer : Distance in hexagons
*
* return : Array : Array of adjacent hexagons
*
*/
adjacentHexes(dist, clockwise) {
let game = this.game;
// TODO Review this algo to allow distance
if (!!clockwise) {
let hexes = [],
c;
let o = (this.y % 2 === 0) ? 1 : 0;
if (this.size == 1) {
c = [{
y: this.y,
x: this.x + 1
},
{
y: this.y - 1,
x: this.x + o
},
{
y: this.y - 1,
x: this.x - 1 + o
},
{
y: this.y,
x: this.x - 1
},
{
y: this.y + 1,
x: this.x - 1 + o
},
{
y: this.y + 1,
x: this.x + o
}
];
}
if (this.size == 2) {
c = [{
y: this.y,
x: this.x + 1
},
{
y: this.y - 1,
x: this.x + o
},
{
y: this.y - 1,
x: this.x - 1 + o
},
{
y: this.y - 1,
x: this.x - 2 + o
},
{
y: this.y,
x: this.x - 2
},
{
y: this.y + 1,
x: this.x - 2 + o
},
{
y: this.y + 1,
x: this.x - 1 + o
},
{
y: this.y + 1,
x: this.x + o
}
];
}
if (this.size == 3) {
c = [{
y: this.y,
x: this.x + 1
},
{
y: this.y - 1,
x: this.x + o
},
{
y: this.y - 1,
x: this.x - 1 + o
},
{
y: this.y - 1,
x: this.x - 2 + o
},
{
y: this.y - 1,
x: this.x - 3 + o
},
{
y: this.y,
x: this.x - 3
},
{
y: this.y + 1,
x: this.x - 3 + o
},
{
y: this.y + 1,
x: this.x - 2 + o
},
{
y: this.y + 1,
x: this.x - 1 + o
},
{
y: this.y + 1,
x: this.x + o
}
];
}
let total = c.length;
for (let i = 0; i < total; i++) {
const { x, y } = c[i];
if (game.grid.hexExists(y, x)) {
hexes.push(game.grid.hexes[y][x]);
}
}
return hexes;
}
if (this.size > 1) {
let hexes = this.hexagons[0].adjacentHex(dist);
let lasthexes = this.hexagons[this.size - 1].adjacentHex(dist);
hexes.forEach((hex) => {
if (arrayUtils.findPos(this.hexagons, hex)) {
arrayUtils.removePos(hexes, hex);
} // Remove from array if own creature hex
});
lasthexes.forEach((hex) => {
// If node doesnt already exist in final collection and if it's not own creature hex
if (!arrayUtils.findPos(hexes, hex) && !arrayUtils.findPos(this.hexagons, hex)) {
hexes.push(hex);
}
});
return hexes;
} else {
return this.hexagons[0].adjacentHex(dist);
}
}
/**
* Restore energy up to the max limit
* amount: amount of energy to restore
*/
recharge(amount) {
this.energy = Math.min(this.stats.energy, this.energy + amount);
}
/* heal(amount)
*
* amount : Damage : Amount of health point to restore
*/
heal(amount, isRegrowth) {
let game = this.game;
// Cap health point
amount = Math.min(amount, this.stats.health - this.health);
if (this.health + amount < 1) {
amount = this.health - 1; // Cap to 1hp
}
this.health += amount;
// Health display Update
this.updateHealth(isRegrowth);
if (amount > 0) {
if (isRegrowth) {
this.hint("+" + amount + " ", 'healing d' + amount);
} else {
this.hint("+" + amount, 'healing d' + amount);
}
game.log("%CreatureName" + this.id + "% recovers +" + amount + " health");
} else if (amount === 0) {
if (isRegrowth) {
this.hint("", 'msg_effects');
} else {
this.hint("!", 'msg_effects');
}
} else {
if (isRegrowth) {
this.hint(amount + " ", 'damage d' + amount);
} else {
this.hint(amount, 'damage d ' + amount);
}
game.log("%CreatureName" + this.id + "% loses " + amount + " health");
}
game.onHeal(this, amount);
}
/* takeDamage(damage)
*
* damage : Damage : Damage object
*
* return : Object : Contains damages dealed and if creature is killed or not
*/
takeDamage(damage, o) {
let game = this.game;
if (this.dead) {
game.log("%CreatureName" + this.id + "% is already dead, aborting takeDamage call.");
return;
}
let defaultOpt = {
ignoreRetaliation: false,
isFromTrap: false
};
o = $j.extend(defaultOpt, o);
// Determine if melee attack
damage.melee = false;
this.adjacentHexes(1).forEach((hex) => {
if (damage.attacker == hex.creature) {
damage.melee = true;
}
});
damage.target = this;
damage.isFromTrap = o.isFromTrap;
// Trigger
game.onUnderAttack(this, damage);
game.onAttack(damage.attacker, damage);
// Calculation
if (damage.status === "") {
// Damages
let dmg = damage.applyDamage();
let dmgAmount = dmg.total;
if (!isFinite(dmgAmount)) { // Check for Damage Errors
this.hint("Error", 'damage');
game.log("Oops something went wrong !");
return {
damages: 0,
kill: false
};
}
this.health -= dmgAmount;
this.health = (this.health < 0) ? 0 : this.health; // Cap
this.addFatigue(dmgAmount);
// Display
let nbrDisplayed = (dmgAmount) ? "-" + dmgAmount : 0;
this.hint(nbrDisplayed, 'damage d' + dmgAmount);
if (!damage.noLog) {
game.log("%CreatureName" + this.id + "% is hit : " + nbrDisplayed + " health");
}
// If Health is empty
if (this.health <= 0) {
this.die(damage.attacker);
return {
damages: dmg,
damageObj: damage,
kill: true
}; // Killed
}
// Effects
damage.effects.forEach((effect) => {
this.addEffect(effect);
});
// Unfreeze if taking non-zero damage
if (dmgAmount > 0) {
this.stats.frozen = false;
}
// Health display Update
// Note: update health after adding effects as some effects may affect
// health display
this.updateHealth();
game.UI.updateFatigue();
// Trigger
if (!o.ignoreRetaliation) {
game.onDamage(this, damage);
}
return {
damages: dmg,
damageObj: damage,
kill: false
}; // Not Killed
} else {
if (damage.status == "Dodged") { // If dodged
if (!damage.noLog) {
game.log("%CreatureName" + this.id + "% dodged the attack");
}
}
if (damage.status == "Shielded") { // If Shielded
if (!damage.noLog) {
game.log("%CreatureName" + this.id + "% shielded the attack");
}
}
if (damage.status == "Disintegrated") { // If Disintegrated
if (!damage.noLog) {
game.log("%CreatureName" + this.id + "% has been disintegrated");
}
this.die(damage.attacker);
}
// Hint
this.hint(damage.status, 'damage ' + damage.status.toLowerCase());
}
return {
damageObj: damage,
kill: false
}; // Not killed
}
updateHealth(noAnimBar) {
let game = this.game;
if (this == game.activeCreature && !noAnimBar) {
game.UI.healthBar.animSize(this.health / this.stats.health);
}
// Dark Priest plasma shield when inactive
if (this.type == "
if (this.<API key>() && this !== game.activeCreature) {
this.displayPlasmaShield();
} else {
this.displayHealthStats()
}
} else {
this.displayHealthStats();
}
}
displayHealthStats() {
if (this.stats.frozen) {
this.<API key>.loadTexture("p" + this.team + "_frozen");
} else {
this.<API key>.loadTexture("p" + this.team + "_health");
}
this.healthIndicatorText.setText(this.health);
}
displayPlasmaShield() {
this.<API key>.loadTexture("p" + this.team + "_plasma");
this.healthIndicatorText.setText(this.player.plasma);
}
<API key>() {
return this.player.plasma > 0;
}
addFatigue(dmgAmount) {
if (!this.stats.fatigueImmunity) {
this.endurance -= dmgAmount;
this.endurance = this.endurance < 0 ? 0 : this.endurance; // Cap
}
this.game.UI.updateFatigue();
}
/* addEffect(effect)
*
* effect : Effect : Effect object
*
*/
addEffect(effect, specialString, specialHint) {
let game = this.game;
if (!effect.stackable && this.findEffect(effect.name).length !== 0) {
//G.log(this.player.name+"'s "+this.name+" is already affected by "+effect.name);
return false;
}
effect.target = this;
this.effects.push(effect);
game.onEffectAttach(this, effect);
this.updateAlteration();
if (effect.name !== "") {
if (specialHint || effect.specialHint) {
this.hint(specialHint, 'msg_effects');
} else {
this.hint(effect.name, 'msg_effects');
}
if (specialString) {
game.log(specialString);
} else {
game.log("%CreatureName" + this.id + "% is affected by " + effect.name);
}
}
}
/**
* Add effect, but if the effect is already attached, replace it with the new
* effect.
* Note that for stackable effects, this is the same as addEffect()
*
* effect - the effect to add
*/
replaceEffect(effect) {
if (!effect.stackable && this.findEffect(effect.name).length !== 0) {
this.removeEffect(effect.name);
}
this.addEffect(effect);
}
/**
* Remove an effect by name
*
* name - name of effect
*/
removeEffect(name) {
let totalEffects = this.effects.length;
for (var i = 0; i < totalEffects; i++) {
if (this.effects[i].name === name) {
this.effects.splice(i, 1);
break;
}
}
}
hint(text, cssClass) {
let game = this.game,
tooltipSpeed = 250,
tooltipDisplaySpeed = 500,
tooltipTransition = Phaser.Easing.Linear.None;
let hintColor = {
confirm: {
fill: "#ffffff",
stroke: "#000000"
},
gamehintblack: {
fill: "#ffffff",
stroke: "#000000"
},
healing: {
fill: "#00ff00"
},
msg_effects: {
fill: "#ffff00"
}
};
let style = $j.extend({
font: "bold 20pt Play",
fill: "#ff0000",
align: "center",
stroke: "#000000",
strokeThickness: 2
}, hintColor[cssClass]);
// Remove constant element
this.hintGrp.forEach((grpHintElem) => {
if (grpHintElem.cssClass == 'confirm') {
grpHintElem.cssClass = "confirm_deleted";
grpHintElem.tweenAlpha = game.Phaser.add.tween(grpHintElem).to({
alpha: 0
}, tooltipSpeed, tooltipTransition).start();
grpHintElem.tweenAlpha.onComplete.add(function () {
this.destroy();
}, grpHintElem);
}
}, this, true);
var hint = game.Phaser.add.text(0, 50, text, style);
hint.anchor.setTo(0.5, 0.5);
hint.alpha = 0;
hint.cssClass = cssClass;
if (cssClass == 'confirm') {
hint.tweenAlpha = game.Phaser.add.tween(hint)
.to({
alpha: 1
}, tooltipSpeed, tooltipTransition)
.start();
} else {
hint.tweenAlpha = game.Phaser.add.tween(hint)
.to({
alpha: 1
}, tooltipSpeed, tooltipTransition)
.to({
alpha: 1
}, tooltipDisplaySpeed, tooltipTransition)
.to({
alpha: 0
}, tooltipSpeed, tooltipTransition).start();
hint.tweenAlpha.onComplete.add(function () {
this.destroy();
}, hint);
}
this.hintGrp.add(hint);
// Stacking
this.hintGrp.forEach((grpHintElem) => {
let index = this.hintGrp.total - this.hintGrp.getIndex(grpHintElem) - 1;
let offset = -50 * index;
if (grpHintElem.tweenPos) {
grpHintElem.tweenPos.stop();
}
grpHintElem.tweenPos = game.Phaser.add.tween(grpHintElem).to({
y: offset
}, tooltipSpeed, tooltipTransition).start();
}, this, true);
}
/* updateAlteration()
*
* Update the stats taking into account the effects' alteration
*
*/
updateAlteration() {
this.stats = $j.extend({}, this.baseStats); // Copy
let buffDebuffArray = this.effects;
buffDebuffArray.forEach((buff) => {
$j.each(buff.alterations, (key, value) => {
if (typeof value == "string") {
// Multiplication Buff
if (value.match(/\*/)) {
this.stats[key] = eval(this.stats[key] + value);
}
// Division Debuff
if (value.match(/\
this.stats[key] = eval(this.stats[key] + value);
}
}
// Usual Buff/Debuff
if ((typeof value) == "number") {
this.stats[key] += value;
}
// Boolean Buff/Debuff
if ((typeof value) == "boolean") {
this.stats[key] = value;
}
});
});
this.stats.endurance = Math.max(this.stats.endurance, 0);
this.endurance = Math.min(this.endurance, this.stats.endurance);
this.energy = Math.min(this.energy, this.stats.energy);
this.remainingMove = Math.min(this.remainingMove, this.stats.movement);
}
/* die()
*
* kill animation. remove creature from queue and from hexes
*
* killer : Creature : Killer of this creature
*
*/
die(killer) {
let game = this.game;
game.log("%CreatureName" + this.id + "% is dead");
this.dead = true;
// Triggers
game.onCreatureDeath(this);
this.killer = killer.player;
let isDeny = (this.killer.flipped == this.player.flipped);
// Drop item
if (game.unitDrops == 1 && this.drop) {
var offsetX = (this.player.flipped) ? this.x - this.size + 1 : this.x;
new Drop(this.drop.name, this.drop.health, this.drop.energy, offsetX, this.y, game);
}
if (!game.firstKill && !isDeny) { // First Kill
this.killer.score.push({
type: "firstKill"
});
game.firstKill = true;
}
if (this.type == "--") { // If Dark Priest
if (isDeny) {
// TEAM KILL (DENY)
this.killer.score.push({
type: "deny",
creature: this
});
} else {
// Humiliation
this.killer.score.push({
type: "humiliation",
player: this.team
});
}
}
if (!this.undead) { // Only if not undead
if (isDeny) {
// TEAM KILL (DENY)
this.killer.score.push({
type: "deny",
creature: this
});
} else {
// KILL
this.killer.score.push({
type: "kill",
creature: this
});
}
}
if (this.player.isAnnihilated()) {
// Remove humiliation as annihilation is an upgrade
let total = this.killer.score.length;
for (let i = 0; i < total; i++) {
var s = this.killer.score[i];
if (s.type == "humiliation") {
if (s.player == this.team) {
this.killer.score.splice(i, 1);
}
break;
}
}
// ANNIHILATION
this.killer.score.push({
type: "annihilation",
player: this.team
});
}
if (this.type == "
this.player.deactivate(); // Here because of score calculation
}
// Kill animation
var tweenSprite = game.Phaser.add.tween(this.sprite).to({
alpha: 0
}, 500, Phaser.Easing.Linear.None).start();
var tweenHealth = game.Phaser.add.tween(this.<API key>).to({
alpha: 0
}, 500, Phaser.Easing.Linear.None).start();
tweenSprite.onComplete.add(() => {
this.sprite.destroy();
});
tweenHealth.onComplete.add(() => {
this.<API key>.destroy();
});
this.cleanHex();
game.queue.remove(this);
game.updateQueueDisplay();
game.grid.updateDisplay();
if (game.activeCreature === this) {
game.nextCreature();
return;
} //End turn if current active creature die
// As hex occupation changes, path must be recalculated for the current creature not the dying one
game.activeCreature.queryMove();
// Queue cleaning
game.UI.updateActivebox();
game.UI.updateQueueDisplay(); // Just in case
}
isFatigued() {
return this.endurance === 0 && !this.isFragile();
}
isFragile() {
return this.stats.endurance === 0;
}
/* getHexMap()
*
* shortcut convenience function to grid.getHexMap
*/
getHexMap(map, invertFlipped) {
var x = (this.player.flipped ? !invertFlipped : invertFlipped) ? this.x + 1 - this.size : this.x;
return this.game.grid.getHexMap(x, this.y - map.origin[1], 0 - map.origin[0], (this.player.flipped ? !invertFlipped : invertFlipped), map);
}
getBuffDebuff(stat) {
let buffDebuffArray = this.effects.concat(this.dropCollection),
buff = 0,
debuff = 0,
buffObjs = {
effects: [],
drops: []
};
let addToBuffObjs = function (obj) {
if (obj instanceof Effect) {
buffObjs.effects.push(obj);
} else if (obj instanceof Drop) {
buffObjs.drops.push(obj);
}
};
buffDebuffArray.forEach((buff) => {
let o = buff;
$j.each(buff.alterations, (key, value) => {
if (typeof value == "string") {
if (key === stat || stat === undefined) {
// Multiplication Buff
if (value.match(/\*/)) {
addToBuffObjs(o);
let base = this.stats[key];
let result = eval(this.stats[key] + value);
if (result > base) {
buff += result - base;
} else {
debuff += result - base;
}
}
// Division Debuff
if (value.match(/\
addToBuffObjs(o);
let base = this.stats[key];
let result = eval(this.stats[key] + value);
if (result > base) {
buff += result - base;
} else {
debuff += result - base;
}
}
}
}
// Usual Buff/Debuff
if ((typeof value) == "number") {
if (key === stat || stat === undefined) {
addToBuffObjs(o);
if (value > 0) {
buff += value;
} else {
debuff += value;
}
}
}
});
});
return {
buff: buff,
debuff: debuff,
objs: buffObjs
};
}
findEffect(name) {
let ret = [];
this.effects.forEach((effect) => {
if (effect.name == name) {
ret.push(effect);
}
});
return ret;
}
// Make units transparent
xray(enable) {
let game = this.game;
if (enable) {
game.Phaser.add.tween(this.grp)
.to({
alpha: 0.5
}, 250, Phaser.Easing.Linear.None)
.start();
} else {
game.Phaser.add.tween(this.grp)
.to({
alpha: 1
}, 250, Phaser.Easing.Linear.None)
.start();
}
}
pickupDrop() {
this.hexagons.forEach((hex) => {
hex.pickupDrop(this);
});
}
/**
* Get movement type for this creature
* @return {string} "normal", "hover", or "flying"
*/
movementType() {
let totalAbilities = this.abilities.length;
// If the creature has an ability that modifies movement type, use that,
// otherwise use the creature's base movement type
for (let i = 0; i < totalAbilities; i++) {
if ('movementType' in this.abilities[i]) {
return this.abilities[i].movementType();
}
}
return this._movementType;
}
}
|
<!DOCTYPE html>
<html lang="en"
>
<head>
<title>40123226 - CDW11 (MDE)</title>
<!-- Using the latest rendering mode for IE -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style type="text/css">
/*some stuff for output/input prompts*/
div.cell{border:1px solid transparent;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch}div.cell.selected{border-radius:4px;border:thin #ababab solid}
div.cell.edit_mode{border-radius:4px;border:thin #008000 solid}
div.cell{width:100%;padding:5px 5px 5px 0;margin:0;outline:none}
div.prompt{min-width:11ex;padding:.4em;margin:0;font-family:monospace;text-align:right;line-height:1.21429em}
@media (max-width:480px){div.prompt{text-align:left}}div.inner_cell{display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;display:flex;flex-direction:column;align-items:stretch;-webkit-box-flex:1;-moz-box-flex:1;box-flex:1;flex:1}
div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;line-height:1.21429em}
div.prompt:empty{padding-top:0;padding-bottom:0}
div.input{page-break-inside:avoid;display:-webkit-box;-webkit-box-orient:horizontal;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:horizontal;-moz-box-align:stretch;display:box;box-orient:horizontal;box-align:stretch;}
div.inner_cell{width:90%;}
div.input_area{border:1px solid #cfcfcf;border-radius:4px;background:#f7f7f7;}
div.input_prompt{color:navy;border-top:1px solid transparent;}
div.output_wrapper{margin-top:5px;position:relative;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;}
div.output_scroll{height:24em;width:100%;overflow:auto;border-radius:4px;-webkit-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);-moz-box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);box-shadow:inset 0 2px 8px rgba(0, 0, 0, 0.8);}
div.output_collapsed{margin:0px;padding:0px;display:-webkit-box;-webkit-box-orient:vertical;-webkit-box-align:stretch;display:-moz-box;-moz-box-orient:vertical;-moz-box-align:stretch;display:box;box-orient:vertical;box-align:stretch;width:100%;}
div.out_prompt_overlay{height:100%;padding:0px 0.4em;position:absolute;border-radius:4px;}
div.out_prompt_overlay:hover{-webkit-box-shadow:inset 0 0 1px #000000;-moz-box-shadow:inset 0 0 1px #000000;box-shadow:inset 0 0 1px #000000;background:rgba(240, 240, 240, 0.5);}
div.output_prompt{color:darkred;}
a.anchor-link:link{text-decoration:none;padding:0px 20px;visibility:hidden;}
h1:hover .anchor-link,h2:hover .anchor-link,h3:hover .anchor-link,h4:hover .anchor-link,h5:hover .anchor-link,h6:hover .anchor-link{visibility:visible;}
/* end stuff for output/input prompts*/
.highlight-ipynb .hll { background-color: #ffffcc }
.highlight-ipynb { background: #f8f8f8; }
.highlight-ipynb .c { color: #408080; font-style: italic } /* Comment */
.highlight-ipynb .err { border: 1px solid #FF0000 } /* Error */
.highlight-ipynb .k { color: #008000; font-weight: bold } /* Keyword */
.highlight-ipynb .o { color: #666666 } /* Operator */
.highlight-ipynb .cm { color: #408080; font-style: italic } /* Comment.Multiline */
.highlight-ipynb .cp { color: #BC7A00 } /* Comment.Preproc */
.highlight-ipynb .c1 { color: #408080; font-style: italic } /* Comment.Single */
.highlight-ipynb .cs { color: #408080; font-style: italic } /* Comment.Special */
.highlight-ipynb .gd { color: #A00000 } /* Generic.Deleted */
.highlight-ipynb .ge { font-style: italic } /* Generic.Emph */
.highlight-ipynb .gr { color: #FF0000 } /* Generic.Error */
.highlight-ipynb .gh { color: #000080; font-weight: bold } /* Generic.Heading */
.highlight-ipynb .gi { color: #00A000 } /* Generic.Inserted */
.highlight-ipynb .go { color: #888888 } /* Generic.Output */
.highlight-ipynb .gp { color: #000080; font-weight: bold } /* Generic.Prompt */
.highlight-ipynb .gs { font-weight: bold } /* Generic.Strong */
.highlight-ipynb .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
.highlight-ipynb .gt { color: #0044DD } /* Generic.Traceback */
.highlight-ipynb .kc { color: #008000; font-weight: bold } /* Keyword.Constant */
.highlight-ipynb .kd { color: #008000; font-weight: bold } /* Keyword.Declaration */
.highlight-ipynb .kn { color: #008000; font-weight: bold } /* Keyword.Namespace */
.highlight-ipynb .kp { color: #008000 } /* Keyword.Pseudo */
.highlight-ipynb .kr { color: #008000; font-weight: bold } /* Keyword.Reserved */
.highlight-ipynb .kt { color: #B00040 } /* Keyword.Type */
.highlight-ipynb .m { color: #666666 } /* Literal.Number */
.highlight-ipynb .s { color: #BA2121 } /* Literal.String */
.highlight-ipynb .na { color: #7D9029 } /* Name.Attribute */
.highlight-ipynb .nb { color: #008000 } /* Name.Builtin */
.highlight-ipynb .nc { color: #0000FF; font-weight: bold } /* Name.Class */
.highlight-ipynb .no { color: #880000 } /* Name.Constant */
.highlight-ipynb .nd { color: #AA22FF } /* Name.Decorator */
.highlight-ipynb .ni { color: #999999; font-weight: bold } /* Name.Entity */
.highlight-ipynb .ne { color: #D2413A; font-weight: bold } /* Name.Exception */
.highlight-ipynb .nf { color: #0000FF } /* Name.Function */
.highlight-ipynb .nl { color: #A0A000 } /* Name.Label */
.highlight-ipynb .nn { color: #0000FF; font-weight: bold } /* Name.Namespace */
.highlight-ipynb .nt { color: #008000; font-weight: bold } /* Name.Tag */
.highlight-ipynb .nv { color: #19177C } /* Name.Variable */
.highlight-ipynb .ow { color: #AA22FF; font-weight: bold } /* Operator.Word */
.highlight-ipynb .w { color: #bbbbbb } /* Text.Whitespace */
.highlight-ipynb .mf { color: #666666 } /* Literal.Number.Float */
.highlight-ipynb .mh { color: #666666 } /* Literal.Number.Hex */
.highlight-ipynb .mi { color: #666666 } /* Literal.Number.Integer */
.highlight-ipynb .mo { color: #666666 } /* Literal.Number.Oct */
.highlight-ipynb .sb { color: #BA2121 } /* Literal.String.Backtick */
.highlight-ipynb .sc { color: #BA2121 } /* Literal.String.Char */
.highlight-ipynb .sd { color: #BA2121; font-style: italic } /* Literal.String.Doc */
.highlight-ipynb .s2 { color: #BA2121 } /* Literal.String.Double */
.highlight-ipynb .se { color: #BB6622; font-weight: bold } /* Literal.String.Escape */
.highlight-ipynb .sh { color: #BA2121 } /* Literal.String.Heredoc */
.highlight-ipynb .si { color: #BB6688; font-weight: bold } /* Literal.String.Interpol */
.highlight-ipynb .sx { color: #008000 } /* Literal.String.Other */
.highlight-ipynb .sr { color: #BB6688 } /* Literal.String.Regex */
.highlight-ipynb .s1 { color: #BA2121 } /* Literal.String.Single */
.highlight-ipynb .ss { color: #19177C } /* Literal.String.Symbol */
.highlight-ipynb .bp { color: #008000 } /* Name.Builtin.Pseudo */
.highlight-ipynb .vc { color: #19177C } /* Name.Variable.Class */
.highlight-ipynb .vg { color: #19177C } /* Name.Variable.Global */
.highlight-ipynb .vi { color: #19177C } /* Name.Variable.Instance */
.highlight-ipynb .il { color: #666666 } /* Literal.Number.Integer.Long */
</style>
<style type="text/css">
/* Overrides of notebook CSS for static HTML export */
div.entry-content {
overflow: visible;
padding: 8px;
}
.input_area {
padding: 0.2em;
}
a.heading-anchor {
white-space: normal;
}
.rendered_html
code {
font-size: .8em;
}
pre.ipynb {
color: black;
background: #f7f7f7;
border: none;
box-shadow: none;
margin-bottom: 0;
padding: 0;
margin: 0px;
font-size: 13px;
}
/* remove the prompt div from text cells */
div.text_cell .prompt {
display: none;
}
/* remove horizontal padding from text cells, */
/* so it aligns with outer body text */
div.text_cell_render {
padding: 0.5em 0em;
}
img.anim_icon{padding:0; border:0; vertical-align:middle; -webkit-box-shadow:none; -box-shadow:none}
</style>
<script src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML" type="text/javascript"></script>
<script type="text/javascript">
init_mathjax = function() {
if (window.MathJax) {
// MathJax loaded
MathJax.Hub.Config({
tex2jax: {
inlineMath: [ ['$','$'], ["\\(","\\)"] ],
displayMath: [ ['$$','$$'], ["\\[","\\]"] ]
},
displayAlign: 'left', // Change this to 'center' to center equations.
"HTML-CSS": {
styles: {'.MathJax_Display': {"margin": 0}}
}
});
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
}
}
init_mathjax();
</script>
<meta name="author" content="kmol" />
<meta name="keywords" content="40123226" />
<!-- Open Graph tags -->
<meta property="og:site_name" content="CDW11 (MDE)" />
<meta property="og:type" content="website"/>
<meta property="og:title" content="CDW11 (MDE)"/>
<meta property="og:url" content="http://cdw11-40323200.rhcloud.com/static/blog"/>
<meta property="og:description" content="CDW11 (MDE)"/>
<!-- Bootstrap -->
<link rel="stylesheet" href="http://cdw11-40323200.rhcloud.com/static/blog/theme/css/bootstrap.united.min.css" type="text/css"/>
<link href="http://cdw11-40323200.rhcloud.com/static/blog/theme/css/font-awesome.min.css" rel="stylesheet">
<link href="http://cdw11-40323200.rhcloud.com/static/blog/theme/css/pygments/monokai.css" rel="stylesheet">
<link href="http://cdw11-40323200.rhcloud.com/static/blog/theme/tipuesearch/tipuesearch.css" rel="stylesheet">
<link rel="stylesheet" href="http://cdw11-40323200.rhcloud.com/static/blog/theme/css/style.css" type="text/css"/>
<link href="http://cdw11-40323200.rhcloud.com/static/blog/feeds/all.atom.xml" type="application/atom+xml" rel="alternate"
title="CDW11 (MDE) ATOM Feed"/>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shCore.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushJScript.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushJava.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushPython.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushSql.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushXml.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushPhp.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCpp.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCss.js"></script>
<script type="text/javascript" src="http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/shBrushCSharp.js"></script>
<script type='text/javascript'>
(function(){
var corecss = document.createElement('link');
var themecss = document.createElement('link');
var corecssurl = "http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/css/shCore.css";
if ( corecss.setAttribute ) {
corecss.setAttribute( "rel", "stylesheet" );
corecss.setAttribute( "type", "text/css" );
corecss.setAttribute( "href", corecssurl );
} else {
corecss.rel = "stylesheet";
corecss.href = corecssurl;
}
document.<API key>("head")[0].insertBefore( corecss, document.getElementById("<API key>") );
var themecssurl = "http://cad-lab.github.io/cadlab_data/files/syntaxhighlighter/css/shThemeDefault.css?ver=3.0.9b";
if ( themecss.setAttribute ) {
themecss.setAttribute( "rel", "stylesheet" );
themecss.setAttribute( "type", "text/css" );
themecss.setAttribute( "href", themecssurl );
} else {
themecss.rel = "stylesheet";
themecss.href = themecssurl;
}
//document.getElementById("<API key>").appendChild(themecss);
document.<API key>("head")[0].insertBefore( themecss, document.getElementById("<API key>") );
})();
SyntaxHighlighter.config.strings.expandSource = '+ expand source';
SyntaxHighlighter.config.strings.help = '?';
SyntaxHighlighter.config.strings.alert = 'SyntaxHighlighter\n\n';
SyntaxHighlighter.config.strings.noBrush = 'Can\'t find brush for: ';
SyntaxHighlighter.config.strings.brushNotHtmlScript = 'Brush wasn\'t configured for html-script option: ';
SyntaxHighlighter.defaults['pad-line-numbers'] = false;
SyntaxHighlighter.defaults['toolbar'] = false;
SyntaxHighlighter.all();
</script>
</head>
<body>
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a href="http://cdw11-40323200.rhcloud.com/static/blog/" class="navbar-brand">
CDW11 (MDE) </a>
</div>
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag1.html">Ag1</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag10.html">Ag10</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag100.html">Ag100</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag4.html">Ag4</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag7.html">Ag7</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag8.html">Ag8</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg1.html">Bg1</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg10.html">Bg10</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg11.html">Bg11</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg2.html">Bg2</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg3.html">Bg3</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg4.html">Bg4</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg5.html">Bg5</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg8.html">Bg8</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg9.html">Bg9</a>
</li>
<li >
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/g3.html">G3</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><span>
<form class="navbar-search" action="http://cdw11-40323200.rhcloud.com/static/blog/search.html">
<input type="text" class="search-query" placeholder="Search" name="q" id="tipue_search_input" required>
</form></span>
</li>
<li><a href="http://cdw11-40323200.rhcloud.com/static/blog/archives.html"><i class="fa fa-th-list"></i><span class="icon-label">Archives</span></a></li>
</ul>
</div>
<!-- /.navbar-collapse -->
</div>
</div> <!-- /.navbar -->
<!-- Banner -->
<!-- End Banner -->
<div class="container">
<div class="row">
<div class="col-sm-9">
<article>
<h2><a href="http://cdw11-40323200.rhcloud.com/static/blog/<API key>.html">40123226 cdw11 </a></h2>
<div class="summary"><p> cdw11 </p>
<a class="btn btn-default btn-xs" href="http://cdw11-40323200.rhcloud.com/static/blog/<API key>.html">more ...</a>
</div>
</article>
<hr/>
</div>
<div class="col-sm-3" id="sidebar">
<aside>
<section class="well well-sm">
<ul class="list-group list-group-flush">
<li class="list-group-item"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Recent Posts</span></h4>
<ul class="list-group" id="recentposts">
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/<API key>.html">
40123226 cdw11
</a>
</li>
</ul>
</li>
<li class="list-group-item"><a href="http://cdw11-40323200.rhcloud.com/static/blog/categories.html"><h4><i class="fa fa-home fa-lg"></i><span class="icon-label">Categories</span></h4></a>
<ul class="list-group" id="categories">
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag1.html">
<i class="fa fa-folder-open fa-lg"></i> ag1
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag10.html">
<i class="fa fa-folder-open fa-lg"></i> ag10
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag100.html">
<i class="fa fa-folder-open fa-lg"></i> ag100
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag4.html">
<i class="fa fa-folder-open fa-lg"></i> ag4
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag7.html">
<i class="fa fa-folder-open fa-lg"></i> ag7
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/ag8.html">
<i class="fa fa-folder-open fa-lg"></i> ag8
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg1.html">
<i class="fa fa-folder-open fa-lg"></i> bg1
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg10.html">
<i class="fa fa-folder-open fa-lg"></i> bg10
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg11.html">
<i class="fa fa-folder-open fa-lg"></i> bg11
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg2.html">
<i class="fa fa-folder-open fa-lg"></i> bg2
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg3.html">
<i class="fa fa-folder-open fa-lg"></i> bg3
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg4.html">
<i class="fa fa-folder-open fa-lg"></i> bg4
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg5.html">
<i class="fa fa-folder-open fa-lg"></i> bg5
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg8.html">
<i class="fa fa-folder-open fa-lg"></i> bg8
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/bg9.html">
<i class="fa fa-folder-open fa-lg"></i> bg9
</a>
</li>
<li class="list-group-item">
<a href="http://cdw11-40323200.rhcloud.com/static/blog/category/g3.html">
<i class="fa fa-folder-open fa-lg"></i> g3
</a>
</li>
</ul>
</li>
<li class="list-group-item"><a href="http://cdw11-40323200.rhcloud.com/static/blog/tags.html"><h4><i class="fa fa-tags fa-lg"></i><span class="icon-label">Tags</span></h4></a>
<ul class="list-group list-inline tagcloud" id="tags">
</ul>
</li>
<li class="list-group-item"><h4><i class="fa <API key> fa-lg"></i><span class="icon-label">Links</span></h4>
<ul class="list-group" id="links">
<li class="list-group-item">
<a href="http://getpelican.com/" target="_blank">
Pelican
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/DandyDev/pelican-bootstrap3/" target="_blank">
pelican-bootstrap3
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/getpelican/pelican-plugins" target="_blank">
pelican-plugins
</a>
</li>
<li class="list-group-item">
<a href="https://github.com/Tipue/Tipue-Search" target="_blank">
Tipue search
</a>
</li>
</ul>
</li>
</ul>
</section>
</aside>
</div>
</div>
</div>
<footer>
<div class="container">
<hr>
<div class="row">
<div class="col-xs-10">© 2016 kmol
· Powered by <a href="https://github.com/DandyDev/pelican-bootstrap3" target="_blank">pelican-bootstrap3</a>,
<a href="http://docs.getpelican.com/" target="_blank">Pelican</a>,
<a href="http://getbootstrap.com" target="_blank">Bootstrap</a> </div>
<div class="col-xs-2"><p class="pull-right"><i class="fa fa-arrow-up"></i> <a href="#">Back to top</a></p></div>
</div>
</div>
</footer>
<script src="http://cdw11-40323200.rhcloud.com/static/blog/theme/js/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="http://cdw11-40323200.rhcloud.com/static/blog/theme/js/bootstrap.min.js"></script>
<script src="http://cdw11-40323200.rhcloud.com/static/blog/theme/js/respond.min.js"></script>
<!-- Disqus -->
<script type="text/javascript">
/* * * CONFIGURATION VARIABLES: EDIT BEFORE PASTING INTO YOUR WEBPAGE * * */
var disqus_shortname = 'cadlabmanual'; // required: replace example with your forum shortname
/* * * DON'T EDIT BELOW THIS LINE * * */
(function () {
var s = document.createElement('script');
s.async = true;
s.type = 'text/javascript';
s.src = '//' + disqus_shortname + '.disqus.com/count.js';
(document.<API key>('HEAD')[0] || document.<API key>('BODY')[0]).appendChild(s);
}());
</script>
<!-- End Disqus Code -->
</body>
</html>
|
class GroupSerializer < ActiveModel::Serializer
embed :ids, include: true
attributes :id,
:organisation_id,
:cohort_id,
:key,
:name,
:created_at,
:description,
:<API key>,
:<API key>,
:<API key>,
:<API key>,
:<API key>,
:<API key>,
:members_can_vote,
:memberships_count,
:members_count,
:visible_to,
:<API key>,
:<API key>,
:logo_url_medium,
:cover_url_desktop,
:has_discussions,
:has_multiple_admins
has_one :parent, serializer: GroupSerializer, root: 'groups'
def logo_url_medium
object.logo.url(:medium)
end
def <API key>?
object.logo.present?
end
def cover_url_desktop
object.cover_photo.url(:desktop)
end
def <API key>?
object.cover_photo.present?
end
def <API key>
object.<API key>
end
def has_discussions
object.discussions_count > 0
end
def has_multiple_admins
object.admins.count > 1
end
end
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
namespace core.Udp
{
class UdpNode
{
public IPAddress IP { get; set; }
public ushort Port { get; set; }
public int Ack { get; set; }
public int Try { get; set; }
public ulong LastConnect { get; set; }
public ulong LastSentIPS { get; set; }
public EndPoint EndPoint
{
get { return new IPEndPoint(this.IP, this.Port); }
}
}
}
|
#pragma once
#include <memory>
#include "FullBlock.h"
#include "BlockEntity.h"
class BlockSource;
class BlockPos;
class BlockSourceListener
{
public:
virtual ~BlockSourceListener();
virtual void onSourceCreated(BlockSource &);
virtual void onSourceDestroyed(BlockSource &);
virtual void onBlocksDirty(BlockSource &, int, int, int, int, int, int);
virtual void onAreaChanged(BlockSource &, BlockPos const &, BlockPos const &);
virtual void onBlockChanged(BlockSource &, BlockPos const &, FullBlock, FullBlock, int);
virtual void onBrightnessChanged(BlockSource &, BlockPos const &);
virtual void <API key>(BlockSource &, BlockEntity &);
virtual void <API key>(BlockSource &, std::unique_ptr<BlockEntity>);
virtual void onBlockEvent(BlockSource &, int, int, int, int, int);
};
|
<html>
<heac>
<meta charset="UTF-8">
<title>Test for MPI.js</title>
<script type="text/javascript" src="MPI.js"></script>
<script type="text/javascript" src="MPIupdateable.js"></script>
<script type="text/javascript" src="mpitests.js"></script>
<script>
MPImain.run();
</script>
</head>
<body>
See console for test output
</body>
</html>
|
class Admin::AdminSerializer < ActiveModel::Serializer
attributes :id, :name, :email, :teachers
def teachers
teacher_ids = User.find(object.id).teacher_ids
teachers_data = TeachersData.run(teacher_ids)
teachers_data.map{|t| Admin::TeacherSerializer.new(t, root: false) }
end
end
|
#!/usr/bin/python
#-*- coding: utf-8 -*-
# This file is part of Skarphed.
# Skarphed is free software: you can redistribute it and/or
# as published by the Free Software Foundation, either
# version.
# Skarphed is distributed in the hope that it will be
# You should have received a copy of the GNU Affero General Public
import os
from daemon import Daemon
from time import sleep
from StringIO import StringIO
from traceback import print_exc
from skarphedcore.configuration import Configuration
from skarphedcore.database import Database
from skarphedcore.core import Core
from skarphedcore.module import Module
from common.errors import OperationException
class Operation(object):
"""
Contais everything necessary to Handle Operations
"""
STATUS_PENDING = 0
STATUS_ACTIVE = 1
STATUS_FAILED = 2
VALID_STORAGE_TYPES = ('int','bool','str','unicode')
def __init__(self, parent_id = None):
self._id = None
self._parent = parent_id
self._values = {}
@classmethod
def drop_operation(cls,operation_id):
"""
Drops an Operation, identified by it's Operation Id and
it's children recursively
Drop deletes the Operations from Database
"""
db = Database()
stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS IN (0, 2) ;"
cur = db.query(stmnt,(operation_id,))
for row in cur.fetchallmap():
cls.drop_operation(row["OPE_ID"])
stmnt = "DELETE FROM OPERATIONS WHERE OPE_ID = ? AND OPE_STATUS IN (0, 2) ;"
db.query(stmnt,(operation_id,),commit=True)
@classmethod
def retry_operation(cls,operation_id):
"""
Resets the state of an operation and it's children recursively to 0 (PENDING)
The operation is identified by a given operationId
"""
db = Database()
stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 2 ;"
cur = db.query(stmnt,(operation_id,))
for row in cur.fetchallmap():
cls.retry_operation(row["OPE_ID"])
stmnt = "UPDATE OPERATIONS SET OPE_STATUS = 0 WHERE OPE_ID = ? AND OPE_STATUS = 2 ;"
db.query(stmnt,(operation_id,),commit=True)
@classmethod
def cancel_operation(cls,operation_id):
"""
Cancels an Operation, identified by it's Operation Id and
it's children recursively
Cancel Deletes the Operation from Database
"""
db = Database()
stmnt = "SELECT OPE_ID FROM OPERATIONS WHERE OPE_OPE_PARENT = ? AND OPE_STATUS = 0 ;"
cur = db.query(stmnt,(operation_id,))
for row in cur.fetchallmap():
cls.cancel_operation(row["OPE_ID"])
stmnt = "DELETE FROM OPERATIONS WHERE OPE_ID = ? AND OPE_STATUS = 0 ;"
db.query(stmnt,(operation_id,),commit=True)
@classmethod
def restore_operation(cls, operation_record):
"""
Restore an Operationobject stored in the database by a Dataset consisting of
the operation's ID and the operation's TYPE:
For example: {"OPE_ID": 100, "OPE_TYPE": "TestOperation"}
Restores the Operationobject's _values-attribute by the data saved
in the DB-Table OPERATIONDATA
"""
classname = operation_record["OPE_TYPE"]
module = "" #TODO Implement modulename from database if Operation belongs to Module
<API key> = False
exec """
try:
type(%(class)s)
except NameError,e:
<API key> = True"""%{'class':classname}
if <API key>:
exec """
from %(module)s import %(class)s
operation = %(class)s()"""%{'class':classname,'module':module}
else:
exec """
operation = %(class)s()"""%{'class':classname}
operation.set_id(operation_record['OPE_ID'])
db = Database()
stmnt = "SELECT OPD_KEY, OPD_VALUE, OPD_TYPE FROM OPERATIONDATA WHERE OPD_OPE_ID = ? ;"
cur = db.query(stmnt,(operation_record["OPE_ID"],))
for row in cur.fetchallmap():
val = row["OPD_VALUE"]
exec """val = %s(val)"""%row["OPD_TYPE"]
operation.set_value(row["OPD_KEY"], val)
return operation
@classmethod
def process_children(cls, operation):
"""
Recursively executes the workloads of Operation's Childoperations
It hereby catches exceptions in the workloads, sets the OPE_STATUS
to 2 (FAILED) if a catch occurs, then passes the exception on to the
higher layer.
If an Operation succeeds, it's entry in DB gets deleted
"""
db = Database()
stmnt = "SELECT OPE_ID, OPE_TYPE FROM OPERATIONS WHERE OPE_OPE_PARENT = ? ORDER BY OPE_INVOKED ;"
stmnt_lock = "UPDATE OPERATIONS SET OPE_STATUS = 1 WHERE OPE_ID = ? ;"
cur = db.query(stmnt,(operation.get_id(),))
for row in cur.fetchallmap():
child_operation = cls.restore_operation(row)
db.query(stmnt_lock,(child_operation.get_id(),),commit=True)
try:
cls.process_children(child_operation)
child_operation.do_workload()
except Exception,e:
stmnt_err = "UPDATE OPERATIONS SET OPE_STATUS = 2 WHERE OPE_ID = ? ;"
db.query(stmnt_err,(int(row["OPE_ID"]),),commit=True)
#TODO GENERATE ERROR IN LOG
raise e
stmnt_delete = "DELETE FROM OPERATIONS WHERE OPE_ID = ?;"
db.query(stmnt_delete,(child_operation.get_id(),),commit=True)
@classmethod
def process_next(cls):
"""
Sets the status of the next toplevel operation to 1 (ACTIVE)
Fetches the next toplevel-operation from the database, applies a FILESYSTEMLOCK!
Which is /tmp/scv_operating.lck !!!
"""
db = Database()
configuration = Configuration()
if os.path.exists(configuration.get_entry("core.webpath")+"/scv_operating.lck"):
return False
lockfile = open(configuration.get_entry("core.webpath")+"/scv_operating.lck","w")
lockfile.close()
stmnt_lock = "UPDATE OPERATIONS SET OPE_STATUS = 1 \
WHERE OPE_ID IN ( \
SELECT OPE_ID FROM OPERATIONS \
WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 0 \
AND OPE_INVOKED = ( \
SELECT MIN(OPE_INVOKED) FROM OPERATIONS \
WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 0) \
) ;"
stmnt = "SELECT OPE_ID, OPE_TYPE FROM OPERATIONS WHERE OPE_OPE_PARENT IS NULL AND OPE_STATUS = 1 ;"
db.query(stmnt_lock,commit=True)
cur = db.query(stmnt)
res = cur.fetchallmap()
if len(res) > 0:
operation = cls.restore_operation(res[0])
try:
cls.process_children(operation)
operation.do_workload()
except Exception, e:
stmnt_err = "UPDATE OPERATIONS SET OPE_STATUS = 2 WHERE OPE_ID = ? ;"
db.query(stmnt_err,(operation.get_id(),),commit=True)
error = StringIO()
print_exc(None,error)
Core().log(error.getvalue())
ret = True
else:
ret = False
stmnt_delete = "DELETE FROM OPERATIONS WHERE OPE_STATUS = 1 ;"
db.query(stmnt_delete,commit=True)
db.commit()
try:
os.unlink(configuration.get_entry("core.webpath")+"/scv_operating.lck")
except OSError,e :
raise OperationException(OperationException.get_msg(0))
return ret
@classmethod
def <API key>(cls, operation_types=None):
"""
Returns all Operations in an associative array.
The array's indices are the operationIDs
The Objects contain all information about the operations,
including the Data
"""
db = Database()
#TODO CHECK HOW LISTS ARE HANDLED IN FDB
if operation_types is not None and type(operation_types) == list:
stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE, OPE_STATUS FROM OPERATIONS WHERE OPE_TYPE IN (?) ORDER BY OPE_INVOKED ;"
cur = db.query(stmnt,(operation_types))
else:
stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE, OPE_STATUS FROM OPERATIONS ORDER BY OPE_INVOKED ;"
cur = db.query(stmnt)
ret = {}
for row in cur.fetchallmap():
operation = cls.restore_operation(row)
custom_values = operation.get_values()
ret[row["OPE_ID"]] = {"id":row["OPE_ID"],
"parent":row["OPE_OPE_PARENT"],
"invoked":str(row["OPE_INVOKED"]),
"type":row["OPE_TYPE"],
"status":row["OPE_STATUS"],
"data":custom_values}
return ret
def get_values(self):
"""
trivial
"""
return self._values
def get_value(self,key):
"""
trivial
"""
return self._values(key)
def set_value(self,key,value):
"""
trivial
"""
self._values[key] = value
def set_parent(self,parent_id):
"""
trivial
"""
self._parent = parent_id
def get_parent(self):
"""
trivial
"""
return self._parent
def set_db_id(self):
"""
Get a new Operation Id from the Database and assign it to this
Operation if this Operation's id is null. Afterwards return the
new Id
"""
if self._id is None:
self._id = Database().get_seq_next('OPE_GEN')
return self._id
def set_id(self, nr):
"""
trivial
"""
self._id = nr
def get_id(self):
"""
trivial
"""
return self._id
def store(self):
"""
Stores this Operation to database.
Also saves every user defined value in $_values as
long as it is a valid type
"""
db = Database()
self.set_db_id()
stmnt = "UPDATE OR INSERT INTO OPERATIONS (OPE_ID, OPE_OPE_PARENT, OPE_INVOKED, OPE_TYPE) \
VALUES (?,?,CURRENT_TIMESTAMP,?) MATCHING (OPE_ID);"
db.query(stmnt,(self._id,self._parent,self.__class__.__name__),commit=True)
stmnt = "UPDATE OR INSERT INTO OPERATIONDATA (OPD_OPE_ID, OPD_KEY, OPD_VALUE, OPD_TYPE) \
VALUES ( ?, ?, ?, ?) MATCHING(OPD_OPE_ID,OPD_KEY);"
for key, value in self._values.items():
typ = str(type(value)).replace("<type '","",1).replace("'>","",1)
if typ not in Operation.VALID_STORAGE_TYPES:
continue
db.query(stmnt,(self._id,key,value,typ),commit=True)
def do_workload(self):
"""
This method must be overridden by inheriting classes.
The code inside this method will be executed when the
Operation is processed by Operation.processNext or
Operation.processChild
"""
pass
#MODULEINVOLVED
class ModuleOperation(Operation):
"""
Abstracts Operations that have to do with modules
"""
def __init__(self):
"""
trivial
"""
Operation.__init__(self)
def set_values(self,module):
"""
Sets this operations values from module metadata
"""
if type(module) == dict:
self.set_value("name",module["name"])
self.set_value("hrname",module["hrname"])
self.set_value("version_major",module["version_major"])
self.set_value("version_minor",module["version_minor"])
self.set_value("revision",module["revision"])
if module.has_key("signature"):
self.set_value("signature",module["signature"])
elif module.__class__.__name__ == "Module":
pass #TODO IMPLEMENT / DISCUSS AFTER IMPLEMENTING MODULE-SUBSYSTEM
def get_meta(self):
"""
trivial
"""
return self._values
@classmethod
def <API key>(cls):
"""
Returns an Array of <API key> that are
currently listedin the queue
"""
db = Database()
stmnt = "SELECT OPE_ID, OPE_OPE_PARENT, OPE_TYPE FROM OPERATIONS \
WHERE OPE_TYPE = '<API key>' \
or OPE_TYPE = '<API key>' ;"
cur = db.query(stmnt);
ret = []
for row in cur.fetchallmap():
ret.append(Operation.restore_operation(row).get_meta())
return ret
def optimize_queue(self):
"""
abtract
"""
pass
#MODULEINVOLVED
class <API key>(ModuleOperation):
"""
Manages the process to install a module to this server
"""
def __init__(self):
"""
trivial
"""
ModuleOperation.__init__(self)
def do_workload(self):
"""
tell the module manager to install a specific module.
"""
Module.install_module(self.get_meta())
def optimize_queue(self):
"""
optimizes the queue.
"""
pass #TODO Implement
#MODULEINVOLVED
class <API key>(ModuleOperation):
"""
Manages the process to uninstall a module to this server
"""
def __init__(self):
"""
trivial
"""
ModuleOperation.__init__(self)
def do_workload(self):
"""
tell the module manager to install a specific module.
"""
module = Module.get_module_by_name(self._values["name"])
module_manager.uninstall_module(module)
def optimize_queue(self):
"""
optimizes the queue.
"""
pass #TODO Implement
#MODULEINVOLVED
class <API key>(ModuleOperation):
"""
Manages the process to uninstall a module to this server
"""
def __init__(self):
"""
trivial
"""
ModuleOperation.__init__(self)
def do_workload(self):
"""
tell the module manager to install a specific module.
"""
module = Module.get_module_by_name(self._values["name"])
module_manager.update_module(module)
def optimize_queue(self):
"""
optimizes the queue.
"""
pass #TODO Implement
class FailOperation(Operation):
"""
For unittest purposes: An Operation that always fails
"""
def __init__(self):
"""
trivial
"""
Operation.__init__(self)
def do_workload(self):
"""
simply fail
"""
raise Exception("Failoperation failed")
class TestOperation(Operation):
"""
For unittest purposes: An Operation that always succeds
"""
def __init__(self):
"""
trivial
"""
Operation.__init__(self)
def do_workload(self):
"""
simply succeed
"""
pass
class OperationDaemon(Daemon):
"""
This is the deamon that runs to actually execute the scheduled operations
"""
def __init__(self, pidfile):
"""
Initialize the deamon
"""
Daemon.__init__(self,pidfile)
def stop(self):
configuration = Configuration()
if os.path.exists(configuration.get_entry("core.webpath")+"/scv_operating.lck"):
os.remove(configuration.get_entry("core.webpath")+"/scv_operating.lck")
Daemon.stop(self)
def run(self):
"""
Do work if there is work to do, otherwise check every two seconds for new work.
"""
while True:
while Operation.process_next():
pass
sleep(2)
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http:
<html xmlns="http:
<head>
<title>ActiveJob::Execution</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="../../css/reset.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/main.css" type="text/css" media="screen" />
<link rel="stylesheet" href="../../css/github.css" type="text/css" media="screen" />
<script src="../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
<script src="../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script>
<script src="../../js/main.js" type="text/javascript" charset="utf-8"></script>
<script src="../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div class="banner">
<span>Ruby on Rails 4.2.3</span><br />
<h1>
<span class="type">Module</span>
ActiveJob::Execution
</h1>
<ul class="files">
<li><a href="../../files/__/__/__/__/usr/local/lib64/ruby/gems/2_1_0/gems/activejob-4_2_3/lib/active_job/execution_rb.html">/usr/local/lib64/ruby/gems/2.1.0/gems/activejob-4.2.3/lib/active_job/execution.rb</a></li>
</ul>
</div>
<div id="bodyContent">
<div id="content">
<!-- Namespace -->
<div class="sectiontitle">Namespace</div>
<ul>
<li>
<span class="type">MODULE</span>
<a href="Execution/ClassMethods.html">ActiveJob::Execution::ClassMethods</a>
</li>
</ul>
<!-- Method ref -->
<div class="sectiontitle">Methods</div>
<dl class="methods">
<dt>P</dt>
<dd>
<ul>
<li>
<a href="#method-i-perform">perform</a>,
</li>
<li>
<a href="#<API key>">perform_now</a>
</li>
</ul>
</dd>
</dl>
<!-- Includes -->
<div class="sectiontitle">Included Modules</div>
<ul>
<li>
<a href="../ActiveSupport/Rescuable.html">
ActiveSupport::Rescuable
</a>
</li>
</ul>
<!-- Methods -->
<div class="sectiontitle">Instance Public methods</div>
<div class="method">
<div class="title method-title" id="method-i-perform">
<b>perform</b>(*)
<a href="../../classes/ActiveJob/Execution.html#method-i-perform" name="method-i-perform" class="permalink">Link</a>
</div>
<div class="description">
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('<API key>')" id="<API key>">show</a>
</p>
<div id="<API key>" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/lib64/ruby/gems/2.1.0/gems/activejob-4.2.3/lib/active_job/execution.rb, line 38</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">perform</span>(<span class="ruby-operator">*</span>)
<span class="ruby-identifier">fail</span> <span class="ruby-constant">NotImplementedError</span>
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
<div class="method">
<div class="title method-title" id="<API key>">
<b>perform_now</b>()
<a href="../../classes/ActiveJob/Execution.html#<API key>" name="<API key>" class="permalink">Link</a>
</div>
<div class="description">
<p>Performs the job immediately. The job is not sent to the queueing adapter
but directly executed by blocking the execution of others until it's
finished.</p>
<pre><code>MyJob.new(*args).perform_now
</code></pre>
</div>
<div class="sourcecode">
<p class="source-link">
Source:
<a href="javascript:toggleSource('<API key>')" id="<API key>">show</a>
</p>
<div id="<API key>" class="dyn-source">
<pre><span class="ruby-comment"># File ../../../../usr/local/lib64/ruby/gems/2.1.0/gems/activejob-4.2.3/lib/active_job/execution.rb, line 29</span>
<span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">perform_now</span>
<span class="ruby-identifier"><API key></span>
<span class="ruby-identifier">run_callbacks</span> <span class="ruby-value">:perform</span> <span class="ruby-keyword">do</span>
<span class="ruby-identifier">perform</span>(<span class="ruby-operator">*</span><span class="ruby-identifier">arguments</span>)
<span class="ruby-keyword">end</span>
<span class="ruby-keyword">rescue</span> =<span class="ruby-operator">></span> <span class="ruby-identifier">exception</span>
<span class="ruby-identifier">rescue_with_handler</span>(<span class="ruby-identifier">exception</span>) <span class="ruby-operator">||</span> <span class="ruby-identifier">raise</span>(<span class="ruby-identifier">exception</span>)
<span class="ruby-keyword">end</span></pre>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
|
package lodo
import java.util.UUID
import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import Helper._
object NotebookSelector {
case class Props(b: Dashboard.Backend, itemMap: ItemMap,
selectedNotebook: Option[UUID],
isAdding: Boolean,
isCompleteHidden: Boolean,
isQuickAdd: Boolean)
case class State(isNotebookAdding: Boolean = false,
addText: String = "",
isDragOver: Boolean = false)
class Backend(t: BackendScope[Props, State]) {
def onClickAdd() = {
t.modState(s => s.copy(isNotebookAdding = !s.isNotebookAdding))
}
def onFocus(e: ReactEventI) =
e.currentTarget.select()
def onEdit(e: ReactEventI) =
t.modState(s => s.copy(addText = e.currentTarget.value))
def onSubmit(e: ReactEvent) = {
e.preventDefault()
t.modState(s => {
t.props.b.<API key>(AddOp(Item(UUID.randomUUID, None, time(), s.addText)))
s.copy(isNotebookAdding = t.props.isQuickAdd, addText = "")
})
}
def onDragEnter(e: ReactDragEvent) = {
e.stopPropagation()
e.preventDefault()
t.modState(_.copy(isDragOver = true))
}
def onDragLeave(e: ReactDragEvent) = {
e.stopPropagation()
e.preventDefault()
t.modState(_.copy(isDragOver = false))
}
def onDragOver(e: ReactDragEvent) = {
e.stopPropagation()
e.preventDefault()
}
def onDrop(e: ReactDragEvent): Unit = {
e.stopPropagation()
e.preventDefault()
t.modState(_.copy(isDragOver = false))
val src = UUID.fromString(e.dataTransfer.getData("lodo"))
val item = t.props.itemMap(Some(src))
item.map(item => {
t.props.b.<API key>(MoveOp(item, None, time()), item.id)
})
}
}
val notebookSelector = ReactComponentB[Props]("NotebookSelector")
.initialState(State())
.backend(new Backend(_))
.render((P, S, B) =>
<.ul(^.cls := "nav nav-sidebar",
P.itemMap.notebooks()
.zipWithIndex
.map { case (c, i) =>
Notebook(Notebook.Props(P.b, P.selectedNotebook, P.isAdding, P.itemMap, c, i))
},
if (S.isNotebookAdding)
<.li(
<.a(^.href := "
<.form(^.onSubmit ==> B.onSubmit,
<.input(^.onFocus ==> B.onFocus, ^.autoFocus := true,
^.onChange ==> B.onEdit)
)
)
)
else
<.li(
^.classSet(("dragover", S.isDragOver)),
^.onDragEnter ==> B.onDragEnter,
^.onDragLeave ==> B.onDragLeave,
^.onDragOver ==> B.onDragOver,
^.onDrop ==> B.onDrop,
^.title := "Create new notebook",
<.a(^.href := "#", ^.onClick --> B.onClickAdd(),
<.span(^.cls := "glyphicon glyphicon-plus"),
<.span(^.classSet(("draghidden", !S.isDragOver)),
" Create notebook from item"
)
)
)
)
)
.build
def apply(props: Props) = notebookSelector(props)
}
|
<?php
namespace mgate\PersonneBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use JMS\SecurityExtraBundle\Annotation\Secure;
use mgate\PersonneBundle\Entity\Poste;
use mgate\PersonneBundle\Entity\Personne;
use mgate\PersonneBundle\Form\PosteType;
class PosteController extends Controller
{
/**
* @Secure(roles="ROLE_SUIVEUR")
*/
public function ajouterAction()
{
$em = $this->getDoctrine()->getManager();
$poste = new Poste;
$form = $this->createForm(new PosteType, $poste);
if( $this->get('request')->getMethod() == 'POST' )
{
$form->bind($this->get('request'));
if( $form->isValid() )
{
$em->persist($poste);
$em->flush();
return $this->redirect( $this->generateUrl('<API key>', array('id' => $poste->getId())) );
}
}
return $this->render('mgatePersonneBundle:Poste:ajouter.html.twig', array(
'form' => $form->createView(),
));
}
/**
* Affiche la liste des pages et permet aux admin d'ajouter un poste
* @Secure(roles="ROLE_MEMBRE")
*/
public function indexAction($page)
{
$em = $this->getDoctrine()->getManager();
$entities = $em->getRepository('mgatePersonneBundle:Poste')->findAll();
$security = $this->get('security.context');
$token = $security->getToken();
$user = $token->getUser();
if($security->isGranted('ROLE_ADMIN')){
$poste = new Poste;
$form = $this->createForm(new PosteType, $poste);
return $this->render('mgatePersonneBundle:Poste:index.html.twig', array(
'postes' => $entities,
'form' => $form->createView()
));
}
return $this->render('mgatePersonneBundle:Poste:index.html.twig', array(
'postes' => $entities,
));
}
/**
* @Secure(roles="ROLE_MEMBRE")
*/
public function voirAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('mgatePersonneBundle:Poste')->find($id);
if (!$entity) {
throw $this-><API key>('Le poste demandé n\'existe pas !');
}
//$deleteForm = $this->createDeleteForm($id);
return $this->render('mgatePersonneBundle:Poste:voir.html.twig', array(
'poste' => $entity,
/*'delete_form' => $deleteForm->createView(), */));
}
/**
* @Secure(roles="ROLE_SUIVEUR")
*/
public function modifierAction($id)
{
$em = $this->getDoctrine()->getManager();
if( ! $poste = $em->getRepository('mgate\PersonneBundle\Entity\Poste')->find($id) )
throw $this-><API key>('Le poste demandé n\'existe pas !');
$form = $this->createForm(new PosteType, $poste);
$deleteForm = $this->createDeleteForm($id);
if( $this->get('request')->getMethod() == 'POST' )
{
$form->bind($this->get('request'));
if( $form->isValid() )
{
$em->persist($poste);
$em->flush();
return $this->redirect( $this->generateUrl('<API key>', array('id' => $poste->getId())) );
}
}
return $this->render('mgatePersonneBundle:Poste:modifier.html.twig', array(
'form' => $form->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* @Secure(roles="ROLE_SUIVEUR")
*/
public function deleteAction($id)
{
$form = $this->createDeleteForm($id);
$request = $this->getRequest();
$form->bind($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
if( ! $entity = $em->getRepository('mgate\PersonneBundle\Entity\Poste')->find($id) )
throw $this-><API key>('Le poste demandé n\'existe pas !');
foreach($entity->getMembres() as $membre)
$membre->setPoste(null);
//$entity->setMembres(null);
$em->remove($entity);
$em->flush();
}
return $this->redirect($this->generateUrl('<API key>'));
}
private function createDeleteForm($id)
{
return $this->createFormBuilder(array('id' => $id))
->add('id', 'hidden')
->getForm()
;
}
}
|
// This file is part of the go-ethereum library.
// The go-ethereum library is free software: you can redistribute it and/or modify
// (at your option) any later version.
// The go-ethereum library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
package state
import (
"math/big"
"github.com/ethereumproject/go-ethereum/common"
)
type journalEntry interface {
undo(*StateDB)
}
type journal []journalEntry
type (
// Changes to the account trie.
createObjectChange struct {
account *common.Address
}
resetObjectChange struct {
prev *StateObject
}
suicideChange struct {
account *common.Address
prev bool // whether account had already suicided
prevbalance *big.Int
}
// Changes to individual accounts.
balanceChange struct {
account *common.Address
prev *big.Int
}
nonceChange struct {
account *common.Address
prev uint64
}
storageChange struct {
account *common.Address
key, prevalue common.Hash
}
codeChange struct {
account *common.Address
prevcode, prevhash []byte
}
// Changes to other state values.
refundChange struct {
prev *big.Int
}
addLogChange struct {
txhash common.Hash
}
)
func (ch createObjectChange) undo(s *StateDB) {
s.GetStateObject(*ch.account).deleted = true
delete(s.stateObjects, *ch.account)
delete(s.stateObjectsDirty, *ch.account)
}
func (ch resetObjectChange) undo(s *StateDB) {
s.setStateObject(ch.prev)
}
func (ch suicideChange) undo(s *StateDB) {
obj := s.GetStateObject(*ch.account)
if obj != nil {
obj.suicided = ch.prev
obj.setBalance(ch.prevbalance)
}
}
func (ch balanceChange) undo(s *StateDB) {
s.GetStateObject(*ch.account).setBalance(ch.prev)
}
func (ch nonceChange) undo(s *StateDB) {
s.GetStateObject(*ch.account).setNonce(ch.prev)
}
func (ch codeChange) undo(s *StateDB) {
s.GetStateObject(*ch.account).setCode(common.BytesToHash(ch.prevhash), ch.prevcode)
}
func (ch storageChange) undo(s *StateDB) {
s.GetStateObject(*ch.account).setState(ch.key, ch.prevalue)
}
func (ch refundChange) undo(s *StateDB) {
s.refund = ch.prev
}
func (ch addLogChange) undo(s *StateDB) {
logs := s.logs[ch.txhash]
if len(logs) == 1 {
delete(s.logs, ch.txhash)
} else {
s.logs[ch.txhash] = logs[:len(logs)-1]
}
}
|
using NetEOC.Auth.Data;
using NetEOC.Auth.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace NetEOC.Auth.Services
{
public class OrganizationService
{
public <API key> <API key> { get; set; }
public <API key> <API key> { get; set; }
public <API key> <API key> { get; set; }
public OrganizationService()
{
<API key> = new <API key>();
<API key> = new <API key>();
<API key> = new <API key>();
}
public async Task<Organization> Create(Organization organization)
{
if (!<API key>(organization)) throw new ArgumentException("Invalid Organization!");
if(organization.Id != Guid.Empty)
{
Organization existing = await Update(organization);
if (existing != null) return existing;
}
return await <API key>.Create(organization);
}
public async Task<Organization> GetById(Guid id)
{
return await <API key>.Get(id);
}
public async Task<Organization[]> GetByOwnerId(Guid ownerId)
{
return await <API key>.GetByOwnerId(ownerId);
}
public async Task<Organization> Update(Organization organization)
{
if (!<API key>(organization)) throw new ArgumentException("Invalid Organization!");
if (organization.Id == Guid.Empty) throw new ArgumentException("Organization has no id!");
//merge organization
Organization existing = await GetById(organization.Id);
if (existing == null) return null;
if (!string.IsNullOrWhiteSpace(organization.Name)) existing.Name = organization.Name;
if (!string.IsNullOrWhiteSpace(organization.Description)) existing.Description = organization.Description;
if (organization.Data != null)
{
foreach (var kv in organization.Data)
{
if (existing.Data.ContainsKey(kv.Key))
{
existing.Data[kv.Key] = kv.Value;
}
else
{
existing.Data.Add(kv.Key, kv.Value);
}
}
}
return await <API key>.Update(existing);
}
public async Task<bool> Delete(Guid organizationId)
{
return await <API key>.Delete(organizationId);
}
public async Task<Guid[]> <API key>(Guid organizationId)
{
return (await <API key>.GetByOrganizationId(organizationId)).Select(x => x.UserId).ToArray();
}
public async Task<Guid[]> <API key>(Guid organizationId)
{
return (await <API key>.GetByOrganizationId(organizationId)).Select(x => x.UserId).ToArray();
}
public async Task<OrganizationMember> <API key>(Guid organizationId, Guid userId)
{
OrganizationMember[] memberships = await <API key>.GetByUserId(userId);
OrganizationMember membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId);
if (membership == null)
{
membership = new OrganizationMember { OrganizationId = organizationId, UserId = userId };
membership = await <API key>.Create(membership);
}
return membership;
}
public async Task<bool> <API key>(Guid organizationId, Guid userId)
{
OrganizationMember[] memberships = await <API key>.GetByUserId(userId);
OrganizationMember membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId);
bool success = false;
if (membership != null)
{
success = await <API key>.Delete(membership.Id);
}
return success;
}
public async Task<OrganizationAdmin> <API key>(Guid organizationId, Guid userId)
{
OrganizationAdmin[] memberships = await <API key>.GetByUserId(userId);
OrganizationAdmin membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId);
if (membership == null)
{
membership = new OrganizationAdmin { OrganizationId = organizationId, UserId = userId };
membership = await <API key>.Create(membership);
}
return membership;
}
public async Task<bool> <API key>(Guid organizationId, Guid userId)
{
OrganizationAdmin[] memberships = await <API key>.GetByUserId(userId);
OrganizationAdmin membership = memberships.FirstOrDefault(x => x.OrganizationId == organizationId);
bool success = false;
if (membership != null)
{
success = await <API key>.Delete(membership.Id);
}
return success;
}
private bool <API key>(Organization organization)
{
if (organization.OwnerId == Guid.Empty) throw new ArgumentException("Organization must have an owner!");
if (string.IsNullOrWhiteSpace(organization.Name)) throw new ArgumentException("Organization must have a name!");
return true;
}
}
}
|
.form-field { overflow: hidden; }
/* Order of the field attributes */
.form-wrap.form-builder .frmb .form-elements { display: flex; flex-direction: column; }
.form-wrap.form-builder .frmb .form-field .form-group { order: 100; }
.required-wrap { order: 0 !important; }
.name-wrap { order: 1 !important; }
.label-wrap { order: 2 !important; }
.subtype-wrap { order: 3 !important; }
.separator-wrap {
order: 50 !important;
margin-top: 10px;
border-top: 1px dashed grey;
padding-top: 10px;
}
.access-wrap { order: 110 !important; }
.separator-field label, .separator-field .copy-button, .separator-field .toggle-form { display: none !important; }
.separator-wrap label, .separator-wrap .input-wrap { display: none !important; }
.separator-wrap {
order: 50 !important;
margin-top: 10px;
border-top: 1px dashed grey;
padding-top: 10px;
}
.form-wrap.form-builder .frmb .form-elements .input-wrap { width: 70%; }
.form-wrap.form-builder .frmb .form-elements .false-label:first-child, .form-wrap.form-builder .frmb .form-elements label:first-child { width: 25%; }
.titre-field .required-wrap,
.titre-field .name-wrap {
display: none !important;
}
.map-field .label-wrap,
.map-field .value-wrap,
.map-field .name-wrap {
display: none !important;
}
.date-field .value-wrap { display: none !important; }
.image-field .value-wrap, .image-field .name-wrap { display: none !important; }
.image-field .name2-wrap { order: 1 !important; }
.select-field .field-options, .radio-group-field .field-options, .<API key> .field-options { display: none !important; }
.form-wrap.form-builder .frmb .form-elements .false-label:first-child, .form-wrap.form-builder .frmb .form-elements label:first-child {
white-space: normal;
text-overflow: initial;
}
.form-wrap.form-builder .form-elements .form-group > label {
white-space: normal !important;
}
.listId-wrap, .formId-wrap { display: none !important; }
.textarea-field .maxlength-wrap,
.textarea-field .subtype-wrap {
display: none !important;
}
.file-field .subtype-wrap { display: none !important; }
.<API key> .required-wrap,
.<API key> .name-wrap,
.<API key> .value-wrap {
display: none !important;
}
.labelhtml-field .required-wrap,
.labelhtml-field .name-wrap,
.labelhtml-field .value-wrap,
.labelhtml-field .label-wrap {
display: none !important;
}
.<API key> .required-wrap,
.<API key> .name-wrap,
.<API key> .value-wrap,
.<API key> .label-wrap {
display: none !important;
}
.acls-field .required-wrap,
.acls-field .name-wrap,
.acls-field .value-wrap,
.acls-field .label-wrap {
display: none !important;
}
.metadatas-field .required-wrap,
.metadatas-field .name-wrap,
.metadatas-field .value-wrap,
.metadatas-field .label-wrap {
display: none !important;
}
.<API key> .required-wrap,
.<API key> .name-wrap,
.<API key> .value-wrap,
.<API key> .label-wrap {
display: none !important;
}
.bookmarklet-field .required-wrap {
display: none !important;
}
.custom-field .required-wrap,
.custom-field .name-wrap,
.custom-field .value-wrap,
.custom-field .label-wrap {
display: none !important;
}
xmp { overflow: auto; }
/* Redefine .fa class when icon- class exists, because redefined by form-builder.min.js*/
.fa[class*=" icon-"]::before, .fa[class^="icon-"]::before {
font-family: inherit;
font-weight: inherit;
font-style: inherit;
margin: 0;
font-variant: inherit;
line-height: inherit;
-<API key>: antialiased;
-<API key>: grayscale;
width: inherit;
text-transform: inherit;
}
/* Make the list of fields smaller */
.form-wrap.form-builder .frmb-control li {
padding: 5px 10px;
font-size: 15px;
}
.form-wrap.form-builder .frmb li {
padding: 5px 10px;
}
.form-wrap.form-builder .frmb li:first-child {
padding-top: 10px;
}
.form-wrap.form-builder .frmb .field-label {
font-weight: bold;
}
.form-wrap.form-builder .frmb .prev-holder {
font-size: 15px;
}
.form-wrap.form-builder .frmb .prev-holder input:not([type=file]),
.form-wrap.form-builder .frmb .prev-holder textarea {
border-radius: 3px;
border: 1px solid #ccc;
box-shadow: none;
}
|
package com.wirecard.acqp.two;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
@Ignore
@SuppressWarnings("javadoc")
public class <API key> {
/**
* The number of threads to use in this test.
*/
private static final int NUM_THREADS = 12;
/**
* Flag to indicate the concurrent test has failed.
*/
private boolean failed;
@Test
public void testConcurrently() {
final <API key> pt = new <API key>();
final String msg = "F0F1F0F0723C440188E18008F1F9F5F4F0F5F6F2F0F0F0F0F0F0F0F0F0F0F0F1F4F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F5F0F5F0F1F2F0F1F3F0F3F0F9F5F8F9F2F7F8F1F3F0F3F0F9F0F1F2F0F1F5F1F1F5F4F1F1F8F1F2F0F6F0F1F3F4F0F1F0F6F2F0F0F3F5F0F0F1F2F0F1F4F5F4F9F3F5F482F0F0F0F0F0F0F1D9C5E3D382F0F0F0F0F0F0F1404040C3C3C240E3F140E28899A340D581948540404040404040C3C3C240E3F140E28899A340D340D7C1D5F0F6F0E3F6F1F0F5F0F0F0F0F1F9F2F0F35C5C5CF4F2F0F7F0F1F0F3F2F1F2F4F3F2F891C982A884F6E38581889492C1C2C5C1C1C1C699D894A8E7A694F07EF9F7F8F0F2F1F1F0F2F5F1F0F0F0F0F6F0F0F0F5F9F1D7C1D5F1F2";
Runnable runnable = new Runnable() {
public void run() {
try {
pt.<API key>();
pt.<API key>();
String fieldValue = MsgAccessoryImpl.readFieldValue(msg, "MASTERCARD",
"2");
assertEquals("PAN (Field 2) was not read correctly.",
"5405620000000000014", fieldValue);
String mti = MsgAccessoryImpl.readFieldValue(msg, "MASTERCARD",
"0");
assertEquals("mti was not read correctly.",
"0100", mti);
pt.<API key>();
} catch (Exception e) {
failed = true;
}
}
};
Thread[] threads = new Thread[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
threads[i] = new Thread(runnable);
}
for (int i = 0; i < NUM_THREADS; i++) {
threads[i].start();
}
for (int i = 0; i < NUM_THREADS; i++) {
try {
threads[i].join();
} catch (<API key> e) {
failed = true;
}
}
assertFalse(failed);
}
// @Test obsolet but temp
// public void <API key>()
// throws <API key>, ISOException,
// <API key>, <API key> {
// // UtilityMethodAccess after construktor
// String msg =
// "F0F1F0F0723C440188E18008F1F9F5F4F0F5F6F2F0F0F0F0F0F0F0F0F0F0F0F1F4F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F5F0F5F0F1F2F0F1F3F0F3F0F9F5F8F9F2F7F8F1F3F0F3F0F9F0F1F2F0F1F5F1F1F5F4F1F1F8F1F2F0F6F0F1F3F4F0F1F0F6F2F0F0F3F5F0F0F1F2F0F1F4F5F4F9F3F5F482F0F0F0F0F0F0F1D9C5E3D382F0F0F0F0F0F0F1404040C3C3C240E3F140E28899A340D581948540404040404040C3C3C240E3F140E28899A340D340D7C1D5F0F6F0E3F6F1F0F5F0F0F0F0F1F9F2F0F35C5C5CF4F2F0F7F0F1F0F3F2F1F2F4F3F2F891C982A884F6E38581889492C1C2C5C1C1C1C699D894A8E7A694F07EF9F7F8F0F2F1F1F0F2F5F1F0F0F0F0F6F0F0F0F5F9F1D7C1D5F1F2";
// assertEquals("PAN (Field 2) was not read correctly.",
// "5405620000000000014",
// msgAccessoryInitial.getFieldValue(msg, "MASTERCARD", "2"));
// assertEquals("PAN (Field 2) was not equal.",
// "5400041234567898",
// msgAccessoryInitial.getFieldValue("2"));
// // UtilityMethodAccess after construktor
// assertEquals("PAN (Field 2) was not read correctly.",
// "5405620000000000014",
// msgAccessoryInitial.getFieldValue(msg, "MASTERCARD", "2"));
}
|
#include "gzguts.h"
#if defined(_WIN32) && !defined(__BORLANDC__)
# define LSEEK _lseeki64
#else
#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
# define LSEEK lseek64
#else
# define LSEEK lseek
#endif
#endif
/* Local functions */
local void gz_reset OF((gz_statep));
local gzFile gz_open OF((const void *, int, const char *));
#if defined UNDER_CE
char ZLIB_INTERNAL *gz_strwinerror (error)
DWORD error;
{
static char buf[1024];
wchar_t *msgbuf;
DWORD lasterr = GetLastError();
DWORD chars = FormatMessage(<API key>
| <API key>,
NULL,
error,
0, /* Default language */
(LPVOID)&msgbuf,
0,
NULL);
if (chars != 0) {
/* If there is an \r\n appended, zap it. */
if (chars >= 2
&& msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
chars -= 2;
msgbuf[chars] = 0;
}
if (chars > sizeof (buf) - 1) {
chars = sizeof (buf) - 1;
msgbuf[chars] = 0;
}
wcstombs(buf, msgbuf, chars + 1);
LocalFree(msgbuf);
}
else {
sprintf(buf, "unknown win32 error (%ld)", error);
}
SetLastError(lasterr);
return buf;
}
#endif /* UNDER_CE */
/* Reset gzip file state */
local void gz_reset(state)
gz_statep state;
{
state->x.have = 0; /* no output data available */
if (state->mode == GZ_READ) { /* for reading ... */
state->eof = 0; /* not at end of file */
state->past = 0; /* have not read past end yet */
state->how = LOOK; /* look for gzip header */
}
else /* for writing ... */
state->reset = 0; /* no deflateReset pending */
state->seek = 0; /* no seek request pending */
gz_error(state, Z_OK, NULL); /* clear error */
state->x.pos = 0; /* no uncompressed data yet */
state->strm.avail_in = 0; /* no input data yet */
}
/* Open a gzip file either by name or file descriptor. */
local gzFile gz_open(path, fd, mode)
const void *path;
int fd;
const char *mode;
{
gz_statep state;
z_size_t len;
int oflag;
#ifdef O_CLOEXEC
int cloexec = 0;
#endif
#ifdef O_EXCL
int exclusive = 0;
#endif
/* check input */
if (path == NULL)
return NULL;
/* allocate gzFile structure to return */
state = (gz_statep)malloc(sizeof(gz_state));
if (state == NULL)
return NULL;
state->size = 0; /* no buffers allocated yet */
state->want = GZBUFSIZE; /* requested buffer size */
state->msg = NULL; /* no error message yet */
/* interpret mode */
state->mode = GZ_NONE;
state->level = <API key>;
state->strategy = Z_DEFAULT_STRATEGY;
state->direct = 0;
while (*mode) {
if (*mode >= '0' && *mode <= '9')
state->level = *mode - '0';
else
switch (*mode) {
case 'r':
state->mode = GZ_READ;
break;
#ifndef NO_GZCOMPRESS
case 'w':
state->mode = GZ_WRITE;
break;
case 'a':
state->mode = GZ_APPEND;
break;
#endif
case '+': /* can't read and write at the same time */
free(state);
return NULL;
case 'b': /* ignore -- will request binary anyway */
break;
#ifdef O_CLOEXEC
case 'e':
cloexec = 1;
break;
#endif
#ifdef O_EXCL
case 'x':
exclusive = 1;
break;
#endif
case 'f':
state->strategy = Z_FILTERED;
break;
case 'h':
state->strategy = Z_HUFFMAN_ONLY;
break;
case 'R':
state->strategy = Z_RLE;
break;
case 'F':
state->strategy = Z_FIXED;
break;
case 'T':
state->direct = 1;
break;
default: /* could consider as an error, but just ignore */
;
}
mode++;
}
/* must provide an "r", "w", or "a" */
if (state->mode == GZ_NONE) {
free(state);
return NULL;
}
/* can't force transparent read */
if (state->mode == GZ_READ) {
if (state->direct) {
free(state);
return NULL;
}
state->direct = 1; /* for empty file */
}
/* save the path name for error messages */
#ifdef WIDECHAR
if (fd == -2) {
len = wcstombs(NULL, path, 0);
if (len == (z_size_t)-1)
len = 0;
}
else
#endif
len = strlen((const char *)path);
state->path = (char *)malloc(len + 1);
if (state->path == NULL) {
free(state);
return NULL;
}
#ifdef WIDECHAR
if (fd == -2)
if (len)
wcstombs(state->path, path, len + 1);
else
*(state->path) = 0;
else
#endif
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
(void)snprintf(state->path, len + 1, "%s", (const char *)path);
#else
strcpy(state->path, path);
#endif
/* compute the flags for open() */
oflag =
#ifdef O_LARGEFILE
O_LARGEFILE |
#endif
#ifdef O_BINARY
O_BINARY |
#endif
#ifdef O_CLOEXEC
(cloexec ? O_CLOEXEC : 0) |
#endif
(state->mode == GZ_READ ?
O_RDONLY :
(O_WRONLY | O_CREAT |
#ifdef O_EXCL
(exclusive ? O_EXCL : 0) |
#endif
(state->mode == GZ_WRITE ?
O_TRUNC :
O_APPEND)));
/* open the file with the appropriate flags (or just use fd) */
state->fd = fd > -1 ? fd : (
#ifdef WIDECHAR
fd == -2 ? _wopen(path, oflag, 0666) :
#endif
open((const char *)path, oflag, 0666));
if (state->fd == -1) {
free(state->path);
free(state);
return NULL;
}
if (state->mode == GZ_APPEND) {
LSEEK(state->fd, 0, SEEK_END); /* so gzoffset() is correct */
state->mode = GZ_WRITE; /* simplify later checks */
}
/* save the current position for rewinding (only if reading) */
if (state->mode == GZ_READ) {
state->start = LSEEK(state->fd, 0, SEEK_CUR);
if (state->start == -1) state->start = 0;
}
/* initialize stream */
gz_reset(state);
/* return stream */
return (gzFile)state;
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzopen(path, mode)
const char *path;
const char *mode;
{
return gz_open(path, -1, mode);
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzopen64(path, mode)
const char *path;
const char *mode;
{
return gz_open(path, -1, mode);
}
/* -- see zlib.h -- */
gzFile ZEXPORT gzdopen(fd, mode)
int fd;
const char *mode;
{
char *path; /* identifier for error messages */
gzFile gz;
if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL)
return NULL;
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
(void)snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd);
#else
sprintf(path, "<fd:%d>", fd); /* for debugging */
#endif
gz = gz_open(path, fd, mode);
free(path);
return gz;
}
/* -- see zlib.h -- */
#ifdef WIDECHAR
gzFile ZEXPORT gzopen_w(path, mode)
const wchar_t *path;
const char *mode;
{
return gz_open(path, -2, mode);
}
#endif
/* -- see zlib.h -- */
int ZEXPORT gzbuffer(file, size)
gzFile file;
unsigned size;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* make sure we haven't already allocated memory */
if (state->size != 0)
return -1;
/* check and set requested size */
if ((size << 1) < size)
return -1; /* need to be able to double it */
if (size < 2)
size = 2; /* need two bytes to check magic header */
state->want = size;
return 0;
}
/* -- see zlib.h -- */
int ZEXPORT gzrewind(file)
gzFile file;
{
gz_statep state;
/* get internal structure */
if (file == NULL)
return -1;
state = (gz_statep)file;
/* check that we're reading and that there's no error */
if (state->mode != GZ_READ ||
(state->err != Z_OK && state->err != Z_BUF_ERROR))
return -1;
/* back up and start over */
if (LSEEK(state->fd, state->start, SEEK_SET) == -1)
return -1;
gz_reset(state);
return 0;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gzseek64(file, offset, whence)
gzFile file;
z_off64_t offset;
int whence;
{
unsigned n;
z_off64_t ret;
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* check that there's no error */
if (state->err != Z_OK && state->err != Z_BUF_ERROR)
return -1;
/* can only seek from start or relative to current position */
if (whence != SEEK_SET && whence != SEEK_CUR)
return -1;
/* normalize offset to a SEEK_CUR specification */
if (whence == SEEK_SET)
offset -= state->x.pos;
else if (state->seek)
offset += state->skip;
state->seek = 0;
/* if within raw area while reading, just go there */
if (state->mode == GZ_READ && state->how == COPY &&
state->x.pos + offset >= 0) {
ret = LSEEK(state->fd, offset - (z_off64_t)state->x.have, SEEK_CUR);
if (ret == -1)
return -1;
state->x.have = 0;
state->eof = 0;
state->past = 0;
state->seek = 0;
gz_error(state, Z_OK, NULL);
state->strm.avail_in = 0;
state->x.pos += offset;
return state->x.pos;
}
/* calculate skip amount, rewinding if needed for back seek when reading */
if (offset < 0) {
if (state->mode != GZ_READ) /* writing -- can't go backwards */
return -1;
offset += state->x.pos;
if (offset < 0) /* before start of file! */
return -1;
if (gzrewind(file) == -1) /* rewind, then skip to offset */
return -1;
}
/* if reading, skip what's in output buffer (one less gzgetc() check) */
if (state->mode == GZ_READ) {
n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ?
(unsigned)offset : state->x.have;
state->x.have -= n;
state->x.next += n;
state->x.pos += n;
offset -= n;
}
/* request skip (if not zero) */
if (offset) {
state->seek = 1;
state->skip = offset;
}
return state->x.pos + offset;
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gzseek(file, offset, whence)
gzFile file;
z_off_t offset;
int whence;
{
z_off64_t ret;
ret = gzseek64(file, (z_off64_t)offset, whence);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gztell64(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* return position */
return state->x.pos + (state->seek ? state->skip : 0);
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gztell(file)
gzFile file;
{
z_off64_t ret;
ret = gztell64(file);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
z_off64_t ZEXPORT gzoffset64(file)
gzFile file;
{
z_off64_t offset;
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return -1;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return -1;
/* compute and return effective offset in file */
offset = LSEEK(state->fd, 0, SEEK_CUR);
if (offset == -1)
return -1;
if (state->mode == GZ_READ) /* reading */
offset -= state->strm.avail_in; /* don't count buffered input */
return offset;
}
/* -- see zlib.h -- */
z_off_t ZEXPORT gzoffset(file)
gzFile file;
{
z_off64_t ret;
ret = gzoffset64(file);
return ret == (z_off_t)ret ? (z_off_t)ret : -1;
}
/* -- see zlib.h -- */
int ZEXPORT gzeof(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return 0;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return 0;
/* return end-of-file state */
return state->mode == GZ_READ ? state->past : 0;
}
/* -- see zlib.h -- */
const char * ZEXPORT gzerror(file, errnum)
gzFile file;
int *errnum;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return NULL;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return NULL;
/* return error information */
if (errnum != NULL)
*errnum = state->err;
return state->err == Z_MEM_ERROR ? "out of memory" :
(state->msg == NULL ? "" : state->msg);
}
/* -- see zlib.h -- */
void ZEXPORT gzclearerr(file)
gzFile file;
{
gz_statep state;
/* get internal structure and check integrity */
if (file == NULL)
return;
state = (gz_statep)file;
if (state->mode != GZ_READ && state->mode != GZ_WRITE)
return;
/* clear error and end-of-file */
if (state->mode == GZ_READ) {
state->eof = 0;
state->past = 0;
}
gz_error(state, Z_OK, NULL);
}
/* Create an error message in allocated memory and set state->err and
state->msg accordingly. Free any previous error message already there. Do
not try to free or allocate space if the error is Z_MEM_ERROR (out of
memory). Simply save the error message as a static string. If there is an
allocation failure constructing the error message, then convert the error to
out of memory. */
void ZLIB_INTERNAL gz_error(state, err, msg)
gz_statep state;
int err;
const char *msg;
{
/* free previously allocated message and clear */
if (state->msg != NULL) {
if (state->err != Z_MEM_ERROR)
free(state->msg);
state->msg = NULL;
}
/* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */
if (err != Z_OK && err != Z_BUF_ERROR)
state->x.have = 0;
/* set error code, and if no message, then done */
state->err = err;
if (msg == NULL)
return;
/* for an out of memory error, return literal string when requested */
if (err == Z_MEM_ERROR)
return;
/* construct error message with path */
if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) ==
NULL) {
state->err = Z_MEM_ERROR;
return;
}
#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
(void)snprintf(state->msg, strlen(state->path) + strlen(msg) + 3,
"%s%s%s", state->path, ": ", msg);
#else
strcpy(state->msg, state->path);
strcat(state->msg, ": ");
strcat(state->msg, msg);
#endif
}
#ifndef INT_MAX
/* portably return maximum value for an int (when limits.h presumed not
available) -- we need to do this to cover cases where 2's complement not
used, since C standard permits 1's complement and sign-bit representations,
otherwise we could just use ((unsigned)-1) >> 1 */
unsigned ZLIB_INTERNAL gz_intmax()
{
unsigned p, q;
p = 1;
do {
q = p;
p <<= 1;
p++;
} while (p > q);
return q >> 1;
}
#endif
|
<?php
class <API key> extends CDbMigration
{
public function up()
{
$this->execute('CREATE OR REPLACE VIEW <API key> AS SELECT
eol.id, eol.eye_id, eol.last_modified_date, <API key>, <API key>,
(SELECT name FROM <API key> oll WHERE oll.id=lens_id_left) as lens_left,
(SELECT description FROM <API key> oll WHERE oll.id=lens_id_left) as <API key>,
(SELECT acon FROM <API key> oll WHERE oll.id=lens_id_left) AS lens_acon_left,
(SELECT name FROM <API key> oll WHERE oll.id=lens_id_right) as lens_right,
(SELECT description FROM <API key> oll WHERE oll.id=lens_id_right) as <API key>,
(SELECT acon FROM <API key> oll WHERE oll.id=lens_id_right) AS lens_acon_right,
k1_left, k1_right, k2_left, k2_right, axis_k1_left, axis_k1_right, axial_length_left, axial_length_right,
snr_left, snr_right, iol_power_left, iol_power_right, <API key>, <API key>, patient_id,
k2_axis_left, k2_axis_right, delta_k_left, delta_k_right, delta_k_axis_left, delta_k_axis_right, acd_left, acd_right,
(SELECT name FROM dicom_eye_status oes WHERE oes.id=lens_id_left) as status_left,
(SELECT name FROM dicom_eye_status oes WHERE oes.id=lens_id_right) as status_right,
comments, eoc.event_id
FROM <API key> eol
JOIN <API key> eoc ON eoc.event_id=eol.event_id
JOIN <API key> eos ON eos.event_id=eol.event_id
JOIN event ev ON ev.id=eol.event_id
JOIN episode ep ON ep.id=ev.episode_id
ORDER BY eol.last_modified_date;');
}
public function down()
{
$this->execute('CREATE OR REPLACE VIEW <API key> AS SELECT
eol.id, eol.eye_id, eol.last_modified_date, <API key>, <API key>,
(SELECT name FROM <API key> oll WHERE oll.id=lens_id_left) as lens_left,
(SELECT description FROM <API key> oll WHERE oll.id=lens_id_left) as <API key>,
(SELECT acon FROM <API key> oll WHERE oll.id=lens_id_left) AS lens_acon_left,
(SELECT name FROM <API key> oll WHERE oll.id=lens_id_right) as lens_right,
(SELECT description FROM <API key> oll WHERE oll.id=lens_id_right) as <API key>,
(SELECT acon FROM <API key> oll WHERE oll.id=lens_id_right) AS lens_acon_right,
k1_left, k1_right, k2_left, k2_right, axis_k1_left, axis_k1_right, axial_length_left, axial_length_right,
snr_left, snr_right, iol_power_left, iol_power_right, <API key>, <API key>, patient_id
FROM <API key> eol
JOIN <API key> eoc ON eoc.event_id=eol.event_id
JOIN <API key> eos ON eos.event_id=eol.event_id
JOIN event ev ON ev.id=eol.event_id
JOIN episode ep ON ep.id=ev.episode_id
ORDER BY eol.last_modified_date;');
}
}
|
"""
Application file for the code snippets app.
"""
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class SnippetsConfig(AppConfig):
"""
Application configuration class for the code snippets app.
"""
name = 'apps.snippets'
verbose_name = _('Code snippets')
|
{"":{"domain":"ckan","lang":"no","plural-forms":"nplurals=2; plural=(n != 1);"},"Cancel":[null,"Avbryt"],"Edit":[null,"Rediger"],"Follow":[null,"Følg"],"Loading...":[null,"Laster..."],"URL":[null,"URL"],"Unfollow":[null,"Ikke følg"],"Upload a file":[null,"Last opp en fil"]}
|
#ifndef __SEGMENTER_H__
#define __SEGMENTER_H__
// includes
#include "media_set.h"
#include "common.h"
// constants
#define <API key> UINT_MAX
#define <API key> (100) // in case of clipping, a segment may start up to 2 frames before the segment boundary
#define <API key> (500)
#define <API key> (600000)
// enums
enum {
MDP_MAX,
MDP_MIN,
};
// typedefs
struct segmenter_conf_s;
typedef struct segmenter_conf_s segmenter_conf_t;
typedef struct {
uint32_t segment_index;
uint32_t repeat_count;
uint64_t time;
uint64_t duration;
bool_t discontinuity;
} <API key>;
typedef struct {
<API key>* items;
uint32_t item_count;
uint32_t segment_count;
uint32_t timescale;
uint32_t discontinuities;
uint64_t start_time;
uint64_t end_time;
uint64_t duration;
} segment_durations_t;
typedef struct {
request_context_t* request_context;
segmenter_conf_t* conf;
media_clip_timing_t timing;
uint32_t segment_index;
int64_t <API key>;
vod_array_part_t* key_frame_durations;
bool_t allow_last_segment;
// no discontinuity
uint64_t last_segment_end;
// discontinuity
uint32_t <API key>;
// gop
uint64_t time;
} <API key>;
typedef struct {
uint32_t min_clip_index;
uint32_t max_clip_index;
uint64_t clip_time;
media_range_t* clip_ranges;
uint32_t clip_count;
uint32_t <API key>;
} <API key>;
typedef uint32_t (*<API key>)(segmenter_conf_t* conf, uint64_t duration_millis);
typedef vod_status_t (*<API key>)(
request_context_t* request_context,
segmenter_conf_t* conf,
media_set_t* media_set,
media_sequence_t* sequence,
uint32_t media_type,
segment_durations_t* result);
struct segmenter_conf_s {
// config fields
uintptr_t segment_duration;
vod_array_t* bootstrap_segments; // array of vod_str_t
bool_t align_to_key_frames;
intptr_t <API key>;
<API key> get_segment_count; // last short / last long / last rounded
<API key> <API key>; // estimate / accurate
vod_uint_t <API key>;
uintptr_t gop_look_behind;
uintptr_t gop_look_ahead;
// derived fields
uint32_t parse_type;
uint32_t <API key>;
uint32_t* <API key>;
uint32_t <API key>;
uint32_t <API key>;
uint32_t <API key>;
uint32_t* <API key>;
uint32_t* <API key>;
uint32_t* <API key>;
};
typedef struct {
request_context_t* request_context;
vod_array_part_t* part;
int64_t* cur_pos;
int64_t offset;
} <API key>;
// init
vod_status_t <API key>(segmenter_conf_t* conf, vod_pool_t* pool);
// get segment count modes
uint32_t <API key>(segmenter_conf_t* conf, uint64_t duration_millis);
uint32_t <API key>(segmenter_conf_t* conf, uint64_t duration_millis);
uint32_t <API key>(segmenter_conf_t* conf, uint64_t duration_millis);
// key frames
int64_t <API key>(
<API key>* context,
int64_t offset,
int64_t limit);
// live window
vod_status_t <API key>(
request_context_t* request_context,
segmenter_conf_t* conf,
media_set_t* media_set,
bool_t parse_all_clips,
<API key>* clip_ranges,
uint32_t* base_clip_index);
// manifest duration
uint64_t <API key>(
segmenter_conf_t* conf,
media_set_t* media_set,
media_sequence_t* sequence,
media_sequence_t* sequences_end,
uint32_t media_type);
// get segment durations modes
vod_status_t <API key>(
request_context_t* request_context,
segmenter_conf_t* conf,
media_set_t* media_set,
media_sequence_t* sequence,
uint32_t media_type,
segment_durations_t* result);
vod_status_t <API key>(
request_context_t* request_context,
segmenter_conf_t* conf,
media_set_t* media_set,
media_sequence_t* sequence,
uint32_t media_type,
segment_durations_t* result);
// get segment index
uint32_t <API key>(
segmenter_conf_t* conf,
uint64_t time_millis);
vod_status_t <API key>(
request_context_t* request_context,
segmenter_conf_t* conf,
uint32_t <API key>,
media_clip_timing_t* timing,
uint64_t time_millis,
uint32_t* result);
// get start end ranges
vod_status_t <API key>(
<API key>* params,
<API key>* result);
vod_status_t <API key>(
<API key>* params,
<API key>* result);
vod_status_t <API key>(
<API key>* params,
<API key>* result);
#endif // __SEGMENTER_H__
|
#include <dirent.h> // for opendir, readdir, dirent
#include <fmt/format.h> // for format
#include <libxml/parser.h> // for <API key>
#include <unistd.h> // for unlink
#include <boost/algorithm/string/replace.hpp> // for replace_all
#include <boost/iterator/iterator_traits.hpp> // for iterator_value<>::type
#include <cstdio> // for sprintf
#include <cstdlib> // for atoi, exit
#include <cstring> // for strcmp, strlen, strcpy
#include <ctime> // for time, ctime, time_t
#include <deque> // for _Deque_iterator
#include <iomanip> // for operator<<, setw
#include <iostream> // for operator<<, char_traits
#include <list> // for operator==, list, _Lis...
#include <map> // for operator==, map, map<>...
#include <string> // for string, operator==
#include <string_view> // for operator==, string_view
#include <utility> // for pair
#include "area.hpp" // for Area, MapMarker, AreaZone
#include "async.hpp" // for Async, AsyncExternal
#include "catRef.hpp" // for CatRef
#include "catRefInfo.hpp" // for CatRefInfo
#include "cmd.hpp" // for cmd
#include "commands.hpp" // for getFullstrText, cmdNoAuth
#include "config.hpp" // for Config, gConfig, Deity...
#include "deityData.hpp" // for DeityData
#include "dice.hpp" // for Dice
#include "dm.hpp" // for dmAddMob, dmAddObj
#include "effects.hpp" // for EffectInfo, Effects
#include "factions.hpp" // for Faction
#include "flags.hpp" // for R_TRAINING_ROOM, R_SHO...
#include "free_crt.hpp" // for free_crt
#include "global.hpp" // for CreatureClass, Creatur...
#include "hooks.hpp" // for Hooks
#include "lasttime.hpp" // for crlasttime
#include <libxml/xmlstring.h> // for BAD_CAST
#include "location.hpp" // for Location
#include "monType.hpp" // for getHitdice, getName
#include "money.hpp" // for Money, GOLD
#include "mudObjects/areaRooms.hpp" // for AreaRoom
#include "mudObjects/creatures.hpp" // for Creature
#include "mudObjects/exits.hpp" // for Exit, getDir, getDirName
#include "mudObjects/monsters.hpp" // for Monster
#include "mudObjects/objects.hpp" // for Object
#include "mudObjects/players.hpp" // for Player
#include "mudObjects/rooms.hpp" // for BaseRoom, ExitList
#include "mudObjects/uniqueRooms.hpp" // for UniqueRoom
#include "os.hpp" // for merror
#include "paths.hpp" // for checkDirExists, AreaRoom
#include "proc.hpp" // for ChildType, ChildType::...
#include "property.hpp" // for Property
#include "proto.hpp" // for log_immort, low, needU...
#include "raceData.hpp" // for RaceData
#include "range.hpp" // for Range
#include "server.hpp" // for Server, gServer
#include "size.hpp" // for getSizeName, getSize
#include "startlocs.hpp" // for StartLoc
#include "stats.hpp" // for Stat
#include "swap.hpp" // for SwapRoom
#include "track.hpp" // for Track
#include "traps.hpp" // for TRAP_ACID, TRAP_ALARM
#include "utils.hpp" // for MAX, MIN
#include "wanderInfo.hpp" // for WanderInfo
#include "xml.hpp" // for loadRoom, loadMonster
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.