Zend\View provides the “View” layer of Zend Framework 2’s MVC system. It is a multi-tiered system allowing a variety of mechanisms for extension, substitution, and more.
The components of the view layer are as follows:
Additionally, Zend Framework 2 provides integration with the MVC via a number of event listeners in the Zend\Mvc\View namespace.
This section of the manual is designed to show you typical usage patterns of the view layer when using it within the Zend Framework 2 MVC. The assumptions are that you are using Dependency Injection and the default MVC view strategies.
The default configuration will typically work out-of-the-box. However, you will still need to select Resolver Strategies and configure them, as well as potentially indicate alternate template names for things like the site layout, 404 (not found) pages, and error pages. The code snippets below can be added to your configuration to accomplish this. We recommend adding it to a site-specific module, such as the “Application” module from the framework’s ZendSkeletonApplication, or to one of your autoloaded configurations within the config/autoload/ directory.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 | return array(
'view_manager' => array(
// The TemplateMapResolver allows you to directly map template names
// to specific templates. The following map would provide locations
// for a home page template ("application/index/index"), as well as for
// the layout ("layout/layout"), error pages ("error/index"), and
// 404 page ("error/404"), resolving them to view scripts.
'template_map' => array(
'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
'site/layout' => __DIR__ . '/../view/layout/layout.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
),
// The TemplatePathStack takes an array of directories. Directories
// are then searched in LIFO order (it's a stack) for the requested
// view script. This is a nice solution for rapid application
// development, but potentially introduces performance expense in
// production due to the number of static calls necessary.
//
// The following adds an entry pointing to the view directory
// of the current module. Make sure your keys differ between modules
// to ensure that they are not overwritten -- or simply omit the key!
'template_path_stack' => array(
'application' => __DIR__ . '/../view',
),
// This will be used as the default suffix for template scripts resolving, it defaults to 'phtml'.
'default_template_suffix' => 'php',
// Set the template name for the site's layout.
//
// By default, the MVC's default Rendering Strategy uses the
// template name "layout/layout" for the site's layout.
// Here, we tell it to use the "site/layout" template,
// which we mapped via the TemplateMapResolver above.
'layout' => 'site/layout',
// By default, the MVC registers an "exception strategy", which is
// triggered when a requested action raises an exception; it creates
// a custom view model that wraps the exception, and selects a
// template. We'll set it to "error/index".
//
// Additionally, we'll tell it that we want to display an exception
// stack trace; you'll likely want to disable this by default.
'display_exceptions' => true,
'exception_template' => 'error/index',
// Another strategy the MVC registers by default is a "route not
// found" strategy. Basically, this gets triggered if (a) no route
// matches the current request, (b) the controller specified in the
// route match cannot be found in the service locator, (c) the controller
// specified in the route match does not implement the DispatchableInterface
// interface, or (d) if a response from a controller sets the
// response status to 404.
//
// The default template used in such situations is "error", just
// like the exception strategy. Here, we tell it to use the "error/404"
// template (which we mapped via the TemplateMapResolver, above).
//
// You can opt in to inject the reason for a 404 situation; see the
// various `Application\:\:ERROR_*`_ constants for a list of values.
// Additionally, a number of 404 situations derive from exceptions
// raised during routing or dispatching. You can opt-in to display
// these.
'display_not_found_reason' => true,
'not_found_template' => 'error/404',
),
);
|
Zend\View\View consumes ViewModels, passing them to the selected renderer. Where do you create these, though?
The most explicit way is to create them in your controllers and return them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | namespace Foo\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class BazBatController extends AbstractActionController
{
public function doSomethingCrazyAction()
{
$view = new ViewModel(array(
'message' => 'Hello world',
));
$view->setTemplate('foo/baz-bat/do-something-crazy');
return $view;
}
}
|
This sets a “message” variable in the View Model, and sets the template name “foo/baz-bat/do-something-crazy”. The View Model is then returned.
In most cases, you’ll likely have a template name based on the module namespace, controller, and action. Considering that, and if you’re simply passing some variables, could this be made simpler? Definitely.
The MVC registers a couple of listeners for controllers to automate this. The first will look to see if you returned an associative array from your controller; if so, it will create a View Model and make this associative array the Variables Container; this View Model then replaces the MvcEvent‘s result. It will also look to see if you returned nothing or null; if so, it will create a View Model without any variables attached; this View Model also replaces the MvcEvent‘s result.
The second listener checks to see if the MvcEvent result is a View Model, and, if so, if it has a template associated with it. If not, it will inspect the controller matched during routing to determine the module namespace and the controller class name, and, if available, it’s “action” parameter in order to create a template name. This will be “module/controller/action”, all normalized to lowercase, dash-separated words.
As an example, the controller Foo\Controller\BazBatController with action “doSomethingCrazyAction”, would be mapped to the template foo/baz-bat/do-something-crazy. As you can see, the words “Controller” and “Action” are omitted.
In practice, that means our previous example could be re-written as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 | namespace Foo\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class BazBatController extends AbstractActionController
{
public function doSomethingCrazyAction()
{
return array(
'message' => 'Hello world',
);
}
}
|
The above method will likely work for the majority of use cases. When you need to specify a different template, explicitly create and return a View Model and specify the template manually, as in the first example.
The other use case you may have for setting explicit View Models is if you wish to nest them. In other words, you might want to render templates to be included within the main View you return.
As an example, you may want the View from an action to be one primary section that includes both an “article” and a couple of sidebars; one of the sidebars may include content from multiple Views as well:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | namespace Content\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class ArticleController extends AbstractActionController
{
public function viewAction()
{
// get the article from the persistence layer, etc...
$view = new ViewModel();
// this is not needed since it matches "module/controller/action"
$view->setTemplate('content/article/view');
$articleView = new ViewModel(array('article' => $article));
$articleView->setTemplate('content/article');
$primarySidebarView = new ViewModel();
$primarySidebarView->setTemplate('content/main-sidebar');
$secondarySidebarView = new ViewModel();
$secondarySidebarView->setTemplate('content/secondary-sidebar');
$sidebarBlockView = new ViewModel();
$sidebarBlockView->setTemplate('content/block');
$secondarySidebarView->addChild($sidebarBlockView, 'block');
$view->addChild($articleView, 'article')
->addChild($primarySidebarView, 'sidebar_primary')
->addChild($secondarySidebarView, 'sidebar_secondary');
return $view;
}
}
|
The above will create and return a View Model specifying the template “content/article/view”. When the View is rendered, it will render three child Views, the $articleView, $primarySidebarView, and $secondarySidebarView; these will be captured to the $view‘s “article”, “sidebar_primary”, and “sidebar_secondary” variables, respectively, so that when it renders, you may include that content. Additionally, the $secondarySidebarView will include an additional View Model, $sidebarBlockView, which will be captured to its “block” view variable.
To better visualize this, let’s look at what the final content might look like, with comments detailing where each nested view model is injected.
Here are the templates, rendered based on a 12-column grid:
1 2 3 4 5 6 7 8 9 | <?php // "content/article/view" template ?>

<?php echo $this->article ?>
<?php echo $this->sidebar_primary ?>
<?php echo $this->sidebar_secondary ?>

|
1 2 3 4 5 6 | <?php // "content/article" template ?>

<?php echo $this->escapeHtml('article') ?>

|
1 2 3 4 5 6 | <?php // "content/main-sidebar" template ?>

sidebar content...

|
1 2 3 4 5 6 | <?php // "content/secondary-sidebar template ?>

<?php echo $this->block ?>

|
1 2 3 4 5 6 | <?php // "content/block template ?>

block content...

|
And here is the aggregate, generated content:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |

Lorem ipsum ....

sidebar content...

block content...

|
As you can see, you can achieve very complex markup using nested Views, while simultaneously keeping the details of rendering isolated from the Request/Response lifecycle of the controller.
Most sites enforce a cohesive look-and-feel which we typically call the site’s “layout”. It includes the default stylesheets and JavaScript necessary, if any, as well as the basic markup structure into which all site content will be injected.
Within Zend Framework 2, layouts are handled via nesting of View Models (see the previous example for examples of View Model nesting). The Zend\Mvc\View\Http\ViewManager composes a View Model which acts as the “root” for nested View Models. As such, it should contain the skeleton (or layout) template for the site. All other content is then rendered and captured to view variables of this root View Model.
The ViewManager sets the layout template as “layout/layout” by default. To change this, you can add some configuration to the “view_manager” area of your configuration.
A listener on the controllers, Zend\Mvc\View\Http\InjectViewModelListener, will take a View Model returned from a controller and inject it as a child of the root (layout) View Model. By default, View Models will capture to the “content” variable of the root View Model. This means you can do the following in your layout view script:
1 2 3 4 5 6 7 8 |

<title><?php echo $this->headTitle() ?></title>

<?php echo $this->content; ?>

|
If you want to specify a different View variable for which to capture, explicitly create a view model in your controller, and set its “capture to” value:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | namespace Foo\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class BazBatController extends AbstractActionController
{
public function doSomethingCrazyAction()
{
$view = new ViewModel(array(
'message' => 'Hello world',
));
// Capture to the layout view's "article" variable
$view->setCaptureTo('article');
return $view;
}
}
|
There will be times you don’t want to render a layout. For example, you might be answering an API call which expects JSON or an XML payload, or you might be answering an XHR request that expects a partial HTML payload. The simplest way to do this is to explicitly create and return a view model from your controller, and mark it as “terminal”, which will hint to the MVC listener that normally injects the returned View Model into the layout View Model, to instead replace the layout view model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | namespace Foo\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class BazBatController extends AbstractActionController
{
public function doSomethingCrazyAction()
{
$view = new ViewModel(array(
'message' => 'Hello world',
));
// Disable layouts; `MvcEvent` will use this View Model instead
$view->setTerminal(true);
return $view;
}
}
|
When discussing nesting View Models, we detailed a nested View Model which contained an article and sidebars. Sometimes, you may want to provide additional View Models to the layout, instead of nesting in the returned layout. This may be done by using the “layout” controller plugin, which returns the root View Model. You can then call the same addChild() method on it as we did in that previous example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | namespace Content\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class ArticleController extends AbstractActionController
{
public function viewAction()
{
// get the article from the persistence layer, etc...
// Get the "layout" view model and inject a sidebar
$layout = $this->layout();
$sidebarView = new ViewModel();
$sidebarView->setTemplate('content/sidebar');
$layout->addChild($sidebarView, 'sidebar');
// Create and return a view model for the retrieved article
$view = new ViewModel(array('article' => $article));
$view->setTemplate('content/article');
return $view;
}
}
|
You could also use this technique to select a different layout, by simply calling the setTemplate() method of the layout View Model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | //In a controller
namespace Content\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class ArticleController extends AbstractActionController
{
public function viewAction()
{
// get the article from the persistence layer, etc...
// Get the "layout" view model and set an alternate template
$layout = $this->layout();
$layout->setTemplate('article/layout');
// Create and return a view model for the retrieved article
$view = new ViewModel(array('article' => $article));
$view->setTemplate('content/article');
return $view;
}
}
|
Sometimes, you may want to access the layout from within your actual view scripts when using the PhpRenderer. Reasons might include wanting to change the layout template or wanting to either access or inject layout view variables. Similar to the “layout” controller plugin, you can use the “layout” View Helper. If you provide a string argument to it, you will change the template; if you provide no arguments, the root layout View Model is returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | //In a view script
// Change the layout:
$this->layout('alternate/layout'); // OR
$this->layout()->setTemplate('alternate/layout');
// Access a layout variable.
// Since access to the base view model is relatively easy, it becomes a
// reasonable place to store things such as API keys, which other view scripts
// may need.
$layout = $this->layout();
$disqusApiKey = false;
if (isset($layout->disqusApiKey)) {
$disqusApiKey = $layout->disqusApiKey;
}
// Set a layout variable
$this->layout()->footer = $this->render('article/footer');
|
Commonly, you may want to alter the layout based on the current module. This requires (a) detecting if the controller matched in routing belongs to this module, and then (b) changing the template of the View Model.
The place to do these actions is in a listener. It should listen either to the “route” event at low (negative) priority, or on the “dispatch” event, at any priority. Typically, you will register this during the bootstrap event.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | namespace Content;
class Module
{
/**
* @param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* @return void
*/
public function onBootstrap($e)
{
// Register a dispatch event
$app = $e->getParam('application');
$app->getEventManager()->attach('dispatch', array($this, 'setLayout'));
}
/**
* @param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* @return void
*/
public function setLayout($e)
{
$matches = $e->getRouteMatch();
$controller = $matches->getParam('controller');
if (false === strpos($controller, __NAMESPACE__)) {
// not a controller from this module
return;
}
// Set the layout template
$viewModel = $e->getViewModel();
$viewModel->setTemplate('content/layout');
}
}
|
Zend\View\View does very little. Its workflow is essentially to martial a ViewEvent, and then trigger two events, “renderer” and “response”. You can attach “strategies” to these events, using the methods addRenderingStrategy() and addResponseStrategy(), respectively. A Rendering Strategy investigates the Request object (or any other criteria) in order to select a Renderer (or fail to select one). A Response Strategy determines how to populate the Response based on the result of rendering.
Zend Framework 2 ships with three Rendering and Response Strategies that you can use within your application.
By default, only the PhpRendererStrategy is registered, meaning you will need to register the other Strategies yourself if you want to use them. Additionally, it means that you will likely want to register these at higher priority to ensure they match before the PhpRendererStrategy. As an example, let’s register the JsonStrategy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | namespace Application;
class Module
{
/**
* @param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* @return void
*/
public function onBootstrap($e)
{
// Register a "render" event, at high priority (so it executes prior
// to the view attempting to render)
$app = $e->getApplication();
$app->getEventManager()->attach('render', array($this, 'registerJsonStrategy'), 100);
}
/**
* @param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* @return void
*/
public function registerJsonStrategy($e)
{
$app = $e->getTarget();
$locator = $app->getServiceManager();
$view = $locator->get('Zend\View\View');
$jsonStrategy = $locator->get('ViewJsonStrategy');
// Attach strategy, which is a listener aggregate, at high priority
$view->getEventManager()->attach($jsonStrategy, 100);
}
}
|
The above will register the JsonStrategy with the “render” event, such that it executes prior to the PhpRendererStrategy, and thus ensure that a JSON payload is created when requested.
What if you want this to happen only in specific modules, or specific controllers? One way is similar to the last example in the previous section on layouts, where we detailed changing the layout for a specific module:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | namespace Content;
class Module
{
/**
* @param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* @return void
*/
public function onBootstrap($e)
{
// Register a render event
$app = $e->getParam('application');
$app->getEventManager()->attach('render', array($this, 'registerJsonStrategy'), 100);
}
/**
* @param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* @return void
*/
public function registerJsonStrategy($e)
{
$matches = $e->getRouteMatch();
$controller = $matches->getParam('controller');
if (false === strpos($controller, __NAMESPACE__)) {
// not a controller from this module
return;
}
// Potentially, you could be even more selective at this point, and test
// for specific controller classes, and even specific actions or request
// methods.
// Set the JSON strategy when controllers from this module are selected
$app = $e->getTarget();
$locator = $app->getServiceManager();
$view = $locator->get('Zend\View\View');
$jsonStrategy = $locator->get('ViewJsonStrategy');
// Attach strategy, which is a listener aggregate, at high priority
$view->getEventManager()->attach($jsonStrategy, 100);
}
}
|
While the above examples detail using the JsonStrategy, the same could be done for the FeedStrategy.
What if you want to use a custom renderer? Or if your app might allow a combination of JSON, Atom feeds, and HTML? At this point, you’ll need to create your own custom strategies. Below is an example that appropriately loops through the HTTP Accept header, and selects the appropriate Renderer based on what is matched first.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 | namespace Content\View;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\Feed\Writer\Feed;
use Zend\View\Renderer\FeedRenderer;
use Zend\View\Renderer\JsonRenderer;
use Zend\View\Renderer\PhpRenderer;
class AcceptStrategy implements ListenerAggregateInterface
{
protected $feedRenderer;
protected $jsonRenderer;
protected $listeners = array();
protected $phpRenderer;
public function __construct(
PhpRenderer $phpRenderer,
JsonRenderer $jsonRenderer,
FeedRenderer $feedRenderer
) {
$this->phpRenderer = $phpRenderer;
$this->jsonRenderer = $jsonRenderer;
$this->feedRenderer = $feedRenderer;
}
public function attach(EventManagerInterface $events, $priority = null)
{
if (null === $priority) {
$this->listeners[] = $events->attach('renderer', array($this, 'selectRenderer'));
$this->listeners[] = $events->attach('response', array($this, 'injectResponse'));
} else {
$this->listeners[] = $events->attach('renderer', array($this, 'selectRenderer'), $priority);
$this->listeners[] = $events->attach('response', array($this, 'injectResponse'), $priority);
}
}
public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $index => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$index]);
}
}
}
/**
* @param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* @return \Zend\View\Renderer\RendererInterface
*/
public function selectRenderer($e)
{
$request = $e->getRequest();
$headers = $request->getHeaders();
// No Accept header? return PhpRenderer
if (!$headers->has('accept')) {
return $this->phpRenderer;
}
$accept = $headers->get('accept');
foreach ($accept->getPrioritized() as $mediaType) {
if (0 === strpos($mediaType, 'application/json')) {
return $this->jsonRenderer;
}
if (0 === strpos($mediaType, 'application/rss+xml')) {
$this->feedRenderer->setFeedType('rss');
return $this->feedRenderer;
}
if (0 === strpos($mediaType, 'application/atom+xml')) {
$this->feedRenderer->setFeedType('atom');
return $this->feedRenderer;
}
}
// Nothing matched; return PhpRenderer. Technically, we should probably
// return an HTTP 415 Unsupported response.
return $this->phpRenderer;
}
/**
* @param \Zend\Mvc\MvcEvent $e The MvcEvent instance
* @return void
*/
public function injectResponse($e)
{
$renderer = $e->getRenderer();
$response = $e->getResponse();
$result = $e->getResult();
if ($renderer === $this->jsonRenderer) {
// JSON Renderer; set content-type header
$headers = $response->getHeaders();
$headers->addHeaderLine('content-type', 'application/json');
} elseif ($renderer === $this->feedRenderer) {
// Feed Renderer; set content-type header, and export the feed if
// necessary
$feedType = $this->feedRenderer->getFeedType();
$headers = $response->getHeaders();
$mediatype = 'application/'
. (('rss' == $feedType) ? 'rss' : 'atom')
. '+xml';
$headers->addHeaderLine('content-type', $mediatype);
// If the $result is a feed, export it
if ($result instanceof Feed) {
$result = $result->export($feedType);
}
} elseif ($renderer !== $this->phpRenderer) {
// Not a renderer we support, therefor not our strategy. Return
return;
}
// Inject the content
$response->setContent($result);
}
}
|
This strategy would be registered just as we demonstrated registering the JsonStrategy earlier. You would also need to define DI configuration to ensure the various renderers are injected when you retrieve the strategy from the application’s locator instance.
The source code of this file is hosted on GitHub. Everyone can update and fix errors in this document with few clicks - no downloads needed.


Controls the number of lines by which a window moves when dot moves out of the window.
This read-only variable holds the last search string used by any search command. The search-string variable is preserved by the save-... functions.
Controls process termination during Emacs rundown. If non-zero, Emacs will kill processes when it exits without asking any questions. Normally, if you have processes running when Emacs exits, Emacs asks the question You have processes on the prowl, should I chase them down for you?.
Controls which windows Emacs considers when it decides to create a new window. Any window with a height that is less than split-height-threshold is a candidate for being split to create space for the new window.
Emacs will limit the number of nested MLisp calls to stack-maximum-depth calls. Raise this limit if you need run recursive or very complex MLisp.
Controls automatic stack tracing. If non-zero, Emacs will write an MLisp stack trace to the Stack trace buffer whenever an error is encountered from within an MLisp function (even inside an error-occurred).
This variable allows you to change the way that emacs interprets control keys you type.
The value of this variable is the character code to swap with ^X. Whenever emacs sees a ^X the value of swap-ctrl-x-char is substituted. And whenever the you type the key corrisponding to the value of swap-ctrl-x-char ^x is substituted.
The reason this variable was added to emacs was to make it easy to use ^X as the Windows style Cut action. Without rewritting all the existing MLisp code so that it does not use ^X as a key binding prefix.
The (default-emacs-init) function sets up ^\ (28) and ^] (29) as suitable swap candadates.
When syntax-array is true Emacs will optimise the operation of commands that depend on syntax data. However maintaining the syntax array will slow down other operations in Emacs.
The following compares commands and features with and without syntax-array:
syntax colouring
Syntax colouring is disabled if syntax-array is turned off. Turning on syntax-colouring will also turn on synatx-array for a buffer.
re-search-forward, re-search-reverse, re-query-replace-string and re-replace-string
The \S, \C, \s, \c regular expression features are only available when syntax-array is true.
backward-paren, forward-paren, backward-balanced-paren-line and forward-balanced-paren-line
When syntax-array is true these commands correctly take into account comments and strings when searching for a parenthesis. When syntax-array is false these commands uses a dead reckoning algorithm that in some situations will not find the correct parenthesis.
current-syntax-entity
When syntax-array is true this command is fast. However when syntax-array is false current-syntax-entity has to calculate the syntax by examining each character from the start of the buffer up to dot.
When syntax-colouring is true Emacs will colour the characters of a buffer depending on the syntax of those characters.
The colours are taken from the variables:
- syntax-word-rendition
- syntax-string-rendition
- syntax-comment-rendition
- syntax-keyword1-rendition
- syntax-keyword2-rendition
All dull characters are displayed in the window-graphic-rendition colour.
If syntax-colouring is false all characters are displayed in the window-graphic-rendition.
Defines the colour that will be used to draw word characters when syntax-colouring is true.
Defines the colour that will be used to draw string characters when syntax-colouring is true.
Defines the colour that will be used to draw comment characters when syntax-colouring is true.
Defines the colour that will be used to draw keyword type 1 characters when syntax-colouring is true.
Defines the colour that will be used to draw keyword type 2 characters when syntax-colouring is true.
Defines the colour that will be used to draw keyword type 3 characters when syntax-colouring is true.


Pair sought after four killed in California party shooting
Police said the men were gunned down while watching a football game on TV in Fresno.
Police are searching for two assailants who sneaked into a backyard party in California on Sunday and opened fire while a small crowd watched football on television, killing four people and injuring six others.
Fresno Police Chief Andrew Hall said the house where a group of Hmong family and friends had gathered was deliberately targeted, but the shooters fired at random once they saw men in the backyard watching football.
Mr Hall said there was no immediate word on a motive and so far there was no indication that any of the victims knew their attackers.
The men who died were ages 21 to 40, he added.
Three were found dead when emergency crews arrived. A fourth person died at a hospital. Six others were hospitalised in critical condition but are expected to survive, authorities said.
Mr Hall said police were investigating whether the shooting was connected to a recent disturbance involving some of the people at the party.
He also announced the establishment of an Asian gang task force ahead of the Hmong New Year, out of concern about the possibility of more violence.
California has the nation’s highest population of Hmong, a south-east Asian ethnic minority.
Residents complained that other shootings have happened recently in the same area and Calvin Gatison, who lives on the same street, said it had been peaceful for years, but at least two shootings happened in recent weeks.
It was at least the second fatal gun attack on Sunday in Fresno, the Fresno Bee reported.
A man in his 20s was shot to death at a home in another part of the city. Police have not said whether the incidents could be connected.
Representative Jim Costa, a Democrat who represents the Fresno area in Congress, said he was saddened to hear of another shooting “this time in my own district”.
He said in a statement that “thoughts and prayers are not enough!” and urged the Senate to take up gun-control legislation.


|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
Represents a request that is being received and the corresponding response to be sent in reply.
An InboundRequest
can be used to read in the
contents of the request and write out the response.
OutboundRequest
,
RequestDispatcher
| Method Summary | |
void |
abort()
Terminates this request, freeing all associated resources. |
InvocationConstraints |
checkConstraints(InvocationConstraints constraints)
Verifies that this request satisfies the transport layer aspects of all of the specified requirements, and returns the requirements that must be at least partially implemented by higher layers in order to fully satisfy the specified requirements. |
void |
checkPermissions()
Verifies that the current security context has all of the security permissions necessary to receive this request. |
InputStream |
getRequestInputStream()
Returns an InputStream to read the request data
from. |
OutputStream |
getResponseOutputStream()
Returns an OutputStream to write the response data
to. |
void |
populateContext(Collection context)
Populates the supplied collection with context information representing this request. |
| Method Detail |
public void checkPermissions()
This method should be used when a particular shared mechanism is used to receive requests for a variety of interested parties, each with potentially different security permissions possibly more limited than those granted to the code managing the shared mechanism, so that the managing code can verify proper access control for each party.
For example, a TCP-based InboundRequest
implementation typically implements this method by invoking the
checkAccept
method of the
current security manager (if any) with the client's host
address and TCP port. An implementation that supports
authentication typically checks that the current security
context has the necessary AuthenticationPermission
with
accept
action.
SecurityException
- if the current security context does
not have the permissions necessary to receive this requestpublic InvocationConstraints checkConstraints(InvocationConstraints constraints) throws UnsupportedConstraintException
For any given constraint, there must be a clear delineation
of which aspects (if any) must be implemented by the transport
layer. This method must not return a constraint (as a
requirement or a preference, directly or as an element of
another constraint) unless this request implements all of those
aspects. Also, this method must not return a constraint for
which all aspects must be implemented by the transport layer.
Most of the constraints in the net.jini.core.constraint
package must be fully implemented by the transport layer and
thus must not be returned by this method; the one exception is
Integrity
, for which the transport layer is responsible
for the data integrity aspect and higher layers are responsible
for the code integrity aspect.
For any ConstraintAlternatives
in the specified
constraints, this method should only return a corresponding
constraint if all of the alternatives satisfied by this request
need to be at least partially implemented by higher layers in
order to be fully satisfied.
The constraints actually in force may cause conditional
constraints to have to be satisfied. For example, if the only
requirement specified is Delegation.YES
but the client was in fact authenticated, then the client must
also have delegated to the server.
The constraints passed to this method may include constraints based on relative time.
constraints
- the constraints that must be satisfied
UnsupportedConstraintException
- if the transport layer
aspects of any of the specified requirements are not satisfied
by this request
NullPointerException
- if constraints
is
null
public void populateContext(Collection context)
context
- the context collection to populate
NullPointerException
- if context
is
null
UnsupportedOperationException
- if context
is unmodifiable and if any elements need to be addedpublic InputStream getRequestInputStream()
InputStream
to read the request data
from. The sequence of bytes produced by reading from the
returned stream will be the sequence of bytes received as the
request data. When the entirety of the request has been
successfully read, reading from the stream will indicate an
EOF.
Invoking the close
method of the returned
stream will cause any subsequent read operations on the stream
to fail with an IOException
, although it will not
terminate this request as a whole; in particular, the response
may still be subsequently written to the stream returned by the
getResponseOutputStream
method. After
close
has been invoked on both the returned stream
and the stream returned by
getResponseOutputStream
, the implementation may
free all resources associated with this request.
If this method is invoked more than once, it will always return the identical stream object that it returned the first time (although the stream may be in a different state than it was upon return from the first invocation).
public OutputStream getResponseOutputStream()
OutputStream
to write the response data
to. The sequence of bytes written to the returned stream will
be the sequence of bytes sent as the response.
After the entirety of the response has been written to the
stream, the stream's close
method must be invoked
to ensure complete delivery of the response. It is possible
that none of the data written to the returned stream will be
delivered before close
has been invoked (even if
the stream's flush
method has been invoked at any
time). Note, however, that some or all of the data written to
the stream may be delivered to (and processed by) the recipient
before the stream's close
method has been invoked.
After the stream's close
method has been
invoked, no more data may be written to the stream; writes
subsequent to a close
invocation will fail with an
IOException
.
If this method is invoked more than once, it will always return the identical stream object that it returned the first time (although the stream may be in a different state than it was upon return from the first invocation).
public void abort()
This method may be invoked at any stage of the processing of the request.
After this method has been invoked, I/O operations on the
streams returned by the getRequestInputStream
and
getResponseOutputStream
methods will fail with an
IOException
, except some operations that may
succeed because they only affect data in local I/O buffers.
If this method is invoked before the close
method has been invoked on the stream returned by
getResponseOutputStream
, there is no guarantee
that any or none of the data written to the stream so far will
be delivered; the implication of such an invocation of this
method is that the user is no longer interested in the
successful delivery of the response.
|
|||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | ||||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


Course Outline: Overview of Software Metrics, The basics of Measurement, Goal based framework for software measurement, Empirical Investigation, Measuring Internal Attributes : Size, Measuring Internal Attributes : Structure, Measuring Cost and Effort, Measuring External product attributes : Quality, Measuring Software Reliability, Object Oriented Metrics, For hands-on experiences: Students will implement different software metrics calculation related algorithms, utilize existing industry related tools for measuring software metrics and compare it with their implementations to gain concrete idea.


This area will contain the left content area.
We will populate this area with images and text.
This area will contain the right content area.
We will populate this area with links and text.


Latest Jobs
Front-end
this should display the filtered category chosen
this should display the filtered category chosen
Back-End
this should display the filtered category chosen
this should display the filtered category chosen
Full-Stack
this should display the filtered category chosen
this should display the filtered category chosen


Wind storm damage: ‘There is a tree on my garage’
Residents across the Lowveld reported power blackouts, wind damage and network failure from Barberton to Lydenburg after a massive wind storm on Saturday night.
by LowvelderPower in Yaverland was restored on Sunday morning. A number of trees fell over, one on to a Mbombela resident’s garage.
Hi-Tech Security, Nelspruit Concerned Citizens, Van Wettens and Thomson’s Towing assisted in clearing the trees.
ALSO READ: Waterval Boven train disaster commemoration slammed
The storm cut a swathe of destruction through Barberton.
A number of roofs were blown off and the electricity supply interrupted.
According to DA councillor Philip Minnaar, municipal workers were hard at work throughout the night to restore the electricity supply and remove trees which had been uprooted in the aftermath of the storm.
The affected areas included a number of areas in Emjindini Township, such as Spearville and Santa view.
As of Sunday afternoon 95 per cent of the power supply had been restored to Emjindi.
Did you suffer any damage? Share your pictures with us on Facebook.


Documentation for the Code¶
Created on Tue Apr 29 13:21:41 2014
@author: Victor Barres
Define semantic knowledge related classes for TCG1.0
-
class
concept.
CONCEPT
(name='', meaning='')[source]¶ Concept (semantico-syntactic knowledge)
- Data:
- name (STR): Name of the concept.
- meaning (STR) : Meaning it carries.
-
create
(meaning='', concept=None)[source]¶ Creates a concept from a meaning string or another concept. (TEMPORARY)
-
match
(concept1, concept2, inclusive=True)[source]¶ Check if two concept match. Case inclusive = False: concepts match only if they carry the same meaning. Case inclusive = True: If a concept is tagged with + (e.g. ANIMAL+) it will match with any of its hyponyms. Otherwise, concepts match if they carry the same meaning.
- Args:
- concept1 (CONCEPT)
- concept2 (CONCEPT)
- inclusive (BOOL)
- Notes:
- In the c++ version matching is boolean. No impact of distance on similarity.
-
class
concept.
SEM_NET
(relations=[])[source]¶ Semantic network (acting as world knowledge)
- Data:
- relation ([SEM_REL]): List of semantic relations
- Notes:
- The network is simply defined as a list of semantic relations.
-
distance
(supMean, subMean, relType=1, heuristic=False)[source]¶ Return the distance in the semantic network between a concept (subMean) and an hypernym (supMean). Return -1 if supMean is not a hypernym of subMean. If heuristic = True: -> does not guarantee to find the shortest distance.
- Args:
- supMean (str)
- subMean (str)
- relType (int)
- heuristic (bool)
-
class
concept.
SEM_REL
(aType=0, subMeaning='', supMeaning='')[source]¶ Semantic Relation
- Data:
- type (INT): UNDEFINED=0, IS_A =1
- supMeaning (STR): Hypernym of subMeaning
- subMeaning (STR): Hyponym of supMeaning
- Note:
- Only IS_A hyponymic relation is defined in c++ code.
Created on Tue Apr 22 15:48:47 2014
@author: Victor Barres
Define constructions related classes for TCG1.0
-
class
construction.
CXN
[source]¶ Grammatical construction.
- Data:
- name (str): construction name
- clss (str): construction class
- preference (int): construction preference
- template ([TP_ELEM]): all cxn template elements
- SemFrame ([TP_SEM_ELEM]): all cxn Sem-Frame elements
- SynForm ([TP_SYN_ELEM]): all cxn Syn-Form elements
-
class
construction.
GRAMMAR
[source]¶ Grammar defined as a set of constructions (“constructicon”)
- Data:
- constructions ([CXN])
- Notes:
- Corresponds to VOCAB in c++ code.
-
class
construction.
TP_SEM_ELEM
[source]¶ Template Sem-Frame element.
- Notes:
- Need to make sure that the link to synform is reciprocal.
-
class
construction.
TP_SLOT
[source]¶ SynFrame slot.
- Notes:
- Need to make sure that the link to SemFrame is reciprocal.
Created on Mon Apr 28 18:14:40 2014
@author: Victor Barres
Define schema instance related classes for TCG1.0
-
class
instance.
CXN_INST
[source]¶ Construction instance.
- Data (inherited):
- id (int): Unique id
- type (int): Type of schema
- activation (int): Current activation value of schema instance
- alive, old, fresh (bool): status flags
- Data:
- base_cxn (CXN): Base grammatical construction.
- cxn_struct (CXN_STRUCT): Structure to which the construction instance belong to.
- covers ([SEMREP_INST]): Covering SemRep instances.
- elems ([TP_SEM_ELEM]): SemFrame elements paired with covering SemRep instances.
- slots ([TP_SLOT]): Slots elements paired with covering SemRep instances.
- _matches ({INT: MATCH_INFO}): Matching dictionary. Key = Cxn instance in. Value = match info
-
compare
(aCxnInst)[source]¶ Compare current cxn instance to another cxn instance aCxnInst (CXN_INST).
- Return true if (1) the two cxn inst share the same base construction
- they cover the same SemRep instances.
-
instantiate
(cxn, semrep, act)[source]¶ Instantiate a construction schema instance for the grammatical construction cxn (CXN) based on the matching with the SemRep instances semrep ([SEMREP_INST]), with activation act (int).
-
match
(cxn1, cxn2, match_info)[source]¶ Match two construction instances. Return True when no conflict occurs.
- Args:
- cxn1 (CNX_INST): first construction instance
- cxn2 (CXN_INST): second construction instance
- match_info (MATCH_INFO): Stores match operation results.
- Algorithm:
1:If a relation already exists between instances (stored in cxn._matches), it is copied and returned.
- 2: Loop through all the SemRep instances covered by both cxn1 and cxn2
- if the two instances overlap on a SemRep instance that is not linked to a shared SemFrame elements in both instances -> CONFLICT
- Otherwise, check if cxn2 can link to a slot of cxn1 (cxn1 = parent, cxn2 = child) or vice versa.
- A link is possible if:
- SemFrame element covering the SemRep instance in the parent instance has an associated slot
- The child instance’s class matches the class restriction of this slot.
- The SemFrame element of the child instance linked to the SemRep instance is the head.
- Notes:
- The match methods returns at most 1 match option. If both cxn1 and cxn2 can be parents, it will only return the option with cxn1 as parent.
-
class
instance.
CXN_LINK
[source]¶ Hierachical link between construction instances.
- Data:
- parent (CXN_INST): parent cxn instance
- child (CXN_INST): child cxn instance
- SynFormIdx (int): index of the parent’s linking slot in its SynFrom list
-
class
instance.
CXN_STRUCT
[source]¶ Construction hiearchy structure.
- Data:
- top (CXN_INST): Top construction instance
- insts ([CNX_INST]): Construction instances forming the structure
- links ([CXN_LINK]): Hierachical construction links forming the structure
- suitability (int): Suitability of the structure
- fresh, valid (bool): Status flags
- Notes:
- Suitability is computed as:
- each covered SemRep instance (that is not shared) adds SEM_WEIGHT
- utterance lengths is measured as number of syllables. Suitability is inveresely
proportional to utterance length (favor compact utterances) weighted by LEN_WEIGHT. - each contruction adds preference*PRF_WEIGHT.
ex. For a single construction that covers 2 unshared SemRep nodes, has 7 syllables and a preference of 4
Suitability = 2*SEM_WEIGHT - 7*LEN_WEIGHT + 4*PRF_WEIGHT.
Other parameters (e.g. frequency, task requirement, etc.) can be considered to.
-
check_complete
()[source]¶ Check if a cxn structure is complete. Structure is complete if all the slots of all the cxn instances currently in the structure are linked to a cxn inst.
-
check_lineage
(cxn_str)[source]¶ Returns True if cxn_str is identical, contains or is contained in the construction structure.
-
check_membership
(cxn=None, link=None)[source]¶ Check if a given cxn (CXN_INST) or link (CXN_LINK) are part of the structure.
-
check_obsolete
()[source]¶ Check if the cxn structure is obsolete. Structure is considered obsolete if all the SemRep instances covered by the cxn instances are old.
-
combine
(cxn_str1, cxn_str2)[source]¶ Combine two construction structures and spawn a new structure.
- Returns:
- A new construction structure that combines both cxn_str1 and cxn_str2.
- None if combination fails.
- Notes:
- Cnx str are combined at the top.
- The top unit of one cxn str is linked to a compatible empty slot in the top unit of the other.
- CONDITIONS: Top units match; there is an compatible empty slot;
there is no conflict between the two construction structures.
-
compare
(cxn_str)[source]¶ Compare this construction structure with cxn_str (CXN_STR).
- Return:
- 0: None matched
- 1: Partial match
- 2: Contained (subset of cxn_str)
- 3: Identical
- 4: Contains (superset of cxn_str)
-
conflict
(cxn_str1, cxn_str2)[source]¶ Check if there is a conflict between two construction structures. Return True if a conflict is found.
Note: Method goes through all the match info data between pairs of instances (i1, i2) in cxn_str1 x cxn_str2.
-
create
(cxn)[source]¶ Initialize the empty construction struture with cxn (CXN_INST) as the top construction. Calculate initial suitability of the structure (see class docstring for more info).
- Args:
- cxn (CXN_INST): The initial top cxn instance
-
get_child
(parent, idx)[source]¶ If it exists, return the child (CXN_INST) for a given parent (CXN_INST) and a given SynForm index idx (int).
-
merge
(cxn_str)[source]¶ Merge construction structure with cxn_str (CXN_STR). Elements (links and cxn insts) of cxn_str are added to the construction structure. Suitability of both cnx structures are added.
THE TWO CONSTRUCTION STRUCTURES SHOULD NOT SHARE ANY ELEMENT (NO DUPLICATION ASSUMED).
Notes: This method is only there to be used within the combine class method, since the output of merge is not a proper construction structure (more a set containing 2 cnx sructs since the top instances have not been linked).
-
overlap
(cxn_str1, cxn_str2)[source]¶ Check if two construction structures overlap on the SemRep.. Return True if an overlap is found.
Notes: Method goes through all the match info data between pairs of instances (i1, i2) in cxn_str1 x cxn_str2.
-
readout
(cxn, act, phon_list, vocal=True)[source]¶ Recursively read out the phonological content generated by the cxn str starting from a given cxn inst.
- Args:
- cxn (CXN_INST): The cxn instance form where to start the read out process
(use top cxn inst to span the whole structure). Method then called recursively on child cxn instances. - act (INT): Value used to reactivate cxn inst and SemRep inst. - phon_list ([TP_PHON]): List phonetic content of recursively read out from cxn inst SynForms. - vocal (BOOL): If True, read out impacts activations and status flags values of cxn inst and semrep insts.
- Returns:
- Phon_list is modified through the recursive application of method (side effect).
- Returns None if no emtpy slot is encountered.
- If an empty slot is encountered, process is interuppted, and a SemRep inst
that should be but are not covered is returned.
- Notes:
- the SemRep instance returned is the one associate with the first empty slot found.
-
class
instance.
MATCH_INFO
[source]¶ Construction instance matching information.
- Data:
- match (int): -1 = conflict, 0 = no relation, 1 = union
- overlap (bool): overlap flag
- parent (CXN_INST): parent construction instance
- child (CXN_INST): child contruction instance
- SynFormIdx (int): SynForm index of the parent’s slot to which the child is linked.
- other (CXN_INST): ...for maintenance purposes...
-
class
instance.
SCHEMA_INST
[source]¶ Schema instance (base class)
- Data:
- id (int): Unique id
- type (int): Type of schema
- activation (int): Current activation value of schema instance
- alive, old, fresh (bool): status flags
-
Activation
(act)[source]¶ If not already the case, set ‘activation’ to act (int) and signal instananeous activity
-
Alive
(bool_val)[source]¶ If not already the case, set alive to bool_val (bool) and signal instantaneous activity.
-
class
instance.
SEMREP_INST
[source]¶ SemRep instance
- Data (inherited):
- id (int): Unique id
- type (int): Type of schema
- activation (int): Current activation value of schema instance
- alive, old, fresh (bool): status flags
- Data:
- concept (CONCEPT): Representing concept
- schema (SCHEMA): Associated perceptual schema
Created on Fri Oct 10 2014
@author: Victor Barres
TCG 1.1 data loader module
This version requires JSON formatted inputs!
Loader for grammar, scenes and conceptual knowledge.
To load grammar use load_grammar function (returns a grammar) To load visual scene use load_scene function (returns a scene) To load conceptual knowledge use function (returns a SemNet)
All other functions should be considered private and are subject to change.
-
loader.
load_SemNet
(file_name, file_path='./')[source]¶ Load and return the semantic network defined in file_path/file_name. Return None if error.
-
loader.
load_grammar
(file_name, file_path='./')[source]¶ - Load and return the TCG grammar defined in file_path
ile_name.
-
loader.
load_scene
(file_name, file_path='./')[source]¶ - Load and return the visual scene defined in file_path
ile_name. Return None if error.
Created on Mon May 05 12:07:09 2014
@author: Victor Barres
Define visual scene structure related classes for TCG1.0
-
class
scene.
PERCEPT
[source]¶ Schema perception.
- Data:
- schema (SCHEMA): Perceived schema.
- concept (CONCEPT): Perceived concept (can be different from original concept carried by schema).
- replace_concept (BOOL): Flag for replacing concept.
- Notes:
- If replace_concept = False -> the concept associated with the percept is the one linked to the schema
if replace_concept = True -> override schema concept and use the one associated directly with the percept. - This class is a first attempt to represent conceptualization process going from perceptual schemas to semantic reprsentation. Needs to be improved.
-
class
scene.
REGION
[source]¶ Scene region.
- Data:
- name (STRING): Name of region
- x, y (INT): Location
- w, h (INT): Size
- saliency (INT): Perceptual saliency of region
- uncertainty (INT): How uncertain is the perception of this region.
- percepts ([PERCEPT]): List of percepts associated with this region.
-
class
scene.
SCENE
[source]¶ Scene being perceived.
- Data:
- width, height (INT): Scene resolution
- schemas ([SCHEMA]): List of perceptual schemas associated with the scene.
- regions ([REGION]): List of regions associated with the scene.
-
class
scene.
SCHEMA
[source]¶ Perceptual schema
- Data:
- type (INT): Schema type (UNDEFINED, OBJECT or RELATION).
- name (STRING): Schema name.
- concept (CONCEPT): Concept associated with the schema.
- region (REGION): Region of the visual scene associated with the schema.
-
class
scene.
SC_REL
[source]¶ Relation schema. Define relation (edge) between two object schemas (SC_OBJECT) pFrom and pTo.
Created on Fri May 09 13:49:40 2014
@author: Victor Barres
Define the simulator that runs the SemRep/TCG processes for TCG1.0
-
class
simulator.
COMP_TRACE
[source]¶ Competition trace Used by the simulator to keep track of construction instances competition outcomes. A comp_trace object is generated after each competition and stored by the simulator.

SIMULATOR
[source]¶ Simulator runs SemRep/TCG processes. The simulator needs to be initialized with a grammar, a SemNet (semantic knowledge) and a visual scene. Max time, thresholds of utterance values and TCG principles flags also need to be defined.
Simulation is run by successive calls to proceed() method, until a termination condition is met. Each call to proceed() corresponds to 1 time step.
- Data:
<LONG TERM MEMORY> - SemNet (SEM_NET): Semantic network (world knowledge) - grammar (GRAMMAR): Grammatical knowledge
<VISUAL INPUT> - scene (SCENE): Currently viewed scene
<VISION SYSTEM> - atten (REGION): Region currently under attentional focus - next_atten (REGION): Next attention focus. Can be either defined based on saliency or based on verbal guidance (see produce_utterance()) - vis_update (BOOL): Visual update flag - per_regions ([REGION]): Already perceived regions
<LANGUAGE SYSTEM> - utter (STR): Produced utterance - incomp_utter (BOOL): Incomplete utterance flag. True if the last utterance did not cover the whole active SemRep. Trigers the VERBAL GUIDANCE! - rd_str (CXN_STRUCT): Last read-out construction structure (useful to implement utterance continuity) - rd_phons ([TP_PHON]): Last read-out phonetic notations (useful to implement utterance continuity)
<WORKING MEMORY> - instances ([SCHEMA_INST]): All schema instances - sem_insts ([SEMREP_INST]): All SemRep instances - cxn_insts ([CXN_INST]): All construction instances - cxn_strs ([CXN_STRUCT]): All construction structures - comp_traces ([COMP_TRACE]): Competition traces. Keep trace of cxn instances competition results
<SIMULATION PARAMETERS> - time (INT): Current simulation time (in relative unit) - max_time (INT): Max simulation duration - utter_time (INT): Last utterance production time
<THRESHOLD OF UTTERANCE> - thresh_time (INT): Time threshold (-1 for infinity) - thresh_cxn (INT): Construction number limit (-1 for infinity) - thresh_syll (INT): Syllable length limit (-1 for infinity)
<TCG PRINCIPLE FLAGS> - prema_prod (BOOL): Premature production principle - utter_cont (BOOL): Utterance continuity principle - verb_guide (BOOL): Verbal guidance principle
-
add_schema_inst
(sc_inst)[source]¶ Add a schema instance to the working memory
- Args:
- sc_inst (SCHEMA_INST)
-
create_comp_trace
(winner, loser)[source]¶ WRITE DOCSTRING!!
- Args:
- winner (CXN_INST)
- loser (CXN_INST)
-
deploy_attention
()[source]¶ Orient attention to most salient scene region and keep it under focus until the region’s uncertainty < = 0. Include inhibition of return.
This method simulate the effect of (bottom-up) visual saliency on the attention process. IMPORTANT: It can be overridden by verbal guidance (see produce_utterance()). If an utterance is produced orematurely while some information is still missing that would be needed to complete it, the next attentional region is set to the region that contains the piece of infomration needed.
- Steps:
- Pick most salient region whose uncertainty >=0 (i.e. that has not yet been perceived)
- Keep it under attentional focus until it’s uncertainty <=0. Decrease uncertainty value by 1 ever time step.
- Go back to 1.
-
ellapsed_time
()[source]¶ Maintenance process.
- Steps:
- Set cxn_inst with activity <= 0 to dead
- Set old cxn_inst to activity = 0 (old means it has been read out)
- Set cxn_inst to Fresh = False (Fresh only when it has just been invoked)
- Validate all instances
- Remove dead instances
- Advance time
-
get_semrep_inst
(schema)[source]¶ Look for the SemRep instance linked to a given perceptual schema. Return the SemRep instance if it exists, None otherwise.
-
initialize
(myGrammar, myScene, mySemNet, maxTime, threshTime, threshCxn, threshSyll, premaProd, utterCont, verbGuide, clearData=False)[source]¶ Initialize the simulator.
- Args:
- myGrammar (GRAMMAR): A grammatical knowledge
- myScene (SCENCE): The input scene
- mySemNet (SEM_NET): The semantic knowledge
- maxTime (INT): Max simulation duration
- threshTime (INT): Time threshold (-1 for infinity)
- threshCxn (INT): Construction number limit (-1 for infinity)
- threshSyll (INT): Syllable length limit (-1 for infinity)
- premaProd (BOOL): Premature production principle
- utterCont (BOOL): Utterance continuity principle
- verbGuide (BOOL): Verbal guidance principles
- clearData (BOOL): If True, grammatical knowlegde, semantic knowledge and visual input are cleared.
-
invoke_constructions
()[source]¶ Invoke all constructions whose SemFrame match SemRep subgraphs (no duplicate).
-
invoke_cxn_inst
(aCxn, sf_idx, attaches)[source]¶ WRITE DOCSTRING!! SUBGRAPH MATCHING ALGORITHM.
Try to match the SemFrame of a construction onto a SemRep subgraph. If success, instantiate construction.
- Args:
- aCxn (CXN): A construction in the grammar.
- sf_idx (INT): Index of SemFrame element in aCXN.SemFrame.
- attaches ([SEMREP_INST]): Keeps track of the SemRep instances that have been matched during
recursive search of matching subgraphs.
- Notes:
- Only instantiates construction that match onto a SemRep sugraph that has
at least one element alive. - Checks that a similar instance doesn’t already exist before adding to working memory. - Algorithm steps:
- For first element of SemFrame, try to find matching SemRep instance
- Then recursively try to find matches for other elements of the SemFrame
- Then check that topology match between SemFrame and list of matching attached SemFrame
instances (i.e. check that toplogy match between SemFrame and Attatches)
- Algorithm comments:
- This does not make use of the directed graph structure during the first search phase since
it only checks the topology afterwards. - If SemRep = N1 elements, SemFrame = N2 elements, number of test during search = N1^N2 !! + then the cost of the topology checks... this algorithm is clearly NOT optimal, but works for now since SemRep and SemFrames are small.
The matching of concept is very simple here (match or no match).
-
match_phon_lists
(prev_phonlist, next_phonlist)[source]¶ Check if there is an i such that prev_phonlist[i:] is a sublist of next_phonlist
- Example:
prev_phonlist = [I, saw, that, the, man, kicks] next_phonlist = [The, man, kicks, a, ball] Return -> matches = 3, corresponds to index of ‘a’ in next_phon_list.
prev_phonlist = [I, saw, that, the, man, kicks] next_phonlist = [the, man, eats, a, cake] Return -> matches = 0, prev_phonlist is not a sublist of next_phonlist.
-
perceive_scene
()[source]¶ Perceive all regions that are certain (uncertainty == 0) and set their uncertainty to -1 so that they won’t be perceived again.
Created on Tue Oct 08 2014
@author: Victor Barres
Define main() function and output printing functions for TCG1.1 Adds a JSON output that can interface with the TCG_viewer. Use the JSON formatted inputs.
-
TCG.
load_init_file
(file_name, sim)[source]¶ Load intialization file and initialize simulator (sim).
- Args:
- file_name (STR): initialization file name (.ini file)
- sim (SIMULATOR): simulator to initialize.
-
TCG.
print_cxn_struct
(cxn_str, cxn_inst, recursive=True)[source]¶ Print construction structure (cxn_str) starting from a given construction instance (cxn_inst) (usually Top instance). If recursive = True, recursively print sub-structures.
-
TCG.
print_inst_status
(sc_inst)[source]¶ - Print status of schema instance
- ! = Fresh, the instance was just invoked. X = Dead, the instance will be pruned out of the working memory next time step. x = Alive instance with activation < 0 O = Alive instance with activation > 0 and not Old (Basic status of active instances) @ = Alive instance with activation > 0 and Old -> The Old flag means that the instance has already been used for read-out.
-
TCG.
print_struct_status
(cxn_str, rd_str)[source]¶ - Print status of construction structure (cxn_str) with respect to the structure that is used for read out (rd_str)
- = This is the cxn_str used for production
X = The structure is not Valid (contains dead instances).
Created on Thu Feb 12 16:13:10 2015
@author: Victor Barres
Defines the TCG_VIEWER class that allows to view a certain dataset into the TCG viewer.
Can be also be use in command line: python viewer.py
-
class
viewer.
TCG_VIEWER
(data_path, PORT=8080, viewer_path='viewer/')[source]¶ Connects the simulation to the the TCG viewer.
- Data:
- server_port (INT): Server port value, default 8080.
- viewer_path (STR): path to the viewer main directory.
- data_path (STR): Path to the data folder that needs to be displayed.
- tmp (STR): Temp folder.


Press Ctrl+Shift+J (Chrome) or Ctrl+Shift+K (Firefox) to open console, then click the links:
Reload the page between simulations.
GO!


This is a prototype. These unit tests are built to validate correctly for devices running iOS and Android. For all other devices, please consider the output based on what you know of the browser/OS capabilities.


---
layout: post
title: Road-trip End
date: 2008-08-14 03:47:09.000000000 -05:00
type: post
parent_id: '0'
published: true
password: ''
status: publish
categories:
- C2C
- English
- USA08
tags: []
meta:
_edit_last: '1412221'
author:
login: dreamessenceonthemove
email<EMAIL_ADDRESS>display_name: darribas
first_name: Daniel
last_name: Arribas-Bel
permalink: "/2008/08/14/road-trip-end/"
---
So this morning, around 12:00 we've crossed the Golden Gate building and the road-trip has come to an end. It's been two weeks and a half of joy, full of fun and where I've also learnt a lot about different things. Now it's too early so as to throw any reflection, that will come later once I get "home" (so the pictures of the trip will come); but I just wanted to say I'm safe and sound, my friend Jesus has already picked me up and I'll stay at his place today and tomorrow; on friday, I'll get on a bus and, after 15 hours through the Californian coast and inwards, I hope I gett off in Phoenix, AZ. There my new housemate will pick me up and take me to what it'll be my new "home" for 10 months in Tempe, AZ.
The new life is coming right up!!! Until then, let's enjoy San Francisco :)


|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |
java.lang.Object atg.core.util.Enum
Base class for enumerated Objects.
Subclasses of the Enum class are the recommended, type safe way to represent a fixed set consisting of enumerable, serializable, comparable values. The Enum pattern is a variant of the Singleton Design Pattern, meaning that each value is guaranteed to have only one Enum instance per VM. No garbage is created by using Enums, and there is no possibility of users passing an invalid or out-of-range value. The == operator may be used to check equality between enumerated values.
The normal usage of Enums is to define an Enum subclass for each enumeration data type, and to define a set of public final static constants in that class which provide access to named singleton instances of the Enum's values.
Every Enum value has an associated String name and an ordinal integer. The String names are returned when toString() is invoked on an Enum value. The ordinals provide a canonical encoding of each Enum that is used to implement comparison and serialization of enumerated types; they also ensure a well-defined correspondence between old and new serialized values of the subclass if the set of values is changed. Note that Enums cannot be converted to or from these ordinals unless the Enum subclass explicitly exposes such conversion publicly. In general, a program which expects enums to correspond to specific integers should be using static final int constants, not Enums. (Conversion between Enums and their String names is, however, provided by the PropertyEditor support described below.)
The inner classes EnumEditor and LocaleEnumEditor make it very easy to define java.beans.PropertyEditor classes for an enumerated data type. This immediately makes the type usable for configurable JavaBeans and Dynamic Beans properties within Dynamo and its associated user interfaces. The getTags() methods of these editors return the set of valid textual values of the Enum type, meaning that JavaBeans-compatible UIs will automatically provide constrained widgets such as ComboBoxes to edit such properties. EnumEditor provides an unlocalized editor which can be used by Nucleus or other JavaBeans-based configurators that represent bean properties as Strings. LocaleEnumEditor provides a way to expose an Enum-type bean property for editing in a locale-dependent UI, such as the Dynamo Control Center, with a ResourceBundle controlling the UI-visible set of stringified values.
A subclass must create at least one instance as a final static constant, and its constructor must be private to prevent the generation of any instances of the class besides its known singletons.
Here is an example of an absolutely minimal subclass, such as might be used algorithmically with no visibility in Dynamo's configuration or user interface.
public class Direction extends Enum { private Direction(String dn, int ordinal) {super(dn, ordinal);} public final static Direction NORTH = new Direction("North", 0); public final static Direction SOUTH = new Direction("South", 1); public final static Direction EAST = new Direction("East", 2); public final static Direction WEST = new Direction("West", 3); }
The following example uses the full set of Enum features for a class that supports the configuration, viewing and editing within Dynamo of JavaBean properties of the class's type.
import java.util.Iterator; import java.util.ResourceBundle; import java.beans.PropertyEditorManager; import atg.beans.LocalePropertyEditorManager; public class Direction extends Enum { private Direction(String dn, int ordinal) {super(dn, ordinal);} public final static Direction NORTH = new Direction("North", 0); public final static Direction SOUTH = new Direction("South", 1); public final static Direction EAST = new Direction("East", 2); public final static Direction WEST = new Direction("West", 3); // an Iterator to iterate over all Direction objects. public static Iterator getIterator() {return iterator(Direction.class);} // The following defines a non-localized PropertyEditor that will // allow Direction values to be edited as "North", "South", etc., and // Direction-type bean properties to be configured with these values in Nucleus. static { PropertyEditorManager.registerEditor(Direction.class, DirectionEditor.class); } public static class DirectionEditor extends Enum.EnumEditor { public Class getEnumClass() { return Direction.class; } } // The following defines a localized PropertyEditor that will be used // in user interfaces to edit Direction-type bean properties in a locale-dependent // fashion. It assumes the existence of a ResourceBundle named DirectionTags // in the same package as this class. static { LocalePropertyEditorManager.registerEditor(Direction.class, LocaleDirectionEditor.class); } public static class LocaleDirectionEditor extends Enum.LocaleEnumEditor { public Class getEnumClass() { return Direction.class; } } }
toString()
,
iterator(Class)
,
iterator()
,
Serialized Form| Nested Class Summary | |
static class |
Enum.EnumEditor
Utility class to allow Enum objects to be used as properties of JavaBeans; the editor exposes tag values equal to the Enum values' logical names. |
static class |
Enum.LocaleEnumEditor
Utility class to allow Enum objects to be used as properties of JavaBeans; the editor exposes tag values obtained by looking up the Enum values' logical names in a ResourceBundle. |
| Field Summary | |
static java.lang.String |
CLASS_VERSION
|
| Constructor Summary | |
protected |
Enum(java.lang.String enumName,
int ordinalVal)
The subclass constructor should be private. |
| Method Summary | |
int |
compareTo(java.lang.Object o)
The compareTo method allows Enum objects to be placed in ordered containers. |
protected static atg.core.util.Enum.EnumClassInfo |
getEnumClassInfo(java.lang.Class c)
|
protected int |
getOrdinal()
|
java.util.Iterator |
iterator()
|
static java.util.Iterator |
iterator(java.lang.Class c)
|
protected static Enum |
lookup(java.lang.Class c,
int ordNum)
|
protected static Enum |
lookup(java.lang.Class c,
java.lang.String name)
|
protected Enum |
lookup(int ordNum)
|
protected Enum |
lookup(java.lang.String name)
|
protected java.lang.Object |
readResolve()
This allows us to read serialized Enum objects without creating new instances. |
java.lang.String |
toString()
|
| Methods inherited from class java.lang.Object |
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait |
| Field Detail |
public static java.lang.String CLASS_VERSION
| Constructor Detail |
protected Enum(java.lang.String enumName, int ordinalVal)
The ordinal value is used to compare (done when sorting, for example) two Enum objects and to order the objects in iterators and PropertyEditors. No two instances of a subclass should have the same ordinal value or name. To safely add new Enum subclass instances and preserve previous orderings in containers the best thing to do is to always use a new ordinal value when creating a new instance rather than changing old instance's ordinal value.
If an enum subclass instance is ever removed, there should be a comment in the file that reserves the old ordinal value so that any old serialized files don't accidentally map an old enum to a new enum.
enumName
- The name of the instance that will appear in editors and toString().ordinalVal
- The ordinal value
java.lang.Error
- if the subclass already has an instance name n or if the ordinal
number is already used by another instance of the same subclass.| Method Detail |
public java.lang.String toString()
protected int getOrdinal()
public int compareTo(java.lang.Object o)
compareTo
in interface java.lang.Comparable
o
- The object to be compared to.
java.lang.ClassCastException
- if o is not an Enum subclass.public static java.util.Iterator iterator(java.lang.Class c)
public java.util.Iterator iterator()
protected static Enum lookup(java.lang.Class c, int ordNum)
c
- The Enum subclass
protected Enum lookup(int ordNum)
protected static Enum lookup(java.lang.Class c, java.lang.String name)
c
- The Enum subclassname
- The name of the Enum to lookup.
protected Enum lookup(java.lang.String name)
name
- The Enum object's name to lookup.
protected java.lang.Object readResolve() throws java.io.ObjectStreamException
java.io.ObjectStreamException
protected static atg.core.util.Enum.EnumClassInfo getEnumClassInfo(java.lang.Class c)
c
- The Class object for the Enum subclass to look up.
|
||||||||||
| PREV CLASS NEXT CLASS | FRAMES NO FRAMES | |||||||||
| SUMMARY: NESTED | FIELD | CONSTR | METHOD | DETAIL: FIELD | CONSTR | METHOD |


Tap to Talk 1-800-820-0184
Speak to our Bone Health Specialists!
Shipping & Returns
|
Health Disclaimer
|
Legal and Privacy Policy
|
Contact
|
Order Now


We are LA's premier wholesale cabinet company. Founded in 2016 we take great pride in our cabinets and the quality of the product we deliver. We strive towards providing our clients with the best product for the best price.


On the Localize service description page, you can provide the service name for customers, the short description, and the detailed description of the marketable service in all supported languages. If defined for the service, you can also translate the name of any defined custom tab that is shown when customers display details on their subscriptions.
For localizing the elements, the marketable service must be deactivated. Existing subscriptions of your customers are not affected by the localization. Any changes you make are effective for new subscriptions only. To provide the service to customers for subscription, you must activate it.
Brokers and resellers as well as their customers can immediately view the service description in the languages in which you provide it. Existing subscriptions to services sold by brokers and resellers are not affected by the localization. Any changes you make are effective for new subscriptions only.
To localize the elements:
After activating the service, the localized elements are visible to your customers, provided they have the corresponding language set in their profile.
Brokers and resellers as well as their customers can instantly view your localized elements.


Introduction¶
The Python package, PDielec, calculates the infrared absorption characteristics of a crystalline material supported in a non-absorbing medium and the absorption of single crystals (thin films or thick slabs) of absorbing material at different orientations. PDielec post processes the output of solid state quantum mechanical and molecular mechanics (MM) based codes such as VASP [1], CASTEP [2], CRYSTAL [3], Abinit [4], Quantum Espresso [5], Phonopy [6], and GULP [7]. The infrared absorption of crystalline insulator materials whose crystal size is small compared with the wavelength of the absorbing radiation is calculated using effective medium theory. The package is suited for the calculation of the complex, frequency dependent permittivity and its associated absorption of infrared radiation for a finely ground crystalline material dispersed in a low loss dielectric medium such KBr or Polytetrafluoroethylene (PTFE). A particular feature of the program is its ability to take into account the constant permittivity of the supporting medium and the particle shape of the material of interest through an effective medium theory.
Using an effective medium method, the package calculates the internal electric field arising from different particle morphologies and calculates the resulting shift in absorption frequency and intensity arising from the coupling between a phonon and the internal field. The theory of the approach is described, followed by a description of the implementation within PDielec. For the specific case of a low concentration of spherical particles, calculations based on Mie scattering allow the exploration of particle size effects. A section providing several examples of its application is given.
For spherical, isotropic particles, embedded in a supporting matrix the Mie method is available to calculate the absorption of infrared radiation. The method uses the routines of PyMieScatt by B. Sumlin [8, 9].
The attenuated total reflection (ATR) spectrum can be calculated for a powdered material next to a high refractive index material such as diamond or germanium.
The calculation of the optical behaviour of a single crystal (thick slab or film) is performed using the pyGTM code available on GitHub [10]. This code implements a generalised transfer matrix method described by Passler et al. [11] and which builds on previous publications [12, 13].
An interface to the vibAnalysis package of Philipe Teixeira [14] is provided through the vibanalysis command. The background to the theory of the analysis is given in a paper [15]. The package performs Vibrational Mode Decompsition (VMD) using three computational approaches; Vibrational Mode Projection, Vibrational Mode Linear Decomposition and Vibrational Mode Automatic Relevance Determination.


--- layout: default permalink: /discord --- {% include menu.html %}
Build our community support network and help keep all of us connected and safe. Come in and meet your neighbours.
Please note:
After entering your email, you will be asked if you wish to 'Get the Desktop App'. This is optional. Click the to proceed without installing the App.


# -*- coding: utf-8 -*-
"""Copyright 2019 DScribe developers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import sys
import numpy as np
from scipy.sparse import coo_matrix
from dscribe.descriptors.descriptor import Descriptor
from dscribe.core import System
from ase import Atoms
from dscribe.ext import ACSFWrapper
import dscribe.utils.geometry
[docs]class ACSF(Descriptor):
"""Implementation of Atom-Centered Symmetry Functions. Currently valid for
finite systems only.
Notice that the species of the central atom is not encoded in the output,
only the surrounding environment is encoded. In a typical application one
can train a different model for each central species.
For reference, see:
"Atom-centered symmetry functions for constructing high-dimensional
neural network potentials", Jörg Behler, The Journal of Chemical
Physics, 134, 074106 (2011), https://doi.org/10.1063/1.3553717
"""
[docs] def __init__(
self,
rcut,
g2_params=None,
g3_params=None,
g4_params=None,
g5_params=None,
species=None,
periodic=False,
sparse=False
):
"""
Args:
rcut (float): The smooth cutoff value in angstroms. This cutoff
value is used throughout the calculations for all symmetry
functions.
g2_params (n*2 np.ndarray): A list of pairs of :math:`\eta` and
:math:`R_s` parameters for :math:`G^2` functions.
g3_params (n*1 np.ndarray): A list of :math:`\kappa` parameters for
:math:`G^3` functions.
g4_params (n*3 np.ndarray): A list of triplets of :math:`\eta`,
:math:`\zeta` and :math:`\lambda` parameters for :math:`G^4` functions.
g5_params (n*3 np.ndarray): A list of triplets of :math:`\eta`,
:math:`\zeta` and :math:`\lambda` parameters for :math:`G^5` functions.
species (iterable): The chemical species as a list of atomic
numbers or as a list of chemical symbols. Notice that this is not
the atomic numbers that are present for an individual system, but
should contain all the elements that are ever going to be
encountered when creating the descriptors for a set of systems.
Keeping the number of chemical species as low as possible is
preferable.
periodic (bool): Determines whether the system is considered to be
periodic.
sparse (bool): Whether the output should be a sparse matrix or a
dense numpy array.
"""
super().__init__(periodic=periodic, flatten=True, sparse=sparse)
self.acsf_wrapper = ACSFWrapper()
# Setup
self.species = species
self.g2_params = g2_params
self.g3_params = g3_params
self.g4_params = g4_params
self.g5_params = g5_params
self.rcut = rcut
[docs] def create(self, system, positions=None, n_jobs=1, verbose=False):
"""Return the ACSF output for the given systems and given positions.
Args:
system (:class:`ase.Atoms` or list of :class:`ase.Atoms`): One or
many atomic structures.
positions (list): Positions where to calculate ACSF. Can be
provided as cartesian positions or atomic indices. If no
positions are defined, the SOAP output will be created for all
atoms in the system. When calculating SOAP for multiple
systems, provide the positions as a list for each system.
n_jobs (int): Number of parallel jobs to instantiate. Parallellizes
the calculation across samples. Defaults to serial calculation
with n_jobs=1.
verbose(bool): Controls whether to print the progress of each job
into to the console.
Returns:
np.ndarray | scipy.sparse.csr_matrix: The ACSF output for the given
systems and positions. The return type depends on the
'sparse'-attribute. The first dimension is determined by the amount
of positions and systems and the second dimension is determined by
the get_number_of_features()-function. When multiple systems are
provided the results are ordered by the input order of systems and
their positions.
"""
# If single system given, skip the parallelization
if isinstance(system, (Atoms, System)):
return self.create_single(system, positions)
else:
self._check_system_list(system)
# Combine input arguments
if positions is None:
inp = [(i_sys,) for i_sys in system]
else:
inp = list(zip(system, positions))
# For ACSF the output size for each job depends on the exact arguments.
# Here we precalculate the size for each job to preallocate memory and
# make the process faster.
n_samples = len(system)
k, m = divmod(n_samples, n_jobs)
jobs = (inp[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n_jobs))
output_sizes = []
for i_job in jobs:
n_desc = 0
if positions is None:
n_desc = 0
for job in i_job:
n_desc += len(job[0])
else:
n_desc = 0
for i_sample, i_pos in i_job:
if i_pos is not None:
n_desc += len(i_pos)
else:
n_desc += len(i_sample)
output_sizes.append(n_desc)
# Create in parallel
output = self.create_parallel(inp, self.create_single, n_jobs, output_sizes, verbose=verbose)
return output
[docs] def create_single(self, system, positions=None):
"""Creates the descriptor for the given system.
Args:
system (:class:`ase.Atoms` | :class:`.System`): Input system.
positions (iterable): Indices of the atoms around which the ACSF
will be returned. If no positions defined, ACSF will be created
for all atoms in the system.
Returns:
np.ndarray | scipy.sparse.coo_matrix: The ACSF output for the
given system and positions. The return type depends on the
'sparse'-attribute. The first dimension is given by the number of
positions and the second dimension is determined by the
get_number_of_features()-function.
"""
# Transform the input system into the internal System-object
system = self.get_system(system)
# Create C-compatible list of atomic indices for which the ACSF is
# calculated
calculate_all = False
if positions is None:
calculate_all = True
indices = np.arange(len(system))
else:
indices = positions
# If periodicity is not requested, and the output is requested for all
# atoms, we skip all the intricate optimizations that will make things
# actually slower for this case.
if calculate_all and not self.periodic:
n_atoms = len(system)
all_pos = system.get_positions()
dmat = dscribe.utils.geometry.get_adjacency_matrix(self.rcut, all_pos, all_pos)
# Otherwise the amount of pairwise distances that are calculated is
# kept at minimum. Only distances for the given indices (and possibly
# the secondary neighbours if G4 is specified) are calculated.
else:
# Create the extended system if periodicity is requested. For ACSF only
# the distance from central atom needs to be considered in extending
# the system.
if self.periodic:
system = dscribe.utils.geometry.get_extended_system(system, self.rcut, return_cell_indices=False)
# First calculate distances from specified centers to all other
# atoms. This is already enough for everything else except G4.
n_atoms = len(system)
all_pos = system.get_positions()
central_pos = all_pos[indices]
dmat_primary = dscribe.utils.geometry.get_adjacency_matrix(self.rcut, central_pos, all_pos)
# Create symmetric full matrix
col = dmat_primary.col
row = [indices[x] for x in dmat_primary.row] # Fix row numbering to refer to original system
data = dmat_primary.data
dmat = coo_matrix((data, (row, col)), shape=(n_atoms, n_atoms))
dmat_lil = dmat.tolil()
dmat_lil[col, row] = dmat_lil[row, col]
# If G4 terms are requested, calculate also secondary neighbour distances
if len(self.g4_params) != 0:
neighbour_indices = np.unique(col)
neigh_pos = all_pos[neighbour_indices]
dmat_secondary = dscribe.utils.geometry.get_adjacency_matrix(self.rcut, neigh_pos, neigh_pos)
col = [neighbour_indices[x] for x in dmat_secondary.col] # Fix col numbering to refer to original system
row = [neighbour_indices[x] for x in dmat_secondary.row] # Fix row numbering to refer to original system
dmat_lil[row, col] = np.array(dmat_secondary.data)
dmat = dmat_lil.tocoo()
# Get adjancency list and full dense adjancency matrix
neighbours = dscribe.utils.geometry.get_adjacency_list(dmat)
dmat_dense = np.full((n_atoms, n_atoms), sys.float_info.max) # The non-neighbor values are treated as "infinitely far".
dmat_dense[dmat.col, dmat.row] = dmat.data
# Calculate ACSF with C++
output = np.array(self.acsf_wrapper.create(
system.get_positions(),
system.get_atomic_numbers(),
dmat_dense,
neighbours,
indices,
),
dtype = np.float32)
# Check if there are types that have not been declared
self.check_atomic_numbers(system.get_atomic_numbers())
# Return sparse matrix if requested
if self._sparse:
output = coo_matrix(output)
return output
[docs] def get_number_of_features(self):
"""Used to inquire the final number of features that this descriptor
will have.
Returns:
int: Number of features for this descriptor.
"""
wrapper = self.acsf_wrapper
descsize = (1 + wrapper.n_g2 + wrapper.n_g3) * wrapper.n_types
descsize += (wrapper.n_g4 + wrapper.n_g5) * wrapper.n_type_pairs
return int(descsize)
@property
def species(self):
return self._species
@species.setter
def species(self, value):
"""Used to check the validity of given atomic numbers and to initialize
the C-memory layout for them.
Args:
value(iterable): Chemical species either as a list of atomic
numbers or list of chemical symbols.
"""
# The species are stored as atomic numbers for internal use.
self._set_species(value)
self.acsf_wrapper.atomic_numbers = self._atomic_numbers.tolist()
@property
def rcut(self):
return self.acsf_wrapper.rcut
@rcut.setter
def rcut(self, value):
"""Used to check the validity of given radial cutoff.
Args:
value(float): Radial cutoff.
"""
if value <= 0:
raise ValueError("Cutoff radius should be positive.")
self.acsf_wrapper.rcut = value
@property
def g2_params(self):
return self.acsf_wrapper.get_g2_params()
@g2_params.setter
def g2_params(self, value):
"""Used to check the validity of given G2 parameters.
Args:
value(n*3 array): List of G2 parameters.
"""
# Disable case
if value is None:
value = np.array([])
else:
# Check dimensions
value = np.array(value, dtype=np.float)
if value.ndim != 2:
raise ValueError("g2_params should be a matrix with two columns (eta, Rs).")
if value.shape[1] != 2:
raise ValueError("g2_params should be a matrix with two columns (eta, Rs).")
# Check that etas are positive
if np.any(value[:, 0] <= 0) is True:
raise ValueError("G2 eta parameters should be positive numbers.")
self.acsf_wrapper.set_g2_params(value.tolist())
@property
def g3_params(self):
return self.acsf_wrapper.g3_params
@g3_params.setter
def g3_params(self, value):
"""Used to check the validity of given G3 parameters and to
initialize the C-memory layout for them.
Args:
value(array): List of G3 parameters.
"""
# Handle the disable case
if value is None:
value = np.array([])
else:
# Check dimensions
value = np.array(value, dtype=np.float)
if value.ndim != 1:
raise ValueError("g3_params should be a vector.")
self.acsf_wrapper.g3_params = value.tolist()
@property
def g4_params(self):
return self.acsf_wrapper.g4_params
@g4_params.setter
def g4_params(self, value):
"""Used to check the validity of given G4 parameters and to
initialize the C-memory layout for them.
Args:
value(n*3 array): List of G4 parameters.
"""
# Handle the disable case
if value is None:
value = np.array([])
else:
# Check dimensions
value = np.array(value, dtype=np.float)
if value.ndim != 2:
raise ValueError("g4_params should be a matrix with three columns (eta, zeta, lambda).")
if value.shape[1] != 3:
raise ValueError("g4_params should be a matrix with three columns (eta, zeta, lambda).")
# Check that etas are positive
if np.any(value[:, 2] <= 0) is True:
raise ValueError("3-body G4 eta parameters should be positive numbers.")
self.acsf_wrapper.g4_params = value.tolist()
@property
def g5_params(self):
return self.acsf_wrapper.g5_params
@g5_params.setter
def g5_params(self, value):
"""Used to check the validity of given G5 parameters and to
initialize the C-memory layout for them.
Args:
value(n*3 array): List of G5 parameters.
"""
# Handle the disable case
if value is None:
value = np.array([])
else:
# Check dimensions
value = np.array(value, dtype=np.float)
if value.ndim != 2:
raise ValueError("g5_params should be a matrix with three columns (eta, zeta, lambda).")
if value.shape[1] != 3:
raise ValueError("g5_params should be a matrix with three columns (eta, zeta, lambda).")
# Check that etas are positive
if np.any(value[:, 2] <= 0) is True:
raise ValueError("3-body G5 eta parameters should be positive numbers.")
self.acsf_wrapper.g5_params = value.tolist()


Edit values
Allowed Days
Set the start and end times to 00:00 to allow access all day
Set the Timezone to ensure your splash restrictions work correctly.
Splash invalid, please check your settings.


I've recently learned something about electric circuits. The ideal model of circuits does ignore that electrons actually need time to pass the components of the circuit. So we introduced the "dead time model". So we added a model component for each real component that does only delay the incoming signal. But I've wondered if dead time of a cable wasn't important, too. So I thought the question would be How fast are electrons moving in a cable?, but I just realized that the question is How fast does a signal move in a wire?.
How fast are electrons moving through a wire?
If you have electric current \(I\) (measured in Ampere), the wire is a cylindric conductore with a cross-sectional area of \(A\), \(e = -1.6021766 \cdot 10^{-19} C\) (coulombs) is the charge of an electron an \(Q\) is \(\frac{\text{mobile electrons}}{\text{volume}}\). \(v = \frac {I}{QeA}\)
According to this source, \(Q = 8.5 \cdot 10^{22} \frac{1}{cm^3}\) for copper. If \(I=1 A\) and if your wire has a radius of 0.5mm, you get: $v= \frac{1 A}{ 8.5 \cdot 10^{22} \frac{1}{cm^3} \cdot e \cdot ((0.5mm)^2 \cdot pi)} = 9.349 \cdot 10^{-5} \frac{m}{s} = $ (see Wolfram|Alpha).
Hmm ... seems to be very slow. Is my calculation correct?
How fast are electrical signals moving through a wire?
\(v = \frac{c}{\sqrt{\mu_r \varepsilon_r}}\)
where \(\varepsilon_r\) is relative permittivity and \(\mu_r\) is relative magnetic susceptibility.
For copper: \(\mu_r = 0.999994\) \(\varepsilon_r = 3\), as you can't measure permeability of metallic conductors (see "Elektromagnetische Felder und Wellen". Paul Lorrain, Dale R. Corson, François Lorrain, page 75) \(v = \frac{c}{\sqrt{0.999994 \cdot 3}} = 0.577352 \cdot c\)
How fast are electrons moving around an atom?
Well, first of all I have to mention, that electrons seem not to move around a nucleus as this image suggests:
A model with atomic orbitals seems to be more accurate. However, you can calulate the speed \(v\) an electron would have in Bohrs model.
The centripedal force is \(F_Z = \frac{m \cdot v^2}{r}\) This force pushes the electron away from the nucleus.
The coulomb-force is \(F_C = \frac{e^2}{4 \pi \varepsilon_0 r^2}\) where \(\varepsilon_0 \approx 8.8541 \cdot 10^{-12} \frac{F}{m}\) is permittivity.
Now you calculate:
Ok, we're almost there. But how do we get \(r\)? Well, you have to know this equation: \( m_{e} v r = n \hbar\) where \(n\) is the principal quantum number and \(\hbar\) is the reduced Planck constant.  This is much less than 1% of the speed of light (which is \(1.079 \cdot 10^9 \frac{km}{h}\))
Sources
Very good:
- How fast do electrons travel in an atomic orbital?
- How fast do electrons move through a conductor? → SPEED OF "ELECTRICITY"
- Explanation for speed of an electrical impulse
Not so good:


Static self-closing alert that disappears after 20 seconds (refresh the page if it has already disappeared)
Show a self-closing success message that disappears after 5 seconds.
Change message


LDBN - Learn DataBase Normalization
Loading.Please wait...
Your browser does not support JavaScript or JavaScript is disabled.


Business Analyst
Front end Web Developer
<EMAIL_ADDRESS>0715056130
Money Market funds advisory
Wealth Management advisory
Date name output calculator
Eldad has a degree in economics from Kenyatta University.
CPA Finalist
The main reason for joining Moringa school
is to advance
my skills in programming and to implement ideas using technology


Before Change
recursive_runner(layer)
def test_jzs2(self):
for weights in [None, [np.ones((10,5))]]:
for ret_seq in [True, False]:
layer = recurrent.JZS2(10, 5, return_sequences=ret_seq, weights=weights)
recursive_runner(layer)
def test_jzs3(self):
for weights in [None, [np.ones((10,5))]]:
for ret_seq in [True, False]:
layer = recurrent.JZS3(10, 5, return_sequences=ret_seq, weights=weights)
After Change
_runner(recurrent.JZS1)
def test_jzs2(self):
_runner(recurrent.JZS2)
def test_jzs3(self):
_runner(recurrent.JZS3)


Most of the election "forecasts" are not forecasts
The NY Times compiles a list of “forecasts” of the presidential election. People I know are paying a lot of attention to the NY Times’s forecast (The Upshot) and the 538 forecast. As the reported probability of Hillary Clinton winning varies, so do their hopes and anxieties.
These forecasts are not really forecasts, however. At the very least, they are not what we usually think of when we think of forecasts. Forecasts are predictions about the future. For the most part, the forecasts that the NY Times reports are judgements about who would win if the election were today - or a “now-cast” (as the 538 people call their explicitly non-forecasting non-forecast). Claiming that these are forecasts is like estimating whether it will rain this weekend by looking out the window.
Of those reported on the NY Times site, the Huffington Post “forecast” is the only one that explicitly says it is a now-cast. And there are other forecasts on the site that are, without a doubt, actually forecasts. These are the ones that are not based on statistical models but on the subjective reports of experts (Cook’s Political Report, Rothenberg & Gonzalez, and Sabato’s Crystal Ball) or the aggregated subjective reports of gamblers (Predictwise).
Although the FiveThirtyEight polls-only model is described as being a true forecast, but comparing their now-cast to the polls-only forecast suggests that the forecast is just a smoothed out version of the now-cast. That is, to the degree that the polls-only model is actually a forecast, it is a poor one, since it varies tremendously, suggesting that it has little predictive power beyond just assuming that what is true today will be true on November 8th.
The remaining “forecasts” do not specify how they work, so it is unclear whether they are really forecasts in a meaninful sense, but given that they all (other than the PEC one that has a broken link) look a lot like now-casts.
It is instructive to compare these probable now-casts to the one true quantitative forecast, the one at Predictwise. Note how much smaller the variance is. And note too the large, consistent, and increasing gap between Clinton and Trump.


This tutorial will demonstrate Moneysocket through hands-on experience using applications built upon the protocol libraries. This includes the Moneysocket Chat App, the Costanza Wallet App and the Custodial Provider. By following these steps, you should gain knowledge of how these pieces interoperate through the protocol and should hopefully stoke your imagination for what kinds of apps could be developed in this ecosystem.
Moneysocket Chat:
Costanza Wallet:
Moneysocket works on an account model for holding an balance assigned authorized to a socket connection. This account with the ability to transact on the Lightning Network must be provided at the "Terminus".
For those interested in getting deep into developing Moneysocket applications, or are a power user that wants to self-custody all their funds, you can run the Terminus application with your Lightning Network node.
For those following this tutorial, we have a custodial solution that is set up for trying out Moneysocket more casually. It does not require you to run and configure your own node, so you can get up and running quickly. Go to the Custodial Portal and register:
Please head the portal's warning you to not leave sats in the custodial accounts that you are not comfortable leaving as a donation to the project. The portal does not verify your email address, but if you leave a real address, we can contact you in the event the accounts are reset.
When you are logged in to the account,